gentle-pi 4.6.0 → 4.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (290) hide show
  1. package/README.md +10 -11
  2. package/assets/agents/gentle-ai-explore.md +1 -0
  3. package/assets/agents/gentle-ai-verify.md +5 -2
  4. package/assets/agents/gentle-ai-worker.md +3 -0
  5. package/assets/agents/jd-fix-agent.md +1 -0
  6. package/assets/agents/jd-judge-a.md +1 -0
  7. package/assets/agents/jd-judge-b.md +1 -0
  8. package/assets/design-canvas/canvas.css +13 -1
  9. package/assets/design-canvas/canvas.js +11 -2
  10. package/assets/install-wizard/wizard.js +1 -0
  11. package/assets/migrations/agent-body-history.json +16 -1
  12. package/assets/orchestrator-delegation-reference.md +4 -4
  13. package/assets/orchestrator-delegation.md +1 -1
  14. package/assets/orchestrator-full-delegation-card.md +65 -0
  15. package/assets/orchestrator-full-delegation.md +34 -0
  16. package/assets/orchestrator-memory.md +3 -3
  17. package/assets/orchestrator-prompts.md +1 -1
  18. package/assets/orchestrator-skills.md +1 -1
  19. package/assets/orchestrator-verification.md +7 -5
  20. package/assets/orchestrator.md +3 -3
  21. package/bin/gentle-shell.mjs +164 -56
  22. package/docs/agent-status.md +61 -0
  23. package/docs/bundled-install.md +7 -5
  24. package/docs/delegated-verification.md +29 -7
  25. package/docs/gentle-agents-activity.md +14 -0
  26. package/docs/gentle-shell.md +54 -16
  27. package/docs/install-wizard.md +1 -1
  28. package/docs/permission-modes.md +9 -4
  29. package/docs/readme-reference.md +75 -30
  30. package/docs/render-cache-performance.md +11 -1
  31. package/docs/review-coordinator.md +33 -0
  32. package/docs/review-request-context.md +19 -0
  33. package/docs/review-windows-acl.md +18 -0
  34. package/docs/voice.md +6 -3
  35. package/docs/yolo-mode.md +5 -5
  36. package/extensions/ask-user-choice.ts +1 -0
  37. package/extensions/ask-user-question.ts +1 -0
  38. package/extensions/child-safety.ts +3 -0
  39. package/extensions/gentle-agent-status.ts +99 -0
  40. package/extensions/gentle-agents.ts +326 -34
  41. package/extensions/gentle-ai.ts +1496 -454
  42. package/extensions/gentle-shell.ts +293 -63
  43. package/extensions/gentle-todo.ts +18 -2
  44. package/extensions/gentle-tps.ts +48 -0
  45. package/extensions/quiet-tools.ts +38 -8
  46. package/extensions/skill-registry.ts +175 -18
  47. package/extensions/startup-banner.ts +30 -3
  48. package/lib/agent-profile-pin.ts +3 -3
  49. package/lib/agent-profiles.ts +160 -2
  50. package/lib/agent-status.ts +105 -0
  51. package/lib/agents-config.ts +46 -0
  52. package/lib/agents-history.ts +24 -5
  53. package/lib/agents-messaging.ts +47 -5
  54. package/lib/agents-runner.ts +183 -12
  55. package/lib/auto-permission-runtime.ts +1 -1
  56. package/lib/bounded-writer-admission.ts +13 -1
  57. package/lib/card-content-policy.ts +8 -6
  58. package/lib/command-palette.ts +133 -17
  59. package/lib/context-backstop.ts +14 -5
  60. package/lib/destructive-command-guard.ts +48 -4
  61. package/lib/execution-surface-guard.ts +20 -0
  62. package/lib/exploration-budget.ts +4 -2
  63. package/lib/gentle-ai-binary.ts +1 -1
  64. package/lib/gentle-design.ts +3 -0
  65. package/lib/gentle-shell-bundled.ts +6 -19
  66. package/lib/gentle-shell-launcher.ts +43 -8
  67. package/lib/herdr-activity.ts +14 -2
  68. package/lib/herdr-busy.ts +45 -0
  69. package/lib/image-attachments.ts +33 -0
  70. package/lib/image-disk-cache.ts +137 -0
  71. package/lib/inprocess-reviewer.ts +270 -140
  72. package/lib/jobs-view.ts +198 -11
  73. package/lib/model-routing-authority.ts +22 -4
  74. package/lib/native-choice-list.ts +20 -2
  75. package/lib/native-review-cli.ts +96 -19
  76. package/lib/orchestrator-mode-policy.ts +105 -0
  77. package/lib/questionnaire/questionnaire-view.ts +105 -12
  78. package/lib/rdd-mode-control.ts +32 -0
  79. package/lib/reply-language-anchor.ts +104 -0
  80. package/lib/review-blocker.ts +92 -0
  81. package/lib/review-candidate-symlink-scan.ts +136 -0
  82. package/lib/review-candidate-view-owner.ts +81 -44
  83. package/lib/review-continuation-registry.ts +99 -0
  84. package/lib/review-coordinator.ts +163 -0
  85. package/lib/review-failure-facts.ts +49 -0
  86. package/lib/review-host-relay.ts +46 -10
  87. package/lib/review-integration-v2.ts +7 -1
  88. package/lib/review-relay-phase-timing.ts +45 -0
  89. package/lib/review-start-context.ts +17 -0
  90. package/lib/session-profile-freeze.ts +4 -2
  91. package/lib/shell-bar.ts +140 -58
  92. package/lib/shell-changes.ts +2 -0
  93. package/lib/shell-panel.ts +17 -3
  94. package/lib/shell-sidebar-layout.ts +112 -40
  95. package/lib/shell-sidebar.ts +7 -0
  96. package/lib/shell-todo.ts +10 -3
  97. package/lib/verifier-admission.ts +1 -1
  98. package/lib/visual-customization-policy.ts +36 -16
  99. package/lib/visual-customize-view.ts +216 -21
  100. package/lib/visual-layout-preview.ts +9 -5
  101. package/lib/visual-profiles.ts +2 -2
  102. package/lib/windows-session-transport.ts +53 -2
  103. package/lib/yolo-session-policy.ts +40 -15
  104. package/package.json +2 -1
  105. package/runtime/gentle-ai-binary.mjs +1 -1
  106. package/runtime/gentle-shell-bundled.mjs +6 -19
  107. package/runtime/gentle-shell-launcher.mjs +42 -7
  108. package/runtime/native-review-cli.mjs +93 -16
  109. package/runtime/review-integration-v2.mjs +7 -1
  110. package/scripts/build-full-delegation-card.mjs +175 -0
  111. package/scripts/bundled-install.mjs +38 -8
  112. package/scripts/download-progress.mjs +68 -0
  113. package/scripts/gentle-ai-installer.mjs +41 -18
  114. package/scripts/gentle-ai-proxy.mjs +294 -0
  115. package/scripts/install-gentle-ai.mjs +14 -1
  116. package/scripts/installer-preflight.mjs +5 -5
  117. package/scripts/installer-runner.mjs +27 -12
  118. package/scripts/installer-server.mjs +8 -7
  119. package/scripts/render-cache-host.mjs +72 -0
  120. package/scripts/render-cache-performance-worker.mjs +5 -4
  121. package/scripts/render-cache-performance.mjs +6 -1
  122. package/scripts/run-test-suite.mjs +40 -28
  123. package/scripts/verify-package-files.mjs +12 -2
  124. package/scripts/voice-worker.cjs +32 -6
  125. package/skills/design/SKILL.md +11 -8
  126. package/skills/gentle-ai/SKILL.md +2 -2
  127. package/skills/gentle-ui-design/SKILL.md +46 -0
  128. package/skills/gentle-ui-design/references/adaptive-interfaces.md +46 -0
  129. package/skills/gentle-ui-design/references/browse-and-compare.md +62 -0
  130. package/skills/gentle-ui-design/references/composition-and-feedback.md +56 -0
  131. package/skills/gentle-ui-design/references/task-and-content.md +60 -0
  132. package/skills/skill-registry/SKILL.md +4 -2
  133. package/skills/work-unit-commits/SKILL.md +6 -7
  134. package/tests/agent-home.test.ts +28 -9
  135. package/tests/agent-profiles-workflow.test.ts +163 -0
  136. package/tests/agent-risk-escalation.test.ts +1 -1
  137. package/tests/agent-status.test.ts +143 -0
  138. package/tests/agents-config.test.ts +96 -0
  139. package/tests/agents-history.test.ts +31 -0
  140. package/tests/agents-jobs-frames.test.ts +93 -0
  141. package/tests/agents-prompt-lifecycle-runtime.test.ts +376 -0
  142. package/tests/agents-runner-drain.test.ts +193 -0
  143. package/tests/agents-runner.test.ts +178 -2
  144. package/tests/append-system-prompt-route.test.ts +4 -1
  145. package/tests/ask-user-choice.test.ts +4 -3
  146. package/tests/ask-user-question.test.ts +97 -0
  147. package/tests/auto-permission-runtime.test.ts +1 -1
  148. package/tests/autonomous-guard.test.ts +346 -10
  149. package/tests/bounded-stop-contract.test.ts +43 -3
  150. package/tests/bridge-cost.test.ts +19 -4
  151. package/tests/bundled-install.test.ts +30 -5
  152. package/tests/card-content-policy.test.ts +3 -3
  153. package/tests/chained-pr-skill.test.ts +8 -6
  154. package/tests/child-safety.test.ts +11 -0
  155. package/tests/codegraph-tools.test.ts +11 -5
  156. package/tests/command-palette.test.ts +284 -1
  157. package/tests/delegate-for-reason-contract.test.ts +3 -3
  158. package/tests/design-canvas-assets.test.ts +185 -2
  159. package/tests/destructive-command-guard.test.ts +52 -0
  160. package/tests/download-progress.test.ts +71 -0
  161. package/tests/execution-surface-guard.test.ts +55 -0
  162. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +9 -5
  163. package/tests/fixtures/proxy-tls/proxy.crt +19 -0
  164. package/tests/fixtures/proxy-tls/proxy.key +28 -0
  165. package/tests/fixtures/session-profile-v1/gentle-ai-reviewer.ts +89 -0
  166. package/tests/fixtures/session-profile-v1/replay.ts +53 -6
  167. package/tests/full-delegation-closure.test.ts +131 -0
  168. package/tests/full-delegation-notices.test.ts +76 -0
  169. package/tests/generic-agent-tools.test.ts +3 -3
  170. package/tests/gentle-agent-status.test.ts +74 -0
  171. package/tests/gentle-agents-child-jobs.test.ts +237 -0
  172. package/tests/gentle-agents.test.ts +1070 -12
  173. package/tests/gentle-ai-binary.test.ts +3 -1
  174. package/tests/gentle-ai-elapsed-store.test.ts +19 -0
  175. package/tests/gentle-ai-exploration-budget.test.ts +18 -2
  176. package/tests/gentle-ai-installer.test.ts +134 -51
  177. package/tests/gentle-ai-proxy.test.ts +434 -0
  178. package/tests/gentle-ai.test.ts +113 -38
  179. package/tests/gentle-design.test.ts +21 -0
  180. package/tests/gentle-herdr-activity.test.ts +9 -6
  181. package/tests/gentle-shell-bin.test.ts +123 -0
  182. package/tests/gentle-shell-bundled.test.ts +207 -31
  183. package/tests/gentle-shell-launcher.test.ts +77 -10
  184. package/tests/gentle-shell.test.ts +899 -59
  185. package/tests/gentle-todo.test.ts +19 -2
  186. package/tests/gentle-tps.test.ts +123 -0
  187. package/tests/gentle-ui-design-skill.test.ts +59 -0
  188. package/tests/herdr-busy.test.ts +59 -0
  189. package/tests/herdr-task-summary-policy.test.ts +8 -4
  190. package/tests/image-disk-cache.test.ts +163 -0
  191. package/tests/independent-recovery-delivery.test.ts +83 -0
  192. package/tests/inprocess-reviewer.test.ts +176 -4
  193. package/tests/installer-posix-bootstrap.test.ts +1 -1
  194. package/tests/installer-preflight.test.ts +5 -4
  195. package/tests/installer-runner.test.ts +79 -44
  196. package/tests/installer-server.test.ts +14 -11
  197. package/tests/jobs-view.test.ts +260 -6
  198. package/tests/modal-mouse-boundaries.test.ts +136 -0
  199. package/tests/model-routing-authority.test.ts +178 -2
  200. package/tests/native-choice-list.test.ts +77 -2
  201. package/tests/native-review-capability-contract.test.ts +7 -1
  202. package/tests/native-review-cli.test.ts +269 -1
  203. package/tests/no-self-pause-contract.test.ts +4 -1
  204. package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
  205. package/tests/orchestrator-budget.test.ts +7 -2
  206. package/tests/orchestrator-delegation-mode.test.ts +153 -0
  207. package/tests/orchestrator-mode-policy.test.ts +175 -0
  208. package/tests/orchestrator-prompt-budget.test.ts +3 -1
  209. package/tests/orchestrator-rdd-ownership.test.ts +2 -2
  210. package/tests/package-manifest.test.ts +11 -9
  211. package/tests/permission-allowlist.test.ts +202 -0
  212. package/tests/pi-update-launcher.test.ts +8 -0
  213. package/tests/pnpm-workspace-config.test.ts +58 -0
  214. package/tests/primary-session-prompt.test.ts +13 -0
  215. package/tests/profile-pin.test.ts +29 -2
  216. package/tests/profile-tier-footer.test.ts +5 -0
  217. package/tests/profiles-panel-delegation-mode.test.ts +422 -0
  218. package/tests/questionnaire-view.test.ts +115 -0
  219. package/tests/quiet-bash-runtime.test.ts +1 -1
  220. package/tests/quiet-tool-rendering.test.ts +48 -0
  221. package/tests/rdd-aware-verification-contract.test.ts +16 -11
  222. package/tests/rdd-customize.test.ts +287 -0
  223. package/tests/rdd-mode-cache.test.ts +450 -0
  224. package/tests/rdd-mode-control.test.ts +407 -0
  225. package/tests/rdd-mode-scope-regression.test.ts +137 -0
  226. package/tests/rdd-off-independent-regression.test.ts +69 -0
  227. package/tests/rdd-status-line.test.ts +18 -0
  228. package/tests/render-cache-performance.test.ts +171 -2
  229. package/tests/reply-language-anchor.test.ts +173 -0
  230. package/tests/review-agent-end-preflight.test.ts +1 -1
  231. package/tests/review-blocker.test.ts +193 -0
  232. package/tests/review-candidate-owner-retry.test.ts +1 -1
  233. package/tests/review-candidate-symlink-scan.test.ts +157 -0
  234. package/tests/review-candidate-view.test.ts +1 -1
  235. package/tests/review-candidate-windows-boundary.test.ts +131 -0
  236. package/tests/review-candidate-windows-probe.test.ts +63 -0
  237. package/tests/review-committed-restart-ack.test.ts +129 -0
  238. package/tests/review-continuation-registry.test.ts +76 -0
  239. package/tests/review-controller-native-routing.test.ts +261 -5
  240. package/tests/review-controller-workspace-root.test.ts +230 -3
  241. package/tests/review-controller.test.ts +96 -11
  242. package/tests/review-coordinator-runtime.test.ts +117 -0
  243. package/tests/review-coordinator.test.ts +195 -0
  244. package/tests/review-failure-facts.test.ts +87 -0
  245. package/tests/review-host-relay-routing.test.ts +258 -4
  246. package/tests/review-host-relay.test.ts +39 -0
  247. package/tests/review-integration-v2.test.ts +46 -3
  248. package/tests/review-json-arguments.test.ts +65 -10
  249. package/tests/review-last-event-closure.test.ts +68 -0
  250. package/tests/review-loadout-rdd-off-sdk.test.ts +65 -31
  251. package/tests/review-owner-identity.test.ts +60 -24
  252. package/tests/review-relay-phase-timing.test.ts +128 -0
  253. package/tests/review-relay-transport-agent.test.ts +12 -2
  254. package/tests/review-reviewer-evidence.test.ts +183 -0
  255. package/tests/review-risk-assessment.test.ts +74 -3
  256. package/tests/review-session-standing-permission-controller.test.ts +21 -1
  257. package/tests/review-start-context.test.ts +19 -0
  258. package/tests/review-tool-prose-budget.test.ts +121 -0
  259. package/tests/run-test-suite.test.ts +122 -1
  260. package/tests/runtime-harness.mjs +4 -1
  261. package/tests/sensitive-path-tools.test.ts +181 -5
  262. package/tests/session-profile-append-controller-pi.test.ts +60 -31
  263. package/tests/session-profile-binding.test.ts +19 -1
  264. package/tests/session-profile-disk-reader-pi.test.ts +58 -16
  265. package/tests/session-profile-v1-compat.test.ts +35 -1
  266. package/tests/shell-bar.test.ts +186 -42
  267. package/tests/shell-panel.test.ts +50 -22
  268. package/tests/shell-sidebar-fullscreen.test.ts +5 -5
  269. package/tests/shell-sidebar-layout.test.ts +294 -23
  270. package/tests/shell-sidebar-scroll-benchmark.test.ts +1 -1
  271. package/tests/shell-surface-transparent.test.ts +89 -0
  272. package/tests/shell-todo.test.ts +12 -0
  273. package/tests/skill-registry.test.ts +838 -5
  274. package/tests/startup-banner.test.ts +152 -1
  275. package/tests/startup-home-repo.test.ts +2 -0
  276. package/tests/support/review-coordinator-runtime.ts +69 -0
  277. package/tests/task-size-routing-contract.test.ts +5 -3
  278. package/tests/verifier-admission.test.ts +49 -0
  279. package/tests/verify-first-launch-contract.test.ts +78 -3
  280. package/tests/visual-customization-policy.test.ts +39 -6
  281. package/tests/visual-customize-view.test.ts +573 -9
  282. package/tests/visual-layout-preview.test.ts +15 -1
  283. package/tests/visual-profiles.test.ts +11 -0
  284. package/tests/voice-worker.test.ts +73 -2
  285. package/tests/windows-session-transport.test.ts +126 -0
  286. package/tests/work-continuity-contract.test.ts +28 -0
  287. package/tests/writer-feature-document-admission.test.ts +92 -0
  288. package/tests/yolo-customize.test.ts +27 -4
  289. package/tests/yolo-mode.test.ts +23 -18
  290. package/tests/yolo-session-policy.test.ts +270 -1
@@ -0,0 +1,422 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import test from "node:test";
6
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
7
+ import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
8
+ import { __testing } from "../extensions/gentle-ai.ts";
9
+ import { PROFILES_KIND, PROFILES_VERSION, bootstrapProfilesFile, readProfilesFileResult, type AgentProfilesFile } from "../lib/agent-profiles.ts";
10
+ import type { AgentModelConfig } from "../lib/model-routing-authority.ts";
11
+ import { createSessionProfileIntegration } from "../lib/session-profile-integration.ts";
12
+ import { resetSessionProfileBindingsForTesting } from "../lib/session-profile-binding.ts";
13
+ import { stripAnsi } from "../lib/terminal-theme.ts";
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // /gentle:profiles exposes the per-profile orchestrator mode (full delegation
17
+ // mode S5) through a panel draft: `w` toggles the shown profile, every commit
18
+ // path (save, use-session) carries it, and the loop persists it with the
19
+ // routing in one atomic write.
20
+ // ---------------------------------------------------------------------------
21
+
22
+ const SCREEN_AGENTS = ["gentle-ai-explore", "gentle-ai-verify", "gentle-ai-worker"];
23
+ const PANEL_MODELS = ["nan/deepseek-v4-flash", "openai/gpt-5.5"];
24
+
25
+ type PanelResult = {
26
+ type: string;
27
+ name?: string;
28
+ config?: AgentModelConfig;
29
+ orchestratorMode?: "organic" | "full-delegation";
30
+ };
31
+
32
+ function teamRouting(): AgentModelConfig {
33
+ return { orchestrator: { model: "openai/gpt-6.1-sol", thinking: "max" }, "gentle-ai-worker": { model: "nan/deepseek-v4-flash" } };
34
+ }
35
+
36
+ function panelFile(workflow?: Record<string, { orchestratorMode: string }>): AgentProfilesFile {
37
+ const file = bootstrapProfilesFile({}) as AgentProfilesFile;
38
+ file.profiles = { team: teamRouting() } as AgentProfilesFile["profiles"];
39
+ file.active = "team";
40
+ if (workflow !== undefined) (file as { workflow?: unknown }).workflow = workflow;
41
+ return file;
42
+ }
43
+
44
+ function renderPanel(
45
+ inputs: string[],
46
+ file: AgentProfilesFile,
47
+ results: PanelResult[] = [],
48
+ width = 100,
49
+ theme?: Theme,
50
+ options: { fallbacks?: unknown; fastModels?: string[] } = {},
51
+ ): string[] {
52
+ const config: AgentModelConfig = JSON.parse(JSON.stringify(file.profiles["team"])) as AgentModelConfig;
53
+ const lines = __testing.routingTablePanel(
54
+ config,
55
+ PANEL_MODELS,
56
+ SCREEN_AGENTS,
57
+ width,
58
+ theme,
59
+ 30,
60
+ inputs,
61
+ [],
62
+ // The panel records its actions into this array; the test reads them through
63
+ // its own narrower shape rather than importing the panel's internal type.
64
+ results as unknown as Parameters<typeof __testing.routingTablePanel>[8],
65
+ { file, profileName: "team", ...(options.fallbacks !== undefined ? { fallbacks: options.fallbacks as never } : {}), ...(options.fastModels ? { fastModels: options.fastModels } : {}) },
66
+ );
67
+ return lines.map(stripAnsi);
68
+ }
69
+
70
+ /** The orchestrator's own row of a rendered screen: the first line naming it (tone probes may recase it). */
71
+ function orchestratorRow(rendered: string[]): string {
72
+ const line = rendered.find((line) => /orchestrator/i.test(line));
73
+ assert.ok(line, "no orchestrator row on screen");
74
+ return line;
75
+ }
76
+
77
+ test("w drafts the shown profile's mode and save carries it in the returned action", () => {
78
+ const results: PanelResult[] = [];
79
+ const lines = renderPanel(["w", "s"], panelFile(), results);
80
+ assert.equal(results.length, 1, "one save action");
81
+ assert.equal(results[0]?.type, "save");
82
+ assert.equal(results[0]?.name, "team");
83
+ assert.equal(results[0]?.orchestratorMode, "full-delegation");
84
+ assert.doesNotMatch(lines.join("\n"), /Nothing to save/, "the drafted mode counts as a change");
85
+ });
86
+
87
+ test("w toggles back: a committed full-delegation profile drafts organic", () => {
88
+ const results: PanelResult[] = [];
89
+ renderPanel(["w", "s"], panelFile({ team: { orchestratorMode: "full-delegation" } }), results);
90
+ assert.equal(results[0]?.type, "save");
91
+ assert.equal(results[0]?.orchestratorMode, "organic");
92
+ });
93
+
94
+ test("esc counts a drafted mode as an unsaved change exactly like a routing edit", () => {
95
+ const warned = renderPanel(["w", "\x1b"], panelFile());
96
+ assert.match(warned.join("\n"), /Unsaved changes\. Press esc again to close without saving\./);
97
+ const closed: PanelResult[] = [];
98
+ renderPanel(["w", "\x1b", "\x1b"], panelFile(), closed);
99
+ assert.deepEqual(closed.map((result) => result.type), ["close"]);
100
+ // The untouched panel still closes on the first esc: the mode alone arms the warning.
101
+ const untouched: PanelResult[] = [];
102
+ renderPanel(["\x1b"], panelFile(), untouched);
103
+ assert.deepEqual(untouched.map((result) => result.type), ["close"]);
104
+ });
105
+
106
+ test("s without any change stays a no-op (preserved)", () => {
107
+ const results: PanelResult[] = [];
108
+ const lines = renderPanel(["s"], panelFile(), results);
109
+ assert.deepEqual(results, [], "no save without a change");
110
+ assert.match(lines.join("\n"), /Nothing to save\./);
111
+ });
112
+
113
+ // ---- orchestrator row mode chip -------------------------------------------
114
+
115
+ const TONE_THEME = {
116
+ // Width-neutral tone probe: dim renders lowercase, accent uppercase, so the
117
+ // chip's tone is observable without changing the line's measured width.
118
+ fg: (color: string, text: string) => (color === "dim" ? text.toLowerCase() : color === "accent" ? text.toUpperCase() : text),
119
+ } as unknown as Theme;
120
+
121
+ test("the orchestrator row shows the drafted mode beside the tier, in both modes", () => {
122
+ const organic = orchestratorRow(renderPanel([], panelFile()));
123
+ assert.match(organic, /Orchestrator\s+openai\/gpt-6\.1-sol\s+max\s+◎ organic/, "the committed organic mode rides the orchestrator row");
124
+ const delegated = orchestratorRow(renderPanel([], panelFile({ team: { orchestratorMode: "full-delegation" } })));
125
+ assert.match(delegated, /Orchestrator\s+openai\/gpt-6\.1-sol\s+max\s+⇄ full delegation/, "the committed full-delegation mode rides the orchestrator row");
126
+ // The chip mirrors the draft: one `w` flips it before anything is saved.
127
+ assert.match(orchestratorRow(renderPanel(["w"], panelFile())), /max\s+⇄ full delegation/);
128
+ assert.match(orchestratorRow(renderPanel(["w"], panelFile({ team: { orchestratorMode: "full-delegation" } }))), /max\s+◎ organic/);
129
+ // No hierarchy: the rows are byte-identical apart from the chip itself, so
130
+ // the two modes render with the same tone by construction.
131
+ const stripChip = (row: string) => row
132
+ .replace(/ ⇄ full delegation/, "")
133
+ .replace(/ ◎ organic/, "")
134
+ .replace(/ ⇄ full(?![a-z])/, "")
135
+ .replace(/ ◎ org(?![a-z])/, "")
136
+ .replace(/\s+│$/, " │");
137
+ assert.equal(stripChip(delegated), stripChip(organic), "peer modes: only the chip's glyph and label differ");
138
+ // A per-mode accent ranking is gone: the chip survives the case probe unchanged.
139
+ assert.match(orchestratorRow(renderPanel([], panelFile({ team: { orchestratorMode: "full-delegation" } }), [], 100, TONE_THEME)), /⇄ full delegation(?!…)/, "not uppercased, so no accent tone");
140
+ assert.doesNotMatch(orchestratorRow(renderPanel([], panelFile(), [], 100, TONE_THEME)), /ORGANIC/, "organic is not ranked with an accent tone either");
141
+ // The chip belongs to the orchestrator row only.
142
+ assert.doesNotMatch(renderPanel([], panelFile({ team: { orchestratorMode: "full-delegation" } })).join("\n"), /gentle-ai-worker\s+nan\/deepseek-v4-flash\s+inherit\s+⇄/);
143
+ });
144
+
145
+ test("the mode chip keeps the full orchestrator row intact at 100 columns", () => {
146
+ const row = orchestratorRow(renderPanel([], panelFile()));
147
+ assert.doesNotMatch(row, /…/, "nothing on the row is cut to make room");
148
+ // Agent rows are untouched by the chip.
149
+ assert.match(renderPanel([], panelFile()).join("\n"), /gentle-ai-worker\s+nan\/deepseek-v4-flash\s+inherit/);
150
+ // With a Fast tier on the row, chip and tier share the line at 100 columns.
151
+ const tiered = orchestratorRow(renderPanel([], panelFile(), [], 100, undefined, { fastModels: ["openai/gpt-6.1-sol"] }));
152
+ assert.match(tiered, /Standard ▾\s+◎ organic/);
153
+ });
154
+
155
+ test("the mode chip degrades before it disappears: full form at 100 with a tier, half form one tier-width earlier", () => {
156
+ // The human's case: a Fast-capable orchestrator at exactly 100 columns still
157
+ // shows the mode (here the widest form fits beside the tier).
158
+ const tiered = orchestratorRow(renderPanel([], panelFile({ team: { orchestratorMode: "full-delegation" } }), [], 100, undefined, { fastModels: ["openai/gpt-6.1-sol"] }));
159
+ assert.match(tiered, /Standard ▾\s+⇄ full delegation/, "the mode is never gone at the default width");
160
+ // One tier-width narrower the wide form no longer fits and the ladder steps down.
161
+ const stepped = orchestratorRow(renderPanel([], panelFile({ team: { orchestratorMode: "full-delegation" } }), [], 95, undefined, { fastModels: ["openai/gpt-6.1-sol"] }));
162
+ assert.match(stepped, /Standard ▾\s+⇄ full(?![a-z])/, "the half-width form rides beside the tier when the wide one cannot");
163
+ assert.doesNotMatch(stepped, /full delegation/, "the wide form is the one that yields");
164
+ // The organic forms share the ladder: beside a tier the full word still fits.
165
+ const organicTiered = orchestratorRow(renderPanel([], panelFile(), [], 100, undefined, { fastModels: ["openai/gpt-6.1-sol"] }));
166
+ assert.match(organicTiered, /Standard ▾\s+◎ organic/);
167
+ });
168
+
169
+ test("only the last-resort form fitting renders it, and never for the wrong mode", () => {
170
+ // At 64 columns the two wide forms do not fit; the shapes remain, one rung
171
+ // apart because the organic word is shorter (symmetric ladder, equal rungs).
172
+ const delegated = orchestratorRow(renderPanel([], panelFile({ team: { orchestratorMode: "full-delegation" } }), [], 64));
173
+ assert.match(delegated, /max\s+⇄\s*│/, "the last-resort full-delegation shape is still on the row");
174
+ const organic = orchestratorRow(renderPanel([], panelFile(), [], 64));
175
+ assert.match(organic, /max\s+◎ org(?![a-z])/, "the organic ladder is one step above its own last resort");
176
+ // At 53 columns even the shorthand does not fit; both shapes remain.
177
+ assert.match(orchestratorRow(renderPanel([], panelFile({ team: { orchestratorMode: "full-delegation" } }), [], 53)), /max\s+⇄\s*│/);
178
+ assert.match(orchestratorRow(renderPanel([], panelFile(), [], 53)), /max\s+◎\s*│/);
179
+ // The shape states its mode: the mapping is per form, not per width.
180
+ assert.doesNotMatch(orchestratorRow(renderPanel([], panelFile(), [], 64, TONE_THEME)), /⇄/, "an organic profile never renders the bolt");
181
+ });
182
+
183
+ test("the mode chip sits after the fallback chain and the chain is sized around it", () => {
184
+ const fallbacks = { chain: () => [{ model: "provider/very-long-model-name-that-is-long" }], save: () => undefined };
185
+ const fastModels = ["openai/gpt-6.1-sol"];
186
+ const row = (width: number) => orchestratorRow(renderPanel([], panelFile(), [], width, undefined, { fallbacks, fastModels }));
187
+
188
+ // Default width: the chain and the mode coexist, in that order.
189
+ const roomy = row(100);
190
+ assert.match(roomy, /◎ (?:organic|org)\b/, "the chip keeps a readable form at default width");
191
+ assert.match(roomy, /↪ /, "the chain keeps its slot at default width");
192
+ assert.doesNotMatch(roomy, /very-long-model-name-that-is-long/, "the long chain model is what shortens");
193
+ // Existing row behaviour this feature must not move: the chain sits directly
194
+ // after the tier, and the chip follows it instead of pushing in between.
195
+ assert.match(roomy, /(?:Standard|Fast) ▾\s+↪ /, "the tier-to-chain adjacency stays exactly where it was");
196
+
197
+ // Narrowing: the chain is what the chip's reserved slot takes, so the chain
198
+ // goes first and the mode stays readable for as long as any of the row fits.
199
+ const narrowed = row(70);
200
+ assert.match(narrowed, /◎ org\b/, "the mode survives where the chain no longer fits");
201
+ assert.doesNotMatch(narrowed, /↪/, "the chain is what the chip's slot displaced");
202
+
203
+ // Very narrow: the row has no room for a reference at all, and the model name
204
+ // wins, exactly as it did before this feature existed.
205
+ const tight = row(60);
206
+ assert.doesNotMatch(tight, /◎|⇄/, "no mode chip once the row cannot hold one");
207
+ assert.match(tight, /gpt-6\.1-sol/, "the model name is never what gives way");
208
+ });
209
+
210
+ // ---- focused-Orchestrator mode explainer ----------------------------------
211
+
212
+ /** The description slot of a rendered screen: the line carrying the profile's scope sentence. */
213
+ function descriptionLine(rendered: string[]): string {
214
+ const line = rendered.find((line) => /Default for new sessions|Not in use|Used in this session|not in use/i.test(line));
215
+ assert.ok(line, "no description slot on screen");
216
+ return line;
217
+ }
218
+
219
+ test("the focused Orchestrator row explains both modes in the existing description slot", () => {
220
+ // The slot previously carried only the profile's scope sentence; the mode
221
+ // explainer appends to it while the Orchestrator row is the focused row.
222
+ const line = descriptionLine(renderPanel([], panelFile()));
223
+ assert.match(line, /Default for new sessions\.\s+◎ inline · ⇄ writer · w switches/);
224
+ // One line for both modes: it does not depend on the current mode at all.
225
+ const delegated = descriptionLine(renderPanel([], panelFile({ team: { orchestratorMode: "full-delegation" } })));
226
+ assert.equal(delegated, line, "both modes read the exact same explanation");
227
+ // Another row in focus: the slot stays the profile's own sentence.
228
+ const moved = descriptionLine(renderPanel(["j"], panelFile()));
229
+ assert.match(moved, /Default for new sessions\./);
230
+ assert.doesNotMatch(moved, /◎ inline/, "the mode explainer never hijacks another row's focus");
231
+ // Truncation: when the slot's room cannot hold both, the explainer yields
232
+ // before the scope sentence, and the line never grows an extra body row.
233
+ const narrow = descriptionLine(renderPanel([], panelFile(), [], 60));
234
+ assert.match(narrow, /Default for new sessions\./);
235
+ assert.doesNotMatch(narrow, /◎ inline/);
236
+ });
237
+
238
+ // ---- loop-level persistence ------------------------------------------------
239
+
240
+ interface PanelHomeFixture {
241
+ root: string;
242
+ configHome: string;
243
+ storePath: string;
244
+ writeStore: (profiles: Record<string, unknown>, extra?: Record<string, unknown>) => void;
245
+ }
246
+
247
+ function panelHomeFixture(t: test.TestContext): PanelHomeFixture {
248
+ const root = mkdtempSync(join(tmpdir(), "profiles-panel-delegation-"));
249
+ const configHome = join(root, "global");
250
+ mkdirSync(configHome, { recursive: true });
251
+ const previousConfigHome = process.env.GENTLE_PI_CONFIG_HOME;
252
+ process.env.GENTLE_PI_CONFIG_HOME = configHome;
253
+ resetSessionProfileBindingsForTesting();
254
+ t.after(() => {
255
+ resetSessionProfileBindingsForTesting();
256
+ if (previousConfigHome === undefined) delete process.env.GENTLE_PI_CONFIG_HOME;
257
+ else process.env.GENTLE_PI_CONFIG_HOME = previousConfigHome;
258
+ rmSync(root, { recursive: true, force: true });
259
+ });
260
+ const storePath = join(configHome, "profiles.json");
261
+ const writeStore = (profiles: Record<string, unknown>, extra?: Record<string, unknown>) => {
262
+ writeFileSync(storePath, JSON.stringify({ kind: PROFILES_KIND, version: PROFILES_VERSION, profiles, ...extra }, null, 2));
263
+ };
264
+ return { root, configHome, storePath, writeStore };
265
+ }
266
+
267
+ function actionManager(root: string): SessionManager {
268
+ const manager = SessionManager.create(root, join(root, "session-fixture"));
269
+ manager.appendMessage({ role: "user", content: "isolated profile action", timestamp: 1 });
270
+ createSessionProfileIntegration().start(manager, (type, data) => { manager.appendCustomEntry(type, data); }, { reason: "startup" });
271
+ return manager;
272
+ }
273
+
274
+ const LIVE = {
275
+ setModel: async (_model: unknown) => true,
276
+ setThinkingLevel() {},
277
+ getThinkingLevel: () => "medium" as const,
278
+ };
279
+
280
+ /** Drives the loop: scripted actions fill the panel visits; a `{ drive }` entry feeds real keys to the real panel instead. */
281
+ async function runLoop(
282
+ fixture: PanelHomeFixture,
283
+ scripted: Array<unknown | { drive: string[] }>,
284
+ options: { answers?: string[] } = {},
285
+ ): Promise<{ screens: string[]; notifications: string[]; actions: unknown[] }> {
286
+ const screens: string[] = [];
287
+ const notifications: string[] = [];
288
+ const actions: unknown[] = [];
289
+ const answers = options.answers ?? [];
290
+ let answerIndex = 0;
291
+ const manager = actionManager(fixture.root);
292
+ const ui = {
293
+ notify(message: string) { notifications.push(message); },
294
+ input: async () => answers[answerIndex++],
295
+ custom: async (factory: (tui: unknown, theme: unknown, keybindings: unknown, done: (result: unknown) => void) => { render(width: number): string[]; handleInput(data: string): void }) => {
296
+ let result: unknown;
297
+ const panel = factory({ terminal: { rows: 30 }, requestRender() {} }, { fg: (_c: string, text: string) => text }, undefined, (value: unknown) => { result = value; });
298
+ screens.push(panel.render(100).map(stripAnsi).join("\n"));
299
+ const visit = scripted.shift();
300
+ if (visit !== undefined && visit !== null && typeof visit === "object" && "drive" in (visit as { drive?: unknown })) {
301
+ for (const key of (visit as { drive: string[] }).drive) {
302
+ panel.handleInput(key);
303
+ panel.render(100);
304
+ }
305
+ screens.push(panel.render(100).map(stripAnsi).join("\n"));
306
+ assert.notEqual(result, undefined, "driven input must finish the interaction");
307
+ actions.push(result);
308
+ return result;
309
+ }
310
+ return visit ?? { type: "close" };
311
+ },
312
+ };
313
+ const ctx = {
314
+ cwd: fixture.root,
315
+ hasUI: true,
316
+ ui,
317
+ sessionManager: manager,
318
+ modelRegistry: { getAvailable: async () => [], find: () => ({ provider: "openai", id: "gpt-6.1-sol" }) },
319
+ } as unknown as ExtensionContext;
320
+ await __testing.openProfilesPanelLoop(ctx, LIVE, "team");
321
+ return { screens, notifications, actions };
322
+ }
323
+
324
+ test("save lands the mode and the routing in one write", async (t) => {
325
+ const fixture = panelHomeFixture(t);
326
+ fixture.writeStore({ team: { orchestrator: { model: "openai/gpt-6.1-sol" } } }, { active: "team" });
327
+ await runLoop(fixture, [
328
+ { type: "save", name: "team", config: { orchestrator: { model: "openai/gpt-6.1-sol" } }, orchestratorMode: "full-delegation" },
329
+ { type: "close" },
330
+ ]);
331
+ const saved = readProfilesFileResult(fixture.storePath);
332
+ assert.equal(saved.status, "valid");
333
+ const file = saved.status === "valid" ? saved.file : undefined;
334
+ assert.deepEqual(file?.workflow?.["team"], { orchestratorMode: "full-delegation" }, "the mode persists beside the routing");
335
+ assert.deepEqual(JSON.parse(JSON.stringify(file?.profiles["team"])), { orchestrator: { model: "openai/gpt-6.1-sol" } }, "the routing lands in the same write");
336
+ });
337
+
338
+ test("toggling back to organic removes the workflow entry instead of persisting an explicit organic", async (t) => {
339
+ const fixture = panelHomeFixture(t);
340
+ fixture.writeStore(
341
+ { team: { orchestrator: { model: "openai/gpt-6.1-sol" } } },
342
+ { active: "team", workflow: { team: { orchestratorMode: "full-delegation" } } },
343
+ );
344
+ await runLoop(fixture, [
345
+ { type: "save", name: "team", config: { orchestrator: { model: "openai/gpt-6.1-sol" } }, orchestratorMode: "organic" },
346
+ { type: "close" },
347
+ ]);
348
+ const saved = readProfilesFileResult(fixture.storePath);
349
+ const file = saved.status === "valid" ? saved.file : undefined;
350
+ assert.equal(file?.workflow, undefined, "an all-organic store keeps the pre-change shape");
351
+ assert.deepEqual(JSON.parse(JSON.stringify(file?.profiles["team"])), { orchestrator: { model: "openai/gpt-6.1-sol" } });
352
+ });
353
+
354
+ test("use-session persists a changed draft mode before binding and reports it", async (t) => {
355
+ const fixture = panelHomeFixture(t);
356
+ fixture.writeStore({ team: { orchestrator: { model: "openai/gpt-6.1-sol" } } }, { active: "team" });
357
+ const before = readFileSync(fixture.storePath, "utf8");
358
+ const { screens } = await runLoop(fixture, [
359
+ { type: "use-session", name: "team", config: { orchestrator: { model: "openai/gpt-6.1-sol" } }, orchestratorMode: "full-delegation" },
360
+ { type: "close" },
361
+ ]);
362
+ const saved = readProfilesFileResult(fixture.storePath);
363
+ const file = saved.status === "valid" ? saved.file : undefined;
364
+ assert.deepEqual(file?.workflow?.["team"], { orchestratorMode: "full-delegation" }, "enter never leaves a toggled mode behind");
365
+ assert.notEqual(readFileSync(fixture.storePath, "utf8"), before, "the store was written");
366
+ const reopened = screens.at(-1) ?? "";
367
+ assert.match(reopened, /now keeps its orchestrator in full-delegation mode/, "the status line reports the persisted mode");
368
+ });
369
+
370
+ test("use-session with an unchanged mode writes nothing (preserved shape)", async (t) => {
371
+ const fixture = panelHomeFixture(t);
372
+ fixture.writeStore({ team: { orchestrator: { model: "openai/gpt-6.1-sol" } } }, { active: "team" });
373
+ const before = readFileSync(fixture.storePath, "utf8");
374
+ await runLoop(fixture, [
375
+ { type: "use-session", name: "team", config: { orchestrator: { model: "openai/gpt-6.1-sol" } }, orchestratorMode: "organic" },
376
+ { type: "close" },
377
+ ]);
378
+ assert.equal(readFileSync(fixture.storePath, "utf8"), before, "an unchanged organic mode never grows a workflow key");
379
+ const saved = readProfilesFileResult(fixture.storePath);
380
+ const file = saved.status === "valid" ? saved.file : undefined;
381
+ assert.equal(file?.workflow, undefined);
382
+ });
383
+
384
+ // ---- draft-loss paths ------------------------------------------------------
385
+
386
+ test("switch-save carries the mode draft: arrowing to another tab and saving keeps it", async (t) => {
387
+ const fixture = panelHomeFixture(t);
388
+ fixture.writeStore(
389
+ { team: { orchestrator: { model: "openai/gpt-6.1-sol" } }, other: {} },
390
+ { active: "team" },
391
+ );
392
+ // w drafts the mode, → opens the switch prompt, s saves the left profile
393
+ // (mode and routing in one write), esc closes the freshly shown profile.
394
+ const { actions, screens } = await runLoop(fixture, [{ drive: ["w", "\x1b[C", "s", "\x1b"] }]);
395
+ const saved = readProfilesFileResult(fixture.storePath);
396
+ const file = saved.status === "valid" ? saved.file : undefined;
397
+ assert.deepEqual(file?.workflow?.["team"], { orchestratorMode: "full-delegation" }, "the switch write keeps the drafted mode");
398
+ assert.deepEqual(JSON.parse(JSON.stringify(file?.profiles["team"])), { orchestrator: { model: "openai/gpt-6.1-sol" } });
399
+ assert.match(screens.at(-1) ?? "", /Showing "other"/, "the switch continues to the next profile");
400
+ assert.equal((actions.at(-1) as PanelResult | undefined)?.type, "close");
401
+ });
402
+
403
+ test("the custom model prompt round trip keeps the mode draft, and saving after it persists both", async (t) => {
404
+ const fixture = panelHomeFixture(t);
405
+ fixture.writeStore({ team: { orchestrator: { model: "openai/gpt-6.1-sol" } } }, { active: "team" });
406
+ const { actions } = await runLoop(fixture, [
407
+ { type: "custom", target: "gentle-ai-worker", config: { orchestrator: { model: "openai/gpt-6.1-sol" } }, modeDraft: "full-delegation" },
408
+ { drive: ["s"] },
409
+ { type: "close" },
410
+ ], { answers: ["openai/beta"] });
411
+ const savedAction = actions.find((action) => (action as PanelResult).type === "save") as PanelResult | undefined;
412
+ assert.equal(savedAction?.orchestratorMode, "full-delegation", "the mode draft survives the reopen");
413
+ assert.equal((savedAction?.config as Record<string, { model?: string }> | undefined)?.["gentle-ai-worker"]?.model, "openai/beta", "the routing draft survives too");
414
+ const saved = readProfilesFileResult(fixture.storePath);
415
+ const file = saved.status === "valid" ? saved.file : undefined;
416
+ assert.deepEqual(file?.workflow?.["team"], { orchestratorMode: "full-delegation" });
417
+ assert.deepEqual(
418
+ JSON.parse(JSON.stringify(file?.profiles["team"])),
419
+ { orchestrator: { model: "openai/gpt-6.1-sol" }, "gentle-ai-worker": { model: "openai/beta" } },
420
+ "the custom model and the mode land together",
421
+ );
422
+ });
@@ -4,7 +4,10 @@ import {
4
4
  CURSOR_MARKER,
5
5
  KeybindingsManager,
6
6
  TUI_KEYBINDINGS,
7
+ TuiAltScreen,
8
+ stripTerminalSequences,
7
9
  visibleWidth,
10
+ type Terminal,
8
11
  type TuiMouseEvent,
9
12
  } from "@earendil-works/pi-tui";
10
13
  import {
@@ -582,6 +585,118 @@ test("the custom row is always appended after the authored options", () => {
582
585
  assert.ok(customRow > betaRow);
583
586
  });
584
587
 
588
+ const hoverTheme: QuestionnaireTheme = {
589
+ fg: (role, text) => role === "warning" ? `\x1b[33m${text}\x1b[39m` : text,
590
+ bold: (text) => text,
591
+ };
592
+
593
+ function move(lines: string[], x: number, y: number, width: number): TuiMouseEvent {
594
+ return { ...mouseEvent(lines, y, "move"), button: "none", x, screenX: x, width };
595
+ }
596
+
597
+ function textRow(lines: string[], text: string): number {
598
+ const row = lines.findIndex((line) => stripTerminalSequences(line).includes(text));
599
+ assert.ok(row >= 0, `missing ${text}`);
600
+ return row;
601
+ }
602
+
603
+ test("questionnaire hovers only selectable labels in the shared warning role, without changing answers", () => {
604
+ const completed: QuestionnaireResult[] = [];
605
+ const view = new QuestionnaireView({
606
+ questions: [question("Pick?", [option("Alpha", "First detail", "Preview body"), option("Beta", "Second detail")], { multiSelect: true })],
607
+ theme: hoverTheme,
608
+ onComplete: (result) => completed.push(result),
609
+ });
610
+ let lines = view.render(100);
611
+ const beta = textRow(lines, "Beta");
612
+ assert.equal(view.handleMouse(move(lines, 3, beta, 100))?.render, true);
613
+ lines = view.render(100);
614
+ assert.match(lines[beta]!, /\x1b\[33mBeta\x1b\[39m/);
615
+ assert.match(lines[textRow(lines, "Alpha")]!, /❯ \[ \] Alpha/);
616
+ assert.doesNotMatch(lines[textRow(lines, "Second detail")]!, /\x1b\[33m/);
617
+ assert.equal(view.handleMouse(move(lines, 3, beta, 100))?.render, false, "repeated motion does not redraw");
618
+ assert.deepEqual(view.getResult(), { cancelled: false, answers: [] });
619
+ assert.deepEqual(completed, []);
620
+
621
+ const description = textRow(lines, "Second detail");
622
+ assert.equal(view.handleMouse(move(lines, 5, description, 100))?.render, true);
623
+ lines = view.render(100);
624
+ assert.doesNotMatch(lines.join("\n"), /\x1b\[33m/);
625
+ const alpha = textRow(lines, "Alpha");
626
+ assert.equal(view.handleMouse(move(lines, 60, alpha, 100)), undefined, "preview cells are not label targets");
627
+ assert.equal(view.handleMouse(move(lines, 3, alpha, 100))?.render, true);
628
+ lines = view.render(100);
629
+ assert.match(lines[alpha]!, /\x1b\[33mAlpha\x1b\[39m/);
630
+ assert.doesNotMatch(lines[alpha]!, /\x1b\[33mPreview/);
631
+ assert.equal(view.handleMouse(move(lines, 2, 0, 100))?.render, true, "the tab heading is not a pointer-actionable target");
632
+ lines = view.render(100);
633
+ const custom = textRow(lines, CUSTOM_ROW_LABEL);
634
+ assert.equal(view.handleMouse(move(lines, 3, custom, 100))?.render, true);
635
+ assert.match(view.render(100)[custom]!, /\x1b\[33mType something\.\x1b\[39m/);
636
+ assert.deepEqual(completed, []);
637
+ view.handleInput(KEY.space);
638
+ view.handleInput(KEY.enter);
639
+ assert.deepEqual(view.getResult().answers, [
640
+ { questionIndex: 0, question: "Pick?", kind: "multi", answer: null, selected: ["Alpha"] },
641
+ ]);
642
+ });
643
+
644
+ test("questionnaire rejects stale, clipped and disposed hover geometry", () => {
645
+ let rows = 24;
646
+ const view = new QuestionnaireView({ questions: single(), theme: hoverTheme, rows: () => rows });
647
+ let lines = view.render(100);
648
+ const beta = textRow(lines, "Beta");
649
+ const old = move(lines, 3, beta, 100);
650
+ assert.equal(view.handleMouse(old)?.render, true);
651
+ lines = view.render(80);
652
+ assert.doesNotMatch(lines.join("\n"), /\x1b\[33m/);
653
+ assert.equal(view.handleMouse(old), undefined, "old width cannot target the new layout");
654
+ assert.equal(view.handleMouse({ ...move(lines, 3, textRow(lines, "Beta"), 80), height: 2 }), undefined, "clipped rows are not targets");
655
+ assert.equal(view.handleMouse(move(lines, 3, textRow(lines, "Beta"), 80))?.render, true);
656
+ view.invalidate();
657
+ assert.equal(view.handleMouse(move(lines, 3, textRow(lines, "Beta"), 80)), undefined, "invalidation rejects geometry until render");
658
+ lines = view.render(80);
659
+ assert.doesNotMatch(lines.join("\n"), /\x1b\[33m/);
660
+ assert.equal(view.handleMouse(move(lines, 3, textRow(lines, "Beta"), 80))?.render, true);
661
+ rows = 10;
662
+ assert.notEqual(view.handleMouse(move(lines, 3, textRow(lines, "Beta"), 80))?.handled, true, "height changes reject the old layout");
663
+ lines = view.render(80);
664
+ assert.doesNotMatch(lines.join("\n"), /\x1b\[33m/);
665
+ view.dispose();
666
+ assert.equal(view.handleMouse(move(lines, 3, textRow(lines, "Beta"), 80)), undefined);
667
+ view.handleInput(KEY.enter);
668
+ assert.deepEqual(view.getResult().answers, []);
669
+ });
670
+
671
+ test("questionnaire receives SGR hover and click through a centered TuiAltScreen overlay", () => {
672
+ let input: ((data: string) => void) | undefined;
673
+ const terminal: Terminal = {
674
+ start(onInput) { input = onInput; }, stop() {}, async drainInput() {}, write() {},
675
+ get columns() { return 120; }, get rows() { return 30; }, get kittyProtocolActive() { return false; },
676
+ moveBy() {}, hideCursor() {}, showCursor() {}, clearLine() {}, clearFromCursor() {}, clearScreen() {},
677
+ setTitle() {}, setProgress() {}, setProgramStatus() {},
678
+ };
679
+ const completed: QuestionnaireResult[] = [];
680
+ const view = new QuestionnaireView({ questions: single(), theme: hoverTheme, onComplete: (result) => completed.push(result) });
681
+ const tui = new TuiAltScreen(terminal, false, undefined, { mouse: true });
682
+ const overlay = tui.showOverlay(view, { anchor: "center", width: 80, maxHeight: 20 });
683
+ tui.start(); tui.renderNow(true);
684
+ try {
685
+ let lines = view.render(80);
686
+ const bounds = overlay.getBounds();
687
+ assert.ok(bounds && bounds.col > 0 && bounds.row > 0);
688
+ const beta = textRow(lines, "Beta");
689
+ const x = bounds.col + 4, y = bounds.row + beta + 1;
690
+ input?.(`\x1b[<35;${x};${y}M`);
691
+ lines = view.render(80);
692
+ assert.match(lines[beta]!, /\x1b\[33mBeta\x1b\[39m/);
693
+ assert.deepEqual(completed, []);
694
+ input?.(`\x1b[<0;${x};${y}M`);
695
+ input?.(`\x1b[<0;${x};${y}m`);
696
+ assert.equal(completed[0]?.answers[0]?.answer, "Beta");
697
+ } finally { tui.stop(); }
698
+ });
699
+
585
700
  test("every rendered line fits the width across 1-4 questions", () => {
586
701
  const questions = [
587
702
  question("One?", [option("A"), option("B", "B description", "preview ".repeat(20))], { header: "One" }),
@@ -64,7 +64,7 @@ if (process.env.GENTLE_TEST_BASH_CHILD === "1") {
64
64
  PI_OFFLINE: "1", GENTLE_PI_QUIET_TOOLS: "1", GENTLE_TEST_BASH_CHILD: "1", GENTLE_TEST_SHELL: shell };
65
65
  try {
66
66
  const result = spawnSync(process.execPath, ["--experimental-strip-types", fileURLToPath(import.meta.url)],
67
- { cwd, env, encoding: "utf8", timeout: 30_000 });
67
+ { cwd, env, encoding: "utf8", timeout: 120_000 });
68
68
  assert.ifError(result.error);
69
69
  assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}\nfixture: ${root}`);
70
70
  assert.match(result.stdout, /quiet=false passed/);
@@ -1766,3 +1766,51 @@ test("the production factory takes over native bash drawing through a tool rende
1766
1766
  assert.match(renderToString(call), /printf hi \(timeout 5s\)/);
1767
1767
  });
1768
1768
 
1769
+
1770
+ test("a minimal bash card titles a long or multi-line command with one summary row and expands to the whole command", (t) => {
1771
+ useCardContent(t, CARD_CONTENT.MINIMAL);
1772
+ const bash = registeredQuietTools().get("bash");
1773
+ const command = "cd /Users/me/work/project && python3 - <<'EOF'\nprint('one')\nprint('two')\nEOF";
1774
+ const rows = (expanded: boolean) => bash.renderCall({ command }, passthroughTheme, routineRenderContext({ args: { command }, isPartial: false, executionStarted: true, expanded })).render(100).map(stripAnsi);
1775
+ const collapsed = rows(false);
1776
+ const title = collapsed.filter((row) => /python3/.test(row));
1777
+ assert.equal(title.length, 1, "one row says what the command does");
1778
+ assert.match(title[0]!, /python3 - <<'EOF' … \+3 lines/, "the first line, without the cd hop, and how much is folded");
1779
+ assert.doesNotMatch(collapsed.join("\n"), /print\('one'\)|\/Users\/me\/work\/project/, "no heredoc body or working-directory hop while collapsed");
1780
+ const long = `npm run build -- --filter ${"package-".repeat(30)}`;
1781
+ const longRows = bash.renderCall({ command: long }, passthroughTheme, routineRenderContext({ args: { command: long }, isPartial: false, executionStarted: true })).render(100).map(stripAnsi);
1782
+ assert.equal(longRows.filter((row) => /npm run build/.test(row)).length, 1);
1783
+ assert.equal(longRows.filter((row) => /package-/.test(row)).length, 1, "a long single line is clipped to its row, not wrapped");
1784
+ assert.match(rows(true).join("\n"), /print\('two'\)/, "expanding shows the whole command");
1785
+ });
1786
+
1787
+ test("a collapsed minimal bash card keeps a long, multi-line or timed-out command on its top row", (t) => {
1788
+ useCardContent(t, CARD_CONTENT.MINIMAL);
1789
+ const bash = registeredQuietTools().get("bash");
1790
+ const cases: Array<[Record<string, unknown>, number[]]> = [
1791
+ [{ command: `npm run build -- --filter ${"package-".repeat(30)}` }, [40, 60, 100, 160]],
1792
+ [{ command: `npm run build -- --filter ${"package-".repeat(30)}`, timeout: 5 }, [40, 60, 100, 160]],
1793
+ [{ command: `git commit -m ${"x".repeat(200)}\nsecond\nthird` }, [40, 60, 100, 160]],
1794
+ [{ command: "cd /Users/me/work/project && python3 - <<'EOF'\nprint('one')\nprint('two')\nEOF" }, [40, 60, 100, 160]],
1795
+ [{ command: "cd /Users/me/work/project && python3 - <<'EOF'\nprint('one')\nprint('two')\nEOF", timeout: 120 }, [60, 100, 160]],
1796
+ ];
1797
+ for (const [args, widths] of cases) for (const width of widths) for (const state of [{ executionStarted: true }, { isError: true }]) {
1798
+ const rows = bash.renderCall(args, passthroughTheme, routineRenderContext({ args, isPartial: false, ...state })).render(width).map(stripAnsi).filter((row: string) => !row.startsWith("╰"));
1799
+ assert.equal(rows.length, 1, `${width} ${JSON.stringify(state)}: one top row, got ${JSON.stringify(rows)}`);
1800
+ assert.equal(visibleWidth(rows[0]!), width);
1801
+ }
1802
+ });
1803
+
1804
+ test("a finished card restored from the session history keeps its expand hint even though Pi never saw its execution start", (t) => {
1805
+ for (const level of [CARD_CONTENT.MINIMAL, CARD_CONTENT.DEFAULT]) {
1806
+ useCardContent(t, level);
1807
+ const tools = registeredQuietTools();
1808
+ for (const [name, args] of [["read", { path: "a.ts" }], ["grep", { pattern: "x", path: "." }], ["bash", { command: "node scripts/build.mjs --check && git diff --check", timeout: 30 }]] as const) {
1809
+ if (name === "bash" && level === CARD_CONTENT.DEFAULT) continue;
1810
+ const restored = tools.get(name).renderCall(args, passthroughTheme, routineRenderContext({ args, isPartial: false, executionStarted: false })).render(120).map(stripAnsi).join("\n");
1811
+ assert.match(restored, /to expand/, `${level} ${name}: a restored finished card says it expands`);
1812
+ const streaming = tools.get(name).renderCall(args, passthroughTheme, routineRenderContext({ args, isPartial: true, executionStarted: false })).render(120).map(stripAnsi).join("\n");
1813
+ assert.doesNotMatch(streaming, /to expand/, `${level} ${name}: a call still streaming has nothing to expand yet`);
1814
+ }
1815
+ }
1816
+ });