@blackbelt-technology/pi-dashboard-extension 0.7.0 → 0.9.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 (265) hide show
  1. package/.pi/skills/browser/SKILL.md +84 -29
  2. package/.pi/skills/browser/UPSTREAM.md +13 -1
  3. package/.pi/skills/browser/references/challenge.md +183 -0
  4. package/.pi/skills/browser/references/dashboard-relay.md +150 -0
  5. package/.pi/skills/browser/references/electron.agent.md +57 -0
  6. package/.pi/skills/browser/references/own-browser.md +305 -0
  7. package/.pi/skills/browser/references/web.agent.md +323 -0
  8. package/.pi/skills/browser/scripts/check-panerelay.sh +157 -0
  9. package/.pi/skills/doctor/SKILL.md +4 -9
  10. package/.pi/skills/doctor/_lib/checks.ts +133 -54
  11. package/.pi/skills/doctor/_lib/derive-tokens.ts +5 -0
  12. package/.pi/skills/doctor/modules/apple-tools.knowledge.hash +1 -0
  13. package/.pi/skills/doctor/modules/apple-tools.md +52 -0
  14. package/.pi/skills/doctor/modules/mcp-builtin.knowledge.hash +1 -0
  15. package/.pi/skills/doctor/modules/mcp-builtin.md +61 -0
  16. package/.pi/skills/doctor/modules/oauth-redirect-base.knowledge.hash +1 -0
  17. package/.pi/skills/doctor/modules/oauth-redirect-base.md +71 -0
  18. package/.pi/skills/doctor/modules/pi-resolution.knowledge.hash +1 -1
  19. package/.pi/skills/doctor/modules/pi-resolution.md +21 -1
  20. package/.pi/skills/doctor/modules/plugins-bridges.md +14 -1
  21. package/.pi/skills/pi-dashboard/SKILL.md +10 -3
  22. package/.pi/skills/pi-dashboard/references/api-reference.agent.md +69 -0
  23. package/.pi/skills/pi-dashboard/scripts/dashboard-bus.ts +4 -4
  24. package/.pi/skills/project-init/SKILL.md +41 -34
  25. package/.pi/skills/project-init/profiles/coding/AGENTS.md.tmpl +0 -23
  26. package/.pi/skills/project-init/profiles/docs/profile.json +1 -1
  27. package/README.md +19 -0
  28. package/agents/DoxTriage.md +80 -0
  29. package/package.json +30 -16
  30. package/src/ask-user-tool.ts +4 -0
  31. package/src/auto-session-namer.ts +486 -70
  32. package/src/autostart-guard.ts +99 -0
  33. package/src/autostart-lock.ts +258 -0
  34. package/src/bridge-activation.ts +26 -0
  35. package/src/bridge-context.ts +106 -23
  36. package/src/bridge-default-model-gate.ts +38 -0
  37. package/src/bridge-polling.ts +148 -0
  38. package/src/bridge-ticket-client.ts +105 -0
  39. package/src/bridge.ts +1760 -350
  40. package/src/canvas-tool.ts +5 -0
  41. package/src/command-handler.ts +392 -71
  42. package/src/connect-target.ts +130 -0
  43. package/src/connection.ts +846 -17
  44. package/src/custom-entry-forward.ts +92 -0
  45. package/src/endpoint-resolution.ts +253 -0
  46. package/src/event-forwarder.ts +42 -0
  47. package/src/extension-identity.ts +59 -0
  48. package/src/flow-event-wiring.ts +125 -3
  49. package/src/followup-buffer.ts +217 -0
  50. package/src/git-dir-watcher.ts +79 -0
  51. package/src/git-poll.ts +45 -12
  52. package/src/git-probe-scheduler.ts +119 -0
  53. package/src/git-tracker.ts +284 -0
  54. package/src/instance-verification.ts +156 -0
  55. package/src/local-token-header.ts +44 -0
  56. package/src/mcp-token-delivery.ts +147 -0
  57. package/src/message-update-coalescer.ts +340 -0
  58. package/src/model-refresh.ts +95 -0
  59. package/src/model-tracker.ts +118 -35
  60. package/src/notify-proxy.ts +36 -0
  61. package/src/path-gate/decide.ts +149 -0
  62. package/src/path-gate/grant-cache.ts +71 -0
  63. package/src/path-gate/grant-link.ts +108 -0
  64. package/src/path-gate/handler.ts +307 -0
  65. package/src/path-gate/index.ts +155 -0
  66. package/src/path-gate/resolve.ts +126 -0
  67. package/src/path-gate/roots.ts +137 -0
  68. package/src/path-gate/suppression.ts +27 -0
  69. package/src/pending-prompt-emitter.ts +59 -0
  70. package/src/pi-env.d.ts +6 -10
  71. package/src/pi-retry-settings.ts +91 -0
  72. package/src/plugin-request-client.ts +114 -0
  73. package/src/poll-cost.ts +40 -0
  74. package/src/pr-status.ts +338 -0
  75. package/src/process-metrics.ts +77 -1
  76. package/src/process-scan-scheduler.ts +137 -0
  77. package/src/process-scanner.ts +226 -247
  78. package/src/project-init/dox-kb-config.ts +3 -0
  79. package/src/project-init/scaffold.ts +1 -4
  80. package/src/project-init/seed-doctrine.ts +23 -60
  81. package/src/prompt-bus.ts +13 -0
  82. package/src/provider-register.ts +92 -21
  83. package/src/remote-registration-gate.ts +102 -0
  84. package/src/retry-tracker.ts +258 -86
  85. package/src/role-manager.ts +38 -91
  86. package/src/role-model-tools.ts +44 -3
  87. package/src/server-auto-start.ts +331 -20
  88. package/src/server-launcher.ts +70 -34
  89. package/src/server-pin-store.ts +92 -0
  90. package/src/session-move.ts +275 -0
  91. package/src/session-sync.ts +75 -20
  92. package/src/slash-dispatch.ts +66 -81
  93. package/src/subagent-fanout-admission.ts +234 -0
  94. package/src/subagent-forward-sites.ts +69 -0
  95. package/src/subagent-frame-buffer.ts +24 -3
  96. package/src/subagent-frame-strip.ts +109 -0
  97. package/src/subagent-saturation.ts +196 -0
  98. package/src/subagent-tick-throttle.ts +250 -0
  99. package/src/terminal-reload.ts +298 -0
  100. package/src/transcript-backfill.ts +151 -0
  101. package/src/transport-diagnostics.ts +76 -0
  102. package/src/tui-prompt-adapter.ts +13 -1
  103. package/src/turn-actionability.ts +20 -0
  104. package/src/ui-stale-guard.ts +58 -0
  105. package/src/usage-drain.ts +167 -0
  106. package/src/vcs-info.ts +261 -63
  107. package/.pi/skills/doctor/AGENTS.md +0 -27
  108. package/.pi/skills/project-init/dox-doctrine.md +0 -104
  109. package/src/AGENTS.md +0 -57
  110. package/src/__tests__/abort-latch.test.ts +0 -97
  111. package/src/__tests__/agent-settled.test.ts +0 -82
  112. package/src/__tests__/artifact-roots.test.ts +0 -83
  113. package/src/__tests__/ask-user-attachments.test.ts +0 -106
  114. package/src/__tests__/ask-user-schema-discriminator.test.ts +0 -141
  115. package/src/__tests__/ask-user-tool.test.ts +0 -571
  116. package/src/__tests__/auto-session-namer.test.ts +0 -339
  117. package/src/__tests__/bridge-default-model-apply.test.ts +0 -242
  118. package/src/__tests__/bridge-default-model-gate.test.ts +0 -50
  119. package/src/__tests__/bridge-entry-id-pi-070.test.ts +0 -174
  120. package/src/__tests__/bridge-followup-chat-order.test.ts +0 -215
  121. package/src/__tests__/bridge-followup-multi-entry.test.ts +0 -202
  122. package/src/__tests__/bridge-followup-mutation.test.ts +0 -217
  123. package/src/__tests__/bridge-followup-queue-drain.test.ts +0 -266
  124. package/src/__tests__/bridge-hasui-flip.test.ts +0 -109
  125. package/src/__tests__/bridge-no-queue-mutation.test.ts +0 -112
  126. package/src/__tests__/bridge-plugin-emit-event.test.ts +0 -44
  127. package/src/__tests__/bridge-queue-update-forward.test.ts +0 -77
  128. package/src/__tests__/bridge-resume-disconnect.test.ts +0 -333
  129. package/src/__tests__/bridge-shadow-queue-gate.test.ts +0 -299
  130. package/src/__tests__/bridge-shutdown-reset.test.ts +0 -159
  131. package/src/__tests__/bridge-slash-command-routing.test.ts +0 -458
  132. package/src/__tests__/bridge-stop-after-turn.test.ts +0 -72
  133. package/src/__tests__/bridge-system-followup.test.ts +0 -163
  134. package/src/__tests__/bridge-thinking-level-select.test.ts +0 -68
  135. package/src/__tests__/browser-skill-registered.test.ts +0 -84
  136. package/src/__tests__/build-provider-catalogue.test.ts +0 -210
  137. package/src/__tests__/command-handler.test.ts +0 -1180
  138. package/src/__tests__/commit-draft.test.ts +0 -100
  139. package/src/__tests__/connection-dropped-frames.test.ts +0 -78
  140. package/src/__tests__/connection-suppress-auto-start.test.ts +0 -97
  141. package/src/__tests__/connection.test.ts +0 -344
  142. package/src/__tests__/credentials-updated.test.ts +0 -26
  143. package/src/__tests__/custom-provider-apikey-roundtrip.test.ts +0 -128
  144. package/src/__tests__/cwd-missing-probe.test.ts +0 -82
  145. package/src/__tests__/dashboard-commands-shipped.test.ts +0 -53
  146. package/src/__tests__/dashboard-context-injector.test.ts +0 -190
  147. package/src/__tests__/dashboard-default-adapter.test.ts +0 -77
  148. package/src/__tests__/dev-build.test.ts +0 -79
  149. package/src/__tests__/doctor/checks.test.ts +0 -121
  150. package/src/__tests__/doctor/modules.test.ts +0 -64
  151. package/src/__tests__/doctor/provenance-hash.test.ts +0 -94
  152. package/src/__tests__/doctor/router.test.ts +0 -143
  153. package/src/__tests__/empty-actionable-guard-config.test.ts +0 -32
  154. package/src/__tests__/empty-actionable-guard.test.ts +0 -73
  155. package/src/__tests__/enrich-model-metadata.test.ts +0 -222
  156. package/src/__tests__/event-forwarder.test.ts +0 -119
  157. package/src/__tests__/extension-slash-command-detection.test.ts +0 -143
  158. package/src/__tests__/filter-enabled-models.test.ts +0 -151
  159. package/src/__tests__/fixtures/turn-actionability-fixtures.ts +0 -69
  160. package/src/__tests__/fork-entryid-timing.test.ts +0 -88
  161. package/src/__tests__/git-info-status.test.ts +0 -73
  162. package/src/__tests__/git-link-builder.test.ts +0 -102
  163. package/src/__tests__/git-poll.test.ts +0 -69
  164. package/src/__tests__/markdown-image-inliner.test.ts +0 -392
  165. package/src/__tests__/model-resolve.test.ts +0 -379
  166. package/src/__tests__/multiselect-dashboard-routing.test.ts +0 -203
  167. package/src/__tests__/multiselect-list.test.ts +0 -137
  168. package/src/__tests__/multiselect-polyfill.test.ts +0 -92
  169. package/src/__tests__/no-session-replacement-calls.test.ts +0 -99
  170. package/src/__tests__/no-tui-multiselect-arm-regression.test.ts +0 -81
  171. package/src/__tests__/openspec-activity-detector.test.ts +0 -337
  172. package/src/__tests__/openspec-cli-shim.test.ts +0 -145
  173. package/src/__tests__/openspec-poller.test.ts +0 -124
  174. package/src/__tests__/pi-version-tracker.test.ts +0 -109
  175. package/src/__tests__/process-metrics.test.ts +0 -47
  176. package/src/__tests__/process-scanner-kill.test.ts +0 -61
  177. package/src/__tests__/process-scanner.test.ts +0 -292
  178. package/src/__tests__/project-init-detect-stack.test.ts +0 -61
  179. package/src/__tests__/project-init-dox-kb-config.test.ts +0 -53
  180. package/src/__tests__/project-init-profiles.test.ts +0 -84
  181. package/src/__tests__/project-init-scaffold.test.ts +0 -139
  182. package/src/__tests__/project-init-seed-doctrine.test.ts +0 -100
  183. package/src/__tests__/project-trust.test.ts +0 -92
  184. package/src/__tests__/prompt-bus-wiring.test.ts +0 -791
  185. package/src/__tests__/prompt-bus.test.ts +0 -513
  186. package/src/__tests__/prompt-expander.test.ts +0 -398
  187. package/src/__tests__/provider-register-native-models.test.ts +0 -182
  188. package/src/__tests__/provider-register-reload.test.ts +0 -498
  189. package/src/__tests__/provider-register-thinking-levels.test.ts +0 -104
  190. package/src/__tests__/retry-tracker.test.ts +0 -152
  191. package/src/__tests__/role-manager.test.ts +0 -585
  192. package/src/__tests__/role-model-tools-registry-readiness.test.ts +0 -114
  193. package/src/__tests__/role-model-tools.test.ts +0 -229
  194. package/src/__tests__/search-files-completeness.test.ts +0 -111
  195. package/src/__tests__/search-files-ranking.test.ts +0 -168
  196. package/src/__tests__/server-auto-start.test.ts +0 -375
  197. package/src/__tests__/server-launcher-launch.test.ts +0 -96
  198. package/src/__tests__/server-launcher.test.ts +0 -101
  199. package/src/__tests__/server-probe.test.ts +0 -25
  200. package/src/__tests__/session-switch.test.ts +0 -139
  201. package/src/__tests__/session-sync.test.ts +0 -243
  202. package/src/__tests__/single-derivation-guard.test.ts +0 -39
  203. package/src/__tests__/source-detector.test.ts +0 -88
  204. package/src/__tests__/stats-extractor.test.ts +0 -92
  205. package/src/__tests__/subagent-frame-buffer.test.ts +0 -239
  206. package/src/__tests__/tool-result-image-inliner.test.ts +0 -206
  207. package/src/__tests__/tui-prompt-adapter.test.ts +0 -213
  208. package/src/__tests__/turn-actionability.test.ts +0 -86
  209. package/src/__tests__/ui-decorators.test.ts +0 -309
  210. package/src/__tests__/ui-modules.test.ts +0 -293
  211. package/src/__tests__/vcs-info.test.ts +0 -265
  212. package/src/__tests__/visibility-intent.test.ts +0 -43
  213. package/src/__tests__/watchdog.test.ts +0 -161
  214. package/src/abort-latch.ts.AGENTS.md +0 -3
  215. package/src/agent-settled.ts +0 -72
  216. package/src/agent-settled.ts.AGENTS.md +0 -3
  217. package/src/artifact-roots.ts.AGENTS.md +0 -3
  218. package/src/ask-user-attachments.ts.AGENTS.md +0 -3
  219. package/src/ask-user-tool.ts.AGENTS.md +0 -3
  220. package/src/auto-session-namer.ts.AGENTS.md +0 -3
  221. package/src/bridge-context.ts.AGENTS.md +0 -3
  222. package/src/bridge-default-model-gate.ts.AGENTS.md +0 -3
  223. package/src/bridge.ts.AGENTS.md +0 -3
  224. package/src/command-handler.ts.AGENTS.md +0 -3
  225. package/src/commit-draft-agent.ts.AGENTS.md +0 -3
  226. package/src/commit-draft.ts.AGENTS.md +0 -3
  227. package/src/connection.ts.AGENTS.md +0 -3
  228. package/src/dashboard-context-injector.ts.AGENTS.md +0 -3
  229. package/src/dashboard-default-adapter.ts.AGENTS.md +0 -3
  230. package/src/dev-build.ts.AGENTS.md +0 -3
  231. package/src/empty-actionable-guard-config.ts.AGENTS.md +0 -3
  232. package/src/empty-actionable-guard.ts.AGENTS.md +0 -3
  233. package/src/event-forwarder.ts.AGENTS.md +0 -3
  234. package/src/flow-event-wiring.ts.AGENTS.md +0 -3
  235. package/src/git-link-builder.ts.AGENTS.md +0 -3
  236. package/src/git-poll.ts.AGENTS.md +0 -3
  237. package/src/hasui-flip.ts.AGENTS.md +0 -3
  238. package/src/markdown-image-inliner.ts.AGENTS.md +0 -3
  239. package/src/model-tracker.ts.AGENTS.md +0 -3
  240. package/src/multiselect-decode.ts.AGENTS.md +0 -3
  241. package/src/multiselect-list.ts.AGENTS.md +0 -3
  242. package/src/multiselect-polyfill.ts.AGENTS.md +0 -3
  243. package/src/openspec-cli-shim.ts.AGENTS.md +0 -7
  244. package/src/process-metrics.ts.AGENTS.md +0 -3
  245. package/src/process-scanner.ts.AGENTS.md +0 -3
  246. package/src/project-init/AGENTS.md +0 -12
  247. package/src/project-trust.ts.AGENTS.md +0 -3
  248. package/src/prompt-bus.ts.AGENTS.md +0 -3
  249. package/src/prompt-expander.ts.AGENTS.md +0 -3
  250. package/src/provider-register.ts.AGENTS.md +0 -3
  251. package/src/retry-tracker.ts.AGENTS.md +0 -3
  252. package/src/role-manager.ts.AGENTS.md +0 -3
  253. package/src/role-model-tools.ts.AGENTS.md +0 -3
  254. package/src/server-auto-start.ts.AGENTS.md +0 -3
  255. package/src/server-launcher.ts.AGENTS.md +0 -3
  256. package/src/session-sync.ts.AGENTS.md +0 -3
  257. package/src/slash-dispatch.ts.AGENTS.md +0 -3
  258. package/src/source-detector.ts.AGENTS.md +0 -3
  259. package/src/subagent-frame-buffer.ts.AGENTS.md +0 -3
  260. package/src/tool-result-image-inliner.ts.AGENTS.md +0 -3
  261. package/src/tui-prompt-adapter.ts.AGENTS.md +0 -3
  262. package/src/turn-actionability.ts.AGENTS.md +0 -3
  263. package/src/ui-modules.ts.AGENTS.md +0 -3
  264. package/src/vcs-info.ts.AGENTS.md +0 -3
  265. package/src/visibility-intent.ts.AGENTS.md +0 -3
@@ -1,1180 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
2
- import { mkdirSync, writeFileSync, rmSync } from "node:fs";
3
- import { join } from "node:path";
4
- import { createCommandHandler, parseSendPrompt, tryExecSlashTemplate, buildDashboardExecEnv } from "../command-handler.js";
5
- import type { ServerToExtensionMessage } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
6
-
7
- // Mock the tool registry so `!`/`!!` bash resolution is deterministic
8
- // across hosts. `bashMock` is mutated per-test to simulate found / missing.
9
- // See change: register-bash-and-tool-install-help.
10
- const registryMock = vi.hoisted(() => ({
11
- bash: { ok: true, path: "/usr/bin/bash" } as { ok: boolean; path: string | null },
12
- }));
13
- vi.mock("@blackbelt-technology/pi-dashboard-shared/tool-registry/index.js", () => ({
14
- getDefaultRegistry: () => ({
15
- resolve: (name: string) =>
16
- name === "bash"
17
- ? {
18
- name: "bash",
19
- ok: registryMock.bash.ok,
20
- path: registryMock.bash.path,
21
- source: registryMock.bash.ok ? "system" : null,
22
- tried: [],
23
- resolvedAt: 0,
24
- }
25
- : { name, ok: false, path: null, source: null, tried: [], resolvedAt: 0 },
26
- }),
27
- }));
28
-
29
- describe("CommandHandler", () => {
30
- function createMockPi() {
31
- return {
32
- sendUserMessage: vi.fn(),
33
- getCommands: vi.fn().mockReturnValue([
34
- { name: "test", description: "Test cmd", source: "extension" as const },
35
- ]),
36
- setSessionName: vi.fn(),
37
- getSessionName: vi.fn(),
38
- on: vi.fn(),
39
- exec: vi.fn(),
40
- };
41
- }
42
-
43
- it("should call sendUserMessage on send_prompt when idle", async () => {
44
- const pi = createMockPi();
45
- const handler = createCommandHandler(pi as any, "s1");
46
-
47
- const msg: ServerToExtensionMessage = {
48
- type: "send_prompt",
49
- sessionId: "s1",
50
- text: "Hello agent",
51
- };
52
-
53
- await handler.handle(msg);
54
-
55
- expect(pi.sendUserMessage).toHaveBeenCalledWith("Hello agent", { deliverAs: "followUp" });
56
- });
57
-
58
- // Non-turn commands never produce a user message_start, so the bridge settles
59
- // any optimistic idle pendingPrompt with `prompt_received {fresh:false}` (drop)
60
- // instead of letting it hang to the 30s timeout.
61
- // See change: optimistic-prompt-progress (CodeRabbit follow-up).
62
- it("emits prompt_received{fresh:false} for a non-turn command (bash)", async () => {
63
- const pi = createMockPi();
64
- const eventSink = vi.fn();
65
- const handler = createCommandHandler(pi as any, "s1", { eventSink });
66
-
67
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "!ls" } as ServerToExtensionMessage);
68
-
69
- expect(eventSink).toHaveBeenCalledWith(
70
- expect.objectContaining({ type: "prompt_received", sessionId: "s1", fresh: false }),
71
- );
72
- });
73
-
74
- it("should ignore messages for different sessionIds", async () => {
75
- const pi = createMockPi();
76
- const handler = createCommandHandler(pi as any, "s1");
77
-
78
- const msg: ServerToExtensionMessage = {
79
- type: "send_prompt",
80
- sessionId: "s2",
81
- text: "Hello",
82
- };
83
-
84
- await handler.handle(msg);
85
- expect(pi.sendUserMessage).not.toHaveBeenCalled();
86
- });
87
-
88
- it("should send images with valid mimeType via sendUserMessage", async () => {
89
- const pi = createMockPi();
90
- const handler = createCommandHandler(pi as any, "s1");
91
-
92
- await handler.handle({
93
- type: "send_prompt",
94
- sessionId: "s1",
95
- text: "check this",
96
- images: [
97
- { type: "image", data: "abc123", mimeType: "image/png" },
98
- ],
99
- });
100
-
101
- expect(pi.sendUserMessage).toHaveBeenCalledWith([
102
- { type: "text", text: "check this" },
103
- { type: "image", data: "abc123", mimeType: "image/png" },
104
- ], { deliverAs: "followUp" });
105
- });
106
-
107
- it("should drop images with invalid mimeType and send text only", async () => {
108
- const pi = createMockPi();
109
- const handler = createCommandHandler(pi as any, "s1");
110
-
111
- await handler.handle({
112
- type: "send_prompt",
113
- sessionId: "s1",
114
- text: "check this",
115
- images: [
116
- { type: "image", data: "abc123", mimeType: "image/bmp" },
117
- ],
118
- });
119
-
120
- // Invalid mimeType → dropped, sends text only
121
- expect(pi.sendUserMessage).toHaveBeenCalledWith("check this", { deliverAs: "followUp" });
122
- });
123
-
124
- it("should drop images with undefined or null mimeType", async () => {
125
- const pi = createMockPi();
126
- const handler = createCommandHandler(pi as any, "s1");
127
-
128
- await handler.handle({
129
- type: "send_prompt",
130
- sessionId: "s1",
131
- text: "check this",
132
- images: [
133
- { type: "image", data: "abc123", mimeType: undefined as any },
134
- { type: "image", data: "abc123", mimeType: null as any },
135
- ],
136
- });
137
-
138
- expect(pi.sendUserMessage).toHaveBeenCalledWith("check this", { deliverAs: "followUp" });
139
- });
140
-
141
- it("should drop images with empty or non-string data", async () => {
142
- const pi = createMockPi();
143
- const handler = createCommandHandler(pi as any, "s1");
144
-
145
- await handler.handle({
146
- type: "send_prompt",
147
- sessionId: "s1",
148
- text: "check this",
149
- images: [
150
- { type: "image", data: "", mimeType: "image/png" },
151
- ],
152
- });
153
-
154
- expect(pi.sendUserMessage).toHaveBeenCalledWith("check this", { deliverAs: "followUp" });
155
- });
156
-
157
- it("should drop non-object image entries", async () => {
158
- const pi = createMockPi();
159
- const handler = createCommandHandler(pi as any, "s1");
160
-
161
- await handler.handle({
162
- type: "send_prompt",
163
- sessionId: "s1",
164
- text: "check this",
165
- images: [null as any, "bad" as any],
166
- });
167
-
168
- expect(pi.sendUserMessage).toHaveBeenCalledWith("check this", { deliverAs: "followUp" });
169
- });
170
-
171
- it("should keep valid images and drop invalid ones", async () => {
172
- const pi = createMockPi();
173
- const handler = createCommandHandler(pi as any, "s1");
174
-
175
- await handler.handle({
176
- type: "send_prompt",
177
- sessionId: "s1",
178
- text: "check this",
179
- images: [
180
- { type: "image", data: "good", mimeType: "image/jpeg" },
181
- { type: "image", data: "bad", mimeType: "image/bmp" },
182
- { type: "image", data: "also-good", mimeType: "image/webp" },
183
- ],
184
- });
185
-
186
- expect(pi.sendUserMessage).toHaveBeenCalledWith([
187
- { type: "text", text: "check this" },
188
- { type: "image", data: "good", mimeType: "image/jpeg" },
189
- { type: "image", data: "also-good", mimeType: "image/webp" },
190
- ], { deliverAs: "followUp" });
191
- });
192
-
193
- it("should handle rename_session by calling setSessionName and returning confirmation", async () => {
194
- const pi = createMockPi();
195
- const handler = createCommandHandler(pi as any, "s1");
196
-
197
- const result = await handler.handle({
198
- type: "rename_session",
199
- sessionId: "s1",
200
- name: "My New Name",
201
- });
202
-
203
- expect(pi.setSessionName).toHaveBeenCalledWith("My New Name");
204
- expect(result).toEqual({
205
- type: "session_name_update",
206
- sessionId: "s1",
207
- name: "My New Name",
208
- });
209
- });
210
-
211
- it("should call shutdown option when shutdown message received", async () => {
212
- const pi = createMockPi();
213
- const shutdown = vi.fn();
214
- const handler = createCommandHandler(pi as any, "s1", { shutdown });
215
-
216
- await handler.handle({ type: "shutdown", sessionId: "s1" } as ServerToExtensionMessage);
217
- expect(shutdown).toHaveBeenCalled();
218
- });
219
-
220
- it("should not crash when shutdown called without option", async () => {
221
- const pi = createMockPi();
222
- const handler = createCommandHandler(pi as any, "s1");
223
-
224
- // Should not throw
225
- await handler.handle({ type: "shutdown", sessionId: "s1" } as ServerToExtensionMessage);
226
- });
227
-
228
- it("should call abort option when abort message received", async () => {
229
- const pi = createMockPi();
230
- const abort = vi.fn();
231
- const handler = createCommandHandler(pi as any, "s1", { abort });
232
-
233
- await handler.handle({ type: "abort", sessionId: "s1" } as ServerToExtensionMessage);
234
- expect(abort).toHaveBeenCalled();
235
- });
236
-
237
- it("should not crash when abort called without option", async () => {
238
- const pi = createMockPi();
239
- const handler = createCommandHandler(pi as any, "s1");
240
-
241
- // Should not throw
242
- await handler.handle({ type: "abort", sessionId: "s1" } as ServerToExtensionMessage);
243
- });
244
-
245
- it("abort schedules persistent-abort retries (rawAbort) until isIdle returns true", async () => {
246
- // Persistent-abort scheduler uses rawAbort (not the full wrapper) for
247
- // repeated 200ms ticks. See change:
248
- // unify-status-banner-and-terminal-limit-stop.
249
- vi.useFakeTimers();
250
- const pi = createMockPi();
251
- const abort = vi.fn();
252
- const rawAbort = vi.fn();
253
- let idleAfter = 3; // become idle after 3 polls
254
- const isIdle = vi.fn(() => --idleAfter <= 0);
255
- const isStreaming = vi.fn(() => true); // stays streaming, only isIdle gates
256
- const handler = createCommandHandler(pi as any, "s1", { abort, rawAbort, isIdle, isStreaming, eventSink: vi.fn() });
257
-
258
- await handler.handle({ type: "abort", sessionId: "s1" } as ServerToExtensionMessage);
259
- expect(abort).toHaveBeenCalledOnce(); // wrapper-abort: exactly once
260
- expect(rawAbort).not.toHaveBeenCalled(); // ticks haven't fired yet
261
-
262
- // Advance through the persistent-abort schedule. Each 200ms tick
263
- // checks streaming transition, then isIdle, then calls rawAbort.
264
- vi.advanceTimersByTime(200); // tick 1: idleAfter 3→2, rawAbort
265
- vi.advanceTimersByTime(200); // tick 2: idleAfter 2→1, rawAbort
266
- vi.advanceTimersByTime(200); // tick 3: idleAfter 1→0, isIdle true, no rawAbort, scheduler stops
267
- vi.advanceTimersByTime(1000); // no more rawAborts
268
-
269
- expect(abort.mock.calls.length).toBe(1); // wrapper still only once
270
- expect(rawAbort.mock.calls.length).toBe(2); // 2 ticks before isIdle returned true
271
- vi.useRealTimers();
272
- });
273
-
274
- it("persistent-abort scheduler stops after 2 seconds even if never idle", async () => {
275
- vi.useFakeTimers();
276
- const pi = createMockPi();
277
- const abort = vi.fn();
278
- const rawAbort = vi.fn();
279
- const isIdle = vi.fn(() => false); // never idle
280
- const isStreaming = vi.fn(() => true); // stays streaming
281
- const handler = createCommandHandler(pi as any, "s1", { abort, rawAbort, isIdle, isStreaming, eventSink: vi.fn() });
282
-
283
- await handler.handle({ type: "abort", sessionId: "s1" } as ServerToExtensionMessage);
284
-
285
- vi.advanceTimersByTime(2500); // safely past 2s cap
286
- // Wrapper-abort: exactly once. Raw-abort: ~10 ticks (2000ms / 200ms).
287
- expect(abort.mock.calls.length).toBe(1);
288
- const rawCalls = rawAbort.mock.calls.length;
289
- expect(rawCalls).toBeGreaterThanOrEqual(9);
290
- expect(rawCalls).toBeLessThanOrEqual(10);
291
-
292
- // Past cap, no more calls
293
- const before = rawAbort.mock.calls.length;
294
- vi.advanceTimersByTime(1000);
295
- expect(rawAbort.mock.calls.length).toBe(before);
296
- vi.useRealTimers();
297
- });
298
-
299
- it("persistent-abort scheduler stops on isAgentStreaming true→false transition", async () => {
300
- // See change: unify-status-banner-and-terminal-limit-stop. Once pi's
301
- // agent_end has flipped streaming off, the scheduler must stop —
302
- // continuing would risk aborting a fresh user re-send.
303
- vi.useFakeTimers();
304
- const pi = createMockPi();
305
- const abort = vi.fn();
306
- const rawAbort = vi.fn();
307
- let streaming = true;
308
- const isStreaming = vi.fn(() => streaming);
309
- const isIdle = vi.fn(() => false); // isIdle never reports idle
310
- const handler = createCommandHandler(pi as any, "s1", { abort, rawAbort, isIdle, isStreaming, eventSink: vi.fn() });
311
-
312
- await handler.handle({ type: "abort", sessionId: "s1" } as ServerToExtensionMessage);
313
- expect(abort).toHaveBeenCalledOnce();
314
-
315
- vi.advanceTimersByTime(200); // tick 1: still streaming, rawAbort fires
316
- vi.advanceTimersByTime(200); // tick 2: still streaming, rawAbort fires
317
- expect(rawAbort.mock.calls.length).toBe(2);
318
-
319
- // pi's agent_end flips streaming off
320
- streaming = false;
321
-
322
- vi.advanceTimersByTime(200); // tick 3: streaming transitioned, scheduler stops
323
- vi.advanceTimersByTime(2000); // no more rawAborts even past the 2s cap
324
- expect(rawAbort.mock.calls.length).toBe(2);
325
- vi.useRealTimers();
326
- });
327
-
328
- it("abort synthesizes auto_retry_end event without finalError after invoking abort callback", async () => {
329
- // The hardcoded "Aborted by user" finalError placeholder was removed.
330
- // The synth still fires (to clear retryState) but no longer sets
331
- // SessionState.lastError to a misleading string — the real provider
332
- // error surfaces via pi's subsequent agent_end / orderer synth.
333
- // See change: unify-status-banner-and-terminal-limit-stop.
334
- const pi = createMockPi();
335
- const calls: Array<{ name: string; arg?: unknown }> = [];
336
- const abort = vi.fn(() => calls.push({ name: "abort" }));
337
- const eventSink = vi.fn((m: unknown) => calls.push({ name: "eventSink", arg: m }));
338
- const handler = createCommandHandler(pi as any, "s1", { abort, eventSink });
339
-
340
- await handler.handle({ type: "abort", sessionId: "s1" } as ServerToExtensionMessage);
341
-
342
- expect(abort).toHaveBeenCalledOnce();
343
- expect(eventSink).toHaveBeenCalledOnce();
344
- // Order: abort() first, then synthesized event
345
- expect(calls[0]!.name).toBe("abort");
346
- expect(calls[1]!.name).toBe("eventSink");
347
- const evt = (calls[1]!.arg as any);
348
- expect(evt.type).toBe("event_forward");
349
- expect(evt.sessionId).toBe("s1");
350
- expect(evt.event.eventType).toBe("auto_retry_end");
351
- expect(evt.event.data).toEqual({ success: false, attempt: -1 });
352
- expect(evt.event.data.finalError).toBeUndefined();
353
- expect(typeof evt.event.timestamp).toBe("number");
354
- });
355
-
356
- it("should handle request_commands message", async () => {
357
- const pi = createMockPi();
358
- const handler = createCommandHandler(pi as any, "s1");
359
-
360
- const msg: ServerToExtensionMessage = {
361
- type: "request_commands",
362
- sessionId: "s1",
363
- };
364
-
365
- const result = await handler.handle(msg);
366
- expect(pi.getCommands).toHaveBeenCalled();
367
- expect(result).toBeDefined();
368
- expect(result?.type).toBe("commands_list");
369
- });
370
-
371
- it("should send flows_list via eventSink on request_commands", async () => {
372
- const pi = createMockPi();
373
- (pi as any).events = {
374
- emit: vi.fn((event: string, probe: any) => {
375
- if (event === "flow:list-flows") {
376
- probe.flows = [{ name: "my-flow", description: "A flow", taskRequired: false }];
377
- }
378
- }),
379
- };
380
- const eventSink = vi.fn();
381
- const handler = createCommandHandler(pi as any, "s1", { eventSink });
382
-
383
- await handler.handle({ type: "request_commands", sessionId: "s1" });
384
- expect(eventSink).toHaveBeenCalledWith({
385
- type: "flows_list",
386
- sessionId: "s1",
387
- flows: [{ name: "my-flow", description: "A flow", taskRequired: false }],
388
- });
389
- });
390
-
391
- it("should send empty flows_list when pi-flows is not installed", async () => {
392
- const pi = createMockPi();
393
- // No events property — pi-flows not installed
394
- const eventSink = vi.fn();
395
- const handler = createCommandHandler(pi as any, "s1", { eventSink });
396
-
397
- await handler.handle({ type: "request_commands", sessionId: "s1" });
398
- expect(eventSink).toHaveBeenCalledWith({
399
- type: "flows_list",
400
- sessionId: "s1",
401
- flows: [],
402
- });
403
- });
404
-
405
- it("should filter hidden commands (starting with __) from commands list", async () => {
406
- const pi = createMockPi();
407
- pi.getCommands.mockReturnValue([
408
- { name: "test", description: "Test cmd", source: "extension" as const },
409
- { name: "__dashboard", source: "extension" as const },
410
- { name: "__internal", source: "extension" as const },
411
- { name: "review", description: "Review", source: "prompt" as const },
412
- ]);
413
- const handler = createCommandHandler(pi as any, "s1");
414
-
415
- const result = await handler.handle({ type: "request_commands", sessionId: "s1" });
416
- expect(result?.type).toBe("commands_list");
417
- const commands = (result as any).commands;
418
- expect(commands).toHaveLength(2);
419
- expect(commands.map((c: any) => c.name)).toEqual(["test", "review"]);
420
- });
421
-
422
- it("should handle list_sessions gracefully when SessionManager is unavailable", async () => {
423
- const pi = createMockPi();
424
- const handler = createCommandHandler(pi as any, "s1");
425
-
426
- const result = await handler.handle({
427
- type: "list_sessions",
428
- sessionId: "s1",
429
- cwd: "/some/path",
430
- } as any);
431
-
432
- // Should return empty array on import failure
433
- expect(result).toBeDefined();
434
- expect(result!.type).toBe("sessions_list");
435
- expect((result as any).sessions).toEqual([]);
436
- });
437
-
438
- it("should use sessionId getter for dynamic session ID", async () => {
439
- const pi = createMockPi();
440
- let currentId = "s1";
441
- const handler = createCommandHandler(pi as any, () => currentId);
442
-
443
- // Message for s1 should work
444
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "hello" });
445
- expect(pi.sendUserMessage).toHaveBeenCalledWith("hello", { deliverAs: "followUp" });
446
-
447
- pi.sendUserMessage.mockClear();
448
-
449
- // Change the session ID
450
- currentId = "s2";
451
-
452
- // Now message for s1 should be ignored
453
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "ignored" });
454
- expect(pi.sendUserMessage).not.toHaveBeenCalled();
455
-
456
- // And message for s2 should work
457
- await handler.handle({ type: "send_prompt", sessionId: "s2", text: "accepted" });
458
- expect(pi.sendUserMessage).toHaveBeenCalledWith("accepted", { deliverAs: "followUp" });
459
- });
460
-
461
- describe("command routing", () => {
462
- it("should route !!command as silent bash execution", async () => {
463
- const pi = createMockPi();
464
- const exec = vi.fn().mockResolvedValue({ stdout: "output", stderr: "", exitCode: 0 });
465
- (pi as any).exec = exec;
466
- const eventSink = vi.fn();
467
- const handler = createCommandHandler(pi as any, "s1", { eventSink });
468
-
469
- registryMock.bash = { ok: true, path: "/usr/bin/bash" };
470
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "!!ls -la" });
471
-
472
- // Spawns the registry-resolved absolute path, not the literal "sh".
473
- expect(exec).toHaveBeenCalledWith("/usr/bin/bash", ["-c", "ls -la"], expect.objectContaining({ timeout: 30000 }));
474
- expect(pi.sendUserMessage).not.toHaveBeenCalled();
475
- expect(eventSink).toHaveBeenCalledWith(expect.objectContaining({
476
- type: "event_forward",
477
- event: expect.objectContaining({
478
- eventType: "bash_output",
479
- data: expect.objectContaining({ command: "ls -la", excludeFromContext: true }),
480
- }),
481
- }));
482
- });
483
-
484
- it("should route !command as bash execution + LLM send", async () => {
485
- const pi = createMockPi();
486
- const exec = vi.fn().mockResolvedValue({ stdout: "file.txt", stderr: "", exitCode: 0 });
487
- (pi as any).exec = exec;
488
- const eventSink = vi.fn();
489
- const handler = createCommandHandler(pi as any, "s1", { eventSink });
490
-
491
- registryMock.bash = { ok: true, path: "/usr/bin/bash" };
492
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "!ls" });
493
-
494
- expect(exec).toHaveBeenCalledWith("/usr/bin/bash", ["-c", "ls"], expect.objectContaining({ timeout: 30000 }));
495
- expect(pi.sendUserMessage).toHaveBeenCalled();
496
- expect(eventSink).toHaveBeenCalledWith(expect.objectContaining({
497
- type: "event_forward",
498
- event: expect.objectContaining({
499
- eventType: "bash_output",
500
- data: expect.objectContaining({ command: "ls", excludeFromContext: false }),
501
- }),
502
- }));
503
- });
504
-
505
- it("emits a MissingToolError and never spawns when bash is unresolved", async () => {
506
- // See change: register-bash-and-tool-install-help (task 3.4).
507
- registryMock.bash = { ok: false, path: null };
508
- const pi = createMockPi();
509
- const exec = vi.fn();
510
- (pi as any).exec = exec;
511
- const eventSink = vi.fn();
512
- const handler = createCommandHandler(pi as any, "s1", { eventSink });
513
-
514
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "!ls" });
515
-
516
- // Never attempts a spawn, never sends to the LLM.
517
- expect(exec).not.toHaveBeenCalled();
518
- expect(pi.sendUserMessage).not.toHaveBeenCalled();
519
- // Emits exactly one bash_output event carrying the missing-tool payload.
520
- const bashEvents = eventSink.mock.calls
521
- .map((c) => c[0] as any)
522
- .filter((m) => m?.event?.eventType === "bash_output");
523
- expect(bashEvents).toHaveLength(1);
524
- expect(bashEvents[0].event.data.missingTool).toEqual({ kind: "missing-tool", toolName: "bash" });
525
- registryMock.bash = { ok: true, path: "/usr/bin/bash" }; // reset
526
- });
527
-
528
- it("should fall through for empty bang commands", async () => {
529
- const pi = createMockPi();
530
- const handler = createCommandHandler(pi as any, "s1");
531
-
532
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "!" });
533
- expect(pi.sendUserMessage).toHaveBeenCalledWith("!", { deliverAs: "followUp" });
534
-
535
- pi.sendUserMessage.mockClear();
536
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "!!" });
537
- expect(pi.sendUserMessage).toHaveBeenCalledWith("!!", { deliverAs: "followUp" });
538
- });
539
-
540
- it("should route /compact to ctx.compact()", async () => {
541
- const pi = createMockPi();
542
- const compact = vi.fn();
543
- const eventSink = vi.fn();
544
- const handler = createCommandHandler(pi as any, "s1", { compact, eventSink });
545
-
546
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "/compact" });
547
-
548
- expect(compact).toHaveBeenCalledWith({});
549
- expect(pi.sendUserMessage).not.toHaveBeenCalled();
550
- expect(eventSink).toHaveBeenCalledWith(expect.objectContaining({
551
- type: "event_forward",
552
- event: expect.objectContaining({
553
- eventType: "command_feedback",
554
- data: expect.objectContaining({ command: "/compact", status: "started" }),
555
- }),
556
- }));
557
- });
558
-
559
- it("should route /compact with custom instructions", async () => {
560
- const pi = createMockPi();
561
- const compact = vi.fn();
562
- const eventSink = vi.fn();
563
- const handler = createCommandHandler(pi as any, "s1", { compact, eventSink });
564
-
565
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "/compact summarize only code" });
566
-
567
- expect(compact).toHaveBeenCalledWith({ customInstructions: "summarize only code" });
568
- });
569
-
570
- it("should send error feedback when compact fails", async () => {
571
- const pi = createMockPi();
572
- const compact = vi.fn().mockImplementation(() => { throw new Error("Already compacted"); });
573
- const eventSink = vi.fn();
574
- const handler = createCommandHandler(pi as any, "s1", { compact, eventSink });
575
-
576
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "/compact" });
577
-
578
- expect(eventSink).toHaveBeenCalledWith(expect.objectContaining({
579
- type: "event_forward",
580
- event: expect.objectContaining({
581
- eventType: "command_feedback",
582
- data: expect.objectContaining({ command: "/compact", status: "error", message: "Already compacted" }),
583
- }),
584
- }));
585
- });
586
-
587
- it("should route /slash commands through sessionPrompt when available", async () => {
588
- const pi = createMockPi();
589
- const sessionPrompt = vi.fn();
590
- const handler = createCommandHandler(pi as any, "s1", { sessionPrompt });
591
-
592
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "/some-command args" });
593
-
594
- expect(sessionPrompt).toHaveBeenCalledWith("/some-command args", undefined);
595
- expect(pi.sendUserMessage).not.toHaveBeenCalled();
596
- });
597
-
598
- it("should emit command_feedback for slash commands", async () => {
599
- const pi = createMockPi();
600
- const sessionPrompt = vi.fn();
601
- const eventSink = vi.fn();
602
- const handler = createCommandHandler(pi as any, "s1", { sessionPrompt, eventSink });
603
-
604
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "/reload" });
605
-
606
- expect(eventSink).toHaveBeenCalledWith(expect.objectContaining({
607
- type: "event_forward",
608
- event: expect.objectContaining({
609
- eventType: "command_feedback",
610
- data: expect.objectContaining({ command: "/reload", status: "completed" }),
611
- }),
612
- }));
613
- });
614
-
615
- it("should NOT emit command_feedback for unrecognized slash commands (no sessionPrompt)", async () => {
616
- // Per fix-extension-slash-commands-in-dashboard, unrecognized slashes
617
- // (not extension commands, not bridge-handled) fall through to
618
- // sendUserMessage with NO command_feedback events. Only registered
619
- // extension commands emit started/{completed,error}.
620
- const pi = createMockPi();
621
- const eventSink = vi.fn();
622
- const handler = createCommandHandler(pi as any, "s1", { eventSink });
623
-
624
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "/some-command" });
625
-
626
- // Slash fallback forwards delivery (default 'followUp'). See change: add-steering-message.
627
- expect(pi.sendUserMessage).toHaveBeenCalledWith("/some-command", { deliverAs: "followUp" });
628
- const feedbackCalls = eventSink.mock.calls.filter(
629
- (c) => (c[0] as any)?.event?.eventType === "command_feedback",
630
- );
631
- expect(feedbackCalls).toHaveLength(0);
632
- });
633
-
634
- it("should fallback to sendUserMessage when sessionPrompt is not available for slash commands", async () => {
635
- const pi = createMockPi();
636
- const handler = createCommandHandler(pi as any, "s1");
637
-
638
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "/some-command args" });
639
-
640
- expect(pi.sendUserMessage).toHaveBeenCalledWith("/some-command args", { deliverAs: "followUp" });
641
- });
642
-
643
- it("should route /quit to shutdown", async () => {
644
- const pi = createMockPi();
645
- const shutdown = vi.fn();
646
- const handler = createCommandHandler(pi as any, "s1", { shutdown });
647
-
648
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "/quit" });
649
-
650
- expect(shutdown).toHaveBeenCalled();
651
- expect(pi.sendUserMessage).not.toHaveBeenCalled();
652
- });
653
-
654
- it("should route /exit to shutdown", async () => {
655
- const pi = createMockPi();
656
- const shutdown = vi.fn();
657
- const handler = createCommandHandler(pi as any, "s1", { shutdown });
658
-
659
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "/exit" });
660
-
661
- expect(shutdown).toHaveBeenCalled();
662
- expect(pi.sendUserMessage).not.toHaveBeenCalled();
663
- });
664
-
665
- it("should route /reload to reload callback", async () => {
666
- const pi = createMockPi();
667
- const reload = vi.fn();
668
- const eventSink = vi.fn();
669
- const handler = createCommandHandler(pi as any, "s1", { reload, eventSink });
670
-
671
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "/reload" });
672
-
673
- expect(reload).toHaveBeenCalled();
674
- expect(pi.sendUserMessage).not.toHaveBeenCalled();
675
- expect(eventSink).toHaveBeenCalledWith(expect.objectContaining({
676
- type: "event_forward",
677
- event: expect.objectContaining({
678
- eventType: "command_feedback",
679
- data: expect.objectContaining({ command: "/reload", status: "completed" }),
680
- }),
681
- }));
682
- });
683
-
684
- it("should not crash when /reload called without option", async () => {
685
- const pi = createMockPi();
686
- const handler = createCommandHandler(pi as any, "s1");
687
-
688
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "/reload" });
689
- expect(pi.sendUserMessage).not.toHaveBeenCalled();
690
- });
691
-
692
- it("should route /new to spawnNew callback", async () => {
693
- const pi = createMockPi();
694
- const spawnNew = vi.fn();
695
- const eventSink = vi.fn();
696
- const handler = createCommandHandler(pi as any, "s1", { spawnNew, eventSink });
697
-
698
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "/new" });
699
-
700
- expect(spawnNew).toHaveBeenCalled();
701
- expect(pi.sendUserMessage).not.toHaveBeenCalled();
702
- expect(eventSink).toHaveBeenCalledWith(expect.objectContaining({
703
- type: "event_forward",
704
- event: expect.objectContaining({
705
- eventType: "command_feedback",
706
- data: expect.objectContaining({ command: "/new", status: "completed" }),
707
- }),
708
- }));
709
- });
710
-
711
- it("should pass plain text through to sendUserMessage", async () => {
712
- const pi = createMockPi();
713
- const handler = createCommandHandler(pi as any, "s1");
714
-
715
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "explain this code" });
716
-
717
- expect(pi.sendUserMessage).toHaveBeenCalledWith("explain this code", { deliverAs: "followUp" });
718
- });
719
-
720
- it("should handle bash execution with non-zero exit code", async () => {
721
- const pi = createMockPi();
722
- const exec = vi.fn().mockResolvedValue({ stdout: "", stderr: "not found", exitCode: 127 });
723
- (pi as any).exec = exec;
724
- const eventSink = vi.fn();
725
- const handler = createCommandHandler(pi as any, "s1", { eventSink });
726
-
727
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "!!badcmd" });
728
-
729
- expect(eventSink).toHaveBeenCalledWith(expect.objectContaining({
730
- type: "event_forward",
731
- event: expect.objectContaining({
732
- eventType: "bash_output",
733
- data: expect.objectContaining({ exitCode: 127, output: "not found" }),
734
- }),
735
- }));
736
- });
737
- });
738
-
739
- describe("set_model", () => {
740
- it("should call setModel with provider and modelId", async () => {
741
- const pi = createMockPi();
742
- const setModel = vi.fn().mockResolvedValue(undefined);
743
- const handler = createCommandHandler(pi as any, "s1", { setModel });
744
-
745
- await handler.handle({
746
- type: "set_model",
747
- sessionId: "s1",
748
- provider: "anthropic",
749
- modelId: "claude-sonnet-4-20250514",
750
- } as ServerToExtensionMessage);
751
-
752
- expect(setModel).toHaveBeenCalledWith("anthropic", "claude-sonnet-4-20250514");
753
- });
754
-
755
- it("should not throw when setModel option is not provided", async () => {
756
- const pi = createMockPi();
757
- const handler = createCommandHandler(pi as any, "s1");
758
-
759
- await expect(handler.handle({
760
- type: "set_model",
761
- sessionId: "s1",
762
- provider: "anthropic",
763
- modelId: "unknown-model",
764
- } as ServerToExtensionMessage)).resolves.toBeUndefined();
765
- });
766
-
767
- it("should route /model slash command through setModel callback", async () => {
768
- const pi = createMockPi();
769
- const setModel = vi.fn().mockResolvedValue(undefined);
770
- const eventSink = vi.fn();
771
- const handler = createCommandHandler(pi as any, "s1", { setModel, eventSink });
772
-
773
- await handler.handle({
774
- type: "send_prompt",
775
- sessionId: "s1",
776
- text: "/model anthropic/claude-haiku-4-5",
777
- });
778
-
779
- expect(setModel).toHaveBeenCalledWith("anthropic", "claude-haiku-4-5");
780
- expect(pi.sendUserMessage).not.toHaveBeenCalled();
781
- expect(eventSink).toHaveBeenCalledWith(expect.objectContaining({
782
- type: "event_forward",
783
- event: expect.objectContaining({
784
- eventType: "command_feedback",
785
- data: expect.objectContaining({ command: "/model anthropic/claude-haiku-4-5", status: "completed" }),
786
- }),
787
- }));
788
- });
789
- });
790
- });
791
-
792
- describe("parseSendPrompt", () => {
793
- it("should detect !! prefix (silent bash)", () => {
794
- const result = parseSendPrompt("!!ls -la");
795
- expect(result).toEqual({ type: "bash", command: "ls -la", excludeFromContext: true });
796
- });
797
-
798
- it("should detect ! prefix (bash with LLM)", () => {
799
- const result = parseSendPrompt("!git status");
800
- expect(result).toEqual({ type: "bash", command: "git status", excludeFromContext: false });
801
- });
802
-
803
- it("should return passthrough for empty !! ", () => {
804
- const result = parseSendPrompt("!!");
805
- expect(result).toEqual({ type: "passthrough", text: "!!" });
806
- });
807
-
808
- it("should return passthrough for empty !", () => {
809
- const result = parseSendPrompt("!");
810
- expect(result).toEqual({ type: "passthrough", text: "!" });
811
- });
812
-
813
- it("should detect /compact without args", () => {
814
- const result = parseSendPrompt("/compact");
815
- expect(result).toEqual({ type: "compact", customInstructions: undefined });
816
- });
817
-
818
- it("should detect /compact with args", () => {
819
- const result = parseSendPrompt("/compact focus on code changes");
820
- expect(result).toEqual({ type: "compact", customInstructions: "focus on code changes" });
821
- });
822
-
823
- it("should detect generic slash commands", () => {
824
- const result = parseSendPrompt("/some-command arg1 arg2");
825
- expect(result).toEqual({ type: "slash", text: "/some-command arg1 arg2" });
826
- });
827
-
828
- it("should return passthrough for plain text", () => {
829
- const result = parseSendPrompt("explain this code");
830
- expect(result).toEqual({ type: "passthrough", text: "explain this code" });
831
- });
832
-
833
- it("should return passthrough for text with / in the middle", () => {
834
- const result = parseSendPrompt("look at src/index.ts");
835
- expect(result).toEqual({ type: "passthrough", text: "look at src/index.ts" });
836
- });
837
-
838
- it("should trim bang command text", () => {
839
- const result = parseSendPrompt("!! ls -la ");
840
- expect(result).toEqual({ type: "bash", command: "ls -la", excludeFromContext: true });
841
- });
842
-
843
- it("should return passthrough for !! with only whitespace after", () => {
844
- const result = parseSendPrompt("!! ");
845
- expect(result).toEqual({ type: "passthrough", text: "!! " });
846
- });
847
-
848
- it("should detect /quit as shutdown", () => {
849
- expect(parseSendPrompt("/quit")).toEqual({ type: "shutdown" });
850
- });
851
-
852
- it("should detect /exit as shutdown", () => {
853
- expect(parseSendPrompt("/exit")).toEqual({ type: "shutdown" });
854
- });
855
-
856
- it("should detect /reload as reload", () => {
857
- expect(parseSendPrompt("/reload")).toEqual({ type: "reload" });
858
- });
859
-
860
- it("should detect /new as new", () => {
861
- expect(parseSendPrompt("/new")).toEqual({ type: "new" });
862
- });
863
-
864
- it("should detect /model provider/id as model command", () => {
865
- expect(parseSendPrompt("/model anthropic/claude-haiku-4-5")).toEqual({
866
- type: "model",
867
- provider: "anthropic",
868
- modelId: "claude-haiku-4-5",
869
- });
870
- });
871
-
872
- it("should treat /model without slash in arg as generic slash", () => {
873
- expect(parseSendPrompt("/model something")).toEqual({ type: "slash", text: "/model something" });
874
- });
875
-
876
- it("should treat bare /model as generic slash", () => {
877
- expect(parseSendPrompt("/model")).toEqual({ type: "slash", text: "/model" });
878
- });
879
-
880
- it("should detect /flows:new as generic slash (routed by bridge sessionPrompt)", () => {
881
- expect(parseSendPrompt("/flows:new create a test flow")).toEqual({
882
- type: "slash",
883
- text: "/flows:new create a test flow",
884
- });
885
- });
886
-
887
- it("should detect /flows:delete as generic slash (routed by session.prompt)", () => {
888
- expect(parseSendPrompt("/flows:delete my-flow")).toEqual({
889
- type: "slash",
890
- text: "/flows:delete my-flow",
891
- });
892
- });
893
- });
894
-
895
- describe("CommandHandler delivery routing (pi-native queues)", () => {
896
- // After change: honest-mid-turn-queue-surface, the bridge appends to pi's
897
- // queues via pi.sendUserMessage{deliverAs} only. clear*Queue stubs remain
898
- // on the mock so we can assert they are NEVER called (negative assertion
899
- // locking in the absence). Pi's real ExtensionAPI exposes no clear*Queue
900
- // method; the stubs here model the policy, not the surface.
901
- function createMockPi() {
902
- return {
903
- sendUserMessage: vi.fn(),
904
- getCommands: vi.fn().mockReturnValue([]),
905
- setSessionName: vi.fn(),
906
- getSessionName: vi.fn(),
907
- on: vi.fn(),
908
- exec: vi.fn(),
909
- clearFollowUpQueue: vi.fn(),
910
- clearSteeringQueue: vi.fn(),
911
- };
912
- }
913
-
914
- it("passthrough followUp on IDLE session forwards to pi (no buffer)", async () => {
915
- // Idle path (default when isStreaming option absent): pi sees the
916
- // message; the bridge buffer is bypassed entirely.
917
- // See change: rework-mid-turn-prompt-queue (design.md D1).
918
- const pi = createMockPi();
919
- const onFollowupSent = vi.fn();
920
- const handler = createCommandHandler(pi as any, "s1", { onFollowupSent });
921
-
922
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "after done", delivery: "followUp" });
923
-
924
- expect(pi.clearFollowUpQueue).not.toHaveBeenCalled();
925
- expect(pi.sendUserMessage).toHaveBeenCalledWith("after done", { deliverAs: "followUp" });
926
- expect(onFollowupSent).not.toHaveBeenCalled(); // buffer untouched on idle path
927
- });
928
-
929
- it("passthrough followUp while STREAMING buffers in bridge and skips pi.sendUserMessage", async () => {
930
- // Streaming path: the bridge owns the follow-up buffer; pi never sees
931
- // the entry until the drain loop ships it on agent_end as a fresh turn.
932
- // See change: rework-mid-turn-prompt-queue (design.md D1).
933
- const pi = createMockPi();
934
- const onFollowupSent = vi.fn();
935
- const handler = createCommandHandler(pi as any, "s1", {
936
- isStreaming: () => true,
937
- onFollowupSent,
938
- });
939
-
940
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "buffered", delivery: "followUp" });
941
-
942
- // CRITICAL: pi.sendUserMessage MUST NOT be called for the streaming
943
- // follow-up path — the entry lives only in the bridge buffer.
944
- expect(pi.sendUserMessage).not.toHaveBeenCalled();
945
- expect(pi.clearFollowUpQueue).not.toHaveBeenCalled();
946
- expect(pi.clearSteeringQueue).not.toHaveBeenCalled();
947
- // onFollowupSent (→ bufferFollowupSend) IS called so the bridge can push
948
- // the text to bridgeFollowUp + emit queue_update.
949
- expect(onFollowupSent).toHaveBeenCalledWith("buffered");
950
- });
951
-
952
- it("passthrough delivery absent defaults to followUp (idle path forwards to pi)", async () => {
953
- const pi = createMockPi();
954
- const handler = createCommandHandler(pi as any, "s1");
955
-
956
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "plain" });
957
-
958
- expect(pi.clearFollowUpQueue).not.toHaveBeenCalled();
959
- expect(pi.sendUserMessage).toHaveBeenCalledWith("plain", { deliverAs: "followUp" });
960
- });
961
-
962
- it("passthrough delivery steer does NOT call clearFollowUpQueue or clearSteeringQueue", async () => {
963
- const pi = createMockPi();
964
- const handler = createCommandHandler(pi as any, "s1");
965
-
966
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "focus on X", delivery: "steer" });
967
-
968
- expect(pi.clearFollowUpQueue).not.toHaveBeenCalled();
969
- expect(pi.clearSteeringQueue).not.toHaveBeenCalled();
970
- expect(pi.sendUserMessage).toHaveBeenCalledWith("focus on X", { deliverAs: "steer" });
971
- });
972
-
973
- it("passthrough with images preserves image content (v2: no pre-clear)", async () => {
974
- const pi = createMockPi();
975
- const images = [{ type: "image" as const, data: "AAA", mimeType: "image/png" }];
976
- const handler = createCommandHandler(pi as any, "s1");
977
-
978
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "img", images, delivery: "followUp" });
979
-
980
- expect(pi.clearFollowUpQueue).not.toHaveBeenCalled();
981
- expect(pi.sendUserMessage).toHaveBeenCalledTimes(1);
982
- const [content, opts] = pi.sendUserMessage.mock.calls[0];
983
- expect(opts).toEqual({ deliverAs: "followUp" });
984
- expect(Array.isArray(content)).toBe(true);
985
- });
986
-
987
- it("bash commands bypass delivery routing entirely (no clearFollowUpQueue call)", async () => {
988
- const pi = createMockPi();
989
- pi.exec = vi.fn().mockResolvedValue({ stdout: "hi", stderr: "", exitCode: 0 });
990
- const handler = createCommandHandler(pi as any, "s1");
991
-
992
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "!ls" });
993
-
994
- // Bash handler forwards stdout via sendUserMessage as its result, but
995
- // delivery routing is not involved — no clearFollowUpQueue or deliverAs option.
996
- expect(pi.clearFollowUpQueue).not.toHaveBeenCalled();
997
- expect(pi.clearSteeringQueue).not.toHaveBeenCalled();
998
- });
999
-
1000
- it("slash command with delivery=steer passes delivery to sessionPrompt; no pi call from handler", async () => {
1001
- const pi = createMockPi();
1002
- const sessionPrompt = vi.fn();
1003
- const handler = createCommandHandler(pi as any, "s1", { sessionPrompt });
1004
-
1005
- await handler.handle({ type: "send_prompt", sessionId: "s1", text: "/some-command args", delivery: "steer" });
1006
-
1007
- expect(sessionPrompt).toHaveBeenCalledWith("/some-command args", "steer");
1008
- expect(pi.sendUserMessage).not.toHaveBeenCalled();
1009
- });
1010
-
1011
- it("abort no longer requires clearQueueOnAbort option", async () => {
1012
- const pi = createMockPi();
1013
- const abort = vi.fn();
1014
- const handler = createCommandHandler(pi as any, "s1", { abort });
1015
-
1016
- await handler.handle({ type: "abort", sessionId: "s1" });
1017
-
1018
- expect(abort).toHaveBeenCalledTimes(1);
1019
- });
1020
-
1021
- // attach_proposal_changed → onAttachProposalChanged mirror (task 3.4).
1022
- // See change: inject-session-context-into-agent.
1023
- describe("attach_proposal_changed", () => {
1024
- it("matching sessionId → calls onAttachProposalChanged with the value", async () => {
1025
- const pi = createMockPi();
1026
- const onAttachProposalChanged = vi.fn();
1027
- const handler = createCommandHandler(pi as any, "s1", { onAttachProposalChanged });
1028
-
1029
- await handler.handle({ type: "attach_proposal_changed", sessionId: "s1", attachedChange: "X" });
1030
-
1031
- expect(onAttachProposalChanged).toHaveBeenCalledWith("X");
1032
- });
1033
-
1034
- it("null payload → clears (calls with null)", async () => {
1035
- const pi = createMockPi();
1036
- const onAttachProposalChanged = vi.fn();
1037
- const handler = createCommandHandler(pi as any, "s1", { onAttachProposalChanged });
1038
-
1039
- await handler.handle({ type: "attach_proposal_changed", sessionId: "s1", attachedChange: null });
1040
-
1041
- expect(onAttachProposalChanged).toHaveBeenCalledWith(null);
1042
- });
1043
-
1044
- it("mismatched sessionId → dropped by the guard, callback untouched", async () => {
1045
- const pi = createMockPi();
1046
- const onAttachProposalChanged = vi.fn();
1047
- const handler = createCommandHandler(pi as any, "s1", { onAttachProposalChanged });
1048
-
1049
- await handler.handle({ type: "attach_proposal_changed", sessionId: "s2", attachedChange: "X" });
1050
-
1051
- expect(onAttachProposalChanged).not.toHaveBeenCalled();
1052
- });
1053
-
1054
- it("malformed attachedChange (non-string, non-null) → dropped, callback untouched", async () => {
1055
- const pi = createMockPi();
1056
- const onAttachProposalChanged = vi.fn();
1057
- const handler = createCommandHandler(pi as any, "s1", { onAttachProposalChanged });
1058
-
1059
- await handler.handle({ type: "attach_proposal_changed", sessionId: "s1", attachedChange: 123 as any });
1060
-
1061
- expect(onAttachProposalChanged).not.toHaveBeenCalled();
1062
- });
1063
- });
1064
- });
1065
-
1066
- describe("tryExecSlashTemplate (executable: bash slash pipeline)", () => {
1067
- const tmpDir = join(import.meta.dirname ?? __dirname, "__tmp_exec_slash__");
1068
- const promptsDir = join(tmpDir, ".pi", "prompts");
1069
-
1070
- function mockPi() {
1071
- return {
1072
- sendUserMessage: vi.fn(),
1073
- getCommands: vi.fn().mockReturnValue([]),
1074
- exec: vi.fn().mockResolvedValue({ stdout: "OK", stderr: "", exitCode: 0 }),
1075
- };
1076
- }
1077
-
1078
- beforeEach(() => {
1079
- mkdirSync(promptsDir, { recursive: true });
1080
- registryMock.bash = { ok: true, path: "/usr/bin/bash" };
1081
- });
1082
- afterEach(() => rmSync(tmpDir, { recursive: true, force: true }));
1083
-
1084
- it("runs an exec template as bash, emits bash_output with source slash-exec, no LLM", async () => {
1085
- writeFileSync(join(promptsDir, "dash-health.md"), "---\nexecutable: bash\n---\necho hi");
1086
- const pi = mockPi();
1087
- const eventSink = vi.fn();
1088
-
1089
- const ran = await tryExecSlashTemplate(pi as any, "/dash-health", tmpDir, "s1", eventSink);
1090
-
1091
- expect(ran).toBe(true);
1092
- expect(pi.sendUserMessage).not.toHaveBeenCalled();
1093
- expect(eventSink).toHaveBeenCalledWith(expect.objectContaining({
1094
- type: "event_forward",
1095
- event: expect.objectContaining({
1096
- eventType: "bash_output",
1097
- data: expect.objectContaining({ source: "slash-exec", excludeFromContext: true }),
1098
- }),
1099
- }));
1100
- });
1101
-
1102
- it("excludeFromContext: false also sends to the LLM (mirrors ! semantics)", async () => {
1103
- writeFileSync(
1104
- join(promptsDir, "dash-capture.md"),
1105
- "---\nexecutable: bash\nexcludeFromContext: false\n---\necho hi",
1106
- );
1107
- const pi = mockPi();
1108
- const eventSink = vi.fn();
1109
-
1110
- const ran = await tryExecSlashTemplate(pi as any, "/dash-capture", tmpDir, "s1", eventSink);
1111
-
1112
- expect(ran).toBe(true);
1113
- expect(eventSink).toHaveBeenCalled();
1114
- expect(pi.sendUserMessage).toHaveBeenCalled();
1115
- });
1116
-
1117
- it("passes positional args after -- so $1, $2 bind in the body", async () => {
1118
- writeFileSync(join(promptsDir, "dash-info.md"), '---\nexecutable: bash\n---\necho "$1 $2"');
1119
- const pi = mockPi();
1120
-
1121
- await tryExecSlashTemplate(pi as any, "/dash-info abc 123", tmpDir, "s1", vi.fn());
1122
-
1123
- const argv = pi.exec.mock.calls[0]![1] as string[];
1124
- expect(argv.slice(-3)).toEqual(["--", "abc", "123"]);
1125
- });
1126
-
1127
- it("injects PI_DASHBOARD_PORT / PI_DASHBOARD_BASE into the script", async () => {
1128
- writeFileSync(join(promptsDir, "dash-env.md"), "---\nexecutable: bash\n---\necho hi");
1129
- const pi = mockPi();
1130
-
1131
- await tryExecSlashTemplate(pi as any, "/dash-env", tmpDir, "s1", vi.fn());
1132
-
1133
- const script = (pi.exec.mock.calls[0]![1] as string[])[1];
1134
- expect(script).toContain("export PI_DASHBOARD_PORT=");
1135
- expect(script).toContain("export PI_DASHBOARD_BASE=");
1136
- });
1137
-
1138
- it("returns false for a non-exec (LLM) template, no bash_output", async () => {
1139
- writeFileSync(join(promptsDir, "dash-llm.md"), "Just instructions for the LLM");
1140
- const pi = mockPi();
1141
- const eventSink = vi.fn();
1142
-
1143
- const ran = await tryExecSlashTemplate(pi as any, "/dash-llm", tmpDir, "s1", eventSink);
1144
-
1145
- expect(ran).toBe(false);
1146
- expect(pi.exec).not.toHaveBeenCalled();
1147
- expect(eventSink).not.toHaveBeenCalled();
1148
- });
1149
- });
1150
-
1151
- describe("buildDashboardExecEnv port resolution", () => {
1152
- const saved = { pi: process.env.PI_DASHBOARD_PORT, dash: process.env.DASHBOARD_PORT };
1153
- afterEach(() => {
1154
- if (saved.pi === undefined) delete process.env.PI_DASHBOARD_PORT;
1155
- else process.env.PI_DASHBOARD_PORT = saved.pi;
1156
- if (saved.dash === undefined) delete process.env.DASHBOARD_PORT;
1157
- else process.env.DASHBOARD_PORT = saved.dash;
1158
- });
1159
-
1160
- it("prefers DASHBOARD_PORT env over config.json (Docker harness: config has no port)", () => {
1161
- delete process.env.PI_DASHBOARD_PORT;
1162
- process.env.DASHBOARD_PORT = "18000";
1163
- const env = buildDashboardExecEnv();
1164
- expect(env.PI_DASHBOARD_PORT).toBe("18000");
1165
- expect(env.PI_DASHBOARD_BASE).toBe("http://localhost:18000");
1166
- });
1167
-
1168
- it("PI_DASHBOARD_PORT takes precedence over DASHBOARD_PORT", () => {
1169
- process.env.PI_DASHBOARD_PORT = "9001";
1170
- process.env.DASHBOARD_PORT = "18000";
1171
- expect(buildDashboardExecEnv().PI_DASHBOARD_PORT).toBe("9001");
1172
- });
1173
-
1174
- it("falls back to 8000 when no env and no config port", () => {
1175
- delete process.env.PI_DASHBOARD_PORT;
1176
- delete process.env.DASHBOARD_PORT;
1177
- // Ephemeral HOME in tests has no ~/.pi/dashboard/config.json with a port.
1178
- expect(buildDashboardExecEnv().PI_DASHBOARD_PORT).toBe("8000");
1179
- });
1180
- });