@blackbelt-technology/pi-dashboard-extension 0.3.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 (57) hide show
  1. package/.pi/skills/pi-dashboard/SKILL.md +134 -0
  2. package/.pi/skills/pi-dashboard/references/api-reference.md +470 -0
  3. package/.pi/skills/pi-dashboard/references/recipes.md +252 -0
  4. package/.pi/skills/pi-dashboard/scripts/dashboard-api.sh +75 -0
  5. package/package.json +38 -0
  6. package/src/__tests__/ask-user-tool.test.ts +432 -0
  7. package/src/__tests__/command-handler.test.ts +712 -0
  8. package/src/__tests__/connection.test.ts +344 -0
  9. package/src/__tests__/credentials-updated.test.ts +26 -0
  10. package/src/__tests__/dashboard-default-adapter.test.ts +77 -0
  11. package/src/__tests__/dev-build.test.ts +79 -0
  12. package/src/__tests__/enrich-model-metadata.test.ts +201 -0
  13. package/src/__tests__/event-forwarder.test.ts +89 -0
  14. package/src/__tests__/fork-entryid-timing.test.ts +100 -0
  15. package/src/__tests__/git-info.test.ts +124 -0
  16. package/src/__tests__/git-link-builder.test.ts +102 -0
  17. package/src/__tests__/openspec-activity-detector.test.ts +232 -0
  18. package/src/__tests__/openspec-poller.test.ts +124 -0
  19. package/src/__tests__/process-metrics.test.ts +47 -0
  20. package/src/__tests__/process-scanner-kill.test.ts +61 -0
  21. package/src/__tests__/process-scanner.test.ts +202 -0
  22. package/src/__tests__/prompt-bus-wiring.test.ts +791 -0
  23. package/src/__tests__/prompt-bus.test.ts +469 -0
  24. package/src/__tests__/prompt-expander.test.ts +54 -0
  25. package/src/__tests__/provider-register-reload.test.ts +394 -0
  26. package/src/__tests__/server-auto-start.test.ts +258 -0
  27. package/src/__tests__/server-launcher.test.ts +61 -0
  28. package/src/__tests__/server-probe.test.ts +25 -0
  29. package/src/__tests__/session-switch.test.ts +139 -0
  30. package/src/__tests__/session-sync.test.ts +55 -0
  31. package/src/__tests__/source-detector.test.ts +73 -0
  32. package/src/__tests__/stats-extractor.test.ts +92 -0
  33. package/src/__tests__/tui-prompt-adapter.test.ts +207 -0
  34. package/src/__tests__/watchdog.test.ts +161 -0
  35. package/src/ask-user-tool.ts +352 -0
  36. package/src/bridge-context.ts +64 -0
  37. package/src/bridge.ts +1182 -0
  38. package/src/command-handler.ts +533 -0
  39. package/src/connection.ts +204 -0
  40. package/src/dashboard-default-adapter.ts +37 -0
  41. package/src/dev-build.ts +39 -0
  42. package/src/event-forwarder.ts +40 -0
  43. package/src/flow-event-wiring.ts +85 -0
  44. package/src/git-info.ts +55 -0
  45. package/src/git-link-builder.ts +112 -0
  46. package/src/model-tracker.ts +56 -0
  47. package/src/pi-env.d.ts +37 -0
  48. package/src/process-metrics.ts +70 -0
  49. package/src/process-scanner.ts +430 -0
  50. package/src/prompt-bus.ts +240 -0
  51. package/src/prompt-expander.ts +108 -0
  52. package/src/provider-register.ts +564 -0
  53. package/src/server-auto-start.ts +113 -0
  54. package/src/server-launcher.ts +126 -0
  55. package/src/server-probe.ts +33 -0
  56. package/src/session-sync.ts +155 -0
  57. package/src/source-detector.ts +26 -0
@@ -0,0 +1,61 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { resolveServerCliPath, buildSpawnArgs } from "../server-launcher.js";
3
+ import { existsSync } from "node:fs";
4
+ import path from "node:path";
5
+
6
+ describe("server-launcher", () => {
7
+ describe("resolveServerCliPath", () => {
8
+ it("should return an absolute path", () => {
9
+ expect(path.isAbsolute(resolveServerCliPath())).toBe(true);
10
+ });
11
+
12
+ it("should point to packages/server/src/cli.ts", () => {
13
+ const cliPath = resolveServerCliPath();
14
+ expect(cliPath).toContain(path.join("packages", "server", "src", "cli.ts"));
15
+ });
16
+
17
+ it("should point to a file that actually exists on disk", () => {
18
+ expect(existsSync(resolveServerCliPath())).toBe(true);
19
+ });
20
+
21
+ it("uses require.resolve so it adapts to installed layout", () => {
22
+ // Regression: the monorepo-relative path math
23
+ // (`<extension>/../../server/src/cli.ts`) produced
24
+ // `<scope>/server/src/cli.ts` instead of
25
+ // `<scope>/pi-dashboard-server/src/cli.ts` when the extension
26
+ // was installed into `node_modules/@blackbelt-technology/`. The
27
+ // resolver must locate the server via package name, not sibling
28
+ // path arithmetic.
29
+ const cliPath = resolveServerCliPath();
30
+ // Either layout is fine; we just must NOT produce the broken
31
+ // `@blackbelt-technology/server/src/cli.ts` shape.
32
+ expect(cliPath).not.toMatch(/@blackbelt-technology[\\/]+server[\\/]+src[\\/]+cli\.ts$/);
33
+ // And must land on pi-dashboard-server (installed) or packages/server (dev).
34
+ expect(cliPath).toMatch(/(pi-dashboard-server|packages[\\/]+server)[\\/]+src[\\/]+cli\.ts$/);
35
+ });
36
+ });
37
+
38
+ describe("buildSpawnArgs", () => {
39
+ it("should include port and pi-port flags", () => {
40
+ const args = buildSpawnArgs({
41
+ port: 3000,
42
+ piPort: 4000,
43
+ autoStart: true,
44
+ autoShutdown: true,
45
+ shutdownIdleSeconds: 300,
46
+ spawnStrategy: "tmux",
47
+ tunnel: { enabled: true },
48
+ devBuildOnReload: false,
49
+ memoryLimits: { maxEventsPerSession: 5000, maxStringFieldSize: 0, maxWsBufferBytes: 4194304 },
50
+ editor: { idleTimeoutMinutes: 10, maxInstances: 3 },
51
+ defaultModel: "",
52
+ trustedNetworks: [],
53
+ resolvedTrustedNetworks: [],
54
+ cors: { allowedOrigins: [] },
55
+ electronMode: false,
56
+ } as any);
57
+
58
+ expect(args).toEqual(["--port", "3000", "--pi-port", "4000"]);
59
+ });
60
+ });
61
+ });
@@ -0,0 +1,25 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { isPortOpen } from "../server-probe.js";
3
+ import net from "node:net";
4
+
5
+ describe("isPortOpen", () => {
6
+ it("should return true when a server is listening", async () => {
7
+ // Start a temporary server
8
+ const server = net.createServer();
9
+ await new Promise<void>((resolve) => server.listen(0, resolve));
10
+ const port = (server.address() as net.AddressInfo).port;
11
+
12
+ try {
13
+ const result = await isPortOpen(port);
14
+ expect(result).toBe(true);
15
+ } finally {
16
+ server.close();
17
+ }
18
+ });
19
+
20
+ it("should return false when no server is listening", async () => {
21
+ // Use a port that's almost certainly not in use
22
+ const result = await isPortOpen(59321);
23
+ expect(result).toBe(false);
24
+ });
25
+ });
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Tests for session switch/fork behavior in the bridge extension.
3
+ * These test the helper functions and logic used during session changes.
4
+ */
5
+ import { describe, it, expect } from "vitest";
6
+
7
+ // We test the extractFirstMessage logic inline since it's a local function in bridge.ts.
8
+ // Replicate the logic here to verify behavior.
9
+
10
+ function extractFirstMessage(ctx: any): string | undefined {
11
+ try {
12
+ const entries = ctx.sessionManager?.getEntries?.();
13
+ if (!entries || !Array.isArray(entries)) return undefined;
14
+ for (const entry of entries) {
15
+ if (entry.role === "user" && typeof entry.content === "string") {
16
+ return entry.content.slice(0, 200);
17
+ }
18
+ if (entry.role === "user" && Array.isArray(entry.content)) {
19
+ for (const part of entry.content) {
20
+ if (part.type === "text" && typeof part.text === "string") {
21
+ return part.text.slice(0, 200);
22
+ }
23
+ }
24
+ }
25
+ }
26
+ } catch { /* ignore */ }
27
+ return undefined;
28
+ }
29
+
30
+ describe("extractFirstMessage", () => {
31
+ it("should extract first user message as string content", () => {
32
+ const ctx = {
33
+ sessionManager: {
34
+ getEntries: () => [
35
+ { role: "system", content: "You are a helpful assistant" },
36
+ { role: "user", content: "Help me fix the auth module" },
37
+ { role: "assistant", content: "Sure, I'll help" },
38
+ ],
39
+ },
40
+ };
41
+ expect(extractFirstMessage(ctx)).toBe("Help me fix the auth module");
42
+ });
43
+
44
+ it("should extract first user message from array content", () => {
45
+ const ctx = {
46
+ sessionManager: {
47
+ getEntries: () => [
48
+ {
49
+ role: "user",
50
+ content: [
51
+ { type: "text", text: "Look at this image and fix the bug" },
52
+ { type: "image", data: "base64..." },
53
+ ],
54
+ },
55
+ ],
56
+ },
57
+ };
58
+ expect(extractFirstMessage(ctx)).toBe("Look at this image and fix the bug");
59
+ });
60
+
61
+ it("should truncate long messages to 200 chars", () => {
62
+ const longMessage = "a".repeat(300);
63
+ const ctx = {
64
+ sessionManager: {
65
+ getEntries: () => [{ role: "user", content: longMessage }],
66
+ },
67
+ };
68
+ expect(extractFirstMessage(ctx)).toBe("a".repeat(200));
69
+ });
70
+
71
+ it("should return undefined when no entries exist", () => {
72
+ const ctx = {
73
+ sessionManager: {
74
+ getEntries: () => [],
75
+ },
76
+ };
77
+ expect(extractFirstMessage(ctx)).toBeUndefined();
78
+ });
79
+
80
+ it("should return undefined when getEntries is not available", () => {
81
+ const ctx = { sessionManager: {} };
82
+ expect(extractFirstMessage(ctx)).toBeUndefined();
83
+ });
84
+
85
+ it("should return undefined when sessionManager is not available", () => {
86
+ expect(extractFirstMessage({})).toBeUndefined();
87
+ });
88
+
89
+ it("should handle errors gracefully", () => {
90
+ const ctx = {
91
+ sessionManager: {
92
+ getEntries: () => { throw new Error("fail"); },
93
+ },
94
+ };
95
+ expect(extractFirstMessage(ctx)).toBeUndefined();
96
+ });
97
+ });
98
+
99
+ describe("session switch flow", () => {
100
+ it("should produce unregister for old ID and register for new ID", () => {
101
+ // This tests the expected message sequence during a session switch.
102
+ // The actual bridge sends these messages; here we verify the logic.
103
+ const messages: any[] = [];
104
+ const send = (msg: any) => messages.push(msg);
105
+
106
+ const oldSessionId = "old-uuid";
107
+ let sessionId = oldSessionId;
108
+
109
+ // Simulate handleSessionChange
110
+ send({ type: "session_unregister", sessionId });
111
+
112
+ sessionId = "new-uuid"; // ctx.sessionManager.getSessionId() returns new ID
113
+
114
+ send({
115
+ type: "session_register",
116
+ sessionId,
117
+ cwd: "/project",
118
+ source: "tui",
119
+ });
120
+
121
+ expect(messages).toHaveLength(2);
122
+ expect(messages[0]).toEqual({ type: "session_unregister", sessionId: "old-uuid" });
123
+ expect(messages[1]).toMatchObject({ type: "session_register", sessionId: "new-uuid" });
124
+ });
125
+
126
+ it("should handle fork identically to switch", () => {
127
+ // Fork produces same message pattern: unregister old, register new
128
+ const messages: any[] = [];
129
+ const send = (msg: any) => messages.push(msg);
130
+
131
+ let sessionId = "original-uuid";
132
+ send({ type: "session_unregister", sessionId });
133
+ sessionId = "forked-uuid";
134
+ send({ type: "session_register", sessionId, cwd: "/project", source: "tui" });
135
+
136
+ expect(messages[0].sessionId).toBe("original-uuid");
137
+ expect(messages[1].sessionId).toBe("forked-uuid");
138
+ });
139
+ });
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Tests for session-sync: sendStateSync and handleSessionSwitch.
3
+ */
4
+ import { describe, it, expect, vi } from "vitest";
5
+ import { sendStateSync } from "../session-sync.js";
6
+ import type { BridgeContext } from "../bridge-context.js";
7
+
8
+ function createMockBridgeContext(overrides?: Partial<BridgeContext>): BridgeContext {
9
+ const sent: any[] = [];
10
+ return {
11
+ pi: {
12
+ getSessionName: () => "test-session",
13
+ getCommands: () => [],
14
+ } as any,
15
+ connection: {
16
+ send: (msg: any) => sent.push(msg),
17
+ } as any,
18
+ sessionId: "sess-123",
19
+ cachedCtx: {
20
+ sessionManager: {
21
+ getSessionFile: () => "/path/to/session.json",
22
+ getSessionDir: () => "/path/to/session",
23
+ getBranch: () => [{ role: "user", content: "hello" }],
24
+ getEntries: () => [{ role: "user", content: "hello" }],
25
+ },
26
+ },
27
+ cachedModelRegistry: null,
28
+ cachedHasUI: true,
29
+ lastModel: undefined,
30
+ lastThinkingLevel: undefined,
31
+ lastSessionFile: undefined,
32
+ lastSessionDir: undefined,
33
+ lastFirstMessage: undefined,
34
+ lastGitBranch: undefined,
35
+ lastGitPrNumber: undefined,
36
+ lastSessionName: undefined,
37
+ ...overrides,
38
+ // Expose sent messages for assertions
39
+ _sent: sent,
40
+ } as any;
41
+ }
42
+
43
+ describe("sendStateSync", () => {
44
+ it("should include pid in session_register message", () => {
45
+ const bc = createMockBridgeContext();
46
+ sendStateSync(bc, () => []);
47
+
48
+ const sent = (bc as any)._sent;
49
+ const registerMsg = sent.find((m: any) => m.type === "session_register");
50
+ expect(registerMsg).toBeDefined();
51
+ expect(registerMsg.pid).toBe(process.pid);
52
+ expect(typeof registerMsg.pid).toBe("number");
53
+ expect(registerMsg.pid).toBeGreaterThan(0);
54
+ });
55
+ });
@@ -0,0 +1,73 @@
1
+ import { describe, it, expect, beforeEach, afterEach } from "vitest";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import os from "node:os";
5
+ import { detectSessionSource } from "../source-detector.js";
6
+ import { writeSessionMeta } from "@blackbelt-technology/pi-dashboard-shared/session-meta.js";
7
+
8
+ describe("detectSessionSource", () => {
9
+ const originalEnv = { ...process.env };
10
+ let tmpDir: string;
11
+
12
+ beforeEach(() => {
13
+ delete process.env.ZED_TERM;
14
+ delete process.env.TMUX;
15
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "source-detect-test-"));
16
+ });
17
+
18
+ afterEach(() => {
19
+ process.env = { ...originalEnv };
20
+ fs.rmSync(tmpDir, { recursive: true, force: true });
21
+ });
22
+
23
+ it("should return 'dashboard' when .meta.json has source dashboard", () => {
24
+ const sessionFile = path.join(tmpDir, "test.jsonl");
25
+ writeSessionMeta(sessionFile, { source: "dashboard" });
26
+ expect(detectSessionSource(undefined, sessionFile)).toBe("dashboard");
27
+ });
28
+
29
+ it("should return 'zed' when ZED_TERM is set and hasUI is false", () => {
30
+ process.env.ZED_TERM = "1";
31
+ expect(detectSessionSource(false)).toBe("zed");
32
+ });
33
+
34
+ it("should return 'zed' when ZED_TERM is set and hasUI is not provided", () => {
35
+ process.env.ZED_TERM = "1";
36
+ expect(detectSessionSource()).toBe("zed");
37
+ });
38
+
39
+ it("should return 'tui' when ZED_TERM is set but hasUI is true", () => {
40
+ process.env.ZED_TERM = "1";
41
+ expect(detectSessionSource(true)).toBe("tui");
42
+ });
43
+
44
+ it("should return 'tmux' when TMUX is set", () => {
45
+ process.env.TMUX = "/tmp/tmux-1000/default,12345,0";
46
+ expect(detectSessionSource()).toBe("tmux");
47
+ });
48
+
49
+ it("should return 'tui' when no env vars or meta file", () => {
50
+ expect(detectSessionSource()).toBe("tui");
51
+ });
52
+
53
+ it("should return 'tui' when no session file provided", () => {
54
+ expect(detectSessionSource(undefined, undefined)).toBe("tui");
55
+ });
56
+
57
+ it("should prioritize zed over tmux when hasUI is false", () => {
58
+ process.env.ZED_TERM = "1";
59
+ process.env.TMUX = "something";
60
+ expect(detectSessionSource(false)).toBe("zed");
61
+ });
62
+
63
+ it("should return 'tui' over tmux when ZED_TERM is set and hasUI is true", () => {
64
+ process.env.ZED_TERM = "1";
65
+ process.env.TMUX = "something";
66
+ expect(detectSessionSource(true)).toBe("tui");
67
+ });
68
+
69
+ it("should return 'tui' when meta file does not exist", () => {
70
+ const sessionFile = path.join(tmpDir, "nonexistent.jsonl");
71
+ expect(detectSessionSource(undefined, sessionFile)).toBe("tui");
72
+ });
73
+ });
@@ -0,0 +1,92 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { extractTurnStats } from "@blackbelt-technology/pi-dashboard-shared/stats-extractor.js";
3
+
4
+ describe("extractTurnStats", () => {
5
+ it("extracts stats from event.message.usage", () => {
6
+ const event = {
7
+ type: "turn_end",
8
+ turnIndex: 0,
9
+ message: {
10
+ usage: {
11
+ input: 1500,
12
+ output: 300,
13
+ cacheRead: 800,
14
+ cacheWrite: 200,
15
+ totalTokens: 2800,
16
+ cost: { input: 0.001, output: 0.002, cacheRead: 0.0005, cacheWrite: 0.0005, total: 0.004 },
17
+ },
18
+ },
19
+ toolResults: [],
20
+ };
21
+
22
+ const result = extractTurnStats(event);
23
+
24
+ expect(result).toEqual({
25
+ tokensIn: 1500,
26
+ tokensOut: 300,
27
+ cost: 0.004,
28
+ turnUsage: {
29
+ input: 1500,
30
+ output: 300,
31
+ cacheRead: 800,
32
+ cacheWrite: 200,
33
+ },
34
+ });
35
+ });
36
+
37
+ it("returns null when message.usage is undefined", () => {
38
+ const event = {
39
+ type: "turn_end",
40
+ turnIndex: 0,
41
+ message: { role: "assistant", content: [] },
42
+ toolResults: [],
43
+ };
44
+
45
+ expect(extractTurnStats(event)).toBeNull();
46
+ });
47
+
48
+ it("returns null when message is undefined", () => {
49
+ const event = { type: "turn_end", turnIndex: 0 };
50
+ expect(extractTurnStats(event)).toBeNull();
51
+ });
52
+
53
+ it("includes contextUsage when provided", () => {
54
+ const event = {
55
+ type: "turn_end",
56
+ message: {
57
+ usage: {
58
+ input: 100,
59
+ output: 50,
60
+ cacheRead: 0,
61
+ cacheWrite: 0,
62
+ totalTokens: 150,
63
+ cost: { total: 0.001 },
64
+ },
65
+ },
66
+ };
67
+
68
+ const result = extractTurnStats(event, { tokens: 5000, contextWindow: 128000 });
69
+
70
+ expect(result?.contextUsage).toEqual({ tokens: 5000, contextWindow: 128000 });
71
+ });
72
+
73
+ it("omits contextUsage when not provided", () => {
74
+ const event = {
75
+ type: "turn_end",
76
+ message: {
77
+ usage: {
78
+ input: 100,
79
+ output: 50,
80
+ cacheRead: 0,
81
+ cacheWrite: 0,
82
+ totalTokens: 150,
83
+ cost: { total: 0.001 },
84
+ },
85
+ },
86
+ };
87
+
88
+ const result = extractTurnStats(event);
89
+
90
+ expect(result?.contextUsage).toBeUndefined();
91
+ });
92
+ });
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Tests for the bridge's built-in TUI adapter behavior.
3
+ * Tests the adapter contract using the same mock pattern as the wiring tests.
4
+ * The TUI adapter is defined inline in bridge.ts session_start.
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
8
+ import { PromptBus, type PromptAdapter, type PromptRequest, type PromptResponse, type PromptClaim } from "../prompt-bus.js";
9
+
10
+ // Minimal TUI adapter reimplementation for testing the contract
11
+ // (mirrors the inline adapter in bridge.ts session_start)
12
+ function createTestTuiAdapter(mockUi: any, bus: PromptBus): PromptAdapter {
13
+ const controllers = new Map<string, AbortController>();
14
+
15
+ return {
16
+ name: "tui",
17
+ onRequest(prompt: PromptRequest): PromptClaim | null {
18
+ const ac = new AbortController();
19
+ controllers.set(prompt.id, ac);
20
+
21
+ const present = async () => {
22
+ try {
23
+ let answer: any;
24
+ if (prompt.type === "select") {
25
+ answer = await mockUi.select(prompt.question, prompt.options, { signal: ac.signal });
26
+ } else if (prompt.type === "input") {
27
+ answer = await mockUi.input(prompt.question, prompt.defaultValue || "", { signal: ac.signal });
28
+ } else if (prompt.type === "confirm") {
29
+ answer = await mockUi.confirm(prompt.question, "", { signal: ac.signal });
30
+ }
31
+ if (!ac.signal.aborted) {
32
+ const str = typeof answer === "boolean" ? (answer ? "true" : "false") : answer;
33
+ bus.respond({ id: prompt.id, answer: str ?? undefined, cancelled: str == null, source: "tui" });
34
+ }
35
+ } catch {
36
+ if (!ac.signal.aborted) {
37
+ bus.respond({ id: prompt.id, cancelled: true, source: "tui" });
38
+ }
39
+ } finally {
40
+ controllers.delete(prompt.id);
41
+ }
42
+ };
43
+ present();
44
+ return {};
45
+ },
46
+ onResponse(response: PromptResponse) {
47
+ if (response.source !== "tui") {
48
+ const ac = controllers.get(response.id);
49
+ if (ac) { ac.abort(); controllers.delete(response.id); }
50
+ }
51
+ },
52
+ onCancel(id: string) {
53
+ const ac = controllers.get(id);
54
+ if (ac) { ac.abort(); controllers.delete(id); }
55
+ },
56
+ };
57
+ }
58
+
59
+ function createMockUi() {
60
+ const signals: Record<string, AbortSignal | undefined> = {};
61
+ const resolvers: Record<string, { resolve: (v: any) => void }> = {};
62
+
63
+ function makeMock(name: string) {
64
+ return vi.fn().mockImplementation((_q: string, _a?: any, opts?: any) => {
65
+ signals[name] = opts?.signal;
66
+ return new Promise((resolve) => {
67
+ resolvers[name] = { resolve };
68
+ opts?.signal?.addEventListener("abort", () => resolve(undefined), { once: true });
69
+ });
70
+ });
71
+ }
72
+
73
+ return {
74
+ select: makeMock("select"),
75
+ input: makeMock("input"),
76
+ confirm: makeMock("confirm"),
77
+ _resolve: (method: string, value: any) => resolvers[method]?.resolve(value),
78
+ _signal: (method: string) => signals[method],
79
+ };
80
+ }
81
+
82
+ describe("Bridge TUI adapter", () => {
83
+ let bus: PromptBus;
84
+ let mockUi: ReturnType<typeof createMockUi>;
85
+
86
+ beforeEach(() => {
87
+ vi.useFakeTimers();
88
+ bus = new PromptBus({ timeoutMs: 5000 });
89
+ mockUi = createMockUi();
90
+ });
91
+
92
+ afterEach(() => {
93
+ vi.useRealTimers();
94
+ });
95
+
96
+ it("calls original select with question and options", () => {
97
+ bus.registerAdapter(createTestTuiAdapter(mockUi, bus));
98
+ bus.request({ pipeline: "command", type: "select", question: "Pick:", options: ["A", "B"] });
99
+
100
+ expect(mockUi.select).toHaveBeenCalledWith("Pick:", ["A", "B"], expect.objectContaining({ signal: expect.any(AbortSignal) }));
101
+ });
102
+
103
+ it("calls original input with question and defaultValue", () => {
104
+ bus.registerAdapter(createTestTuiAdapter(mockUi, bus));
105
+ bus.request({ pipeline: "command", type: "input", question: "Name:", defaultValue: "default" });
106
+
107
+ expect(mockUi.input).toHaveBeenCalledWith("Name:", "default", expect.objectContaining({ signal: expect.any(AbortSignal) }));
108
+ });
109
+
110
+ it("calls original confirm with question", () => {
111
+ bus.registerAdapter(createTestTuiAdapter(mockUi, bus));
112
+ bus.request({ pipeline: "command", type: "confirm", question: "Sure?" });
113
+
114
+ expect(mockUi.confirm).toHaveBeenCalledWith("Sure?", "", expect.objectContaining({ signal: expect.any(AbortSignal) }));
115
+ });
116
+
117
+ it("responds via bus when user answers select", async () => {
118
+ bus.registerAdapter(createTestTuiAdapter(mockUi, bus));
119
+ const promise = bus.request({ pipeline: "command", type: "select", question: "Q", options: ["A"] });
120
+
121
+ mockUi._resolve("select", "A");
122
+ await vi.advanceTimersByTimeAsync(0);
123
+
124
+ const result = await promise;
125
+ expect(result.answer).toBe("A");
126
+ expect(result.source).toBe("tui");
127
+ });
128
+
129
+ it("responds cancelled when user dismisses dialog", async () => {
130
+ bus.registerAdapter(createTestTuiAdapter(mockUi, bus));
131
+ const promise = bus.request({ pipeline: "command", type: "select", question: "Q", options: ["A"] });
132
+
133
+ mockUi._resolve("select", undefined);
134
+ await vi.advanceTimersByTimeAsync(0);
135
+
136
+ const result = await promise;
137
+ expect(result.cancelled).toBe(true);
138
+ });
139
+
140
+ it("converts boolean confirm to string", async () => {
141
+ bus.registerAdapter(createTestTuiAdapter(mockUi, bus));
142
+ const promise = bus.request({ pipeline: "command", type: "confirm", question: "Sure?" });
143
+
144
+ mockUi._resolve("confirm", true);
145
+ await vi.advanceTimersByTimeAsync(0);
146
+
147
+ const result = await promise;
148
+ expect(result.answer).toBe("true");
149
+ });
150
+
151
+ it("aborts TUI dialog when another adapter answers", async () => {
152
+ bus.registerAdapter(createTestTuiAdapter(mockUi, bus));
153
+ const promise = bus.request({ pipeline: "command", type: "select", question: "Q", options: ["A"] });
154
+
155
+ // External adapter answers
156
+ const id = (mockUi.select.mock.calls[0] as any)?.[2]?.signal ? undefined : undefined;
157
+ // Get the prompt id from the bus's pending
158
+ bus.respond({ id: (bus as any).pending.keys().next().value, answer: "B", source: "dashboard" });
159
+ await vi.advanceTimersByTimeAsync(0);
160
+
161
+ const result = await promise;
162
+ expect(result.answer).toBe("B");
163
+ expect(result.source).toBe("dashboard");
164
+ expect(mockUi._signal("select")?.aborted).toBe(true);
165
+ });
166
+
167
+ it("aborts TUI dialog on cancel", async () => {
168
+ bus.registerAdapter(createTestTuiAdapter(mockUi, bus));
169
+ const promise = bus.request({ pipeline: "command", type: "select", question: "Q", options: ["A"] });
170
+
171
+ const id = (bus as any).pending.keys().next().value;
172
+ bus.cancel(id);
173
+ await vi.advanceTimersByTimeAsync(0);
174
+
175
+ const result = await promise;
176
+ expect(result.cancelled).toBe(true);
177
+ expect(mockUi._signal("select")?.aborted).toBe(true);
178
+ });
179
+
180
+ it("does not respond after being aborted", async () => {
181
+ const respondSpy = vi.spyOn(bus, "respond");
182
+ bus.registerAdapter(createTestTuiAdapter(mockUi, bus));
183
+ bus.request({ pipeline: "command", type: "select", question: "Q", options: ["A"] });
184
+
185
+ const id = (bus as any).pending.keys().next().value;
186
+ // Dashboard answers first
187
+ bus.respond({ id, answer: "B", source: "dashboard" });
188
+ await vi.advanceTimersByTimeAsync(0);
189
+
190
+ // TUI resolves after abort — should NOT call respond again
191
+ mockUi._resolve("select", "A");
192
+ await vi.advanceTimersByTimeAsync(0);
193
+
194
+ // respond was called exactly once (by dashboard)
195
+ expect(respondSpy.mock.calls.filter(c => c[0].id === id)).toHaveLength(1);
196
+ });
197
+
198
+ it("returns empty claim (no component)", () => {
199
+ const adapter = createTestTuiAdapter(mockUi, bus);
200
+ bus.registerAdapter(adapter);
201
+ const claim = adapter.onRequest({
202
+ id: "test", pipeline: "command", type: "select", question: "Q", options: ["A"],
203
+ });
204
+ expect(claim).toEqual({});
205
+ expect(claim?.component).toBeUndefined();
206
+ });
207
+ });