gentle-pi 4.5.1 → 4.6.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 (239) hide show
  1. package/README.md +9 -6
  2. package/assets/agents/gentle-ai-verify.md +4 -0
  3. package/assets/agents/gentle-ai-worker.md +1 -0
  4. package/assets/migrations/agent-body-history.json +147 -0
  5. package/assets/orchestrator-delegation-reference.md +3 -3
  6. package/assets/orchestrator-delegation.md +2 -2
  7. package/assets/orchestrator-verification.md +10 -6
  8. package/assets/orchestrator.md +8 -8
  9. package/bin/gentle-shell.mjs +61 -26
  10. package/docs/ci-performance.md +11 -0
  11. package/docs/delegated-verification.md +6 -0
  12. package/docs/fast-mode.md +15 -0
  13. package/docs/gentle-agents-activity.md +8 -0
  14. package/docs/gentle-shell.md +69 -19
  15. package/docs/install-wizard.md +1 -1
  16. package/docs/mcp-status.md +52 -0
  17. package/docs/prompt-budget.md +28 -0
  18. package/docs/readme-reference.md +79 -20
  19. package/docs/session-profile-format.md +20 -5
  20. package/docs/sound-notifications.md +1 -1
  21. package/docs/star-prompt.md +32 -0
  22. package/docs/work-continuity.md +46 -0
  23. package/extensions/ask-user-question.ts +1 -0
  24. package/extensions/codegraph-tools.ts +38 -4
  25. package/extensions/gentle-agents.ts +477 -50
  26. package/extensions/gentle-ai.ts +1041 -188
  27. package/extensions/gentle-fast.ts +61 -0
  28. package/extensions/gentle-guide.ts +174 -0
  29. package/extensions/gentle-herdr-activity.ts +21 -1
  30. package/extensions/gentle-herdr-agent.ts +144 -0
  31. package/extensions/gentle-program-identity.ts +61 -0
  32. package/extensions/gentle-shell.ts +642 -97
  33. package/extensions/gentle-star-prompt.ts +334 -0
  34. package/extensions/gentle-stats.ts +5 -5
  35. package/extensions/gentle-todo.ts +42 -22
  36. package/extensions/history/store.ts +18 -12
  37. package/extensions/skill-registry.ts +35 -3
  38. package/extensions/startup-banner.ts +39 -7
  39. package/lib/agent-assets.ts +74 -17
  40. package/lib/agent-profiles.ts +1 -1
  41. package/lib/agents-config.ts +12 -3
  42. package/lib/agents-keys.ts +8 -16
  43. package/lib/agents-protocol.ts +80 -4
  44. package/lib/agents-runner.ts +105 -4
  45. package/lib/agents-view.ts +6 -1
  46. package/lib/agents-widget.ts +132 -9
  47. package/lib/bridge-cost.ts +28 -0
  48. package/lib/codemode-renderer.ts +16 -0
  49. package/lib/command-palette-catalog.ts +1 -0
  50. package/lib/command-palette.ts +21 -8
  51. package/lib/exploration-budget.ts +62 -0
  52. package/lib/gentle-guide.ts +201 -0
  53. package/lib/gentle-shell-launcher.ts +4 -0
  54. package/lib/herdr-activity.ts +9 -3
  55. package/lib/herdr-task-summary-policy.ts +85 -0
  56. package/lib/inprocess-reviewer.ts +33 -13
  57. package/lib/jobs-sidebar-state.ts +5 -6
  58. package/lib/jobs-widget.ts +16 -52
  59. package/lib/keymaps-customize.ts +81 -0
  60. package/lib/keymaps.ts +291 -0
  61. package/lib/model-fallback-notice.ts +61 -0
  62. package/lib/model-fallback-policy.ts +141 -0
  63. package/lib/model-fallback-store.ts +143 -0
  64. package/lib/model-routing-authority.ts +10 -2
  65. package/lib/nan-provider.ts +3 -2
  66. package/lib/native-review-cli.ts +7 -2
  67. package/lib/notification-customize.ts +48 -51
  68. package/lib/openai-fast-tier.ts +22 -0
  69. package/lib/orchestrator-discovery.ts +5 -1
  70. package/lib/orchestrator-fallback.ts +75 -0
  71. package/lib/pasted-image-paths.ts +113 -0
  72. package/lib/questionnaire/questionnaire-view.ts +121 -7
  73. package/lib/review-candidate-view-owner.ts +4 -0
  74. package/lib/review-candidate-view.ts +10 -7
  75. package/lib/review-host-relay.ts +5 -1
  76. package/lib/review-integration-v2.ts +22 -7
  77. package/lib/review-repository.ts +5 -0
  78. package/lib/session-profile-append-controller.ts +21 -6
  79. package/lib/session-profile-authority.ts +119 -0
  80. package/lib/session-profile-binding.ts +54 -5
  81. package/lib/session-profile-freeze.ts +105 -9
  82. package/lib/session-profile-integration.ts +313 -0
  83. package/lib/session-profile-persistence.ts +63 -9
  84. package/lib/shell-bar.ts +171 -56
  85. package/lib/shell-card.ts +26 -6
  86. package/lib/shell-page.ts +120 -0
  87. package/lib/shell-panel.ts +149 -0
  88. package/lib/shell-prompt.ts +53 -1
  89. package/lib/shell-sidebar-layout.ts +98 -25
  90. package/lib/shell-sidebar.ts +54 -1
  91. package/lib/shell-stats.ts +123 -0
  92. package/lib/shell-todo.ts +71 -0
  93. package/lib/shell-usage.ts +12 -2
  94. package/lib/star-prompt.ts +197 -0
  95. package/lib/verifier-admission.ts +18 -8
  96. package/lib/verifier-settle-reminder.ts +64 -0
  97. package/lib/vim-editor-adapter.ts +6 -1
  98. package/lib/visual-customization-policy.ts +41 -6
  99. package/lib/visual-customize-view.ts +164 -26
  100. package/lib/visual-layout-preview.ts +43 -0
  101. package/lib/yolo-session-policy.ts +28 -1
  102. package/package.json +1 -1
  103. package/runtime/gentle-shell-launcher.mjs +4 -0
  104. package/runtime/native-review-cli.mjs +7 -2
  105. package/runtime/review-integration-v2.mjs +22 -7
  106. package/runtime/windows-session-transport.ps1 +60 -3
  107. package/scripts/bootstrap.sh +4 -1
  108. package/scripts/installer-preflight.mjs +1 -1
  109. package/scripts/pi-update.mjs +113 -3
  110. package/scripts/run-test-suite.mjs +17 -1
  111. package/scripts/shell-snapshot.mjs +340 -0
  112. package/scripts/test-packed-runner.mjs +1 -1
  113. package/scripts/update-agent-body-history.mjs +41 -0
  114. package/scripts/verify-installer-tap.mjs +45 -0
  115. package/scripts/verify-package-files.mjs +2 -0
  116. package/skills/gentle-ai/SKILL.md +2 -2
  117. package/skills/tui-design/NOTICE.md +5 -0
  118. package/skills/tui-design/SKILL.md +56 -0
  119. package/skills/tui-design/references/commands.md +75 -0
  120. package/skills/tui-design/references/critique.md +48 -0
  121. package/skills/tui-design/references/design-doc.md +44 -0
  122. package/skills/tui-design/references/terminal-craft.md +64 -0
  123. package/skills/tui-design/references/visual-loop.md +32 -0
  124. package/tests/agents-protocol.test.ts +53 -1
  125. package/tests/agents-runner.test.ts +168 -3
  126. package/tests/agents-view.test.ts +27 -0
  127. package/tests/agents-widget.test.ts +312 -10
  128. package/tests/bounded-scan-contract.test.ts +39 -0
  129. package/tests/bridge-cost.test.ts +32 -0
  130. package/tests/bundled-install.test.ts +6 -4
  131. package/tests/ci-concurrency.test.ts +11 -0
  132. package/tests/ci-merge-base-identity.test.ts +114 -0
  133. package/tests/codegraph-tools.test.ts +69 -0
  134. package/tests/codemode-rendering.test.ts +22 -2
  135. package/tests/command-palette.test.ts +16 -2
  136. package/tests/commit-slice-signal.test.ts +11 -9
  137. package/tests/delegate-for-reason-contract.test.ts +5 -4
  138. package/tests/exploration-budget.test.ts +128 -0
  139. package/tests/fixtures/agent-assets/gentle-ai-worker.strict-tdd-era.md +122 -0
  140. package/tests/fixtures/measure-orchestrator-prompt.mjs +2 -1
  141. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +18 -10
  142. package/tests/fixtures/session-profile-v1/replay.ts +125 -0
  143. package/tests/fixtures/session-profile-v1/session-profile-authority.ts +113 -0
  144. package/tests/fixtures/session-profile-v1/session-profile-binding.ts +83 -0
  145. package/tests/fixtures/session-profile-v1/session-profile-disk-reader.ts +182 -0
  146. package/tests/fixtures/session-profile-v1/session-profile-freeze.ts +290 -0
  147. package/tests/fixtures/session-profile-v1/session-profile-persistence.ts +195 -0
  148. package/tests/fixtures/session-profile-v1/v1-inputs.ts +16 -0
  149. package/tests/fixtures/windows-pipe-availability.ps1 +26 -0
  150. package/tests/fixtures/windows-session-bootstrap.ps1 +6 -2
  151. package/tests/gentle-agents.test.ts +416 -21
  152. package/tests/gentle-ai-exploration-budget.test.ts +135 -0
  153. package/tests/gentle-ai.test.ts +1007 -33
  154. package/tests/gentle-fast.test.ts +73 -0
  155. package/tests/gentle-guide.test.ts +208 -0
  156. package/tests/gentle-herdr-activity.test.ts +76 -2
  157. package/tests/gentle-herdr-agent.test.ts +111 -0
  158. package/tests/gentle-program-identity.test.ts +197 -0
  159. package/tests/gentle-shell-bin.test.ts +49 -26
  160. package/tests/gentle-shell-launcher.test.ts +18 -2
  161. package/tests/gentle-shell.test.ts +1068 -37
  162. package/tests/gentle-stats.test.ts +15 -2
  163. package/tests/gentle-todo.test.ts +50 -4
  164. package/tests/herdr-task-summary-policy.test.ts +128 -0
  165. package/tests/history-store-private-mode.test.ts +40 -0
  166. package/tests/image-paste-chips.test.ts +42 -0
  167. package/tests/inprocess-reviewer.test.ts +122 -0
  168. package/tests/installer-posix-bootstrap.test.ts +67 -5
  169. package/tests/installer-server.test.ts +2 -2
  170. package/tests/installer-windows-diagnostics.test.ts +4 -5
  171. package/tests/isolated-config-home.ts +28 -0
  172. package/tests/jobs-widget.test.ts +25 -37
  173. package/tests/keymaps-customize.test.ts +114 -0
  174. package/tests/keymaps.test.ts +103 -0
  175. package/tests/maintainer/mcp-status.maintest.ts +88 -0
  176. package/tests/maintainer/pi-update-source.maintest.ts +116 -0
  177. package/tests/model-fallback-notice.test.ts +45 -0
  178. package/tests/model-fallback-policy.test.ts +83 -0
  179. package/tests/model-fallback-store.test.ts +111 -0
  180. package/tests/nan-provider.test.ts +4 -4
  181. package/tests/no-self-pause-contract.test.ts +19 -0
  182. package/tests/notification-customize.test.ts +58 -34
  183. package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
  184. package/tests/odd-routing-contract.test.ts +1 -1
  185. package/tests/orchestrator-fallback.test.ts +82 -0
  186. package/tests/orchestrator-prompt-budget.test.ts +131 -0
  187. package/tests/package-manifest.test.ts +160 -7
  188. package/tests/pasted-image-paths.test.ts +118 -0
  189. package/tests/persona-reply-language.test.ts +20 -1
  190. package/tests/pi-update-launcher.test.ts +32 -8
  191. package/tests/pi-update-source.test.ts +162 -0
  192. package/tests/profile-fast-tier.test.ts +311 -0
  193. package/tests/profile-tier-footer.test.ts +79 -0
  194. package/tests/questionnaire-view.test.ts +150 -0
  195. package/tests/review-candidate-owner-sweep.test.ts +93 -0
  196. package/tests/review-candidate-view.test.ts +51 -0
  197. package/tests/review-controller-native-routing.test.ts +120 -6
  198. package/tests/review-gate.test.ts +24 -0
  199. package/tests/review-inspect-preflight.test.ts +197 -0
  200. package/tests/review-integration-v2-forward.test.ts +59 -0
  201. package/tests/review-repository.test.ts +52 -1
  202. package/tests/review-sidebar-state.test.ts +5 -5
  203. package/tests/run-test-suite.test.ts +61 -5
  204. package/tests/sensitive-path-tools.test.ts +74 -0
  205. package/tests/session-profile-append-controller.test.ts +63 -0
  206. package/tests/session-profile-authority.test.ts +259 -0
  207. package/tests/session-profile-binding.test.ts +15 -0
  208. package/tests/session-profile-extension.test.ts +615 -0
  209. package/tests/session-profile-freeze.test.ts +110 -2
  210. package/tests/session-profile-integration.test.ts +857 -0
  211. package/tests/session-profile-persistence.test.ts +57 -0
  212. package/tests/session-profile-v1-compat.test.ts +221 -0
  213. package/tests/shell-bar.test.ts +113 -55
  214. package/tests/shell-card.test.ts +13 -1
  215. package/tests/shell-page.test.ts +108 -0
  216. package/tests/shell-panel.test.ts +332 -0
  217. package/tests/shell-prompt.test.ts +54 -0
  218. package/tests/shell-render-cache.test.ts +5 -0
  219. package/tests/shell-sidebar-fullscreen.test.ts +12 -0
  220. package/tests/shell-sidebar-layout.test.ts +159 -27
  221. package/tests/shell-stats.test.ts +90 -0
  222. package/tests/shell-usage.test.ts +14 -0
  223. package/tests/skill-registry.test.ts +68 -1
  224. package/tests/star-prompt.test.ts +470 -0
  225. package/tests/startup-banner.test.ts +57 -1
  226. package/tests/task-size-routing-contract.test.ts +45 -1
  227. package/tests/verifier-settle-reminder.test.ts +281 -0
  228. package/tests/verify-first-launch-contract.test.ts +56 -5
  229. package/tests/verify-installer-tap.test.ts +57 -0
  230. package/tests/vim-editor-adapter.test.ts +2 -2
  231. package/tests/visual-customization-policy.test.ts +61 -7
  232. package/tests/visual-customize-view.test.ts +253 -8
  233. package/tests/visual-layout-preview.test.ts +28 -0
  234. package/tests/windows-session-bootstrap.test.ts +105 -2
  235. package/tests/work-continuity-contract.test.ts +86 -0
  236. package/tests/writer-surfaces.test.ts +12 -10
  237. package/tests/yolo-customize.test.ts +30 -11
  238. package/tests/yolo-mode-runtime.test.ts +4 -2
  239. package/tests/yolo-mode.test.ts +16 -2
@@ -34,7 +34,7 @@ interface Harness {
34
34
  advance(ms: number): void;
35
35
  }
36
36
 
37
- function harness(options: { resolvePi?: RunnerDeps["resolvePi"]; failStart?: boolean; process?: RunnerDeps["process"]; pid?: number; maxConcurrency?: number; stallTimeoutMs?: number; toolStallTimeoutMs?: number; cleanupTimeoutMs?: number; answer?: Record<string, unknown>; exitOnKill?: boolean; exitOnStdinEnd?: boolean; state?: Record<string, unknown>; stateSuccess?: boolean; onNotification?: RunnerHooks["onNotification"]; onSuccessfulMutation?: RunnerHooks["onSuccessfulMutation"]; onFinish?: RunnerHooks["onFinish"] } = {}): Harness {
37
+ function harness(options: { resolvePi?: RunnerDeps["resolvePi"]; failStart?: boolean; process?: RunnerDeps["process"]; pid?: number; maxConcurrency?: number; stallTimeoutMs?: number; toolStallTimeoutMs?: number; cleanupTimeoutMs?: number; answer?: Record<string, unknown>; exitOnKill?: boolean; exitOnStdinEnd?: boolean; state?: Record<string, unknown>; stateSuccess?: boolean; onNotification?: RunnerHooks["onNotification"]; onSuccessfulMutation?: RunnerHooks["onSuccessfulMutation"]; onFinish?: RunnerHooks["onFinish"]; onFallback?: RunnerHooks["onFallback"]; reject?: (command: Record<string, unknown>) => boolean; hold?: (command: Record<string, unknown>) => boolean } = {}): Harness {
38
38
  const children: FakeChild[] = [];
39
39
  const timers: Harness["timers"] = [];
40
40
  const asks: Harness["asks"] = [];
@@ -54,8 +54,10 @@ function harness(options: { resolvePi?: RunnerDeps["resolvePi"]; failStart?: boo
54
54
  fake.child.stdin.on("data", (chunk) => {
55
55
  const command = JSON.parse(String(chunk));
56
56
  fake.written.push(command);
57
- fake.emit({ type: "response", id: command.id, success: command.type !== "get_state" || options.stateSuccess !== false,
58
- data: command.type === "get_state" ? options.state : undefined });
57
+ if (options.hold?.(command)) return;
58
+ const rejected = options.reject?.(command) === true;
59
+ fake.emit({ type: "response", id: command.id, success: !rejected && (command.type !== "get_state" || options.stateSuccess !== false),
60
+ ...(rejected ? { error: "No API key for provider" } : {}), data: command.type === "get_state" ? options.state : undefined });
59
61
  });
60
62
  }
61
63
  children.push(fake);
@@ -81,6 +83,7 @@ function harness(options: { resolvePi?: RunnerDeps["resolvePi"]; failStart?: boo
81
83
  onFinish: (task, observations) => { finishes.push(task.id); options.onFinish?.(task, observations); },
82
84
  onNotification: options.onNotification,
83
85
  onSuccessfulMutation: options.onSuccessfulMutation,
86
+ onFallback: options.onFallback,
84
87
  });
85
88
  return { store, runner, children, timers, asks, finishes, spawnOptions, advance(ms) {
86
89
  clock += ms;
@@ -2256,3 +2259,165 @@ test("advisories S2: session shutdown keeps a running or quarantined subagent's
2256
2259
  assert.equal(existsSync(scratch), false, "the startup sweep removes the kept scratch once its owner ended");
2257
2260
  next.shutdown();
2258
2261
  });
2262
+
2263
+ const quotaEnd = { type: "agent_end", messages: [{ role: "assistant", content: [], stopReason: "error", errorMessage: "429 insufficient_quota: monthly usage limit reached" }] };
2264
+
2265
+ test("a subagent that runs out of quota switches its child to the next model in place and continues", async () => {
2266
+ const fallbacks: Array<{ task: string; from: string; to: string; category: string }> = [];
2267
+ const h = harness({ state: { model: { provider: "fb-a", id: "primary" } }, onFallback: (task, change) => { fallbacks.push({ task: task.id, ...change }); } });
2268
+ const task = h.runner.run(request({ model: { provider: "fb-a", id: "primary" }, thinking: "high", fallbacks: [{ model: "fb-b/second", thinking: "medium" }, { model: "fb-c/third" }] }));
2269
+ await tick();
2270
+ h.children[0].emit(quotaEnd);
2271
+ h.children[0].emit({ type: "agent_settled" });
2272
+ await tick(); await tick(); await tick();
2273
+ assert.notEqual(h.store.get(task.id)?.status, TASK_STATUS.FAILED, "the task is still alive");
2274
+ const sent = h.children[0].written.map((command) => command.type);
2275
+ assert.deepEqual(h.children[0].written.filter((command) => command.type === "set_model").map((command) => [command.provider, command.modelId]), [["fb-b", "second"]]);
2276
+ assert.deepEqual(h.children[0].written.filter((command) => command.type === "set_thinking_level").map((command) => command.level), ["medium"]);
2277
+ assert.ok(sent.lastIndexOf("prompt") > sent.indexOf("set_model"), "the continue prompt follows the switch");
2278
+ assert.match(String(h.children[0].written.at(-1)?.message), /continue/i);
2279
+ assert.equal(h.store.get(task.id)?.model, "fb-b/second");
2280
+ assert.deepEqual(fallbacks, [{ task: task.id, from: "fb-a/primary", to: "fb-b/second", category: "quota" }]);
2281
+ assert.equal(h.spawnOptions.length, 1, "the same child keeps going");
2282
+ h.children[0].emit({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "done on the fallback" }], stopReason: "stop" }] });
2283
+ h.children[0].emit({ type: "agent_settled" });
2284
+ const done = await h.runner.waitFor(task.id);
2285
+ assert.equal(done.status, TASK_STATUS.COMPLETED);
2286
+ assert.equal(done.result, "done on the fallback");
2287
+ });
2288
+
2289
+ test("errors another model would repeat, or an exhausted chain, fail the subagent as before", async () => {
2290
+ const context = harness({ state: {} });
2291
+ const contextTask = context.runner.run(request({ model: { provider: "fb-d", id: "one" }, fallbacks: [{ model: "fb-e/two" }] }));
2292
+ await tick();
2293
+ context.children[0].emit({ type: "agent_end", messages: [{ role: "assistant", content: [], stopReason: "error", errorMessage: "prompt is too long: maximum context length" }] });
2294
+ context.children[0].emit({ type: "agent_settled" });
2295
+ const failed = await context.runner.waitFor(contextTask.id);
2296
+ assert.equal(failed.status, TASK_STATUS.FAILED);
2297
+ assert.equal(context.children[0].written.some((command) => command.type === "set_model"), false);
2298
+
2299
+ const none = harness({ state: {} });
2300
+ const noneTask = none.runner.run(request({ model: { provider: "fb-f", id: "only" } }));
2301
+ await tick();
2302
+ none.children[0].emit(quotaEnd);
2303
+ none.children[0].emit({ type: "agent_settled" });
2304
+ assert.equal((await none.runner.waitFor(noneTask.id)).status, TASK_STATUS.FAILED, "no chain, no fallback");
2305
+
2306
+ const spent = harness({ state: {} });
2307
+ const spentTask = spent.runner.run(request({ model: { provider: "fb-g", id: "one" }, fallbacks: [{ model: "fb-h/two" }] }));
2308
+ await tick();
2309
+ spent.children[0].emit(quotaEnd);
2310
+ spent.children[0].emit({ type: "agent_settled" });
2311
+ await tick(); await tick(); await tick();
2312
+ spent.children[0].emit(quotaEnd);
2313
+ spent.children[0].emit({ type: "agent_settled" });
2314
+ const exhausted = await spent.runner.waitFor(spentTask.id);
2315
+ assert.equal(exhausted.status, TASK_STATUS.FAILED, "the last model failing ends the task");
2316
+ assert.match(exhausted.error ?? "", /quota/);
2317
+ assert.equal(spent.children[0].written.filter((command) => command.type === "set_model").length, 1);
2318
+ });
2319
+
2320
+ test("a launch whose primary model is cooling down starts on the first usable fallback", async () => {
2321
+ const first = harness({ state: {} });
2322
+ const task = first.runner.run(request({ model: { provider: "fb-i", id: "cool" }, fallbacks: [{ model: "fb-j/warm" }] }));
2323
+ await tick();
2324
+ first.children[0].emit(quotaEnd);
2325
+ first.children[0].emit({ type: "agent_settled" });
2326
+ await tick(); await tick();
2327
+ const next = harness({ state: {} });
2328
+ next.runner.run(request({ model: { provider: "fb-i", id: "cool" }, thinking: "low", fallbacks: [{ model: "fb-j/warm", thinking: "high" }] }));
2329
+ await tick();
2330
+ const args = next.spawnOptions[0]!.args;
2331
+ assert.equal(args[args.indexOf("--model") + 1], "fb-j/warm:high", "the cooled primary is skipped at launch");
2332
+ assert.ok(task.id);
2333
+ });
2334
+
2335
+ test("a fallback Pi refuses (no key, unknown model) gives way to the next one, and only the model actually used is announced", async () => {
2336
+ const announced: string[] = [];
2337
+ const h = harness({ state: {}, reject: (command) => command.type === "set_model" && command.provider === "fb-l", onFallback: (_task, change) => { announced.push(`${change.from}->${change.to}`); } });
2338
+ const task = h.runner.run(request({ model: { provider: "fb-k", id: "one" }, fallbacks: [{ model: "fb-l/two" }, { model: "fb-m/three" }] }));
2339
+ await tick();
2340
+ h.children[0].emit(quotaEnd);
2341
+ h.children[0].emit({ type: "agent_settled" });
2342
+ for (let i = 0; i < 6; i++) await tick();
2343
+ assert.deepEqual(h.children[0].written.filter((command) => command.type === "set_model").map((command) => `${command.provider}/${command.modelId}`), ["fb-l/two", "fb-m/three"]);
2344
+ assert.deepEqual(announced, ["fb-k/one->fb-m/three"]);
2345
+ assert.equal(h.store.get(task.id)?.model, "fb-m/three");
2346
+ assert.notEqual(h.store.get(task.id)?.status, TASK_STATUS.FAILED);
2347
+ const none = harness({ state: {}, reject: (command) => command.type === "set_model" });
2348
+ const lost = none.runner.run(request({ model: { provider: "fb-n", id: "one" }, fallbacks: [{ model: "fb-o/two" }] }));
2349
+ await tick();
2350
+ none.children[0].emit(quotaEnd);
2351
+ none.children[0].emit({ type: "agent_settled" });
2352
+ const failed = await none.runner.waitFor(lost.id);
2353
+ assert.equal(failed.status, TASK_STATUS.FAILED);
2354
+ assert.match(failed.error ?? "", /could not switch to fb-o\/two: No API key/);
2355
+ });
2356
+
2357
+ test("starting on a fallback because the primary is cooling down is announced like any other switch", async () => {
2358
+ const first = harness({ state: {} });
2359
+ first.runner.run(request({ model: { provider: "fb-p", id: "cool" }, fallbacks: [{ model: "fb-q/warm" }] }));
2360
+ await tick();
2361
+ first.children[0].emit(quotaEnd);
2362
+ first.children[0].emit({ type: "agent_settled" });
2363
+ await tick(); await tick();
2364
+ const announced: Array<{ from: string; to: string; category: string; launch?: boolean }> = [];
2365
+ const next = harness({ state: {}, onFallback: (_task, change) => { announced.push(change); } });
2366
+ next.runner.run(request({ model: { provider: "fb-p", id: "cool" }, fallbacks: [{ model: "fb-q/warm" }] }));
2367
+ await tick();
2368
+ assert.deepEqual(announced, [{ from: "fb-p/cool", to: "fb-q/warm", category: "quota", launch: true }]);
2369
+ });
2370
+
2371
+ test("the task record remembers the model a fallback moved away from", async () => {
2372
+ const h = harness({ state: {} });
2373
+ const task = h.runner.run(request({ model: { provider: "fb-r", id: "one" }, fallbacks: [{ model: "fb-s/two" }] }));
2374
+ await tick();
2375
+ h.children[0].emit(quotaEnd);
2376
+ h.children[0].emit({ type: "agent_settled" });
2377
+ for (let i = 0; i < 4; i++) await tick();
2378
+ assert.equal(h.store.get(task.id)?.fallbackFrom, "fb-r/one");
2379
+ assert.equal(h.store.get(task.id)?.model, "fb-s/two");
2380
+ });
2381
+
2382
+ test("a fallback step without its own effort runs at the agent's configured effort", async () => {
2383
+ const h = harness({ state: {} });
2384
+ h.runner.run(request({ model: { provider: "fb-u", id: "one" }, thinking: "high", fallbacks: [{ model: "fb-v/two", thinking: "low" }, { model: "fb-w/three" }] }));
2385
+ await tick();
2386
+ for (let round = 0; round < 2; round++) {
2387
+ h.children[0].emit(quotaEnd);
2388
+ h.children[0].emit({ type: "agent_settled" });
2389
+ for (let i = 0; i < 6; i++) await tick();
2390
+ }
2391
+ assert.deepEqual(h.children[0].written.filter((command) => command.type === "set_thinking_level").map((command) => command.level), ["low", "high"]);
2392
+ });
2393
+
2394
+ test("a launch fallback is announced only once the child actually started", async () => {
2395
+ const first = harness({ state: {} });
2396
+ first.runner.run(request({ model: { provider: "fb-x", id: "cool" }, fallbacks: [{ model: "fb-y/warm" }] }));
2397
+ await tick();
2398
+ first.children[0].emit(quotaEnd);
2399
+ first.children[0].emit({ type: "agent_settled" });
2400
+ await tick(); await tick();
2401
+ const announced: string[] = [];
2402
+ const failing = harness({ failStart: true, onFallback: (_task, change) => { announced.push(change.to); } });
2403
+ const task = failing.runner.run(request({ model: { provider: "fb-x", id: "cool" }, fallbacks: [{ model: "fb-y/warm" }] }));
2404
+ await failing.runner.waitFor(task.id);
2405
+ assert.deepEqual(announced, [], "a spawn that failed announces nothing");
2406
+ const starting = harness({ state: {}, onFallback: (_task, change) => { announced.push(change.to); } });
2407
+ starting.runner.run(request({ model: { provider: "fb-x", id: "cool" }, fallbacks: [{ model: "fb-y/warm" }] }));
2408
+ await tick();
2409
+ assert.deepEqual(announced, ["fb-y/warm"]);
2410
+ });
2411
+
2412
+ test("a task cancelled after Pi accepted the new model records that model", async () => {
2413
+ const h = harness({ state: {}, hold: (command) => command.type === "set_thinking_level" });
2414
+ const task = h.runner.run(request({ model: { provider: "fb-z", id: "one" }, fallbacks: [{ model: "fb-za/two", thinking: "low" }] }));
2415
+ await tick();
2416
+ h.children[0].emit(quotaEnd);
2417
+ h.children[0].emit({ type: "agent_settled" });
2418
+ for (let i = 0; i < 4; i++) await tick();
2419
+ h.runner.cancel(task.id);
2420
+ const done = await h.runner.waitFor(task.id);
2421
+ assert.equal(done.model, "fb-za/two");
2422
+ assert.equal(done.fallbackFrom, "fb-z/one");
2423
+ });
@@ -298,6 +298,33 @@ test("AgentsView keys move the selection, scroll, follow, cancel, open, and clos
298
298
  assert.deepEqual(events, ["cancel:a", "open:a", "close"]);
299
299
  });
300
300
 
301
+ test("AgentsView clamps thread scrolling at the bottom so the first upward key moves", () => {
302
+ for (const [down, up] of [["\x0a", "\x0b"], ["\x1b[6~", "\x1b[5~"]]) {
303
+ const { store, view } = harness(8);
304
+ try {
305
+ store.add(task("a"));
306
+ for (let i = 0; i < 30; i++) store.apply("a", { type: TASK_EVENT.TEXT, text: `line ${i}\n` }, 2000);
307
+ const bottom = view.render(80).slice(1, 5);
308
+ assert.match(bottom.join("\n"), /line 29/);
309
+ view.handleInput(up);
310
+ const previousPage = view.render(80).slice(1, 5);
311
+ assert.notDeepEqual(previousPage, bottom, "ordinary upward scrolling still moves one page");
312
+ view.handleInput(down);
313
+ assert.deepEqual(view.render(80).slice(1, 5), bottom, "ordinary downward scrolling returns to the bottom");
314
+ for (let i = 0; i < 7; i++) {
315
+ view.handleInput(down);
316
+ assert.deepEqual(view.render(80).slice(1, 5), bottom, "extra downward presses leave the bottom visible");
317
+ }
318
+ view.handleInput(up);
319
+ assert.deepEqual(view.render(80).slice(1, 5), previousPage, "the first upward press moves immediately without consuming hidden offset");
320
+ view.handleInput("f");
321
+ assert.deepEqual(view.render(80).slice(1, 5), bottom, "follow still restores the tail");
322
+ } finally {
323
+ view.dispose();
324
+ }
325
+ }
326
+ });
327
+
301
328
  test("AgentsView subscribes only to the selected task and survives an empty store", () => {
302
329
  const { store, view, renders } = harness(6);
303
330
  assert.match(stripAnsi(view.render(60)[1]), /no tasks yet/);
@@ -1,8 +1,14 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test, { after, before, type TestContext } from "node:test";
3
3
  import { visibleWidth } from "@earendil-works/pi-tui";
4
- import { TASK_STATUS, type TaskRecord } from "../lib/agents-protocol.ts";
5
- import { formatElapsed, renderAgentsCard, widgetExpiryMs, widgetRows, widgetTasks } from "../lib/agents-widget.ts";
4
+ import { TASK_STATUS, TaskStore, type TaskRecord } from "../lib/agents-protocol.ts";
5
+ import installGentleAgents from "../extensions/gentle-agents.ts";
6
+ import { PresencePublisher } from "../lib/orchestrator-presence.ts";
7
+ import { sidebarState } from "../lib/shell-sidebar.ts";
8
+ import { installSidebar } from "../lib/shell-sidebar-layout.ts";
9
+ import { TuiAltScreen, VStack, type Component, type Terminal, type TUI, type TuiMouseEvent } from "@earendil-works/pi-tui";
10
+ import { agentsSpend, agentsSummary, formatElapsed, renderAgentsAlert, renderAgentsCard, renderAgentsSection, widgetExpiryMs, widgetRows, widgetTasks } from "../lib/agents-widget.ts";
11
+ import { formatTokens } from "../lib/shell-bar.ts";
6
12
  import { CARD_STYLE, cardStyle, setCardStyle, type CardStyle } from "../lib/shell-card.ts";
7
13
  import { stripAnsi } from "../lib/terminal-theme.ts";
8
14
 
@@ -102,6 +108,51 @@ test("renderAgentsCard draws columns for agent, task, and model · tokens · cos
102
108
  assert.deepEqual(renderAgentsCard([], plainTheme, 60, 0, { collapsed: false }), []);
103
109
  });
104
110
 
111
+ test("sidebar activity appears below each agent without changing the capped above-editor view", () => {
112
+ const tasks = [
113
+ task({ id: "a", agent: "explore", label: "Investigando estado de subagentes" }),
114
+ task({ id: "b", agent: "writer", label: "Preparando pruebas", createdAt: 2000, startedAt: 2000 }),
115
+ ];
116
+ const sidebar = renderAgentsCard(tasks, plainTheme, 44, 5_000, { collapsed: false }).map(stripAnsi);
117
+ assert.match(sidebar[1]!, /explore.*34k · \$0\.270 · 4s/);
118
+ assert.equal(bodyText(sidebar[2]!), "Investigando estado de subagentes");
119
+ assert.match(sidebar[3]!, /writer.*34k · \$0\.270 · 3s/);
120
+ assert.equal(bodyText(sidebar[4]!), "Preparando pruebas");
121
+ for (const line of sidebar) assert.equal(visibleWidth(line), 44);
122
+
123
+ const above = renderAgentsCard(tasks, plainTheme, 44, 5_000, { collapsed: false, maxRows: 8 }).map(stripAnsi);
124
+ assert.equal(above.length, 4);
125
+ assert.match(above[1]!, /explore.*34k · \$0\.270 · 4s/);
126
+ assert.match(above[2]!, /writer.*34k · \$0\.270 · 3s/);
127
+ assert.doesNotMatch(above.join("\n"), /Investigando|Preparando/);
128
+ });
129
+
130
+ test("sidebar activity uses waiting and error text, clips to width, and preserves fallback metadata", () => {
131
+ const tasks = [
132
+ task({ id: "a", agent: "explore", status: TASK_STATUS.WAITING, lastStep: "asked: ¿Continuar?", label: "not waiting text", model: "long-model-name", thinking: "high" }),
133
+ task({ id: "b", agent: "writer", status: TASK_STATUS.FAILED, endedAt: 4_000, error: "falló la ejecución", label: "not error text", model: "long-model-name", thinking: "high", createdAt: 2000, startedAt: 2000 }),
134
+ ];
135
+ const sidebar = renderAgentsCard(tasks, plainTheme, 16, 5_000, { collapsed: false }).map(stripAnsi);
136
+ assert.ok(sidebar.some((line) => bodyText(line) === "asked: ¿Con…"));
137
+ assert.ok(sidebar.some((line) => bodyText(line) === "falló la ej…"));
138
+ assert.equal(sidebar.filter((line) => line.includes(" · high")).length, 2, "fallback execution metadata survives on its own row");
139
+ assert.doesNotMatch(sidebar.join("\n"), /not waiting|not error/);
140
+ for (const line of sidebar) assert.equal(visibleWidth(line), 16);
141
+ for (const width of [0, 1, 2, 3, 4, 8, 16, 24, 28, 44]) {
142
+ for (const line of renderAgentsCard(tasks, plainTheme, width, 5_000, { collapsed: false })) assert.equal(visibleWidth(line), width);
143
+ }
144
+ });
145
+
146
+ test("sidebar activity is not duplicated when inline and includes queued tasks", () => {
147
+ const queued = task({ id: "q", agent: "writer", status: TASK_STATUS.QUEUED, startedAt: null, label: "Preparando pruebas" });
148
+ const narrow = renderAgentsCard([queued], plainTheme, 28, 5_000, { collapsed: false }).map(stripAnsi);
149
+ assert.match(narrow[1]!, /writer.*queued/);
150
+ assert.equal(bodyText(narrow[2]!), "Preparando pruebas");
151
+ const wide = renderAgentsCard([queued], plainTheme, 100, 5_000, { collapsed: false }).map(stripAnsi);
152
+ assert.equal(wide.length, 3);
153
+ assert.match(wide[1]!, /writer\s+Preparando pruebas/);
154
+ });
155
+
105
156
  test("renderAgentsCard right-aligns model·effort, tokens, cost, and elapsed in fixed columns that line up across rows", () => {
106
157
  const tasks = [
107
158
  task({ id: "a", agent: "a", model: "claude-sonnet-5", thinking: "medium", startedAt: 1000, endedAt: 26_000, tokens: 34_000, cost: 0.27 }),
@@ -159,7 +210,7 @@ test("renderAgentsCard keeps every task on one line, clipping long labels, and d
159
210
  // Narrow cards degrade per column: task text first, then the model name,
160
211
  // then tokens and cost. Elapsed is the one value the reader cannot rebuild
161
212
  // from anything else on screen, so it is the last to go.
162
- const narrow = renderAgentsCard(tasks, plainTheme, 44, 5_000, { collapsed: false }).map(stripAnsi);
213
+ const narrow = renderAgentsCard(tasks, plainTheme, 44, 5_000, { collapsed: false, maxRows: 8 }).map(stripAnsi);
163
214
  assert.equal(narrow.length, 3);
164
215
  assert.match(narrow[1], /^│ ◐ sdd-explore +34k · \$0\.270 · 4s │$/, "the model name goes before tokens, cost and elapsed");
165
216
  });
@@ -168,12 +219,12 @@ test("renderAgentsCard keeps every task on one line, clipping long labels, and d
168
219
  // model-only fallback, silently dropping tokens, cost and the running time.
169
220
  test("renderAgentsCard keeps tokens, cost and elapsed when a long model name no longer fits", () => {
170
221
  const tasks = [task({ id: "a", model: "anthropic/claude-sonnet-4-5-20250929", tokens: 12_345, cost: 0.42, startedAt: 5_000 - 184_000 })];
171
- const lines = renderAgentsCard(tasks, plainTheme, 46, 5_000, { collapsed: false }).map(stripAnsi);
222
+ const lines = renderAgentsCard(tasks, plainTheme, 46, 5_000, { collapsed: false, maxRows: 8 }).map(stripAnsi);
172
223
  assert.equal(lines.length, 3);
173
224
  assert.match(lines[1], /^│ ◐ sdd-explore +12k · \$0\.420 · 3m04s │$/, "tokens, cost and elapsed survive; the model name is what gives way");
174
- const tighter = renderAgentsCard(tasks, plainTheme, 34, 5_000, { collapsed: false }).map(stripAnsi);
225
+ const tighter = renderAgentsCard(tasks, plainTheme, 34, 5_000, { collapsed: false, maxRows: 8 }).map(stripAnsi);
175
226
  assert.match(tighter[1], /^│ ◐ sdd-explore +\$0\.420 · 3m04s │$/, "then tokens go, then cost, elapsed last");
176
- const tightest = renderAgentsCard(tasks, plainTheme, 28, 5_000, { collapsed: false }).map(stripAnsi);
227
+ const tightest = renderAgentsCard(tasks, plainTheme, 28, 5_000, { collapsed: false, maxRows: 8 }).map(stripAnsi);
177
228
  assert.match(tightest[1], /^│ ◐ sdd-explore +3m04s │$/, "elapsed is the last column standing");
178
229
  });
179
230
 
@@ -182,7 +233,7 @@ test("renderAgentsCard degrades every row of a mixed card together so columns st
182
233
  task({ id: "a", model: "anthropic/claude-sonnet-4-5-20250929", tokens: 12_345, cost: 0.42 }),
183
234
  task({ id: "b", agent: "writer", model: "openai/gpt-5", tokens: 900, cost: 0.01 }),
184
235
  ];
185
- const lines = renderAgentsCard(tasks, plainTheme, 46, 5_000, { collapsed: false }).map(stripAnsi);
236
+ const lines = renderAgentsCard(tasks, plainTheme, 46, 5_000, { collapsed: false, maxRows: 8 }).map(stripAnsi);
186
237
  assert.match(lines[1], /12k · \$0\.420 · 4s │$/);
187
238
  assert.match(lines[2], /900 · \$0\.010 · 4s │$/);
188
239
  assert.equal(lines[1].indexOf("· 4s"), lines[2].indexOf("· 4s"), "elapsed stays in one column across rows");
@@ -215,14 +266,14 @@ test("renderAgentsCard shows questions and failures in place of the task, and co
215
266
  // the label is the one value the user already chose and can look up.
216
267
  test("usage outranks the model label at narrow widths without inventing unknown values", () => {
217
268
  for (const width of [60, 100]) {
218
- const lines = renderAgentsCard([task({ agent: "worker", model: "openai/gpt-5", thinking: "high" })], plainTheme, width, 5000, { collapsed: false });
269
+ const lines = renderAgentsCard([task({ agent: "worker", model: "openai/gpt-5", thinking: "high" })], plainTheme, width, 5000, { collapsed: false, maxRows: 8 });
219
270
  assert.equal(lines.length, 3);
220
271
  assert.match(lines[1], /worker/);
221
272
  assert.match(lines[1], /gpt-5 · high · 34k · \$0\.270 · 4s/, "wide enough for every column");
222
273
  for (const line of lines) assert.equal(visibleWidth(line), width);
223
274
  }
224
275
  for (const width of [32, 44]) {
225
- const lines = renderAgentsCard([task({ agent: "worker", model: "openai/gpt-5", thinking: "high" })], plainTheme, width, 5000, { collapsed: false });
276
+ const lines = renderAgentsCard([task({ agent: "worker", model: "openai/gpt-5", thinking: "high" })], plainTheme, width, 5000, { collapsed: false, maxRows: 8 });
226
277
  assert.equal(lines.length, 3);
227
278
  assert.match(lines[1], /worker/);
228
279
  assert.doesNotMatch(lines[1], /gpt-5/, "the model label is the first column to go");
@@ -230,7 +281,7 @@ test("usage outranks the model label at narrow widths without inventing unknown
230
281
  for (const line of lines) assert.equal(visibleWidth(line), width);
231
282
  }
232
283
  for (const width of [0, 1, 2, 3, 4, 8, 16, 24]) {
233
- const lines = renderAgentsCard([task({ agent: "界worker", thinking: "xhigh" })], plainTheme, width, 5000, { collapsed: false });
284
+ const lines = renderAgentsCard([task({ agent: "界worker", thinking: "xhigh" })], plainTheme, width, 5000, { collapsed: false, maxRows: 8 });
234
285
  assert.ok(lines.length <= 4, "narrow metadata gets at most one dedicated row");
235
286
  for (const line of lines) assert.equal(visibleWidth(line), width);
236
287
  }
@@ -366,3 +417,254 @@ test("renderAgentsCard in the float style is a float panel two rows taller than
366
417
  const [, header] = renderAgentsCard([task({ status: TASK_STATUS.WAITING })], tagged, 120, 5000, { collapsed: true, collapseKey: "ctrl+a" });
367
418
  assert.match(stripAnsi(header!), /^ <warning>▎<\/warning> <warning>❀ Agents<\/warning> <muted>1 waiting<\/muted> +<muted>ctrl\+a expand<\/muted> {3}$/);
368
419
  });
420
+
421
+ // The fullscreen rail draws Agents as a panel section (design/shell-rework/06-many-agents.html):
422
+ // one row per agent, the task first, then the agent kind and its tokens and
423
+ // time, ordered by what needs you; finished work folds into one row.
424
+
425
+ test("the Agents section orders rows by what needs you and aligns kind and time columns", () => {
426
+ const now = 400_000;
427
+ const tasks = [
428
+ task({ id: "done", agent: "gentle-ai-verify", label: "verify T1 title row", status: TASK_STATUS.COMPLETED, startedAt: 0, endedAt: 380_000 }),
429
+ task({ id: "worker", agent: "gentle-ai-worker", label: "T3 rail panel sections", startedAt: 28_000, tokens: 2_100_000 }),
430
+ task({ id: "asks", agent: "gentle-ai-explore", label: "map sidebar render paths", lastStep: "Which base branch should the chain use?", status: TASK_STATUS.WAITING, startedAt: 10_000 }),
431
+ task({ id: "queued", agent: "gentle-ai-worker", label: "T5 mobile work row", status: TASK_STATUS.QUEUED, startedAt: null, createdAt: 50_000, tokens: 0 }),
432
+ task({ id: "failed", agent: "gentle-ai-worker", label: "T6 customize presets", status: TASK_STATUS.FAILED, error: "T6 customize presets", startedAt: 300_000, endedAt: 370_000 }),
433
+ task({ id: "verify", agent: "gentle-ai-verify", label: "verify T2 editor rule", startedAt: 277_000, tokens: 800_000 }),
434
+ ];
435
+ const lines = renderAgentsSection(tasks, plainTheme, 50, now, { collapsed: false });
436
+ for (const line of lines) assert.equal(visibleWidth(line), 50, `row fills the section: ${line}`);
437
+ const rows = lines.map((line) => line.trimEnd());
438
+ assert.match(rows[0]!, /^▾ AGENTS +2 running · 1 waiting$/);
439
+ const worker = `${formatTokens(2_100_000)} ${formatElapsed(372_000)}`;
440
+ const verify = `${formatTokens(800_000)} ${formatElapsed(123_000)}`;
441
+ assert.deepEqual(rows.slice(1).map((row) => row.replace(/\s{2,}/g, " | ")), [
442
+ " | ? Which base branch should… explore | asks you",
443
+ ` | ◐ T3 rail panel sections | worker | ${worker}`,
444
+ ` | ◐ verify T2 editor rule | verify | ${verify}`,
445
+ " | ○ T5 mobile work row | worker | queued",
446
+ ` | ✗ T6 customize presets | worker | failed ${formatElapsed(70_000)}`,
447
+ " | ✓ 1 done · /gentle:agents",
448
+ ]);
449
+ const kindColumn = rows.slice(1, 6).map((row) => [...row.matchAll(/(explore|worker|verify)(?= )/g)].at(-1)!.index);
450
+ assert.equal(new Set(kindColumn).size, 1, `agent kinds line up in one column: ${kindColumn}`);
451
+ });
452
+
453
+ test("agent row hover paints only the pointed task text in the shared warning role", () => {
454
+ const roles: Record<string, number> = { warning: 208, accent: 30, text: 250, muted: 245, dim: 240, error: 160, border: 238 };
455
+ const theme = { fg: (role: string, text: string) => `\x1b[38;5;${roles[role] ?? 255}m${text}\x1b[39m` };
456
+ const tasks = [task({ id: "a", agent: "scout", label: "map files" }), task({ id: "b", agent: "writer", label: "write tests", status: TASK_STATUS.FAILED, endedAt: 4_000 })];
457
+ const warning = "\x1b[38;5;208m";
458
+ const error = "\x1b[38;5;160m✗";
459
+ for (const render of [
460
+ (hoveredRow?: number) => renderAgentsCard(tasks, theme, 80, 5_000, { collapsed: false, hoveredRow }),
461
+ (hoveredRow?: number) => renderAgentsSection(tasks, theme, 80, 5_000, { collapsed: false, hoveredRow }),
462
+ ]) {
463
+ const idle = render();
464
+ const hovered = render(2);
465
+ assert.equal(hovered[1], idle[1], "the neighboring task is not highlighted");
466
+ assert.match(hovered[2]!, new RegExp(`${warning.replaceAll("[", "\\[")}[^\\x1b]*write tests`));
467
+ assert.ok(hovered[2]!.includes(error), "the failed status glyph keeps its error role");
468
+ assert.deepEqual(render(), idle, "leaving restores every original role");
469
+ }
470
+ });
471
+
472
+ test("agent hover geometry excludes float padding, overflow and idle rows", (t) => {
473
+ useCardStyle(t, CARD_STYLE.FLOAT);
474
+ const theme = withBackground({ fg: (role: string, text: string) => `\x1b[38;5;${role === "warning" ? 208 : 250}m${text}\x1b[39m` });
475
+ const tasks = Array.from({ length: 4 }, (_, index) => task({ id: String(index), agent: `worker-${index}`, label: `task-${index}` }));
476
+ const agentRows: number[] = [];
477
+ const idle = renderAgentsCard(tasks, theme, 80, 5_000, { collapsed: false, maxRows: 4, onAgentRow: (row) => agentRows.push(row) });
478
+ assert.deepEqual(agentRows, [3]);
479
+ assert.match(stripAnsi(idle[4]!), /… 3 more/);
480
+ const hovered = renderAgentsCard(tasks, theme, 80, 5_000, { collapsed: false, maxRows: 4, hoveredRow: 3 });
481
+ assert.ok(hovered[3]!.includes("\x1b[38;5;208m"));
482
+ assert.equal(hovered[2], idle[2], "float separator stays unpainted");
483
+ assert.equal(hovered[4], idle[4], "overflow stays unpainted");
484
+ const idleRows: number[] = [];
485
+ renderAgentsSection([], theme, 50, 5_000, { collapsed: false, onAgentRow: (row) => idleRows.push(row) });
486
+ assert.deepEqual(idleRows, []);
487
+ });
488
+
489
+ test("agent widget routes row hover, reset, collapse and clicks through its public component", async (t) => {
490
+ const tasks = [task({ id: "a", agent: "scout", label: "map files" }), task({ id: "b", agent: "writer", label: "write tests" })];
491
+ t.mock.method(TaskStore.prototype, "list", () => tasks);
492
+ t.mock.method(PresencePublisher, "start", () => { throw new Error("presence disabled in this test"); });
493
+ const handlers = new Map<string, Array<(event: { reason: string }, ctx: unknown) => unknown>>();
494
+ const pi = {
495
+ on(name: string, handler: (event: { reason: string }, ctx: unknown) => unknown) { handlers.set(name, [...(handlers.get(name) ?? []), handler]); },
496
+ events: { on: () => () => {}, emit() {} },
497
+ registerTool() {}, registerCommand() {}, registerShortcut() {}, registerMarkdownTransformer() {}, registerMessageRenderer() {}, registerEntryRenderer() {},
498
+ };
499
+ installGentleAgents(pi as never, { GENTLE_PI_CONFIG_HOME: "/dev/null" }, {
500
+ home: "/dev/null", agentHome: "/dev/null", env: { GENTLE_PI_CONFIG_HOME: "/dev/null" },
501
+ now: () => 5_000, schedule: () => () => {}, resolveWorktree: () => undefined,
502
+ });
503
+ let factory: ((tui: unknown, theme: unknown) => Component) | undefined;
504
+ let opens = 0;
505
+ const ctx = {
506
+ hasUI: true, mode: "tui", cwd: "/repo", modelRegistry: {},
507
+ sessionManager: { getSessionId: () => "bad id", getCwd: () => "/repo", getEntries: () => [], getBranch: () => [] },
508
+ ui: { setWidget: (_key: string, value: typeof factory) => { factory = value; }, custom: async () => { opens++; return null; }, notify() {} },
509
+ };
510
+ await handlers.get("session_start")!.at(-1)!({ reason: "new" }, ctx);
511
+ const tui = { terminal: { columns: 160, rows: 40 }, requestRender() {} };
512
+ const theme = { fg: (role: string, text: string) => `\x1b[38;5;${role === "warning" ? 208 : 250}m${text}\x1b[39m` };
513
+ const component = factory!(tui, theme);
514
+ const rows = component.render(80);
515
+ const event = (type: TuiMouseEvent["type"], button: TuiMouseEvent["button"], y: number): TuiMouseEvent => ({ type, button, x: 5, y, screenX: 15, screenY: 20 + y, width: 80, height: rows.length, shift: false, alt: false, ctrl: false });
516
+ const rail = sidebarState(tui as unknown as TUI).parts.get("agents")!;
517
+ const before = rail.digest!();
518
+ component.handleMouse?.(event("move", "none", 1));
519
+ assert.ok(component.render(80)[1]!.includes("\x1b[38;5;208m"), "the pointed agent row uses the hover role");
520
+ component.handleMouse?.(event("move", "none", 2));
521
+ assert.ok(component.render(80)[2]!.includes("\x1b[38;5;208m"), "moving selects the other row");
522
+ component.handleMouse?.(event("move", "none", rows.length - 1));
523
+ assert.ok(!component.render(80)[2]!.includes("\x1b[38;5;208m"), "moving to the spacer clears row hover");
524
+ assert.equal(rail.digest!(), before, "hover is cleared from the cache digest");
525
+ const railRows = rail.render(46);
526
+ const railEvent = (type: TuiMouseEvent["type"], button: TuiMouseEvent["button"], y: number): TuiMouseEvent => ({ type, button, x: 5, y, screenX: 105, screenY: 5 + y, width: 46, height: railRows.length, shift: false, alt: false, ctrl: false });
527
+ rail.handleMouse?.(railEvent("move", "none", 1));
528
+ assert.notEqual(rail.digest!(), before, "rail hover invalidates the section digest");
529
+ assert.ok(rail.render(46)[1]!.includes("\x1b[38;5;208m"));
530
+ rail.invalidate();
531
+ assert.equal(rail.digest!(), before);
532
+ component.handleMouse?.(event("move", "none", rows.length - 1));
533
+ assert.ok(!component.render(80).at(-1)!.includes("\x1b[38;5;208m"), "spacer and border never light up");
534
+ component.handleMouse?.(event("click", "right", 1));
535
+ assert.equal(opens, 0);
536
+ component.handleMouse?.(event("click", "left", 1));
537
+ assert.equal(opens, 1, "an agent row still opens the agents view");
538
+ component.handleMouse?.(event("click", "left", 0));
539
+ assert.match(stripAnsi(component.render(80)[0]!), /Expand/, "the header still collapses");
540
+ assert.equal(opens, 1);
541
+ await t.test("native fullscreen motion into a sibling clears agent hover", () => {
542
+ let input: ((data: string) => void) | undefined;
543
+ const terminal: Terminal = {
544
+ start(onInput) { input = onInput; }, stop() {}, async drainInput() {}, write() {}, columns: 80, rows: 24, kittyProtocolActive: false,
545
+ moveBy() {}, hideCursor() {}, showCursor() {}, clearLine() {}, clearFromCursor() {}, clearScreen() {}, setTitle() {}, setProgress() {}, setProgramStatus() {},
546
+ };
547
+ const nativeTui = new TuiAltScreen(terminal, false, undefined, { mouse: true });
548
+ const nativeCard = factory!(nativeTui, theme);
549
+ const outside = { render: () => ["outside"], invalidate() {} };
550
+ nativeTui.setLayoutRoot(new VStack([nativeCard, outside]));
551
+ const uninstall = installSidebar(nativeTui, { fg: theme.fg, bold: (text) => text });
552
+ nativeTui.start();
553
+ try {
554
+ nativeTui.renderNow(true);
555
+ const rendered = nativeCard.render(80);
556
+ input?.("\x1b[<35;6;2M");
557
+ assert.ok(nativeCard.render(80)[1]!.includes("\x1b[38;5;208m"), "native motion enters an agent row");
558
+ input?.(`\x1b[<35;1;${rendered.length + 1}M`);
559
+ assert.ok(!nativeCard.render(80)[1]!.includes("\x1b[38;5;208m"), "native motion into a sibling clears hover");
560
+ } finally {
561
+ uninstall();
562
+ (nativeCard as Component & { dispose?(): void }).dispose?.();
563
+ nativeTui.stop();
564
+ }
565
+ });
566
+ tasks.length = 0;
567
+ const idle = rail.render(46);
568
+ rail.handleMouse?.(railEvent("move", "none", 1));
569
+ assert.equal(rail.render(46)[1], idle[1], "the idle row is not an agent hover target");
570
+ (component as Component & { dispose?(): void }).dispose?.();
571
+ });
572
+
573
+ test("an idle Agents section keeps one muted row pointing at /gentle:agents", () => {
574
+ const lines = renderAgentsSection([], plainTheme, 50, 0, { collapsed: false }).map((line) => line.trimEnd());
575
+ assert.deepEqual(lines.map((row) => row.replace(/\s{2,}/g, " | ")), ["▾ AGENTS | idle", " | none running · /gentle:agents"]);
576
+ });
577
+
578
+ test("a collapsed Agents section keeps the row that needs you most", () => {
579
+ const tasks = [task({ id: "run", label: "running one" }), task({ id: "ask", label: "asking", lastStep: "Pick one?", status: TASK_STATUS.WAITING })];
580
+ const lines = renderAgentsSection(tasks, plainTheme, 50, 10_000, { collapsed: true }).map((line) => line.trimEnd());
581
+ assert.equal(lines.length, 2);
582
+ assert.match(lines[0]!, /^▸ AGENTS/);
583
+ assert.match(lines[1]!, /^ {2}\? Pick one\?/);
584
+ });
585
+
586
+ test("more agents than the section's rows keep waiting and running rows and count the rest", () => {
587
+ const tasks = Array.from({ length: 12 }, (_, index) => task({ id: `q${index}`, label: `queued ${index}`, status: TASK_STATUS.QUEUED, startedAt: null, createdAt: index }))
588
+ .concat(task({ id: "run", label: "the running one", createdAt: 100 }), task({ id: "ask", label: "asking", lastStep: "Need you?", status: TASK_STATUS.WAITING, createdAt: 101 }));
589
+ const rows = renderAgentsSection(tasks, plainTheme, 50, 10_000, { collapsed: false }).map((line) => line.trim());
590
+ assert.match(rows[1]!, /^\? Need you\?/);
591
+ assert.match(rows[2]!, /^◐ the running one/);
592
+ assert.equal(rows.length, 1 + 8, "eight rows, the last one counting the rest");
593
+ assert.match(rows.at(-1)!, /^… 7 more · \/gentle:agents$/);
594
+ });
595
+
596
+ test("the agents alert names the agent asking the user and its question, above the editor", () => {
597
+ const painted = { fg: (_color: string, text: string) => text, bg: (_color: string, text: string) => `\x1b[48;5;52m${text}\x1b[49m` };
598
+ const waiting = [
599
+ task({ id: "a", agent: "gentle-ai-explore", status: TASK_STATUS.WAITING, lastStep: "asked: Which base branch should the chain use?", createdAt: 1 }),
600
+ task({ id: "b", agent: "gentle-ai-worker", status: TASK_STATUS.WAITING, lastStep: "asked: Overwrite the fixture?", createdAt: 2 }),
601
+ task({ id: "c", label: "running" }),
602
+ ];
603
+ const lines = renderAgentsAlert(waiting, painted, 110);
604
+ assert.equal(lines.length, 1);
605
+ assert.ok(lines[0]!.startsWith("\x1b[48;5;52m"), "the alert sits on the selection surface");
606
+ const row = stripAnsi(lines[0]!);
607
+ assert.equal(visibleWidth(row), 110);
608
+ assert.match(stripAnsi(renderAgentsAlert(waiting, painted, 60)[0]!), /…\s+\+1 more · \/gentle:agents $/, "a narrow row clips the question, never the way to the agents view");
609
+ assert.match(row, /^ \? explore asked: Which base branch should the chain use\? +\+1 more · \/gentle:agents $/);
610
+ assert.deepEqual(renderAgentsAlert([task({ id: "c" })], painted, 80), [], "nothing waits, nothing paints");
611
+ });
612
+
613
+ test("the agents summary counts running, waiting and failed agents for the mobile work row", () => {
614
+ const tasks = [task({ id: "a" }), task({ id: "b" }), task({ id: "c", status: TASK_STATUS.WAITING, lastStep: "asked: x" }), task({ id: "d", status: TASK_STATUS.FAILED, endedAt: 9_000 })];
615
+ assert.deepEqual(agentsSummary(tasks, plainTheme, 10_000), { left: "◐ 3 agents · ? 1 waiting · ✗ 1", priority: 1 });
616
+ assert.equal(agentsSummary([task({ id: "e", status: TASK_STATUS.COMPLETED, endedAt: 9_000 })], plainTheme, 10_000), undefined, "finished work alone is not live work");
617
+ });
618
+
619
+ test("agentsSpend totals every started subagent's tokens and cost for the Stats section", () => {
620
+ assert.equal(agentsSpend([]), undefined);
621
+ assert.equal(agentsSpend([task({ id: "q", status: TASK_STATUS.QUEUED, tokens: 0, cost: 0 })]), undefined, "queued tasks have not spent anything");
622
+ const spend = agentsSpend([
623
+ task({ id: "a", status: TASK_STATUS.COMPLETED, tokens: 1200, cost: 0.12 }),
624
+ task({ id: "b", status: TASK_STATUS.RUNNING, tokens: 2300, cost: 0.08 }),
625
+ task({ id: "c", status: TASK_STATUS.FAILED, tokens: 0, cost: 0 }),
626
+ task({ id: "q", status: TASK_STATUS.QUEUED, tokens: 0, cost: 0 }),
627
+ ])!;
628
+ assert.equal(spend.runs, 3);
629
+ assert.equal(spend.tokens, 3500);
630
+ assert.equal(Math.round(spend.cost * 100), 20);
631
+ });
632
+
633
+ test("an agent that fell back to another model says so on its row", () => {
634
+ const theme = { fg: (_role: string, text: string) => text };
635
+ const now = 10_000;
636
+ const moved = task({ id: "m", status: TASK_STATUS.RUNNING, startedAt: 1_000, model: "openai/gpt-5.5", fallbackFrom: "anthropic/claude-opus-5-5", tokens: 1200 });
637
+ const stayed = task({ id: "s", status: TASK_STATUS.RUNNING, startedAt: 2_000, model: "anthropic/claude-opus-5-5", tokens: 800 });
638
+ const rows = renderAgentsSection([moved, stayed], theme as never, 60, now, { collapsed: false }).map((row) => row.trimEnd());
639
+ assert.ok(rows.some((row) => /↪ .+ · gpt-5\.5/.test(row)), rows.join("\n"));
640
+ assert.equal(rows.filter((row) => row.includes("↪")).length, 1, "only the agent that moved");
641
+ });
642
+
643
+ test("a moved agent's ↪ mark never changes the other rows, at any rail width", () => {
644
+ const theme = { fg: (_role: string, text: string) => text };
645
+ const now = 70_000;
646
+ const others = [
647
+ task({ id: "w", status: TASK_STATUS.WAITING, startedAt: 1_000, prompt: "grep the repo", agent: "sdd-explore" }),
648
+ task({ id: "f", status: TASK_STATUS.FAILED, startedAt: 2_000, endedAt: 59_000, prompt: "verify the change", agent: "gentle-ai-verify" }),
649
+ ];
650
+ const running = task({ id: "r", status: TASK_STATUS.RUNNING, startedAt: 3_000, prompt: "write the parser", agent: "gentle-ai-worker", tokens: 34_000, model: "anthropic/claude-opus-5-5" });
651
+ for (const width of [46, 30, 20]) {
652
+ const plain = renderAgentsSection([...others, running], theme as never, width, now, { collapsed: false });
653
+ const moved = renderAgentsSection([...others, { ...running, model: "openai/gpt-5.5", fallbackFrom: "anthropic/claude-opus-5-5" }], theme as never, width, now, { collapsed: false });
654
+ const movedRow = moved.findIndex((row) => /34k/.test(row));
655
+ moved.forEach((row, index) => {
656
+ if (index !== movedRow) assert.equal(row, plain[index], `row ${index} is untouched at ${width}`);
657
+ assert.ok(visibleWidth(row) <= width);
658
+ });
659
+ if (width >= 30) assert.match(moved[movedRow]!, /↪/, `the mark shows at ${width}`);
660
+ }
661
+ });
662
+
663
+ test("a moved agent's row keeps its task readable and adds the model when there is room", () => {
664
+ const theme = { fg: (_role: string, text: string) => text };
665
+ const running = task({ id: "r", status: TASK_STATUS.RUNNING, startedAt: 3_000, prompt: "write the parser", label: "write the parser", agent: "gentle-ai-worker", tokens: 34_000, model: "anthropic/claude-opus-5-5", fallbackFrom: "openai/gpt-5.5" });
666
+ const at46 = renderAgentsSection([running], theme as never, 46, 70_000, { collapsed: false }).join("\n");
667
+ assert.match(at46, /↪ write the/, "the task comes first after the mark");
668
+ const at90 = renderAgentsSection([running], theme as never, 90, 70_000, { collapsed: false }).join("\n");
669
+ assert.match(at90, /↪ write the parser · claude-opus-5-5/);
670
+ });