gentle-pi 3.6.0 → 4.0.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 (320) hide show
  1. package/README.md +37 -6
  2. package/assets/agents/gentle-ai-explore.md +4 -4
  3. package/assets/agents/gentle-ai-verify.md +6 -4
  4. package/assets/agents/gentle-ai-worker.md +7 -9
  5. package/assets/orchestrator-delegation.md +40 -41
  6. package/assets/orchestrator-memory.md +1 -22
  7. package/assets/orchestrator-skills.md +1 -1
  8. package/assets/orchestrator.md +12 -24
  9. package/assets/support/strict-tdd-verify.md +4 -266
  10. package/assets/support/strict-tdd.md +8 -360
  11. package/bin/gentle-shell.mjs +254 -29
  12. package/docs/delegated-verification.md +26 -1
  13. package/docs/gentle-agents-activity.md +24 -0
  14. package/docs/gentle-shell.md +95 -30
  15. package/docs/native-authority-architecture.md +2 -2
  16. package/docs/prompt-history.md +280 -0
  17. package/docs/readme-reference.md +117 -235
  18. package/docs/telemetry.md +1 -1
  19. package/docs/yolo-mode.md +86 -0
  20. package/extensions/child-context.ts +26 -0
  21. package/extensions/child-safety.ts +23 -0
  22. package/extensions/gentle-agents.ts +509 -275
  23. package/extensions/gentle-ai.ts +781 -683
  24. package/extensions/gentle-shell.ts +1375 -88
  25. package/extensions/gentle-stats.ts +101 -0
  26. package/extensions/gentle-todo.ts +18 -7
  27. package/extensions/history/atomic-write.ts +38 -0
  28. package/extensions/history/hide-prompts.ts +183 -0
  29. package/extensions/history/index.ts +1419 -0
  30. package/extensions/history/load-shared-history.ts +39 -0
  31. package/extensions/history/selector-helpers.ts +538 -0
  32. package/extensions/history/session-scan.ts +233 -0
  33. package/extensions/history/store.ts +1119 -0
  34. package/extensions/nan-provider.ts +6 -0
  35. package/extensions/quiet-tools.ts +179 -87
  36. package/extensions/resume-hint.ts +60 -0
  37. package/extensions/skill-registry.ts +16 -12
  38. package/extensions/startup-banner.ts +60 -31
  39. package/lib/agent-assets.ts +604 -0
  40. package/lib/agent-profile-pin.ts +12 -0
  41. package/lib/agents-message-delivery.ts +181 -0
  42. package/lib/agents-protocol.ts +60 -0
  43. package/lib/agents-runner.ts +105 -98
  44. package/lib/agents-view.ts +26 -3
  45. package/lib/agents-widget.ts +16 -9
  46. package/lib/append-system-prompt.ts +21 -0
  47. package/lib/bounded-writer-admission.ts +147 -0
  48. package/lib/card-style-policy.ts +60 -0
  49. package/lib/child-context-files.ts +166 -0
  50. package/lib/codemode-renderer.ts +185 -0
  51. package/lib/command-palette-catalog.ts +3 -9
  52. package/lib/command-palette.ts +25 -14
  53. package/lib/destructive-command-guard.ts +144 -0
  54. package/lib/foreign-target-grants.ts +32 -0
  55. package/lib/gentle-ai-elapsed-store.ts +87 -0
  56. package/lib/gentle-ai-renderer.ts +196 -39
  57. package/lib/gentle-shell-launcher.ts +24 -13
  58. package/lib/gentle-shell-resume-hint.ts +176 -0
  59. package/lib/history-capture-policy.ts +95 -0
  60. package/lib/model-routing-authority.ts +5 -1
  61. package/lib/nan-provider.ts +227 -0
  62. package/lib/native-review-cli.ts +53 -108
  63. package/lib/odd-phase-inference.ts +231 -0
  64. package/lib/odd-phase.ts +141 -0
  65. package/lib/overlay-repaint.ts +26 -0
  66. package/lib/pi-tui-keys.ts +53 -0
  67. package/lib/review-candidate-view-owner.ts +67 -17
  68. package/lib/review-candidate-view.ts +112 -25
  69. package/lib/review-reminder-receipt.ts +48 -8
  70. package/lib/review-risk-assessment.ts +156 -11
  71. package/lib/review-sidebar-state.ts +223 -0
  72. package/lib/selection-engine.ts +515 -0
  73. package/lib/session-change-capture.ts +10 -1
  74. package/lib/session-messaging-grants.ts +135 -0
  75. package/lib/session-worktree-registry.ts +14 -2
  76. package/lib/shell-bar.ts +179 -24
  77. package/lib/shell-card.ts +287 -18
  78. package/lib/shell-changes-view.ts +2 -1
  79. package/lib/shell-prompt.ts +102 -6
  80. package/lib/shell-sidebar-layout.ts +78 -14
  81. package/lib/shell-sidebar.ts +15 -1
  82. package/lib/shell-todo.ts +23 -13
  83. package/lib/shell-usage-view.ts +9 -4
  84. package/lib/shell-usage.ts +66 -10
  85. package/lib/stats-collector.ts +381 -0
  86. package/lib/stats-view.ts +431 -0
  87. package/lib/theme-customization.ts +52 -0
  88. package/lib/vim-editor-adapter.ts +379 -0
  89. package/lib/vim-normal-engine.ts +154 -0
  90. package/lib/vim-operator-engine.ts +416 -0
  91. package/lib/vim-policy.ts +49 -0
  92. package/lib/vim-visual-engine.ts +107 -0
  93. package/lib/visual-customization-policy.ts +108 -0
  94. package/lib/visual-customize-view.ts +330 -0
  95. package/lib/visual-profiles.ts +228 -0
  96. package/lib/yolo-session-policy.ts +240 -0
  97. package/package.json +20 -8
  98. package/runtime/gentle-shell-launcher.mjs +23 -12
  99. package/runtime/gentle-shell-resume-hint.mjs +177 -0
  100. package/runtime/native-review-cli.mjs +53 -108
  101. package/runtime/review-risk-assessment.mjs +154 -9
  102. package/scripts/build-runtime-modules.mjs +1 -0
  103. package/scripts/gentle-ai-installer.mjs +14 -13
  104. package/scripts/mirror-odd-routing.mjs +2 -2
  105. package/scripts/run-test-suite.mjs +76 -0
  106. package/scripts/test-packed-runner.mjs +31 -14
  107. package/scripts/verify-package-files.mjs +11 -22
  108. package/skills/branch-pr/SKILL.md +24 -52
  109. package/skills/chained-pr/SKILL.md +31 -15
  110. package/skills/chained-pr/references/chaining-details.md +31 -20
  111. package/skills/gentle-ai/SKILL.md +9 -15
  112. package/skills/issue-creation/SKILL.md +8 -2
  113. package/skills/issue-creation/references/delegated-workflow-actions.md +19 -0
  114. package/skills/work-unit-commits/SKILL.md +4 -3
  115. package/tests/agent-profiles.test.ts +18 -0
  116. package/tests/agents-fake-child.ts +2 -2
  117. package/tests/agents-message-delivery.test.ts +106 -0
  118. package/tests/agents-protocol.test.ts +40 -0
  119. package/tests/agents-runner.test.ts +400 -89
  120. package/tests/agents-view-thread-identity.test.ts +169 -0
  121. package/tests/agents-view.test.ts +8 -2
  122. package/tests/agents-widget.test.ts +154 -15
  123. package/tests/append-system-prompt-route.test.ts +160 -0
  124. package/tests/append-system-prompt.test.ts +46 -0
  125. package/tests/artifact-language.test.ts +19 -213
  126. package/tests/ask-user-question.test.ts +44 -1
  127. package/tests/asset-installation-runtime.test.ts +5 -16
  128. package/tests/autonomous-guard.test.ts +69 -1
  129. package/tests/bounded-writer-admission.test.ts +95 -0
  130. package/tests/branch-pr-skill.test.ts +43 -0
  131. package/tests/card-style-policy.test.ts +55 -0
  132. package/tests/chained-pr-skill.test.ts +124 -0
  133. package/tests/child-context-files.test.ts +255 -0
  134. package/tests/child-safety.test.ts +82 -0
  135. package/tests/codemode-rendering.test.ts +491 -0
  136. package/tests/command-palette.test.ts +39 -3
  137. package/tests/delegated-key-learnings-contract.test.ts +0 -76
  138. package/tests/destructive-command-guard.test.ts +84 -0
  139. package/tests/devbinary/native-review-parity.devtest.ts +170 -2
  140. package/tests/devbinary/non-git-subagent-bootstrap.devtest.ts +193 -0
  141. package/tests/fixtures/stats/sessions/--work-alpha--/2026-09-28T10-00-00-000Z_aaa.jsonl +7 -0
  142. package/tests/fixtures/stats/sessions/--work-alpha--/2026-09-29T23-00-00-000Z_bbb.jsonl +3 -0
  143. package/tests/fixtures/stats/sessions/--work-alpha--/2026-09-30T08-00-00-000Z_ddd.jsonl +2 -0
  144. package/tests/fixtures/stats/sessions/--work-alpha--/2026-09-30T09-00-00-000Z_eee.jsonl +3 -0
  145. package/tests/fixtures/stats/sessions/--work-alpha--/run-1/session.jsonl +2 -0
  146. package/tests/fixtures/stats/sessions/--work-beta--/2026-09-01T12-00-00-000Z_ccc.jsonl +2 -0
  147. package/tests/fixtures/stats/user-pi/sessions/--work-alpha--/2026-09-28T10-00-00-000Z_aaa.jsonl +2 -0
  148. package/tests/fixtures/stats/user-pi/sessions/--work-alpha--/2026-09-29T23-00-00-000Z_bbb.jsonl +4 -0
  149. package/tests/fixtures/stats/user-pi/sessions/--work-gamma--/2026-09-20T09-00-00-000Z_fff.jsonl +3 -0
  150. package/tests/foreign-target-grants.test.ts +58 -0
  151. package/tests/generic-agent-tools.test.ts +54 -0
  152. package/tests/gentle-agents.test.ts +1411 -256
  153. package/tests/gentle-ai-binary.test.ts +3 -3
  154. package/tests/gentle-ai-elapsed-store.test.ts +68 -0
  155. package/tests/gentle-ai-installer.test.ts +68 -54
  156. package/tests/gentle-ai-renderer.test.ts +487 -8
  157. package/tests/gentle-ai.test.ts +288 -65
  158. package/tests/gentle-card-text.ts +2 -1
  159. package/tests/gentle-shell-bin.test.ts +651 -114
  160. package/tests/gentle-shell-launcher.test.ts +99 -52
  161. package/tests/gentle-shell-resume-hint.test.ts +270 -0
  162. package/tests/gentle-shell.test.ts +3839 -187
  163. package/tests/gentle-stats.test.ts +152 -0
  164. package/tests/gentle-theme.test.ts +4 -1
  165. package/tests/gentle-todo.test.ts +80 -8
  166. package/tests/history-atomic-write.test.ts +57 -0
  167. package/tests/history-capture-policy.test.ts +102 -0
  168. package/tests/history-command-registration.test.ts +164 -0
  169. package/tests/history-dedupe-entries.test.ts +123 -0
  170. package/tests/history-delete-backfill.test.ts +190 -0
  171. package/tests/history-delete-confirm.test.ts +460 -0
  172. package/tests/history-dispatch.test.ts +180 -0
  173. package/tests/history-drain-hidden.test.ts +110 -0
  174. package/tests/history-drain-order.test.ts +98 -0
  175. package/tests/history-expanded-globals.test.ts +62 -0
  176. package/tests/history-gc.test.ts +832 -0
  177. package/tests/history-header-layout.test.ts +265 -0
  178. package/tests/history-hide-prompts.test.ts +275 -0
  179. package/tests/history-lazy-windowing.test.ts +508 -0
  180. package/tests/history-legacy-migrate-v2.test.ts +297 -0
  181. package/tests/history-load-shared-history.test.ts +53 -0
  182. package/tests/history-max-results-cap.test.ts +76 -0
  183. package/tests/history-multi-reader.test.ts +203 -0
  184. package/tests/history-off-path.test.ts +170 -0
  185. package/tests/history-openflow-integration.test.ts +173 -0
  186. package/tests/history-overlay-margin.test.ts +326 -0
  187. package/tests/history-preview-layout.test.ts +93 -0
  188. package/tests/history-registry.test.ts +143 -0
  189. package/tests/history-scope-delete.test.ts +411 -0
  190. package/tests/history-search-caret-keys.test.ts +142 -0
  191. package/tests/history-seed-bootstrap.test.ts +170 -0
  192. package/tests/history-seed-regen.test.ts +129 -0
  193. package/tests/history-selector-windowing.test.ts +94 -0
  194. package/tests/history-session-scan-directory.test.ts +87 -0
  195. package/tests/history-session-scan-extract.test.ts +583 -0
  196. package/tests/history-session-writer.test.ts +351 -0
  197. package/tests/history-store-paths.test.ts +79 -0
  198. package/tests/history-tombstone-exact.test.ts +139 -0
  199. package/tests/history-wheel-mouse.test.ts +242 -0
  200. package/tests/inprocess-reviewer.test.ts +29 -19
  201. package/tests/issue-creation-skill.test.ts +61 -0
  202. package/tests/model-routing-authority.test.ts +16 -0
  203. package/tests/nan-provider.test.ts +471 -0
  204. package/tests/native-review-capability-contract.test.ts +13 -1
  205. package/tests/native-review-cli.test.ts +6 -120
  206. package/tests/native-review-parity-runtime.test.ts +100 -3
  207. package/tests/odd-integration.test.ts +67 -0
  208. package/tests/odd-phase-inference.test.ts +213 -0
  209. package/tests/odd-phase-loader.test.ts +253 -0
  210. package/tests/odd-phase.test.ts +307 -0
  211. package/tests/odd-routing-canonical-ratchet.test.ts +11 -6
  212. package/tests/odd-routing-contract.test.ts +86 -35
  213. package/tests/orchestrator-budget.test.ts +14 -39
  214. package/tests/orchestrator-rdd-ownership.test.ts +3 -3
  215. package/tests/overlay-repaint.test.ts +74 -0
  216. package/tests/package-manifest.test.ts +252 -115
  217. package/tests/packed-runner-owned-path.test.ts +46 -0
  218. package/tests/persona-single-channel.test.ts +6 -6
  219. package/tests/provider-defect-handoff.test.ts +3 -11
  220. package/tests/quiet-bash-runtime.test.ts +76 -0
  221. package/tests/quiet-tool-rendering.test.ts +409 -184
  222. package/tests/rdd-aware-verification-contract.test.ts +76 -1
  223. package/tests/rdd-status-line.test.ts +9 -4
  224. package/tests/resume-hint-extension.test.ts +122 -0
  225. package/tests/review-agent-end-preflight.test.ts +176 -12
  226. package/tests/review-candidate-owner-retry.test.ts +22 -1
  227. package/tests/review-candidate-view.test.ts +298 -0
  228. package/tests/review-contract-prompt.test.ts +108 -43
  229. package/tests/review-controller-lock-status.test.ts +0 -1
  230. package/tests/review-controller-native-routing.test.ts +611 -5
  231. package/tests/review-controller-workspace-root.test.ts +163 -4
  232. package/tests/review-host-relay-routing.test.ts +338 -2
  233. package/tests/review-integration-v2-forward.test.ts +200 -0
  234. package/tests/review-ledger-contract.test.ts +10 -34
  235. package/tests/review-reminder-receipt.test.ts +47 -1
  236. package/tests/review-risk-assessment.test.ts +498 -6
  237. package/tests/review-sidebar-state.test.ts +402 -0
  238. package/tests/run-test-suite.test.ts +124 -0
  239. package/tests/runtime-harness.mjs +145 -786
  240. package/tests/runtime-metrics-children.test.ts +16 -23
  241. package/tests/selection-engine.test.ts +421 -0
  242. package/tests/session-change-capture.test.ts +12 -1
  243. package/tests/session-messaging-grants.test.ts +255 -0
  244. package/tests/session-worktree-registry.test.ts +77 -0
  245. package/tests/shell-bar.test.ts +382 -1
  246. package/tests/shell-card.test.ts +353 -1
  247. package/tests/shell-changes-view.test.ts +52 -0
  248. package/tests/shell-prompt.test.ts +94 -2
  249. package/tests/shell-sidebar-layout.test.ts +325 -21
  250. package/tests/shell-sidebar-scroll-benchmark.test.ts +255 -0
  251. package/tests/shell-todo.test.ts +87 -1
  252. package/tests/shell-usage-view.test.ts +27 -0
  253. package/tests/shell-usage.test.ts +73 -0
  254. package/tests/skill-registry.test.ts +50 -1
  255. package/tests/startup-banner.test.ts +130 -2
  256. package/tests/stats-collector.test.ts +195 -0
  257. package/tests/stats-view.test.ts +202 -0
  258. package/tests/telemetry-trigger.test.ts +81 -20
  259. package/tests/theme-customization.test.ts +72 -0
  260. package/tests/vim-editor-adapter-host-resolution.test.ts +37 -0
  261. package/tests/vim-editor-adapter.test.ts +804 -0
  262. package/tests/vim-normal-engine.test.ts +101 -0
  263. package/tests/vim-operator-engine.test.ts +215 -0
  264. package/tests/vim-policy.test.ts +19 -0
  265. package/tests/vim-visual-engine.test.ts +52 -0
  266. package/tests/visual-customization-policy.test.ts +110 -0
  267. package/tests/visual-customize-view.test.ts +418 -0
  268. package/tests/visual-profiles.test.ts +87 -0
  269. package/tests/yolo-customize.test.ts +256 -0
  270. package/tests/yolo-mode-runtime.test.ts +161 -0
  271. package/tests/yolo-mode.test.ts +261 -0
  272. package/tests/yolo-session-policy.test.ts +59 -0
  273. package/themes/Gentle.json +2 -1
  274. package/themes/Gentleman-Cute.json +2 -1
  275. package/themes/Gentleman-Sexy.json +2 -1
  276. package/assets/agents/sdd-apply.md +0 -159
  277. package/assets/agents/sdd-archive.md +0 -228
  278. package/assets/agents/sdd-design.md +0 -49
  279. package/assets/agents/sdd-explore.md +0 -48
  280. package/assets/agents/sdd-init.md +0 -56
  281. package/assets/agents/sdd-onboard.md +0 -52
  282. package/assets/agents/sdd-proposal.md +0 -64
  283. package/assets/agents/sdd-remediate.md +0 -37
  284. package/assets/agents/sdd-research.md +0 -49
  285. package/assets/agents/sdd-spec.md +0 -192
  286. package/assets/agents/sdd-status.md +0 -54
  287. package/assets/agents/sdd-tasks.md +0 -108
  288. package/assets/agents/sdd-verify.md +0 -124
  289. package/assets/chains/sdd-full.chain.md +0 -83
  290. package/assets/chains/sdd-plan.chain.md +0 -56
  291. package/assets/chains/sdd-verify.chain.md +0 -43
  292. package/assets/sdd-orchestrator-workflow.md +0 -319
  293. package/assets/support/sdd-status-contract.md +0 -77
  294. package/docs/assets/diagrams/sdd-cycle.svg +0 -14
  295. package/extensions/sdd-init.ts +0 -816
  296. package/lib/openspec-deltas.ts +0 -156
  297. package/lib/sdd-preflight.ts +0 -1066
  298. package/lib/sdd-research-capabilities.ts +0 -94
  299. package/lib/sdd-status.ts +0 -26
  300. package/tests/fixtures/legacy/sdd-research-v2.5.0.md +0 -54
  301. package/tests/fixtures/native-review-cli/v2.1.3/bind-sdd.json +0 -25
  302. package/tests/fixtures/v0.10.7/assets/agents/sdd-apply.md +0 -132
  303. package/tests/openspec-deltas.test.ts +0 -209
  304. package/tests/sdd-agent-tools.test.ts +0 -156
  305. package/tests/sdd-archive-replay.test.ts +0 -82
  306. package/tests/sdd-classical-continuation.test.ts +0 -74
  307. package/tests/sdd-execution-routing-contract.test.ts +0 -44
  308. package/tests/sdd-managed-runtime-settlement.test.ts +0 -155
  309. package/tests/sdd-native-managed-uptake.test.ts +0 -243
  310. package/tests/sdd-no-attempts-contract.test.ts +0 -15
  311. package/tests/sdd-odd-integration.test.ts +0 -33
  312. package/tests/sdd-optional-research.test.ts +0 -124
  313. package/tests/sdd-planning-routing-contract.test.ts +0 -45
  314. package/tests/sdd-preflight-rpc-input.test.ts +0 -125
  315. package/tests/sdd-preflight.test.ts +0 -541
  316. package/tests/sdd-research-capabilities.test.ts +0 -114
  317. package/tests/sdd-research-live.test.ts +0 -241
  318. package/tests/sdd-selection-transport.test.ts +0 -653
  319. package/tests/sdd-status.test.ts +0 -9
  320. package/tests/sdd-task-truth.test.ts +0 -43
@@ -1,17 +1,39 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { execFileSync, execFile } from "node:child_process";
3
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import { createRequire } from "node:module";
4
5
  import { tmpdir } from "node:os";
5
6
  import { join } from "node:path";
6
- import test from "node:test";
7
+ import test, { after } from "node:test";
7
8
  import { initTheme, type ExtensionAPI, type ExtensionContext, type SlashCommandInfo, type SourceInfo } from "@earendil-works/pi-coding-agent";
8
- import type { TUI, TuiMouseEvent } from "@earendil-works/pi-tui";
9
- import installGentleShell, { buildShellBarModel, createActiveProfileReader, changesShortcut, devBinaryCard, extractQueuedText, fetchCodexUsage, fetchNanUsage, loadFileDiff, shellGitRunner, openInExternalEditor, usageShortcut, type GentlePromptEditor } from "../extensions/gentle-shell.ts";
10
- import { USAGE_SOURCE_EVENT, USAGE_SOURCE_SCHEMA } from "../lib/shell-usage.ts";
9
+ import { CURSOR_MARKER, visibleWidth, type TUI, type TuiMouseEvent } from "@earendil-works/pi-tui";
10
+ import installGentleShell, { buildShellBarModel, createActiveProfileReader, changesShortcut, devBinaryCard, extractQueuedText, fetchCodexUsage, fetchNanUsage, loadFileDiff, shellGitRunner, openInExternalEditor, usageShortcut, GentlePromptEditor } from "../extensions/gentle-shell.ts";
11
+ import { CODEX_USAGE_URL, NAN_QUOTA_URL, USAGE_SOURCE_EVENT, USAGE_SOURCE_SCHEMA } from "../lib/shell-usage.ts";
12
+ import { createVimEditorAdapter } from "../lib/vim-editor-adapter.ts";
13
+ import { buildCommandPaletteGroups } from "../lib/command-palette-catalog.ts";
11
14
  import { CHANGE_STATUS } from "../lib/shell-changes.ts";
12
- import { sidebarState, type SidebarRail } from "../lib/shell-sidebar.ts";
15
+ import { sidebarPart, sidebarState, type SidebarRail } from "../lib/shell-sidebar.ts";
16
+ import { renderTodoCard } from "../lib/shell-todo.ts";
13
17
  import type { ShellBarTheme } from "../lib/shell-bar.ts";
14
18
  import { stripAnsi } from "../lib/terminal-theme.ts";
19
+ import { createGentleAiExtension } from "../extensions/gentle-ai.ts";
20
+ import { decodeReviewStatusV3 } from "../lib/review-integration-v2.ts";
21
+ import { REVIEW_SIDEBAR_EVENT } from "../lib/review-sidebar-state.ts";
22
+ import type { NativeReviewCli } from "../lib/native-review-cli.ts";
23
+ import { resolveVisualSettings, writeVisualSettings } from "../lib/visual-customization-policy.ts";
24
+ import { resolveAnimationPolicy } from "../lib/animation-policy.ts";
25
+ import { resolveVimPolicy, writeVimPolicy } from "../lib/vim-policy.ts";
26
+ import { resolveHistoryCapturePolicy, writeHistoryCapturePolicy } from "../lib/history-capture-policy.ts";
27
+ import { readBannerConfig } from "../extensions/startup-banner.ts";
28
+ import { listVisualProfiles, saveVisualProfile } from "../lib/visual-profiles.ts";
29
+ import { oddPhaseRegistry } from "../lib/odd-phase.ts";
30
+ import { CARD_STYLE, cardStyle, setCardStyle } from "../lib/shell-card.ts";
31
+ import { resolveCardStyle, writeCardStyle } from "../lib/card-style-policy.ts";
32
+
33
+
34
+ // Vim fixtures claim the installed pi-tui release, which the adapter gate
35
+ // verifies against imported metadata; the open devDependency range is policy.
36
+ const INSTALLED_PI = (createRequire(import.meta.url)("@earendil-works/pi-tui/package.json") as { version: string }).version;
15
37
 
16
38
  // The Gentle Shell extension wires the pure bar renderer into pi's footer
17
39
  // slot. These tests drive it with a fake ExtensionAPI and context.
@@ -19,7 +41,18 @@ import { stripAnsi } from "../lib/terminal-theme.ts";
19
41
  initTheme("dark");
20
42
 
21
43
  const resolveWorktree = (path: string) => ({ root: path.startsWith("/repo") || path === "." ? "/repo" : path, commonDir: "/clone/git" });
22
- const gentleShell: typeof installGentleShell = (pi, env, deps) => installGentleShell(pi, env, { resolveWorktree, gitRunner: (cwd) => async (args) => pi.exec("git", ["-C", cwd, ...args], { timeout: 5000 }), ...deps });
44
+ // Without GENTLE_PI_CONFIG_HOME the extension reads ~/.pi/gentle-ai, so a
45
+ // developer's persisted preferences (for example /gentle:vim on) would leak into
46
+ // tests. Each instance gets a fresh empty config home unless the test owns one.
47
+ const isolatedConfigHomes: string[] = [];
48
+ after(() => { for (const home of isolatedConfigHomes) rmSync(home, { recursive: true, force: true }); });
49
+ function isolatedEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
50
+ if (env.GENTLE_PI_CONFIG_HOME !== undefined) return env;
51
+ const home = mkdtempSync(join(tmpdir(), "gentle-shell-config-"));
52
+ isolatedConfigHomes.push(home);
53
+ return { ...env, GENTLE_PI_CONFIG_HOME: home };
54
+ }
55
+ const gentleShell: typeof installGentleShell = (pi, env, deps) => installGentleShell(pi, isolatedEnv(env), { resolveWorktree, gitRunner: (cwd) => async (args) => pi.exec("git", ["-C", cwd, ...args], { timeout: 5000 }), ...deps });
23
56
 
24
57
  const plainTheme = {
25
58
  fg(_color: string, value: string) {
@@ -137,6 +170,7 @@ function fakeContext(options: { hasUI?: boolean; entries?: unknown[]; oauth?: bo
137
170
  const entries = options.entries ?? [];
138
171
  const ctx = {
139
172
  hasUI: options.hasUI ?? true,
173
+ mode: "tui",
140
174
  hasPendingMessages: () => options.pending ?? false,
141
175
  isIdle: () => options.idle ?? true,
142
176
  cwd: "/repo",
@@ -151,6 +185,9 @@ function fakeContext(options: { hasUI?: boolean; entries?: unknown[]; oauth?: bo
151
185
  getContextUsage: () => ({ tokens: 122_400, contextWindow: 272_000, percent: 45 }),
152
186
  ui: {
153
187
  theme: plainTheme,
188
+ getAllThemes: () => [{ name: "dark", path: undefined }, { name: "light", path: undefined }],
189
+ getTheme: (name: string) => name === "dark" || name === "light" ? { name } : undefined,
190
+ setTheme: (name: string) => ({ success: name === "dark" || name === "light" }),
154
191
  // Added only when requested: an absent select keeps the no-menu fallback
155
192
  // that every pre-existing test relies on.
156
193
  ...(options.select ? { select: options.select } : {}),
@@ -182,7 +219,9 @@ function fakeContext(options: { hasUI?: boolean; entries?: unknown[]; oauth?: bo
182
219
  ui.overlay = factory;
183
220
  return new Promise<T | null>((resolve) => {
184
221
  ui.closeOverlay = () => resolve(null);
185
- ui.overlayView = factory(fakeTui, plainTheme, fakeKeybindings, (value: T) => resolve(value));
222
+ // An identity bg mock hides focused rows; omit it so overlay navigation
223
+ // remains inspectable through Commands' ▸ fallback.
224
+ ui.overlayView = factory(fakeTui, { ...plainTheme, bg: undefined }, fakeKeybindings, (value: T) => resolve(value));
186
225
  resolveOverlay();
187
226
  });
188
227
  },
@@ -259,6 +298,138 @@ test("gentleShell installs the footer on session_start when a UI exists", () =>
259
298
  assert.match(lines[0], /main ⟡ gpt-5\.5 · medium/);
260
299
  });
261
300
 
301
+ async function reviewSidebarHarness() {
302
+ const { pi, handlers, tools } = fakePi();
303
+ gentleShell(pi, { GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, { activeProfile: () => undefined });
304
+ const { ctx, ui } = fakeContext();
305
+ ctx.cwd = process.cwd();
306
+ let sessionId = "shell-session";
307
+ ctx.sessionManager.getSessionId = () => sessionId;
308
+ const raw = JSON.parse(readFileSync(new URL("./fixtures/devbinary/status-v5-capture-result-submission.captured.json", import.meta.url), "utf8"));
309
+ raw.action = "stop";
310
+ raw.projection.paths = ["src/fresh.ts"];
311
+ const status = decodeReviewStatusV3(raw);
312
+ // Each hold() parks the next native status call until the returned release runs.
313
+ const held: Array<(release: (result: typeof status) => void) => void> = [];
314
+ const native = { targetStatus: async () => {
315
+ const park = held.shift();
316
+ return park ? new Promise<typeof status>((resolve) => park(resolve)) : status;
317
+ } } as unknown as NativeReviewCli;
318
+ const hold = () => {
319
+ let release!: () => void;
320
+ held.push((resolve) => { release = () => resolve(status); });
321
+ return () => release();
322
+ };
323
+ const published: unknown[] = [];
324
+ const bus = pi.events;
325
+ const observedPi = { ...pi, events: {
326
+ ...bus,
327
+ emit(name: string, value: unknown) {
328
+ if (name === REVIEW_SIDEBAR_EVENT) published.push(value);
329
+ bus.emit(name, value);
330
+ },
331
+ } } as ExtensionAPI;
332
+ const producerHooks = new Map<string, Array<(event: unknown, context: ExtensionContext) => unknown>>();
333
+ createGentleAiExtension({ nativeReviewCli: native, candidateViews: null, processEnv: {} })({
334
+ ...observedPi,
335
+ on(name: string, handler: (event: unknown, context: ExtensionContext) => unknown) {
336
+ producerHooks.set(name, [...(producerHooks.get(name) ?? []), handler]);
337
+ },
338
+ } as ExtensionAPI);
339
+ const produce = async (name: string, event: unknown = {}) => {
340
+ for (const hook of producerHooks.get(name) ?? []) await hook(event, ctx);
341
+ };
342
+ await fire(handlers, "session_start", ctx);
343
+ await produce("session_start");
344
+ const tui = { terminal: { rows: 40, columns: 160 }, requestRender() {} };
345
+ const factory = ui.footerFactory as (tui: unknown, theme: ShellBarTheme, footerData: unknown) => { dispose(): void };
346
+ const component = factory(tui, plainTheme, { getGitBranch: () => "main", getExtensionStatuses: () => new Map(), getAvailableProviderCount: () => 1, onBranchChange: () => () => {} });
347
+ const rail = sidebarState(tui as unknown as TUI).parts.get("footer") as SidebarRail;
348
+ return {
349
+ pi,
350
+ rail,
351
+ published,
352
+ hold,
353
+ text: () => rail.render(60).join("\n"),
354
+ sessionId: () => sessionId,
355
+ run: () => tools.get("gentle_review")!.execute("reset-test", { operation: "status", lineageId: status.authority!.lineageId }, undefined, undefined, ctx),
356
+ async startSession(next: string) {
357
+ sessionId = next;
358
+ await fire(handlers, "session_start", ctx);
359
+ await produce("session_start");
360
+ },
361
+ async navigateTree() {
362
+ await fire(handlers, "session_tree", ctx);
363
+ await produce("session_tree");
364
+ },
365
+ shutdownShell: () => fire(handlers, "session_shutdown", ctx),
366
+ async dispose() {
367
+ await produce("session_shutdown", { reason: "quit" });
368
+ await fire(handlers, "session_shutdown", ctx);
369
+ component.dispose();
370
+ },
371
+ };
372
+ }
373
+
374
+ test("review sidebar ignores a stale completion after session_start and accepts the new session", async () => {
375
+ const harness = await reviewSidebarHarness();
376
+ try {
377
+ const release = harness.hold();
378
+ const pending = harness.run();
379
+ assert.match(harness.text(), /Updating…/);
380
+ await harness.startSession("next-session");
381
+ assert.doesNotMatch(harness.text(), /RDD/);
382
+ const before = harness.published.length;
383
+ release();
384
+ await pending;
385
+ assert.equal(harness.published.length, before, "producer must not publish the old session completion");
386
+ assert.doesNotMatch(harness.text(), /RDD/, "old completion must not repaint the new session");
387
+ await harness.run();
388
+ assert.match(harness.text(), /fresh\.ts/, "a fresh result in the new session is accepted");
389
+ } finally {
390
+ await harness.dispose();
391
+ }
392
+ });
393
+
394
+ test("review sidebar ignores a stale completion after same-session tree navigation", async () => {
395
+ const harness = await reviewSidebarHarness();
396
+ try {
397
+ await harness.run();
398
+ assert.match(harness.text(), /fresh\.ts/);
399
+ const release = harness.hold();
400
+ const pending = harness.run();
401
+ assert.match(harness.text(), /Updating…/);
402
+ await harness.navigateTree();
403
+ assert.doesNotMatch(harness.text(), /RDD/, "tree navigation clears the visible snapshot");
404
+ const before = harness.published.length;
405
+ release();
406
+ await pending;
407
+ assert.equal(harness.published.length, before, "producer must not publish the old tree completion with the same session ID");
408
+ assert.doesNotMatch(harness.text(), /RDD/);
409
+ await harness.run();
410
+ assert.match(harness.text(), /fresh\.ts/, "a fresh tree-bound result is accepted");
411
+ } finally {
412
+ await harness.dispose();
413
+ }
414
+ });
415
+
416
+ test("review sidebar rejects foreign-session events and unsubscribes on shutdown", async () => {
417
+ const harness = await reviewSidebarHarness();
418
+ try {
419
+ await harness.run();
420
+ assert.match(harness.text(), /fresh\.ts/);
421
+ const previous = harness.rail.digest?.();
422
+ harness.pi.events.emit(REVIEW_SIDEBAR_EVENT, { sessionId: "foreign", snapshot: { state: "closed", scope: "foreign.ts" } });
423
+ assert.equal(harness.rail.digest?.(), previous, "foreign events cannot replace the current snapshot");
424
+ await harness.shutdownShell();
425
+ assert.doesNotMatch(harness.text(), /RDD/);
426
+ harness.pi.events.emit(REVIEW_SIDEBAR_EVENT, { sessionId: harness.sessionId(), snapshot: { state: "closed", scope: "late.ts" } });
427
+ assert.doesNotMatch(harness.text(), /RDD/, "shutdown unsubscribes the consumer");
428
+ } finally {
429
+ await harness.dispose();
430
+ }
431
+ });
432
+
262
433
  test("the fullscreen Status rail carries a live digest so a profile switch refreshes it", async () => {
263
434
  const { pi, handlers } = fakePi();
264
435
  let profile: string | undefined = "team";
@@ -396,6 +567,109 @@ test("profile reader follows store changes and rejects missing or invalid active
396
567
  assert.equal(read(), undefined);
397
568
  });
398
569
 
570
+ test("bound profile reader follows pin precedence and keeps frames free of resolution", (t) => {
571
+ const home = mkdtempSync(join(tmpdir(), "shell-effective-"));
572
+ t.after(() => rmSync(home, { recursive: true, force: true }));
573
+ const repo = join(home, "repo");
574
+ const commonDir = join(home, "git");
575
+ const local = join(commonDir, "gentle-ai", "profile-pin.json");
576
+ const shared = join(repo, ".pi", "gentle-ai", "profile.json");
577
+ mkdirSync(join(commonDir, "gentle-ai"), { recursive: true });
578
+ mkdirSync(join(repo, ".pi", "gentle-ai"), { recursive: true });
579
+ writeFileSync(join(home, "profiles.json"), JSON.stringify({ kind: "gentle-pi.agent_model_profiles", version: 1, active: "team", profiles: { team: {}, other: {} } }));
580
+ const pin = (path: string, profile: string) => writeFileSync(path, JSON.stringify({ kind: "gentle-pi.agent_model_profile_pin", version: 1, profile }));
581
+ const read = createActiveProfileReader({ GENTLE_PI_CONFIG_HOME: home });
582
+ let resolutions = 0;
583
+ const resolver = () => { resolutions++; return { root: repo, commonDir }; };
584
+ assert.equal(read(), "team");
585
+ read.bind(repo, resolver);
586
+ assert.equal(read(), "team");
587
+ pin(shared, "other");
588
+ assert.equal(read(), "team", "edits wait for a refresh");
589
+ assert.equal(read.refresh(), true);
590
+ assert.equal(read(), "other (repo)");
591
+ pin(local, "other");
592
+ assert.equal(read.refresh(), true, "same name with a different source changes the display");
593
+ assert.equal(read(), "other (local)");
594
+ for (let i = 0; i < 20; i++) assert.equal(read(), "other (local)");
595
+ assert.equal(resolutions, 1, "bound frames and polls reuse the worktree identity");
596
+ pin(local, "stale");
597
+ assert.equal(read.refresh(), true);
598
+ assert.equal(read(), "other (repo)");
599
+ writeFileSync(shared, "invalid");
600
+ assert.equal(read.refresh(), true);
601
+ assert.equal(read(), "team");
602
+ read.reset();
603
+ assert.equal(read(), "team");
604
+ assert.equal(read.refresh(), false);
605
+ });
606
+
607
+ test("profile polling refreshes both fullscreen surfaces only on change and stops across sessions", async (t) => {
608
+ const home = mkdtempSync(join(tmpdir(), "shell-poll-"));
609
+ t.after(() => rmSync(home, { recursive: true, force: true }));
610
+ const repo = join(home, "repo");
611
+ const commonDir = join(home, "git");
612
+ const local = join(commonDir, "gentle-ai", "profile-pin.json");
613
+ mkdirSync(join(commonDir, "gentle-ai"), { recursive: true });
614
+ mkdirSync(repo);
615
+ writeFileSync(join(home, "profiles.json"), JSON.stringify({ kind: "gentle-pi.agent_model_profiles", version: 1, active: "team", profiles: { team: {}, other: {} } }));
616
+ const intervals: Array<{ tick: () => void; delay: number; stopped: boolean }> = [];
617
+ t.mock.method(globalThis, "setInterval", (tick: () => void, delay: number) => {
618
+ const timer = { tick, delay, stopped: false };
619
+ intervals.push(timer);
620
+ return { unref() {}, timer };
621
+ });
622
+ t.mock.method(globalThis, "clearInterval", (handle: { timer: (typeof intervals)[number] }) => { handle.timer.stopped = true; });
623
+ const { pi, handlers } = fakePi();
624
+ let resolutions = 0;
625
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, {
626
+ resolveWorktree: () => { resolutions++; return { root: repo, commonDir }; },
627
+ });
628
+ const first = fakeContext();
629
+ await fire(handlers, "session_start", first.ctx);
630
+ const tui = { terminal: { rows: 40, columns: 160 }, requestRender: t.mock.fn() };
631
+ const footerData = { getGitBranch: () => "main", getExtensionStatuses: () => new Map(), getAvailableProviderCount: () => 1, onBranchChange: () => () => {} };
632
+ const factory = first.ui.footerFactory as (tui: unknown, theme: ShellBarTheme, data: unknown) => { dispose(): void };
633
+ const component = factory(tui, plainTheme, footerData);
634
+ const state = sidebarState(tui as unknown as TUI);
635
+ const status = () => (state.parts.get("footer") as SidebarRail).render(60).join("\n");
636
+ const header = () => (state.parts.get("header") as SidebarRail).render(160).join("\n");
637
+ try {
638
+ const timer = intervals.find((entry) => entry.delay === 2000);
639
+ assert.ok(timer, "UI session installs the 2000ms profile refresh");
640
+ assert.match(status(), /Profile.*team/);
641
+ assert.match(header(), /team/);
642
+ const before = tui.requestRender.mock.callCount();
643
+ timer.tick();
644
+ assert.equal(tui.requestRender.mock.callCount(), before, "unchanged poll does not render");
645
+ writeFileSync(local, JSON.stringify({ kind: "gentle-pi.agent_model_profile_pin", version: 1, profile: "other" }));
646
+ assert.match(status(), /Profile.*team/, "external edits do not read during render");
647
+ timer.tick();
648
+ assert.equal(tui.requestRender.mock.callCount(), before + 1);
649
+ assert.match(status(), /Profile.*other \(local\)/);
650
+ assert.match(header(), /other \(local\)/);
651
+ timer.tick();
652
+ assert.equal(tui.requestRender.mock.callCount(), before + 1);
653
+ const afterBind = resolutions;
654
+ status(); header(); timer.tick();
655
+ assert.equal(resolutions, afterBind, "poll and render reuse the session Git identity");
656
+ const second = fakeContext();
657
+ await fire(handlers, "session_start", second.ctx);
658
+ assert.equal(timer.stopped, true);
659
+ const replacement = intervals.filter((entry) => entry.delay === 2000).at(-1)!;
660
+ assert.notEqual(replacement, timer);
661
+ writeFileSync(local, "invalid");
662
+ timer.tick();
663
+ assert.equal(tui.requestRender.mock.callCount(), before + 1, "old session cannot repaint");
664
+ await fire(handlers, "session_shutdown", second.ctx);
665
+ assert.equal(replacement.stopped, true);
666
+ replacement.tick();
667
+ assert.equal(tui.requestRender.mock.callCount(), before + 1);
668
+ } finally {
669
+ component.dispose();
670
+ }
671
+ });
672
+
399
673
  test("gentleShell stays out of the way without a UI or when disabled", () => {
400
674
  const disabled = fakePi();
401
675
  gentleShell(disabled.pi, { GENTLE_PI_SHELL: "0" });
@@ -424,6 +698,44 @@ function installedPrompt(
424
698
  return factory(fakeTui, editorTheme, keybindings);
425
699
  }
426
700
 
701
+ interface MutablePromptThemeHost {
702
+ theme: ExtensionContext["ui"]["theme"];
703
+ }
704
+
705
+ test("T2 float prompt installed editor reads live toolSuccessBg and preserves Esc/queued hints", () => {
706
+ const previous = cardStyle();
707
+ const { pi, handlers } = fakePi();
708
+ gentleShell(pi, { GENTLE_PI_DOUBLE_ESC_CANCEL: "on" });
709
+ const { ctx, ui } = fakeContext({ pending: true });
710
+ const editor = installedPrompt(ctx, ui, handlers, { matches: (data: string, action: string) => action === "app.interrupt" && data === "\x1b" });
711
+ // The fake context owns this mutable slot; the production UI exposes it readonly.
712
+ const themeHost = ctx.ui as unknown as MutablePromptThemeHost;
713
+ const originalTheme = themeHost.theme;
714
+ try {
715
+ setCardStyle(CARD_STYLE.FLOAT);
716
+ themeHost.theme = { ...plainTheme, bg: (role: string, text: string) => {
717
+ assert.equal(role, "toolSuccessBg");
718
+ return `\x1b[44m${text}\x1b[49m`;
719
+ } } as unknown as typeof ctx.ui.theme;
720
+ editor.focused = true;
721
+ assert.match(editor.render(80)[0], /\x1b\[44m/);
722
+ assert.match(stripAnsi(editor.render(80)[1]), /type, or \/ for commands/);
723
+ themeHost.theme = { ...plainTheme, bg: (_role: string, text: string) => `\x1b[45m${text}\x1b[49m` } as unknown as typeof ctx.ui.theme;
724
+ assert.match(editor.render(80)[0], /\x1b\[45m/);
725
+ editor.setText("draft");
726
+ editor.handleInput("\x1b");
727
+ assert.match(stripAnsi(editor.render(80)[0]), /esc again to clear/);
728
+ for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
729
+ assert.match(stripAnsi(editor.render(80)[0]), /queued/);
730
+ editor.handleInput("\x1b");
731
+ assert.match(stripAnsi(editor.render(80)[0]), /esc again to cancel/);
732
+ assert.match(editor.render(80)[0], /\x1b\[45m/);
733
+ assert.match(editor.render(80)[2], /\x1b\[45m/);
734
+ themeHost.theme = plainTheme as unknown as typeof ctx.ui.theme;
735
+ assert.match(stripAnsi(editor.render(80)[0]), /^╭/);
736
+ } finally { themeHost.theme = originalTheme; editor.dispose(); setCardStyle(previous); }
737
+ });
738
+
427
739
  test("gentleShell frames the editor with the petal prompt and a hint while empty", () => {
428
740
  const { pi, handlers } = fakePi();
429
741
  gentleShell(pi, {});
@@ -441,214 +753,2924 @@ test("gentleShell frames the editor with the petal prompt and a hint while empty
441
753
  editor.dispose();
442
754
  });
443
755
 
444
- test("registered prompt stays transparent while idle, working, and queued", () => {
445
- const { pi, handlers, tools } = fakePi();
756
+ test("an explicit ODD phase reported for the session renders in the working label", () => {
757
+ const { pi, handlers } = fakePi();
446
758
  gentleShell(pi, {});
447
759
  const { ctx, ui } = fakeContext();
448
- ctx.ui.theme = { ...plainTheme, getBgAnsi: () => "\x1b[44m" } as typeof ctx.ui.theme;
449
760
  const editor = installedPrompt(ctx, ui, handlers);
450
761
  try {
451
- for (const state of ["idle", "working", "queued"]) {
452
- if (state === "working") for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
453
- (ctx as unknown as { hasPendingMessages(): boolean }).hasPendingMessages = () => state === "queued";
454
- for (const width of [8, 40, 80]) assert.doesNotMatch(editor.render(width).join("\n"), /\x1b\[44m/, state);
455
- }
762
+ for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
763
+ oddPhaseRegistry.report(ctx.sessionManager.getSessionId(), "exploring");
764
+ assert.match(editor.render(60).map(stripAnsi)[0], /^╭─ .+ exploring… ─+╮$/);
456
765
  } finally {
766
+ oddPhaseRegistry.clear(ctx.sessionManager.getSessionId());
457
767
  editor.dispose();
458
768
  }
459
- assert.equal(tools.get("session_worktree_register")?.renderShell, "self");
460
769
  });
461
770
 
462
- test("gentleShell shows working while the agent runs and queued when messages wait", () => {
771
+ test("an unknown or unreported phase falls back to the generic working label", () => {
463
772
  const { pi, handlers } = fakePi();
464
773
  gentleShell(pi, {});
465
- const pending = { value: false };
466
774
  const { ctx, ui } = fakeContext();
467
- (ctx as unknown as { hasPendingMessages: () => boolean }).hasPendingMessages = () => pending.value;
468
775
  const editor = installedPrompt(ctx, ui, handlers);
776
+ try {
777
+ for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
778
+ assert.match(editor.render(60).map(stripAnsi)[0], /^╭─ .+ working… ─+╮$/);
779
+ } finally {
780
+ editor.dispose();
781
+ }
782
+ });
469
783
 
470
- for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
471
- assert.match(stripAnsi(editor.render(60)[0]), /^╭─ ✿ working… ─+╮$/);
472
- pending.value = true;
473
- assert.match(stripAnsi(editor.render(60)[0]), /^╭─ [✿❀❁✾] queued ─+╮$/);
474
- for (const handler of handlers.get("agent_end") ?? []) handler({}, ctx);
475
- assert.match(stripAnsi(editor.render(60)[0]), /queued/, "low-level run end is not settled");
476
- pending.value = false;
477
- for (const handler of handlers.get("agent_settled") ?? []) handler({}, ctx);
478
- assert.match(stripAnsi(editor.render(60)[0]), /^╭─ ✿ ─+╮$/);
479
- editor.dispose();
784
+ test("agent_start clears a previous turn's phase so it never leaks into the next turn", () => {
785
+ const { pi, handlers } = fakePi();
786
+ gentleShell(pi, {});
787
+ const { ctx, ui } = fakeContext();
788
+ const editor = installedPrompt(ctx, ui, handlers);
789
+ try {
790
+ for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
791
+ oddPhaseRegistry.report(ctx.sessionManager.getSessionId(), "checking");
792
+ for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
793
+ assert.match(editor.render(60).map(stripAnsi)[0], /^╭─ .+ working… ─+╮$/, "a new turn must start unlabeled");
794
+ } finally {
795
+ editor.dispose();
796
+ }
480
797
  });
481
798
 
482
- test("animations command reports without writing and switches the live pulse", async (t) => {
483
- const configHome = scopedDoubleEscCancelConfigHome(t);
484
- const delays: number[] = [];
485
- let active = 0;
486
- t.mock.method(globalThis, "setInterval", (_callback: () => void, delay: number) => {
487
- delays.push(delay); active++; return { unref() {} };
488
- });
489
- t.mock.method(globalThis, "clearInterval", () => { active--; });
490
- const { pi, handlers, commands } = fakePi();
491
- gentleShell(pi, { GENTLE_PI_CONFIG_HOME: configHome });
799
+ test("agent_settled going idle clears the reported phase, including after an abort", async () => {
800
+ const { pi, handlers } = fakePi();
801
+ gentleShell(pi, {});
492
802
  const { ctx, ui } = fakeContext();
493
803
  const editor = installedPrompt(ctx, ui, handlers);
494
- const command = commands.get("gentle:animations");
495
- assert.ok(command);
496
- await command.handler("", ctx);
497
- assert.match(ui.notices.at(-1)!, /animations: quality/);
498
- assert.equal(existsSync(join(configHome, "animations.json")), false);
499
- for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
500
- assert.deepEqual(delays, [80]);
501
- await command.handler("performance", ctx);
502
- assert.deepEqual(delays, [80, 1000]);
503
- assert.equal(active, 1);
504
- await command.handler("potato", ctx);
505
- assert.equal(active, 0);
506
- assert.match(stripAnsi(editor.render(60)[0]), /working/);
507
- assert.equal(JSON.parse(readFileSync(join(configHome, "animations.json"), "utf8")).policy, "potato");
508
- await command.handler("invalid", ctx);
509
- assert.equal(JSON.parse(readFileSync(join(configHome, "animations.json"), "utf8")).policy, "potato");
510
- await command.handler("quality", ctx);
511
- assert.deepEqual(delays, [80, 1000, 80]);
512
- for (const handler of handlers.get("agent_settled") ?? []) handler({}, ctx);
513
- assert.equal(active, 0);
514
- editor.dispose();
804
+ try {
805
+ for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
806
+ oddPhaseRegistry.report(ctx.sessionManager.getSessionId(), "implementing");
807
+ await fire(handlers, "agent_settled", ctx);
808
+ assert.equal(oddPhaseRegistry.get(ctx.sessionManager.getSessionId()), undefined);
809
+ } finally {
810
+ editor.dispose();
811
+ }
515
812
  });
516
813
 
517
- test("potato repaints start/settle and shows queued state on the host's next render without intervals", async (t) => {
518
- const configHome = scopedDoubleEscCancelConfigHome(t);
519
- writeFileSync(join(configHome, "animations.json"), '{"schema":"gentle-pi.animations/v1","policy":"potato"}');
520
- const intervals = t.mock.method(globalThis, "setInterval", () => { throw new Error("potato must not animate"); });
521
- const renders = t.mock.method(fakeTui, "requestRender", () => {});
522
- const { pi, handlers, commands } = fakePi();
523
- gentleShell(pi, { GENTLE_PI_CONFIG_HOME: configHome });
814
+ test("session_shutdown clears the reported phase", () => {
815
+ const { pi, handlers } = fakePi();
816
+ gentleShell(pi, {});
524
817
  const { ctx, ui } = fakeContext();
525
- const pending = { value: false };
526
- (ctx as unknown as { hasPendingMessages(): boolean }).hasPendingMessages = () => pending.value;
527
818
  const editor = installedPrompt(ctx, ui, handlers);
528
- let before = renders.mock.callCount();
529
- for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
530
- assert.ok(renders.mock.callCount() > before);
531
- assert.match(stripAnsi(editor.render(60)[0]), /✿ working/);
532
- before = renders.mock.callCount();
533
- pending.value = true;
534
- assert.equal(renders.mock.callCount(), before, "changing the queue flag is not a Gentle repaint event");
535
- // Pi owns enqueue and its repaint scheduling; this fake context exposes only
536
- // hasPendingMessages, not Pi's enqueue path. Simulate the host's render request:
537
- // this proves next-render visibility, not real Pi enqueue-to-paint latency.
538
- fakeTui.requestRender();
539
- assert.equal(renders.mock.callCount(), before + 1);
540
- assert.match(stripAnsi(editor.render(60)[0]), /✿ queued/);
541
- before = renders.mock.callCount();
542
- for (const handler of handlers.get("agent_settled") ?? []) handler({}, ctx);
543
- assert.ok(renders.mock.callCount() > before);
544
- assert.doesNotMatch(stripAnsi(editor.render(60)[0]), /working|queued/);
545
- await commands.get("gentle:animations")!.handler("status", ctx);
546
- assert.match(ui.notices.at(-1)!, /animations: potato/);
819
+ oddPhaseRegistry.report(ctx.sessionManager.getSessionId(), "researching");
547
820
  for (const handler of handlers.get("session_shutdown") ?? []) handler({}, ctx);
548
- assert.equal(intervals.mock.callCount(), 0);
821
+ assert.equal(oddPhaseRegistry.get(ctx.sessionManager.getSessionId()), undefined);
822
+ editor.dispose();
549
823
  });
550
824
 
551
- test("animations status attributes malformed files and reports a failed write", async (t) => {
552
- const configHome = scopedDoubleEscCancelConfigHome(t);
553
- const path = join(configHome, "animations.json");
554
- writeFileSync(path, "broken");
555
- const { pi, commands } = fakePi();
556
- gentleShell(pi, { GENTLE_PI_CONFIG_HOME: configHome });
825
+ test("a phase reported for one session never leaks into another session's prompt", () => {
826
+ const { pi, handlers } = fakePi();
827
+ gentleShell(pi, {});
557
828
  const { ctx, ui } = fakeContext();
558
- await commands.get("gentle:animations")!.handler("", ctx);
559
- assert.match(ui.notices.at(-1)!, /animations: quality.*global file.*malformed/);
560
- assert.equal(readFileSync(path, "utf8"), "broken");
561
- rmSync(path);
562
- mkdirSync(path);
563
- await commands.get("gentle:animations")!.handler("potato", ctx);
564
- assert.match(ui.notices.at(-1)!, /EISDIR|ENOTEMPTY|EPERM/);
829
+ const editor = installedPrompt(ctx, ui, handlers);
830
+ try {
831
+ for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
832
+ oddPhaseRegistry.report("a-background-child-session", "exploring");
833
+ assert.match(editor.render(60).map(stripAnsi)[0], /^╭─ .+ working… ─+╮$/, "a different session's report must not override this prompt");
834
+ } finally {
835
+ oddPhaseRegistry.clear("a-background-child-session");
836
+ editor.dispose();
837
+ }
565
838
  });
566
839
 
567
- test("animations with no argument opens a selectable menu and applies the chosen policy", async (t) => {
568
- const configHome = scopedDoubleEscCancelConfigHome(t);
569
- const path = join(configHome, "animations.json");
570
- const { pi, commands } = fakePi();
571
- gentleShell(pi, { GENTLE_PI_CONFIG_HOME: configHome });
572
- // No editor/prompt is installed: the handler's `prompt?.setAnimationPolicy`
573
- // optional chain must tolerate the interactive menu without one.
574
- const chosen = fakeContext({
575
- select: async (title, options) => {
576
- assert.match(title, /Gentle animations/);
577
- assert.deepEqual(options, ["quality", "performance", "potato", "status"]);
578
- return "potato";
579
- },
580
- });
581
- await commands.get("gentle:animations")!.handler("", chosen.ctx);
582
- assert.equal(JSON.parse(readFileSync(path, "utf8")).policy, "potato");
583
- assert.match(chosen.ui.notices.at(-1)!, /animations: potato/);
840
+ test("a reported phase does not override the queued label", () => {
841
+ const { pi, handlers } = fakePi();
842
+ gentleShell(pi, {});
843
+ const { ctx, ui } = fakeContext({ pending: true });
844
+ const editor = installedPrompt(ctx, ui, handlers);
845
+ try {
846
+ for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
847
+ oddPhaseRegistry.report(ctx.sessionManager.getSessionId(), "checking");
848
+ assert.match(editor.render(60).map(stripAnsi)[0], /^╭─ .+ queued ─+╮$/);
849
+ } finally {
850
+ oddPhaseRegistry.clear(ctx.sessionManager.getSessionId());
851
+ editor.dispose();
852
+ }
853
+ });
584
854
 
585
- // A dismissed menu (undefined selection) reports nothing and writes nothing.
586
- const dismissHome = scopedDoubleEscCancelConfigHome(t);
587
- const { pi: dismissPi, commands: dismissCommands } = fakePi();
588
- gentleShell(dismissPi, { GENTLE_PI_CONFIG_HOME: dismissHome });
589
- const dismissed = fakeContext({ select: async () => undefined });
590
- await dismissCommands.get("gentle:animations")!.handler("", dismissed.ctx);
591
- assert.equal(dismissed.ui.notices.length, 0);
592
- assert.equal(existsSync(join(dismissHome, "animations.json")), false);
855
+ test("reporting an ODD phase requests an immediate redraw even under the potato animation policy, which runs no pulse loop at all", () => {
856
+ const { pi, handlers } = fakePi();
857
+ gentleShell(pi, {});
858
+ const { ctx, ui } = fakeContext();
859
+ for (const handler of handlers.get("session_start") ?? []) handler({}, ctx);
860
+ let renders = 0;
861
+ const localTui = { terminal: { rows: 40, columns: 120 }, requestRender() { renders += 1; } };
862
+ const factory = ui.editorFactory as (tui: unknown, theme: unknown, keybindings: unknown) => GentlePromptEditor;
863
+ const editor = factory(localTui, editorTheme, fakeKeybindings);
864
+ try {
865
+ editor.setAnimationPolicy("potato");
866
+ for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
867
+ renders = 0;
868
+ oddPhaseRegistry.report(ctx.sessionManager.getSessionId(), "planning");
869
+ assert.ok(renders > 0, "a phase report must trigger a redraw directly; potato mode schedules no pulse interval to pick it up later");
870
+ } finally {
871
+ oddPhaseRegistry.clear(ctx.sessionManager.getSessionId());
872
+ editor.dispose();
873
+ }
593
874
  });
594
875
 
595
- test("prompt uses the compact banner cadence and releases its unref timer at settlement", (t) => {
596
- const configHome = scopedDoubleEscCancelConfigHome(t);
597
- writeFileSync(join(configHome, "animations.json"), '{"schema":"gentle-pi.animations/v1","policy":"quality"}');
598
- const delays: number[] = [];
599
- let active = 0;
600
- let unrefs = 0;
601
- t.mock.method(globalThis, "setInterval", (_callback: () => void, delay: number) => {
602
- delays.push(delay);
603
- active++;
604
- return { unref() { unrefs++; } };
605
- });
606
- t.mock.method(globalThis, "clearInterval", () => { active--; });
876
+ test("session_shutdown stops requesting redraws for a since-closed session", () => {
607
877
  const { pi, handlers } = fakePi();
608
- gentleShell(pi, { GENTLE_PI_CONFIG_HOME: configHome });
878
+ gentleShell(pi, {});
609
879
  const { ctx, ui } = fakeContext();
610
- const editor = installedPrompt(ctx, ui, handlers);
611
- assert.equal(active, 0);
612
- for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
613
- assert.deepEqual(delays, [80]);
614
- assert.equal(unrefs, 1);
615
- for (const handler of handlers.get("agent_settled") ?? []) handler({}, ctx);
616
- assert.equal(active, 0);
880
+ for (const handler of handlers.get("session_start") ?? []) handler({}, ctx);
881
+ let renders = 0;
882
+ const localTui = { terminal: { rows: 40, columns: 120 }, requestRender() { renders += 1; } };
883
+ const factory = ui.editorFactory as (tui: unknown, theme: unknown, keybindings: unknown) => GentlePromptEditor;
884
+ const editor = factory(localTui, editorTheme, fakeKeybindings);
885
+ for (const handler of handlers.get("session_shutdown") ?? []) handler({}, ctx);
886
+ renders = 0;
887
+ oddPhaseRegistry.report(ctx.sessionManager.getSessionId(), "closing");
888
+ assert.equal(renders, 0, "a session that already shut down must not receive further redraw requests");
889
+ oddPhaseRegistry.clear(ctx.sessionManager.getSessionId());
617
890
  editor.dispose();
618
- assert.equal(active, 0);
619
891
  });
620
892
 
621
- // ---------------------------------------------------------------------------
622
- // double-esc-cancel (issue #1163): opt-in, off by default. While the prompt
623
- // is working and autocomplete is hidden, the first Esc is swallowed and the
624
- // frame shows a hint; a second Esc within the window falls through to
625
- // CustomEditor's own handleInput so Pi's onEscape performs the abort exactly
626
- // as it always has. Idle double-Esc (tree/fork), bash-mode Esc, and
627
- // autocomplete cancel live entirely in Pi's own onEscape/CustomEditor and are
628
- // untouched by this gate.
629
- // ---------------------------------------------------------------------------
893
+ test("dot replays at a new cursor; each repeat and insert session is one undo unit", () => {
894
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
895
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
896
+ try {
897
+ editor.setVimPolicy("on"); editor.setText("one two three"); editor.handleInput("\x1b");
898
+ editor.handleInput("0"); editor.handleInput("x");
899
+ assert.equal(editor.getText(), "ne two three");
900
+ editor.handleInput("w"); editor.handleInput(".");
901
+ assert.equal(editor.getText(), "ne wo three");
902
+ editor.handleInput("u"); assert.equal(editor.getText(), "ne two three");
903
+ editor.handleInput("u"); assert.equal(editor.getText(), "one two three");
904
+ editor.handleInput("i");
905
+ for (const key of ["é", " ", "👩‍💻"]) editor.handleInput(key);
906
+ editor.handleInput("\x1b");
907
+ assert.equal(editor.getText(), "é 👩‍💻one two three");
908
+ editor.handleInput("u"); assert.equal(editor.getText(), "one two three");
909
+ } finally { editor.dispose(); }
910
+ });
630
911
 
631
- const escapeKeybindings = { matches: (_data: string, keybinding: string) => keybinding === "app.interrupt" };
912
+ test("completed insert and change replay as semantic Unicode edits with one undo per dot", () => {
913
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
914
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
915
+ try {
916
+ editor.setVimPolicy("on"); editor.setText("one two three"); editor.handleInput("\x1b"); editor.handleInput("0");
917
+ editor.handleInput("c"); editor.handleInput("w"); editor.handleInput("👩‍💻"); editor.handleInput("é"); editor.handleInput("\x1b");
918
+ assert.equal(editor.getText(), "👩‍💻étwo three");
919
+ editor.handleInput("w"); editor.handleInput(".");
920
+ assert.equal(editor.getText(), "👩‍💻étwo 👩‍💻é");
921
+ editor.handleInput("u"); assert.equal(editor.getText(), "👩‍💻étwo three");
922
+ editor.handleInput("u"); assert.equal(editor.getText(), "one two three");
923
+ editor.handleInput("i"); editor.handleInput("雪"); editor.handleInput("\x1b");
924
+ editor.handleInput("w"); editor.handleInput("2"); editor.handleInput(".");
925
+ assert.equal((editor.getText().match(/雪/gu) ?? []).length, 3);
926
+ editor.handleInput("u"); assert.equal((editor.getText().match(/雪/gu) ?? []).length, 2);
927
+ editor.handleInput("u"); assert.equal((editor.getText().match(/雪/gu) ?? []).length, 1);
928
+ } finally { editor.dispose(); }
929
+ });
930
+
931
+ test("open-line, substitute and motion shift remain bounded across multiline replay", () => {
932
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
933
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
934
+ try {
935
+ editor.setVimPolicy("on"); editor.setText("one\ntwo\nthree"); editor.handleInput("\x1b");
936
+ editor.handleInput("g"); editor.handleInput("g"); editor.handleInput(">"); editor.handleInput("j");
937
+ assert.equal(editor.getText(), " one\n two\nthree");
938
+ editor.handleInput("u"); assert.equal(editor.getText(), "one\ntwo\nthree");
939
+ editor.handleInput("g"); editor.handleInput("g"); editor.handleInput("o");
940
+ editor.handleInput("雪"); editor.handleInput("\x1b");
941
+ assert.equal(editor.getText(), "one\n雪\ntwo\nthree");
942
+ editor.handleInput("j"); editor.handleInput(".");
943
+ assert.equal(editor.getText(), "one\n雪\ntwo\n雪\nthree");
944
+ editor.handleInput("u"); assert.equal(editor.getText(), "one\n雪\ntwo\nthree");
945
+ editor.handleInput("u"); assert.equal(editor.getText(), "one\ntwo\nthree");
946
+ } finally { editor.dispose(); }
947
+ });
948
+
949
+ test("O and S replay multiline text with one undo unit and no raw-key playback", () => {
950
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
951
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
952
+ try {
953
+ editor.setVimPolicy("on"); editor.setText("a\nb"); editor.handleInput("\x1b");
954
+ editor.handleInput("O"); editor.handleInput("雪"); editor.handleInput("\x1b");
955
+ assert.equal(editor.getText(), "a\n雪\nb");
956
+ editor.handleInput("g"); editor.handleInput("g"); editor.handleInput(".");
957
+ assert.equal(editor.getText(), "雪\na\n雪\nb");
958
+ editor.handleInput("u"); assert.equal(editor.getText(), "a\n雪\nb");
959
+ editor.handleInput("u"); assert.equal(editor.getText(), "a\nb");
960
+ editor.handleInput("S"); editor.handleInput("👩‍💻"); editor.handleInput("\x1b");
961
+ editor.handleInput("g"); editor.handleInput("g"); editor.handleInput(".");
962
+ assert.equal(editor.getText(), "👩‍💻\n👩‍💻");
963
+ editor.handleInput("u"); assert.equal(editor.getText(), "a\n👩‍💻");
964
+ } finally { editor.dispose(); }
965
+ });
966
+
967
+ test("substitute and append replay at the new cursor without changing the register", () => {
968
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
969
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
970
+ try {
971
+ editor.setVimPolicy("on"); editor.setText("ab cd"); editor.handleInput("\x1b"); editor.handleInput("0");
972
+ editor.handleInput("s"); editor.handleInput("é"); editor.handleInput("\x1b");
973
+ editor.handleInput("w"); editor.handleInput(".");
974
+ assert.equal(editor.getText(), "éb éd");
975
+ editor.handleInput("u"); assert.equal(editor.getText(), "éb cd");
976
+ editor.handleInput("u"); assert.equal(editor.getText(), "ab cd");
977
+ editor.handleInput("0"); editor.handleInput("a"); editor.handleInput("雪"); editor.handleInput("\x1b");
978
+ editor.handleInput("w"); editor.handleInput(".");
979
+ assert.equal((editor.getText().match(/雪/gu) ?? []).length, 2);
980
+ } finally { editor.dispose(); }
981
+ });
982
+
983
+ test("empty insert and interrupted insert do not replace the last completed repeat", () => {
984
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
985
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers,
986
+ { matches: (data: string, action: string) => action === "app.interrupt" && data === "\x03" });
987
+ try {
988
+ editor.setVimPolicy("on"); editor.setText("abcd"); editor.handleInput("\x1b"); editor.handleInput("0");
989
+ editor.handleInput("x"); editor.handleInput("i"); editor.handleInput("\x1b");
990
+ editor.handleInput("."); assert.equal(editor.getText(), "cd");
991
+ editor.handleInput("i"); editor.handleInput("雪"); editor.handleInput("\x03");
992
+ editor.handleInput("."); assert.equal(editor.getText(), "雪d");
993
+ } finally { editor.dispose(); }
994
+ });
995
+
996
+ test("change plus its insert session undoes as one complete change", () => {
997
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
998
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
999
+ try {
1000
+ editor.setVimPolicy("on"); editor.setText("one two"); editor.handleInput("\x1b"); editor.handleInput("0");
1001
+ editor.handleInput("c"); editor.handleInput("w");
1002
+ editor.handleInput("é"); editor.handleInput(" "); editor.handleInput("👩‍💻"); editor.handleInput("\x1b");
1003
+ assert.equal(editor.getText(), "é 👩‍💻two");
1004
+ editor.handleInput("u"); assert.equal(editor.getText(), "one two");
1005
+ } finally { editor.dispose(); }
1006
+ });
1007
+
1008
+ test("counted dot, canceled operator, empty changes and unsupported visual do not corrupt the draft", () => {
1009
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1010
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1011
+ try {
1012
+ editor.setVimPolicy("on"); editor.setText("abcde"); editor.handleInput("\x1b");
1013
+ editor.handleInput("0"); editor.handleInput("x");
1014
+ editor.handleInput("2"); editor.handleInput(".");
1015
+ assert.equal(editor.getText(), "de");
1016
+ editor.handleInput("u"); assert.equal(editor.getText(), "cde");
1017
+ editor.handleInput("u"); assert.equal(editor.getText(), "bcde");
1018
+ editor.handleInput("d"); editor.handleInput("\x1b");
1019
+ editor.handleInput("v"); editor.handleInput("y"); editor.handleInput(".");
1020
+ assert.equal(editor.getText(), "cde");
1021
+ } finally { editor.dispose(); }
1022
+ });
1023
+
1024
+ test("visual char and line selections paint effective inverse in the framed editor and Esc keeps the draft", () => {
1025
+ const { pi, handlers } = fakePi();
1026
+ gentleShell(pi, {});
1027
+ const { ctx, ui } = fakeContext();
1028
+ const editor = installedPrompt(ctx, ui, handlers);
1029
+ try {
1030
+ editor.setVimPolicy("on");
1031
+ editor.setText("ab\ncd");
1032
+ editor.handleInput("\x1b");
1033
+ editor.handleInput("v");
1034
+ editor.handleInput("2"); editor.handleInput("h");
1035
+ assert.deepEqual(reverseColumns(editor.render(30)[2]!), [1, 2], "selection includes both c and d");
1036
+ editor.handleInput("V");
1037
+ assert.deepEqual(reverseColumns(editor.render(30)[2]!), [1, 2]);
1038
+ editor.handleInput("k");
1039
+ assert.deepEqual(reverseColumns(editor.render(30)[1]!), [1, 2]);
1040
+ editor.handleInput("\x1b");
1041
+ assert.equal(editor.getText(), "ab\ncd");
1042
+ assert.match(editor.render(30).join("\n"), /NORMAL/);
1043
+ } finally { editor.dispose(); }
1044
+ });
1045
+
1046
+ test("visual line delete, yank/paste, change and shifts use one undo step without leaking NORMAL text", () => {
1047
+ const { pi, handlers } = fakePi();
1048
+ gentleShell(pi, {});
1049
+ const { ctx, ui } = fakeContext();
1050
+ const editor = installedPrompt(ctx, ui, handlers);
1051
+ try {
1052
+ editor.setVimPolicy("on"); editor.setText("one\ntwo\nthree"); editor.handleInput("\x1b");
1053
+ editor.handleInput("V"); editor.handleInput("k"); editor.handleInput("y");
1054
+ assert.equal(editor.getText(), "one\ntwo\nthree");
1055
+ editor.handleInput("p"); assert.equal(editor.getText(), "one\ntwo\ntwo\nthree\nthree");
1056
+ editor.handleInput("u"); assert.equal(editor.getText(), "one\ntwo\nthree");
1057
+ editor.handleInput("V"); editor.handleInput("k"); editor.handleInput("d");
1058
+ assert.equal(editor.getText(), "three");
1059
+ editor.handleInput("u"); assert.equal(editor.getText(), "one\ntwo\nthree");
1060
+ editor.handleInput("V"); editor.handleInput(">");
1061
+ assert.equal(editor.getText(), " one\ntwo\nthree");
1062
+ editor.handleInput("u"); assert.equal(editor.getText(), "one\ntwo\nthree");
1063
+ editor.handleInput("G"); editor.handleInput("v"); editor.handleInput("c");
1064
+ assert.match(editor.render(30).join("\n"), /INSERT/);
1065
+ editor.handleInput("Z"); assert.equal(editor.getText(), "one\ntwo\nZhree");
1066
+ } finally { editor.dispose(); }
1067
+ });
1068
+
1069
+ test("visual anchor swap, grapheme delete and registered paste rejection keep selection safe", () => {
1070
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1071
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1072
+ try {
1073
+ editor.setVimPolicy("on"); editor.setText("a👩‍💻b"); editor.handleInput("\x1b");
1074
+ editor.handleInput("0"); editor.handleInput("v"); editor.handleInput("l");
1075
+ editor.handleInput("o"); assert.deepEqual(editor.getCursor(), { line: 0, col: 0 });
1076
+ editor.handleInput("d"); assert.equal(editor.getText(), "b");
1077
+ editor.handleInput("u"); assert.equal(editor.getText(), "a👩‍💻b");
1078
+ editor.setText(""); editor.handleInput("i");
1079
+ editor.handleInput(`\x1b[200~${"z".repeat(1001)}\x1b[201~`);
1080
+ const before = editor.getExpandedText();
1081
+ editor.handleInput("\x1b"); editor.handleInput("0"); editor.handleInput("v"); editor.handleInput("y");
1082
+ assert.equal(editor.getExpandedText(), before);
1083
+ assert.match(editor.render(30).join("\n"), /VISUAL/);
1084
+ editor.handleInput("\x1b"); assert.match(editor.render(30).join("\n"), /NORMAL/);
1085
+ } finally { editor.dispose(); }
1086
+ });
1087
+
1088
+ test("visual text objects select exact range then operate, with failed match retaining selection and register", () => {
1089
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1090
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1091
+ try {
1092
+ editor.setVimPolicy("on"); editor.setText('one two (é 👩‍💻) "hi"'); editor.handleInput("\x1b");
1093
+ editor.handleInput("g"); editor.handleInput("g"); editor.handleInput("v");
1094
+ for (const key of ["i", "w", "y"]) editor.handleInput(key);
1095
+ assert.equal(editor.getText(), 'one two (é 👩‍💻) "hi"');
1096
+ editor.handleInput("f"); editor.handleInput("("); editor.handleInput("v");
1097
+ for (const key of ["i", "(", "d"]) editor.handleInput(key);
1098
+ assert.equal(editor.getText(), 'one two () "hi"');
1099
+ editor.handleInput("u");
1100
+ editor.handleInput("v"); editor.handleInput("i"); editor.handleInput('"');
1101
+ assert.match(editor.render(30).join("\n"), /VISUAL/);
1102
+ assert.equal(editor.getText(), 'one two (é 👩‍💻) "hi"');
1103
+ editor.handleInput("d"); assert.equal(editor.getText(), 'one two (é ) "hi"');
1104
+ } finally { editor.dispose(); }
1105
+ });
1106
+
1107
+ test("visual word, WORD and quoted objects replace only the selected text and allow shortcut handoff", () => {
1108
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1109
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1110
+ try {
1111
+ editor.setVimPolicy("on"); editor.setText('alpha beta "é👩‍💻"'); editor.handleInput("\x1b");
1112
+ editor.handleInput("g"); editor.handleInput("g"); editor.handleInput("v");
1113
+ for (const key of ["i", "w", "y"]) editor.handleInput(key);
1114
+ editor.handleInput("v"); editor.handleInput("a"); editor.handleInput("w"); editor.handleInput("d");
1115
+ assert.equal(editor.getText(), 'beta "é👩‍💻"');
1116
+ editor.handleInput("u");
1117
+ editor.handleInput("f"); editor.handleInput('"'); editor.handleInput("v"); editor.handleInput("a"); editor.handleInput('"');
1118
+ editor.handleInput("c");
1119
+ assert.equal(editor.getText(), 'alpha beta ');
1120
+ assert.match(editor.render(30).join("\n"), /INSERT/);
1121
+ editor.handleInput("\x1b"); editor.handleInput("v");
1122
+ editor.onExtensionShortcut = (data) => {
1123
+ if (data !== "ctrl+k") return false;
1124
+ assert.match(editor.render(30).join("\n"), /INSERT/);
1125
+ return true;
1126
+ };
1127
+ editor.handleInput("i"); editor.handleInput("ctrl+k");
1128
+ assert.match(editor.render(30).join("\n"), /INSERT/);
1129
+ } finally { editor.dispose(); }
1130
+ });
1131
+
1132
+ test("visual object selection refuses registered paste markers without moving or changing text", () => {
1133
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1134
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1135
+ try {
1136
+ editor.setVimPolicy("on"); editor.setText("(abc)"); editor.handleInput("\x1b");
1137
+ editor.handleInput("g"); editor.handleInput("g"); editor.handleInput("l"); editor.handleInput("i"); editor.handleInput(`\x1b[200~${"z".repeat(1001)}\x1b[201~`);
1138
+ const original = editor.getExpandedText();
1139
+ editor.handleInput("\x1b"); editor.handleInput("v");
1140
+ const cursor = editor.getCursor();
1141
+ editor.handleInput("i"); editor.handleInput("(");
1142
+ assert.equal(editor.getExpandedText(), original);
1143
+ assert.deepEqual(editor.getCursor(), cursor);
1144
+ assert.match(editor.render(30).join("\n"), /VISUAL/);
1145
+ } finally { editor.dispose(); }
1146
+ });
1147
+
1148
+ test("visual entry at EOF selects the last grapheme and empty document cannot clobber the register", () => {
1149
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1150
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1151
+ try {
1152
+ editor.setVimPolicy("on"); editor.setText("abc"); editor.handleInput("\x1b");
1153
+ editor.handleInput("v");
1154
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 2 });
1155
+ editor.handleInput("d"); assert.equal(editor.getText(), "ab");
1156
+ editor.handleInput("u"); assert.equal(editor.getText(), "abc");
1157
+ editor.setText(""); editor.handleInput("v"); editor.handleInput("d");
1158
+ assert.equal(editor.getText(), "");
1159
+ editor.handleInput("p"); assert.equal(editor.getText(), "c");
1160
+ } finally { editor.dispose(); }
1161
+ });
1162
+
1163
+ test("visual entry and yank clear a pending delete before a normal motion", () => {
1164
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1165
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1166
+ try {
1167
+ editor.setVimPolicy("on"); editor.setText("abc def"); editor.handleInput("\x1b");
1168
+ editor.handleInput("h");
1169
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 6 });
1170
+ for (const key of ["d", "v", "y", "0"]) editor.handleInput(key);
1171
+ assert.equal(editor.getText(), "abc def");
1172
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 0 });
1173
+ editor.handleInput("P");
1174
+ assert.equal(editor.getText(), "fabc def", "visual yank remains available after clearing the pending operator");
1175
+ } finally { editor.dispose(); }
1176
+ });
1177
+
1178
+ test("empty visual-line delete leaves the previous register available", () => {
1179
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1180
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1181
+ try {
1182
+ editor.setVimPolicy("on"); editor.setText("saved"); editor.handleInput("\x1b");
1183
+ editor.handleInput("v"); editor.handleInput("y");
1184
+ editor.setText("");
1185
+ editor.handleInput("V"); editor.handleInput("d");
1186
+ assert.equal(editor.getText(), "");
1187
+ editor.handleInput("p");
1188
+ assert.equal(editor.getText(), "d", "the no-op delete must not replace the saved character with a newline");
1189
+ } finally { editor.dispose(); }
1190
+ });
1191
+
1192
+ test("visual p replaces a Unicode selection atomically and yanks overwritten text", () => {
1193
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1194
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1195
+ try {
1196
+ editor.setVimPolicy("on"); editor.setText("👩‍💻é z"); editor.handleInput("\x1b");
1197
+ editor.handleInput("0"); editor.handleInput("v"); editor.handleInput("y");
1198
+ editor.handleInput("l"); editor.handleInput("v"); editor.handleInput("p");
1199
+ assert.equal(editor.getText(), "👩‍💻👩‍💻 z");
1200
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 5 });
1201
+ assert.match(editor.render(30).join("\n"), /NORMAL/);
1202
+ editor.handleInput("u"); assert.equal(editor.getText(), "👩‍💻é z");
1203
+ editor.handleInput("P"); assert.equal(editor.getText(), "👩‍💻éé z", "overwritten selection becomes the register");
1204
+ } finally { editor.dispose(); }
1205
+ });
1206
+
1207
+ test("visual line p swaps whole lines, one undo restores the selection, and paste marker rejection retains mode", () => {
1208
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1209
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1210
+ try {
1211
+ editor.setVimPolicy("on"); editor.setText("alpha\nbeta\ngamma"); editor.handleInput("\x1b");
1212
+ editor.handleInput("V"); editor.handleInput("y");
1213
+ editor.handleInput("k"); editor.handleInput("V"); editor.handleInput("p");
1214
+ assert.equal(editor.getText(), "alpha\ngamma\ngamma");
1215
+ assert.deepEqual(editor.getCursor(), { line: 1, col: 0 });
1216
+ editor.handleInput("u"); assert.equal(editor.getText(), "alpha\nbeta\ngamma");
1217
+ editor.setText(""); editor.handleInput("i");
1218
+ editor.handleInput(`\x1b[200~${"z".repeat(1001)}\x1b[201~`);
1219
+ const original = editor.getExpandedText();
1220
+ editor.handleInput("\x1b"); editor.handleInput("0"); editor.handleInput("v"); editor.handleInput("p");
1221
+ assert.equal(editor.getExpandedText(), original);
1222
+ assert.match(editor.render(30).join("\n"), /VISUAL/);
1223
+ } finally { editor.dispose(); }
1224
+ });
1225
+
1226
+ test("full-line characterwise VISUAL c/p on ordinary text retain frame and autocomplete", () => {
1227
+ for (const command of ["c", "p"] as const) {
1228
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1229
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1230
+ try {
1231
+ editor.setVimPolicy("on"); editor.setText("asdf asdf asd f"); editor.handleInput("\x1b");
1232
+ editor.handleInput("0"); editor.handleInput("v"); editor.handleInput("$");
1233
+ const before = editor.render(30);
1234
+ assert.match(before.join("\n"), /VISUAL(?! LINE)/);
1235
+ assert.deepEqual(reverseColumns(before[1]!).filter((col) => col >= 1 && col <= 15).length, 15);
1236
+ assert.ok(before.every((row) => visibleWidth(row) === 30));
1237
+ const internal = editor as unknown as { autocompleteState: string; autocompleteList: { render(width: number): string[] } };
1238
+ if (command === "p") {
1239
+ editor.handleInput("y"); editor.handleInput("0"); editor.handleInput("v"); editor.handleInput("$");
1240
+ }
1241
+ internal.autocompleteState = "force";
1242
+ internal.autocompleteList = { render: () => ["completion"] };
1243
+ editor.handleInput(command);
1244
+ assert.equal(ui.notices.length, 0);
1245
+ assert.equal(editor.getText(), command === "c" ? "" : "asdf asdf asd f");
1246
+ assert.match(editor.render(30).join("\n"), command === "c" ? /INSERT/ : /NORMAL/);
1247
+ assert.equal(editor.isShowingAutocomplete(), false);
1248
+ assert.ok(editor.render(30).every((row) => visibleWidth(row) === 30));
1249
+ } finally { editor.dispose(); }
1250
+ }
1251
+ });
1252
+
1253
+ test("typed INSERT draft can enter VISUAL c after Escape across repeated mode cycles", () => {
1254
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1255
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1256
+ try {
1257
+ editor.setVimPolicy("on");
1258
+ // Pi installs a global shortcut probe even when no extension owns the key.
1259
+ editor.onExtensionShortcut = () => false;
1260
+ for (const key of "asdf asdf") editor.handleInput(key);
1261
+ editor.handleInput("\x1b");
1262
+ assert.match(editor.render(30).join("\n"), /NORMAL/);
1263
+ editor.handleInput("0"); editor.handleInput("v"); editor.handleInput("l"); editor.handleInput("c");
1264
+ assert.deepEqual(ui.notices, []);
1265
+ assert.equal(editor.getText(), "df asdf");
1266
+ assert.match(editor.render(30).join("\n"), /INSERT/);
1267
+ editor.handleInput("X"); editor.handleInput("\x1b");
1268
+ assert.match(editor.render(30).join("\n"), /NORMAL/);
1269
+ editor.handleInput("p");
1270
+ assert.equal(editor.getText(), "Xdasf asdf");
1271
+ editor.handleInput("u");
1272
+ assert.equal(editor.getText(), "Xdf asdf");
1273
+ editor.handleInput("u");
1274
+ assert.equal(editor.getText(), "asdf asdf");
1275
+ editor.handleInput("i"); editor.handleInput("!"); editor.handleInput("\x1b");
1276
+ editor.handleInput("0"); editor.handleInput("v"); editor.handleInput("l"); editor.handleInput("c");
1277
+ assert.deepEqual(ui.notices, []);
1278
+ assert.equal(editor.getText(), "sdf asdf");
1279
+ assert.match(editor.render(30).join("\n"), /INSERT/);
1280
+ } finally { editor.dispose(); }
1281
+ });
1282
+
1283
+ test("VISUAL c/p report unsafe registered paste selections without changing draft or register", () => {
1284
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1285
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1286
+ try {
1287
+ editor.setVimPolicy("on"); editor.setText("saved"); editor.handleInput("\x1b");
1288
+ editor.handleInput("0"); editor.handleInput("v"); editor.handleInput("y");
1289
+ editor.setText(""); editor.handleInput("i");
1290
+ editor.handleInput(`\x1b[200~${"z".repeat(1001)}\x1b[201~`);
1291
+ const draft = editor.getExpandedText();
1292
+ editor.handleInput("\x1b"); editor.handleInput("0"); editor.handleInput("v");
1293
+ for (const command of ["c", "p"]) {
1294
+ const count = ui.notices.length;
1295
+ editor.handleInput(command);
1296
+ assert.equal(editor.getExpandedText(), draft);
1297
+ assert.match(editor.render(30).join("\n"), /VISUAL/);
1298
+ assert.equal(ui.notices.length, count + 1);
1299
+ assert.match(ui.notices.at(-1)!, /selection.*paste marker.*\[readRange:paste-marker\]/i);
1300
+ assert.ok(!ui.notices.at(-1)!.includes("z".repeat(20)));
1301
+ }
1302
+ editor.handleInput("\x1b"); editor.setText("xx"); editor.handleInput("0"); editor.handleInput("v"); editor.handleInput("p");
1303
+ assert.equal(editor.getText(), "sx", "unsafe c/p must not overwrite the Vim register");
1304
+ } finally { editor.dispose(); }
1305
+ });
1306
+
1307
+ test("VISUAL replace failure reports a bounded stage without leaking raw host errors", () => {
1308
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1309
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1310
+ try {
1311
+ editor.setVimPolicy("on"); editor.setText("asdf asdf asd f"); editor.handleInput("\x1b");
1312
+ editor.handleInput("0"); editor.handleInput("v"); editor.handleInput("$");
1313
+ const internal = editor as unknown as { pushUndoSnapshot(): void };
1314
+ const originalSnapshot = internal.pushUndoSnapshot;
1315
+ internal.pushUndoSnapshot = () => { throw new Error("private /secret/draft asdf asdf asd f"); };
1316
+ editor.handleInput("c");
1317
+ assert.equal(editor.getText(), "asdf asdf asd f");
1318
+ assert.match(editor.render(30).join("\n"), /VISUAL/);
1319
+ assert.equal(ui.notices.at(-1), "Vim selection cannot be edited safely; try a different selection. [replace:unexpected]");
1320
+ assert.ok(!ui.notices.at(-1)!.includes("/secret/"));
1321
+ internal.pushUndoSnapshot = originalSnapshot;
1322
+ editor.handleInput("c");
1323
+ assert.equal(ui.notices.length, 1, "failed replacement must close its insert session before retry");
1324
+ assert.equal(editor.getText(), "");
1325
+ assert.match(editor.render(30).join("\n"), /INSERT/);
1326
+ } finally { editor.dispose(); }
1327
+ });
1328
+
1329
+ test("visual case, replace, join and shift operators act on selected text without escaping ownership", () => {
1330
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1331
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1332
+ try {
1333
+ editor.setVimPolicy("on"); editor.setText("aB\ncD"); editor.handleInput("\x1b");
1334
+ editor.handleInput("g"); editor.handleInput("g"); editor.handleInput("v"); editor.handleInput("l"); editor.handleInput("U");
1335
+ assert.equal(editor.getText(), "AB\ncD");
1336
+ editor.handleInput("u"); assert.equal(editor.getText(), "aB\ncD");
1337
+ editor.onExtensionShortcut = () => false;
1338
+ editor.handleInput("g"); editor.handleInput("g"); editor.handleInput("v"); editor.handleInput("r"); editor.handleInput("👩‍💻");
1339
+ assert.equal(editor.getText(), "👩‍💻B\ncD");
1340
+ editor.handleInput("u"); assert.equal(editor.getText(), "aB\ncD");
1341
+ editor.handleInput("G"); editor.handleInput("V"); editor.handleInput("k"); editor.handleInput("J");
1342
+ assert.equal(editor.getText(), "aB cD");
1343
+ editor.handleInput("u"); assert.equal(editor.getText(), "aB\ncD");
1344
+ editor.handleInput("G"); editor.handleInput("V"); editor.handleInput("k"); editor.handleInput("<");
1345
+ assert.equal(editor.getText(), "aB\ncD");
1346
+ editor.handleInput("G"); editor.handleInput("v"); editor.handleInput("l"); editor.handleInput("u");
1347
+ assert.equal(editor.getText(), "aB\ncd");
1348
+ editor.handleInput("u"); assert.equal(editor.getText(), "aB\ncD");
1349
+ editor.handleInput("G"); editor.handleInput("V"); editor.handleInput("x"); assert.equal(editor.getText(), "aB");
1350
+ } finally { editor.dispose(); }
1351
+ });
1352
+
1353
+ test("GentlePromptEditor visual selection uses adapter inside the fixed-width frame", () => {
1354
+ const { pi, handlers } = fakePi();
1355
+ gentleShell(pi, {});
1356
+ const { ctx, ui } = fakeContext();
1357
+ const editor = installedPrompt(ctx, ui, handlers);
1358
+ editor.setVimPolicy("on");
1359
+ editor.setText("abcd");
1360
+ editor.handleInput("\x1b");
1361
+ editor.handleInput("h");
1362
+ editor.handleInput("h");
1363
+ editor.handleInput("v");
1364
+ editor.handleInput("l");
1365
+ const lines = editor.render(30);
1366
+ assert.deepEqual(reverseColumns(lines[1]!), [3, 4], "c is selected; d alone is Pi's software cursor");
1367
+ assert.ok(lines.every((line) => [...stripAnsi(line)].length === 30), "frame retains requested width");
1368
+ editor.dispose();
1369
+ });
1370
+
1371
+ test("GentlePromptEditor preserves autocomplete below the bottom border during visual selection", () => {
1372
+ const { pi, handlers } = fakePi();
1373
+ gentleShell(pi, {});
1374
+ const { ctx, ui } = fakeContext();
1375
+ const editor = installedPrompt(ctx, ui, handlers);
1376
+ editor.setVimPolicy("on");
1377
+ editor.setText("abcd");
1378
+ editor.handleInput("\x1b");
1379
+ editor.handleInput("h");
1380
+ editor.handleInput("h");
1381
+ editor.handleInput("v");
1382
+ editor.handleInput("l");
1383
+ const internal = editor as unknown as { autocompleteState: string; autocompleteList: { render(width: number): string[] } };
1384
+ internal.autocompleteState = "force";
1385
+ internal.autocompleteList = { render: () => ["completion one", "completion two"] };
1386
+ try {
1387
+ const rows = editor.render(30).map(stripAnsi);
1388
+ assert.ok(rows.some((row) => row.includes("completion one")));
1389
+ assert.ok(rows.some((row) => row.includes("completion two")));
1390
+ assert.match(rows[rows.length - 3]!, /^╰.*╯$/);
1391
+ assert.ok(rows.every((row) => [...row].length === 30));
1392
+ assert.ok(editor.render(30).some((row) => /\x1b\[7mc/.test(row)));
1393
+ } finally { editor.dispose(); }
1394
+ });
1395
+
1396
+ for (const kind of ["char", "line"] as const) {
1397
+ for (const autocomplete of [false, true]) {
1398
+ test(`VISUAL ${kind} c edits the selection with autocomplete ${autocomplete ? "visible" : "hidden"}`, () => {
1399
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1400
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1401
+ try {
1402
+ editor.setVimPolicy("on"); editor.setText(kind === "char" ? "abcd" : "one\ntwo\nthree");
1403
+ editor.handleInput("\x1b");
1404
+ if (kind === "char") { editor.handleInput("h"); editor.handleInput("h"); editor.handleInput("v"); editor.handleInput("l"); }
1405
+ else { editor.handleInput("g"); editor.handleInput("g"); editor.handleInput("V"); editor.handleInput("j"); }
1406
+ const internal = editor as unknown as { autocompleteState: string; autocompleteList: { render(width: number): string[] } };
1407
+ if (autocomplete) { internal.autocompleteState = "force"; internal.autocompleteList = { render: () => ["completion"] }; }
1408
+ editor.handleInput("c");
1409
+ assert.equal(editor.getText(), kind === "char" ? "ab" : "\nthree", "c must not be inserted or discard the unselected draft");
1410
+ assert.match(editor.render(30).join("\n"), /INSERT/);
1411
+ assert.equal(editor.isShowingAutocomplete(), false);
1412
+ } finally { editor.dispose(); }
1413
+ });
1414
+ test(`VISUAL ${kind} p replaces from register with autocomplete ${autocomplete ? "visible" : "hidden"}`, () => {
1415
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1416
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1417
+ try {
1418
+ editor.setVimPolicy("on"); editor.setText(kind === "char" ? "abc def" : "one\ntwo\nthree");
1419
+ editor.handleInput("\x1b"); editor.handleInput("g"); editor.handleInput("g");
1420
+ if (kind === "char") {
1421
+ editor.handleInput("v"); editor.handleInput("l"); editor.handleInput("y");
1422
+ editor.handleInput("w"); editor.handleInput("v"); editor.handleInput("l");
1423
+ } else {
1424
+ editor.handleInput("V"); editor.handleInput("y");
1425
+ editor.handleInput("j"); editor.handleInput("V");
1426
+ }
1427
+ const internal = editor as unknown as { autocompleteState: string; autocompleteList: { render(width: number): string[] } };
1428
+ if (autocomplete) { internal.autocompleteState = "force"; internal.autocompleteList = { render: () => ["completion"] }; }
1429
+ editor.handleInput("p");
1430
+ assert.equal(editor.getText(), kind === "char" ? "abc abf" : "one\none\nthree", "p must not insert its key or discard surrounding draft");
1431
+ assert.match(editor.render(30).join("\n"), /NORMAL/);
1432
+ assert.equal(editor.isShowingAutocomplete(), false);
1433
+ } finally { editor.dispose(); }
1434
+ });
1435
+ }
1436
+ }
1437
+
1438
+ test("VISUAL owns h/l and counts despite visible autocomplete; no bytes enter the draft", () => {
1439
+ for (const kind of ["v", "V"] as const) {
1440
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1441
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1442
+ try {
1443
+ editor.setVimPolicy("on"); editor.setText(kind === "v" ? "abcdef" : "one\ntwo\nthree\nfour");
1444
+ editor.handleInput("\x1b"); editor.handleInput("g"); editor.handleInput("g");
1445
+ editor.handleInput(kind);
1446
+ const internal = editor as unknown as { autocompleteState: string; autocompleteList: { render(width: number): string[] } };
1447
+ internal.autocompleteState = "force";
1448
+ internal.autocompleteList = { render: () => ["completion"] };
1449
+ const draft = editor.getText();
1450
+ editor.handleInput("2"); editor.handleInput(kind === "v" ? "l" : "j");
1451
+ assert.equal(editor.getText(), draft);
1452
+ assert.deepEqual(editor.getCursor(), kind === "v" ? { line: 0, col: 2 } : { line: 2, col: 0 });
1453
+ assert.match(editor.render(30).join("\n"), /VISUAL/);
1454
+ assert.equal(editor.isShowingAutocomplete(), false);
1455
+ editor.handleInput(kind === "v" ? "h" : "k");
1456
+ assert.deepEqual(editor.getCursor(), kind === "v" ? { line: 0, col: 1 } : { line: 1, col: 0 });
1457
+ assert.equal(editor.getText(), draft);
1458
+ } finally { editor.dispose(); }
1459
+ }
1460
+ });
1461
+
1462
+ test("VISUAL Escape dismisses visible autocomplete and selection without clearing the draft", () => {
1463
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1464
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1465
+ try {
1466
+ editor.setVimPolicy("on"); editor.setText("abcd"); editor.handleInput("\x1b"); editor.handleInput("h"); editor.handleInput("v");
1467
+ const internal = editor as unknown as { autocompleteState: string; autocompleteList: { render(width: number): string[] } };
1468
+ internal.autocompleteState = "force";
1469
+ internal.autocompleteList = { render: () => ["completion"] };
1470
+ editor.handleInput("\x1b");
1471
+ assert.equal(editor.getText(), "abcd");
1472
+ assert.match(editor.render(30).join("\n"), /NORMAL/);
1473
+ assert.equal(editor.isShowingAutocomplete(), false);
1474
+ } finally { editor.dispose(); }
1475
+ });
1476
+
1477
+ test("GentlePromptEditor keeps visual selection when autocomplete offers printable input", () => {
1478
+ const { pi, handlers } = fakePi();
1479
+ gentleShell(pi, {});
1480
+ const { ctx, ui } = fakeContext();
1481
+ const editor = installedPrompt(ctx, ui, handlers);
1482
+ try {
1483
+ editor.setVimPolicy("on");
1484
+ editor.setText("abcd");
1485
+ editor.handleInput("\x1b");
1486
+ editor.handleInput("h");
1487
+ editor.handleInput("h");
1488
+ editor.handleInput("v");
1489
+ editor.handleInput("l");
1490
+ const internal = editor as unknown as { autocompleteState: string; autocompleteList: { render(width: number): string[] } };
1491
+ internal.autocompleteState = "force";
1492
+ internal.autocompleteList = { render: () => ["completion"] };
1493
+ assert.deepEqual(reverseColumns(editor.render(30)[1]!), [3, 4]);
1494
+ editor.handleInput("z");
1495
+ assert.equal(editor.getText(), "abcd");
1496
+ assert.match(editor.render(30).join("\n"), /VISUAL/);
1497
+ assert.equal(editor.isShowingAutocomplete(), false);
1498
+ assert.deepEqual(reverseColumns(editor.render(30)[1]!), [3, 4], "the selected range remains anchored");
1499
+ } finally { editor.dispose(); }
1500
+ });
1501
+
1502
+ test("VISUAL autocomplete leaves app shortcut ownership ahead of c and p", () => {
1503
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1504
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1505
+ try {
1506
+ editor.setVimPolicy("on"); editor.setText("abcd"); editor.handleInput("\x1b");
1507
+ editor.handleInput("h"); editor.handleInput("v");
1508
+ const internal = editor as unknown as { autocompleteState: string; autocompleteList: { render(width: number): string[] } };
1509
+ internal.autocompleteState = "force"; internal.autocompleteList = { render: () => ["completion"] };
1510
+ let called = 0;
1511
+ editor.onExtensionShortcut = (data) => {
1512
+ if (data !== "c") return false;
1513
+ called++;
1514
+ assert.match(editor.render(30).join("\n"), /INSERT/);
1515
+ return true;
1516
+ };
1517
+ editor.handleInput("c");
1518
+ assert.equal(called, 1);
1519
+ assert.equal(editor.getText(), "abcd");
1520
+ assert.match(editor.render(30).join("\n"), /INSERT/);
1521
+ } finally { editor.dispose(); }
1522
+ });
1523
+
1524
+ test("GentlePromptEditor enters INSERT before an app shortcut writes from NORMAL", () => {
1525
+ const { pi, handlers } = fakePi();
1526
+ gentleShell(pi, {});
1527
+ const { ctx, ui } = fakeContext();
1528
+ const editor = installedPrompt(ctx, ui, handlers);
1529
+ try {
1530
+ editor.setVimPolicy("on");
1531
+ editor.setText("abcd");
1532
+ editor.handleInput("\x1b");
1533
+ editor.handleInput("h");
1534
+ editor.handleInput("h");
1535
+ editor.handleInput("v");
1536
+ editor.handleInput("l");
1537
+ editor.onExtensionShortcut = (data) => {
1538
+ if (data !== "ctrl+k") return false;
1539
+ assert.match(editor.render(30).join("\n"), /INSERT/, "the shortcut must not write in NORMAL");
1540
+ editor.insertTextAtCursor("X");
1541
+ return true;
1542
+ };
1543
+ editor.handleInput("ctrl+k");
1544
+ assert.equal(editor.getText(), "abcXd");
1545
+ assert.deepEqual(reverseColumns(editor.render(30)[1]!), [5], "the old visual range must be gone");
1546
+ } finally { editor.dispose(); }
1547
+ });
1548
+
1549
+ test("throwing shortcut probes restore NORMAL or VISUAL and permit a subsequent insert session", () => {
1550
+ for (const visual of [false, true]) {
1551
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1552
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1553
+ try {
1554
+ editor.setVimPolicy("on"); editor.setText("abcd"); editor.handleInput("\x1b");
1555
+ editor.handleInput("h"); editor.handleInput("h");
1556
+ if (visual) { editor.handleInput("v"); editor.handleInput("l"); }
1557
+ const failure = new Error("shortcut failed");
1558
+ editor.onExtensionShortcut = () => { throw failure; };
1559
+ assert.throws(() => editor.handleInput("ctrl+k"), (error) => error === failure);
1560
+ assert.equal(editor.getText(), "abcd");
1561
+ assert.match(editor.render(30).join("\n"), visual ? /VISUAL/ : /NORMAL/);
1562
+ if (visual) assert.deepEqual(reverseColumns(editor.render(30)[1]!), [3, 4]);
1563
+ editor.onExtensionShortcut = () => false;
1564
+ editor.handleInput("ctrl+k");
1565
+ assert.match(editor.render(30).join("\n"), visual ? /VISUAL/ : /NORMAL/);
1566
+ if (visual) assert.deepEqual(reverseColumns(editor.render(30)[1]!), [3, 4]);
1567
+ if (visual) editor.handleInput("\x1b");
1568
+ editor.handleInput("i"); editor.handleInput("X"); editor.handleInput("\x1b");
1569
+ assert.match(editor.getText(), /X/);
1570
+ } finally { editor.dispose(); }
1571
+ }
1572
+ });
1573
+
1574
+ test("throwing shortcuts that change a draft retain INSERT ownership from NORMAL or VISUAL", () => {
1575
+ for (const visual of [false, true]) {
1576
+ const { pi, handlers } = fakePi(); gentleShell(pi, {});
1577
+ const { ctx, ui } = fakeContext(); const editor = installedPrompt(ctx, ui, handlers);
1578
+ try {
1579
+ editor.setVimPolicy("on"); editor.setText("abcd"); editor.handleInput("\x1b");
1580
+ editor.handleInput("h"); editor.handleInput("h");
1581
+ if (visual) { editor.handleInput("v"); editor.handleInput("l"); }
1582
+ const failure = new Error("shortcut failed after writing");
1583
+ editor.onExtensionShortcut = () => { editor.insertTextAtCursor("X"); throw failure; };
1584
+ assert.throws(() => editor.handleInput("ctrl+k"), (error) => error === failure);
1585
+ assert.equal(editor.getText(), visual ? "abcXd" : "abXcd");
1586
+ assert.match(editor.render(30).join("\n"), /INSERT/);
1587
+ assert.equal(reverseColumns(editor.render(30)[1]!).length, 1, "old visual range must be gone");
1588
+ editor.onExtensionShortcut = () => false;
1589
+ editor.handleInput("Y");
1590
+ assert.match(editor.getText(), /Y/);
1591
+ } finally { editor.dispose(); }
1592
+ }
1593
+ });
1594
+
1595
+ test("unhandled shortcut and blocked printable input leave NORMAL selection unchanged", () => {
1596
+ const { pi, handlers } = fakePi();
1597
+ gentleShell(pi, {});
1598
+ const { ctx, ui } = fakeContext();
1599
+ const editor = installedPrompt(ctx, ui, handlers);
1600
+ try {
1601
+ editor.setVimPolicy("on");
1602
+ editor.setText("abcd");
1603
+ editor.handleInput("\x1b");
1604
+ editor.handleInput("h");
1605
+ editor.handleInput("h");
1606
+ editor.handleInput("v");
1607
+ editor.handleInput("l");
1608
+ editor.onExtensionShortcut = () => false;
1609
+ editor.handleInput("z");
1610
+ editor.handleInput("ctrl+k");
1611
+ assert.equal(editor.getText(), "abcd");
1612
+ assert.match(editor.render(30).join("\n"), /VISUAL/);
1613
+ assert.deepEqual(reverseColumns(editor.render(30)[1]!), [3, 4]);
1614
+ } finally { editor.dispose(); }
1615
+ });
1616
+
1617
+ function reverseColumns(row: string): number[] {
1618
+ let inverse = false;
1619
+ let column = 0;
1620
+ const selected: number[] = [];
1621
+ const tokens = row.match(/\x1b\[[0-9;]*m|\x1b_pi:c\x07|[^\x1b]/g) ?? [];
1622
+ assert.equal(tokens.join(""), row);
1623
+ for (const token of tokens) {
1624
+ if (token === CURSOR_MARKER) continue;
1625
+ if (token.startsWith("\x1b[")) {
1626
+ for (const code of token.slice(2, -1).split(";").map(Number)) {
1627
+ if (code === 0 || code === 27) inverse = false;
1628
+ if (code === 7) inverse = true;
1629
+ }
1630
+ } else {
1631
+ if (inverse) selected.push(column);
1632
+ column++;
1633
+ }
1634
+ }
1635
+ return selected;
1636
+ }
1637
+
1638
+ test("focused framed selection preserves hardware cursor position and software cursor cell", () => {
1639
+ const { pi, handlers } = fakePi();
1640
+ gentleShell(pi, {});
1641
+ const { ctx, ui } = fakeContext();
1642
+ const editor = installedPrompt(ctx, ui, handlers);
1643
+ try {
1644
+ editor.setVimPolicy("on");
1645
+ editor.setText("abcd");
1646
+ editor.focused = true;
1647
+ editor.handleInput("\x1b");
1648
+ editor.handleInput("h");
1649
+ editor.handleInput("h");
1650
+ editor.handleInput("v");
1651
+ editor.handleInput("l");
1652
+ const original = editor.render(30);
1653
+ const row = original[1]!;
1654
+ assert.ok(row.includes(CURSOR_MARKER));
1655
+ assert.equal(visibleWidth(row.split(CURSOR_MARKER)[0]!), 4,
1656
+ "frame border adds one column to the native cursor over d");
1657
+ assert.deepEqual(reverseColumns(row), [3, 4], "c is selected; d is Pi's software cursor");
1658
+ assert.ok(original.every((line) => visibleWidth(line) === 30));
1659
+ } finally { editor.dispose(); }
1660
+ });
1661
+
1662
+ test("autocomplete below a focused visual selection retains both cursor and framed row geometry", () => {
1663
+ const { pi, handlers } = fakePi();
1664
+ gentleShell(pi, {});
1665
+ const { ctx, ui } = fakeContext();
1666
+ const editor = installedPrompt(ctx, ui, handlers);
1667
+ try {
1668
+ editor.setVimPolicy("on");
1669
+ editor.setText("abcd");
1670
+ editor.handleInput("\x1b");
1671
+ editor.handleInput("h");
1672
+ editor.handleInput("h");
1673
+ editor.handleInput("v");
1674
+ editor.handleInput("l");
1675
+ editor.focused = true;
1676
+ const internal = editor as unknown as { autocompleteState: string; autocompleteList: { render(width: number): string[] } };
1677
+ internal.autocompleteState = "force";
1678
+ internal.autocompleteList = { render: () => ["completion one", "completion two"] };
1679
+ const rows = editor.render(30);
1680
+ assert.deepEqual(reverseColumns(rows[1]!), [3, 4]);
1681
+ assert.equal(visibleWidth(rows[1]!.split(CURSOR_MARKER)[0]!), 4);
1682
+ assert.match(stripAnsi(rows[2]!), /^╰.*╯$/);
1683
+ assert.deepEqual(rows.slice(3).map((row) => stripAnsi(row).slice(1, 15)), ["completion one", "completion two"]);
1684
+ assert.ok(rows.every((row) => visibleWidth(row) === 30));
1685
+ } finally { editor.dispose(); }
1686
+ });
1687
+
1688
+ test("focused framed empty logical line keeps hardware cursor at column zero inside the border", () => {
1689
+ const { pi, handlers } = fakePi();
1690
+ gentleShell(pi, {});
1691
+ const { ctx, ui } = fakeContext();
1692
+ const editor = installedPrompt(ctx, ui, handlers);
1693
+ try {
1694
+ editor.setVimPolicy("on");
1695
+ editor.setText("a\n\nb");
1696
+ editor.focused = true;
1697
+ const adapter = createVimEditorAdapter(editor, INSTALLED_PI);
1698
+ adapter.move({ line: 0, col: 0 });
1699
+ editor.handleInput("\x1b");
1700
+ editor.handleInput("v");
1701
+ adapter.move({ line: 1, col: 0 });
1702
+ const rows = editor.render(30);
1703
+ assert.deepEqual(reverseColumns(rows[1]!), [1]);
1704
+ assert.equal(visibleWidth(rows[2]!.split(CURSOR_MARKER)[0]!), 1);
1705
+ assert.deepEqual(reverseColumns(rows[2]!), [1], "only native empty-line cursor is inverted");
1706
+ assert.ok(rows.every((row) => visibleWidth(row) === 30));
1707
+ } finally { editor.dispose(); }
1708
+ });
1709
+
1710
+ test("framed scrolled paste marker paints exactly its split visible cells", () => {
1711
+ const { pi, handlers } = fakePi();
1712
+ gentleShell(pi, {});
1713
+ const { ctx, ui } = fakeContext();
1714
+ const editor = installedPrompt(ctx, ui, handlers);
1715
+ try {
1716
+ editor.setVimPolicy("on");
1717
+ editor.setText("a".repeat(100));
1718
+ editor.handleInput(`\x1b[200~${"z".repeat(1001)}\x1b[201~`);
1719
+ const pasteEnd = editor.getText().length;
1720
+ editor.insertTextAtCursor("TAIL");
1721
+ const adapter = createVimEditorAdapter(editor, INSTALLED_PI);
1722
+ adapter.move({ line: 0, col: 100 });
1723
+ editor.handleInput("\x1b");
1724
+ editor.handleInput("v");
1725
+ adapter.move({ line: 0, col: pasteEnd });
1726
+ editor.focused = true;
1727
+ const rows = editor.render(10);
1728
+ const internal = editor as unknown as { scrollOffset: number; layoutText(width: number): Array<{ text: string; hasCursor: boolean; cursorPos?: number }> };
1729
+ const layout = internal.layoutText(7);
1730
+ let offset = layout.slice(0, internal.scrollOffset).reduce((n, chunk) => n + chunk.text.length, 0);
1731
+ assert.ok(internal.scrollOffset > 0);
1732
+ const selected = rows.slice(1, -1).map((row, index) => {
1733
+ const chunk = layout[internal.scrollOffset + index]!;
1734
+ const expected = [...chunk.text].flatMap((_, col) => offset + col >= 100 && offset + col < pasteEnd ? [col + 1] : []);
1735
+ if (chunk.hasCursor && chunk.cursorPos !== undefined) expected.push(chunk.cursorPos + 1);
1736
+ offset += chunk.text.length;
1737
+ assert.deepEqual(reverseColumns(row), expected);
1738
+ assert.equal(visibleWidth(row), 10);
1739
+ return row;
1740
+ });
1741
+ assert.ok(selected.some((row) => row.includes("[")));
1742
+ assert.ok(selected.some((row) => row.includes("]")));
1743
+ assert.ok(rows.every((row) => visibleWidth(row) === 10));
1744
+ assert.equal(editor.getExpandedText(), "a".repeat(100) + "z".repeat(1001) + "TAIL");
1745
+ } finally { editor.dispose(); }
1746
+ });
1747
+
1748
+ test("owned frame fails closed when the installed TUI version does not match the adapter", () => {
1749
+ const notices: string[] = [];
1750
+ const editor = new GentlePromptEditor(fakeTui as never, editorTheme as never, fakeKeybindings as never, {
1751
+ fg: (_color, text) => text, bold: (text) => text, requestRender() {},
1752
+ pending: () => false, now: () => 0, doubleEscCancelEnabled: () => false,
1753
+ dispatchQueuedText() {}, tuiVersion: () => "0.85.1", notifyCompatibility: (message: string) => notices.push(message),
1754
+ });
1755
+ try {
1756
+ editor.setVimPolicy("on");
1757
+ editor.setText("abcd");
1758
+ editor.focused = true;
1759
+ editor.handleInput("\x1b");
1760
+ editor.handleInput("h");
1761
+ editor.handleInput("h");
1762
+ editor.handleInput("v");
1763
+ editor.handleInput("l");
1764
+ assert.equal(notices.length, 1);
1765
+ assert.match(notices[0]!, /vim.*unsupported.*ordinary editing/i);
1766
+ editor.handleInput("z");
1767
+ assert.equal(notices.length, 1);
1768
+ const frame = editor.render(30);
1769
+ assert.deepEqual(reverseColumns(frame[1]!), [10], "only Pi's own software cursor remains inverse");
1770
+ assert.equal(visibleWidth(frame[1]!.split(CURSOR_MARKER)[0]!), 10);
1771
+ assert.ok(frame.every((row) => visibleWidth(row) === 30));
1772
+ assert.equal(editor.getText(), "abcdhhvlz", "unsupported Vim never enters inert NORMAL: ordinary input still works");
1773
+ } finally { editor.dispose(); }
1774
+ });
1775
+
1776
+ test("duplicate registered paste marker disables Vim visibly and keeps ordinary editing", () => {
1777
+ const notices: string[] = [];
1778
+ const editor = new GentlePromptEditor(fakeTui as never, editorTheme as never, fakeKeybindings as never, {
1779
+ fg: (_color, text) => text, bold: (text) => text, requestRender() {},
1780
+ pending: () => false, now: () => 0, doubleEscCancelEnabled: () => false,
1781
+ dispatchQueuedText() {}, notifyCompatibility: (message: string) => notices.push(message),
1782
+ });
1783
+ try {
1784
+ editor.handleInput(`\x1b[200~${"z".repeat(1001)}\x1b[201~`);
1785
+ const markerText = editor.getText();
1786
+ editor.insertTextAtCursor(` ${markerText}`);
1787
+ const before = editor.getExpandedText();
1788
+ editor.setVimPolicy("on");
1789
+ assert.equal(notices.length, 1);
1790
+ assert.match(notices[0]!, /unsupported.*ordinary editing/i);
1791
+ editor.handleInput("x");
1792
+ assert.equal(editor.getExpandedText(), before + "x");
1793
+ } finally { editor.dispose(); }
1794
+ });
1795
+
1796
+ test("a duplicate marker introduced after Vim enable exits NORMAL with a visible warning", () => {
1797
+ const notices: string[] = [];
1798
+ const editor = new GentlePromptEditor(fakeTui as never, editorTheme as never, fakeKeybindings as never, {
1799
+ fg: (_color, text) => text, bold: (text) => text, requestRender() {},
1800
+ pending: () => false, now: () => 0, doubleEscCancelEnabled: () => false,
1801
+ dispatchQueuedText() {}, notifyCompatibility: (message: string) => notices.push(message),
1802
+ });
1803
+ try {
1804
+ editor.handleInput(`\x1b[200~${"z".repeat(1001)}\x1b[201~`);
1805
+ editor.setVimPolicy("on");
1806
+ const markerText = editor.getText();
1807
+ editor.insertTextAtCursor(` ${markerText}`);
1808
+ editor.handleInput("\x1b");
1809
+ assert.equal(notices.length, 1);
1810
+ const before = editor.getExpandedText();
1811
+ editor.handleInput("x");
1812
+ assert.equal(editor.getExpandedText(), before + "x");
1813
+ } finally { editor.dispose(); }
1814
+ });
1815
+
1816
+ test("GentlePromptEditor autocomplete respects narrow frame widths", () => {
1817
+ const { pi, handlers } = fakePi();
1818
+ gentleShell(pi, {});
1819
+ const { ctx, ui } = fakeContext();
1820
+ const editor = installedPrompt(ctx, ui, handlers);
1821
+ const internal = editor as unknown as { autocompleteState: string; autocompleteList: { render(width: number): string[] } };
1822
+ internal.autocompleteState = "force";
1823
+ internal.autocompleteList = { render: () => ["completion"] };
1824
+ try {
1825
+ for (const width of [0, 1, 2, 30]) {
1826
+ const rows = editor.render(width).map(stripAnsi);
1827
+ assert.ok(rows.every((row) => [...row].length <= width), `width ${width}: ${JSON.stringify(rows)}`);
1828
+ if (width === 30) assert.ok(rows.some((row) => row.includes("completion")));
1829
+ }
1830
+ } finally { editor.dispose(); }
1831
+ });
1832
+
1833
+ test("registered prompt stays transparent while idle, working, and queued", () => {
1834
+ const { pi, handlers, tools } = fakePi();
1835
+ gentleShell(pi, {});
1836
+ const { ctx, ui } = fakeContext();
1837
+ ctx.ui.theme = { ...plainTheme, getBgAnsi: () => "\x1b[44m" } as typeof ctx.ui.theme;
1838
+ const editor = installedPrompt(ctx, ui, handlers);
1839
+ try {
1840
+ for (const state of ["idle", "working", "queued"]) {
1841
+ if (state === "working") for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
1842
+ (ctx as unknown as { hasPendingMessages(): boolean }).hasPendingMessages = () => state === "queued";
1843
+ for (const width of [8, 40, 80]) assert.doesNotMatch(editor.render(width).join("\n"), /\x1b\[44m/, state);
1844
+ }
1845
+ } finally {
1846
+ editor.dispose();
1847
+ }
1848
+ assert.equal(tools.get("session_worktree_register")?.renderShell, "self");
1849
+ });
1850
+
1851
+ test("gentleShell shows working while the agent runs and queued when messages wait", () => {
1852
+ const { pi, handlers } = fakePi();
1853
+ gentleShell(pi, {});
1854
+ const pending = { value: false };
1855
+ const { ctx, ui } = fakeContext();
1856
+ (ctx as unknown as { hasPendingMessages: () => boolean }).hasPendingMessages = () => pending.value;
1857
+ const editor = installedPrompt(ctx, ui, handlers);
1858
+
1859
+ for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
1860
+ assert.match(stripAnsi(editor.render(60)[0]), /^╭─ ✿ working… ─+╮$/);
1861
+ pending.value = true;
1862
+ assert.match(stripAnsi(editor.render(60)[0]), /^╭─ [✿❀❁✾] queued ─+╮$/);
1863
+ for (const handler of handlers.get("agent_end") ?? []) handler({}, ctx);
1864
+ assert.match(stripAnsi(editor.render(60)[0]), /queued/, "low-level run end is not settled");
1865
+ pending.value = false;
1866
+ for (const handler of handlers.get("agent_settled") ?? []) handler({}, ctx);
1867
+ assert.match(stripAnsi(editor.render(60)[0]), /^╭─ ✿ ─+╮$/);
1868
+ editor.dispose();
1869
+ });
1870
+
1871
+ test("visual customization and Vim register once and remain independently discoverable", async (t) => {
1872
+ const home = scopedDoubleEscCancelConfigHome(t);
1873
+ const { pi, commands } = fakePi();
1874
+ const registrations: string[] = [];
1875
+ const register = pi.registerCommand.bind(pi);
1876
+ pi.registerCommand = ((name, registration) => {
1877
+ registrations.push(name);
1878
+ register(name, registration);
1879
+ }) as typeof pi.registerCommand;
1880
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
1881
+ for (const name of ["gentle:customize", "gentle:vim"]) {
1882
+ assert.equal(registrations.filter((registered) => registered === name).length, 1, `${name} must register once`);
1883
+ assert.ok(commands.has(name));
1884
+ }
1885
+ const groups = buildCommandPaletteGroups([...commands].map(([name, value]) => ({ name, description: value.description })), {});
1886
+ const configuration = groups.find((group) => group.title === "Configuration")!;
1887
+ assert.deepEqual(configuration.items.filter((item) => ["gentle:customize", "gentle:vim"].includes(item.command)).map((item) => item.command), ["gentle:customize", "gentle:vim"]);
1888
+ const { ctx, ui, overlayReady } = fakeContext();
1889
+ await commands.get("gentle:vim")!.handler("enable", ctx);
1890
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
1891
+ await overlayReady;
1892
+ assert.ok(ui.overlayView!.render(90).some((row) => row.includes("Animations: quality")));
1893
+ ui.overlayView!.handleInput("\x1b");
1894
+ await pending;
1895
+ assert.equal(JSON.parse(readFileSync(join(home, "vim.json"), "utf8")).policy, "on");
1896
+ });
1897
+
1898
+ test("actual Pi 1.0.0 enables a live prompt and enters NORMAL without a compatibility fallback", async () => {
1899
+ assert.equal(INSTALLED_PI, "1.0.0", "the shell audit must run against actual installed Pi 1.0.0");
1900
+ const configHome = mkdtempSync(join(tmpdir(), "gentle-vim-shell-"));
1901
+ const { pi, handlers, commands } = fakePi();
1902
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: configHome });
1903
+ const { ctx, ui } = fakeContext();
1904
+ const editor = installedPrompt(ctx, ui, handlers);
1905
+ editor.setText("hello");
1906
+ await commands.get("gentle:vim")!.handler("enable", ctx);
1907
+ editor.handleInput("\x1b");
1908
+ assert.equal(editor.getText(), "hello");
1909
+ assert.match(editor.render(60).join("\n"), /NORMAL/);
1910
+ assert.match(ui.notices.at(-1)!, /Prompt applies now/);
1911
+ assert.ok(ui.notices.every((notice) => !/unsupported|ordinary editing remains active|compatibility/i.test(notice)),
1912
+ "actual installed runtime must not report fallback");
1913
+ editor.handleInput("i");
1914
+ assert.match(editor.render(60).join("\n"), /INSERT/);
1915
+ editor.dispose();
1916
+ });
1917
+
1918
+ test("vim command distinguishes persisted preference from rejected live editor and recovers on next start", async () => {
1919
+ const configHome = mkdtempSync(join(tmpdir(), "gentle-vim-rejected-"));
1920
+ const { pi, handlers, commands } = fakePi();
1921
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: configHome }, { vimRuntimeVersion: () => "unsupported" });
1922
+ const { ctx, ui } = fakeContext();
1923
+ const editor = installedPrompt(ctx, ui, handlers);
1924
+ try {
1925
+ editor.setText("draft");
1926
+ await commands.get("gentle:vim")!.handler("enable", ctx);
1927
+ assert.equal(JSON.parse(readFileSync(join(configHome, "vim.json"), "utf8")).policy, "on");
1928
+ assert.match(ui.notices.at(-1)!, /vim: on.*ordinary editing remains active/i);
1929
+ assert.doesNotMatch(ui.notices.at(-1)!, /applies now/i);
1930
+ editor.handleInput("h");
1931
+ assert.equal(editor.getText(), "drafth");
1932
+ // Split bracketed paste must not leak its framing bytes or run modal commands.
1933
+ for (const part of ["\x1b[200~", "z", "\x1b[20", "1~"]) editor.handleInput(part);
1934
+ assert.equal(editor.getExpandedText(), "drafthz");
1935
+ await commands.get("gentle:vim")!.handler("status", ctx);
1936
+ assert.match(ui.notices.at(-1)!, /vim: on.*ordinary editing remains active/i);
1937
+ editor.dispose();
1938
+ const next = installedPrompt(ctx, ui, handlers);
1939
+ try {
1940
+ assert.doesNotMatch(next.render(40).join("\n"), /NORMAL|INSERT/);
1941
+ next.handleInput("h");
1942
+ assert.equal(next.getText(), "h");
1943
+ await commands.get("gentle:vim")!.handler("disable", ctx);
1944
+ assert.match(ui.notices.at(-1)!, /vim: off.*ordinary editing/i);
1945
+ } finally { next.dispose(); }
1946
+ } finally { editor.dispose(); }
1947
+ });
1948
+
1949
+ test("compatible vim command reports live activation and disable returns ordinary editing", async () => {
1950
+ const { pi, handlers, commands } = fakePi();
1951
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: mkdtempSync(join(tmpdir(), "gentle-vim-compatible-")) }, { vimRuntimeVersion: () => INSTALLED_PI });
1952
+ const { ctx, ui } = fakeContext();
1953
+ const editor = installedPrompt(ctx, ui, handlers);
1954
+ try {
1955
+ await commands.get("gentle:vim")!.handler("enable", ctx);
1956
+ assert.match(ui.notices.at(-1)!, /Prompt applies now/);
1957
+ editor.handleInput("\x1b");
1958
+ assert.match(editor.render(40).join("\n"), /NORMAL/);
1959
+ await commands.get("gentle:vim")!.handler("disable", ctx);
1960
+ assert.doesNotMatch(editor.render(40).join("\n"), /NORMAL|INSERT/);
1961
+ editor.handleInput("h");
1962
+ assert.equal(editor.getText(), "h");
1963
+ } finally { editor.dispose(); }
1964
+ });
1965
+
1966
+ test("vim NORMAL slash uses Pi's command and skill completion without displacing a draft", async () => {
1967
+ const theme = { ...editorTheme, selectList: {
1968
+ selectedText: (text: string) => text, description: (text: string) => text,
1969
+ noMatch: (text: string) => text, scrollInfo: (text: string) => text,
1970
+ } };
1971
+ const editor = new GentlePromptEditor(fakeTui as never, theme as never, {
1972
+ matches: (data: string, action: string) => action === "app.interrupt" && data === "\x1b",
1973
+ } as never, {
1974
+ fg: (_color, text) => text, bold: (text) => text, requestRender() {}, pending: () => false,
1975
+ now: () => 0, doubleEscCancelEnabled: () => false, dispatchQueuedText() {}, tuiVersion: () => INSTALLED_PI,
1976
+ });
1977
+ const entries = ["gentle:vim", "gentle:models", "skill:example"];
1978
+ const requests: string[] = [];
1979
+ editor.setAutocompleteProvider({
1980
+ async getSuggestions(lines: string[], line: number, col: number) {
1981
+ const prefix = lines[line]!.slice(0, col);
1982
+ requests.push(prefix);
1983
+ const items = entries.filter((name) => name.startsWith(prefix.slice(1))).map((name) => ({ value: `/${name}`, label: name }));
1984
+ return { prefix, items };
1985
+ },
1986
+ applyCompletion(lines: string[], line: number, col: number, selected: { value: string }) {
1987
+ return { lines: [selected.value + lines[line]!.slice(col)], cursorLine: line, cursorCol: selected.value.length };
1988
+ },
1989
+ } as never);
1990
+ try {
1991
+ editor.setVimPolicy("on");
1992
+ editor.handleInput("\x1b");
1993
+ editor.handleInput("/");
1994
+ await new Promise<void>((resolve) => setImmediate(resolve));
1995
+ assert.equal(editor.getText(), "/");
1996
+ assert.ok(editor.isShowingAutocomplete(), "Pi opens the native slash menu");
1997
+ assert.deepEqual(requests, ["/"]);
1998
+ assert.match(editor.render(40).join("\n"), /INSERT/);
1999
+ for (const char of "skill:") editor.handleInput(char);
2000
+ await new Promise<void>((resolve) => setImmediate(resolve));
2001
+ assert.equal(requests.at(-1), "/skill:");
2002
+ assert.ok(editor.isShowingAutocomplete(), "Pi filters skill entries");
2003
+ editor.handleInput("\x1b");
2004
+ assert.equal(editor.getText(), "/skill:");
2005
+ assert.equal(editor.isShowingAutocomplete(), false);
2006
+ assert.match(editor.render(40).join("\n"), /INSERT/);
2007
+ editor.handleInput("\x1b");
2008
+ assert.match(editor.render(40).join("\n"), /NORMAL/);
2009
+ editor.setText("");
2010
+ editor.handleInput("/");
2011
+ for (const char of "gentle:") editor.handleInput(char);
2012
+ await new Promise<void>((resolve) => setImmediate(resolve));
2013
+ assert.equal(requests.at(-1), "/gentle:");
2014
+ assert.ok(editor.isShowingAutocomplete(), "Pi filters command entries");
2015
+ editor.handleInput("\x1b");
2016
+ editor.handleInput("\x1b");
2017
+ editor.setText("saved draft");
2018
+ const before = requests.length;
2019
+ editor.handleInput("/");
2020
+ await new Promise<void>((resolve) => setImmediate(resolve));
2021
+ assert.equal(editor.getText(), "saved draft/", "Pi inserts slash at the cursor, without moving the draft");
2022
+ assert.equal(requests.length, before, "Pi does not open the slash menu after draft text");
2023
+ assert.equal(editor.isShowingAutocomplete(), false);
2024
+ assert.match(editor.render(40).join("\n"), /INSERT/);
2025
+ editor.handleInput("\x1b");
2026
+ assert.match(editor.render(40).join("\n"), /NORMAL/);
2027
+ editor.setVimPolicy("off");
2028
+ editor.handleInput("z");
2029
+ assert.equal(editor.getText(), "saved draft/z");
2030
+ } finally { editor.dispose(); }
2031
+ });
2032
+
2033
+ test("vim NORMAL gives extension and app shortcuts precedence over modal letters without writing in NORMAL", () => {
2034
+ const editor = new GentlePromptEditor(fakeTui as never, editorTheme as never, {
2035
+ matches: (data: string, action: string) => data === "h" && action === "app.model.select",
2036
+ } as never, {
2037
+ fg: (_color, text) => text, bold: (text) => text, requestRender() {}, pending: () => false,
2038
+ now: () => 0, doubleEscCancelEnabled: () => false, dispatchQueuedText() {},
2039
+ });
2040
+ try {
2041
+ editor.setVimPolicy("on");
2042
+ editor.setText("abcd");
2043
+ editor.handleInput("\x1b");
2044
+ const before = editor.getCursor();
2045
+ let calls = 0;
2046
+ editor.onAction("app.model.select", () => {
2047
+ calls++;
2048
+ assert.match(editor.render(30).join("\n"), /INSERT/);
2049
+ });
2050
+ editor.handleInput("h");
2051
+ assert.equal(calls, 1);
2052
+ assert.deepEqual(editor.getCursor(), before);
2053
+ assert.equal(editor.getText(), "abcd");
2054
+ editor.handleInput("\x1b");
2055
+ editor.onExtensionShortcut = (data) => {
2056
+ if (data !== "i") return false;
2057
+ calls++;
2058
+ assert.match(editor.render(30).join("\n"), /INSERT/);
2059
+ return true;
2060
+ };
2061
+ editor.handleInput("i");
2062
+ assert.equal(calls, 2);
2063
+ assert.equal(editor.getText(), "abcd");
2064
+ } finally { editor.dispose(); }
2065
+ });
2066
+
2067
+ test("vim NORMAL blocks Kitty and emoji text, handles encoded motions and ignores releases", async () => {
2068
+ const { pi, handlers, commands } = fakePi();
2069
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: mkdtempSync(join(tmpdir(), "gentle-vim-keys-")) });
2070
+ const { ctx, ui } = fakeContext();
2071
+ const editor = installedPrompt(ctx, ui, handlers, { matches: (data: string, binding: string) => binding === "app.interrupt" && data === "\x1b" });
2072
+ await commands.get("gentle:vim")!.handler("enable", ctx);
2073
+ editor.setText("ab\n雪🙂");
2074
+ editor.handleInput("\x1b");
2075
+ editor.handleInput("\x1b[120u");
2076
+ editor.handleInput("\x1b[27;1;120~");
2077
+ editor.handleInput("\x1b[200~pasted\x1b[201~");
2078
+ editor.handleInput("🙂");
2079
+ editor.handleInput("\x1b[105;1:3u");
2080
+ assert.equal(editor.getText(), "ab\n雪🙂");
2081
+ assert.match(editor.render(60).join("\n"), /NORMAL/);
2082
+ editor.handleInput("\x1b[104u");
2083
+ editor.handleInput("\x1b[105u");
2084
+ assert.match(editor.render(60).join("\n"), /INSERT/);
2085
+ editor.dispose();
2086
+ });
2087
+
2088
+ test("vim bracketed paste frames split across editor events never run NORMAL commands", () => {
2089
+ const editor = new GentlePromptEditor(fakeTui as never, editorTheme as never, fakeKeybindings as never, {
2090
+ fg: (_color, text) => text, bold: (text) => text, requestRender() {}, pending: () => false,
2091
+ now: () => 0, doubleEscCancelEnabled: () => false, dispatchQueuedText() {}, tuiVersion: () => INSTALLED_PI,
2092
+ });
2093
+ try {
2094
+ editor.setVimPolicy("on");
2095
+ editor.setText("saved draft");
2096
+ editor.handleInput("\x1b");
2097
+ for (const chunk of ["\x1b[200~", "a", "z", "\x1b[20", "1~"]) {
2098
+ editor.handleInput(chunk);
2099
+ assert.equal(editor.getText(), "saved draft", `partial paste ${JSON.stringify(chunk)}`);
2100
+ assert.match(editor.render(40).join("\n"), /NORMAL/);
2101
+ }
2102
+ editor.handleInput("i");
2103
+ assert.match(editor.render(40).join("\n"), /INSERT/);
2104
+ for (const chunk of ["\x1b[200~", "hello", "\x1b[20", "1~"]) editor.handleInput(chunk);
2105
+ assert.equal(editor.getText(), "saved drafthello");
2106
+ assert.match(editor.render(40).join("\n"), /INSERT/);
2107
+ } finally { editor.dispose(); }
2108
+ });
2109
+
2110
+ test("bracketed paste replaces native selection atomically while Vim VISUAL overflow leaves its range intact", () => {
2111
+ const payload = "z".repeat(1024 * 1024 + 1);
2112
+ const deps = {
2113
+ fg: (_color: string, text: string) => text, bold: (text: string) => text, requestRender() {}, pending: () => false,
2114
+ now: () => 0, doubleEscCancelEnabled: () => false, dispatchQueuedText() {}, tuiVersion: () => INSTALLED_PI,
2115
+ };
2116
+ const editor = new GentlePromptEditor(fakeTui as never, editorTheme as never, fakeKeybindings as never, deps);
2117
+ try {
2118
+ for (const replacement of ["new", payload]) {
2119
+ editor.setText("hello");
2120
+ editor.handleInput("\x1b[1;2H");
2121
+ editor.handleInput("\x1b[200~");
2122
+ editor.handleInput(replacement);
2123
+ editor.handleInput("\x1b[201~");
2124
+ assert.equal(editor.getExpandedText(), replacement, "paste replaces the selected draft");
2125
+ (editor as unknown as { undo(): void }).undo();
2126
+ assert.equal(editor.getText(), "hello", "one undo restores the selection's original text");
2127
+ }
2128
+ editor.setVimPolicy("on");
2129
+ editor.setText("hello");
2130
+ editor.handleInput("\x1b");
2131
+ editor.handleInput("v");
2132
+ editor.handleInput("h");
2133
+ const before = editor.render(30)[1]!;
2134
+ editor.handleInput("\x1b[200~");
2135
+ editor.handleInput(payload);
2136
+ editor.handleInput("\x1b[201~");
2137
+ assert.equal(editor.getText(), "hello", "Vim overflow is discarded, not interpreted as commands");
2138
+ assert.deepEqual(reverseColumns(editor.render(30)[1]!), reverseColumns(before), "visual selection remains active");
2139
+ } finally { editor.dispose(); }
2140
+ });
2141
+
2142
+ test("incomplete bracketed paste buffered up to exactly the 16 MiB bound still completes with one-step undo", () => {
2143
+ const BOUND = 16 * 1024 * 1024;
2144
+ const deps = {
2145
+ fg: (_color: string, text: string) => text, bold: (text: string) => text, requestRender() {}, pending: () => false,
2146
+ now: () => 0, doubleEscCancelEnabled: () => false, dispatchQueuedText() {}, tuiVersion: () => INSTALLED_PI,
2147
+ };
2148
+ const editor = new GentlePromptEditor(fakeTui as never, editorTheme as never, fakeKeybindings as never, deps);
2149
+ try {
2150
+ editor.setText("hello");
2151
+ editor.handleInput("\x1b[1;2H");
2152
+ editor.handleInput("\x1b[200~");
2153
+ const payload = "z".repeat(BOUND - "\x1b[200~".length);
2154
+ editor.handleInput(payload);
2155
+ editor.handleInput("\x1b[201~");
2156
+ assert.equal(editor.getExpandedText(), payload, "a frame buffered up to exactly the bound still completes");
2157
+ (editor as unknown as { undo(): void }).undo();
2158
+ assert.equal(editor.getText(), "hello", "one undo restores the selection's original text");
2159
+ } finally { editor.dispose(); }
2160
+ });
2161
+
2162
+ test("a complete bracketed paste larger than the 16 MiB incomplete-frame bound, delivered as one chunk, is never capped", () => {
2163
+ const BOUND = 16 * 1024 * 1024;
2164
+ const deps = {
2165
+ fg: (_color: string, text: string) => text, bold: (text: string) => text, requestRender() {}, pending: () => false,
2166
+ now: () => 0, doubleEscCancelEnabled: () => false, dispatchQueuedText() {}, tuiVersion: () => INSTALLED_PI,
2167
+ };
2168
+ const editor = new GentlePromptEditor(fakeTui as never, editorTheme as never, fakeKeybindings as never, deps);
2169
+ try {
2170
+ editor.setText("hello");
2171
+ editor.handleInput("\x1b[1;2H");
2172
+ const payload = "z".repeat(BOUND + 1024);
2173
+ editor.handleInput(`\x1b[200~${payload}\x1b[201~`);
2174
+ assert.equal(editor.getExpandedText(), payload, "a complete frame larger than the incomplete-frame bound is never capped");
2175
+ (editor as unknown as { undo(): void }).undo();
2176
+ assert.equal(editor.getText(), "hello");
2177
+ } finally { editor.dispose(); }
2178
+ });
2179
+
2180
+ test("an incomplete bracketed paste that crosses the 16 MiB bound without a terminator is abandoned, never forwarded to native", () => {
2181
+ const BOUND = 16 * 1024 * 1024;
2182
+ const deps = {
2183
+ fg: (_color: string, text: string) => text, bold: (text: string) => text, requestRender() {}, pending: () => false,
2184
+ now: () => 0, doubleEscCancelEnabled: () => false, dispatchQueuedText() {}, tuiVersion: () => INSTALLED_PI,
2185
+ };
2186
+ const editor = new GentlePromptEditor(fakeTui as never, editorTheme as never, fakeKeybindings as never, deps);
2187
+ try {
2188
+ editor.setText("hello");
2189
+ editor.handleInput("\x1b[1;2H");
2190
+ editor.handleInput("\x1b[200~");
2191
+ const payload = "z".repeat(BOUND - "\x1b[200~".length + 1);
2192
+ editor.handleInput(payload);
2193
+ assert.equal(editor.getText(), "hello", "no partial paste bytes are ever forwarded to the native editor");
2194
+ editor.handleInput("x");
2195
+ assert.equal(editor.getText(), "x", "input after abandonment behaves like a fresh keystroke over the still-active selection");
2196
+ } finally { editor.dispose(); }
2197
+ });
2198
+
2199
+ test("vim paste overflow and policy cancellation discard partial frames without leaking modal commands", () => {
2200
+ const editor = new GentlePromptEditor(fakeTui as never, editorTheme as never, fakeKeybindings as never, {
2201
+ fg: (_color, text) => text, bold: (text) => text, requestRender() {}, pending: () => false,
2202
+ now: () => 0, doubleEscCancelEnabled: () => false, dispatchQueuedText() {}, tuiVersion: () => INSTALLED_PI,
2203
+ });
2204
+ try {
2205
+ editor.setVimPolicy("on");
2206
+ editor.handleInput("\x1b[200~");
2207
+ editor.handleInput("z".repeat(1024 * 1024 + 1));
2208
+ editor.handleInput("\x1b[20");
2209
+ editor.handleInput("1~");
2210
+ assert.equal(editor.getText(), "", "oversized paste is discarded in INSERT");
2211
+ editor.handleInput("\x1b[200~");
2212
+ editor.handleInput("a");
2213
+ editor.setVimPolicy("off");
2214
+ editor.setVimPolicy("on");
2215
+ editor.handleInput("\x1b");
2216
+ editor.handleInput("z");
2217
+ assert.equal(editor.getText(), "", "canceled paste and NORMAL input remain isolated");
2218
+ assert.match(editor.render(40).join("\n"), /NORMAL/);
2219
+ } finally { editor.dispose(); }
2220
+ });
2221
+
2222
+ test("vim NORMAL rejects encoded insertions and paste without losing Unicode multiline draft", async () => {
2223
+ const { pi, handlers, commands } = fakePi();
2224
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: mkdtempSync(join(tmpdir(), "gentle-vim-safety-")) });
2225
+ const { ctx, ui } = fakeContext();
2226
+ const editor = installedPrompt(ctx, ui, handlers);
2227
+ await commands.get("gentle:vim")!.handler("enable", ctx);
2228
+ editor.setText("雪🙂\nhello");
2229
+ editor.handleInput("\x1b");
2230
+ for (const input of ["\x1b[13u", "\x1b[9u", "\x1b[200~", "pasted", "\x1b[201~", "\x1b[27;5;120~", "\x1b[27;1;120~", "\x1b[105;2u", "\x1b[105;1:2u"]) {
2231
+ editor.handleInput(input);
2232
+ assert.equal(editor.getText(), "雪🙂\nhello", `NORMAL input ${JSON.stringify(input)}`);
2233
+ }
2234
+ editor.dispose();
2235
+ });
2236
+
2237
+ test("vim NORMAL hands autocomplete and bash-mode input to Pi only after entering INSERT", () => {
2238
+ const editor = new GentlePromptEditor(fakeTui as never, editorTheme as never, fakeKeybindings as never, {
2239
+ fg: (_color, text) => text, bold: (text) => text, requestRender() {}, pending: () => false,
2240
+ now: () => 0, doubleEscCancelEnabled: () => false, dispatchQueuedText() {},
2241
+ });
2242
+ try {
2243
+ editor.setVimPolicy("on");
2244
+ editor.setText("abcd");
2245
+ editor.handleInput("\x1b");
2246
+ const internal = editor as unknown as { autocompleteState: string; autocompleteList: { render(width: number): string[] } };
2247
+ internal.autocompleteState = "force";
2248
+ internal.autocompleteList = { render: () => ["completion"] };
2249
+ editor.handleInput("z");
2250
+ assert.match(editor.render(30).join("\n"), /INSERT/);
2251
+ assert.equal(editor.getText(), "abcdz");
2252
+ internal.autocompleteState = "none";
2253
+ editor.setText("!echo");
2254
+ editor.handleInput("\x1b");
2255
+ assert.match(editor.render(30).join("\n"), /NORMAL/);
2256
+ editor.handleInput("z");
2257
+ assert.match(editor.render(30).join("\n"), /INSERT/);
2258
+ assert.equal(editor.getText(), "!echoz");
2259
+ } finally { editor.dispose(); }
2260
+ });
2261
+
2262
+ test("vim bash draft reaches Pi's Escape handler on second Esc", () => {
2263
+ const { pi, handlers } = fakePi();
2264
+ gentleShell(pi, {});
2265
+ const { ctx, ui } = fakeContext();
2266
+ const editor = installedPrompt(ctx, ui, handlers, {
2267
+ matches: (data: string, binding: string) => binding === "app.interrupt" && data === "\x1b",
2268
+ });
2269
+ try {
2270
+ editor.setVimPolicy("on");
2271
+ editor.setText("!echo");
2272
+ let escapes = 0;
2273
+ editor.onEscape = () => { escapes++; };
2274
+ editor.handleInput("\x1b");
2275
+ assert.equal(escapes, 0, "INSERT Esc only enters NORMAL");
2276
+ assert.equal(editor.getText(), "!echo");
2277
+ assert.match(editor.render(40).join("\n"), /NORMAL/);
2278
+ editor.handleInput("\x1b");
2279
+ assert.equal(escapes, 1, "NORMAL Esc reaches Pi's bash-mode Escape handler");
2280
+ assert.equal(editor.getText(), "!echo");
2281
+ } finally { editor.dispose(); }
2282
+ });
2283
+
2284
+ test("vim NORMAL motions and insert/open commands use Unicode and multiline cursor positions", () => {
2285
+ const { pi, handlers } = fakePi();
2286
+ gentleShell(pi, {});
2287
+ const { ctx, ui } = fakeContext();
2288
+ const editor = installedPrompt(ctx, ui, handlers);
2289
+ try {
2290
+ editor.setVimPolicy("on");
2291
+ editor.setText("a👩‍💻z\n snow");
2292
+ editor.handleInput("\x1b");
2293
+ createVimEditorAdapter(editor, INSTALLED_PI).move({ line: 0, col: 0 });
2294
+ for (const key of ["l", "l", "j", "k", "g", "g", "G", "0", "^", "$"]) editor.handleInput(key);
2295
+ assert.deepEqual(editor.getCursor(), { line: 1, col: 6 });
2296
+ editor.handleInput("O");
2297
+ assert.equal(editor.getText(), "a👩‍💻z\n\n snow");
2298
+ assert.deepEqual(editor.getCursor(), { line: 1, col: 0 });
2299
+ assert.match(editor.render(40).join("\n"), /INSERT/);
2300
+ } finally { editor.dispose(); }
2301
+ });
2302
+
2303
+ test("unhandled extension shortcut probes preserve pending NORMAL gg and 2j", () => {
2304
+ const { pi, handlers } = fakePi();
2305
+ gentleShell(pi, {});
2306
+ const { ctx, ui } = fakeContext();
2307
+ const editor = installedPrompt(ctx, ui, handlers);
2308
+ try {
2309
+ editor.setVimPolicy("on");
2310
+ editor.setText("a\nb\nc");
2311
+ editor.onExtensionShortcut = () => false;
2312
+ editor.handleInput("\x1b");
2313
+ editor.handleInput("g");
2314
+ editor.handleInput("g");
2315
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 0 });
2316
+ editor.handleInput("2");
2317
+ editor.handleInput("j");
2318
+ assert.deepEqual(editor.getCursor(), { line: 2, col: 0 });
2319
+ assert.match(editor.render(30).join("\n"), /NORMAL/);
2320
+ } finally { editor.dispose(); }
2321
+ });
2322
+
2323
+ test("NORMAL first non-whitespace motion and insert land after a combining grapheme", () => {
2324
+ const { pi, handlers } = fakePi();
2325
+ gentleShell(pi, {});
2326
+ const { ctx, ui } = fakeContext();
2327
+ const editor = installedPrompt(ctx, ui, handlers);
2328
+ try {
2329
+ editor.setVimPolicy("on");
2330
+ editor.setText(" \u0301a");
2331
+ editor.handleInput("\x1b");
2332
+ createVimEditorAdapter(editor, INSTALLED_PI).move({ line: 0, col: 0 });
2333
+ editor.handleInput("^");
2334
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 2 });
2335
+ createVimEditorAdapter(editor, INSTALLED_PI).move({ line: 0, col: 0 });
2336
+ editor.handleInput("I");
2337
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 2 });
2338
+ assert.match(editor.render(30).join("\n"), /INSERT/);
2339
+ } finally { editor.dispose(); }
2340
+ });
2341
+
2342
+ test("NORMAL h crosses a collapsed paste marker without entering its interior", () => {
2343
+ const { pi, handlers } = fakePi();
2344
+ gentleShell(pi, {});
2345
+ const { ctx, ui } = fakeContext();
2346
+ const editor = installedPrompt(ctx, ui, handlers);
2347
+ try {
2348
+ editor.setVimPolicy("on");
2349
+ editor.setText("a");
2350
+ editor.handleInput(`\x1b[200~${"z".repeat(1001)}\x1b[201~`);
2351
+ const before = editor.getText();
2352
+ const expanded = editor.getExpandedText();
2353
+ editor.handleInput("\x1b");
2354
+ editor.handleInput("h");
2355
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 1 });
2356
+ assert.equal(editor.getText(), before);
2357
+ assert.equal(editor.getExpandedText(), expanded);
2358
+ editor.handleInput("l");
2359
+ assert.deepEqual(editor.getCursor(), { line: 0, col: before.length });
2360
+ } finally { editor.dispose(); }
2361
+ });
2362
+
2363
+ test("vim NORMAL counted find and repeats remain Unicode/paste-safe and do not change the draft", () => {
2364
+ const { pi, handlers } = fakePi();
2365
+ gentleShell(pi, {});
2366
+ const { ctx, ui } = fakeContext();
2367
+ const editor = installedPrompt(ctx, ui, handlers);
2368
+ try {
2369
+ editor.setVimPolicy("on");
2370
+ editor.setText("a👩‍💻x👩‍💻x\nnext");
2371
+ editor.handleInput("\x1b");
2372
+ createVimEditorAdapter(editor, INSTALLED_PI).move({ line: 0, col: 0 });
2373
+ for (const key of ["2", "f", "👩‍💻"]) editor.handleInput(key);
2374
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 7 });
2375
+ editor.handleInput(",");
2376
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 1 });
2377
+ editor.handleInput(";");
2378
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 7 });
2379
+ editor.handleInput("f");
2380
+ editor.handleInput("z");
2381
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 7 }, "no match never moves onto another line");
2382
+ assert.equal(editor.getText(), "a👩‍💻x👩‍💻x\nnext");
2383
+ assert.match(editor.render(40).join("\n"), /NORMAL/);
2384
+ } finally { editor.dispose(); }
2385
+ });
2386
+
2387
+ test("vim operator session edits, cancels, and restores the draft with Pi undo", () => {
2388
+ const { pi, handlers } = fakePi();
2389
+ gentleShell(pi, {});
2390
+ const { ctx, ui } = fakeContext();
2391
+ const editor = installedPrompt(ctx, ui, handlers);
2392
+ try {
2393
+ editor.setVimPolicy("on");
2394
+ editor.setText("👩‍💻 hello\nnext");
2395
+ editor.handleInput("\x1b");
2396
+ createVimEditorAdapter(editor, INSTALLED_PI).move({ line: 0, col: 0 });
2397
+ for (const key of ["d", "w"]) editor.handleInput(key);
2398
+ assert.equal(editor.getText(), "hello\nnext");
2399
+ editor.handleInput("u");
2400
+ assert.equal(editor.getText(), "👩‍💻 hello\nnext");
2401
+ editor.handleInput("d");
2402
+ editor.handleInput("\x1b");
2403
+ editor.handleInput("l");
2404
+ assert.equal(editor.getText(), "👩‍💻 hello\nnext");
2405
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 5 });
2406
+ } finally { editor.dispose(); }
2407
+ });
2408
+
2409
+ test("vim join and shift are single undo units and Escape cancels pending shift", () => {
2410
+ const editor = new GentlePromptEditor(fakeTui as never, editorTheme as never, fakeKeybindings as never, {
2411
+ fg: (_color, text) => text, bold: (text) => text, requestRender() {}, pending: () => false,
2412
+ now: () => 0, doubleEscCancelEnabled: () => false, dispatchQueuedText() {},
2413
+ });
2414
+ try {
2415
+ editor.setVimPolicy("on");
2416
+ editor.setText("👩‍💻 one\n two\nthird");
2417
+ editor.handleInput("\x1b");
2418
+ createVimEditorAdapter(editor, INSTALLED_PI).move({ line: 0, col: 0 });
2419
+ editor.handleInput(">");
2420
+ editor.handleInput("\x1b");
2421
+ editor.handleInput("J");
2422
+ assert.equal(editor.getText(), "👩‍💻 one two\nthird");
2423
+ editor.handleInput("u");
2424
+ assert.equal(editor.getText(), "👩‍💻 one\n two\nthird");
2425
+ for (const key of ["2", ">", ">"]) editor.handleInput(key);
2426
+ assert.equal(editor.getText(), " 👩‍💻 one\n two\nthird");
2427
+ editor.handleInput("u");
2428
+ assert.equal(editor.getText(), "👩‍💻 one\n two\nthird");
2429
+ } finally { editor.dispose(); }
2430
+ });
2431
+
2432
+ test("vim operator survives an unhandled extension shortcut probe", () => {
2433
+ const editor = new GentlePromptEditor(fakeTui as never, editorTheme as never, fakeKeybindings as never, {
2434
+ fg: (_color, text) => text, bold: (text) => text, requestRender() {}, pending: () => false,
2435
+ now: () => 0, doubleEscCancelEnabled: () => false, dispatchQueuedText() {},
2436
+ });
2437
+ try {
2438
+ editor.setVimPolicy("on");
2439
+ editor.setText("abc def");
2440
+ editor.onExtensionShortcut = () => false;
2441
+ editor.handleInput("\x1b");
2442
+ createVimEditorAdapter(editor, INSTALLED_PI).move({ line: 0, col: 0 });
2443
+ editor.handleInput("d");
2444
+ editor.handleInput("w");
2445
+ assert.equal(editor.getText(), "def");
2446
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 0 });
2447
+ } finally { editor.dispose(); }
2448
+ });
2449
+
2450
+ test("vim final-line yy/P, cc and empty S keep line boundaries and INSERT state", () => {
2451
+ const editor = new GentlePromptEditor(fakeTui as never, editorTheme as never, fakeKeybindings as never, {
2452
+ fg: (_color, text) => text, bold: (text) => text, requestRender() {}, pending: () => false,
2453
+ now: () => 0, doubleEscCancelEnabled: () => false, dispatchQueuedText() {},
2454
+ });
2455
+ try {
2456
+ editor.setVimPolicy("on");
2457
+ editor.setText("one\ntwo");
2458
+ editor.handleInput("\x1b");
2459
+ createVimEditorAdapter(editor, INSTALLED_PI).move({ line: 1, col: 0 });
2460
+ for (const key of ["y", "y", "P"]) editor.handleInput(key);
2461
+ assert.equal(editor.getText(), "one\ntwo\ntwo");
2462
+ assert.deepEqual(editor.getCursor(), { line: 1, col: 0 });
2463
+ editor.handleInput("u");
2464
+ assert.equal(editor.getText(), "one\ntwo");
2465
+ createVimEditorAdapter(editor, INSTALLED_PI).move({ line: 1, col: 0 });
2466
+ for (const key of ["c", "c"]) editor.handleInput(key);
2467
+ assert.equal(editor.getText(), "one\n");
2468
+ assert.deepEqual(editor.getCursor(), { line: 1, col: 0 });
2469
+ assert.match(editor.render(40).join("\n"), /INSERT/);
2470
+ editor.setText("one");
2471
+ editor.handleInput("\x1b");
2472
+ createVimEditorAdapter(editor, INSTALLED_PI).move({ line: 0, col: 0 });
2473
+ for (const key of ["c", "c"]) editor.handleInput(key);
2474
+ assert.equal(editor.getText(), "");
2475
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 0 });
2476
+ assert.match(editor.render(40).join("\n"), /INSERT/);
2477
+ editor.handleInput("\x1b");
2478
+ editor.handleInput("S");
2479
+ assert.equal(editor.getText(), "");
2480
+ assert.match(editor.render(40).join("\n"), /INSERT/);
2481
+ } finally { editor.dispose(); }
2482
+ });
2483
+
2484
+ test("vim NORMAL Escape cancels pending find without inserting the next character", () => {
2485
+ const { pi, handlers } = fakePi();
2486
+ gentleShell(pi, {});
2487
+ const { ctx, ui } = fakeContext();
2488
+ const editor = installedPrompt(ctx, ui, handlers);
2489
+ try {
2490
+ editor.setVimPolicy("on");
2491
+ editor.setText("ax");
2492
+ editor.handleInput("\x1b");
2493
+ createVimEditorAdapter(editor, INSTALLED_PI).move({ line: 0, col: 0 });
2494
+ editor.handleInput("f");
2495
+ editor.handleInput("\x1b");
2496
+ editor.handleInput("l");
2497
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 1 }, "Escape consumes the pending find, not the next motion");
2498
+ assert.equal(editor.getText(), "ax");
2499
+ } finally { editor.dispose(); }
2500
+ });
2501
+
2502
+ test("vim NORMAL k at the first visual line does not recall history", () => {
2503
+ const { pi, handlers } = fakePi();
2504
+ gentleShell(pi, {});
2505
+ const { ctx, ui } = fakeContext();
2506
+ const editor = installedPrompt(ctx, ui, handlers, {
2507
+ matches: (data: string, binding: string) => binding === "app.interrupt" && data === "\x1b" ||
2508
+ binding === "tui.editor.historyPrevious" && data === "\x1b[A",
2509
+ });
2510
+ try {
2511
+ editor.setVimPolicy("on");
2512
+ editor.addToHistory("previous prompt");
2513
+ editor.setText("draft\nsecond line");
2514
+ editor.handleInput("\x1b");
2515
+ createVimEditorAdapter(editor, INSTALLED_PI).move({ line: 1, col: 0 });
2516
+ editor.handleInput("k");
2517
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 0 });
2518
+ const before = editor.getText();
2519
+ editor.handleInput("k");
2520
+ assert.equal(editor.getText(), before, "top-edge k must not replace the draft with history");
2521
+ assert.deepEqual(editor.getCursor(), { line: 0, col: 0 });
2522
+ assert.match(editor.render(40).join("\n"), /NORMAL/);
2523
+ createVimEditorAdapter(editor, INSTALLED_PI).move({ line: 1, col: 0 });
2524
+ editor.handleInput("j");
2525
+ assert.equal(editor.getText(), before, "bottom-edge j must not browse history");
2526
+ assert.deepEqual(editor.getCursor(), { line: 1, col: 0 });
2527
+ createVimEditorAdapter(editor, INSTALLED_PI).move({ line: 0, col: 0 });
2528
+ editor.handleInput("\x1b[A");
2529
+ assert.equal(editor.getText(), "previous prompt", "explicit Pi history binding still works");
2530
+ assert.match(editor.render(40).join("\n"), /INSERT/);
2531
+ } finally { editor.dispose(); }
2532
+ });
2533
+
2534
+ test("vim status preserves NORMAL and frame remains width-safe in every state", async () => {
2535
+ const { pi, handlers, commands } = fakePi();
2536
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: mkdtempSync(join(tmpdir(), "gentle-vim-frame-")) });
2537
+ const { ctx, ui } = fakeContext();
2538
+ const editor = installedPrompt(ctx, ui, handlers);
2539
+ await commands.get("gentle:vim")!.handler("enable", ctx);
2540
+ editor.handleInput("\x1b");
2541
+ await commands.get("gentle:vim")!.handler("status", ctx);
2542
+ for (const state of ["idle", "working", "queued"]) {
2543
+ editor.setWorking(state !== "idle");
2544
+ if (state === "queued") ctx.hasPendingMessages = () => true;
2545
+ for (const width of [12, 18, 60]) {
2546
+ const rendered = editor.render(width).map(stripAnsi);
2547
+ for (const line of rendered) assert.ok([...line].length <= width, `${state} width ${width}: ${line}`);
2548
+ if (width === 60) assert.match(editor.render(width).join("\n"), /NORMAL/);
2549
+ }
2550
+ }
2551
+ editor.dispose();
2552
+ });
2553
+
2554
+ test("vim NORMAL Escape retains working cancellation and idle draft clearing", async () => {
2555
+ const { pi, handlers, commands } = fakePi();
2556
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: mkdtempSync(join(tmpdir(), "gentle-vim-esc-")) });
2557
+ const { ctx, ui } = fakeContext();
2558
+ const editor = installedPrompt(ctx, ui, handlers, { matches: (data: string, binding: string) => binding === "app.interrupt" && data === "\x1b" });
2559
+ await commands.get("gentle:vim")!.handler("enable", ctx);
2560
+ let aborted = 0;
2561
+ editor.onEscape = () => { aborted++; };
2562
+ editor.setWorking(true);
2563
+ editor.handleInput("\x1b");
2564
+ assert.equal(aborted, 0);
2565
+ editor.handleInput("\x1b");
2566
+ assert.equal(aborted, 1);
2567
+ editor.setWorking(false);
2568
+ editor.setText("draft");
2569
+ editor.handleInput("\x1b");
2570
+ assert.equal(editor.getText(), "draft");
2571
+ editor.handleInput("\x1b");
2572
+ assert.equal(editor.getText(), "");
2573
+ editor.dispose();
2574
+ });
2575
+
2576
+ test("vim live disable restores ordinary input, re-enable starts INSERT, and invalid persisted preference fails closed", async () => {
2577
+ const home = mkdtempSync(join(tmpdir(), "gentle-vim-toggle-"));
2578
+ const { pi, handlers, commands } = fakePi();
2579
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
2580
+ const { ctx, ui } = fakeContext();
2581
+ const editor = installedPrompt(ctx, ui, handlers);
2582
+ try {
2583
+ await commands.get("gentle:vim")!.handler("enable", ctx);
2584
+ editor.setText("draft");
2585
+ editor.handleInput("\x1b");
2586
+ editor.handleInput("z");
2587
+ assert.equal(editor.getText(), "draft");
2588
+ await commands.get("gentle:vim")!.handler("disable", ctx);
2589
+ editor.handleInput("z");
2590
+ assert.equal(editor.getText(), "draftz");
2591
+ await commands.get("gentle:vim")!.handler("enable", ctx);
2592
+ assert.match(editor.render(40).join("\n"), /INSERT/);
2593
+ writeFileSync(join(home, "vim.json"), '{"schema":"gentle-pi.vim/v1","policy":"invalid"}');
2594
+ await commands.get("gentle:vim")!.handler("status", ctx);
2595
+ assert.match(ui.notices.at(-1)!, /vim: off.*falling back to off/);
2596
+ assert.doesNotMatch(editor.render(40).join("\n"), /INSERT|NORMAL/);
2597
+ } finally { editor.dispose(); }
2598
+ });
2599
+
2600
+ test("vim selector exposes enable, disable and status; status and cancellation do not write", async (t) => {
2601
+ const home = mkdtempSync(join(tmpdir(), "gentle-vim-menu-"));
2602
+ t.after(() => rmSync(home, { recursive: true, force: true }));
2603
+ const { pi, handlers, commands } = fakePi();
2604
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
2605
+ let selected: string | undefined = "enable";
2606
+ const choices: string[][] = [];
2607
+ const { ctx, ui } = fakeContext({ select: async (_title, options) => { choices.push(options); return selected; } });
2608
+ const editor = installedPrompt(ctx, ui, handlers);
2609
+ try {
2610
+ const command = commands.get("gentle:vim")!;
2611
+ await command.handler("", { ...ctx, hasUI: false });
2612
+ assert.match(ui.notices.at(-1)!, /vim: off/);
2613
+ assert.equal(existsSync(join(home, "vim.json")), false);
2614
+ await command.handler("", ctx);
2615
+ assert.deepEqual(choices.at(-1), ["enable", "disable", "status"]);
2616
+ assert.equal(JSON.parse(readFileSync(join(home, "vim.json"), "utf8")).policy, "on");
2617
+ editor.handleInput("\x1b");
2618
+ const saved = readFileSync(join(home, "vim.json"), "utf8");
2619
+ selected = "status";
2620
+ await command.handler("", ctx);
2621
+ assert.equal(readFileSync(join(home, "vim.json"), "utf8"), saved);
2622
+ assert.match(editor.render(60).join("\n"), /NORMAL/);
2623
+ selected = undefined;
2624
+ await command.handler("", ctx);
2625
+ assert.equal(readFileSync(join(home, "vim.json"), "utf8"), saved);
2626
+ selected = "disable";
2627
+ await command.handler("", ctx);
2628
+ assert.equal(JSON.parse(readFileSync(join(home, "vim.json"), "utf8")).policy, "off");
2629
+ assert.doesNotMatch(editor.render(60).join("\n"), /INSERT|NORMAL/);
2630
+ } finally { editor.dispose(); }
2631
+ });
2632
+
2633
+ test("animations command reports without writing and switches the live pulse", async (t) => {
2634
+ const configHome = scopedDoubleEscCancelConfigHome(t);
2635
+ const delays: number[] = [];
2636
+ let active = 0;
2637
+ t.mock.method(globalThis, "setInterval", (_callback: () => void, delay: number) => {
2638
+ delays.push(delay); active++; return { unref() {} };
2639
+ });
2640
+ t.mock.method(globalThis, "clearInterval", () => { active--; });
2641
+ const { pi, handlers, commands } = fakePi();
2642
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: configHome });
2643
+ const { ctx, ui } = fakeContext();
2644
+ const editor = installedPrompt(ctx, ui, handlers);
2645
+ const command = commands.get("gentle:animations");
2646
+ assert.ok(command);
2647
+ await command.handler("", ctx);
2648
+ assert.match(ui.notices.at(-1)!, /animations: quality/);
2649
+ assert.equal(existsSync(join(configHome, "animations.json")), false);
2650
+ for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
2651
+ assert.deepEqual(delays, [2000, 80]);
2652
+ await command.handler("performance", ctx);
2653
+ assert.deepEqual(delays, [2000, 80, 1000]);
2654
+ assert.equal(active, 2);
2655
+ await command.handler("potato", ctx);
2656
+ assert.equal(active, 1);
2657
+ assert.match(stripAnsi(editor.render(60)[0]), /working/);
2658
+ assert.equal(JSON.parse(readFileSync(join(configHome, "animations.json"), "utf8")).policy, "potato");
2659
+ await command.handler("invalid", ctx);
2660
+ assert.equal(JSON.parse(readFileSync(join(configHome, "animations.json"), "utf8")).policy, "potato");
2661
+ await command.handler("quality", ctx);
2662
+ assert.deepEqual(delays, [2000, 80, 1000, 80]);
2663
+ for (const handler of handlers.get("agent_settled") ?? []) handler({}, ctx);
2664
+ assert.equal(active, 1);
2665
+ editor.dispose();
2666
+ await fire(handlers, "session_shutdown", ctx);
2667
+ assert.equal(active, 0);
2668
+ });
2669
+
2670
+ test("potato repaints start/settle and shows queued state on the host's next render without intervals", async (t) => {
2671
+ const configHome = scopedDoubleEscCancelConfigHome(t);
2672
+ writeFileSync(join(configHome, "animations.json"), '{"schema":"gentle-pi.animations/v1","policy":"potato"}');
2673
+ const intervals = t.mock.method(globalThis, "setInterval", (_callback: () => void, delay: number) => {
2674
+ assert.equal(delay, 2000, "potato must not animate");
2675
+ return { unref() {} };
2676
+ });
2677
+ const renders = t.mock.method(fakeTui, "requestRender", () => {});
2678
+ const { pi, handlers, commands } = fakePi();
2679
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: configHome });
2680
+ const { ctx, ui } = fakeContext();
2681
+ const pending = { value: false };
2682
+ (ctx as unknown as { hasPendingMessages(): boolean }).hasPendingMessages = () => pending.value;
2683
+ const editor = installedPrompt(ctx, ui, handlers);
2684
+ let before = renders.mock.callCount();
2685
+ for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
2686
+ assert.ok(renders.mock.callCount() > before);
2687
+ assert.match(stripAnsi(editor.render(60)[0]), /✿ working/);
2688
+ before = renders.mock.callCount();
2689
+ pending.value = true;
2690
+ assert.equal(renders.mock.callCount(), before, "changing the queue flag is not a Gentle repaint event");
2691
+ // Pi owns enqueue and its repaint scheduling; this fake context exposes only
2692
+ // hasPendingMessages, not Pi's enqueue path. Simulate the host's render request:
2693
+ // this proves next-render visibility, not real Pi enqueue-to-paint latency.
2694
+ fakeTui.requestRender();
2695
+ assert.equal(renders.mock.callCount(), before + 1);
2696
+ assert.match(stripAnsi(editor.render(60)[0]), /✿ queued/);
2697
+ before = renders.mock.callCount();
2698
+ for (const handler of handlers.get("agent_settled") ?? []) handler({}, ctx);
2699
+ assert.ok(renders.mock.callCount() > before);
2700
+ assert.doesNotMatch(stripAnsi(editor.render(60)[0]), /working|queued/);
2701
+ await commands.get("gentle:animations")!.handler("status", ctx);
2702
+ assert.match(ui.notices.at(-1)!, /animations: potato/);
2703
+ for (const handler of handlers.get("session_shutdown") ?? []) handler({}, ctx);
2704
+ assert.equal(intervals.mock.callCount(), 1);
2705
+ });
2706
+
2707
+ test("animations status attributes malformed files and reports a failed write", async (t) => {
2708
+ const configHome = scopedDoubleEscCancelConfigHome(t);
2709
+ const path = join(configHome, "animations.json");
2710
+ writeFileSync(path, "broken");
2711
+ const { pi, commands } = fakePi();
2712
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: configHome });
2713
+ const { ctx, ui } = fakeContext();
2714
+ await commands.get("gentle:animations")!.handler("", ctx);
2715
+ assert.match(ui.notices.at(-1)!, /animations: quality.*global file.*malformed/);
2716
+ assert.equal(readFileSync(path, "utf8"), "broken");
2717
+ rmSync(path);
2718
+ mkdirSync(path);
2719
+ await commands.get("gentle:animations")!.handler("potato", ctx);
2720
+ assert.match(ui.notices.at(-1)!, /EISDIR|ENOTEMPTY|EPERM/);
2721
+ });
2722
+
2723
+ test("animations with no argument opens a selectable menu and applies the chosen policy", async (t) => {
2724
+ const configHome = scopedDoubleEscCancelConfigHome(t);
2725
+ const path = join(configHome, "animations.json");
2726
+ const { pi, commands } = fakePi();
2727
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: configHome });
2728
+ // No editor/prompt is installed: the handler's `prompt?.setAnimationPolicy`
2729
+ // optional chain must tolerate the interactive menu without one.
2730
+ const chosen = fakeContext({
2731
+ select: async (title, options) => {
2732
+ assert.match(title, /Gentle animations/);
2733
+ assert.deepEqual(options, ["quality", "performance", "potato", "status"]);
2734
+ return "potato";
2735
+ },
2736
+ });
2737
+ await commands.get("gentle:animations")!.handler("", chosen.ctx);
2738
+ assert.equal(JSON.parse(readFileSync(path, "utf8")).policy, "potato");
2739
+ assert.match(chosen.ui.notices.at(-1)!, /animations: potato/);
2740
+
2741
+ // A dismissed menu (undefined selection) reports nothing and writes nothing.
2742
+ const dismissHome = scopedDoubleEscCancelConfigHome(t);
2743
+ const { pi: dismissPi, commands: dismissCommands } = fakePi();
2744
+ gentleShell(dismissPi, { GENTLE_PI_CONFIG_HOME: dismissHome });
2745
+ const dismissed = fakeContext({ select: async () => undefined });
2746
+ await dismissCommands.get("gentle:animations")!.handler("", dismissed.ctx);
2747
+ assert.equal(dismissed.ui.notices.length, 0);
2748
+ assert.equal(existsSync(join(dismissHome, "animations.json")), false);
2749
+ });
2750
+
2751
+ test("prompt uses the compact banner cadence and releases its unref timer at settlement", async (t) => {
2752
+ const configHome = scopedDoubleEscCancelConfigHome(t);
2753
+ writeFileSync(join(configHome, "animations.json"), '{"schema":"gentle-pi.animations/v1","policy":"quality"}');
2754
+ const delays: number[] = [];
2755
+ let active = 0;
2756
+ let unrefs = 0;
2757
+ t.mock.method(globalThis, "setInterval", (_callback: () => void, delay: number) => {
2758
+ delays.push(delay);
2759
+ active++;
2760
+ return { unref() { unrefs++; } };
2761
+ });
2762
+ t.mock.method(globalThis, "clearInterval", () => { active--; });
2763
+ const { pi, handlers } = fakePi();
2764
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: configHome });
2765
+ const { ctx, ui } = fakeContext();
2766
+ const editor = installedPrompt(ctx, ui, handlers);
2767
+ assert.equal(active, 1);
2768
+ for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
2769
+ assert.deepEqual(delays, [2000, 80]);
2770
+ assert.equal(unrefs, 2);
2771
+ for (const handler of handlers.get("agent_settled") ?? []) handler({}, ctx);
2772
+ assert.equal(active, 1);
2773
+ editor.dispose();
2774
+ await fire(handlers, "session_shutdown", ctx);
2775
+ assert.equal(active, 0);
2776
+ });
2777
+
2778
+ // ---------------------------------------------------------------------------
2779
+ // double-esc-cancel (issue #1163): opt-in, off by default. While the prompt
2780
+ // is working and autocomplete is hidden, the first Esc is swallowed and the
2781
+ // frame shows a hint; a second Esc within the window falls through to
2782
+ // CustomEditor's own handleInput so Pi's onEscape performs the abort exactly
2783
+ // as it always has. Idle double-Esc (tree/fork), bash-mode Esc, and
2784
+ // autocomplete cancel live entirely in Pi's own onEscape/CustomEditor and are
2785
+ // untouched by this gate.
2786
+ // ---------------------------------------------------------------------------
2787
+
2788
+ const escapeKeybindings = { matches: (_data: string, keybinding: string) => keybinding === "app.interrupt" };
2789
+
2790
+ test("double-esc-cancel default off: a single Esc while working still aborts immediately, exactly as before", (t) => {
2791
+ const { pi, handlers } = fakePi();
2792
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: scopedDoubleEscCancelConfigHome(t) });
2793
+ const { ctx, ui } = fakeContext();
2794
+ const editor = installedPrompt(ctx, ui, handlers, escapeKeybindings);
2795
+ let aborted = 0;
2796
+ editor.onEscape = () => { aborted++; };
2797
+ for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
2798
+ editor.handleInput("\x1b");
2799
+ assert.equal(aborted, 1);
2800
+ assert.doesNotMatch(stripAnsi(editor.render(60).join("\n")), /esc again to cancel/);
2801
+ editor.dispose();
2802
+ });
2803
+
2804
+ function scopedDoubleEscCancelConfigHome(t: { after(callback: () => void): void }): string {
2805
+ const configHome = mkdtempSync(join(tmpdir(), "gp-esc-cfg-"));
2806
+ t.after(() => rmSync(configHome, { recursive: true, force: true }));
2807
+ return configHome;
2808
+ }
2809
+
2810
+ function findCustomizeRow(ui: FakeUi, label: string, width = 90): boolean {
2811
+ const view = ui.overlayView!;
2812
+ view.handleInput("\x1b[D");
2813
+ for (let category = 0; category < 10; category++) {
2814
+ view.handleInput("\x1b[C");
2815
+ for (let index = 0; index < 35; index++) {
2816
+ if (view.render(width).some((line) => line.includes(`▸ ${label}`))) return true;
2817
+ view.handleInput("\x1b[B");
2818
+ }
2819
+ view.handleInput("\x1b[D");
2820
+ view.handleInput("\x1b[B");
2821
+ }
2822
+ return false;
2823
+ }
2824
+
2825
+ async function customizeAction(ui: FakeUi, label: string): Promise<void> {
2826
+ assert.ok(findCustomizeRow(ui, label), `missing ${label}`);
2827
+ const notices = ui.notices.length;
2828
+ ui.overlayView!.handleInput("\r");
2829
+ for (let attempt = 0; attempt < 100 && ui.notices.length === notices; attempt++) await new Promise<void>((resolve) => setTimeout(resolve, 5));
2830
+ assert.ok(ui.notices.length > notices, `action did not finish: ${label}`);
2831
+ }
2832
+
2833
+ test("customize Editor rows preview global preference without applying until Enter or Space", async (t) => {
2834
+ const home = scopedDoubleEscCancelConfigHome(t);
2835
+ const { pi, commands } = fakePi();
2836
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
2837
+ const { ctx, ui, overlayReady } = fakeContext();
2838
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
2839
+ await overlayReady;
2840
+ assert.ok(findCustomizeRow(ui, "Vim: enable"));
2841
+ assert.match(ui.overlayView!.render(90).join("\n"), /Preview · Vim[\s\S]*preference: off.*effective: no active prompt/i);
2842
+ assert.equal(existsSync(join(home, "vim.json")), false);
2843
+ await customizeAction(ui, "Vim: enable");
2844
+ await new Promise<void>(resolve => setImmediate(resolve));
2845
+ assert.equal(resolveVimPolicy({ gentlePiConfigHome: home }).policy, "on");
2846
+ assert.ok(findCustomizeRow(ui, "Vim: disable"));
2847
+ assert.match(ui.overlayView!.render(90).join("\n"), /preference: on.*effective:/i);
2848
+ ui.overlayView!.handleInput(" ");
2849
+ await new Promise<void>((resolve) => setImmediate(resolve));
2850
+ assert.equal(resolveVimPolicy({ gentlePiConfigHome: home }).policy, "off");
2851
+ ui.overlayView!.handleInput("\x1b"); await pending;
2852
+ });
2853
+
2854
+ test("customize History rows persist prompt history capture and keep stored history", async (t) => {
2855
+ const home = scopedDoubleEscCancelConfigHome(t);
2856
+ const { pi, commands } = fakePi();
2857
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
2858
+ const { ctx, ui, overlayReady } = fakeContext();
2859
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
2860
+ await overlayReady;
2861
+ assert.ok(findCustomizeRow(ui, "Prompt history capture: enable"));
2862
+ assert.match(ui.overlayView!.render(90).join("\n"), /History · 1\/2/);
2863
+ assert.match(ui.overlayView!.render(90).join("\n"), /Preview · Prompt history capture[\s\S]*preference: off · effective: off/i);
2864
+ assert.equal(existsSync(join(home, "history-capture.json")), false, "highlighting never applies");
2865
+ await customizeAction(ui, "Prompt history capture: enable");
2866
+ await new Promise<void>(resolve => setImmediate(resolve));
2867
+ assert.equal(resolveHistoryCapturePolicy({ gentlePiConfigHome: home }).policy, "on");
2868
+ assert.match(ui.notices.at(-1)!, /Prompt history capture: on\. Applies from the next prompt/i);
2869
+ assert.ok(findCustomizeRow(ui, "Prompt history capture: enable (current)"));
2870
+ assert.match(ui.overlayView!.render(90).join("\n"), /preference: on · effective: on/i);
2871
+ await customizeAction(ui, "Prompt history capture: disable");
2872
+ await new Promise<void>(resolve => setImmediate(resolve));
2873
+ assert.equal(resolveHistoryCapturePolicy({ gentlePiConfigHome: home }).policy, "off");
2874
+ assert.match(ui.notices.at(-1)!, /stored history is kept/i);
2875
+ ui.overlayView!.handleInput("\x1b"); await pending;
2876
+ });
2877
+
2878
+ test("customize Cards rows persist the card style and switch live conversation cards", async (t) => {
2879
+ const home = scopedDoubleEscCancelConfigHome(t);
2880
+ const found = cardStyle();
2881
+ t.after(() => setCardStyle(found));
2882
+ const { pi, commands } = fakePi();
2883
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
2884
+ assert.equal(cardStyle(), CARD_STYLE.FLOAT, "no preference file means float");
2885
+ const { ctx, ui, overlayReady } = fakeContext();
2886
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
2887
+ await overlayReady;
2888
+ assert.ok(findCustomizeRow(ui, "Card style: float (current)"));
2889
+ assert.match(ui.overlayView!.render(90).join("\n"), /Cards · 2\/2/);
2890
+ assert.ok(findCustomizeRow(ui, "Card style: neon"));
2891
+ assert.ok(!ui.overlayView!.render(90).some((line) => line.includes("▸ Card style: neon (current)")), "neon is not current without a saved preference");
2892
+ assert.equal(existsSync(join(home, "card-style.json")), false, "highlighting never applies");
2893
+ const requestRender = fakeTui.requestRender;
2894
+ let renders = 0;
2895
+ fakeTui.requestRender = () => { renders++; };
2896
+ try {
2897
+ await customizeAction(ui, "Card style: neon");
2898
+ } finally {
2899
+ fakeTui.requestRender = requestRender;
2900
+ }
2901
+ assert.equal(resolveCardStyle({ gentlePiConfigHome: home }).style, "neon");
2902
+ assert.equal(cardStyle(), CARD_STYLE.NEON, "the live slot follows the choice");
2903
+ assert.ok(renders > 0, "conversation cards redraw");
2904
+ assert.match(ui.notices.at(-1)!, /Card style: neon/);
2905
+ assert.ok(findCustomizeRow(ui, "Card style: neon (current)"));
2906
+ assert.ok(findCustomizeRow(ui, "Card style: float"));
2907
+ await customizeAction(ui, "Card style: float");
2908
+ assert.equal(resolveCardStyle({ gentlePiConfigHome: home }).style, "float");
2909
+ assert.equal(cardStyle(), CARD_STYLE.FLOAT);
2910
+ ui.overlayView!.handleInput("\x1b"); await pending;
2911
+ });
2912
+
2913
+ test("T3 live style Cards action refreshes cached TODO, header, footer and prompt in both directions", async (t) => {
2914
+ const home = scopedDoubleEscCancelConfigHome(t);
2915
+ const previous = cardStyle();
2916
+ t.after(() => setCardStyle(previous));
2917
+ writeCardStyle(CARD_STYLE.NEON, { gentlePiConfigHome: home });
2918
+ const { pi, handlers, commands } = fakePi();
2919
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home }, { activeProfile: () => "team" });
2920
+ const { ctx, ui, overlayReady } = fakeContext();
2921
+ await fire(handlers, "session_start", ctx);
2922
+ const painted = { ...plainTheme, strikethrough: (text: string) => text, bg: (_role: string, text: string) => `\x1b[44m${text}\x1b[49m` };
2923
+ (ctx.ui as unknown as MutablePromptThemeHost).theme = painted as unknown as typeof ctx.ui.theme;
2924
+ const node = Symbol.for("@earendil-works/pi-tui/layout-node");
2925
+ const root = { render: () => ["transcript"], invalidate() {}, [node]: () => ({ type: "vstack", entries: [] }) };
2926
+ let hostRenders = 0;
2927
+ let ready = false;
2928
+ const tui = { mode: "fullscreen", terminal: { rows: 40, columns: 160 }, layoutRoot: root, requestRender() { hostRenders++; if (ready) paint(); } };
2929
+ const factory = ui.footerFactory as (tui: unknown, theme: ShellBarTheme, data: unknown) => { render(width: number): string[]; dispose(): void };
2930
+ const footer = factory(tui, painted, { getGitBranch: () => "main", getExtensionStatuses: () => new Map(), getAvailableProviderCount: () => 1, onBranchChange: () => () => {} });
2931
+ const editorFactory = ui.editorFactory as (tui: unknown, theme: unknown, keys: unknown) => GentlePromptEditor;
2932
+ const editor = editorFactory(tui, editorTheme, fakeKeybindings);
2933
+ t.after(() => { ready = false; ui.closeOverlay?.(); editor.dispose(); footer.dispose(); });
2934
+ let statusRenders = 0;
2935
+ const status = sidebarState(tui as unknown as TUI).parts.get("footer")!;
2936
+ const renderStatus = status.render.bind(status);
2937
+ status.render = (width) => { statusRenders++; return renderStatus(width); };
2938
+ let todoRenders = 0;
2939
+ sidebarPart(tui as unknown as TUI, "todo", { render: () => [], invalidate() {} }, {
2940
+ render(width) {
2941
+ todoRenders++;
2942
+ return renderTodoCard({ tasks: [{ id: 1, title: "Cached task", status: "pending" }], nextId: 2, updatedTurn: 0 }, painted, width, { scrollable: true, collapsed: false, staleTurns: 0 });
2943
+ }, invalidate() {},
2944
+ });
2945
+ let frame = { header: "", rail: "", prompt: "" };
2946
+ function paint() {
2947
+ const layout = root[node]() as unknown as { entries: { component: { render(width: number): string[]; [node](): { entries: { component: { render(width: number): string[] } }[] } } }[] };
2948
+ frame = {
2949
+ header: layout.entries[0].component.render(160).join("\n"),
2950
+ rail: layout.entries[1].component[node]().entries[1].component.render(50).join("\n"),
2951
+ prompt: editor.render(100).join("\n"),
2952
+ };
2953
+ }
2954
+ ready = true;
2955
+ paint();
2956
+ assert.equal(todoRenders, 1);
2957
+ assert.match(frame.rail, /Cached task/);
2958
+ const neon = { ...frame };
2959
+ paint();
2960
+ assert.equal(todoRenders, 1, "unchanged frame uses cached TODO");
2961
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
2962
+ await overlayReady;
2963
+ let overlayRenders = 0;
2964
+ t.mock.method(fakeTui, "requestRender", () => { overlayRenders++; });
2965
+ for (const style of [CARD_STYLE.FLOAT, CARD_STYLE.NEON]) {
2966
+ const before = { ...frame };
2967
+ const beforeHost = hostRenders;
2968
+ const beforeTodo = todoRenders;
2969
+ const beforeStatus = statusRenders;
2970
+ const beforeOverlay = overlayRenders;
2971
+ await customizeAction(ui, `Card style: ${style}`);
2972
+ assert.equal(resolveCardStyle({ gentlePiConfigHome: home }).style, style);
2973
+ assert.equal(cardStyle(), style);
2974
+ assert.ok(hostRenders > beforeHost, "action requests the main render without another state change");
2975
+ assert.ok(overlayRenders > beforeOverlay, "customize redraws too");
2976
+ assert.equal(todoRenders, beforeTodo + 1, "revision invalidation refreshes digest-less TODO");
2977
+ assert.equal(statusRenders, beforeStatus + 1, "live style digest refreshes cached Status");
2978
+ for (const key of ["header", "rail", "prompt"] as const) assert.notEqual(frame[key], before[key], `${key} changes immediately`);
2979
+ assert.match(ui.notices.at(-1)!, /Conversation cards and shell chrome redraw now/);
2980
+ assert.match(ui.overlayView!.render(90).join("\n"), /prompt|shell chrome/i);
2981
+ const rendered = { ...frame };
2982
+ paint();
2983
+ assert.equal(todoRenders, beforeTodo + 1, "next unchanged render reuses TODO");
2984
+ assert.equal(statusRenders, beforeStatus + 1, "next unchanged render reuses Status");
2985
+ assert.deepEqual(frame, rendered);
2986
+ }
2987
+ assert.deepEqual(frame, neon, "returning to neon restores approved bytes");
2988
+ ui.overlayView!.handleInput("\x1b"); await pending;
2989
+ });
2990
+
2991
+ test("T3 live style failed persistence leaves live style and sidebar revision unchanged", async (t) => {
2992
+ const home = scopedDoubleEscCancelConfigHome(t);
2993
+ const previous = cardStyle();
2994
+ t.after(() => setCardStyle(previous));
2995
+ writeCardStyle(CARD_STYLE.NEON, { gentlePiConfigHome: home });
2996
+ const { pi, handlers, commands } = fakePi();
2997
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home }, { activeProfile: () => "team" });
2998
+ const { ctx, ui, overlayReady } = fakeContext();
2999
+ await fire(handlers, "session_start", ctx);
3000
+ let renders = 0;
3001
+ const tui = { terminal: { rows: 40, columns: 160 }, requestRender() { renders++; } };
3002
+ const factory = ui.footerFactory as (tui: unknown, theme: ShellBarTheme, data: unknown) => { dispose(): void };
3003
+ const footer = factory(tui, plainTheme, { getGitBranch: () => "main", getExtensionStatuses: () => new Map(), getAvailableProviderCount: () => 1, onBranchChange: () => () => {} });
3004
+ t.after(() => footer.dispose());
3005
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3006
+ await overlayReady;
3007
+ writeFileSync(join(home, "card-style.json"), "{");
3008
+ const cache = Symbol.for("gentle-pi.experimental-sidebar.cache");
3009
+ const revision = () => (tui.terminal as unknown as Record<symbol, { revision: number }>)[cache]?.revision;
3010
+ const beforeRevision = revision();
3011
+ const beforeRenders = renders;
3012
+ await customizeAction(ui, "Card style: float");
3013
+ assert.match(ui.notices.at(-1)!, /Cannot update malformed or unreadable card style preference/);
3014
+ assert.equal(readFileSync(join(home, "card-style.json"), "utf8"), "{");
3015
+ assert.equal(cardStyle(), CARD_STYLE.NEON);
3016
+ assert.equal(revision(), beforeRevision, "failed save cannot invalidate the sidebar");
3017
+ assert.equal(renders, beforeRenders, "failed save cannot request a main redraw");
3018
+ ui.overlayView!.handleInput("\x1b"); await pending;
3019
+ });
3020
+
3021
+ test("the saved card style applies at startup and on every session start", async (t) => {
3022
+ const home = scopedDoubleEscCancelConfigHome(t);
3023
+ const found = cardStyle();
3024
+ t.after(() => setCardStyle(found));
3025
+ writeCardStyle("neon", { gentlePiConfigHome: home });
3026
+ const { pi, handlers } = fakePi();
3027
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3028
+ assert.equal(cardStyle(), CARD_STYLE.NEON);
3029
+ writeCardStyle("float", { gentlePiConfigHome: home });
3030
+ const { ctx } = fakeContext({ hasUI: false });
3031
+ for (const handler of handlers.get("session_start") ?? []) await handler({}, ctx);
3032
+ assert.equal(cardStyle(), CARD_STYLE.FLOAT);
3033
+ });
3034
+
3035
+ test("customize Cards rows refuse to overwrite a malformed preference", async (t) => {
3036
+ const home = scopedDoubleEscCancelConfigHome(t);
3037
+ const found = cardStyle();
3038
+ t.after(() => setCardStyle(found));
3039
+ writeFileSync(join(home, "card-style.json"), "{");
3040
+ const { pi, commands } = fakePi();
3041
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3042
+ const { ctx, ui, overlayReady } = fakeContext();
3043
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3044
+ await overlayReady;
3045
+ assert.ok(findCustomizeRow(ui, "Card style: float"));
3046
+ assert.match(ui.overlayView!.render(90).join("\n"), /malformed or unreadable file/i);
3047
+ ui.overlayView!.handleInput("\r");
3048
+ for (let attempt = 0; attempt < 100 && !ui.notices.some(n => /malformed or unreadable card style/i.test(n)); attempt++) await new Promise<void>((resolve) => setTimeout(resolve, 5));
3049
+ assert.ok(ui.notices.some(n => /Cannot update malformed or unreadable card style preference/i.test(n)), ui.notices.join("\n"));
3050
+ assert.equal(readFileSync(join(home, "card-style.json"), "utf8"), "{");
3051
+ assert.equal(cardStyle(), CARD_STYLE.FLOAT);
3052
+ ui.overlayView!.handleInput("\x1b"); await pending;
3053
+ });
3054
+
3055
+ test("customize History rows show when GENTLE_PI_HISTORY_CAPTURE overrides the saved preference", async (t) => {
3056
+ const home = scopedDoubleEscCancelConfigHome(t);
3057
+ writeHistoryCapturePolicy("on", { gentlePiConfigHome: home });
3058
+ const { pi, commands } = fakePi();
3059
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_HISTORY_CAPTURE: " Off " });
3060
+ const { ctx, ui, overlayReady } = fakeContext();
3061
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3062
+ await overlayReady;
3063
+ assert.ok(findCustomizeRow(ui, "Prompt history capture: enable (current) · env override"));
3064
+ assert.match(ui.overlayView!.render(90).join("\n"), /preference: on · effective: off · GENTLE_PI_HISTORY_CAPTURE overrides/i);
3065
+ await customizeAction(ui, "Prompt history capture: disable");
3066
+ await new Promise<void>(resolve => setImmediate(resolve));
3067
+ // The choice is still saved for when the env stops forcing a value.
3068
+ assert.equal(resolveHistoryCapturePolicy({ gentlePiConfigHome: home }).policy, "off");
3069
+ await customizeAction(ui, "Prompt history capture: enable");
3070
+ await new Promise<void>(resolve => setImmediate(resolve));
3071
+ assert.equal(resolveHistoryCapturePolicy({ gentlePiConfigHome: home }).policy, "on");
3072
+ assert.match(ui.notices.at(-1)!, /GENTLE_PI_HISTORY_CAPTURE=off overrides it; capture stays off/i);
3073
+ ui.overlayView!.handleInput("\x1b"); await pending;
3074
+ });
3075
+
3076
+ test("customize History rows refuse to overwrite a malformed preference and report it", async (t) => {
3077
+ const home = scopedDoubleEscCancelConfigHome(t);
3078
+ writeFileSync(join(home, "history-capture.json"), "{");
3079
+ const { pi, commands } = fakePi();
3080
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3081
+ const { ctx, ui, overlayReady } = fakeContext();
3082
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3083
+ await overlayReady;
3084
+ assert.ok(findCustomizeRow(ui, "Prompt history capture: enable"));
3085
+ assert.match(ui.overlayView!.render(90).join("\n"), /preference: off · effective: off · malformed or unreadable file/i);
3086
+ ui.overlayView!.handleInput("\r");
3087
+ for (let attempt = 0; attempt < 100 && !ui.notices.some(n => /malformed or unreadable history capture/i.test(n)); attempt++) await new Promise<void>((resolve) => setTimeout(resolve, 5));
3088
+ assert.ok(ui.notices.some(n => /Cannot update malformed or unreadable history capture preference/i.test(n)), ui.notices.join("\n"));
3089
+ assert.equal(readFileSync(join(home, "history-capture.json"), "utf8"), "{");
3090
+ ui.overlayView!.handleInput("\x1b"); await pending;
3091
+ });
3092
+
3093
+ test("external Vim preference change while customize is open never implies a compatibility failure", async (t) => {
3094
+ const home = scopedDoubleEscCancelConfigHome(t);
3095
+ const { pi, handlers, commands } = fakePi();
3096
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home }, { vimRuntimeVersion: () => INSTALLED_PI });
3097
+ const { ctx, ui, overlayReady } = fakeContext();
3098
+ const editor = installedPrompt(ctx, ui, handlers);
3099
+ try {
3100
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3101
+ await overlayReady;
3102
+ assert.ok(findCustomizeRow(ui, "Vim: enable"));
3103
+ writeVimPolicy("on", { gentlePiConfigHome: home }); // Another session changes the global preference.
3104
+ assert.equal(editor.effectiveVimPolicy, "off");
3105
+ const preview = ui.overlayView!.render(90).join("\n");
3106
+ assert.match(preview, /preference: on.*effective: off/i);
3107
+ assert.doesNotMatch(preview, /compatibility rejected|unsupported/i);
3108
+ await commands.get("gentle:vim")!.handler("status", ctx);
3109
+ assert.equal(editor.effectiveVimPolicy, "on");
3110
+ assert.doesNotMatch(ui.notices.at(-1)!, /compatibility rejected|unsupported/i);
3111
+ ui.overlayView!.handleInput("\x1b"); await pending;
3112
+ } finally { editor.dispose(); }
3113
+ });
3114
+
3115
+ test("customize updates live Vim prompt and reports unsupported effective state without attributing its cause", async (t) => {
3116
+ for (const version of [INSTALLED_PI, "unsupported"]) {
3117
+ const home = scopedDoubleEscCancelConfigHome(t);
3118
+ const { pi, handlers, commands } = fakePi();
3119
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home }, { vimRuntimeVersion: () => version });
3120
+ const { ctx, ui, overlayReady } = fakeContext();
3121
+ const editor = installedPrompt(ctx, ui, handlers);
3122
+ try {
3123
+ const pending = commands.get("gentle:customize")!.handler("", ctx); await overlayReady;
3124
+ await customizeAction(ui, "Vim: enable");
3125
+ await new Promise<void>(resolve => setImmediate(resolve));
3126
+ assert.equal(editor.effectiveVimPolicy, version === "unsupported" ? "off" : "on");
3127
+ assert.match(ui.notices.at(-1)!, version === "unsupported" ? /Effective prompt: off; saved preference and prompt differ; ordinary editing remains active/i : /Prompt applies now/i);
3128
+ assert.ok(findCustomizeRow(ui, "Vim: enable"));
3129
+ assert.match(ui.overlayView!.render(90).join("\n"), version === "unsupported" ? /preference: on.*effective: off.*preference and prompt differ/i : /preference: on.*effective: on/i);
3130
+ await customizeAction(ui, "Vim: disable");
3131
+ assert.equal(editor.effectiveVimPolicy, "off");
3132
+ ui.overlayView!.handleInput("\x1b"); await pending;
3133
+ } finally { editor.dispose(); }
3134
+ }
3135
+ });
3136
+
3137
+ test("customize Vim reports a persistence error without changing the live prompt", async (t) => {
3138
+ const home = scopedDoubleEscCancelConfigHome(t);
3139
+ const { pi, handlers, commands } = fakePi(); gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3140
+ const { ctx, ui, overlayReady } = fakeContext();
3141
+ const editor = installedPrompt(ctx, ui, handlers);
3142
+ const pending = commands.get("gentle:customize")!.handler("", ctx); await overlayReady;
3143
+ chmodSync(home, 0o500);
3144
+ try {
3145
+ await customizeAction(ui, "Vim: enable");
3146
+ assert.match(ui.notices.at(-1)!, /Visual customization:/);
3147
+ assert.equal(editor.effectiveVimPolicy, "off");
3148
+ assert.equal(resolveVimPolicy({ gentlePiConfigHome: home }).policy, "off");
3149
+ } finally {
3150
+ chmodSync(home, 0o700);
3151
+ ui.overlayView!.handleInput("\x1b"); await pending;
3152
+ editor.dispose();
3153
+ }
3154
+ });
3155
+
3156
+ test("customize Vim refuses malformed or unreadable policy without false success", async (t) => {
3157
+ const home = scopedDoubleEscCancelConfigHome(t);
3158
+ const path = join(home, "vim.json");
3159
+ writeFileSync(path, "invalid");
3160
+ const { pi, commands } = fakePi(); gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3161
+ const { ctx, ui, overlayReady } = fakeContext();
3162
+ const pending = commands.get("gentle:customize")!.handler("", ctx); await overlayReady;
3163
+ assert.ok(findCustomizeRow(ui, "Vim: enable"));
3164
+ assert.match(ui.overlayView!.render(90).join("\n"), /malformed or unreadable/i);
3165
+ await customizeAction(ui, "Vim: enable");
3166
+ assert.equal(readFileSync(path, "utf8"), "invalid");
3167
+ assert.match(ui.notices.at(-1)!, /malformed or unreadable/i);
3168
+ rmSync(path); mkdirSync(path);
3169
+ assert.ok(findCustomizeRow(ui, "Vim: disable"));
3170
+ assert.match(ui.overlayView!.render(90).join("\n"), /malformed or unreadable/i);
3171
+ await customizeAction(ui, "Vim: disable");
3172
+ assert.match(ui.notices.at(-1)!, /malformed or unreadable/i);
3173
+ assert.equal(resolveVimPolicy({ gentlePiConfigHome: home }).malformed, true);
3174
+ ui.overlayView!.handleInput("\x1b"); await pending;
3175
+ });
3176
+
3177
+ test("customize command updates displayed settings and applies layout immediately", async (t) => {
3178
+ const home = scopedDoubleEscCancelConfigHome(t);
3179
+ const { pi, commands } = fakePi();
3180
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3181
+ const { ctx, ui, overlayReady } = fakeContext();
3182
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3183
+ await overlayReady;
3184
+ assert.match(ui.overlayView!.render(90).join("\n"), /Animations: quality.*current/);
3185
+ await customizeAction(ui, "Animations: performance");
3186
+ assert.equal(resolveAnimationPolicy({ gentlePiConfigHome: home }).policy, "performance");
3187
+ assert.match(ui.overlayView!.render(90).join("\n"), /Animations: performance.*current/);
3188
+ assert.match(ui.notices.at(-1)!, /Prompt applies now.*banner.*next startup/i);
3189
+ await customizeAction(ui, "Banner rose");
3190
+ assert.equal((await readBannerConfig(home)).showRose, false);
3191
+ assert.match(ui.overlayView!.render(90).join("\n"), /Banner rose: off/);
3192
+ assert.match(ui.notices.at(-1)!, /next startup/i);
3193
+ await customizeAction(ui, "Status placement: hidden");
3194
+ assert.equal(resolveVisualSettings({ gentlePiConfigHome: home }).settings.statusPlacement, "hidden");
3195
+ assert.match(ui.overlayView!.render(90).join("\n"), /Status placement: hidden.*current/);
3196
+ assert.match(ui.notices.at(-1)!, /saved and applied/);
3197
+ ui.overlayView!.handleInput("\x1b");
3198
+ await pending;
3199
+ });
3200
+
3201
+ test("below-input header remains a fullscreen widget without the rail and follows live placement", async (t) => {
3202
+ const home = scopedDoubleEscCancelConfigHome(t);
3203
+ const { pi, handlers, commands } = fakePi();
3204
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3205
+ const { ctx, ui, overlayReady } = fakeContext();
3206
+ await fire(handlers, "session_start", ctx);
3207
+ const tui = { mode: "fullscreen", terminal: { rows: 40, columns: 180 }, requestRender() {} };
3208
+ const footer = (ui.footerFactory as (tui: unknown, theme: ShellBarTheme, data: unknown) => { dispose(): void })(tui, plainTheme, {
3209
+ getGitBranch: () => "main", getExtensionStatuses: () => new Map(), getAvailableProviderCount: () => 1, onBranchChange: () => () => {},
3210
+ });
3211
+ try {
3212
+ const widget = ui.widgets.get("gentle-shell-below-input-header") as (tui: unknown, theme: ShellBarTheme) => { render(width: number): string[] };
3213
+ assert.deepEqual(widget(tui, plainTheme).render(180), []);
3214
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3215
+ await overlayReady;
3216
+ await customizeAction(ui, "Header placement: below-input");
3217
+ assert.match(widget(tui, plainTheme).render(180).join("\n"), /Gentle Shell/);
3218
+ assert.equal(widget(tui, plainTheme).render(180).length, 2);
3219
+ tui.mode = "regular";
3220
+ assert.deepEqual(widget(tui, plainTheme).render(180), []);
3221
+ ui.overlayView!.handleInput("\x1b");
3222
+ await pending;
3223
+ } finally { footer.dispose(); }
3224
+ });
3225
+
3226
+ test("narrow fullscreen with a below-input header shows only the bottom bar, carrying the header's data and extension statuses", async (t) => {
3227
+ const home = scopedDoubleEscCancelConfigHome(t);
3228
+ const { pi, handlers, commands } = fakePi();
3229
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3230
+ const { ctx, ui, overlayReady } = fakeContext();
3231
+ await fire(handlers, "session_start", ctx);
3232
+ const tui = { mode: "fullscreen", terminal: { rows: 40, columns: 100 }, requestRender() {} };
3233
+ const footer = (ui.footerFactory as (tui: unknown, theme: ShellBarTheme, data: unknown) => { render(width: number): string[]; dispose(): void })(tui, plainTheme, {
3234
+ getGitBranch: () => "main", getExtensionStatuses: () => new Map([["mcp", "MCP: 2 servers"]]), getAvailableProviderCount: () => 1, onBranchChange: () => () => {},
3235
+ });
3236
+ try {
3237
+ const widget = ui.widgets.get("gentle-shell-below-input-header") as (tui: unknown, theme: ShellBarTheme) => { render(width: number): string[] };
3238
+ const topBottom = footer.render(100);
3239
+ assert.equal(topBottom.length, 1, "top placement keeps the compact bar contract");
3240
+ assert.match(topBottom[0]!, /gentle shell/);
3241
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3242
+ await overlayReady;
3243
+ await customizeAction(ui, "Header placement: below-input");
3244
+ assert.deepEqual(widget(tui, plainTheme).render(100), [], "no second status row below the input at narrow width");
3245
+ const narrow = footer.render(100);
3246
+ assert.equal(narrow.length, 2);
3247
+ assert.match(narrow[0]!, /Gentle Shell/, "bottom-only bar reuses the header row");
3248
+ assert.match(narrow[0]!, /ctx .* 45%/);
3249
+ assert.match(narrow[0]!, /\$0\.000 sub/);
3250
+ assert.match(narrow[0]!, /usage/);
3251
+ assert.match(narrow[1]!, /MCP: 2 servers/, "extension statuses survive on their own line");
3252
+ assert.ok(narrow.every((line) => visibleWidth(line) <= 100));
3253
+ for (const width of [60, 80]) {
3254
+ tui.terminal.columns = width;
3255
+ const mobile = footer.render(width);
3256
+ assert.match(mobile[0]!, /ctx/, `${width} keeps context before location`);
3257
+ assert.ok(mobile.every((line) => visibleWidth(line) <= width));
3258
+ }
3259
+ tui.terminal.columns = 180;
3260
+ assert.equal(widget(tui, plainTheme).render(180).length, 2, "wide keeps the below-input header");
3261
+ assert.match(footer.render(180).join("\n"), /gentle shell/, "wide keeps the compact bottom bar");
3262
+ tui.terminal.columns = 100;
3263
+ await customizeAction(ui, "Status placement: hidden");
3264
+ assert.deepEqual(footer.render(100), [], "hidden never paints a bottom bar");
3265
+ assert.equal(widget(tui, plainTheme).render(100).length, 2, "with no bottom bar the below-input header stays");
3266
+ tui.mode = "regular";
3267
+ await customizeAction(ui, "Status placement: bottom");
3268
+ assert.equal(footer.render(100).length, 1, "regular mode keeps the compact bar");
3269
+ ui.overlayView!.handleInput("\x1b");
3270
+ await pending;
3271
+ } finally { footer.dispose(); }
3272
+ });
3273
+
3274
+ test("T4d unified float footer uses one live owner and restores legacy Changes on transitions", async (t) => {
3275
+ const previous = cardStyle();
3276
+ t.after(() => setCardStyle(previous));
3277
+ const home = scopedDoubleEscCancelConfigHome(t);
3278
+ writeCardStyle("float", { gentlePiConfigHome: home });
3279
+ writeVisualSettings({ ...resolveVisualSettings({ gentlePiConfigHome: home }).settings, headerPlacement: "below-input" }, { gentlePiConfigHome: home });
3280
+ const { pi, handlers, commands } = fakePi();
3281
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3282
+ const { ctx, ui, overlayReady } = fakeContext();
3283
+ await fire(handlers, "session_start", ctx);
3284
+ const tui = { mode: "fullscreen", terminal: { rows: 40, columns: 139 }, requestRender() {} };
3285
+ const bg = "\x1b[48;5;22m";
3286
+ let hasBackground = true;
3287
+ const theme = { ...plainTheme, bg: (_role: string, text: string) => hasBackground ? `${bg}${text}\x1b[49m` : text, getBgAnsi: () => hasBackground ? bg : "" };
3288
+ const statuses = new Map([["mcp", "MCP ready"]]);
3289
+ const footer = (ui.footerFactory as (tui: unknown, theme: ShellBarTheme, data: unknown) => SidebarRail & { dispose(): void })(tui, theme, {
3290
+ getGitBranch: () => "main", getExtensionStatuses: () => statuses, getAvailableProviderCount: () => 1, onBranchChange: () => () => {},
3291
+ });
3292
+ const widget = (key: string) => (ui.widgets.get(key) as (tui: unknown, theme: ShellBarTheme) => SidebarRail)(tui, theme);
3293
+ const header = widget("gentle-shell-below-input-header");
3294
+ const state = sidebarState(tui as unknown as TUI);
3295
+ const click = (x: number, y: number, width: number): TuiMouseEvent => ({ type: "click", button: "left", x, y, screenX: x, screenY: y, width, height: 6, shift: false, alt: false, ctrl: false } as TuiMouseEvent);
3296
+ try {
3297
+ const withoutChanges = footer.render(139);
3298
+ assert.equal(withoutChanges.length, 5);
3299
+ assert.deepEqual(header.render(139), []);
3300
+ const initialUsageX = stripAnsi(withoutChanges[2]!).indexOf("usage");
3301
+ assert.equal(footer.handleMouse?.(click(initialUsageX, 3, 139)), undefined);
3302
+ assert.equal(footer.handleMouse?.(click(initialUsageX, 2, 139))?.handled, true);
3303
+ ui.closeOverlay?.();
3304
+ sessionChange(ctx, "t4d-a", "/repo", "lib/live.ts", "", "one\ntwo\n");
3305
+ await fire(handlers, "agent_end", ctx);
3306
+ const changes = widget("gentle-shell-changes");
3307
+ for (const width of [139, 140, 240]) {
3308
+ tui.terminal.columns = width;
3309
+ const rows = footer.render(width);
3310
+ assert.equal(rows.length, 6);
3311
+ assert.match(stripAnsi(rows[2]!), /1 file · \+2 −0/);
3312
+ assert.match(stripAnsi(rows[3]!), /Gentle Shell/);
3313
+ assert.match(stripAnsi(rows[4]!), /^ MCP ready/);
3314
+ assert.ok(rows.slice(1).every((row) => row.startsWith(bg)));
3315
+ assert.deepEqual(changes.render(width), []);
3316
+ assert.deepEqual(header.render(width), []);
3317
+ const usageX = stripAnsi(rows[3]!).indexOf("usage");
3318
+ assert.ok(usageX > 0);
3319
+ assert.equal(footer.handleMouse?.(click(usageX, 2, width)), undefined);
3320
+ assert.equal(footer.handleMouse?.(click(usageX, 3, width))?.handled, true);
3321
+ ui.closeOverlay?.();
3322
+ }
3323
+ const railHeader = state.parts.get("header")!;
3324
+ const digest = railHeader.digest!();
3325
+ statuses.set("mcp", "MCP updated");
3326
+ assert.notEqual(railHeader.digest!(), digest, "live status changes update the grouped digest");
3327
+ const statusDigest = railHeader.digest!();
3328
+ sessionChange(ctx, "t4d-b", "/repo", "lib/live.ts", "one\ntwo\n", "one\ntwo\nthree\n");
3329
+ await fire(handlers, "agent_end", ctx);
3330
+ assert.notEqual(railHeader.digest!(), statusDigest, "captured changes update the grouped digest");
3331
+ assert.match(stripAnsi(footer.render(240).join("\n")), /\+3 −0/);
3332
+ assert.match(stripAnsi(footer.render(240).join("\n")), /MCP updated/);
3333
+ state.active = true;
3334
+ state.ownsHost = () => true;
3335
+ assert.deepEqual(footer.render(240), [""], "suppressed float footer leaves an unpainted exterior dock row");
3336
+ assert.deepEqual(footer.render(9), [], "narrow fallback does not add spacing");
3337
+ hasBackground = false;
3338
+ assert.deepEqual(footer.render(240), [], "missing background retains the legacy dock");
3339
+ hasBackground = true;
3340
+ setCardStyle(CARD_STYLE.NEON);
3341
+ assert.deepEqual(footer.render(240), [], "neon retains the legacy dock");
3342
+ setCardStyle(CARD_STYLE.FLOAT);
3343
+ const grouped = header.render(240);
3344
+ assert.equal(grouped.length, 5, "rail owns statuses; widget owns Changes/header only");
3345
+ assert.doesNotMatch(stripAnsi(grouped.join("\n")), /MCP updated/);
3346
+ assert.deepEqual(widget("gentle-shell-changes").render(240), []);
3347
+ const usageX = stripAnsi(grouped[3]!).indexOf("usage");
3348
+ assert.equal(header.handleMouse?.(click(usageX, 2, 240)), undefined);
3349
+ assert.equal(header.handleMouse?.(click(usageX, 3, 240))?.handled, true);
3350
+ ui.closeOverlay?.();
3351
+ state.active = false;
3352
+ for (const width of [9, 10]) {
3353
+ tui.terminal.columns = width;
3354
+ assert.equal(widget("gentle-shell-changes").render(width).length, width === 9 ? 1 : 0);
3355
+ }
3356
+ tui.terminal.columns = 240;
3357
+ hasBackground = false;
3358
+ assert.equal(widget("gentle-shell-changes").render(240).length, 1, "missing background restores Changes without new evidence");
3359
+ assert.equal(header.render(240).length, 2);
3360
+ assert.equal(footer.render(240).length, 1);
3361
+ hasBackground = true;
3362
+ assert.deepEqual(widget("gentle-shell-changes").render(240), []);
3363
+ setCardStyle(CARD_STYLE.NEON);
3364
+ assert.equal(widget("gentle-shell-changes").render(240).length, 1);
3365
+ assert.equal(header.render(240).length, 2);
3366
+ setCardStyle(CARD_STYLE.FLOAT);
3367
+ tui.mode = "regular";
3368
+ assert.equal(widget("gentle-shell-changes").render(240).length, 1);
3369
+ assert.equal(footer.render(240).length, 1);
3370
+ assert.deepEqual(header.render(240), []);
3371
+ tui.mode = "fullscreen";
3372
+ const previousView = ui.overlayView;
3373
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3374
+ await overlayReady;
3375
+ for (let attempt = 0; attempt < 100 && ui.overlayView === previousView; attempt++) await new Promise<void>((resolve) => setTimeout(resolve, 5));
3376
+ await customizeAction(ui, "Status placement: hidden");
3377
+ assert.deepEqual(footer.render(240), [""], "hidden float status retains exterior dock spacing");
3378
+ assert.equal(header.render(240).length, 5);
3379
+ assert.doesNotMatch(stripAnsi(header.render(240).join("\n")), /MCP updated/);
3380
+ await customizeAction(ui, "Section changes: shown");
3381
+ assert.equal(header.render(240).length, 4);
3382
+ assert.equal(ui.widgets.has("gentle-shell-changes"), false);
3383
+ await customizeAction(ui, "Section changes: hidden");
3384
+ await customizeAction(ui, "Header placement: top");
3385
+ assert.deepEqual(header.render(240), []);
3386
+ assert.equal(widget("gentle-shell-changes").render(240).length, 1, "top placement restores standalone Changes");
3387
+ const above = railHeader.render(240);
3388
+ assert.equal(above.length, 4);
3389
+ assert.match(stripAnsi(above[1]!), /Gentle Shell/);
3390
+ assert.equal(stripAnsi(above[3]!), "▔".repeat(240));
3391
+ ui.overlayView!.handleInput("\x1b");
3392
+ await pending;
3393
+ } finally {
3394
+ footer.dispose();
3395
+ await fire(handlers, "session_shutdown", ctx);
3396
+ }
3397
+ });
3398
+
3399
+ test("customize previews installed source palette without selecting until Enter", async (t) => {
3400
+ const home = scopedDoubleEscCancelConfigHome(t);
3401
+ const source = new URL("../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/dark.json", import.meta.url).pathname;
3402
+ const { pi, commands } = fakePi();
3403
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3404
+ const { ctx, ui, overlayReady } = fakeContext();
3405
+ const themeApi = ctx.ui as unknown as { getTheme(name: string): { name: string; sourcePath?: string } | undefined; setTheme(name: string): { success: boolean } };
3406
+ const original = themeApi.getTheme;
3407
+ themeApi.getTheme = (name) => name === "dark" ? { name, sourcePath: source } : original(name);
3408
+ const applied: string[] = [];
3409
+ themeApi.setTheme = (name) => { applied.push(name); return { success: true }; };
3410
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3411
+ await overlayReady;
3412
+ assert.ok(findCustomizeRow(ui, "Theme: dark"), "missing Theme: dark");
3413
+ const lines = ui.overlayView!.render(90).join("\n");
3414
+ assert.match(lines, /dark · source palette/);
3415
+ assert.match(lines, /sample text/);
3416
+ assert.deepEqual(applied, []);
3417
+ ui.overlayView!.handleInput("\r");
3418
+ assert.deepEqual(applied, ["dark"]);
3419
+ ui.overlayView!.handleInput("\x1b");
3420
+ await pending;
3421
+ });
3422
+
3423
+ test("customize preserves invalid visual settings and reports failed theme selection", async (t) => {
3424
+ const home = scopedDoubleEscCancelConfigHome(t);
3425
+ const path = join(home, "visual-customization.json");
3426
+ writeFileSync(path, "invalid");
3427
+ const { pi, commands } = fakePi();
3428
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3429
+ const { ctx, ui, overlayReady } = fakeContext();
3430
+ const api = ctx.ui as unknown as { getTheme(name: string): unknown; setTheme(name: string): unknown };
3431
+ api.getTheme = () => undefined;
3432
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3433
+ await overlayReady;
3434
+ await customizeAction(ui, "Status placement: hidden");
3435
+ assert.equal(readFileSync(path, "utf8"), "invalid");
3436
+ assert.match(ui.notices.at(-1)!, /malformed/);
3437
+ await customizeAction(ui, "Theme: light");
3438
+ assert.match(ui.notices.at(-1)!, /unavailable/);
3439
+ ui.overlayView!.handleInput("\x1b");
3440
+ await pending;
3441
+ });
3442
+
3443
+ test("customize never overwrites malformed banner through toggle, color or reset", async (t) => {
3444
+ const home = scopedDoubleEscCancelConfigHome(t);
3445
+ const bannerPath = join(home, "banner.json");
3446
+ writeFileSync(bannerPath, "invalid banner");
3447
+ const { pi, commands } = fakePi();
3448
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3449
+ const { ctx, ui, overlayReady } = fakeContext();
3450
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3451
+ await overlayReady;
3452
+ for (const action of ["Banner rose", "Banner color: cyan", "Reset visual, banner and animation defaults"]) {
3453
+ await customizeAction(ui, action);
3454
+ assert.equal(readFileSync(bannerPath, "utf8"), "invalid banner");
3455
+ assert.match(ui.notices.at(-1)!, /malformed.*banner/i);
3456
+ }
3457
+ assert.equal(resolveVisualSettings({ gentlePiConfigHome: home }).source, "default");
3458
+ ui.overlayView!.handleInput("\x1b");
3459
+ await pending;
3460
+ });
3461
+
3462
+ test("customize refuses an unreadable banner path before modifying visual settings", async (t) => {
3463
+ const home = scopedDoubleEscCancelConfigHome(t);
3464
+ mkdirSync(join(home, "banner.json"));
3465
+ const { pi, commands } = fakePi();
3466
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3467
+ const { ctx, ui, overlayReady } = fakeContext();
3468
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3469
+ await overlayReady;
3470
+ await customizeAction(ui, "Banner color: cyan");
3471
+ assert.match(ui.notices.at(-1)!, /unreadable banner/i);
3472
+ await customizeAction(ui, "Reset visual, banner and animation defaults");
3473
+ assert.match(ui.notices.at(-1)!, /unreadable banner/i);
3474
+ assert.equal(resolveVisualSettings({ gentlePiConfigHome: home }).source, "default");
3475
+ ui.overlayView!.handleInput("\x1b");
3476
+ await pending;
3477
+ });
3478
+
3479
+ test("customize reports a partial reset and identifies committed stores on animation write failure", async (t) => {
3480
+ const home = scopedDoubleEscCancelConfigHome(t);
3481
+ const options = { gentlePiConfigHome: home };
3482
+ writeVisualSettings({ ...resolveVisualSettings(options).settings, statusPlacement: "hidden" }, options);
3483
+ mkdirSync(join(home, "animations.json"));
3484
+ const { pi, commands } = fakePi();
3485
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3486
+ const { ctx, ui, overlayReady } = fakeContext();
3487
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3488
+ await overlayReady;
3489
+ await customizeAction(ui, "Reset visual, banner and animation defaults");
3490
+ assert.equal(resolveVisualSettings(options).settings.statusPlacement, "auto");
3491
+ assert.match(ui.notices.at(-1)!, /Partial reset.*visual.*changed.*banner.*changed.*animation.*unchanged/i);
3492
+ ui.overlayView!.handleInput("\x1b");
3493
+ await pending;
3494
+ });
3495
+
3496
+ test("named profile applies installed theme, banner, animation and visual settings only after confirmation", async (t) => {
3497
+ const home = scopedDoubleEscCancelConfigHome(t);
3498
+ const options = { gentlePiConfigHome: home };
3499
+ const visual = { ...resolveVisualSettings(options).settings, statusPlacement: "hidden" as const };
3500
+ saveVisualProfile("night", { themeName: "light", animationPolicy: "performance", banner: { showRose: false, showTextLogo: true, color: "cyan" }, visual }, options);
3501
+ const { pi, commands } = fakePi();
3502
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3503
+ const { ctx, ui, overlayReady } = fakeContext();
3504
+ const applied: string[] = [];
3505
+ (ctx.ui as unknown as { setTheme(name: string): { success: boolean } }).setTheme = (name) => { applied.push(name); return { success: true }; };
3506
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3507
+ await overlayReady;
3508
+ const view = ui.overlayView!;
3509
+ view.handleInput("p");
3510
+ assert.match(view.render(90).join("\n"), /night.*Theme: light/s);
3511
+ assert.deepEqual(applied, [], "preview has no side effects");
3512
+ view.handleInput("a");
3513
+ assert.match(view.render(90).join("\n"), /Confirm apply night/);
3514
+ view.handleInput("y");
3515
+ for (let i = 0; i < 100 && !ui.notices.some(notice => /profile night applied/.test(notice)); i++) await new Promise<void>(resolve => setTimeout(resolve, 5));
3516
+ assert.deepEqual(applied, ["light"]);
3517
+ assert.equal(resolveVisualSettings(options).settings.statusPlacement, "hidden");
3518
+ assert.deepEqual(await readBannerConfig(home), { showRose: false, showTextLogo: true, color: "cyan" });
3519
+ assert.equal(resolveAnimationPolicy(options).policy, "performance");
3520
+ assert.match(ui.notices.at(-1)!, /profile night applied.*banner applies at next startup/i);
3521
+ view.handleInput("\x1b");
3522
+ view.handleInput("\x1b");
3523
+ await pending;
3524
+ });
3525
+
3526
+ test("saving a profile refuses an active theme that is not installed or resolvable", async (t) => {
3527
+ const home = scopedDoubleEscCancelConfigHome(t);
3528
+ const { pi, commands } = fakePi();
3529
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3530
+ const { ctx, ui, overlayReady } = fakeContext();
3531
+ (ctx.ui as unknown as { theme: { name: string } }).theme = { name: "phantom" };
3532
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3533
+ await overlayReady;
3534
+ const view = ui.overlayView!;
3535
+ view.handleInput("p");
3536
+ view.render(90);
3537
+ view.handleInput("s");
3538
+ for (const char of "ghost") view.handleInput(char);
3539
+ view.render(90);
3540
+ view.handleInput("\r");
3541
+ for (let i = 0; i < 100 && !ui.notices.some(notice => /unavailable|invalid/i.test(notice)); i++) await new Promise<void>(resolve => setTimeout(resolve, 5));
3542
+ assert.deepEqual(listVisualProfiles({ gentlePiConfigHome: home }), [], "no profile should be written for an unresolvable theme");
3543
+ assert.match(ui.notices.at(-1)!, /theme.*(unavailable|invalid|not installed)/i);
3544
+ view.handleInput("\x1b");
3545
+ view.handleInput("\x1b");
3546
+ await pending;
3547
+ });
3548
+
3549
+ test("saving a profile refuses a malformed or unreadable animation policy store", async (t) => {
3550
+ const home = scopedDoubleEscCancelConfigHome(t);
3551
+ mkdirSync(join(home, "animations.json"));
3552
+ const { pi, commands } = fakePi();
3553
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3554
+ const { ctx, ui, overlayReady } = fakeContext();
3555
+ (ctx.ui as unknown as { theme: { name: string } }).theme = { name: "dark" };
3556
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3557
+ await overlayReady;
3558
+ const view = ui.overlayView!;
3559
+ view.handleInput("p");
3560
+ view.render(90);
3561
+ view.handleInput("s");
3562
+ for (const char of "broken") view.handleInput(char);
3563
+ view.render(90);
3564
+ view.handleInput("\r");
3565
+ for (let i = 0; i < 100 && !ui.notices.some(notice => /animation/i.test(notice)); i++) await new Promise<void>(resolve => setTimeout(resolve, 5));
3566
+ assert.deepEqual(listVisualProfiles({ gentlePiConfigHome: home }), [], "no profile should be written while the animation store is unreadable");
3567
+ assert.match(ui.notices.at(-1)!, /(animation.*(unreadable|malformed|cannot read))|(cannot read animation)/i);
3568
+ view.handleInput("\x1b");
3569
+ view.handleInput("\x1b");
3570
+ await pending;
3571
+ });
3572
+
3573
+ test("profile save, replace, delete and reset succeed through the modal and persist to the catalog", async (t) => {
3574
+ const home = scopedDoubleEscCancelConfigHome(t);
3575
+ const { pi, commands } = fakePi();
3576
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3577
+ const { ctx, ui, overlayReady } = fakeContext();
3578
+ (ctx.ui as unknown as { theme: { name: string } }).theme = { name: "dark" };
3579
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3580
+ await overlayReady;
3581
+ const view = ui.overlayView!;
3582
+ view.handleInput("p");
3583
+ view.render(90);
3584
+ view.handleInput("s");
3585
+ for (const char of "work") view.handleInput(char);
3586
+ view.render(90);
3587
+ let before = ui.notices.length;
3588
+ view.handleInput("\r");
3589
+ for (let i = 0; i < 100 && ui.notices.length === before; i++) await new Promise<void>(resolve => setTimeout(resolve, 5));
3590
+ await new Promise<void>(resolve => setTimeout(resolve, 5));
3591
+ assert.match(ui.notices.at(-1)!, /profile work saved/i);
3592
+ assert.deepEqual(listVisualProfiles({ gentlePiConfigHome: home }), ["work"]);
3593
+ view.render(90);
3594
+ view.handleInput("r");
3595
+ view.render(90);
3596
+ before = ui.notices.length;
3597
+ view.handleInput("y");
3598
+ for (let i = 0; i < 100 && ui.notices.length === before; i++) await new Promise<void>(resolve => setTimeout(resolve, 5));
3599
+ await new Promise<void>(resolve => setTimeout(resolve, 5));
3600
+ assert.match(ui.notices.at(-1)!, /profile work saved/i);
3601
+ assert.deepEqual(listVisualProfiles({ gentlePiConfigHome: home }), ["work"], "replace keeps the same single entry");
3602
+ view.render(90);
3603
+ view.handleInput("d");
3604
+ view.render(90);
3605
+ before = ui.notices.length;
3606
+ view.handleInput("y");
3607
+ for (let i = 0; i < 100 && ui.notices.length === before; i++) await new Promise<void>(resolve => setTimeout(resolve, 5));
3608
+ await new Promise<void>(resolve => setTimeout(resolve, 5));
3609
+ assert.match(ui.notices.at(-1)!, /profile work deleted/i);
3610
+ assert.deepEqual(listVisualProfiles({ gentlePiConfigHome: home }), []);
3611
+ saveVisualProfile("leftover", { themeName: "dark", animationPolicy: "quality", banner: { showRose: true, showTextLogo: false, color: "pink" }, visual: resolveVisualSettings({ gentlePiConfigHome: home }).settings }, { gentlePiConfigHome: home });
3612
+ view.render(90);
3613
+ view.handleInput("z");
3614
+ view.render(90);
3615
+ before = ui.notices.length;
3616
+ view.handleInput("y");
3617
+ for (let i = 0; i < 100 && ui.notices.length === before; i++) await new Promise<void>(resolve => setTimeout(resolve, 5));
3618
+ assert.match(ui.notices.at(-1)!, /catalog cleared/i);
3619
+ assert.deepEqual(listVisualProfiles({ gentlePiConfigHome: home }), []);
3620
+ view.handleInput("\x1b");
3621
+ view.handleInput("\x1b");
3622
+ await pending;
3623
+ });
632
3624
 
633
- test("double-esc-cancel default off: a single Esc while working still aborts immediately, exactly as before", (t) => {
634
- const { pi, handlers } = fakePi();
635
- gentleShell(pi, { GENTLE_PI_CONFIG_HOME: scopedDoubleEscCancelConfigHome(t) });
636
- const { ctx, ui } = fakeContext();
637
- const editor = installedPrompt(ctx, ui, handlers, escapeKeybindings);
638
- let aborted = 0;
639
- editor.onEscape = () => { aborted++; };
640
- for (const handler of handlers.get("agent_start") ?? []) handler({}, ctx);
641
- editor.handleInput("\x1b");
642
- assert.equal(aborted, 1);
643
- assert.doesNotMatch(stripAnsi(editor.render(60).join("\n")), /esc again to cancel/);
644
- editor.dispose();
3625
+ test("named profile reports PARTIAL when animation store fails, and never activates an unavailable theme", async (t) => {
3626
+ const home = scopedDoubleEscCancelConfigHome(t);
3627
+ const options = { gentlePiConfigHome: home };
3628
+ const visual = { ...resolveVisualSettings(options).settings, statusPlacement: "hidden" as const };
3629
+ saveVisualProfile("missing", { themeName: "not-installed", animationPolicy: "potato", banner: { showRose: false, showTextLogo: false, color: "green" }, visual }, options);
3630
+ mkdirSync(join(home, "animations.json"));
3631
+ const { pi, commands } = fakePi();
3632
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3633
+ const { ctx, ui, overlayReady } = fakeContext();
3634
+ const applied: string[] = [];
3635
+ (ctx.ui as unknown as { setTheme(name: string): { success: boolean } }).setTheme = (name) => { applied.push(name); return { success: true }; };
3636
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3637
+ await overlayReady;
3638
+ const view = ui.overlayView!;
3639
+ view.handleInput("p");
3640
+ view.render(90);
3641
+ view.handleInput("a");
3642
+ view.render(90);
3643
+ view.handleInput("y");
3644
+ for (let i = 0; i < 100 && !ui.notices.some(notice => /PARTIAL profile apply/.test(notice)); i++) await new Promise<void>(resolve => setTimeout(resolve, 5));
3645
+ assert.deepEqual(applied, [], "unknown theme never reaches setTheme");
3646
+ assert.equal(resolveVisualSettings(options).settings.statusPlacement, "hidden");
3647
+ assert.equal((await readBannerConfig(home)).color, "green");
3648
+ assert.equal(resolveAnimationPolicy(options).policy, "quality");
3649
+ assert.match(ui.notices.at(-1)!, /PARTIAL profile apply: visual, banner changed; theme:.*unavailable.*animation:/i);
3650
+ assert.doesNotMatch(ui.notices.at(-1)!, /profile missing applied/i);
3651
+ assert.doesNotMatch(view.render(90).join("\n"), /Create theme|Edit theme|Import theme|Export theme/);
3652
+ view.handleInput("\x1b");
3653
+ view.handleInput("\x1b");
3654
+ await pending;
645
3655
  });
646
3656
 
647
- function scopedDoubleEscCancelConfigHome(t: { after(callback: () => void): void }): string {
648
- const configHome = mkdtempSync(join(tmpdir(), "gp-esc-cfg-"));
649
- t.after(() => rmSync(configHome, { recursive: true, force: true }));
650
- return configHome;
651
- }
3657
+ test("customize degrades unavailable theme APIs and refuses noninteractive UI", async (t) => {
3658
+ const home = scopedDoubleEscCancelConfigHome(t);
3659
+ const { pi, commands } = fakePi();
3660
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home });
3661
+ const { ctx, ui, overlayReady } = fakeContext();
3662
+ (ctx.ui as unknown as { getAllThemes(): unknown }).getAllThemes = () => { throw new Error("theme lookup failed"); };
3663
+ const pending = commands.get("gentle:customize")!.handler("", ctx);
3664
+ await overlayReady;
3665
+ assert.ok(findCustomizeRow(ui, "Themes unavailable; use Pi /settings"), "missing Themes unavailable message");
3666
+ ui.overlayView!.handleInput("\x1b");
3667
+ await pending;
3668
+ const { ctx: rpc, ui: rpcUi } = fakeContext();
3669
+ (rpc as unknown as { mode: string }).mode = "rpc";
3670
+ await commands.get("gentle:customize")!.handler("", rpc);
3671
+ assert.equal(rpcUi.overlayView, undefined);
3672
+ assert.match(rpcUi.notices.at(-1)!, /interactive terminal/);
3673
+ });
652
3674
 
653
3675
  test("double-esc-cancel enabled: the first Esc while working is swallowed and shows the hint instead of aborting", (t) => {
654
3676
  const configHome = scopedDoubleEscCancelConfigHome(t);
@@ -768,6 +3790,30 @@ test("working cancel: an aborted turn with a queued message sends it once settle
768
3790
  editor.dispose();
769
3791
  });
770
3792
 
3793
+ test("vim INSERT Esc only enters NORMAL; NORMAL Esc hands off queued text after settlement", async (t) => {
3794
+ const { pi, handlers, commands, sentMessages } = fakePi();
3795
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: scopedDoubleEscCancelConfigHome(t) });
3796
+ const { ctx, ui } = fakeContext();
3797
+ const editor = installedPrompt(ctx, ui, handlers, escapeKeybindings);
3798
+ try {
3799
+ await commands.get("gentle:vim")!.handler("enable", ctx);
3800
+ editor.setText("draft reply");
3801
+ let aborts = 0;
3802
+ editor.onEscape = () => { aborts++; editor.setText(`follow up\n\n${editor.getText()}`); };
3803
+ await fire(handlers, "agent_start", ctx);
3804
+ editor.handleInput("\x1b");
3805
+ assert.equal(aborts, 0);
3806
+ assert.equal(editor.getText(), "draft reply");
3807
+ assert.match(editor.render(60).join("\n"), /NORMAL/);
3808
+ editor.handleInput("\x1b");
3809
+ assert.equal(aborts, 1);
3810
+ assert.equal(editor.getText(), "draft reply");
3811
+ assert.equal(sentMessages.length, 0);
3812
+ await fire(handlers, "agent_settled", ctx);
3813
+ assert.deepEqual(sentMessages.map((message) => message.content), ["follow up"]);
3814
+ } finally { editor.dispose(); }
3815
+ });
3816
+
771
3817
  test("working cancel: an aborted turn with no queued messages behaves exactly as before, with no redundant setText", (t) => {
772
3818
  const { pi, handlers, sentMessages } = fakePi();
773
3819
  gentleShell(pi, { GENTLE_PI_CONFIG_HOME: scopedDoubleEscCancelConfigHome(t) });
@@ -1130,6 +4176,29 @@ test("idle draft: typing and deleting between two Esc presses still invalidates
1130
4176
  editor.dispose();
1131
4177
  });
1132
4178
 
4179
+ test("idle draft: selection-only input and same-character replacement cancel pending clear", (t) => {
4180
+ let now = 1_000_000;
4181
+ const { pi, handlers } = fakePi();
4182
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: scopedDoubleEscCancelConfigHome(t) }, { now: () => now });
4183
+ const { ctx, ui } = fakeContext();
4184
+ const preciseEscape = { matches: (data: string, keybinding: string) => keybinding === "app.interrupt" && data === "\x1b" };
4185
+ const editor = installedPrompt(ctx, ui, handlers, preciseEscape);
4186
+ try {
4187
+ for (const inputs of [["\x1b[1;2H"], ["\x1b[1;2H", "x"]]) {
4188
+ editor.setText("x");
4189
+ editor.handleInput("\x1b");
4190
+ for (const input of inputs) editor.handleInput(input);
4191
+ assert.equal(editor.getText(), "x", "selection or same-character replacement leaves the draft unchanged");
4192
+ assert.doesNotMatch(stripAnsi(editor.render(60).join("\n")), /esc again to clear/);
4193
+ now += 400;
4194
+ editor.handleInput("\x1b");
4195
+ assert.equal(editor.getText(), "x", "intervening input must make this a fresh first Esc");
4196
+ assert.match(stripAnsi(editor.render(60).join("\n")), /esc again to clear/);
4197
+ now += 501;
4198
+ }
4199
+ } finally { editor.dispose(); }
4200
+ });
4201
+
1133
4202
  test("idle draft: a bash-mode draft's Esc bypasses the idle-clear gate entirely", (t) => {
1134
4203
  const { pi, handlers } = fakePi();
1135
4204
  gentleShell(pi, { GENTLE_PI_CONFIG_HOME: scopedDoubleEscCancelConfigHome(t) });
@@ -1362,6 +4431,30 @@ const onlyHeadLabels = (git: readonly string[][]) => git.every((args) => {
1362
4431
  return command[0] === "symbolic-ref" || (command[0] === "rev-parse" && command.includes("--verify"));
1363
4432
  });
1364
4433
 
4434
+ test("same-session explicit registration after bootstrap does not claim Changes", async () => {
4435
+ const { pi, handlers, commands, tools, git } = fakePi();
4436
+ let bootstrapped = false;
4437
+ gentleShell(pi, { GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, {
4438
+ resolveWorktree: (path) => bootstrapped ? { root: path === "." ? "/repo" : path, commonDir: path === "/foreign" ? "/foreign/git" : "/repo/.git" } : undefined,
4439
+ });
4440
+ const { ctx, ui } = fakeContext();
4441
+ const manager = ctx.sessionManager;
4442
+ await fire(handlers, "session_start", ctx);
4443
+ const register = tools.get("session_worktree_register")!;
4444
+ await assert.rejects(register.execute("before", { path: "/repo" }, undefined, undefined, ctx), /same Git clone/);
4445
+ bootstrapped = true;
4446
+ await register.execute("after", { path: "/repo" }, undefined, undefined, ctx);
4447
+ await register.execute("dedup", { path: "/repo" }, undefined, undefined, ctx);
4448
+ await assert.rejects(register.execute("foreign", { path: "/foreign" }, undefined, undefined, ctx), /same Git clone/);
4449
+ assert.equal(ctx.sessionManager, manager);
4450
+ assert.equal(ctx.sessionManager.getEntries().length, 1);
4451
+ await commands.get("gentle:changes")!.handler("", ctx);
4452
+ assert.match(ui.notices.join("\n"), /No captured agent changes/);
4453
+ assert.equal(ui.overlay, undefined);
4454
+ assert.deepEqual(git, []);
4455
+ await fire(handlers, "session_shutdown", ctx);
4456
+ });
4457
+
1365
4458
  test("Changes opens only for captured mutations, not registered dirty roots", async () => {
1366
4459
  const {pi,handlers,commands,tools,git}=fakePi();
1367
4460
  gentleShell(pi,{});
@@ -1455,7 +4548,7 @@ test("registered canonical root governs real Git discovery, status and diff desp
1455
4548
  const discovery = await run(["worktree", "list", "--porcelain", "-z"]);
1456
4549
  assert.match(discovery.stdout, new RegExp(`worktree ${selected}`));
1457
4550
  assert.ok(!discovery.stdout.includes(foreign));
1458
- installGentleShell(h.pi, { GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, { devBinary: () => undefined, gitRunner: (cwd) => shellGitRunner(cwd, poisoned) });
4551
+ installGentleShell(h.pi, isolatedEnv({ GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }), { devBinary: () => undefined, gitRunner: (cwd) => shellGitRunner(cwd, poisoned) });
1459
4552
  await fire(h.handlers, "session_start", ctx);
1460
4553
  t.after(() => fire(h.handlers, "session_shutdown", ctx));
1461
4554
  assert.equal(ui.widgets.has("gentle-shell-changes"), false, "preexisting dirty files are not agent changes");
@@ -1850,12 +4943,13 @@ test("a registered source's rejecting fetch never crashes the shell or poisons t
1850
4943
  }
1851
4944
  assert.deepEqual(unhandled, [], "a foreign source's rejection must never surface as an unhandled rejection");
1852
4945
 
1853
- // The panel still explains itself with the pending note, never a crash,
1854
- // even through the awaited refresh openUsage runs on open.
4946
+ // The panel still explains itself with the generic failure note (the fetch
4947
+ // ran and answered nothing), never a crash, even through the awaited
4948
+ // refresh openUsage runs on open.
1855
4949
  const opened = commands.get("gentle:usage")!.handler("", ctx);
1856
4950
  await new Promise((resolve) => setTimeout(resolve, 0));
1857
4951
  const plain = ui.overlayView!.render(90).map(stripAnsi);
1858
- assert.match(plain[1], /✿ acme-cloud · no usage yet · r to fetch/);
4952
+ assert.match(plain[1], /✿ acme-cloud · fetch failed · r to retry/);
1859
4953
  ui.closeOverlay?.();
1860
4954
  await opened;
1861
4955
  });
@@ -1889,7 +4983,7 @@ test("a registered source resolving usage for another provider is rejected witho
1889
4983
  assert.match(renderFooter(ui), /nan total ▰+▱+/, "the real nan snapshot must survive a mismatched acme-cloud resolution untouched");
1890
4984
  });
1891
4985
 
1892
- test("gentleShell leaves the pending note when a registered source resolves a malformed usage", async () => {
4986
+ test("gentleShell leaves a generic failure note when a registered source resolves a malformed usage", async () => {
1893
4987
  const { pi, handlers, commands } = fakePi();
1894
4988
  gentleShell(pi, { GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, { now: () => 1_788_600_000_000 });
1895
4989
  pi.events.emit(USAGE_SOURCE_EVENT, {
@@ -1906,7 +5000,7 @@ test("gentleShell leaves the pending note when a registered source resolves a ma
1906
5000
  const opened = commands.get("gentle:usage")!.handler("", ctx);
1907
5001
  await new Promise((resolve) => setTimeout(resolve, 0));
1908
5002
  const plain = ui.overlayView!.render(90).map(stripAnsi);
1909
- assert.match(plain[1], /✿ acme-cloud · no usage yet · r to fetch/);
5003
+ assert.match(plain[1], /✿ acme-cloud · fetch failed · r to retry/);
1910
5004
  ui.closeOverlay?.();
1911
5005
  await opened;
1912
5006
  });
@@ -2005,9 +5099,12 @@ test("gentleShell binds the usage shortcut to the same handler as /gentle:usage"
2005
5099
  assert.equal(silent.shortcuts.has("alt+u"), false, "the usage shortcut must not register when disabled");
2006
5100
  });
2007
5101
 
2008
- test("gentleShell draws the review preflight message as a Gentle card", () => {
5102
+ test("gentleShell draws the review preflight message as a Gentle card", (t) => {
5103
+ const found = cardStyle();
5104
+ t.after(() => setCardStyle(found));
2009
5105
  const { pi } = fakePi();
2010
5106
  gentleShell(pi, {});
5107
+ setCardStyle(CARD_STYLE.NEON);
2011
5108
  const renderer = renderers.get("gentle-pi.review-preflight");
2012
5109
  assert.ok(renderer, "renderer not registered");
2013
5110
  const message = { customType: "gentle-pi.review-preflight", content: "Receipt-driven development is enabled.\n\nCall the gentle_review tool." };
@@ -2020,7 +5117,15 @@ test("gentleShell draws the review preflight message as a Gentle card", () => {
2020
5117
  assert.match(expanded[1], /^│ Receipt-driven development is enabled\. +│$/);
2021
5118
  assert.ok(expanded.some((line) => line.includes("gentle_review")));
2022
5119
  const collapsed = renderer({ ...message, content: [{ type: "text", text: message.content }] }, { expanded: false }, plainTheme).render(80).map(stripAnsi);
2023
- assert.equal(collapsed.length, 3);
5120
+ assert.equal(collapsed.length, 4, "collapsed previews both sentences without the blank separator");
5121
+ assert.match(collapsed[1], /^│ Receipt-driven development is enabled\. +│$/);
5122
+ assert.match(collapsed[2], /^│ Call the gentle_review tool\. +│$/);
5123
+ assert.match(collapsed[3], /^╰─+╯$/);
5124
+ const long = { ...message, content: "First sentence.\n\nSecond.\nThird.\nFourth." };
5125
+ const bounded = renderer(long, { expanded: false }, plainTheme).render(80).map(stripAnsi);
5126
+ assert.deepEqual(bounded.slice(1, -1).map((row) => row.replace(/^│ | *│$/g, "")), ["First sentence.", "Second.", "Third."]);
5127
+ assert.ok(renderer(long, { expanded: true }, plainTheme).render(80).some((line) => line.includes("Fourth.")), "expanded keeps the full notice");
5128
+ assert.deepEqual(renderer(long, { expanded: false }, plainTheme).render(0), []);
2024
5129
  });
2025
5130
 
2026
5131
  test("the review preflight card paints the rose INFO frame (border) and title (accent)", () => {
@@ -2034,16 +5139,19 @@ test("the review preflight card paints the rose INFO frame (border) and title (a
2034
5139
  assert.match(lines[0]!, /<accent>✿ Gentle AI<\/accent>/);
2035
5140
  });
2036
5141
 
2037
- test("gentleShell keeps a dev-binary override visible above the editor for the whole session", async () => {
5142
+ test("gentleShell keeps a dev-binary override visible above the editor for the whole session", async (t) => {
5143
+ const found = cardStyle();
5144
+ t.after(() => setCardStyle(found));
2038
5145
  const { pi, handlers } = fakePi();
2039
5146
  const deps = { fetch: fakeFetch({}, false).fetchFn, now: () => 0, devBinary: () => ({ state: "active" as const, path: "/Users/me/go/bin/gentle-ai", sha256: "6e53bfc6305a3949deadbeef" }) };
2040
5147
  gentleShell(pi, { GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, deps);
2041
5148
  const { ctx, ui } = fakeContext();
2042
5149
  await fire(handlers, "session_start", ctx);
5150
+ setCardStyle(CARD_STYLE.NEON);
2043
5151
  const factory = ui.widgets.get("gentle-shell-dev-binary") as (tui: unknown, theme: unknown) => { render(width: number): string[] };
2044
5152
  assert.ok(factory, "dev binary widget missing");
2045
5153
  const lines = factory(fakeTui, plainTheme).render(100).map(stripAnsi);
2046
- assert.match(lines[0], /^╭─ ✿ Gentle AI · dev binary override · field-test only ─+╮$/);
5154
+ assert.match(lines[0], /^╭─ \u{1F339} gentle-ai · dev binary override · field-test only ─+╮$/u, "the override notice carries the Gentle AI rose");
2047
5155
  assert.match(lines[1], /^│ \/Users\/me\/go\/bin\/gentle-ai · sha256:6e53bfc6305a3949 +│$/);
2048
5156
  assert.match(lines[2], /^╰─+╯$/);
2049
5157
  assert.equal(lines[3], "", "a blank line keeps the card off the prompt frame");
@@ -2061,7 +5169,10 @@ test("gentleShell keeps a dev-binary override visible above the editor for the w
2061
5169
  await fire(clean.handlers, "session_start", fresh.ctx);
2062
5170
  assert.equal(fresh.ui.widgets.has("gentle-shell-dev-binary"), false);
2063
5171
 
2064
- assert.equal(devBinaryCard({ state: "invalid", reason: "binary missing" }).tone, "error");
5172
+ const invalid = devBinaryCard({ state: "invalid", reason: "binary missing" });
5173
+ assert.equal(invalid.tone, "error");
5174
+ assert.equal(invalid.glyph, "\u{1F339}", "the invalid override notice keeps the rose too");
5175
+ assert.deepEqual(factory(fakeTui, plainTheme).render(0), [""], "zero width keeps only the spacer");
2065
5176
  });
2066
5177
 
2067
5178
  test("gentle:commands registers alt+k by default", () => {
@@ -2180,3 +5291,544 @@ test("resolving the overlay through closeOverlay sends nothing and does not thro
2180
5291
  await opened;
2181
5292
  assert.deepEqual(sentMessages, []);
2182
5293
  });
5294
+
5295
+ // Targeted usage scope: the session's own provider plus every provider the
5296
+ // active profile's subagent routing names, honoring a repository pin over the
5297
+ // global active profile.
5298
+
5299
+ function writeProfilesStore(home: string, profiles: Record<string, unknown>, active?: string): void {
5300
+ writeFileSync(join(home, "profiles.json"), JSON.stringify({ kind: "gentle-pi.agent_model_profiles", version: 1, ...(active ? { active } : {}), profiles }));
5301
+ }
5302
+
5303
+ async function settle(): Promise<void> {
5304
+ await new Promise((resolve) => setTimeout(resolve, 0));
5305
+ }
5306
+
5307
+ test("gentleShell refreshes the active profile's subagent providers alongside the session provider", async (t) => {
5308
+ const home = mkdtempSync(join(tmpdir(), "shell-usage-scope-"));
5309
+ t.after(() => rmSync(home, { recursive: true, force: true }));
5310
+ writeProfilesStore(home, { team: { reviewer: { model: "nan/glm5.3" } } }, "team");
5311
+ const { pi, handlers } = fakePi();
5312
+ const { fetchFn, calls } = fakeFetch(NAN_QUOTA_PAYLOAD);
5313
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, { fetch: fetchFn, now: () => 1_788_600_000_000 });
5314
+ const { ctx } = fakeContext({ token: JWT });
5315
+ await fire(handlers, "session_start", ctx);
5316
+ await settle();
5317
+ assert.ok(calls.some((call) => call.url === NAN_QUOTA_URL), "the profile's nan route is fetched");
5318
+ assert.ok(calls.some((call) => call.url === CODEX_USAGE_URL), "the session provider is still fetched");
5319
+
5320
+ await fire(handlers, "agent_end", ctx);
5321
+ await settle();
5322
+ assert.equal(calls.length, 2, "the 5-minute throttle still applies per targeted provider");
5323
+ });
5324
+
5325
+ test("a pinned profile's subagent providers are the refreshed ones, not the global active profile's", async (t) => {
5326
+ const home = mkdtempSync(join(tmpdir(), "shell-usage-pin-"));
5327
+ const commonDir = mkdtempSync(join(tmpdir(), "shell-usage-pin-git-"));
5328
+ t.after(() => {
5329
+ rmSync(home, { recursive: true, force: true });
5330
+ rmSync(commonDir, { recursive: true, force: true });
5331
+ });
5332
+ mkdirSync(join(commonDir, "gentle-ai"), { recursive: true });
5333
+ writeFileSync(join(commonDir, "gentle-ai", "profile-pin.json"), JSON.stringify({ kind: "gentle-pi.agent_model_profile_pin", version: 1, profile: "pinned" }));
5334
+ writeProfilesStore(home, {
5335
+ team: { reviewer: { model: "openai-codex/gpt-5.5" } },
5336
+ pinned: { reviewer: { model: "nan/glm5.3" } },
5337
+ }, "team");
5338
+ const { pi, handlers } = fakePi();
5339
+ const { fetchFn, calls } = fakeFetch(NAN_QUOTA_PAYLOAD);
5340
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, { fetch: fetchFn, now: () => 1_788_600_000_000, resolveWorktree: () => ({ root: "/repo", commonDir }) });
5341
+ const { ctx } = fakeContext({ token: JWT });
5342
+ await fire(handlers, "session_start", ctx);
5343
+ await settle();
5344
+ assert.ok(calls.some((call) => call.url === NAN_QUOTA_URL), "the pin decides the routing, so the pinned profile's nan route is fetched");
5345
+ });
5346
+
5347
+ test("a bare routing model id resolves through the model registry only when exactly one provider carries it", async (t) => {
5348
+ const home = mkdtempSync(join(tmpdir(), "shell-usage-bare-"));
5349
+ t.after(() => rmSync(home, { recursive: true, force: true }));
5350
+ writeProfilesStore(home, { team: { reviewer: { model: "glm5.3" } } }, "team");
5351
+ const { pi, handlers } = fakePi();
5352
+ const { fetchFn, calls } = fakeFetch(NAN_QUOTA_PAYLOAD);
5353
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, { fetch: fetchFn, now: () => 1_788_600_000_000 });
5354
+ const { ctx } = fakeContext({ token: JWT });
5355
+ (ctx as unknown as { modelRegistry: { getAll(): Array<{ id: string; provider: string }> } }).modelRegistry.getAll = () => [{ id: "gpt-5.5", provider: "openai-codex" }, { id: "glm5.3", provider: "nan" }];
5356
+ await fire(handlers, "session_start", ctx);
5357
+ await settle();
5358
+ assert.ok(calls.some((call) => call.url === NAN_QUOTA_URL), "a bare id one provider carries is targeted");
5359
+
5360
+ const ambiguous = fakePi();
5361
+ const ambiguousFetch = fakeFetch(NAN_QUOTA_PAYLOAD);
5362
+ gentleShell(ambiguous.pi, { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, { fetch: ambiguousFetch.fetchFn, now: () => 1_788_600_000_000 });
5363
+ const ambiguousCtx = fakeContext({ token: JWT });
5364
+ (ambiguousCtx.ctx as unknown as { modelRegistry: { getAll(): Array<{ id: string; provider: string }> } }).modelRegistry.getAll = () => [{ id: "glm5.3", provider: "nan" }, { id: "glm5.3", provider: "openai-codex" }];
5365
+ await fire(ambiguous.handlers, "session_start", ambiguousCtx.ctx);
5366
+ await settle();
5367
+ assert.equal(ambiguousFetch.calls.some((call) => call.url === NAN_QUOTA_URL), false, "a bare id two providers carry is never guessed");
5368
+ });
5369
+
5370
+ test("a usage source registered after session start refreshes a subagent provider of the active profile", async (t) => {
5371
+ const home = mkdtempSync(join(tmpdir(), "shell-usage-source-"));
5372
+ t.after(() => rmSync(home, { recursive: true, force: true }));
5373
+ writeProfilesStore(home, { team: { watcher: { model: "acme-cloud/acme" } } }, "team");
5374
+ const { pi, handlers } = fakePi();
5375
+ const seen: Array<string | undefined> = [];
5376
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, { now: () => 1_788_600_000_000 });
5377
+ const { ctx } = fakeContext({ token: "acme-token" });
5378
+ await fire(handlers, "session_start", ctx);
5379
+ await settle();
5380
+
5381
+ pi.events.emit(USAGE_SOURCE_EVENT, acmeSource((apiKey) => seen.push(apiKey)));
5382
+ await settle();
5383
+ assert.deepEqual(seen, ["acme-token"], "a subagent route's provider gets the registered fetch, not just the session's own provider");
5384
+ });
5385
+
5386
+ test("the subscriptions panel shows targeted providers with no data and a generic fetch-failure note", async (t) => {
5387
+ const home = mkdtempSync(join(tmpdir(), "shell-usage-fail-"));
5388
+ t.after(() => rmSync(home, { recursive: true, force: true }));
5389
+ writeProfilesStore(home, { team: { reviewer: { model: "nan/glm5.3" } } }, "team");
5390
+ const { pi, handlers, commands } = fakePi();
5391
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, { fetch: fakeFetch(NAN_QUOTA_PAYLOAD, false).fetchFn, now: () => 1_788_600_000_000 });
5392
+ const { ctx, ui } = fakeContext({ token: JWT });
5393
+ await fire(handlers, "session_start", ctx);
5394
+ const opened = commands.get("gentle:usage")!.handler("", ctx);
5395
+ await settle();
5396
+ const plain = ui.overlayView!.render(90).map(stripAnsi);
5397
+ assert.match(plain.find((line) => line.includes("nan")) ?? "", /nan · fetch failed · r to retry/, "a targeted provider whose fetch answered nothing says so, generically");
5398
+ assert.equal(plain.some((line) => /sk-nan-secret|Bearer|acct-1/.test(line)), false, "the failure note stays nonsecret");
5399
+ ui.closeOverlay?.();
5400
+ await opened;
5401
+ });
5402
+
5403
+ // One stalled provider must not hold the panel hostage: refreshes run
5404
+ // concurrently per provider and each one is bounded, so the overlay opens
5405
+ // immediately, the healthy provider still lands its snapshot, the stalled one
5406
+ // degrades to the generic failure note when its window expires, and a late
5407
+ // answer can never mutate what the timeout already settled.
5408
+ test("a stalled provider times out without hanging the overlay, and a late answer cannot mutate", async (t) => {
5409
+ const home = mkdtempSync(join(tmpdir(), "shell-usage-stall-"));
5410
+ t.after(() => rmSync(home, { recursive: true, force: true }));
5411
+ writeProfilesStore(home, { team: { reviewer: { model: "nan/glm5.3" } } }, "team");
5412
+ const { pi, handlers, commands } = fakePi();
5413
+ let stalledCalls = 0;
5414
+ let releaseStalled: ((usage: unknown) => void) | undefined;
5415
+ const acmePayload = {
5416
+ provider: "acme-cloud",
5417
+ plan: "Acme cloud",
5418
+ limits: [{ name: "acme-cloud", windows: [{ label: "week", usedPercent: 40, windowSeconds: 604_800, resetAt: null }], limitReached: false }],
5419
+ fetchedAt: 0,
5420
+ };
5421
+ const { fetchFn } = fakeFetch(NAN_QUOTA_PAYLOAD);
5422
+ gentleShell(
5423
+ pi,
5424
+ { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off", GENTLE_PI_SHELL_USAGE_TIMEOUT_MS: "25" },
5425
+ { fetch: fetchFn, now: () => 1_788_600_000_000 },
5426
+ );
5427
+ pi.events.emit(USAGE_SOURCE_EVENT, {
5428
+ schema: USAGE_SOURCE_SCHEMA,
5429
+ provider: "acme-cloud",
5430
+ fetch: async () => {
5431
+ stalledCalls += 1;
5432
+ return await new Promise((resolve) => {
5433
+ releaseStalled = () => resolve(acmePayload);
5434
+ });
5435
+ },
5436
+ });
5437
+ const { ctx, ui } = fakeContext({ token: "sk-nan-secret" });
5438
+ (ctx as unknown as { model: { provider: string } }).model.provider = "acme-cloud";
5439
+ await fire(handlers, "session_start", ctx);
5440
+
5441
+ // The stalled fetch is still pending, yet the panel opens right away and
5442
+ // shows whatever the store already holds.
5443
+ const opened = commands.get("gentle:usage")!.handler("", ctx);
5444
+ await settle();
5445
+ assert.ok(ui.overlayView, "the overlay must open while a provider is still stalled");
5446
+ assert.match(ui.overlayView!.render(90).map(stripAnsi).find((line) => /^│ nan · updated just now/.test(line)) ?? "", /nan/, "the healthy provider's snapshot lands while the other provider is stalled");
5447
+
5448
+ // The stalled provider's window expires: its row wears the generic failure
5449
+ // note, and it was still fetched — bounding, never skipping.
5450
+ await new Promise((resolve) => setTimeout(resolve, 60));
5451
+ await settle();
5452
+ const plain = ui.overlayView!.render(90).map(stripAnsi);
5453
+ assert.match(plain.find((line) => line.includes("acme-cloud")) ?? "", /acme-cloud · fetch failed · r to retry/, "the stalled provider degrades to the generic failure note");
5454
+ assert.ok(stalledCalls >= 1, "the stalled provider was still fetched");
5455
+
5456
+ // An answer arriving after the timeout cannot mutate the settled state.
5457
+ releaseStalled!(acmePayload);
5458
+ await settle();
5459
+ const late = ui.overlayView!.render(90).map(stripAnsi);
5460
+ assert.match(late.find((line) => line.includes("acme-cloud")) ?? "", /fetch failed · r to retry/, "a late answer must not replace the timeout's failure note");
5461
+ assert.doesNotMatch(late.join("\n"), /Acme cloud/, "a late answer must not record a snapshot");
5462
+ ui.closeOverlay?.();
5463
+ await opened;
5464
+ });
5465
+
5466
+ // The fix for "healthy results record but nothing repaints until the slowest
5467
+ // timeout": each settled provider — snapshot or failure — notifies the shell
5468
+ // immediately, so the open overlay repaints per provider instead of waiting
5469
+ // for the whole refresh (whose slowest member is the bounded window itself).
5470
+ test("a settled provider repaints the overlay before the stalled provider's window expires", async (t) => {
5471
+ const home = mkdtempSync(join(tmpdir(), "shell-usage-repaint-"));
5472
+ t.after(() => rmSync(home, { recursive: true, force: true }));
5473
+ writeProfilesStore(home, { team: { reviewer: { model: "nan/glm5.3" } } }, "team");
5474
+ const { pi, handlers, commands } = fakePi();
5475
+ let releaseNan: (() => void) | undefined;
5476
+ const nanFetch = (async () => {
5477
+ return await new Promise<Response>((resolve) => {
5478
+ releaseNan = () => resolve({ ok: true, json: async () => NAN_QUOTA_PAYLOAD } as Response);
5479
+ });
5480
+ }) as typeof fetch;
5481
+ gentleShell(
5482
+ pi,
5483
+ { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off", GENTLE_PI_SHELL_USAGE_TIMEOUT_MS: "100" },
5484
+ { fetch: nanFetch, now: () => 1_788_600_000_000 },
5485
+ );
5486
+ pi.events.emit(USAGE_SOURCE_EVENT, {
5487
+ schema: USAGE_SOURCE_SCHEMA,
5488
+ provider: "acme-cloud",
5489
+ fetch: async () => await new Promise(() => {}),
5490
+ });
5491
+ const { ctx, ui } = fakeContext({ token: "sk-nan-secret" });
5492
+ (ctx as unknown as { model: { provider: string } }).model.provider = "acme-cloud";
5493
+ await fire(handlers, "session_start", ctx);
5494
+ await settle();
5495
+ // Arm the shell render host the way a real session does (the footer factory
5496
+ // owns renderHost), then count frames from the shared fake TUI.
5497
+ renderFooter(ui);
5498
+ let frames = 0;
5499
+ const originalRequestRender = fakeTui.requestRender;
5500
+ fakeTui.requestRender = () => {
5501
+ frames += 1;
5502
+ };
5503
+ try {
5504
+ const opened = commands.get("gentle:usage")!.handler("", ctx);
5505
+ await settle();
5506
+ // Both providers are pending; releasing only the healthy one must repaint
5507
+ // the overlay at once, with the refresh still in flight.
5508
+ const framesBeforeRelease = frames;
5509
+ releaseNan!();
5510
+ await settle();
5511
+ const lines = ui.overlayView!.render(90).map(stripAnsi);
5512
+ assert.ok(frames > framesBeforeRelease, "the settled provider notifies the shell before the stalled window expires");
5513
+ assert.match(lines.find((line) => /^│ nan · updated just now/.test(line)) ?? "", /nan/, "the healthy row is painted immediately on its own settle");
5514
+ assert.match(lines[0], /refreshing…/, "the repaint is per settled provider — the refresh is still in flight");
5515
+ // Only then does the stalled provider's window expire into the failure note.
5516
+ await new Promise((resolve) => setTimeout(resolve, 250));
5517
+ await settle();
5518
+ assert.match(ui.overlayView!.render(90).map(stripAnsi).find((line) => line.includes("acme-cloud")) ?? "", /fetch failed · r to retry/);
5519
+ ui.closeOverlay?.();
5520
+ await opened;
5521
+ } finally {
5522
+ fakeTui.requestRender = originalRequestRender;
5523
+ }
5524
+ });
5525
+
5526
+ // The window's signal must compose with whatever the caller already carries —
5527
+ // init.signal, like a source passing its own cancellation — not replace it:
5528
+ // either side aborting still aborts, exactly like a plain fetch.
5529
+ test("the refresh timeout composes with a source's own abort signal instead of replacing it", async (t) => {
5530
+ const home = mkdtempSync(join(tmpdir(), "shell-usage-signal-"));
5531
+ t.after(() => rmSync(home, { recursive: true, force: true }));
5532
+ const { pi, handlers } = fakePi();
5533
+ let captured: AbortSignal | undefined;
5534
+ const spyFetch = (async (_input: string | URL, init?: RequestInit) => {
5535
+ captured = (init?.signal ?? undefined) as AbortSignal | undefined;
5536
+ return await new Promise<Response>(() => {});
5537
+ }) as typeof fetch;
5538
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off", GENTLE_PI_SHELL_USAGE_TIMEOUT_MS: "100" }, { fetch: spyFetch, now: () => 1_788_600_000_000 });
5539
+ const hangingSource = (caller: AbortController): unknown => ({
5540
+ schema: USAGE_SOURCE_SCHEMA,
5541
+ provider: "acme-cloud",
5542
+ fetch: async (_apiKey: string | undefined, fetchFn: typeof fetch) => {
5543
+ await fetchFn("https://acme.example/usage", { signal: caller.signal });
5544
+ return undefined;
5545
+ },
5546
+ });
5547
+ const { ctx } = fakeContext({ token: "acme-token" });
5548
+ (ctx as unknown as { model: { provider: string } }).model.provider = "acme-cloud";
5549
+ const callerA = new AbortController();
5550
+ pi.events.emit(USAGE_SOURCE_EVENT, hangingSource(callerA));
5551
+ await fire(handlers, "session_start", ctx);
5552
+ await settle();
5553
+ assert.ok(captured, "the source's fetch reached the shell fetch");
5554
+ assert.notEqual(captured, callerA.signal, "the window's signal composes with the caller's, it does not replace it");
5555
+ callerA.abort();
5556
+ assert.ok(captured!.aborted, "the caller's own abort still aborts the composed signal");
5557
+
5558
+ // A fresh, un-aborted caller must still be aborted by the window itself.
5559
+ const callerB = new AbortController();
5560
+ pi.events.emit(USAGE_SOURCE_EVENT, hangingSource(callerB));
5561
+ await settle();
5562
+ const capturedB = captured;
5563
+ assert.ok(capturedB && !capturedB.aborted, "the second dispatch starts un-aborted");
5564
+ await new Promise((resolve) => setTimeout(resolve, 250));
5565
+ assert.ok(capturedB!.aborted, "the window's expiry aborts the composed signal too");
5566
+ });
5567
+
5568
+ // A provider whose credential resolution outlives its window must never start
5569
+ // its fetch at all: the timeout bounds the whole operation, not just the wire.
5570
+ test("a provider aborted while its credential resolves never starts its fetch", async (t) => {
5571
+ const home = mkdtempSync(join(tmpdir(), "shell-usage-credential-"));
5572
+ t.after(() => rmSync(home, { recursive: true, force: true }));
5573
+ const { pi, handlers } = fakePi();
5574
+ let fetchCalls = 0;
5575
+ const spyFetch = (async () => {
5576
+ fetchCalls += 1;
5577
+ return { ok: true, json: async () => ({}) } as Response;
5578
+ }) as typeof fetch;
5579
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off", GENTLE_PI_SHELL_USAGE_TIMEOUT_MS: "25" }, { fetch: spyFetch, now: () => 1_788_600_000_000 });
5580
+ pi.events.emit(USAGE_SOURCE_EVENT, {
5581
+ schema: USAGE_SOURCE_SCHEMA,
5582
+ provider: "acme-cloud",
5583
+ fetch: async () => {
5584
+ fetchCalls += 1;
5585
+ return undefined;
5586
+ },
5587
+ });
5588
+ const { ctx } = fakeContext({ token: "acme-token" });
5589
+ let releaseCredential: (() => void) | undefined;
5590
+ (ctx as unknown as { modelRegistry: unknown }).modelRegistry = {
5591
+ isUsingOAuth: () => true,
5592
+ getApiKeyForProvider: () => new Promise<string | undefined>((resolve) => { releaseCredential = () => resolve("acme-token"); }),
5593
+ };
5594
+ (ctx as unknown as { model: { provider: string } }).model.provider = "acme-cloud";
5595
+ await fire(handlers, "session_start", ctx);
5596
+ await new Promise((resolve) => setTimeout(resolve, 60));
5597
+ releaseCredential!();
5598
+ await settle();
5599
+ assert.equal(fetchCalls, 0, "the window expired during credential resolution; the source must never be invoked");
5600
+ });
5601
+
5602
+ test("the panel keeps a headers-only subagent provider pending instead of a false failure", async (t) => {
5603
+ const home = mkdtempSync(join(tmpdir(), "shell-usage-anthropic-"));
5604
+ t.after(() => rmSync(home, { recursive: true, force: true }));
5605
+ writeProfilesStore(home, { team: { reviewer: { model: "anthropic/claude-x" } } }, "team");
5606
+ const { pi, handlers, commands } = fakePi();
5607
+ const { fetchFn, calls } = fakeFetch(NAN_QUOTA_PAYLOAD);
5608
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, { fetch: fetchFn, now: () => 1_788_600_000_000 });
5609
+ const { ctx, ui } = fakeContext({ token: JWT });
5610
+ await fire(handlers, "session_start", ctx);
5611
+ await settle();
5612
+ assert.deepEqual(calls.map((call) => call.url), [CODEX_USAGE_URL], "anthropic has no usage endpoint to fetch; only the session's own provider is fetched");
5613
+ const opened = commands.get("gentle:usage")!.handler("", ctx);
5614
+ await settle();
5615
+ const plain = ui.overlayView!.render(90).map(stripAnsi);
5616
+ assert.match(plain.find((line) => line.includes("anthropic")) ?? "", /anthropic · usage arrives with the first response/);
5617
+ assert.equal(plain.some((line) => line.includes("fetch failed")), false, "headers-only providers never wear a fetch-failure note");
5618
+ ui.closeOverlay?.();
5619
+ await opened;
5620
+ });
5621
+
5622
+ test("after a profile switch the panel stops presenting the old profile's provider", async (t) => {
5623
+ const home = mkdtempSync(join(tmpdir(), "shell-usage-switch-"));
5624
+ t.after(() => rmSync(home, { recursive: true, force: true }));
5625
+ writeProfilesStore(home, { team: { reviewer: { model: "nan/glm5.3" } }, solo: {} }, "team");
5626
+ const { pi, handlers, commands } = fakePi();
5627
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, { fetch: fakeFetch(NAN_QUOTA_PAYLOAD).fetchFn, now: () => 1_788_600_000_000 });
5628
+ const { ctx, ui } = fakeContext({ token: JWT });
5629
+ await fire(handlers, "session_start", ctx);
5630
+ const opened = commands.get("gentle:usage")!.handler("", ctx);
5631
+ await settle();
5632
+ assert.ok(ui.overlayView!.render(90).map(stripAnsi).some((line) => /^│ nan ·/.test(line)), "the team profile's nan route is current scope");
5633
+ ui.closeOverlay?.();
5634
+ await opened;
5635
+
5636
+ writeProfilesStore(home, { team: { reviewer: { model: "nan/glm5.3" } }, solo: {} }, "solo");
5637
+ const reopened = commands.get("gentle:usage")!.handler("", ctx);
5638
+ await settle();
5639
+ assert.equal(ui.overlayView!.render(90).map(stripAnsi).some((line) => line.includes("nan")), false, "a provider recorded under the previous profile's routing is not current scope");
5640
+ ui.closeOverlay?.();
5641
+ await reopened;
5642
+ });
5643
+
5644
+ function openPanelLines(ui: FakeUi): string[] {
5645
+ return ui.overlayView!.render(90).map(stripAnsi);
5646
+ }
5647
+
5648
+ test("a failed refresh says so beside the retained snapshot and clears on the next success", async (t) => {
5649
+ const home = mkdtempSync(join(tmpdir(), "shell-usage-retained-"));
5650
+ t.after(() => rmSync(home, { recursive: true, force: true }));
5651
+ writeProfilesStore(home, { team: { reviewer: { model: "nan/glm5.3" } } }, "team");
5652
+ let fail = false;
5653
+ let now = 1_788_600_000_000;
5654
+ const fetchFn = (async () => {
5655
+ if (fail) throw new TypeError("network down");
5656
+ return { ok: true, json: async () => NAN_QUOTA_PAYLOAD } as Response;
5657
+ }) as typeof fetch;
5658
+ const { pi, handlers, commands } = fakePi();
5659
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, { fetch: fetchFn, now: () => now });
5660
+ const { ctx, ui } = fakeContext({ token: JWT });
5661
+ await fire(handlers, "session_start", ctx);
5662
+ await settle();
5663
+ const opened = commands.get("gentle:usage")!.handler("", ctx);
5664
+ await settle();
5665
+ assert.ok(openPanelLines(ui).some((line) => /^│ nan · updated just now/.test(line)), "the good snapshot is recorded");
5666
+ assert.equal(openPanelLines(ui).some((line) => line.includes("fetch failed")), false, "a successful refresh carries no failure note");
5667
+ ui.closeOverlay?.();
5668
+ await opened;
5669
+
5670
+ fail = true;
5671
+ now += 6 * 60_000;
5672
+ await fire(handlers, "agent_end", ctx);
5673
+ await settle();
5674
+ const reopened = commands.get("gentle:usage")!.handler("", ctx);
5675
+ await settle();
5676
+ const afterFailure = openPanelLines(ui);
5677
+ assert.ok(afterFailure.some((line) => /^│ nan · updated 6m ago/.test(line)), "the retained snapshot still headlines the provider, honestly stale");
5678
+ assert.ok(afterFailure.some((line) => line.includes("glm5.3") && line.includes("27%")), "the retained snapshot's rows survive");
5679
+ assert.ok(afterFailure.some((line) => line.includes("fetch failed · r to retry")), "the failed refresh is visible beside the retained snapshot");
5680
+ ui.closeOverlay?.();
5681
+ await reopened;
5682
+
5683
+ fail = false;
5684
+ now += 6 * 60_000;
5685
+ await fire(handlers, "agent_end", ctx);
5686
+ await settle();
5687
+ const recovered = commands.get("gentle:usage")!.handler("", ctx);
5688
+ await settle();
5689
+ assert.ok(openPanelLines(ui).some((line) => /^│ nan · updated just now/.test(line)));
5690
+ assert.equal(openPanelLines(ui).some((line) => line.includes("fetch failed")), false, "a successful refresh clears the failure note");
5691
+ ui.closeOverlay?.();
5692
+ await recovered;
5693
+ });
5694
+
5695
+ test("a replaced source's late failure cannot mark the provider failed after its replacement succeeded", async (t) => {
5696
+ const home = mkdtempSync(join(tmpdir(), "shell-usage-stale-fail-"));
5697
+ t.after(() => rmSync(home, { recursive: true, force: true }));
5698
+ writeProfilesStore(home, { team: { watcher: { model: "acme-cloud/acme" } } }, "team");
5699
+ let now = 1_788_600_000_000;
5700
+ const acmePayload = () => ({
5701
+ provider: "acme-cloud",
5702
+ plan: "Acme",
5703
+ limits: [{ name: "acme-cloud", windows: [{ label: "week", usedPercent: 40, windowSeconds: 604_800, resetAt: null }], limitReached: false }],
5704
+ fetchedAt: 0,
5705
+ });
5706
+ let aCalls = 0;
5707
+ let releaseStaleFailure!: () => void;
5708
+ const staleGate = new Promise<void>((resolve) => { releaseStaleFailure = resolve; });
5709
+ const sourceA = {
5710
+ schema: USAGE_SOURCE_SCHEMA,
5711
+ provider: "acme-cloud",
5712
+ fetch: async () => {
5713
+ aCalls += 1;
5714
+ if (aCalls <= 2) return acmePayload();
5715
+ await staleGate;
5716
+ return undefined; // the replaced source's late failure
5717
+ },
5718
+ };
5719
+ const sourceB = {
5720
+ schema: USAGE_SOURCE_SCHEMA,
5721
+ provider: "acme-cloud",
5722
+ fetch: async () => {
5723
+ if (bCalls === 0) {
5724
+ bCalls += 1;
5725
+ return acmePayload();
5726
+ }
5727
+ await new Promise(() => {}); // later refreshes stay in flight, mutating nothing
5728
+ },
5729
+ };
5730
+ let bCalls = 0;
5731
+ const { pi, handlers, commands } = fakePi();
5732
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, { fetch: fakeFetch().fetchFn, now: () => now });
5733
+ pi.events.emit(USAGE_SOURCE_EVENT, sourceA);
5734
+ const { ctx, ui } = fakeContext({ token: JWT });
5735
+ await fire(handlers, "session_start", ctx);
5736
+ await settle();
5737
+ const opened = commands.get("gentle:usage")!.handler("", ctx);
5738
+ await settle();
5739
+ assert.ok(openPanelLines(ui).some((line) => line.includes("acme-cloud") && line.includes("40%")), "the original source's snapshot is showing");
5740
+
5741
+ now += 6 * 60_000;
5742
+ await fire(handlers, "agent_end", ctx);
5743
+ await settle();
5744
+ pi.events.emit(USAGE_SOURCE_EVENT, sourceB);
5745
+ await settle();
5746
+ releaseStaleFailure();
5747
+ await settle();
5748
+ const lines = openPanelLines(ui);
5749
+ assert.ok(lines.some((line) => line.includes("acme-cloud") && line.includes("40%")), "the replacement's snapshot stands");
5750
+ assert.equal(lines.some((line) => line.includes("fetch failed")), false, "the replaced source's late failure must not mark the provider failed");
5751
+ ui.closeOverlay?.();
5752
+ await opened;
5753
+ });
5754
+
5755
+ test("a valid response-header snapshot clears a prior refresh failure", async (_t) => {
5756
+ const { pi, handlers, commands } = fakePi();
5757
+ gentleShell(pi, { GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, { fetch: fakeFetch(USAGE_PAYLOAD, false).fetchFn, now: () => 1_788_600_000_000 });
5758
+ const { ctx, ui } = fakeContext({ token: JWT });
5759
+ await fire(handlers, "session_start", ctx);
5760
+ await settle();
5761
+ const opened = commands.get("gentle:usage")!.handler("", ctx);
5762
+ await settle();
5763
+ assert.ok(openPanelLines(ui).some((line) => line.includes("✿ openai-codex · fetch failed")), "the failed refresh is visible first");
5764
+
5765
+ for (const handler of handlers.get("after_provider_response") ?? []) {
5766
+ handler({ status: 200, headers: { "x-codex-primary-used-percent": "10", "x-codex-primary-window-minutes": "300" } }, ctx);
5767
+ }
5768
+ const lines = openPanelLines(ui);
5769
+ assert.ok(lines.some((line) => line.includes("✿ openai-codex · updated just now")), "the header snapshot is recorded");
5770
+ assert.ok(lines.some((line) => line.includes("10%")), "the header snapshot's window renders");
5771
+ assert.equal(lines.some((line) => line.includes("fetch failed")), false, "a valid header snapshot clears the failure");
5772
+ ui.closeOverlay?.();
5773
+ await opened;
5774
+ });
5775
+
5776
+ test("the panel's scope is resolved on refresh, not on every render", async (t) => {
5777
+ const home = mkdtempSync(join(tmpdir(), "shell-usage-cache-"));
5778
+ t.after(() => rmSync(home, { recursive: true, force: true }));
5779
+ writeProfilesStore(home, { team: { reviewer: { model: "nan/glm5.3" } } }, "team");
5780
+ let resolutions = 0;
5781
+ const { pi, handlers, commands } = fakePi();
5782
+ gentleShell(pi, { GENTLE_PI_CONFIG_HOME: home, GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, {
5783
+ fetch: fakeFetch(NAN_QUOTA_PAYLOAD).fetchFn,
5784
+ now: () => 1_788_600_000_000,
5785
+ resolveWorktree: (cwd: string) => {
5786
+ resolutions += 1;
5787
+ return { root: cwd, commonDir: "/clone/git" };
5788
+ },
5789
+ });
5790
+ const { ctx, ui } = fakeContext({ token: JWT });
5791
+ await fire(handlers, "session_start", ctx);
5792
+ await settle();
5793
+ const opened = commands.get("gentle:usage")!.handler("", ctx);
5794
+ await settle();
5795
+ assert.ok(openPanelLines(ui).some((line) => line.includes("nan")), "the panel renders the scoped providers");
5796
+ const before = resolutions;
5797
+ ui.overlayView!.render(90);
5798
+ ui.overlayView!.render(90);
5799
+ ui.overlayView!.render(90);
5800
+ assert.equal(resolutions, before, "renders reuse the cached scope instead of re-resolving Git and the profiles store");
5801
+ ui.closeOverlay?.();
5802
+ await opened;
5803
+ });
5804
+
5805
+ test("an older overlapping refresh cannot mark a provider failed after a newer one succeeded", async (_t) => {
5806
+ const { pi, handlers, commands } = fakePi();
5807
+ let now = 1_788_600_000_000;
5808
+ let codexCalls = 0;
5809
+ let releaseStaleFailure!: () => void;
5810
+ const staleGate = new Promise<void>((resolve) => { releaseStaleFailure = resolve; });
5811
+ const fetchFn = (async () => {
5812
+ codexCalls += 1;
5813
+ if (codexCalls === 1) {
5814
+ await staleGate;
5815
+ return { ok: false } as Response; // the older refresh's late failure
5816
+ }
5817
+ return { ok: true, json: async () => USAGE_PAYLOAD } as Response; // the newer refresh succeeds
5818
+ }) as typeof fetch;
5819
+ gentleShell(pi, { GENTLE_PI_SHELL_CHANGES_WATCH_MS: "off" }, { fetch: fetchFn, now: () => now });
5820
+ const { ctx, ui } = fakeContext({ token: JWT });
5821
+ await fire(handlers, "session_start", ctx);
5822
+ await settle();
5823
+ const opened = commands.get("gentle:usage")!.handler("", ctx);
5824
+ await settle();
5825
+ assert.ok(openPanelLines(ui).some((line) => line.includes("✿ openai-codex · pro")), "the newer refresh's snapshot is showing");
5826
+
5827
+ releaseStaleFailure();
5828
+ await settle();
5829
+ const lines = openPanelLines(ui);
5830
+ assert.ok(lines.some((line) => line.includes("✿ openai-codex")), "the newer refresh's snapshot stands");
5831
+ assert.equal(lines.some((line) => line.includes("fetch failed")), false, "the older refresh's late failure must not mark the provider failed");
5832
+ ui.closeOverlay?.();
5833
+ await opened;
5834
+ });