diff --git a/docs/gentle-shell.md b/docs/gentle-shell.md index cf0625a67..0a55a6a2d 100644 --- a/docs/gentle-shell.md +++ b/docs/gentle-shell.md @@ -65,6 +65,10 @@ The [v2.6.0 release](https://github.com/Gentleman-Programming/gentle-pi/releases - Fullscreen pointer navigation and the responsive sidebar keep changes, agents, and TODO usable at changing terminal widths; cached frames avoid redrawing inactive sidebar content while live status still updates. - The Agents List and Details views preserve the orchestrator/session hierarchy and completion, abort, and lost-exit history. Parent-child queries and notifications have an explicit handoff path, while model, effort, and usage stay observable per task. - Named `/gentle:profiles` atomically route the orchestrator separately from packaged and review roles, and carry a per-profile orchestrator workflow mode (`w` on the models screen: organic, where the orchestrator may implement inline, or full delegation, where every implementation goes to a subagent); see the [technical reference](readme-reference.md#agent-model-profiles) for the profile model. Full delegation pays off with an expensive orchestrator and light workers; on small tasks it costs a few times the wall time of organic, so see [Orchestrator workflow mode](readme-reference.md#orchestrator-workflow-mode) for the measured cost and which mode to pick. A profile can also turn on [Controlled Engineering](readme-reference.md#controlled-engineering) (`c` on the models screen, off by default), which adds authoring rules against unrequested machinery to the sessions that write or verify code. +- `/gentle:profiles card on|off` shows or hides the sidebar profile card. It is hidden by default, the choice is persisted globally (`~/.pi/gentle-ai/profile-card.json`), and it takes effect live without `/reload`; any other argument prints the usage and changes nothing. +- The card's `✓ Use in session` action asks for confirmation before it binds anything: declining leaves the session profile, the live model and the thinking level untouched, and a profile apply already running says so without asking. It binds the shown profile to this session only (never the shared defaults) under the same single-apply gate `/gentle:profiles` uses. +- The profile card has three shortcuts: `alt+,` shows the previous profile, `alt+.` the next one (both wrap around, like the card's `◀` / `▶` arrows) and `alt+m` uses the shown profile in this session, exactly like clicking the card's use action (same confirmation, same single-apply gate). `GENTLE_PI_PROFILE_CARD_PREVIOUS_KEY`, `GENTLE_PI_PROFILE_CARD_NEXT_KEY` and `GENTLE_PI_PROFILE_CARD_USE_KEY` rebind them (`off` or empty leaves one unbound), and `/gentle:customize` → Keymaps can reassign them; a saved change applies after `/reload`. While the card is hidden they change nothing and show one notice naming `/gentle:profiles card on`; with no saved profiles the notice names `/gentle:profiles`. +- `ctrl+shift+e` collapses or expands the profile card to its header, toggling the same in-memory state as clicking its title (like `ctrl+shift+a`, `ctrl+shift+j` and `ctrl+shift+t` for the agents, jobs and todo cards). `GENTLE_PI_PROFILE_CARD_COLLAPSE_KEY` rebinds it (`off` or empty leaves it unbound), `/gentle:customize` → Keymaps can reassign it, and a saved change applies after `/reload`. While the card is hidden it changes nothing and shows one notice naming `/gentle:profiles card on`. The source checkout declares `gentle-pi` `5.0.0` with a package-local Gentle AI `v5.0.0` pin; the source manifest does not establish whether that version is published. The mirror uses the signed provider bundle published with v5.0.0. Its bundle version stays `1.6.0`, and the native review CLI still advertises `capabilities/v2.6` without legacy authority. diff --git a/docs/readme-reference.md b/docs/readme-reference.md index 16f47ef5b..e29fd0941 100644 --- a/docs/readme-reference.md +++ b/docs/readme-reference.md @@ -720,7 +720,7 @@ Synthetic tests prove the observer's behavior, not the cause of issue #213. A ne ```text /gentle:status Check package assets and global model config. /gentle:doctor Run read-only diagnostics for assets, config, tools, guards, and Herdr setup. -/gentle:profiles Open the models screen on this repository's profile. Subcommands: export , import, publish , export-routing, restore-routing, clear. +/gentle:profiles Open the models screen on this repository's profile. Subcommands: export , import, publish , export-routing, restore-routing, clear, card on|off. /gentle:persona Switch between gentleman and neutral persona modes. /gentle:background-subagents Show or set the managed background-subagents policy, with its deciding source. /gentle:rdd Open the interactive RDD selector for this repository or an explicit machine-wide choice. @@ -1205,6 +1205,9 @@ The file operations are subcommands: | ------------------------------------ | ------ | | `/gentle:profiles export ` | Export a profile to `~/.pi/gentle-ai/profiles.export.json`. | | `/gentle:profiles import` | Import the profile in `~/.pi/gentle-ai/profiles.export.json`, asking before it replaces one with the same name. | +| `/gentle:profiles card on\|off` | Show or hide the sidebar profile card. Hidden by default, persisted globally in `~/.pi/gentle-ai/profile-card.json`, and applied live without `/reload`. Any other argument prints the usage and changes nothing. | +| `alt+,` / `alt+.` / `alt+m` | Profile card shortcuts: previous profile, next profile (both wrap), and use the shown profile in this session (the same action as the card's use click, so it asks for the same confirmation first). Rebind with `GENTLE_PI_PROFILE_CARD_PREVIOUS_KEY`, `GENTLE_PI_PROFILE_CARD_NEXT_KEY` and `GENTLE_PI_PROFILE_CARD_USE_KEY` (`off` or empty disables one). Hidden card or no saved profiles: no change and one notice naming `/gentle:profiles card on` or `/gentle:profiles`. | +| `ctrl+shift+e` | Collapse or expand the profile card (the same in-memory state as clicking its title, like `ctrl+shift+a` / `ctrl+shift+j` / `ctrl+shift+t` for agents, jobs and todo). Rebind with `GENTLE_PI_PROFILE_CARD_COLLAPSE_KEY` (`off` or empty disables it). Hidden card: no change and one notice naming `/gentle:profiles card on`. | | `/gentle:profiles publish ` | Publish the shared repository declaration at `/.pi/gentle-ai/profile.json` so the whole team starts from that profile; run it again to remove the declaration. | The binding made by **Use in this session** writes no shared routing: not `models.json`, Pi's global `settings.json`, agent frontmatter, `subagents.json`, or repository pins. When the table has unsaved edits, they are saved to the profile in `profiles.json` first, exactly as **Save** would, and the screen says so; with no pending edits nothing is written at all. Other open sessions keep their own bindings and live orchestrators. The session binding overrides pins and global routing as a complete snapshot, including reviewer routing; omitted roles do not fall back to another profile. The selection is appended to the session file as its own record, so start, resume, reload, fork and tree navigation restore it from the current branch without selecting it again. Re-selecting re-copies the profile definition from `profiles.json`; later edits to `subagents.json` or agent frontmatter never reach a bound session, in that session or through a re-selection. @@ -1422,7 +1425,7 @@ The notice appears once per distinct change: further launches stay quiet until t | -------------------------------- | ------------------------------------------------------------------- | | `/gentle:status` | Shows package assets and global model config status. | | `/gentle:doctor` | Runs read-only diagnostics for assets, model/persona config, memory tools, safety guards, and (inside Herdr) the task-summary sidebar setup. | -| `/gentle:profiles` | Opens the models screen on this repository's profile. `export `, `import`, and `publish ` handle profile files and the repository declaration; `export-routing` and `restore-routing` move the saved global routing through `models.export.json`. | +| `/gentle:profiles` | Opens the models screen on this repository's profile. `export `, `import`, and `publish ` handle profile files and the repository declaration; `export-routing` and `restore-routing` move the saved global routing through `models.export.json`; `card on\|off` shows or hides the sidebar profile card (hidden by default, persisted globally, live). | | `/gentle:commands` | Opens the command palette (default `alt+k`): a curated, grouped menu (Configuration, Session, Diagnostics, Skills) of registered Gentle commands; search and run by label. | | `/gentle:persona` | Switches global persona mode, with project override support. | | `/gentle:background-subagents` | Shows or sets the managed background-subagents policy (`status\|enable\|disable`), naming the source that decided it. | diff --git a/extensions/gentle-ai.ts b/extensions/gentle-ai.ts index ea119f050..c6ce9936e 100644 --- a/extensions/gentle-ai.ts +++ b/extensions/gentle-ai.ts @@ -32,6 +32,9 @@ import { ReviewContinuationRegistry, type RetainedReviewContinuation, type Retai import { boundedFindingClaims, parseReviewCoordinatorInput, runReviewCoordinator } from "../lib/review-coordinator.ts"; import { StatusTimingDiagnostics } from "../lib/status-timing-diagnostics.ts"; import { isOddPhase, oddPhaseRegistry, ODD_PHASES } from "../lib/odd-phase.ts"; +import { PROFILE_CARD_SETTINGS_CHANGED, writeProfileCard } from "../lib/profile-card-policy.ts"; +import { loadKeymaps } from "../lib/keymaps.ts"; +import { createProfileCardOwner, createProfileCardReader, createProfileCardUseHandler, mountProfileCard, PROFILE_CARD_USE_CONFIRM_TITLE, profileCardUseConfirmMessage, registerProfileCardShortcuts } from "../lib/profile-card-sidebar.ts"; import { shellEnabled } from "../lib/shell-bar.ts"; import { resolveSessionWorktree, SessionWorktreeRegistry, toolWorktreePath } from "../lib/session-worktree-registry.ts"; import { canonicalizeTarget, clearPathConsentSkills, isIndexedSkillTarget, isTempTarget, isWithinPath, setPathConsentSkills } from "../lib/path-consent-fence.ts"; @@ -3702,6 +3705,31 @@ function sessionProfileAuthorityAvailable(ctx: ExtensionContext): boolean { return readSessionProfileAuthority(manager).available; } +/** + * The card's use action: asks the user to confirm, then runs the owner's "Use in + * this session" with the real session context so its binding notices appear. The + * confirmation lives on this path and not in the shared action: the + * `/gentle:profiles` `use-session` branch applies without asking (a maintainer + * follow-up), while the card must bind nothing and move no live model or + * thinking level until the user approves. Declining changes nothing; a busy + * apply gate never prompts. Reads the store (never seeds or writes it) and runs + * only for a profile that still exists. + */ +async function useProfileFromCard(ctx: ExtensionContext, live: LiveSession, name: string): Promise { + const path = profilesFilePath(gentleAiConfigHome()); + const read = readProfilesFileResult(path); + if (read.status !== "valid") { + ctx.ui.notify(`el Gentleman cannot use profile "${name}": ${path} is missing or invalid. Run /gentle:profiles.`, "warning"); + return; + } + if (!hasOwnProfile(read.file.profiles, name)) { + ctx.ui.notify(`el Gentleman cannot use profile "${name}": it is no longer in profiles.json.`, "warning"); + return; + } + const config = normalizeModelConfig(read.file.profiles[name]) ?? {}; + await runProfilesPanelAction(ctx, live, path, read.file, { type: "use-session", name, config }); +} + /** The routing this session's launches use: its profile, or the global effective routing. */ async function readSessionLaunchModelConfigAsync(ctx: ExtensionContext, authorityAvailable: boolean): Promise { return sessionLaunchProfile(ctx, authorityAvailable)?.modelProfiles @@ -7102,7 +7130,7 @@ async function runProfilesPanelAction( } /** `/gentle:profiles`: seed or open the store, then loop the panel over one action at a time until it closes. */ -const PROFILES_COMMAND_USAGE = "Usage: /gentle:profiles [export | import | publish | export-routing | restore-routing | clear]"; +const PROFILES_COMMAND_USAGE = "Usage: /gentle:profiles [export | import | publish | export-routing | restore-routing | clear | card on|off]"; /** * `/gentle:profiles` opens the models screen. File operations live in @@ -7111,7 +7139,8 @@ const PROFILES_COMMAND_USAGE = "Usage: /gentle:profiles [export | import * profile through `profiles.export.json`, `publish ` toggles the * committed repository declaration, and `export-routing` / `restore-routing` * move the saved global routing (models.json, not a profile) through - * `models.export.json`. The routing verbs carry their own names so a profile + * `models.export.json`. `card on|off` shows or hides the sidebar profile card + * (a global flag, hidden by default, live). The routing verbs carry their own names so a profile * can never be mistaken for them. */ async function handleProfilesCommand(ctx: ExtensionContext, live: LiveSession, args = ""): Promise { @@ -7120,6 +7149,25 @@ async function handleProfilesCommand(ctx: ExtensionContext, live: LiveSession, a await openModelsScreen(ctx, live); return; } + if (verb === "card") { + const choice = rest.length === 1 ? rest[0] : undefined; + if (choice !== "on" && choice !== "off") { + ctx.ui.notify(PROFILES_COMMAND_USAGE, "warning"); + return; + } + try { + writeProfileCard(choice === "on"); + } catch (error) { + ctx.ui.notify(`Could not save the profile card setting: ${profilesErrorMessage(error)}`, "warning"); + return; + } + live.events?.emit(PROFILE_CARD_SETTINGS_CHANGED, { visible: choice === "on" }); + ctx.ui.notify( + choice === "on" ? "Profile card shown. Turn it off with /gentle:profiles card off." : "Profile card hidden. Turn it on with /gentle:profiles card on.", + "info", + ); + return; + } if (verb === "export-routing" || verb === "restore-routing" || verb === "clear") { if (rest.length > 0) { ctx.ui.notify(PROFILES_COMMAND_USAGE, "warning"); @@ -12466,6 +12514,36 @@ function createGentleAiExtensionForTesting( const statusTiming = new StatusTimingDiagnostics(); const reviewSidebar = createReviewSidebarPublisher(pi); const sessionProfiles = createSessionProfileIntegration(); + // The sidebar profile card: one owner holds the card state (visibility, shown + // profile) so the use action and keyboard shortcuts act on the same selection. + let profileCardCtx: ExtensionContext | undefined; + let stopProfileCardEvents: (() => void) | undefined; + const profileCardReader = createProfileCardReader(); + const profileCard = createProfileCardOwner({ + loadItems: () => { + if (!profileCardCtx) throw new Error("no session"); + return profileCardReader.items({ configHome: gentleAiConfigHome(), sessionId: profileCardCtx.sessionManager?.getSessionId?.(), cwd: profileCardCtx.cwd, ...(typeof profileCardCtx.sessionManager?.getBranch === "function" ? { session: profileCardCtx.sessionManager } : {}) }); + }, + }); + profileCard.setUseHandler(createProfileCardUseHandler({ + begin: beginDesktopProfileApply, + end: endDesktopProfileApply, + notify: (message, level) => { profileCardCtx?.ui.notify(message, level); }, + // /gentle:profiles `use-session` applies without asking; the card binds nothing + // before the user approves. An unanswerable dialog is never an approval. + confirm: async (name) => { + const current = profileCardCtx; + if (!current) return false; + try { return (await current.ui.confirm(PROFILE_CARD_USE_CONFIRM_TITLE, profileCardUseConfirmMessage(name))) === true; } + catch { return false; } + }, + run: async (name) => { + if (!profileCardCtx) throw new Error("no active session"); + await useProfileFromCard(profileCardCtx, pi, name); + }, + // A use just changed the session record: drop what the reader cached so the markers re-read. + refresh: () => { profileCardReader.invalidate(); profileCard.refreshItems(); }, + })); pi.on("session_before_fork", async (event, ctx) => { await waitCurrentSessionProfileSelection(ctx.sessionManager); sessionProfiles.beforeFork(ctx.sessionManager, { entryId: event.entryId, position: event.position }); @@ -12519,6 +12597,9 @@ function createGentleAiExtensionForTesting( statusTiming.reset(); reminderSessionActive = false; reminderEpoch += 1; + stopProfileCardEvents?.(); + stopProfileCardEvents = undefined; + profileCardCtx = undefined; activeRddContext = undefined; unbindPreparation?.(); unbindPreparation = undefined; @@ -13013,6 +13094,12 @@ function createGentleAiExtensionForTesting( }); } + // Pi reads extension shortcuts at startup and /reload; the keys resolve like every Gentle keymap. + { + const keymapEnv = dependencies.processEnv ?? process.env; + registerProfileCardShortcuts(pi, profileCard, keymapEnv, loadKeymaps(keymapEnv).bindings); + } + pi.on("session_start", async (event, ctx) => { const startupEpoch = reminderEpoch; const profileSessionId = ctx.sessionManager?.getSessionId?.(); @@ -13057,6 +13144,17 @@ function createGentleAiExtensionForTesting( } } readSessionProfileAuthority(ctx.sessionManager); + // The card's first read comes after this session recorded its startup profile + // and published it as the session profile, so the card starts on the profile in + // effect for this session (S2/T4b), not on the store's active one. A session + // boundary resets a card that stayed visible across a session replacement. + // The card re-reads its visibility store on the settings event (the payload is not trusted). + profileCardCtx = ctx; + stopProfileCardEvents?.(); + stopProfileCardEvents = pi.events?.on?.(PROFILE_CARD_SETTINGS_CHANGED, () => profileCard.refreshVisibility()); + profileCard.refreshVisibility(); + profileCard.resetForSession(); + if (ctx.hasUI && typeof ctx.ui.setWidget === "function") ctx.ui.setWidget("gentle-profile-card", (tui, theme) => mountProfileCard(tui, theme, profileCard)); if (ctx.hasUI) notifySessionProfileProblem(ctx); auto.reset(); yolo.reset(ctx); @@ -13633,7 +13731,7 @@ function createGentleAiExtensionForTesting( } pi.registerCommand("gentle:profiles", { - description: "Open the models screen (profiles as tabs). Subcommands: export , import, publish , export-routing, restore-routing, clear.", + description: "Open the models screen (profiles as tabs). Subcommands: export , import, publish , export-routing, restore-routing, clear, card on|off.", handler: async (args, ctx) => { await handleProfilesCommand(ctx, pi, typeof args === "string" ? args : ""); }, diff --git a/lib/keymaps.ts b/lib/keymaps.ts index 1a8cc0ea5..6ff2f7f7b 100644 --- a/lib/keymaps.ts +++ b/lib/keymaps.ts @@ -38,6 +38,10 @@ export const KEYMAP_ACTIONS: readonly KeymapAction[] = [ { id: "jobs.collapse", label: "Collapse the jobs card", env: "GENTLE_PI_JOBS_KEY", defaultKey: "ctrl+shift+j" }, { id: "todo.collapse", label: "Collapse the todo list", env: "GENTLE_PI_TODO_KEY", defaultKey: "ctrl+shift+t" }, { id: "stats.view", label: "Usage stats", env: "GENTLE_PI_STATS_VIEW_KEY", command: "gentle:stats" }, + { id: "profileCard.previous", label: "Previous profile (profile card)", env: "GENTLE_PI_PROFILE_CARD_PREVIOUS_KEY", defaultKey: "alt+," }, + { id: "profileCard.next", label: "Next profile (profile card)", env: "GENTLE_PI_PROFILE_CARD_NEXT_KEY", defaultKey: "alt+." }, + { id: "profileCard.use", label: "Use the shown profile in this session (profile card)", env: "GENTLE_PI_PROFILE_CARD_USE_KEY", defaultKey: "alt+m" }, + { id: "profileCard.collapse", label: "Collapse the profile card", env: "GENTLE_PI_PROFILE_CARD_COLLAPSE_KEY", defaultKey: "ctrl+shift+e" }, ]; // Pi refuses extension shortcuts on these editor-global keybindings diff --git a/lib/profile-card-policy.ts b/lib/profile-card-policy.ts new file mode 100644 index 000000000..9e274ca14 --- /dev/null +++ b/lib/profile-card-policy.ts @@ -0,0 +1,56 @@ +import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; +import { randomUUID } from "node:crypto"; +import { join } from "node:path"; +import { gentlePiConfigHome } from "./agent-home.ts"; + +// Whether the sidebar profile card is shown, set by `/gentle:profiles card +// on|off`. A standalone global flag, separate from the visual settings. A +// missing, malformed or unreadable file reads as hidden and never throws; the +// writer replaces such a file, since the flag is the file's only content. +// There is no environment override. +export const PROFILE_CARD_SCHEMA = "gentle-pi.profile-card/v1"; +/** Emitted on `pi.events` after the flag is written, so a sidebar can refresh live. */ +export const PROFILE_CARD_SETTINGS_CHANGED = "gentle-pi:profile-card-settings-changed"; +const PROFILE_CARD_FILE = "profile-card.json"; +interface ProfileCardOptions { gentlePiConfigHome?: string } +export interface ProfileCardResolution { + visible: boolean; + source: "global_file" | "default"; + malformed: boolean; + globalFile: string; +} + +export function parseProfileCardFile(raw: string): boolean | undefined { + try { + const value: unknown = JSON.parse(raw); + if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined; + if (Object.keys(value).length !== 2 || !("schema" in value) || value.schema !== PROFILE_CARD_SCHEMA || !("visible" in value)) return undefined; + return typeof value.visible === "boolean" ? value.visible : undefined; + } catch { return undefined; } +} + +export function resolveProfileCard(options: ProfileCardOptions = {}): ProfileCardResolution { + const globalFile = join(options.gentlePiConfigHome ?? gentlePiConfigHome(), PROFILE_CARD_FILE); + try { + const visible = parseProfileCardFile(readFileSync(globalFile, "utf8")); + return { visible: visible ?? false, source: "global_file", malformed: visible === undefined, globalFile }; + } catch (error) { + const missing = typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT"; + return { visible: false, source: missing ? "default" : "global_file", malformed: !missing, globalFile }; + } +} + +export function writeProfileCard(visible: boolean, options: ProfileCardOptions = {}): string { + if (typeof visible !== "boolean") throw new TypeError("Invalid profile card visibility"); + const home = options.gentlePiConfigHome ?? gentlePiConfigHome(); + const path = join(home, PROFILE_CARD_FILE); + const temporary = `${path}.${randomUUID()}.tmp`; + mkdirSync(home, { recursive: true }); + try { + writeFileSync(temporary, `${JSON.stringify({ schema: PROFILE_CARD_SCHEMA, visible })}\n`, { flag: "wx", mode: 0o600 }); + renameSync(temporary, path); + } finally { + try { unlinkSync(temporary); } catch { /* Rename consumed the temporary file. */ } + } + return path; +} diff --git a/lib/profile-card-sidebar.ts b/lib/profile-card-sidebar.ts new file mode 100644 index 000000000..c726cd226 --- /dev/null +++ b/lib/profile-card-sidebar.ts @@ -0,0 +1,508 @@ +import { statSync } from "node:fs"; +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; +import type { Component, TUI, TuiMouseEvent, TuiMouseEventResult } from "@earendil-works/pi-tui"; +import { effectiveKey, type KeymapBindings } from "./keymaps.ts"; +import { evaluateProfilePin, readProfilePinStatus } from "./agent-profile-pin.ts"; +import { profilesFilePath, readProfilesFileResult, type ProfilesFileReadResult } from "./agent-profiles.ts"; +import { NativePointerRegion } from "./native-pointer-region.ts"; +import { resolveProfileCard } from "./profile-card-policy.ts"; +import { readSessionProfileBinding } from "./session-profile-binding.ts"; +import { readSessionProfileDisk, type SessionProfileSource } from "./session-profile-disk-reader.ts"; +import { readCurrentSessionProfileFailedEntryIds } from "./session-profile-integration.ts"; +import { isSessionProfileFamilyEntry } from "./session-profile-persistence.ts"; +import { + buildProfileCardItems, + initialProfileIndex, + nextProfileIndex, + previousProfileIndex, + profileCardActionAt, + reconcileProfileIndex, + renderProfileCardSection, + type ProfileCardAction, + type ProfileCardHit, + type ProfileCardItem, +} from "./profile-card-widget.ts"; +import type { PanelTheme } from "./shell-panel.ts"; +import { releaseSidebarHover, setSidebarHover, sidebarPart, type SidebarRail } from "./shell-sidebar.ts"; +import { invalidateSidebar } from "./shell-sidebar-layout.ts"; + +// The sidebar profile card's owner and registration glue. The owner holds the +// ONE copy of the card state (visibility, shown profile) so every surface — +// mouse clicks here, the "use" action (T4) and keyboard shortcuts (T5) — acts +// on the same selection. It does no rendering; `mountProfileCard` paints it. + +/** The key the card registers under in `sidebarState(tui).parts`. */ +export const PROFILE_CARD_SIDEBAR_KEY = "profiles"; +// Saved profiles and session markers change outside this process's events (the +// /gentle:profiles panel writes the store), so a visible card re-reads them at +// most this often instead of on every frame. +export const PROFILE_CARD_REFRESH_MS = 1000; + +/** Applies the shown profile in this session. T4 supplies the real implementation. */ +export type ProfileCardUseHandler = (name: string) => void | Promise; + +/** + * Asks the user to approve binding a profile to this session (S3/S6). The card + * confirms before anything is bound: declining leaves the session binding, the + * live model and the thinking level exactly as they were. + */ +export type ProfileCardUseConfirmation = (name: string) => boolean | Promise; + +/** The confirmation dialog the card shows before it binds a profile. */ +export const PROFILE_CARD_USE_CONFIRM_TITLE = "Use this profile in this session?"; + +export function profileCardUseConfirmMessage(name: string): string { + return `Profile "${name}" will be bound to this session: its routing applies to this session's subagents, and this session attempts to switch its live model and thinking level to the profile's orchestrator. Nothing shared is written — the global routing, pins and materialized stores are untouched. Continue?`; +} + +export interface ProfileCardOwnerOptions { + /** The saved profiles with their markers, read from the profile stores. */ + loadItems: () => readonly ProfileCardItem[]; + /** The "use" seam; defaults to a no-op until the owner action is wired. */ + onUse?: ProfileCardUseHandler; + /** Config home holding profile-card.json; the real one when omitted. */ + configHome?: () => string | undefined; + now?: () => number; +} + +export interface ProfileCardOwner { + /** Whether profile-card.json says the card is shown (as last read). */ + visible(): boolean; + items(): readonly ProfileCardItem[]; + /** The shown position, always valid for `items()` (0 when empty). */ + index(): number; + /** The shown profile, or undefined with no saved profiles. */ + shown(): ProfileCardItem | undefined; + /** Whether the card shows only its header. In memory like the other cards' collapse state: it resets with the session. */ + collapsed(): boolean; + /** Fold or unfold the card; repaints every surface. */ + toggleCollapsed(): void; + /** Re-read the visibility flag from its store; a card turning on restarts at the session's profile. */ + refreshVisibility(): void; + /** Re-read the saved profiles, keeping the shown one by name when it still exists (one session: `resetForSession` at a boundary). */ + refreshItems(): void; + /** + * A session boundary (`session_start`): restart on the profile in effect for + * the new session even when the card is already visible, so the card never + * shows (and the use action never applies) a profile the new session does not + * use, and expands a collapsed card. A hidden card still reads nothing. + */ + resetForSession(): void; + /** Cheap staleness check for render time: refreshItems at most once per PROFILE_CARD_REFRESH_MS while visible. */ + pollItems(): void; + next(): boolean; + previous(): boolean; + /** Run the use handler for the shown profile; false when nothing is shown. */ + use(): boolean; + setUseHandler(handler: ProfileCardUseHandler | undefined): void; + /** Called after any change a surface must repaint for. */ + onChange(listener: () => void): () => void; + /** A string that changes whenever the painted card would. */ + digest(): string; +} + +export function createProfileCardOwner(options: ProfileCardOwnerOptions): ProfileCardOwner { + const now = options.now ?? Date.now; + const listeners = new Set<() => void>(); + let useHandler = options.onUse; + let visible = false; + let items: readonly ProfileCardItem[] = []; + let index = 0; + let selectedName: string | undefined; + let collapsed = false; + let loadedAt = Number.NEGATIVE_INFINITY; + const emit = () => { for (const listener of [...listeners]) listener(); }; + // A failed read (a stale session context, say) keeps what the card already shows. + const safeLoad = (): readonly ProfileCardItem[] => { + try { return options.loadItems(); } catch { return items; } + }; + const select = (next: number) => { index = next; selectedName = items[next]?.name; }; + const same = (a: readonly ProfileCardItem[], b: readonly ProfileCardItem[]) => JSON.stringify(a) === JSON.stringify(b); + const reload = (restart: boolean): boolean => { + const loaded = safeLoad(); + loadedAt = now(); + const before = `${index}:${selectedName}`; + const changed = !same(items, loaded); + items = loaded; + select(restart ? initialProfileIndex(items) : reconcileProfileIndex(selectedName, index, items)); + return changed || before !== `${index}:${selectedName}`; + }; + const move = (target: (index: number, count: number) => number): boolean => { + if (!visible || items.length === 0) return false; + const next = target(index, items.length); + const changed = next !== index; + select(next); + if (changed) emit(); + return changed; + }; + return { + visible: () => visible, + items: () => items, + index: () => index, + shown: () => items[index], + collapsed: () => collapsed, + toggleCollapsed() { + collapsed = !collapsed; + emit(); + }, + refreshVisibility() { + let next = false; + try { next = resolveProfileCard({ gentlePiConfigHome: options.configHome?.() }).visible; } catch { next = false; } + const turnedOn = next && !visible; + visible = next; + if (turnedOn) reload(true); + emit(); + }, + refreshItems() { + // Hidden by default: a hidden card reads nothing, so the profile stores stay untouched. + if (!visible) return; + if (reload(false)) emit(); + }, + resetForSession() { + // Collapse is in-memory for one session: the new session starts expanded, before + // the guard so a card that was folded and then hidden also expands. + collapsed = false; + // The shown profile belongs to the session that showed it: a boundary restarts at + // the profile in effect now, even when the previous selection still exists. + if (!visible) return; + reload(true); + emit(); + }, + pollItems() { + // No emit: the caller is the render pass, which reads `digest()` right after. + if (!visible || now() - loadedAt < PROFILE_CARD_REFRESH_MS) return; + reload(false); + }, + next: () => move(nextProfileIndex), + previous: () => move(previousProfileIndex), + use() { + const name = items[index]?.name; + if (!visible || name === undefined) return false; + void Promise.resolve(useHandler?.(name)).catch(() => {}); + return true; + }, + setUseHandler(handler) { useHandler = handler; }, + onChange(listener) { + listeners.add(listener); + return () => { listeners.delete(listener); }; + }, + digest: () => JSON.stringify([visible, items, index, collapsed]), + }; +} + +/** Route one click's action to the owner: arrows navigate, `use` runs the handler. */ +export function runProfileCardAction(owner: ProfileCardOwner, action: ProfileCardAction): void { + if (action === "previous") owner.previous(); + else if (action === "next") owner.next(); + else owner.use(); +} + +/** + * Register the card as the fullscreen rail's "profiles" section. It paints only + * in the rail (the above-editor copy is always empty) and only while the owner + * says visible. Returns the part, whose dispose() unregisters it and stops the + * owner's repaint subscription. + */ +export function mountProfileCard(tui: TUI, theme: PanelTheme, owner: ProfileCardOwner): Component & { dispose(): void } { + // Click positions belong to the width that painted them: /gentle:panel renders + // this same card at sheet width, far wider than the rail, and a sheet frame must + // never route a rail click (it could land on "use"). The rail re-renders at its + // own width only when its digest changes, so the last two frames — the rail's and + // the sheet's — are kept and a click resolves against the width it names. + let frames: Array<{ width: number; hits: readonly ProfileCardHit[] }> = []; + const hitsAt = (width: number | undefined) => frames.find((frame) => frame.width === width)?.hits ?? []; + // Only the title row is the collapse control (frame row 0), like the other cards. + let hovered = false; + const repaint = () => { + invalidateSidebar(tui); + (tui as { requestRender?: () => void }).requestRender?.(); + }; + const unsubscribe = owner.onChange(repaint); + const card: Component = { + render(width: number) { + if (!owner.visible()) { + frames = []; + return []; + } + const section = renderProfileCardSection(owner.items(), owner.index(), theme, width, { collapsed: owner.collapsed(), hovered }); + frames = [...frames.filter((frame) => frame.width !== width), { width, hits: section.hits }].slice(-2); + return section.lines; + }, + invalidate() { + hovered = false; + }, + }; + const region: NativePointerRegion = new NativePointerRegion(card, { + onHover(event) { + if (!owner.visible()) return undefined; + const next = event.y === 0; + if (next) setSidebarHover(tui, region, () => region.clearHover()); + else setSidebarHover(tui); + if (next === hovered) return { handled: true }; + hovered = next; + return { handled: true, render: true }; + }, + onLeave() { + releaseSidebarHover(tui, region); + if (!hovered) return; + hovered = false; + repaint(); + }, + onClick(event) { + if (event.button !== "left" || !owner.visible()) return undefined; + if (event.y === 0) { + region.clearHover(); + owner.toggleCollapsed(); + return { handled: true, render: true }; + } + const action = profileCardActionAt(hitsAt(event.width), event.x, event.y); + if (action === undefined) return undefined; + runProfileCardAction(owner, action); + return { handled: true, render: true }; + }, + }); + const rail: SidebarRail & { dispose(): void } = { + surface: "panel", + render: (width: number) => region.render(width), + digest() { + owner.pollItems(); + return hovered ? `${owner.digest()}:hover` : owner.digest(); + }, + handleMouse: (event: TuiMouseEvent) => region.handleMouse(event), + invalidate: () => region.invalidate(), + dispose() { unsubscribe(); region.dispose(); }, + }; + const bottom: Component & { dispose?(): void } = { render: () => [], invalidate() {} }; + const part = sidebarPart(tui, PROFILE_CARD_SIDEBAR_KEY, bottom, rail); + return { ...part, dispose() { unsubscribe(); region.dispose(); part.dispose(); } }; +} + +// ---- Display read ---- + +export interface ProfileCardReaderDeps { + /** The pure session record read; tests inject a counting spy. */ + readDisk?: typeof readSessionProfileDisk; + readProfiles?: typeof readProfilesFileResult; +} + +export interface ProfileCardSource { + configHome: string; + sessionId: string | undefined; + cwd: string; + session?: SessionProfileSource; +} + +export interface ProfileCardReader { + /** The saved profiles with their markers; see `readProfileCardItems`. */ + items(source: ProfileCardSource): ProfileCardItem[]; + /** Forget what was read, so the next `items` reads again (right after a use). */ + invalidate(): void; +} + +/** Cheap file identity from one stat (inode, size, mtime in ns); undefined when the file cannot be statted. */ +function fileSignature(path: string | undefined): string | undefined { + if (path === undefined) return undefined; + try { + const stat = statSync(path, { bigint: true }); + return `${stat.ino}:${stat.size}:${stat.mtimeNs}`; + } catch { return undefined; } +} + +/** The id of the newest session-profile record on the branch: an in-memory scan, no I/O. */ +function newestRecordId(session: SessionProfileSource): string { + try { + const branch = session.getBranch(); + for (let index = branch.length - 1; index >= 0; index--) { + if (isSessionProfileFamilyEntry(branch[index])) return String((branch[index] as { id?: unknown }).id); + } + } catch { /* An unreadable branch is simply a different signal. */ } + return ""; +} + +/** + * The card's display reader. Strictly pure (no freeze, clear, append or write), + * and change-driven: a visible card refreshes every second, and the session + * file can be several MB, so each source is re-read only when its signal moved. + * + * Session marker. The newest session-profile record on the branch, corroborated + * by `readSessionProfileDisk` (stateless, no writes, no cache): a bind is the + * user's explicit choice (origin `user`) or the session's startup record + * (origin local/repo/global), so the newest record gives the precedence; a + * clear or no record means no profile. `resolveSessionProfile` and + * `readSessionProfileAuthority` are NOT used: they freeze a profile or clear a + * binding they cannot corroborate. A record whose append failed is excluded + * through the append controller's own failed-ID evidence + * (`readCurrentSessionProfileFailedEntryIds`, a pure read with no refresh), so + * the card shows what the authority decides is in effect, never a record the + * authority has quarantined. Signal for re-reading: the session file's + * stat signature (a profile record reaches disk only by appending, which moves + * size and mtime), the newest profile record id on the branch (an in-memory + * scan; a record newer than disk is not disk-corroborated yet), the excluded + * IDs and the in-memory binding name. A stat is one syscall regardless of file + * size; the branch scan costs no I/O. An indeterminate read (file not flushed, + * record newer than disk) is never cached: it falls back to the in-memory + * binding (`readSessionProfileBinding`, a copy read) and retries on the next tick. + * + * profiles.json is small but is gated the same way, by its stat signature. + */ +export function createProfileCardReader(deps: ProfileCardReaderDeps = {}): ProfileCardReader { + const readDisk = deps.readDisk ?? readSessionProfileDisk; + const readProfiles = deps.readProfiles ?? readProfilesFileResult; + let marker: { signal: string; name: string | undefined } | undefined; + let profiles: { path: string; signature: string; result: ProfilesFileReadResult } | undefined; + const readProfilesGated = (path: string): ProfilesFileReadResult => { + const signature = fileSignature(path); + if (signature !== undefined && profiles?.path === path && profiles.signature === signature) return profiles.result; + const result = readProfiles(path); + profiles = signature !== undefined && result.status === "valid" ? { path, signature, result } : undefined; + return result; + }; + const readMarker = (sessionId: string | undefined, session: SessionProfileSource | undefined): string | undefined => { + const memory = readSessionProfileBinding(sessionId)?.name; + if (session === undefined) return memory; + let file: string | undefined; + try { file = session.getSessionFile(); } catch { return memory; } + // The append authority's own exclusion, read purely: a record whose append + // failed is never the profile in effect, even when it reached disk. + const failed = readCurrentSessionProfileFailedEntryIds(session); + const signature = fileSignature(file); + const signal = signature === undefined ? undefined : JSON.stringify([sessionId, file, signature, newestRecordId(session), [...failed].sort(), memory ?? null]); + if (signal !== undefined && marker?.signal === signal) return marker.name; + try { + const disk = readDisk(session, { knownFailedEntryIds: failed }); + if (disk.status === "indeterminate") return memory; + const name = disk.status === "bound" ? disk.binding.name : undefined; + marker = signal === undefined ? undefined : { signal, name }; + return name; + } catch { return memory; } + }; + return { + items(source) { + const read = readProfilesGated(profilesFilePath(source.configHome)); + if (read.status !== "valid") return []; + const pinned = evaluateProfilePin(readProfilePinStatus(source.cwd), read.file.profiles).winner?.profile; + return buildProfileCardItems(read.file, pinned, readMarker(source.sessionId, source.session)); + }, + invalidate() { + marker = undefined; + profiles = undefined; + }, + }; +} + +/** + * The saved profiles with their markers, read without side effects. Without a + * `reader` every call reads fresh; the live card passes one shared reader. + * A missing or invalid store shows nothing and is never seeded. + */ +export function readProfileCardItems(source: ProfileCardSource, reader: ProfileCardReader = createProfileCardReader()): ProfileCardItem[] { + return reader.items(source); +} + +// ---- Use action ---- + +export const PROFILE_CARD_BUSY_NOTICE = "Another profile apply is already running. Wait for it to finish, then use the profile again."; + +export interface ProfileCardUseDeps { + /** The shared single-apply gate (`beginDesktopProfileApply`); false when another apply holds it. */ + begin: () => boolean; + end: () => void; + notify: (message: string, level: "info" | "warning") => void; + /** + * Asks the user before anything is bound, inside the gate (a busy apply never + * prompts). Only `true` applies; declining or a failing confirmation surface + * binds nothing and leaves the live model and thinking level alone. Omitting it + * keeps the unconfirmed behavior for hosts without a confirmation surface. + */ + confirm?: ProfileCardUseConfirmation; + /** The owner's "Use in this session" action for one profile, with its own notices. */ + run: (name: string) => Promise; + /** Re-read the card's items so the markers reflect the outcome. */ + refresh: () => void; +} + +/** + * The card's use handler: asks for confirmation, then runs the owner action under + * the shared apply gate. A busy gate applies nothing and says so without asking; + * a declined confirmation binds nothing; a failing action is notified, never + * thrown into the TUI; the gate is always released and an applied action's + * markers refreshed. + */ +export function createProfileCardUseHandler(deps: ProfileCardUseDeps): ProfileCardUseHandler { + return async (name) => { + if (!deps.begin()) { + deps.notify(PROFILE_CARD_BUSY_NOTICE, "info"); + return; + } + let attempted = false; + try { + // Asked under the gate: no two prompts race, and a busy gate never prompts. + if (deps.confirm !== undefined) { + let approved = false; + try { approved = (await deps.confirm(name)) === true; } catch { approved = false; } + if (!approved) return; + } + attempted = true; + await deps.run(name); + } catch (error) { + deps.notify(`Could not use profile "${name}" in this session: ${error instanceof Error ? error.message : String(error)}`, "warning"); + } finally { + deps.end(); + if (attempted) { + try { deps.refresh(); } catch { /* A failed re-read keeps the markers on screen. */ } + } + } + }; +} + +// ---- Keyboard shortcuts ---- + +export const PROFILE_CARD_HIDDEN_NOTICE = "The profile card is hidden. Turn it on with /gentle:profiles card on."; +export const PROFILE_CARD_EMPTY_NOTICE = "The profile card has no saved profiles. Create one in /gentle:profiles."; + +/** + * One shortcut press. A hidden card or an empty list changes nothing and says + * why in a single info notice; otherwise previous/next move the shown profile + * (the owner repaints the rail) and use runs the same handler a click runs. + */ +export function runProfileCardShortcut(owner: ProfileCardOwner, action: ProfileCardAction, notify: (message: string, level: "info") => void): void { + if (!owner.visible()) { notify(PROFILE_CARD_HIDDEN_NOTICE, "info"); return; } + if (owner.items().length === 0) { notify(PROFILE_CARD_EMPTY_NOTICE, "info"); return; } + runProfileCardAction(owner, action); +} + +/** The collapse shortcut: a hidden card changes nothing and says why; otherwise it toggles the same state as the title click. */ +export function runProfileCardCollapseShortcut(owner: ProfileCardOwner, notify: (message: string, level: "info") => void): void { + if (!owner.visible()) { notify(PROFILE_CARD_HIDDEN_NOTICE, "info"); return; } + owner.toggleCollapsed(); +} + +const PROFILE_CARD_SHORTCUTS: ReadonlyArray<{ id: string; action: ProfileCardAction | "collapse"; description: string }> = [ + { id: "profileCard.previous", action: "previous", description: "Show the previous profile on the profile card" }, + { id: "profileCard.next", action: "next", description: "Show the next profile on the profile card" }, + { id: "profileCard.use", action: "use", description: "Use the profile shown on the profile card in this session" }, + { id: "profileCard.collapse", action: "collapse", description: "Collapse or expand the profile card" }, +]; + +/** + * Register the card's shortcuts on the key each `KEYMAP_ACTIONS` entry resolves + * to (environment variable, then saved keymaps.json, then default; "off" or + * empty leaves one unregistered). Called where the owner lives, with the same + * `effectiveKey` resolution every Gentle shortcut uses. + */ +export function registerProfileCardShortcuts(pi: Pick, owner: ProfileCardOwner, env: NodeJS.ProcessEnv, bindings: KeymapBindings): void { + // Minimal hosts (and test doubles) have no shortcut registry. + if (typeof pi.registerShortcut !== "function") return; + for (const shortcut of PROFILE_CARD_SHORTCUTS) { + const key = effectiveKey(shortcut.id, env, bindings); + if (!key) continue; + pi.registerShortcut(key as Parameters[0], { + description: shortcut.description, + handler: (ctx: ExtensionContext) => { + const notify = (message: string, level: "info") => ctx.ui.notify(message, level); + if (shortcut.action === "collapse") runProfileCardCollapseShortcut(owner, notify); + else runProfileCardShortcut(owner, shortcut.action, notify); + }, + }); + } +} diff --git a/lib/profile-card-widget.ts b/lib/profile-card-widget.ts new file mode 100644 index 000000000..42dcdfa8e --- /dev/null +++ b/lib/profile-card-widget.ts @@ -0,0 +1,167 @@ +import { visibleWidth } from "@earendil-works/pi-tui"; +import type { AgentProfilesFile } from "./agent-profiles.ts"; +import { clipPanelText, PANEL_ROW_INDENT, renderPanelHeader, renderPanelRow, type PanelTheme } from "./shell-panel.ts"; +import { sanitizeTerminalText } from "./terminal-theme.ts"; + +// Profile card: the pure part of the sidebar card that shows ONE saved agent +// profile, navigates between profiles with ◀/▶ (wrapping) and offers a "use" +// action. No pi/ctx access and no I/O: the sidebar registers the section, +// owns the selected index, and routes clicks through `profileCardActionAt`. + +export type ProfileCardAction = "previous" | "next" | "use"; + +/** + * A clickable span in the section's own frame: `y` is the row (0 = header), + * `x0` inclusive and `x1` exclusive are columns from the section's left edge. + */ +export interface ProfileCardHit { + y: number; + x0: number; + x1: number; + action: ProfileCardAction; +} + +export interface ProfileCardItem { + name: string; + active: boolean; + pinned: boolean; + session: boolean; +} + +export interface ProfileCardRender { + lines: string[]; + hits: ProfileCardHit[]; +} + +export const PROFILE_CARD_PREVIOUS_GLYPH = "◀"; +export const PROFILE_CARD_NEXT_GLYPH = "▶"; +export const PROFILE_CARD_USE_GLYPH = "✓"; +export const PROFILE_CARD_USE_LABEL = "Use in session"; +export const PROFILE_CARD_EMPTY_HINT = "No profiles yet. Create one in /gentle:profiles"; + +// ---- Navigation state ---- + +/** + * One item per saved profile, with the same markers `buildProfileListItems` + * names: `active` is the global claim; a session binding outranks the pin, so + * `session` and `pinned` never both apply to one profile. + */ +export function buildProfileCardItems(file: Pick, pinned?: string, sessionBound?: string): ProfileCardItem[] { + return Object.keys(file.profiles).map((name) => ({ + name, + active: name === file.active, + pinned: name !== sessionBound && name === pinned, + session: name === sessionBound, + })); +} + +/** The profile in effect for the session: session marker first, then active, else the first. */ +export function initialProfileIndex(items: readonly ProfileCardItem[]): number { + const session = items.findIndex((entry) => entry.session); + if (session >= 0) return session; + const active = items.findIndex((entry) => entry.active); + return active >= 0 ? active : 0; +} + +export function nextProfileIndex(index: number, count: number): number { + return count <= 0 ? 0 : (clampIndex(index, count) + 1) % count; +} + +export function previousProfileIndex(index: number, count: number): number { + return count <= 0 ? 0 : (clampIndex(index, count) - 1 + count) % count; +} + +/** The index to show after the list changed: the same profile name if it still exists, else the old index clamped. */ +export function reconcileProfileIndex(selectedName: string | undefined, index: number, items: readonly ProfileCardItem[]): number { + if (selectedName !== undefined) { + const found = items.findIndex((entry) => entry.name === selectedName); + if (found >= 0) return found; + } + return clampIndex(index, items.length); +} + +function clampIndex(index: number, count: number): number { + if (count <= 0 || !Number.isFinite(index)) return 0; + return Math.max(0, Math.min(count - 1, Math.trunc(index))); +} + +// ---- Rendering ---- + +const ARROW_ROLE = "accent"; +const NAME_ROLE = "text"; +const META_ROLE = "dim"; +// Below this width the row drops its indent so the arrows still fit. +const MIN_INDENTED_WIDTH = 7; + +function clean(text: string): string { + return sanitizeTerminalText(text).replace(/\s+/g, " "); +} + +function markersText(entry: ProfileCardItem): string { + const marks = [entry.active ? "active" : "", entry.pinned ? "pinned" : "", entry.session ? "session" : ""].filter(Boolean); + return marks.length ? `(${marks.join(", ")})` : ""; +} + +export interface ProfileCardRenderOptions { + /** Only the header row is drawn: no body rows and no hits. */ + collapsed?: boolean; + /** The pointer is on the title row: it paints the shared hover role like the other cards. */ + hovered?: boolean; +} + +/** The profile card section: header, one navigation row and the use row; or the empty-state hint. */ +export function renderProfileCardSection(items: readonly ProfileCardItem[], index: number, theme: PanelTheme, width: number, options: ProfileCardRenderOptions = {}): ProfileCardRender { + const w = Math.max(0, Math.floor(width)); + const header = renderPanelHeader(theme, w, { title: "Profile", open: !options.collapsed, hovered: options.hovered === true }); + if (options.collapsed) return { lines: [header], hits: [] }; + if (items.length === 0) { + return { lines: [header, renderPanelRow(w, theme.fg(META_ROLE, clipPanelText(PROFILE_CARD_EMPTY_HINT, Math.max(0, w - PANEL_ROW_INDENT))))], hits: [] }; + } + const current = clampIndex(index, items.length); + const entry = items[current]!; + const indent = w >= MIN_INDENTED_WIDTH ? PANEL_ROW_INDENT : 0; + const prev = PROFILE_CARD_PREVIOUS_GLYPH; + const next = PROFILE_CARD_NEXT_GLYPH; + const hits: ProfileCardHit[] = []; + + // Navigation row: `◀ name (markers) n/total ▶`, ▶ pinned to the last column. + let nav: string; + if (w < 2) { + nav = w === 1 ? theme.fg(ARROW_ROLE, prev) : ""; + if (w === 1) hits.push({ y: 1, x0: 0, x1: 1, action: "previous" }); + } else { + const counter = `${current + 1}/${items.length}`; + let right = `${counter} ${next}`; + let room = w - indent - 2 - visibleWidth(right) - 1; + if (room < 1) { right = next; room = w - indent - 2 - 1 - 1; } + const name = clean(entry.name); + const markers = markersText(entry); + let left = ""; + if (room >= 1) { + const markersWidth = markers ? visibleWidth(markers) + 1 : 0; + if (visibleWidth(name) + markersWidth <= room) { + left = theme.fg(NAME_ROLE, name) + (markers ? ` ${theme.fg(META_ROLE, markers)}` : ""); + } else if (markers && room - markersWidth >= 4) { + left = `${theme.fg(NAME_ROLE, clipPanelText(name, room - markersWidth))} ${theme.fg(META_ROLE, markers)}`; + } else { + left = theme.fg(NAME_ROLE, clipPanelText(name, room)); + } + } + const head = `${" ".repeat(indent)}${theme.fg(ARROW_ROLE, prev)}${left ? ` ${left}` : ""}`; + const rightPainted = right === next ? theme.fg(ARROW_ROLE, next) : `${theme.fg(META_ROLE, counter)} ${theme.fg(ARROW_ROLE, next)}`; + nav = `${head}${" ".repeat(Math.max(0, w - visibleWidth(head) - visibleWidth(right)))}${rightPainted}`; + hits.push({ y: 1, x0: indent, x1: indent + 1, action: "previous" }, { y: 1, x0: w - 1, x1: w, action: "next" }); + } + + // Use row: glyph and label are one clickable span. + const useText = clipPanelText(`${PROFILE_CARD_USE_GLYPH} ${PROFILE_CARD_USE_LABEL}`, Math.max(0, w - indent)); + const useRow = `${" ".repeat(indent)}${theme.fg(ARROW_ROLE, useText)}`; + const usePadded = `${useRow}${" ".repeat(Math.max(0, w - visibleWidth(useRow)))}`; + if (visibleWidth(useText) > 0) hits.push({ y: 2, x0: indent, x1: indent + visibleWidth(useText), action: "use" }); + return { lines: [header, nav, usePadded], hits }; +} + +/** The action whose span covers the frame coordinate (`x` from the left edge, `y` from the first row), if any. */ +export function profileCardActionAt(hits: readonly ProfileCardHit[], x: number, y: number): ProfileCardAction | undefined { + return hits.find((hit) => hit.y === y && x >= hit.x0 && x < hit.x1)?.action; +} diff --git a/lib/session-profile-append-controller.ts b/lib/session-profile-append-controller.ts index 25ff66fac..85decd197 100644 --- a/lib/session-profile-append-controller.ts +++ b/lib/session-profile-append-controller.ts @@ -472,6 +472,26 @@ export function createSessionProfileAppendController( return unavailable("append-not-corroborated"); } } + /** + * Pure read of the IDs this controller already excludes as failed appends: a + * display read needs the authority's exclusion without its refresh. No + * capture, no scope creation, no state change; a copy, so callers cannot + * mutate the evidence. A detached controller has no source to key the + * evidence, so it excludes nothing. + */ + function knownFailedEntryIds(): ReadonlySet { + try { + if (!source) return new Set(); + const session = source.getSessionId(), + file = source.getSessionFile(); + if (typeof session !== "string" || !session) return new Set(); + if (file !== undefined && (typeof file !== "string" || !file)) + return new Set(); + return new Set(scopes.get(session)?.get(file)?.failed); + } catch { + return new Set(); + } + } function attachment(): SessionProfileAttachment { const epoch = generation; const live = () => source !== undefined && epoch === generation; @@ -724,5 +744,11 @@ export function createSessionProfileAppendController( } return attachment(); } - return { ...attachment(), captureForkEvidence, detach, attach }; + return { + ...attachment(), + captureForkEvidence, + detach, + attach, + knownFailedEntryIds, + }; } diff --git a/lib/session-profile-integration.ts b/lib/session-profile-integration.ts index d22146a2a..cc403bbed 100644 --- a/lib/session-profile-integration.ts +++ b/lib/session-profile-integration.ts @@ -9,6 +9,7 @@ import { type SessionProfileForkPreparation, type SessionProfileForkHandoff, } from "./session-profile-append-controller.ts"; +import type { SessionProfileSource } from "./session-profile-disk-reader.ts"; export type SessionProfileLifecycleManager = SessionProfileForkView; export type SessionProfileLifecycleReason = @@ -83,6 +84,23 @@ export function readCurrentSessionProfileOutcome( } } +/** + * Pure read of the IDs the session's append authority already excludes as + * failed appends, so a display read applies the same exclusion as the authority + * that decides what is in effect. No refresh, no capture and no other effect: + * unlike `readCurrentSessionProfileOutcome`, looking here changes nothing. + * The key is the identity the lifecycle registered (the session manager). + */ +export function readCurrentSessionProfileFailedEntryIds( + source: SessionProfileSource, +): ReadonlySet { + try { + return registry().owners.get(source)?.controller.knownFailedEntryIds() ?? new Set(); + } catch { + return new Set(); + } +} + /** Serialize explicit selections; lifecycle hooks drain this same owner queue. * The promise is transient work, not another quarantine or authority store. */ diff --git a/lib/shell-panel.ts b/lib/shell-panel.ts index 5b1fa9721..321dcc98b 100644 --- a/lib/shell-panel.ts +++ b/lib/shell-panel.ts @@ -122,7 +122,7 @@ export interface PanelSheet { maxScroll: number; } -const SHEET_ORDER = ["todo", "jobs", "agents", "footer"] as const; +const SHEET_ORDER = ["todo", "jobs", "agents", "profiles", "footer"] as const; /** * The rail's sections as a full-width sheet (/gentle:panel, mobile): a fixed diff --git a/lib/shell-sidebar-layout.ts b/lib/shell-sidebar-layout.ts index c19e90300..e17881292 100644 --- a/lib/shell-sidebar-layout.ts +++ b/lib/shell-sidebar-layout.ts @@ -341,7 +341,7 @@ export function installSidebar(tui: TUI, theme: ShellBarTheme, placement: () => // A carded section renders one indent wider; its body rows drop that indent inside the card. const renderWidth = carded ? panelInnerWidth(theme, contentWidth) + PANEL_ROW_INDENT : contentWidth - RAIL_PADDING * 2; // Live work first, then the session Status sections (design/shell-rework/02-proposal.html). - const sections = ["todo", "jobs", "agents", "footer"].filter((key) => key !== "todo" || state.visibility?.todo !== false).map((key) => { + const sections = ["todo", "jobs", "agents", "profiles", "footer"].filter((key) => key !== "todo" || state.visibility?.todo !== false).map((key) => { const component = state.parts.get(key); if (!component) { sectionCache.delete(key); @@ -401,7 +401,9 @@ export function installSidebar(tui: TUI, theme: ShellBarTheme, placement: () => // The title row folds the section like its header; body rows keep their own rows. const frame = { frameWidth: renderWidth, frameHeight: section.lines.length }; hits.push({ key: section.key, component: section.component, startY: top + geometry.headerRow, height: 1, width: renderWidth, x: geometry.headerX, row: group.start, wholeRow: true, ...frame }); - if (body.length) hits.push({ key: section.key, component: section.component, startY: top + geometry.bodyRow, height: body.length, width: renderWidth - PANEL_ROW_INDENT, x: geometry.bodyX - PANEL_ROW_INDENT, row: group.start + 1, ...frame }); + // The body drops its indent, so its frame x starts PANEL_ROW_INDENT left of bodyX: the span + // is the whole frame width, which keeps the last body cells (a ▶ in the last column) hittable. + if (body.length) hits.push({ key: section.key, component: section.component, startY: top + geometry.bodyRow, height: body.length, width: renderWidth, x: geometry.bodyX - PANEL_ROW_INDENT, row: group.start + 1, ...frame }); }); const loose = (layout.loose ?? []).map((row) => section.lines[row] ?? "").filter((row) => row.trim() !== ""); if (loose.length && sectionGap(density())) railLines.push(""); diff --git a/odd/tasks/profile-card.md b/odd/tasks/profile-card.md new file mode 100644 index 000000000..6f7909358 --- /dev/null +++ b/odd/tasks/profile-card.md @@ -0,0 +1,81 @@ +# Profile card: swipe and apply saved profiles from the sidebar + +Branch `feat/profile-card`. A new Gentle Shell sidebar card shows one saved agent-model +profile at a time, navigates between profiles horizontally, and applies the shown one to the +current session. Opt-in through `/gentle:profiles card on|off`. + +## Specs + +- **S1 Visibility command.** User: "El card debe ser configurable por el usuario, es decir, + configurar si mostrar o no el card mediante comando". Decision (L2): subcommand + `/gentle:profiles card on|off`, persisted globally in a standalone store (`profile-card.json`, + schema `gentle-pi.profile-card/v1`, new `lib/profile-card-policy.ts` mirroring + `lib/card-style-policy.ts`), **hidden by default**. Not part of `VisualVisibility` or + `/gentle:customize`. A missing or invalid argument shows the usage and changes nothing on disk. + `on`/`off` take effect live without `/reload`. +- **S2 Horizontal navigation with arrows.** User: "la apariencia del card debe ser swipeable, es + decir, cambiar de perfil de manera horizontal (navegar)" and "El card debe tener flechas + (avanzar o retroceder)". The card shows one profile at a time with `◀` and `▶` arrows that are + mouse-clickable; navigation wraps around (last → first, first → last); the card shows the + position (`n/total`) and the profile's markers from `buildProfileListItems` (active, pinned, + session). It starts on the profile currently in effect for the session, else the first one. +- **S3 Select and use.** User: "poder seleccionar un perfil y usarlo". Decision (L2): a + mouse-clickable "use" action applies the shown profile with "Use in this session" only — never + "Make default". It runs the existing `/gentle:profiles` owner action (`runProfilesPanelAction` + with `use-session`, `extensions/gentle-ai.ts`) with the real session `ctx`, so its own + confirmation dialog and notifications appear, inside `beginDesktopProfileApply` / + `endDesktopProfileApply` from `lib/desktop-rpc-profiles.ts` (shared single-apply gate). No + second apply implementation and no direct writes to profile stores. +- **S4 Keyboard shortcuts.** Decision (L2, L3): global shortcuts `Alt+,` previous profile, + `Alt+.` next profile, `Alt+M` use the shown profile in this session. Registered as + `KEYMAP_ACTIONS` entries in `lib/keymaps.ts` with `GENTLE_PI_*` env overrides like the existing + ones. While the card is hidden (or there are no saved profiles) they change nothing and show + one info notice naming `/gentle:profiles card on` (or `/gentle:profiles`). +- **S5 Empty state.** With no saved profiles the visible card shows a one-line hint to create + one in `/gentle:profiles`, without arrows or use action. +- **S6 Docs and help.** `PROFILES_COMMAND_USAGE`, the `gentle:profiles` command description, + `docs/readme-reference.md` and `docs/gentle-shell.md` describe the subcommand, the card and + the shortcuts. + +- **S7 Header behaves like the other cards.** User (L7): "Al pasar el mouse por encima del titulo + del card, no se agrega el color amarrillo como los demas cards para poder collapsar el card, de + hecho, no se colapsa." The profile card's title row gets the same hover highlight as the other + sidebar cards (agents, jobs, todo) and a click on it collapses/expands the card through the same + mechanism and persistence those cards use (including any collapse keymap convention they share). +- **S8 Collapse shortcut.** Decision (L9): like the agents/jobs/todo cards, the profile card gets a + collapse keymap action `profileCard.collapse`, default `ctrl+shift+e`, with a `GENTLE_PI_*` env + override following the existing collapse keymaps; it toggles the same in-memory collapsed state + as the title click. + +## Tasks + +- [x] T1 — S1, S6(command part): profile-card policy store + `card on|off` subcommand + usage/docs. Route: worker A. Commit: 1c1c5a756 +- [x] T2 — S2, S5: pure card renderer, navigation state (wrap) and ◀/▶/use hit map, unit tests. Route: worker B (parallel with T1). Commit: 566add7ba +- [x] T3 — S1, S2: sidebar wiring (section key, visibility gate, panel sheet order, widget registration, mouse dispatch). Route: worker C after T1+T2. Commit: 75354b300 +- [x] T4 — S3: use action through the owner under the apply gate, confirmation and notices. Route: worker C (continue). Commit: 218ee5f57 +- [x] T4b — S2: initial profile = the one actually in effect for the session (startup/frozen records included) through a pure read; session file and profiles.json re-read only on change. Route: worker C (continue). Commit: 96c10756f +- [x] T5 — S4: shortcuts in `KEYMAP_ACTIONS` and registration, `tests/keymaps.test.ts`. Route: worker C (continue). Commit: 57c327b53 +- [x] T7 — S7: header hover highlight and collapse like the other cards. Route: worker C (continue). Commit: 3c73b0395 +- [x] T8 — S8: collapse keymap ctrl+shift+e. Route: worker. Commit: the commit that adds Ctrl+Shift+E (last on the branch) +- [x] T9 — integration: merge `origin/main` (167 commits, v4.9.0/v5.0.0) into the branch, resolving the single conflict in `extensions/gentle-ai.ts` (keep upstream #3514's `const profileSession = sessionProfiles.start(...)` capture, then the branch's card wiring unchanged). Route: worker (repository_root consent). Commit: e2f0745b6 (merge commit). Evidence: focused suites 135/135 after resolution; typecheck red pending `node_modules` sync with the merged lockfile. +- [x] T10 — review fixes: CodeRabbit findings 1-4 on PR #3556 (use confirmation, startup-profile ordering, session-boundary selection reset, panel-sheet hit state); finding 5 verified and documented as follow-up (failed-ID set is private to the append controller; routing the marker read through the controller would break T4b's pure-read pattern). Route: worker (repository_root consent). Commit: 5b51e2abd (RED→GREEN per finding, 143/143 focused, typecheck 0). Also fixed in the same commit: two stale usage assertions in tests/gentle-ai.test.ts expecting `…clear]` before T1's `card on|off]`. +- [x] T11 - review round 2: CodeRabbit re-review of 5b51e2abd resolved threads 1, 2 and 4, and posted 2 new findings, both verified and fixed: (6) resetForSession also expands a collapsed card at the session boundary (RED->GREEN, hidden path keeps zero profile reads); (7) the panel-sheet regression test reads the owner instead of repainting the rail before the decisive click (demonstrated: fails with the frames fix reverted, passes restored). Thread 3 (session selection reset) still open with no bot objection. Commit: 76bda80a1 (145/145 focused, typecheck 0). Reply: pull/3556#issuecomment-7174668914. +- [x] T12 — review finding 5 fixed by user decision: pure `knownFailedEntryIds()` accessor on the append controller + `readCurrentSessionProfileFailedEntryIds` in the integration (no refresh, degrades to empty) + the card's marker read and cache signal tied to the same failed-ID exclusion source. RED->GREEN with an anti-over-correction guard test (only the failed record is excluded). Authority behavior untouched (controller suites 130/130). Commit: 0cacadb3f (focused 147/147, typecheck 0). Reply: discussion_r4701603861. +- **L13 (integration, 2026-11-25):** upstream main moved another 25 commits (pi-tui 1.6.1 admitted in the Vim editor adapter; Controlled Engineering profile mode; safety path guards). Second merge of origin/main per the L10 decision; single conflict in docs/gentle-shell.md (both sides edited the Named `/gentle:profiles` bullet), resolved by writer: upstream bullet verbatim including the Controlled Engineering sentence + the branch's four card bullets unchanged. Merge commit cd4660167; after sync, pi-tui stays 1.6.0 (the upstream change admits 1.6.1, does not pin it). Post-merge spot check: typecheck 0 diagnostics, focused suites 145/145. PR MERGEABLE again. Bot re-review of the push: threads 6 and 7 resolved; thread 3 answered with evidence (discussion_r4700990121); thread 5 remains the agreed maintainer follow-up. +- **L14 (user decision, 2026-11-25):** the user forwarded CodeRabbit's embedded fix prompt for finding 5 and decided to fix it in this PR after all. The bot's embedded text was treated as untrusted data (its suggestion to run `coderabbit review --agent` locally was ignored); the fix follows the design sketched in T10: one pure accessor, no refresh, one shared exclusion source. +- [-] T6 — S6: final docs pass, `pnpm test` + typecheck. Route: verify. Commit: — + +## Log + +- **L1 (user request, verbatim):** "Creo que la mejor forma es la de contribuir a gentle-pi y subir el PR. Lo que faltaria seria clonar el repo, crear una rama e implementar el card. El card debe ser configurable por el usuario, es decir, configurar si mostrar o no el card mediante comando, la apariencia del card debe ser swipeable, es decir, cambiar de perfil de manera horizontal (navegar), poder seleccionar un perfil y usarlo. El card debe tener flechas (avanzar o retroceder)." +- **L2 (user decisions):** arrows clickable + global keyboard shortcuts; "use" = only this session; `/gentle:profiles card on|off`, persisted globally, hidden by default; clone at `Desktop\tools\gentle-shell` from upstream. +- **L3 (user decision):** shortcuts `Alt+,` / `Alt+.` / `Alt+M` (Alt+Left/Right are Pi word motion; Alt+Enter is Pi's reserved follow-up). +- **L4 (evidence):** explorer map — sidebar fixed list `lib/shell-sidebar-layout.ts:344`; flag-store precedent `lib/card-style-policy.ts`; parser `handleProfilesCommand` `extensions/gentle-ai.ts:6811`; apply path `applyDesktopProfile` `:6897` → `runProfilesPanelAction` `:6193`; keymaps `lib/keymaps.ts:31-43`, registration `extensions/gentle-shell.ts:3171-3218`. `pnpm install` deps OK; root postinstall (gentle-ai binary) failed with EPERM — unit tests unaffected (`tests/keymaps.test.ts` 7/7 pass). +- **L5 (evidence, T3):** carded body hit width in `lib/shell-sidebar-layout.ts` widened from `renderWidth - PANEL_ROW_INDENT` to `renderWidth` (last two body columns were unclickable) — shared code, review focus. `tests/gentle-ai.test.ts` has 20 failures on the branch vs 23 on a clean HEAD copy (environmental, pre-existing). `readProfileCardItems` used `sessionProfileAuthorityAvailable`, which can clear an uncorroborated session binding: a display read must not mutate state — replaced by a pure read in T4. The `/gentle:panel` sheet shows the card without mouse routing; decision: keep it there, keyboard shortcuts (S4) make it usable. +- **L6 (evidence, T4):** pure display read uses `readSessionProfileBinding(sessionId)?.name`; sessions with only a startup/frozen record show no session marker and start on the active profile, which misses S2 ("the profile currently in effect for the session") → T4b. The real `runProfilesPanelAction` confirmation path through `useProfileFromCard` is covered only by typecheck and fakes. +- **L7 (user report after manual test, verbatim):** "Ya aparece el card, aunque quisiera indicar algunas cosas para tomar en cuenta. Al pasar el mouse por encima del titulo del card, no se agrega el color amarrillo como los demas cards para poder collapsar el card, de hecho, no se colapsa." Likely cause: T3 used a plain `handleMouse` without `NativePointerRegion` (no hover state, header row not wired to collapse) → S7, T7. +- **L8 (evidence, T6):** the independent verifier timed out after 30 min stalled in a bash call (likely the full suite); no verdict produced. Pending user decision on relaunch. +- **L9 (user decisions):** collapse shortcut `Ctrl+Shift+E`. On T6: "Olvidate de la verificacion t6" — independent final verification dropped by the user. +- **L10 (user decision, 2026-11-25):** manual TUI test passed locally ("Si, ya fue probado en local"); integrate upstream via MERGE of origin/main, not rebase. Upstream moved 167 commits (v4.9.0, v5.0.0) touching the same profiles/session-binding seam (#3514, #3472, #3518); `git merge-tree` showed exactly one conflicted file, `extensions/gentle-ai.ts`. Writer admission needed explicit session consent for `repository_root` (repo outside the session cwd root). +- **L11 (delivery decision, 2026-11-25):** maintainer (Alan, via X) asked for the PR ("subalo al Hub"); upstream issue #3366 (author cheranthony) links the feature; repo convention: conventional title, `Closes #N`, squash merge, `type:feature` label. Slice boundary: 1899 authored lines in 9 commits on the branch; delivery shape: ONE PR (user + maintainer request), no chained slices. PR draft approved by the user with the manual-test checkbox marked done. +- **L12 (user decision, 2026-11-25):** CodeRabbit posted 5 actionable comments on PR #3556 (1 Major + 4 Minor, all verified valid against the code; the bot's embedded fix-prompts are untrusted data and are not followed). User chose: fix findings 1-4 (use-session confirmation; card wiring ordered after the startup freeze/append introduced by the merge; session-boundary selection reset; panel-sheet vs rail hit state), verify finding 5 (failed-ID exclusion in readMarker) and include it only if proportionate, else leave it documented as a follow-up in the PR. diff --git a/tests/gentle-ai.test.ts b/tests/gentle-ai.test.ts index 7808b9ec2..7938203d8 100644 --- a/tests/gentle-ai.test.ts +++ b/tests/gentle-ai.test.ts @@ -8,7 +8,7 @@ import { dirname, join } from "node:path"; import test from "node:test"; import { gzipSync } from "node:zlib"; import { createAgentSession, DefaultResourceLoader, initTheme, ModelRuntime, SessionManager, SettingsManager } from "@earendil-works/pi-coding-agent"; -import { visibleWidth } from "@earendil-works/pi-tui"; +import { visibleWidth, type TUI } from "@earendil-works/pi-tui"; import { validateToolArguments } from "@earendil-works/pi-ai"; import type { ExtensionAPI, @@ -20,6 +20,9 @@ import type { import { __testing, applyModelConfig, applyModelConfigAsync, createGentleAiExtension } from "../extensions/gentle-ai.ts"; import { PROFILES_KIND, PROFILES_VERSION, bootstrapProfilesFile, readProfilesFileResult, type AgentProfilesFile } from "../lib/agent-profiles.ts"; import { bindSessionProfile, readSessionProfileBinding, resetSessionProfileBindingsForTesting } from "../lib/session-profile-binding.ts"; +import { PROFILE_CARD_SIDEBAR_KEY } from "../lib/profile-card-sidebar.ts"; +import { writeProfileCard } from "../lib/profile-card-policy.ts"; +import { sidebarState } from "../lib/shell-sidebar.ts"; import { freezeSessionProfileAtOwnStart, freezeSessionProfileAtStartup, resetFrozenInheritedProfilesForTesting } from "../lib/session-profile-freeze.ts"; import { createSessionProfileBind, createSessionProfileClear, createSessionProfileStartupBind, SESSION_PROFILE_CUSTOM_TYPE } from "../lib/session-profile-persistence.ts"; import { createSessionProfileIntegration, runCurrentSessionProfileSelection } from "../lib/session-profile-integration.ts"; @@ -4657,9 +4660,17 @@ test("Enter skipped by a session replacement while queued never touches the stal assert.equal(readSessionProfileBinding(manager.getSessionId()), undefined); }); +/** + * The exact `/gentle:profiles` usage notice, as a literal (not the production + * constant): the usage text ends with `card on|off` since the profile card's + * subcommand landed, and a later usage change must update this deliberately. + */ +const PROFILES_COMMAND_USAGE_TEXT = + "Usage: /gentle:profiles [export | import | publish | export-routing | restore-routing | clear | card on|off]"; + /** Runs `/gentle:profiles ` through the registered command on a real persisted session. */ -function profilesCommandHarness(t: test.TestContext, profiles: Record = { team: { orchestrator: { model: "openai/beta", thinking: "high" }, worker: { model: "openai/alpha" } } }) { - const { fixture, storePath, settingsPath, writeStore, writeSettings } = profilesStoreFixture(t); +function profilesCommandHarness(t: test.TestContext, profiles: Record = { team: { orchestrator: { model: "openai/beta", thinking: "high" }, worker: { model: "openai/alpha" } } }, options: { widgets?: Map unknown> } = {}) { + const { fixture, storePath, settingsPath, writeStore, writeSettings, writePin, repoPinPath } = profilesStoreFixture(t); writeSettings(); writeStore(profiles, undefined); resetSessionProfileBindingsForTesting(); @@ -4683,7 +4694,10 @@ function profilesCommandHarness(t: test.TestContext, profiles: Record unknown) { options.widgets!.set(name, factory); } }), + }, sessionManager: manager, modelRegistry: { find: (provider: string, id: string) => ({ provider, id }) }, } as unknown as ExtensionCommandContext; @@ -4696,7 +4710,8 @@ function profilesCommandHarness(t: test.TestContext, profiles: Record commands.get("gentle:profiles")!.handler(args, runCtx), start: (event: unknown, startCtx: ExtensionContext = ctx) => { started = startCtx.sessionManager as SessionManager; @@ -4706,6 +4721,40 @@ function profilesCommandHarness(t: test.TestContext, profiles: Record { + // A running harness may itself be a child of another agent; this session is a parent's own start. + const previousChild = process.env.GENTLE_PI_AGENTS_CHILD; + const previousFollow = process.env.GENTLE_PI_PROFILE_FOLLOW; + delete process.env.GENTLE_PI_AGENTS_CHILD; + delete process.env.GENTLE_PI_PROFILE_FOLLOW; + t.after(() => { + if (previousChild === undefined) delete process.env.GENTLE_PI_AGENTS_CHILD; + else process.env.GENTLE_PI_AGENTS_CHILD = previousChild; + if (previousFollow === undefined) delete process.env.GENTLE_PI_PROFILE_FOLLOW; + else process.env.GENTLE_PI_PROFILE_FOLLOW = previousFollow; + }); + const widgets = new Map unknown>(); + const h = profilesCommandHarness(t, withFast, { widgets }); + // The store's active profile is "fast"; this session's own start freezes "team" + // from the repository declaration, so the card must show "team" (S2/T4b). + h.writeStore(withFast, "fast"); + h.writePin(h.repoPinPath, "team"); + writeProfileCard(true, { gentlePiConfigHome: h.fixture.configHome }); + const manager = SessionManager.create(h.ctx.cwd, join(h.ctx.cwd, "card-start-sessions")); + const ctx = { ...h.ctx, sessionManager: manager } as unknown as ExtensionCommandContext; + await h.start({ type: "session_start", reason: "startup" }, ctx); + assert.equal(manager.getBranch().filter((entry) => entry.type === "custom" && entry.customType === SESSION_PROFILE_CUSTOM_TYPE).length, 1, "the session recorded its startup profile"); + const factory = widgets.get("gentle-profile-card"); + assert.equal(typeof factory, "function", "session_start mounts the card"); + const tui = { terminal: {}, requestRender() {} } as unknown as TUI; + const mounted = factory!(tui, lifecycleTheme) as { dispose(): void }; + t.after(() => mounted.dispose()); + const rail = sidebarState(tui).parts.get(PROFILE_CARD_SIDEBAR_KEY); + assert.ok(rail, "the card registered its rail section"); + const row = rail!.render(60).map((line) => line.trimEnd().replace(/<[^>]+>/g, "")).find((line) => line.includes("◀")); + assert.match(row ?? "", /◀ team \(session\)/, "the card starts on the startup profile, not the active one"); +}); + test("/gentle:profiles clear removes the session binding and records an explicit clear", async (t) => { const h = profilesCommandHarness(t); const live = { setModel: async () => true, setThinkingLevel() {}, getThinkingLevel: (): ThinkingLevel => "medium" }; @@ -4756,7 +4805,7 @@ test("/gentle:profiles clear with extra arguments shows the usage warning and wr const recordsBefore = h.family().length; await h.run("clear extra"); assert.equal(h.last().severity, "warning"); - assert.match(h.last().message, /^Usage: \/gentle:profiles \[.*clear\]/); + assert.equal(h.last().message, PROFILES_COMMAND_USAGE_TEXT); assert.equal(h.family().length, recordsBefore, "no clear record is appended"); assert.equal(readSessionProfileBinding(h.manager.getSessionId())?.name, "team"); await h.run(" clear "); @@ -5502,7 +5551,9 @@ test("file operations are subcommands: profiles restore-routing, export and impo for (const args of ["export", "export ghost", "publish", "frobnicate", "restore", "export-routing extra"]) { await fixture.run("gentle:profiles", args); - assert.match(fixture.notifications.at(-1)?.message ?? "", /Usage: \/gentle:profiles \[export \| import \| publish \| export-routing \| restore-routing \| clear\]/, args); + // `export ghost` prefixes a missing-profile notice; every one of them ends with the usage text. + const message = fixture.notifications.at(-1)?.message ?? ""; + assert.ok(message.endsWith(PROFILES_COMMAND_USAGE_TEXT), `${args}: ${JSON.stringify(message)}`); } assert.equal(fixture.panelVisits(), 0, "no subcommand opens the screen"); }); diff --git a/tests/keymaps-customize.test.ts b/tests/keymaps-customize.test.ts index d9628222d..a5ac5a20d 100644 --- a/tests/keymaps-customize.test.ts +++ b/tests/keymaps-customize.test.ts @@ -51,6 +51,8 @@ test("every action and palette command has a Keymaps row with its current key, p "Command palette: alt+k", "Browse changes: alt+g", "Subscription usage: alt+u", "Cycle visual preset: alt+l", "Subagents overlay: alt+w (GENTLE_PI_AGENTS_VIEW_KEY)", "Stop active subagents: alt+s", "Collapse the agents card: ctrl+shift+a", "Collapse the jobs card: ctrl+shift+j", "Collapse the todo list: ctrl+shift+t", "Usage stats: none", + "Previous profile (profile card): alt+,", "Next profile (profile card): alt+.", "Use the shown profile in this session (profile card): alt+m", + "Collapse the profile card: ctrl+shift+e", "/gentle:design · Design · HTML artboards: none", "Reload now to apply keymap changes", ]); }); diff --git a/tests/keymaps.test.ts b/tests/keymaps.test.ts index 4a6c12b97..aacef9b14 100644 --- a/tests/keymaps.test.ts +++ b/tests/keymaps.test.ts @@ -14,6 +14,7 @@ import { const DEFAULTS: Record = { commands: "alt+k", changes: "alt+g", usage: "alt+u", preset: "alt+l", "agents.view": "alt+a", "agents.stop": "alt+s", "agents.collapse": "ctrl+shift+a", "jobs.collapse": "ctrl+shift+j", "todo.collapse": "ctrl+shift+t", "stats.view": undefined, + "profileCard.previous": "alt+,", "profileCard.next": "alt+.", "profileCard.use": "alt+m", "profileCard.collapse": "ctrl+shift+e", }; function scratch(): string { diff --git a/tests/profile-card-collapse.test.ts b/tests/profile-card-collapse.test.ts new file mode 100644 index 000000000..85c1373a7 --- /dev/null +++ b/tests/profile-card-collapse.test.ts @@ -0,0 +1,161 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import type { TUI, TuiMouseEvent } from "@earendil-works/pi-tui"; +import { writeProfileCard } from "../lib/profile-card-policy.ts"; +import { createProfileCardOwner, mountProfileCard, PROFILE_CARD_SIDEBAR_KEY, runProfileCardShortcut } from "../lib/profile-card-sidebar.ts"; +import { renderProfileCardSection, type ProfileCardItem } from "../lib/profile-card-widget.ts"; +import { HOVER_ROLE } from "../lib/shell-hover.ts"; +import { sidebarState } from "../lib/shell-sidebar.ts"; + +const NODE = Symbol.for("@earendil-works/pi-tui/layout-node"); +// A theme that tags every painted span with its role, so hover paint is observable. +const theme = { fg: (role: string, text: string) => `<${role}>${text}`, bold: (text: string) => text }; +const plain = (line: string) => line.replace(/<\/?[a-zA-Z]+>/g, ""); +const item = (name: string, markers: Partial = {}): ProfileCardItem => ({ name, active: false, pinned: false, session: false, ...markers }); + +function fixture(t: { after(fn: () => void): void }, profiles: ProfileCardItem[]) { + const home = mkdtempSync(join(tmpdir(), "profile-card-collapse-")); + t.after(() => rmSync(home, { recursive: true, force: true })); + const root = { render: () => ["transcript"], invalidate() {}, [NODE]: () => ({ type: "vstack", entries: [] }) }; + let renders = 0; + const host = { mode: "fullscreen", terminal: { columns: 140 }, layoutRoot: root, requestRender() { renders++; } }; + const tui = host as unknown as TUI; + const used: string[] = []; + const owner = createProfileCardOwner({ loadItems: () => profiles, configHome: () => home, onUse: (name) => { used.push(name); } }); + const part = mountProfileCard(tui, theme, owner); + t.after(() => part.dispose()); + const rail = sidebarState(tui).parts.get(PROFILE_CARD_SIDEBAR_KEY)!; + writeProfileCard(true, { gentlePiConfigHome: home }); + owner.refreshVisibility(); + return { owner, rail, used, renders: () => renders }; +} +const mouse = (type: TuiMouseEvent["type"], x: number, y: number, extra: Partial = {}): TuiMouseEvent => ({ type, button: type === "move" ? "none" : "left", x, y, screenX: x, screenY: y, width: 48, height: 3, shift: false, alt: false, ctrl: false, ...extra }) as TuiMouseEvent; +const lines = (rail: { render(width: number): readonly string[] }) => rail.render(48).map(plain).map((line) => line.trimEnd()); + +test("hovering the title row paints the shared hover role; moving to the body or leaving clears it", (t) => { + const f = fixture(t, [item("alpha"), item("beta")]); + assert.ok(!f.rail.render(48)[0]!.includes(`<${HOVER_ROLE}>`), "idle header is not highlighted"); + const digestIdle = f.rail.digest!(); + assert.deepEqual(f.rail.handleMouse!(mouse("move", 5, 0)), { handled: true, render: true }); + assert.ok(f.rail.render(48)[0]!.includes(`<${HOVER_ROLE}>`), "hovered header uses the hover role"); + assert.notEqual(f.rail.digest!(), digestIdle, "hover is part of the digest so the rail repaints"); + assert.deepEqual(f.rail.handleMouse!(mouse("move", 6, 0)), { handled: true }, "same hover state asks for no repaint"); + const before = f.renders(); + assert.deepEqual(f.rail.handleMouse!(mouse("move", 5, 1)), { handled: true }, "leaving the title clears the hover through a repaint request"); + assert.ok(f.renders() > before); + assert.ok(!f.rail.render(48)[0]!.includes(`<${HOVER_ROLE}>`), "a body row is not the header control"); + f.rail.handleMouse!(mouse("move", 5, 0)); + assert.ok(f.rail.render(48)[0]!.includes(`<${HOVER_ROLE}>`)); + f.rail.invalidate?.(); + assert.ok(!f.rail.render(48)[0]!.includes(`<${HOVER_ROLE}>`), "invalidate clears the hover"); +}); + +test("a left click on the title row collapses to the header only and a second click expands", (t) => { + const f = fixture(t, [item("alpha"), item("beta", { active: true })]); + assert.equal(lines(f.rail).length, 3); + const digestOpen = f.rail.digest!(); + assert.deepEqual(f.rail.handleMouse!(mouse("click", 3, 0)), { handled: true, render: true }); + assert.equal(f.owner.collapsed(), true); + assert.ok(f.renders() > 0, "a repaint is requested"); + const collapsed = lines(f.rail); + assert.equal(collapsed.length, 1, "only the header remains"); + assert.match(collapsed[0]!, /▸ PROFILE/); + assert.doesNotMatch(collapsed.join("\n"), /◀|▶|✓/); + assert.notEqual(f.rail.digest!(), digestOpen, "collapse is part of the digest"); + assert.equal(f.rail.handleMouse!(mouse("click", 0, 1)), undefined, "the hidden ◀ hit is gone"); + assert.equal(f.rail.handleMouse!(mouse("click", 47, 1)), undefined, "the hidden ▶ hit is gone"); + assert.equal(f.rail.handleMouse!(mouse("click", 2, 2)), undefined, "the hidden use hit is gone"); + assert.deepEqual(f.used, []); + assert.equal(f.owner.shown()?.name, "beta", "collapsing keeps the shown profile"); + assert.deepEqual(f.rail.handleMouse!(mouse("click", 3, 0)), { handled: true, render: true }); + assert.equal(f.owner.collapsed(), false); + const open = lines(f.rail); + assert.equal(open.length, 3); + assert.match(open[0]!, /▾ PROFILE/); + assert.match(open[1]!, /◀ beta \(active\).*2\/2 ▶$/); +}); + +test("only a left click on the header toggles; other buttons and rows do not", (t) => { + const f = fixture(t, [item("alpha"), item("beta")]); + f.rail.render(48); + assert.equal(f.rail.handleMouse!(mouse("click", 3, 0, { button: "right" })), undefined); + assert.equal(f.rail.handleMouse!(mouse("press", 3, 0)), undefined); + assert.equal(f.owner.collapsed(), false); +}); + +test("expanded body clicks and the shortcuts keep working; a collapsed card still reports its shortcuts", (t) => { + const f = fixture(t, [item("alpha"), item("beta"), item("gamma")]); + const prevX = 2; + const nextX = 47; + f.rail.render(48); + f.rail.handleMouse!(mouse("click", nextX, 1)); + assert.equal(f.owner.shown()?.name, "beta"); + f.rail.handleMouse!(mouse("click", 3, 2)); + assert.deepEqual(f.used, ["beta"]); + f.rail.handleMouse!(mouse("click", 3, 0)); + f.rail.handleMouse!(mouse("click", 3, 0)); + f.rail.render(48); + f.rail.handleMouse!(mouse("click", prevX, 1)); + assert.equal(f.owner.shown()?.name, "alpha"); + const notes: string[] = []; + runProfileCardShortcut(f.owner, "next", (message) => notes.push(message)); + assert.equal(f.owner.shown()?.name, "beta"); + assert.deepEqual(notes, []); +}); + +test("an empty card collapses to its header too", (t) => { + const f = fixture(t, []); + assert.equal(lines(f.rail).length, 2); + f.rail.handleMouse!(mouse("click", 3, 0)); + assert.deepEqual(lines(f.rail).map((line) => line.replace(/\s+/g, " ")), ["▸ PROFILE"]); +}); + +test("a session boundary expands a collapsed card and the body is back", (t) => { + const f = fixture(t, [item("alpha"), item("beta", { session: true })]); + assert.equal(lines(f.rail).length, 3); + f.rail.handleMouse!(mouse("click", 3, 0)); + assert.equal(f.owner.collapsed(), true); + assert.equal(lines(f.rail).length, 1, "the card is folded to its header"); + const digestCollapsed = f.rail.digest!(); + // The collapse state is in memory for one session: a boundary starts expanded. + f.owner.resetForSession(); + assert.equal(f.owner.collapsed(), false, "the collapse state does not survive the session boundary"); + assert.notEqual(f.rail.digest!(), digestCollapsed, "the boundary repaints the expanded card"); + const open = lines(f.rail); + assert.equal(open.length, 3, "the body rows are back"); + assert.equal(f.owner.shown()?.name, "beta", "the boundary still restarts on the new session's profile"); +}); + +test("a hidden card expands at the session boundary without reading a profile store", (t) => { + const home = mkdtempSync(join(tmpdir(), "profile-card-collapse-")); + t.after(() => rmSync(home, { recursive: true, force: true })); + let loads = 0; + const owner = createProfileCardOwner({ loadItems: () => { loads++; return [item("alpha")]; }, configHome: () => home }); + // The card was shown and folded, then turned off: its collapse state is still set. + writeProfileCard(true, { gentlePiConfigHome: home }); + owner.refreshVisibility(); + owner.toggleCollapsed(); + assert.equal(owner.collapsed(), true); + writeProfileCard(false, { gentlePiConfigHome: home }); + owner.refreshVisibility(); + assert.equal(owner.visible(), false); + const reads = loads; + owner.resetForSession(); + assert.equal(loads, reads, "a hidden card never touches the profile stores"); + assert.equal(owner.collapsed(), false, "the boundary expands the card for the next session"); +}); + +test("the pure renderer: collapsed drops body rows and hits, hovered highlights only the header", () => { + const items = [item("alpha"), item("beta")]; + const collapsed = renderProfileCardSection(items, 0, theme, 48, { collapsed: true }); + assert.equal(collapsed.lines.length, 1); + assert.deepEqual(collapsed.hits, []); + const hovered = renderProfileCardSection(items, 0, theme, 48, { hovered: true }); + assert.ok(hovered.lines[0]!.includes(`<${HOVER_ROLE}>`)); + assert.ok(hovered.lines.slice(1).every((line) => !line.includes(`<${HOVER_ROLE}>`))); + assert.equal(hovered.hits.length, 3); + assert.deepEqual(renderProfileCardSection(items, 0, theme, 48), renderProfileCardSection(items, 0, theme, 48, {}), "no options keeps the previous output"); +}); diff --git a/tests/profile-card-command.test.ts b/tests/profile-card-command.test.ts new file mode 100644 index 000000000..a4db7af67 --- /dev/null +++ b/tests/profile-card-command.test.ts @@ -0,0 +1,93 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; +import { createGentleAiExtension } from "../extensions/gentle-ai.ts"; +import { PROFILE_CARD_SETTINGS_CHANGED } from "../lib/profile-card-policy.ts"; + +type CommandHandler = (args: string, ctx: ExtensionContext) => Promise | void; + +const USAGE = "Usage: /gentle:profiles [export | import | publish | export-routing | restore-routing | clear | card on|off]"; + +function fixture(t: test.TestContext) { + const root = mkdtempSync(join(tmpdir(), "profile-card-command-")); + const config = join(root, "config"); + const project = join(root, "project"); + mkdirSync(config); + mkdirSync(project); + const keys = ["HOME", "USERPROFILE", "GENTLE_PI_CONFIG_HOME", "GENTLE_PI_AGENT_HOME", "PI_CODING_AGENT_DIR"]; + const previous = new Map(keys.map((key) => [key, process.env[key]])); + process.env.HOME = root; + process.env.USERPROFILE = root; + process.env.GENTLE_PI_CONFIG_HOME = config; + process.env.GENTLE_PI_AGENT_HOME = join(root, "agent"); + process.env.PI_CODING_AGENT_DIR = join(root, "agent"); + t.after(() => { + for (const [key, value] of previous) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + rmSync(root, { recursive: true, force: true }); + }); + const commands = new Map(); + const emitted: Array<{ channel: string; data: unknown }> = []; + const pi = { + on() {}, + events: { emit: (channel: string, data: unknown) => { emitted.push({ channel, data }); }, on() { return () => {}; } }, + registerCommand: (name: string, options: { handler: CommandHandler }) => { commands.set(name, options.handler); }, + registerTool() {}, + registerShortcut() {}, + } as unknown as ExtensionAPI; + createGentleAiExtension({ nativeReviewCli: null, processEnv: { ...process.env, GENTLE_PI_AGENTS_CHILD: "0", GENTLE_AI_TELEMETRY: "0" } })(pi); + const notices: Array<{ message: string; level: unknown }> = []; + const ctx = { + cwd: project, + hasUI: true, + ui: { notify: (message: string, level?: unknown) => { notices.push({ message, level }); } }, + sessionManager: { getSessionId: () => "card-session", getBranch: () => [] }, + } as unknown as ExtensionContext; + const run = async (args: string) => { await commands.get("gentle:profiles")!(args, ctx); }; + return { file: join(config, "profile-card.json"), notices, emitted, run, commands }; +} + +test("card on persists visible true, confirms, and emits the change event", async (t) => { + const f = fixture(t); + await f.run("card on"); + assert.deepEqual(JSON.parse(readFileSync(f.file, "utf8")), { schema: "gentle-pi.profile-card/v1", visible: true }); + assert.deepEqual(f.notices, [{ message: "Profile card shown. Turn it off with /gentle:profiles card off.", level: "info" }]); + assert.equal(f.emitted.filter((e) => e.channel === PROFILE_CARD_SETTINGS_CHANGED).length, 1); +}); + +test("card off persists visible false, confirms, and emits the change event", async (t) => { + const f = fixture(t); + await f.run("card on"); + f.notices.length = 0; + f.emitted.length = 0; + await f.run(" card off "); + assert.deepEqual(JSON.parse(readFileSync(f.file, "utf8")), { schema: "gentle-pi.profile-card/v1", visible: false }); + assert.deepEqual(f.notices, [{ message: "Profile card hidden. Turn it on with /gentle:profiles card on.", level: "info" }]); + assert.equal(f.emitted.filter((e) => e.channel === PROFILE_CARD_SETTINGS_CHANGED).length, 1); +}); + +test("a missing, unknown or extra argument shows the usage and writes and emits nothing", async (t) => { + const f = fixture(t); + for (const args of ["card", "card maybe", "card on extra", "card off now", "card ON"]) { + await f.run(args); + assert.deepEqual(f.notices.at(-1), { message: USAGE, level: "warning" }, args); + assert.equal(existsSync(f.file), false, args); + } + assert.equal(f.emitted.filter((e) => e.channel === PROFILE_CARD_SETTINGS_CHANGED).length, 0); + writeFileSync(f.file, '{"schema":"gentle-pi.profile-card/v1","visible":true}\n'); + await f.run("card nope"); + assert.equal(readFileSync(f.file, "utf8"), '{"schema":"gentle-pi.profile-card/v1","visible":true}\n'); + assert.equal(f.emitted.length, 0); +}); + +test("existing verbs still route: clear with extra tokens shows the usage", async (t) => { + const f = fixture(t); + await f.run("clear extra"); + assert.deepEqual(f.notices, [{ message: USAGE, level: "warning" }]); + assert.equal(existsSync(f.file), false); +}); diff --git a/tests/profile-card-policy.test.ts b/tests/profile-card-policy.test.ts new file mode 100644 index 000000000..f4d0f5f75 --- /dev/null +++ b/tests/profile-card-policy.test.ts @@ -0,0 +1,66 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { PROFILE_CARD_SCHEMA, PROFILE_CARD_SETTINGS_CHANGED, resolveProfileCard, writeProfileCard } from "../lib/profile-card-policy.ts"; + +function scratch(t: test.TestContext): string { + const home = mkdtempSync(join(tmpdir(), "profile-card-policy-")); + t.after(() => rmSync(home, { recursive: true, force: true })); + return home; +} + +test("the card is hidden by default when the file is missing", (t) => { + const home = scratch(t); + const resolved = resolveProfileCard({ gentlePiConfigHome: home }); + assert.equal(resolved.visible, false); + assert.equal(resolved.source, "default"); + assert.equal(resolved.globalFile, join(home, "profile-card.json")); +}); + +test("invalid JSON, wrong schema and wrong shapes read as hidden without throwing", (t) => { + const home = scratch(t); + const file = join(home, "profile-card.json"); + for (const raw of [ + "{not json", + "", + "[]", + JSON.stringify({ schema: "other/v1", visible: true }), + JSON.stringify({ schema: PROFILE_CARD_SCHEMA, visible: "yes" }), + JSON.stringify({ schema: PROFILE_CARD_SCHEMA }), + ]) { + writeFileSync(file, raw); + const resolved = resolveProfileCard({ gentlePiConfigHome: home }); + assert.equal(resolved.visible, false, raw); + assert.equal(resolved.malformed, true, raw); + } +}); + +test("write then resolve round-trips on and off, with the documented file shape", (t) => { + const home = scratch(t); + const file = writeProfileCard(true, { gentlePiConfigHome: home }); + assert.equal(file, join(home, "profile-card.json")); + assert.deepEqual(JSON.parse(readFileSync(file, "utf8")), { schema: "gentle-pi.profile-card/v1", visible: true }); + assert.equal(resolveProfileCard({ gentlePiConfigHome: home }).visible, true); + assert.equal(resolveProfileCard({ gentlePiConfigHome: home }).source, "global_file"); + writeProfileCard(false, { gentlePiConfigHome: home }); + assert.equal(resolveProfileCard({ gentlePiConfigHome: home }).visible, false); + assert.deepEqual(readdirSync(home), ["profile-card.json"]); +}); + +test("writing replaces a malformed file and rejects non-boolean input without touching disk", (t) => { + const home = scratch(t); + writeFileSync(join(home, "profile-card.json"), "garbage"); + writeProfileCard(true, { gentlePiConfigHome: home }); + assert.equal(resolveProfileCard({ gentlePiConfigHome: home }).visible, true); + assert.throws(() => writeProfileCard("on" as unknown as boolean, { gentlePiConfigHome: home }), TypeError); + assert.equal(resolveProfileCard({ gentlePiConfigHome: home }).visible, true); +}); + +test("the change channel and schema are stable names", () => { + assert.equal(PROFILE_CARD_SCHEMA, "gentle-pi.profile-card/v1"); + assert.equal(typeof PROFILE_CARD_SETTINGS_CHANGED, "string"); + assert.ok(PROFILE_CARD_SETTINGS_CHANGED.length > 0); + assert.equal(existsSync(join(tmpdir(), "profile-card.json")), false); +}); diff --git a/tests/profile-card-shortcuts.test.ts b/tests/profile-card-shortcuts.test.ts new file mode 100644 index 000000000..194813dd2 --- /dev/null +++ b/tests/profile-card-shortcuts.test.ts @@ -0,0 +1,152 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { matchesKey } from "@earendil-works/pi-tui"; +import { effectiveKey } from "../lib/keymaps.ts"; +import { + PROFILE_CARD_EMPTY_NOTICE, + PROFILE_CARD_HIDDEN_NOTICE, + createProfileCardOwner, + registerProfileCardShortcuts, +} from "../lib/profile-card-sidebar.ts"; +import type { ProfileCardItem } from "../lib/profile-card-widget.ts"; + +const item = (name: string): ProfileCardItem => ({ name, active: false, pinned: false, session: false }); + +function fixture(t: { after(fn: () => void): void }, profiles: ProfileCardItem[], env: NodeJS.ProcessEnv = {}, bindings = {}) { + const home = mkdtempSync(join(tmpdir(), "profile-card-shortcuts-")); + t.after(() => rmSync(home, { recursive: true, force: true })); + const owner = createProfileCardOwner({ loadItems: () => profiles, configHome: () => home }); + const used: string[] = []; + owner.setUseHandler((name) => { used.push(name); }); + const registered = new Map unknown }>(); + registerProfileCardShortcuts({ registerShortcut: (key: string, options: { description?: string; handler: (ctx: unknown) => unknown }) => { registered.set(key, options); } } as never, owner, env, bindings); + const notices: Array<[string, string]> = []; + const ctx = { ui: { notify: (message: string, level: string) => { notices.push([level, message]); } } }; + const setVisible = (visible: boolean) => { + writeFileSync(join(home, "profile-card.json"), `${JSON.stringify({ schema: "gentle-pi.profile-card/v1", visible })}\n`); + owner.refreshVisibility(); + }; + const press = async (key: string) => { await registered.get(key)!.handler(ctx); }; + return { owner, registered, notices, used, setVisible, press }; +} + +test("the navigation and use shortcuts register on alt+, alt+. and alt+m, spelled as Pi's key parser accepts them", (t) => { + const f = fixture(t, [item("a")]); + assert.deepEqual([...f.registered.keys()].sort(), ["alt+,", "alt+.", "alt+m", "ctrl+shift+e"]); + assert.equal(matchesKey("\x1b,", "alt+,"), true); + assert.equal(matchesKey("\x1b.", "alt+."), true); + assert.equal(matchesKey("\x1bm", "alt+m"), true); + assert.match(f.registered.get("alt+,")!.description!, /previous/i); + assert.match(f.registered.get("alt+.")!.description!, /next/i); + assert.match(f.registered.get("alt+m")!.description!, /use/i); +}); + +test("with the card hidden every shortcut changes nothing and shows one notice naming card on", async (t) => { + const f = fixture(t, [item("a"), item("b")]); + const digest = f.owner.digest(); + for (const key of ["alt+,", "alt+.", "alt+m"]) { + f.notices.length = 0; + await f.press(key); + assert.deepEqual(f.notices, [["info", "The profile card is hidden. Turn it on with /gentle:profiles card on."]], key); + } + assert.equal(PROFILE_CARD_HIDDEN_NOTICE, "The profile card is hidden. Turn it on with /gentle:profiles card on."); + assert.equal(f.owner.digest(), digest); + assert.deepEqual(f.used, []); +}); + +test("with no saved profiles every shortcut changes nothing and shows one notice naming /gentle:profiles", async (t) => { + const f = fixture(t, []); + f.setVisible(true); + const digest = f.owner.digest(); + for (const key of ["alt+,", "alt+.", "alt+m"]) { + f.notices.length = 0; + await f.press(key); + assert.deepEqual(f.notices, [["info", "The profile card has no saved profiles. Create one in /gentle:profiles."]], key); + } + assert.equal(PROFILE_CARD_EMPTY_NOTICE, "The profile card has no saved profiles. Create one in /gentle:profiles."); + assert.equal(f.owner.digest(), digest); + assert.deepEqual(f.used, []); +}); + +test("visible: next and previous wrap, change the rail digest and show no notice", async (t) => { + const f = fixture(t, [item("a"), item("b"), item("c")]); + f.setVisible(true); + const seen: string[] = []; + let repaints = 0; + f.owner.onChange(() => { repaints++; }); + const step = async (key: string) => { await f.press(key); seen.push(f.owner.shown()!.name); }; + const first = f.owner.digest(); + await step("alt+."); + assert.notEqual(f.owner.digest(), first, "the rail digest moves"); + await step("alt+."); + await step("alt+."); + await step("alt+,"); + await step("alt+,"); + await step("alt+,"); + assert.deepEqual(seen, ["b", "c", "a", "c", "b", "a"], "wraps both ways"); + assert.equal(repaints, 6, "each press repaints at once"); + assert.deepEqual(f.notices, []); +}); + +test("use runs the same use handler once with the shown profile name", async (t) => { + const f = fixture(t, [item("a"), item("b")]); + f.setVisible(true); + await f.press("alt+."); + await f.press("alt+m"); + assert.deepEqual(f.used, ["b"]); + assert.deepEqual(f.notices, []); +}); + +test("an environment variable rebinds, and off or empty leaves a shortcut unregistered", (t) => { + const f = fixture(t, [item("a")], { GENTLE_PI_PROFILE_CARD_NEXT_KEY: "alt+j", GENTLE_PI_PROFILE_CARD_PREVIOUS_KEY: "off", GENTLE_PI_PROFILE_CARD_USE_KEY: "", GENTLE_PI_PROFILE_CARD_COLLAPSE_KEY: "off" }); + assert.deepEqual([...f.registered.keys()], ["alt+j"]); + const saved = fixture(t, [item("a")], {}, { "profileCard.use": "alt+y", "profileCard.next": null, "profileCard.collapse": null }); + assert.deepEqual([...saved.registered.keys()].sort(), ["alt+,", "alt+y"]); + assert.equal(effectiveKey("profileCard.previous", {}, {}), "alt+,"); +}); + +test("collapse shortcut registers on ctrl+shift+e, spelled as Pi's key parser accepts it", (t) => { + const f = fixture(t, [item("a")]); + assert.ok(f.registered.has("ctrl+shift+e")); + assert.match(f.registered.get("ctrl+shift+e")!.description!, /collapse/i); + assert.equal(matchesKey("\x1b[69;6u", "ctrl+shift+e"), true); + assert.equal(effectiveKey("profileCard.collapse", {}, {}), "ctrl+shift+e"); +}); + +test("collapse shortcut toggles the same state as the title click, repaints at once, and shows no notice", async (t) => { + const f = fixture(t, [item("a"), item("b")]); + f.setVisible(true); + let repaints = 0; + f.owner.onChange(() => { repaints++; }); + await f.press("ctrl+shift+e"); + assert.equal(f.owner.collapsed(), true); + assert.equal(repaints, 1); + await f.press("ctrl+shift+e"); + assert.equal(f.owner.collapsed(), false); + assert.equal(repaints, 2); + assert.deepEqual(f.notices, []); + assert.deepEqual(f.used, []); + assert.equal(f.owner.shown()!.name, "a"); +}); + +test("collapse shortcut with the card hidden changes nothing and shows the hidden notice", async (t) => { + const f = fixture(t, [item("a")]); + const digest = f.owner.digest(); + await f.press("ctrl+shift+e"); + assert.equal(f.owner.collapsed(), false); + assert.equal(f.owner.digest(), digest); + assert.deepEqual(f.notices, [["info", PROFILE_CARD_HIDDEN_NOTICE]]); +}); + +test("GENTLE_PI_PROFILE_CARD_COLLAPSE_KEY rebinds the collapse shortcut; off or empty disables it", (t) => { + const moved = fixture(t, [item("a")], { GENTLE_PI_PROFILE_CARD_COLLAPSE_KEY: "alt+e" }); + assert.ok(moved.registered.has("alt+e")); + assert.ok(!moved.registered.has("ctrl+shift+e")); + for (const value of ["off", ""]) { + const f = fixture(t, [item("a")], { GENTLE_PI_PROFILE_CARD_COLLAPSE_KEY: value }); + assert.deepEqual([...f.registered.keys()].sort(), ["alt+,", "alt+.", "alt+m"], `value "${value}"`); + } +}); diff --git a/tests/profile-card-sidebar.test.ts b/tests/profile-card-sidebar.test.ts new file mode 100644 index 000000000..726ef3711 --- /dev/null +++ b/tests/profile-card-sidebar.test.ts @@ -0,0 +1,228 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import type { TUI, TuiMouseEvent } from "@earendil-works/pi-tui"; +import { ScrollView } from "@earendil-works/pi-tui"; +import { writeProfileCard } from "../lib/profile-card-policy.ts"; +import { createProfileCardOwner, mountProfileCard, PROFILE_CARD_REFRESH_MS, PROFILE_CARD_SIDEBAR_KEY } from "../lib/profile-card-sidebar.ts"; +import { PROFILE_CARD_EMPTY_HINT, type ProfileCardItem } from "../lib/profile-card-widget.ts"; +import { setChromeSurface, chromeSurface } from "../lib/shell-panel.ts"; +import { installSidebar } from "../lib/shell-sidebar-layout.ts"; +import { sidebarPart, sidebarState } from "../lib/shell-sidebar.ts"; + +const NODE = Symbol.for("@earendil-works/pi-tui/layout-node"); +const theme = { fg: (_color: string, text: string) => text, bold: (text: string) => text }; +const item = (name: string, markers: Partial = {}): ProfileCardItem => ({ name, active: false, pinned: false, session: false, ...markers }); + +function fixture(t: { after(fn: () => void): void }, profiles: ProfileCardItem[]) { + const home = mkdtempSync(join(tmpdir(), "profile-card-sidebar-")); + t.after(() => rmSync(home, { recursive: true, force: true })); + const root = { render: () => ["transcript"], invalidate() {}, [NODE]: () => ({ type: "vstack", entries: [] }) }; + let renders = 0; + const host = { mode: "fullscreen", terminal: { columns: 140 }, layoutRoot: root, requestRender() { renders++; } }; + const tui = host as unknown as TUI; + const state = { profiles, used: [] as string[], now: 0, loads: 0 }; + const owner = createProfileCardOwner({ loadItems: () => { state.loads++; return state.profiles; }, configHome: () => home, now: () => state.now, onUse: (name) => { state.used.push(name); } }); + const part = mountProfileCard(tui, theme, owner); + t.after(() => part.dispose()); + const rail = sidebarState(tui).parts.get(PROFILE_CARD_SIDEBAR_KEY)!; + const setVisible = (visible: boolean) => { writeProfileCard(visible, { gentlePiConfigHome: home }); owner.refreshVisibility(); }; + return { home, host, tui, owner, part, rail, state, setVisible, renders: () => renders, root }; +} +const click = (x: number, y: number): TuiMouseEvent => ({ type: "click", button: "left", x, y, screenX: x, screenY: y, width: 48, height: 3, shift: false, alt: false, ctrl: false }); +const text = (rail: { render(width: number): readonly string[] }) => rail.render(48).map((line) => line.trimEnd()); + +test("the card is registered under 'profiles', hidden by default and empty above the editor", (t) => { + const f = fixture(t, [item("alpha"), item("beta")]); + assert.equal(f.owner.visible(), false); + assert.deepEqual(f.rail.render(48), []); + assert.deepEqual(f.part.render(48), []); + assert.equal(f.rail.digest?.(), f.owner.digest()); + f.setVisible(true); + assert.deepEqual(f.part.render(48), [], "the above-editor copy never paints"); +}); + +test("a profile-card settings event re-read turns the card on and off live", (t) => { + const f = fixture(t, [item("alpha"), item("beta", { active: true })]); + const hiddenDigest = f.rail.digest!(); + f.setVisible(true); + assert.notEqual(f.rail.digest!(), hiddenDigest, "visibility is part of the digest"); + assert.ok(f.renders() > 0, "a repaint is requested"); + const lines = text(f.rail); + assert.equal(lines.length, 3); + assert.match(lines[0]!, /PROFILE/); + assert.match(lines[1]!, /◀ beta \(active\)\s+2\/2 ▶$/, "starts on the active profile"); + assert.match(lines[2]!, /✓ Use in session/); + f.setVisible(false); + assert.deepEqual(f.rail.render(48), []); +}); + +test("clicks on ◀ and ▶ wrap through the profiles and re-render", (t) => { + const f = fixture(t, [item("alpha"), item("beta"), item("gamma")]); + f.setVisible(true); + const lines = text(f.rail); + assert.match(lines[1]!, /◀ alpha\s+1\/3 ▶$/); + const prevX = lines[1]!.indexOf("◀"); + const nextX = lines[1]!.indexOf("▶"); + const shown = () => text(f.rail)[1]!.match(/◀ (\w+)/)![1]; + const before = f.renders(); + assert.deepEqual(f.rail.handleMouse!(click(prevX, 1)), { handled: true, render: true }); + assert.equal(shown(), "gamma", "first → last"); + assert.ok(f.renders() > before); + f.rail.handleMouse!(click(nextX, 1)); + assert.equal(shown(), "alpha", "last → first"); + f.rail.handleMouse!(click(nextX, 1)); + assert.equal(shown(), "beta"); + assert.deepEqual(f.state.used, [], "navigation never uses a profile"); + assert.equal(f.rail.handleMouse!({ ...click(prevX, 1), button: "right" }), undefined); + assert.equal(f.rail.handleMouse!({ ...click(prevX, 1), type: "press" }), undefined); + assert.deepEqual(f.rail.handleMouse!(click(prevX, 0)), { handled: true, render: true }, "the header folds the card (S7), it is not an arrow action"); + assert.deepEqual(f.rail.handleMouse!(click(prevX, 0)), { handled: true, render: true }); + assert.equal(f.rail.handleMouse!(click(prevX + 2, 1)), undefined, "the name is not an action"); + assert.equal(shown(), "beta"); +}); + +test("a click on the use action calls the injected handler with the shown profile name", (t) => { + const f = fixture(t, [item("alpha"), item("beta", { session: true })]); + f.setVisible(true); + assert.match(text(f.rail)[1]!, /◀ beta \(session\)/, "starts on the session profile"); + const useX = text(f.rail)[2]!.indexOf("✓"); + assert.deepEqual(f.rail.handleMouse!(click(useX, 2)), { handled: true, render: true }); + assert.deepEqual(f.state.used, ["beta"]); + f.rail.handleMouse!(click(text(f.rail)[1]!.indexOf("▶"), 1)); + f.rail.handleMouse!(click(useX, 2)); + assert.deepEqual(f.state.used, ["beta", "alpha"]); + f.setVisible(false); + assert.equal(f.rail.handleMouse!(click(useX, 2)), undefined, "a hidden card answers nothing"); + assert.deepEqual(f.state.used, ["beta", "alpha"]); +}); + +test("the use handler can be replaced and is the single seam", (t) => { + const f = fixture(t, [item("alpha")]); + f.setVisible(true); + const seen: string[] = []; + f.owner.setUseHandler((name) => { seen.push(name); }); + assert.equal(f.owner.use(), true); + assert.deepEqual(seen, ["alpha"]); + assert.deepEqual(f.state.used, []); + f.owner.setUseHandler(undefined); + assert.equal(f.owner.use(), true, "no handler is a no-op"); +}); + +test("an empty profile list shows only the hint, with no actions", (t) => { + const f = fixture(t, []); + f.setVisible(true); + const lines = f.rail.render(60).map((line) => line.trimEnd()); + assert.equal(lines.length, 2); + assert.equal(lines[1], ` ${PROFILE_CARD_EMPTY_HINT}`); + for (let x = 0; x < 48; x++) for (let y = 1; y < 3; y++) assert.equal(f.rail.handleMouse!(click(x, y)), undefined); + assert.equal(f.owner.use(), false); + assert.equal(f.owner.next(), false); + assert.deepEqual(f.state.used, []); +}); + +test("saved profiles are re-read at most once per refresh window and keep the shown profile by name", (t) => { + const f = fixture(t, [item("alpha"), item("beta"), item("gamma")]); + f.setVisible(true); + f.owner.next(); + assert.equal(f.owner.shown()?.name, "beta"); + f.state.profiles = [item("zeta"), item("beta"), item("gamma")]; + f.rail.digest!(); + assert.equal(f.owner.items()[0]!.name, "alpha", "not re-read inside the window"); + f.state.now += PROFILE_CARD_REFRESH_MS; + f.rail.digest!(); + assert.equal(f.owner.items()[0]!.name, "zeta"); + assert.equal(f.owner.shown()?.name, "beta", "the shown profile is followed by name"); + f.state.profiles = [item("zeta")]; + f.owner.refreshItems(); + assert.equal(f.owner.shown()?.name, "zeta"); + assert.equal(f.owner.index(), 0); +}); + +test("a session boundary restarts on the profile in effect even when the card is visible", (t) => { + const f = fixture(t, [item("alpha", { session: true }), item("beta"), item("gamma")]); + f.setVisible(true); + assert.equal(f.owner.shown()?.name, "alpha", "the first session starts on its profile"); + f.owner.next(); + assert.equal(f.owner.shown()?.name, "beta"); + const before = f.renders(); + // The session changed: beta is still in the list, but it is not in effect now. + f.state.profiles = [item("alpha"), item("beta"), item("gamma", { session: true })]; + f.owner.resetForSession(); + assert.equal(f.owner.shown()?.name, "gamma", "the new session's profile is shown, not the old selection"); + assert.ok(f.renders() > before, "the rail repaints at the boundary"); + // Within one session an ordinary refresh still follows the shown profile by name. + f.owner.next(); + assert.equal(f.owner.shown()?.name, "alpha"); + f.state.profiles = [item("delta"), ...f.state.profiles]; + f.owner.refreshItems(); + assert.equal(f.owner.shown()?.name, "alpha", "a same-session refresh keeps the shown profile"); +}); + +test("a hidden card reads nothing at a session boundary", (t) => { + const f = fixture(t, [item("alpha"), item("beta", { session: true })]); + const before = f.state.loads; + f.owner.resetForSession(); + assert.equal(f.state.loads, before, "a hidden card never touches the profile stores"); + assert.equal(f.owner.index(), 0); +}); + +test("a panel-sheet render at sheet width never overwrites the rail's click map", (t) => { + const f = fixture(t, [item("alpha"), item("beta")]); + f.setVisible(true); + const railRow = text(f.rail)[1]!; + const railNextX = railRow.indexOf("▶"); + // /gentle:panel paints the same card at sheet width, far wider than the rail. + const sheetRow = f.rail.render(120).map((line) => line.trimEnd())[1]!; + const sheetNextX = sheetRow.indexOf("▶"); + assert.notEqual(sheetNextX, railNextX, "the sheet frame puts ▶ somewhere else"); + const shown = () => text(f.rail)[1]!.match(/◀ (\w+)/)![1]; + // Read the shown profile from the owner: rendering the rail here would repaint its + // width-48 frame and refresh its hit map, which is what this test must not need. + assert.equal(f.owner.shown()?.name, "alpha"); + // A rail click still routes against the frame the rail painted for its own width. + assert.deepEqual(f.rail.handleMouse!(click(railNextX, 1)), { handled: true, render: true }, "rail ▶ still works after a sheet render"); + assert.equal(shown(), "beta", "the rail click moved the card"); + f.rail.render(120); + // A sheet-width position can never route a rail click (it could hit use). + assert.equal(f.rail.handleMouse!(click(sheetNextX, 1)), undefined, "a sheet-width column is not a rail control"); + assert.equal(shown(), "beta"); + assert.deepEqual(f.state.used, [], "no click used a profile"); +}); + +test("through the installed rail a click lands on the arrows in tinted and carded surfaces", (t) => { + const found = chromeSurface(); + t.after(() => setChromeSurface(found)); + for (const surface of ["tinted", "transparent"] as const) { + setChromeSurface(surface); + const f = fixture(t, [item("alpha"), item("beta"), item("gamma")]); + sidebarPart(f.tui, "footer", { render: () => ["Status"], invalidate() {} }); + f.setVisible(true); + const dispose = installSidebar(f.tui, theme); + const node = f.root[NODE]() as unknown as { entries: { component: ScrollView }[] }; + const scroll = node.entries[1]!.component; + const content = scroll.render(50); + scroll.updateLayout(content.length, 20, () => {}); + const plain = (line: string) => line.replace(/\x1b\[[0-9;]*m/g, ""); + const lines = () => { f.root[NODE](); return scroll.render(50).map(plain); }; + const navY = () => lines().findIndex((line) => line.includes("◀")); + const mouse = (x: number, y: number): TuiMouseEvent => ({ type: "click", button: "left", x, y, screenX: 90 + x, screenY: y, width: 50, height: 20, shift: false, alt: false, ctrl: false }); + const row = lines()[navY()]!; + assert.match(row, /alpha/, `${surface}: starts on the first profile`); + assert.equal(scroll.handleMouse(mouse(row.indexOf("▶"), navY()))?.handled, true, `${surface}: ▶ click handled`); + assert.match(lines()[navY()]!, /◀ beta/, `${surface}: ▶ moved to beta`); + scroll.handleMouse(mouse(lines()[navY()]!.indexOf("◀"), navY())); + assert.match(lines()[navY()]!, /◀ alpha/, `${surface}: ◀ moved back`); + scroll.handleMouse(mouse(lines()[navY()]!.indexOf("◀"), navY())); + assert.match(lines()[navY()]!, /◀ gamma/, `${surface}: ◀ wraps`); + const useRow = lines().findIndex((line) => line.includes("✓ Use in session")); + scroll.handleMouse(mouse(lines()[useRow]!.indexOf("✓"), useRow)); + assert.deepEqual(f.state.used, ["gamma"], `${surface}: use click reaches the handler`); + f.setVisible(false); + assert.ok(!lines().some((line) => line.includes("◀")), `${surface}: hidden card leaves the rail`); + dispose(); + } +}); + diff --git a/tests/profile-card-use.test.ts b/tests/profile-card-use.test.ts new file mode 100644 index 000000000..a852b3a26 --- /dev/null +++ b/tests/profile-card-use.test.ts @@ -0,0 +1,421 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { readProfilesFileResult } from "../lib/agent-profiles.ts"; +import { readSessionProfileDisk } from "../lib/session-profile-disk-reader.ts"; +import { beginDesktopProfileApply, endDesktopProfileApply, isDesktopProfileApplyRunning } from "../lib/desktop-rpc-profiles.ts"; +import { PROFILE_CARD_BUSY_NOTICE, createProfileCardOwner, createProfileCardReader, createProfileCardUseHandler, readProfileCardItems } from "../lib/profile-card-sidebar.ts"; +import { bindSessionProfile, readSessionProfileBinding, readSessionProfileStartupNone, resetSessionProfileBindingsForTesting } from "../lib/session-profile-binding.ts"; +import { createSessionProfileIntegration } from "../lib/session-profile-integration.ts"; +import { createSessionProfileBind, createSessionProfileClear, createSessionProfileStartupBind, SESSION_PROFILE_CUSTOM_TYPE } from "../lib/session-profile-persistence.ts"; +import type { ProfileCardItem } from "../lib/profile-card-widget.ts"; + +const item = (name: string, markers: Partial = {}): ProfileCardItem => ({ name, active: false, pinned: false, session: false, ...markers }); + +function setup(t: { after(fn: () => void): void }, run: (name: string) => Promise | void, home?: string) { + assert.equal(isDesktopProfileApplyRunning(), false, "the gate starts free"); + t.after(() => endDesktopProfileApply()); + const notices: Array<[string, string]> = []; + let loads = 0; + let profiles = [item("alpha"), item("beta")]; + const owner = createProfileCardOwner({ loadItems: () => { loads++; return profiles; }, configHome: () => home }); + const runs: string[] = []; + const handler = createProfileCardUseHandler({ + begin: beginDesktopProfileApply, + end: endDesktopProfileApply, + notify: (message, level) => { notices.push([level, message]); }, + run: async (name) => { runs.push(name); await run(name); }, + refresh: () => owner.refreshItems(), + }); + owner.setUseHandler(handler); + return { owner, notices, runs, loads: () => loads, setProfiles: (next: ProfileCardItem[]) => { profiles = next; } }; +} +// The owner only acts while visible; flip it through the store-free path. +function show(owner: ReturnType, home: string) { + writeFileSync(join(home, "profile-card.json"), `${JSON.stringify({ schema: "gentle-pi.profile-card/v1", visible: true })}\n`); + owner.refreshVisibility(); +} +function scratch(t: { after(fn: () => void): void }) { + const home = mkdtempSync(join(tmpdir(), "profile-card-use-")); + t.after(() => rmSync(home, { recursive: true, force: true })); + return home; +} +const settle = () => new Promise((resolve) => setImmediate(resolve)); + +test("use runs the owner action once with the shown profile name, under the shared gate, then refreshes", async (t) => { + const home = scratch(t); + let gateDuringRun: boolean | undefined; + const f = setup(t, () => { gateDuringRun = isDesktopProfileApplyRunning(); }); + const owner = createProfileCardOwner({ loadItems: () => [item("alpha"), item("beta")], configHome: () => home }); + let refreshes = 0; + owner.setUseHandler(createProfileCardUseHandler({ begin: beginDesktopProfileApply, end: endDesktopProfileApply, notify: () => {}, run: async (name) => { f.runs.push(name); gateDuringRun = isDesktopProfileApplyRunning(); }, refresh: () => { refreshes++; owner.refreshItems(); } })); + show(owner, home); + owner.next(); + assert.equal(owner.use(), true); + await settle(); + assert.deepEqual(f.runs, ["beta"]); + assert.equal(gateDuringRun, true, "the apply runs inside the shared gate"); + assert.equal(isDesktopProfileApplyRunning(), false, "the gate is released afterwards"); + assert.equal(refreshes, 1, "markers refresh after the action"); + assert.deepEqual(f.notices, []); +}); + +test("a busy gate applies nothing and says so once", async (t) => { + const f = setup(t, () => {}); + assert.equal(beginDesktopProfileApply(), true); + await createProfileCardUseHandler({ begin: beginDesktopProfileApply, end: endDesktopProfileApply, notify: (m, l) => { f.notices.push([l, m]); }, run: async (name) => { f.runs.push(name); }, refresh: () => { throw new Error("must not refresh"); } })("alpha"); + assert.deepEqual(f.runs, []); + assert.deepEqual(f.notices, [["info", PROFILE_CARD_BUSY_NOTICE]]); + assert.equal(isDesktopProfileApplyRunning(), true, "the other apply keeps its gate"); +}); + +// ---- The card asks before it binds (S3/S6): a use that binds and switches the live session is confirmed ---- + +test("a declined confirmation binds nothing, says nothing and leaves the gate free", async (t) => { + const home = scratch(t); + t.after(() => endDesktopProfileApply()); + const asked: string[] = []; + const runs: string[] = []; + const notices: Array<[string, string]> = []; + let refreshes = 0; + const owner = createProfileCardOwner({ loadItems: () => [item("alpha"), item("beta")], configHome: () => home }); + owner.setUseHandler(createProfileCardUseHandler({ + begin: beginDesktopProfileApply, + end: endDesktopProfileApply, + confirm: async (name) => { asked.push(name); return false; }, + notify: (message, level) => { notices.push([level, message]); }, + run: async (name) => { runs.push(name); }, + refresh: () => { refreshes++; }, + })); + show(owner, home); + owner.next(); + assert.equal(owner.use(), true); + await settle(); + assert.deepEqual(asked, ["beta"], "the shown profile is the one asked about"); + assert.deepEqual(runs, [], "declining binds no profile and touches no live state"); + assert.deepEqual(notices, [], "declining is silent"); + assert.equal(isDesktopProfileApplyRunning(), false, "the gate is released"); + assert.equal(refreshes, 0, "declining re-reads nothing: nothing changed"); +}); + +test("a confirmation surface that fails binds nothing", async (t) => { + t.after(() => endDesktopProfileApply()); + const runs: string[] = []; + await createProfileCardUseHandler({ + begin: beginDesktopProfileApply, + end: endDesktopProfileApply, + confirm: async () => { throw new Error("no confirmation surface"); }, + notify: () => {}, + run: async (name) => { runs.push(name); }, + refresh: () => {}, + })("alpha"); + assert.deepEqual(runs, [], "an unanswerable confirmation is not an approval"); + assert.equal(isDesktopProfileApplyRunning(), false); +}); + +test("an approved confirmation runs the owner action under the gate, after asking", async (t) => { + t.after(() => endDesktopProfileApply()); + const order: string[] = []; + await createProfileCardUseHandler({ + begin: () => { order.push("begin"); return beginDesktopProfileApply(); }, + end: () => { order.push("end"); endDesktopProfileApply(); }, + confirm: async (name) => { order.push(`confirm:${name}:${isDesktopProfileApplyRunning()}`); return true; }, + notify: () => {}, + run: async (name) => { order.push(`run:${name}:${isDesktopProfileApplyRunning()}`); }, + refresh: () => { order.push("refresh"); }, + })("alpha"); + assert.deepEqual(order, ["begin", "confirm:alpha:true", "run:alpha:true", "end", "refresh"], "ask first, then bind inside the shared gate"); +}); + +test("a busy gate never asks for confirmation", async (t) => { + const f = setup(t, () => {}); + let asked = 0; + assert.equal(beginDesktopProfileApply(), true); + await createProfileCardUseHandler({ + begin: beginDesktopProfileApply, + end: endDesktopProfileApply, + confirm: async () => { asked++; return true; }, + notify: (m, l) => { f.notices.push([l, m]); }, + run: async (name) => { f.runs.push(name); }, + refresh: () => { throw new Error("must not refresh"); }, + })("alpha"); + assert.equal(asked, 0, "a busy apply is never confirmed: it cannot run anyway"); + assert.deepEqual(f.runs, []); + assert.deepEqual(f.notices, [["info", PROFILE_CARD_BUSY_NOTICE]]); +}); + +test("without a confirmation surface the handler applies directly, as before", async (t) => { + const home = scratch(t); + const f = setup(t, () => {}, home); + show(f.owner, home); + f.owner.use(); + await settle(); + assert.deepEqual(f.runs, ["alpha"], "a host without the seam keeps the previous behavior"); + assert.equal(isDesktopProfileApplyRunning(), false); + assert.deepEqual(f.notices, []); +}); + +test("an owner action that applies nothing (declined or not applied) leaves items refreshed and throws nothing", async (t) => { + const home = scratch(t); + const f = setup(t, () => { /* the owner declined: it only notifies and returns */ }, home); + show(f.owner, home); + const before = f.loads(); + f.setProfiles([item("alpha", { session: false }), item("beta")]); + assert.equal(f.owner.use(), true); + await settle(); + assert.deepEqual(f.runs, ["alpha"]); + assert.ok(f.loads() > before, "items re-read after the action"); + assert.equal(isDesktopProfileApplyRunning(), false); + assert.deepEqual(f.notices, []); +}); + +test("a throwing owner action is notified as a warning, releases the gate and still refreshes", async (t) => { + const home = scratch(t); + const f = setup(t, () => { throw new Error("boom"); }, home); + show(f.owner, home); + const before = f.loads(); + f.owner.use(); + await settle(); + assert.deepEqual(f.notices, [["warning", 'Could not use profile "alpha" in this session: boom']]); + assert.equal(isDesktopProfileApplyRunning(), false); + assert.ok(f.loads() > before); +}); + +test("a second use while an apply runs starts no second apply", async (t) => { + const home = scratch(t); + let release!: () => void; + const pending = new Promise((resolve) => { release = resolve; }); + const f = setup(t, () => pending, home); + show(f.owner, home); + f.owner.use(); + await settle(); + f.owner.use(); + f.owner.use(); + await settle(); + assert.deepEqual(f.runs, ["alpha"], "only the first click applies"); + assert.deepEqual(f.notices, [["info", PROFILE_CARD_BUSY_NOTICE], ["info", PROFILE_CARD_BUSY_NOTICE]]); + release(); + await settle(); + assert.equal(isDesktopProfileApplyRunning(), false); + f.owner.use(); + await settle(); + assert.deepEqual(f.runs, ["alpha", "alpha"], "a later click applies again once the gate is free"); +}); + +test("the display read marks the session binding without mutating session profile state or the stores", (t) => { + const home = scratch(t); + t.after(() => resetSessionProfileBindingsForTesting()); + const profiles = `${JSON.stringify({ kind: "gentle-pi.agent_model_profiles", version: 1, active: "alpha", profiles: { alpha: {}, beta: {} } })}\n`; + writeFileSync(join(home, "profiles.json"), profiles); + const read = () => readProfileCardItems({ configHome: home, sessionId: "s1", cwd: home }); + // Unbound: nothing is bound, recorded or cleared by looking. + assert.deepEqual(read().map((entry) => [entry.name, entry.active, entry.session]), [["alpha", true, false], ["beta", false, false]]); + assert.equal(readSessionProfileBinding("s1"), undefined); + assert.equal(readSessionProfileStartupNone("s1"), false); + bindSessionProfile("s1", "beta", { worker: { model: "p/m" } } as never); + const binding = readSessionProfileBinding("s1"); + assert.deepEqual(read().map((entry) => [entry.name, entry.session]), [["alpha", false], ["beta", true]]); + assert.deepEqual(readSessionProfileBinding("s1"), binding, "the binding is untouched"); + assert.equal(readFileSync(join(home, "profiles.json"), "utf8"), profiles); + assert.deepEqual(readdirSync(home).sort(), ["profiles.json"], "no store file was written"); + assert.deepEqual(readProfileCardItems({ configHome: join(home, "missing"), sessionId: "s1", cwd: home }), [], "no profiles file shows no profiles and writes nothing"); + assert.deepEqual(readdirSync(home).sort(), ["profiles.json"]); +}); + +// ---- The session marker follows the profile in effect: explicit choice, then the startup record, else none ---- + +const profilesJson = `${JSON.stringify({ kind: "gentle-pi.agent_model_profiles", version: 1, active: "alpha", profiles: { alpha: {}, beta: {}, gamma: {} } })} +`; +const recordEntry = (id: string, data: unknown) => ({ type: "custom", id, parentId: null, timestamp: "2026-10-05T00:00:00Z", customType: SESSION_PROFILE_CUSTOM_TYPE, data }); +function sessionFixture(t: { after(fn: () => void): void }, entries: unknown[], options: { flushed?: boolean } = {}) { + const home = scratch(t); + t.after(() => resetSessionProfileBindingsForTesting()); + writeFileSync(join(home, "profiles.json"), profilesJson); + const file = join(home, "session.jsonl"); + if (options.flushed !== false) writeFileSync(file, [{ type: "session", id: "s2", version: 3 }, ...entries].map((row) => JSON.stringify(row)).join("\n")); + const session = { getSessionId: () => "s2", getSessionFile: () => file, getBranch: () => entries }; + const read = () => readProfileCardItems({ configHome: home, sessionId: "s2", cwd: home, session }); + const snapshot = () => JSON.stringify([readSessionProfileBinding("s2"), readSessionProfileStartupNone("s2"), readdirSync(home).sort(), readFileSync(join(home, "profiles.json"), "utf8"), options.flushed === false ? "" : readFileSync(file, "utf8"), entries]); + return { home, read, snapshot }; +} +const marks = (items: ProfileCardItem[]) => items.map((entry) => `${entry.name}${entry.active ? "*" : ""}${entry.session ? "#" : ""}`); +function startIndex(home: string, read: () => ProfileCardItem[]) { + const owner = createProfileCardOwner({ loadItems: read, configHome: () => home }); + writeFileSync(join(home, "profile-card.json"), `${JSON.stringify({ schema: "gentle-pi.profile-card/v1", visible: true })} +`); + owner.refreshVisibility(); + return owner.shown()?.name; +} + +test("an explicit session choice marks its profile and the card starts there", (t) => { + const f = sessionFixture(t, [recordEntry("e1", createSessionProfileBind("gamma", {}))]); + const before = f.snapshot(); + assert.deepEqual(marks(f.read()), ["alpha*", "beta", "gamma#"]); + assert.equal(startIndex(f.home, f.read), "gamma"); + assert.equal(f.snapshot().replace(/"profile-card\.json",/, ""), before.replace(/"profile-card\.json",/, ""), "session state, stores and the session file are untouched"); +}); + +test("a startup-only record marks the startup profile and the card starts there", (t) => { + for (const origin of ["global", "local", "repo"] as const) { + const f = sessionFixture(t, [recordEntry("s1", createSessionProfileStartupBind(origin, "beta", {}))]); + const before = f.snapshot(); + assert.deepEqual(marks(f.read()), ["alpha*", "beta#", "gamma"], origin); + assert.equal(startIndex(f.home, f.read), "beta", origin); + assert.equal(f.snapshot().replace(/"profile-card\.json",/, ""), before.replace(/"profile-card\.json",/, ""), `${origin}: nothing mutated`); + } +}); + +test("a newer clear (legacy or started with no profile) shows no session marker and the card falls back to the active profile", (t) => { + for (const clear of [createSessionProfileClear(), createSessionProfileClear("none")]) { + const f = sessionFixture(t, [recordEntry("e1", createSessionProfileBind("gamma", {})), recordEntry("e2", clear)]); + const before = f.snapshot(); + assert.deepEqual(marks(f.read()), ["alpha*", "beta", "gamma"]); + assert.equal(startIndex(f.home, f.read), "alpha"); + assert.equal(f.snapshot().replace(/"profile-card\.json",/, ""), before.replace(/"profile-card\.json",/, "")); + } +}); + +test("a session with no record falls back to the active profile", (t) => { + const f = sessionFixture(t, []); + const before = f.snapshot(); + assert.deepEqual(marks(f.read()), ["alpha*", "beta", "gamma"]); + assert.equal(startIndex(f.home, f.read), "alpha"); + assert.equal(f.snapshot().replace(/"profile-card\.json",/, ""), before.replace(/"profile-card\.json",/, "")); +}); + +test("a session file not flushed yet falls back to the in-memory binding, still without writes", (t) => { + const f = sessionFixture(t, [recordEntry("e1", createSessionProfileBind("beta", {}))], { flushed: false }); + assert.deepEqual(marks(f.read()), ["alpha*", "beta", "gamma"], "nothing bound in memory yet: no marker"); + bindSessionProfile("s2", "beta", {}); + const before = f.snapshot(); + assert.deepEqual(marks(f.read()), ["alpha*", "beta#", "gamma"]); + assert.equal(f.snapshot(), before); +}); + +// ---- A failed append is not the session in effect: the card excludes the same IDs as the authority ---- + +/** A session whose append writes the record to disk and then throws (a failed append on disk). */ +function failedAppendFixture(t: { after(fn: () => void): void }) { + const home = scratch(t); + t.after(() => resetSessionProfileBindingsForTesting()); + writeFileSync(join(home, "profiles.json"), profilesJson); + const file = join(home, "session.jsonl"); + const entries: Array<{ id: string }> = []; + const flush = () => writeFileSync(file, [{ type: "session", id: "s4", version: 3 }, ...entries].map((row) => JSON.stringify(row)).join("\n")); + flush(); + const session = { getSessionId: () => "s4", getSessionFile: () => file, getBranch: () => entries }; + const integration = createSessionProfileIntegration(); + let serial = 0; + let failing = true; + const started = integration.start(session as never, (type, data) => { + entries.push({ type: "custom", id: `e${++serial}`, parentId: entries.at(-1)?.id ?? null, timestamp: "2026-10-05T00:00:00Z", customType: type, data } as never); + flush(); + if (failing) throw new Error("append failed after the record reached disk"); + }, { reason: "startup" }); + const read = () => readProfileCardItems({ configHome: home, sessionId: "s4", cwd: home, session }); + return { home, file, entries, session, started, read, healthy: () => { failing = false; } }; +} + +test("a record whose append failed after it reached disk is not the session marker the card shows", (t) => { + const f = failedAppendFixture(t); + const outcome = f.started.attachment.bind("gamma", {}); + assert.equal(outcome.status, "append-failed-preserved", "the failed append is quarantined, never a success"); + assert.match(readFileSync(f.file, "utf8"), /"gamma"/, "the failed record is on disk"); + const settled = JSON.stringify([readdirSync(f.home).sort(), readFileSync(f.file, "utf8"), readSessionProfileBinding("s4")]); + assert.deepEqual(marks(f.read()), ["alpha*", "beta", "gamma"], "a record whose append failed is not the profile in effect"); + assert.deepEqual(marks(f.read()), ["alpha*", "beta", "gamma"], "and the cached read does not resurrect it"); + assert.equal(JSON.stringify([readdirSync(f.home).sort(), readFileSync(f.file, "utf8"), readSessionProfileBinding("s4")]), settled, "the display read writes nothing"); + assert.equal(startIndex(f.home, f.read), "alpha", "the card starts on the active profile, not the failed record"); +}); + +test("only the failed record is excluded: a later recorded selection marks its profile again", (t) => { + const f = failedAppendFixture(t); + assert.equal(f.started.attachment.bind("gamma", {}).status, "append-failed-preserved"); + assert.deepEqual(marks(f.read()), ["alpha*", "beta", "gamma"], "the failed record is excluded"); + f.healthy(); + assert.equal(f.started.attachment.bind("beta", {}).status, "persisted", "a recorded selection succeeds"); + assert.deepEqual(marks(f.read()), ["alpha*", "beta#", "gamma"], "the exclusion is limited to the failed record"); +}); + +// ---- The session file and profiles.json are re-read only when they change ---- + +function counted(t: { after(fn: () => void): void }, flushed = true) { + const home = scratch(t); + t.after(() => resetSessionProfileBindingsForTesting()); + writeFileSync(join(home, "profiles.json"), profilesJson); + const file = join(home, "session.jsonl"); + const entries: unknown[] = []; + const flush = () => writeFileSync(file, [{ type: "session", id: "s3", version: 3 }, ...entries].map((row) => JSON.stringify(row)).join("\n")); + if (flushed) flush(); + let diskReads = 0; + let profileReads = 0; + const reader = createProfileCardReader({ + readDisk: (source, options) => { diskReads++; return readSessionProfileDisk(source, options); }, + readProfiles: (path) => { profileReads++; return readProfilesFileResult(path); }, + }); + const session = { getSessionId: () => "s3", getSessionFile: () => file, getBranch: () => entries }; + const read = () => marks(readProfileCardItems({ configHome: home, sessionId: "s3", cwd: home, session }, reader)); + return { home, entries, flush, reader, read, disk: () => diskReads, profiles: () => profileReads }; +} + +test("repeated reads with an unchanged session file and profiles.json read neither again", (t) => { + const f = counted(t); + f.entries.push(recordEntry("e1", createSessionProfileBind("gamma", {}))); + f.flush(); + for (let i = 0; i < 5; i++) assert.deepEqual(f.read(), ["alpha*", "beta", "gamma#"]); + assert.equal(f.disk(), 1, "the session file is parsed once"); + assert.equal(f.profiles(), 1, "profiles.json is parsed once"); +}); + +test("an appended session record re-reads the file and moves the marker", (t) => { + const f = counted(t); + f.entries.push(recordEntry("e1", createSessionProfileBind("gamma", {}))); + f.flush(); + assert.deepEqual(f.read(), ["alpha*", "beta", "gamma#"]); + f.entries.push(recordEntry("e2", createSessionProfileBind("beta", {}))); + f.flush(); + assert.deepEqual(f.read(), ["alpha*", "beta#", "gamma"]); + assert.equal(f.disk(), 2); + f.read(); + assert.equal(f.disk(), 2, "stable again afterwards"); +}); + +test("an edited profiles.json is re-read; a changed in-memory binding or invalidate() re-reads the session", (t) => { + const f = counted(t); + f.entries.push(recordEntry("e1", createSessionProfileBind("gamma", {}))); + f.flush(); + f.read(); + writeFileSync(join(f.home, "profiles.json"), profilesJson.replace('"gamma":{}', '"gamma":{},"delta":{}')); + assert.deepEqual(f.read(), ["alpha*", "beta", "gamma#", "delta"]); + assert.equal(f.profiles(), 2); + assert.equal(f.disk(), 1, "the session file did not change"); + bindSessionProfile("s3", "beta", {}); + f.read(); + assert.equal(f.disk(), 2, "a changed in-memory binding name re-reads"); + f.reader.invalidate(); + f.read(); + assert.equal(f.disk(), 3, "invalidate (after a use) re-reads"); + assert.equal(f.profiles(), 3, "and profiles.json too"); +}); + +test("an indeterminate read is never cached as final", (t) => { + const f = counted(t, false); + f.entries.push(recordEntry("e1", createSessionProfileBind("gamma", {}))); + // No session file yet: indeterminate, memory has no binding. + assert.deepEqual(f.read(), ["alpha*", "beta", "gamma"]); + assert.deepEqual(f.read(), ["alpha*", "beta", "gamma"]); + assert.equal(f.disk(), 2, "retried on every tick"); + f.flush(); + assert.deepEqual(f.read(), ["alpha*", "beta", "gamma#"], "the flushed file now decides"); + f.read(); + assert.equal(f.disk(), 3, "and is cached once determinate"); + // A record newer than disk is indeterminate too: retried, never frozen. + f.entries.push(recordEntry("e2", createSessionProfileBind("beta", {}))); + f.read(); + f.read(); + assert.equal(f.disk(), 5); + f.flush(); + assert.deepEqual(f.read(), ["alpha*", "beta#", "gamma"]); +}); diff --git a/tests/profile-card-widget.test.ts b/tests/profile-card-widget.test.ts new file mode 100644 index 000000000..0d34d1ff6 --- /dev/null +++ b/tests/profile-card-widget.test.ts @@ -0,0 +1,132 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { visibleWidth } from "@earendil-works/pi-tui"; +import { + buildProfileCardItems, + initialProfileIndex, + nextProfileIndex, + previousProfileIndex, + profileCardActionAt, + reconcileProfileIndex, + renderProfileCardSection, + type ProfileCardItem, +} from "../lib/profile-card-widget.ts"; +import { stripAnsi } from "../lib/terminal-theme.ts"; + +const plainTheme = { + fg(_color: string, text: string) { + return text; + }, + bold(text: string) { + return text; + }, +}; + +const item = (name: string, markers: Partial = {}): ProfileCardItem => ({ name, active: false, pinned: false, session: false, ...markers }); +const three = [item("alpha"), item("beta", { active: true }), item("gamma")]; + +test("buildProfileCardItems names the markers from the raw profiles file, session outranking pin", () => { + const file = { profiles: { a: {}, "b (x)": {}, c: {}, d: {} }, active: "c" }; + assert.deepEqual(buildProfileCardItems(file), [ + item("a"), item("b (x)"), item("c", { active: true }), item("d"), + ]); + assert.deepEqual(buildProfileCardItems(file, "b (x)", "c"), [ + item("a"), item("b (x)", { pinned: true }), item("c", { active: true, session: true }), item("d"), + ]); + assert.deepEqual(buildProfileCardItems(file, "c", "c"), [ + item("a"), item("b (x)"), item("c", { active: true, session: true }), item("d"), + ], "a profile that is both bound and pinned shows the session marker only"); + assert.deepEqual(buildProfileCardItems({ profiles: {} }), []); +}); + +test("initial index prefers the session profile, then the active one, else 0", () => { + assert.equal(initialProfileIndex([item("a", { active: true }), item("b", { session: true })]), 1); + assert.equal(initialProfileIndex([item("a"), item("b", { active: true }), item("c", { pinned: true })]), 1); + assert.equal(initialProfileIndex([item("a"), item("b", { pinned: true })]), 0); + assert.equal(initialProfileIndex([]), 0); +}); + +test("next and previous wrap around at both ends", () => { + assert.equal(nextProfileIndex(0, 3), 1); + assert.equal(nextProfileIndex(2, 3), 0); + assert.equal(previousProfileIndex(2, 3), 1); + assert.equal(previousProfileIndex(0, 3), 2); +}); + +test("a single profile stays put and an empty list yields 0", () => { + assert.equal(nextProfileIndex(0, 1), 0); + assert.equal(previousProfileIndex(0, 1), 0); + assert.equal(nextProfileIndex(0, 0), 0); + assert.equal(previousProfileIndex(0, 0), 0); +}); + +test("reconcile keeps the selection by name, else clamps", () => { + assert.equal(reconcileProfileIndex("gamma", 2, [item("gamma"), item("alpha")]), 0, "same name moved"); + assert.equal(reconcileProfileIndex("gamma", 2, [item("alpha"), item("beta")]), 1, "removed: clamp to last"); + assert.equal(reconcileProfileIndex("beta", 1, [item("alpha"), item("x"), item("y")]), 1, "removed: same slot"); + assert.equal(reconcileProfileIndex("beta", 1, []), 0); + assert.equal(reconcileProfileIndex(undefined, 9, three), 2); + assert.equal(reconcileProfileIndex(undefined, -4, three), 0); +}); + +test("renders header, navigation row and use action with exact text", () => { + const { lines, hits } = renderProfileCardSection(three, 1, plainTheme, 40); + assert.equal(lines.length, 3); + assert.match(lines[0]!, /^▾ PROFILE/); + assert.equal(lines[1], ` ◀ beta (active)${" ".repeat(18)}2/3 ▶`); + assert.equal(lines[2], " ✓ Use in session".padEnd(40)); + for (const line of lines) assert.equal(visibleWidth(stripAnsi(line)), 40); + assert.equal(hits.length, 3); +}); + +test("markers render in a fixed order", () => { + const { lines } = renderProfileCardSection([item("p", { session: true, pinned: true, active: true })], 0, plainTheme, 50); + assert.match(lines[1]!, /^ {2}◀ p \(active, pinned, session\) +1\/1 ▶$/); +}); + +test("every line respects the width at narrow sizes and the name truncates", () => { + const long = [item("a-very-long-profile-name-indeed", { active: true }), item("b")]; + for (const width of [60, 30, 24, 18, 14, 12, 10, 8, 6, 4, 2, 1]) { + const { lines, hits } = renderProfileCardSection(long, 0, plainTheme, width); + for (const line of lines) assert.ok(visibleWidth(stripAnsi(line)) <= width, `w=${width}: ${line}`); + for (const hit of hits) assert.ok(hit.x1 <= width && hit.x0 < hit.x1, `w=${width} hit ${JSON.stringify(hit)}`); + } + const mid = renderProfileCardSection(long, 0, plainTheme, 24).lines[1]!; + assert.match(mid, /◀ .*… .*1\/2 ▶$/); + assert.equal(visibleWidth(mid), 24); +}); + +test("hit spans land on the arrows and the use label", () => { + const width = 40; + const { lines, hits } = renderProfileCardSection(three, 1, plainTheme, width); + const nav = lines[1]!; + const use = lines[2]!; + const prev = hits.find((h) => h.action === "previous")!; + const next = hits.find((h) => h.action === "next")!; + const useHit = hits.find((h) => h.action === "use")!; + assert.deepEqual([prev.y, prev.x0, prev.x1], [1, nav.indexOf("◀"), nav.indexOf("◀") + 1]); + assert.deepEqual([next.y, next.x0, next.x1], [1, nav.indexOf("▶"), nav.indexOf("▶") + 1]); + assert.equal(useHit.y, 2); + assert.equal(useHit.x0, use.indexOf("✓")); + assert.equal(useHit.x1, use.indexOf("Use in session") + "Use in session".length); + assert.equal(profileCardActionAt(hits, prev.x0, 1), "previous"); + assert.equal(profileCardActionAt(hits, next.x0, 1), "next"); + assert.equal(profileCardActionAt(hits, useHit.x0, 2), "use"); + assert.equal(profileCardActionAt(hits, useHit.x1 - 1, 2), "use"); + assert.equal(profileCardActionAt(hits, useHit.x1, 2), undefined); + assert.equal(profileCardActionAt(hits, prev.x1, 1), undefined); + assert.equal(profileCardActionAt(hits, next.x0 - 1, 1), undefined); + assert.equal(profileCardActionAt(hits, 0, 0), undefined, "header is not an action"); + assert.equal(profileCardActionAt(hits, prev.x0, 5), undefined); +}); + +test("empty state is one hint line with no arrows, use action or hits", () => { + const { lines, hits } = renderProfileCardSection([], 0, plainTheme, 50); + assert.equal(lines.length, 2); + assert.match(lines[0]!, /^▾ PROFILE/); + assert.equal(lines[1], " No profiles yet. Create one in /gentle:profiles".padEnd(50)); + assert.deepEqual(hits, []); + assert.doesNotMatch(lines.join("\n"), /◀|▶|Use in session/); + assert.equal(profileCardActionAt(hits, 2, 1), undefined); + for (const width of [30, 10, 3]) for (const line of renderProfileCardSection([], 0, plainTheme, width).lines) assert.ok(visibleWidth(stripAnsi(line)) <= width); +}); diff --git a/tests/shell-sidebar-layout.test.ts b/tests/shell-sidebar-layout.test.ts index e48c2d3a7..97d456d50 100644 --- a/tests/shell-sidebar-layout.test.ts +++ b/tests/shell-sidebar-layout.test.ts @@ -340,6 +340,21 @@ test("rail orders live work first, then Status, without standalone changes", (t) assert.deepEqual(rail(f).render(50).map((line) => line.trim()), ["✿ Gentle Shell ✿", "", "todo", "", "agents", "", "Status"]); }); +test("the profiles section renders between agents and Status when registered and is absent otherwise", (t) => { + const f = fixture(); + for (const key of ["todo", "agents"]) sidebarPart(f.tui, key, { render: () => [key, ""], invalidate() {} }); + t.after(installSidebar(f.tui, theme)); + const lines = () => rail(f).render(50).map((line) => line.trim()); + assert.deepEqual(lines(), ["✿ Gentle Shell ✿", "", "todo", "", "agents", "", "Status"], "no profiles part: nothing is reserved for it"); + const profiles = sidebarPart(f.tui, "profiles", { render: () => [] as string[], invalidate() {}, dispose() {} }, { digest: () => "p", render: () => ["profiles", ""], invalidate() {} }); + assert.deepEqual(lines(), ["✿ Gentle Shell ✿", "", "todo", "", "agents", "", "profiles", "", "Status"], "profiles sits after agents and before Status"); + sidebarState(f.tui).visibility = { todo: false }; + invalidateSidebar(f.tui); + assert.deepEqual(lines(), ["✿ Gentle Shell ✿", "", "agents", "", "profiles", "", "Status"], "the todo visibility filter still applies"); + profiles.dispose(); + assert.deepEqual(lines(), ["✿ Gentle Shell ✿", "", "agents", "", "Status"]); +}); + test("branding belongs to scroll content before Status, never transcript or narrow bottom", (t) => { const f = fixture(); t.after(installSidebar(f.tui, theme));