@firstpick/pi-package-webui 0.7.5 → 0.7.7

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 (40) hide show
  1. package/README.md +37 -4
  2. package/bin/pi-webui-rpc-supervisor.mjs +518 -0
  3. package/bin/pi-webui.mjs +1003 -82
  4. package/lib/WEBUI_TUI_NATIVE_PARITY.json +13 -0
  5. package/lib/rpc-supervisor-client.mjs +301 -0
  6. package/lib/rpc-supervisor-protocol.mjs +236 -0
  7. package/lib/rpc-supervisor-state.mjs +165 -0
  8. package/lib/trust-boundaries.mjs +1 -0
  9. package/package.json +2 -2
  10. package/public/app.js +1243 -87
  11. package/public/index.html +334 -24
  12. package/public/service-worker.js +6 -1
  13. package/public/styles.css +642 -41
  14. package/public/subagent-gate-visibility.mjs +36 -0
  15. package/public/workflow-status-stack.mjs +69 -0
  16. package/tests/app-runner-process-tree-harness.test.mjs +37 -3
  17. package/tests/boot-failure-diagnostics.test.mjs +180 -0
  18. package/tests/compact-sections-static.test.mjs +111 -0
  19. package/tests/durable-rpc-supervisor-harness.test.mjs +252 -0
  20. package/tests/fast-mode-client-static.test.mjs +2 -2
  21. package/tests/fixtures/compacting-pi.mjs +0 -0
  22. package/tests/fixtures/fake-pi.mjs +81 -2
  23. package/tests/git-panel-file-preview-static.test.mjs +221 -0
  24. package/tests/http-endpoints-harness.test.mjs +458 -33
  25. package/tests/mobile-static.test.mjs +77 -9
  26. package/tests/native-parity-harness.test.mjs +2 -1
  27. package/tests/native-parity.test.mjs +11 -0
  28. package/tests/numpad-decimal-input-static.test.mjs +128 -0
  29. package/tests/prompt-routing-input-clear-static.test.mjs +34 -0
  30. package/tests/prompt-routing-tab-status.test.mjs +103 -0
  31. package/tests/rpc-supervisor-host.test.mjs +275 -0
  32. package/tests/rpc-supervisor-protocol.test.mjs +67 -0
  33. package/tests/rpc-supervisor-state.test.mjs +62 -0
  34. package/tests/run-all.mjs +4 -1
  35. package/tests/streaming-ui-coupling.test.mjs +15 -0
  36. package/tests/subagent-gate-visibility.test.mjs +66 -0
  37. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  38. package/tests/subagents-helper.test.mjs +145 -8
  39. package/tests/workflow-status-stack.test.mjs +87 -0
  40. package/webui-rpc-helper.mjs +164 -4
@@ -0,0 +1,252 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { setTimeout as delay } from "node:timers/promises";
8
+ import { connectRpcSupervisor } from "../lib/rpc-supervisor-client.mjs";
9
+ import { readSupervisorState, supervisorPaths } from "../lib/rpc-supervisor-state.mjs";
10
+
11
+ const root = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
12
+ const serverScript = path.join(root, "bin", "pi-webui.mjs");
13
+ const fakePi = path.join(root, "tests", "fixtures", "fake-pi.mjs");
14
+ const port = 39000 + Math.floor(Math.random() * 15000);
15
+ const streamPrompt = "fixture continuity delayed stream";
16
+
17
+ async function request(pathname, { method = "GET", body, timeoutMs = 3_000 } = {}) {
18
+ const response = await fetch(`http://127.0.0.1:${port}${pathname}`, {
19
+ method,
20
+ headers: body === undefined ? undefined : { "content-type": "application/json" },
21
+ body: body === undefined ? undefined : JSON.stringify(body),
22
+ signal: AbortSignal.timeout(timeoutMs),
23
+ });
24
+ let payload;
25
+ try { payload = await response.json(); } catch { payload = undefined; }
26
+ return { status: response.status, body: payload };
27
+ }
28
+
29
+ async function waitFor(label, predicate, { timeoutMs = 12_000, intervalMs = 80 } = {}) {
30
+ const deadline = Date.now() + timeoutMs;
31
+ let lastError;
32
+ while (Date.now() < deadline) {
33
+ try {
34
+ const value = await predicate();
35
+ if (value) return value;
36
+ } catch (error) {
37
+ lastError = error;
38
+ }
39
+ await delay(intervalMs);
40
+ }
41
+ throw new Error(`${label} did not happen in time${lastError ? `: ${lastError.message}` : ""}`);
42
+ }
43
+
44
+ async function initialSseEvents(tabId, expectedCount = 3) {
45
+ const controller = new AbortController();
46
+ const timeout = setTimeout(() => controller.abort(new Error("timed out reading continuity SSE state")), 5_000);
47
+ try {
48
+ const response = await fetch(`http://127.0.0.1:${port}/api/events?tab=${encodeURIComponent(tabId)}`, { signal: controller.signal });
49
+ assert.equal(response.status, 200, "replacement server SSE endpoint must open");
50
+ const reader = response.body.getReader();
51
+ const decoder = new TextDecoder();
52
+ const events = [];
53
+ let buffer = "";
54
+ while (events.length < expectedCount) {
55
+ const { done, value } = await reader.read();
56
+ if (done) break;
57
+ buffer += decoder.decode(value, { stream: true });
58
+ let boundary;
59
+ while ((boundary = buffer.indexOf("\n\n")) >= 0) {
60
+ const block = buffer.slice(0, boundary);
61
+ buffer = buffer.slice(boundary + 2);
62
+ const data = block.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).join("\n");
63
+ if (data) events.push(JSON.parse(data));
64
+ }
65
+ }
66
+ return events;
67
+ } finally {
68
+ clearTimeout(timeout);
69
+ controller.abort();
70
+ }
71
+ }
72
+
73
+ function pidIsAlive(pid) {
74
+ if (!Number.isInteger(pid) || pid < 1) return false;
75
+ try {
76
+ process.kill(pid, 0);
77
+ return true;
78
+ } catch (error) {
79
+ return error?.code === "EPERM";
80
+ }
81
+ }
82
+
83
+ function spawnServer({ cwd, env, output }) {
84
+ const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
85
+ stdio: ["ignore", "pipe", "pipe"],
86
+ env,
87
+ });
88
+ child.stdout.on("data", (chunk) => output.push(String(chunk)));
89
+ child.stderr.on("data", (chunk) => output.push(String(chunk)));
90
+ return child;
91
+ }
92
+
93
+ async function health() {
94
+ const response = await request("/api/health", { timeoutMs: 1_000 });
95
+ if (response.status !== 200 || response.body?.ok !== true) return null;
96
+ return response.body;
97
+ }
98
+
99
+ async function tabs() {
100
+ const response = await request("/api/tabs");
101
+ assert.equal(response.status, 200, "tabs endpoint should be available");
102
+ return response.body?.data?.tabs || [];
103
+ }
104
+
105
+ async function readLog(logFile) {
106
+ const text = await readFile(logFile, "utf8").catch(() => "");
107
+ return text.split("\n").filter(Boolean).map((line) => JSON.parse(line));
108
+ }
109
+
110
+ const work = await mkdtemp(path.join(tmpdir(), "pi-webui-continuity-harness-"));
111
+ const agentDir = path.join(work, "agent");
112
+ const cwd = path.join(work, "cwd");
113
+ const settingsFile = path.join(work, "settings.json");
114
+ const sessionFile = path.join(work, "fixture-session.jsonl");
115
+ const logFile = path.join(work, "fake-pi.jsonl");
116
+ const output = [];
117
+ const environment = {
118
+ ...process.env,
119
+ PI_CODING_AGENT_DIR: agentDir,
120
+ PI_WEBUI_SETTINGS_FILE: settingsFile,
121
+ PI_WEBUI_RPC_SUPERVISOR: "1",
122
+ FAKE_PI_CONTINUITY_MODE: "1",
123
+ FAKE_PI_CONTINUITY_SESSION_FILE: sessionFile,
124
+ FAKE_PI_LOG_FILE: logFile,
125
+ };
126
+ const paths = await supervisorPaths({ agentDir, port });
127
+ let initialServer;
128
+ let manualServer;
129
+ let observedPiPid;
130
+ let observedTabId;
131
+
132
+ try {
133
+ await writeFile(settingsFile, "{}\n");
134
+ await mkdir(cwd, { recursive: true });
135
+ initialServer = spawnServer({ cwd, env: environment, output });
136
+
137
+ const initialHealth = await waitFor("initial supervised server health", health);
138
+ assert.equal(initialHealth.rpcSupervisor?.enabled, true, "harness must opt into the supervisor");
139
+ assert.equal(initialHealth.rpcSupervisor?.attached, true, "server must attach to the supervisor");
140
+ const initialWebuiPid = initialHealth.webuiPid;
141
+ const initialTabs = await tabs();
142
+ assert.equal(initialTabs.length, 1, "isolated server startup should create one tab");
143
+ const initialTab = initialTabs[0];
144
+ observedTabId = initialTab.id;
145
+ observedPiPid = initialTab.pid;
146
+ assert.ok(Number.isInteger(observedPiPid) && observedPiPid > 0, "initial tab must expose its fake Pi PID");
147
+ assert.equal(initialTab.cwd, cwd, "tab metadata must retain the isolated cwd");
148
+ assert.equal(initialTab.sessionFile, sessionFile, "fixture session metadata must be captured before restart");
149
+
150
+ const controlledPrompt = await request("/api/prompt", { method: "POST", body: { tab: observedTabId, message: streamPrompt } });
151
+ assert.equal(controlledPrompt.status, 200, "controlled-restart prompt must be accepted once");
152
+ const preRestartTab = (await tabs())[0];
153
+ const restart = await request("/api/restart", { method: "POST" });
154
+ assert.equal(restart.status, 200, "controlled restart must be accepted");
155
+ assert.equal(restart.body?.webuiPid, initialWebuiPid, "restart response must identify the retiring HTTP server");
156
+
157
+ const restartedHealth = await waitFor("controlled-restart replacement health", async () => {
158
+ const value = await health();
159
+ return value && value.webuiPid !== initialWebuiPid ? value : null;
160
+ }, { timeoutMs: 15_000 });
161
+ const controlledTabs = await tabs();
162
+ assert.equal(controlledTabs.length, 1, "controlled restart must hydrate instead of spawning duplicate tabs");
163
+ assert.deepEqual(
164
+ controlledTabs.map((tab) => ({ id: tab.id, pid: tab.pid, cwd: tab.cwd, sessionFile: tab.sessionFile, title: tab.title, index: tab.index })),
165
+ [{ id: preRestartTab.id, pid: observedPiPid, cwd, sessionFile, title: preRestartTab.title, index: preRestartTab.index }],
166
+ "controlled restart must retain the same managed tab metadata and Pi PID",
167
+ );
168
+ assert.equal(restartedHealth.piPid, observedPiPid, "controlled restart must retain the active Pi process");
169
+ await waitFor("controlled stream completion", async () => {
170
+ const state = await request(`/api/state?tab=${encodeURIComponent(observedTabId)}`);
171
+ return state.body?.data?.isStreaming === false;
172
+ });
173
+
174
+ const abruptPrompt = await request("/api/prompt", { method: "POST", body: { tab: observedTabId, message: streamPrompt } });
175
+ assert.equal(abruptPrompt.status, 200, "abrupt-loss prompt must be accepted once");
176
+ const abruptWebuiPid = restartedHealth.webuiPid;
177
+ process.kill(abruptWebuiPid, "SIGKILL");
178
+ await waitFor("abrupt HTTP server exit", () => !pidIsAlive(abruptWebuiPid));
179
+ await delay(1_500);
180
+
181
+ const state = await readSupervisorState(paths);
182
+ assert.ok(state, "supervisor state must remain available after HTTP SIGKILL");
183
+
184
+ manualServer = spawnServer({ cwd, env: environment, output });
185
+ const manualHealth = await waitFor("manual same-port replacement health", health, { timeoutMs: 15_000 });
186
+ assert.notEqual(manualHealth.webuiPid, abruptWebuiPid, "manual relaunch must use a new HTTP server process");
187
+ assert.equal(manualHealth.piPid, observedPiPid, "manual same-port relaunch must attach to the original Pi process");
188
+ const manualTabs = await tabs();
189
+ assert.equal(manualTabs.length, 1, "manual relaunch must not duplicate the supervised tab");
190
+ assert.deepEqual(
191
+ manualTabs.map((tab) => ({ id: tab.id, pid: tab.pid, cwd: tab.cwd, sessionFile: tab.sessionFile, title: tab.title, index: tab.index })),
192
+ [{ id: preRestartTab.id, pid: observedPiPid, cwd, sessionFile, title: preRestartTab.title, index: preRestartTab.index }],
193
+ "manual relaunch must retain tab ID, PID, and persisted metadata",
194
+ );
195
+
196
+ const reconnectEvents = await initialSseEvents(observedTabId);
197
+ const connectedEvent = reconnectEvents.find((event) => event.type === "webui_connected");
198
+ const replayGapEvent = reconnectEvents.find((event) => event.type === "webui_supervisor_replay_gap");
199
+ assert.equal(connectedEvent?.supervisorReplayGap, true, "actual replacement server must report a truthful cursor-less replay gap");
200
+ assert.equal(Object.hasOwn(connectedEvent || {}, "supervisorGap"), false, "replacement server must use the browser's canonical replay-gap field");
201
+ assert.equal(replayGapEvent?.supervisorReplayGap, true, "replacement SSE must explicitly warn that authoritative replay recovery ran");
202
+
203
+ const recoveredState = await request(`/api/state?tab=${encodeURIComponent(observedTabId)}`);
204
+ assert.equal(recoveredState.status, 200, "replacement server must query authoritative Pi state");
205
+ assert.equal(recoveredState.body?.data?.isStreaming, false, "replacement server must observe the completed downtime turn");
206
+ const recoveredMessages = await request(`/api/messages?tab=${encodeURIComponent(observedTabId)}`);
207
+ assert.equal(recoveredMessages.status, 200, "replacement server must expose the authoritative transcript");
208
+ const recoveredTranscript = recoveredMessages.body?.data?.messages || [];
209
+ assert.equal(recoveredTranscript.filter((message) => message?.role === "user" && message.content === streamPrompt).length, 2, "both accepted continuity prompts must appear once in the transcript");
210
+ assert.equal(recoveredTranscript.filter((message) => message?.role === "assistant" && message.content?.[0]?.text === "continuity stream complete").length, 2, "the completed controlled and downtime outputs must each appear once authoritatively");
211
+ const replacementStatus = await request("/api/webui-status?detailed=true&events=200");
212
+ const replayedEventTypes = (replacementStatus.body?.data?.events || []).map((event) => event.type);
213
+ const lastAgentStart = replayedEventTypes.lastIndexOf("agent_start");
214
+ const followingAgentEnd = replayedEventTypes.indexOf("agent_end", lastAgentStart);
215
+ assert.deepEqual(replayedEventTypes.slice(lastAgentStart, followingAgentEnd + 1), ["agent_start", "message_start", "message_update", "message_end", "agent_end"], "replacement server must apply the ordered downtime event stream before authoritative refresh events");
216
+
217
+ const commandEntries = (await readLog(logFile)).filter((entry) => entry.direction === "command" && entry.message === streamPrompt);
218
+ assert.equal(commandEntries.length, 2, "each accepted continuity prompt must reach fake Pi exactly once despite server loss");
219
+ assert.equal(new Set(commandEntries.map((entry) => entry.type)).size, 1, "continuity prompt command records must remain identifiable");
220
+ assert.equal(commandEntries[0].type, "prompt");
221
+
222
+ const stopped = await request("/api/shutdown", { method: "POST" });
223
+ assert.equal(stopped.status, 200, "explicit shutdown must be accepted");
224
+ await waitFor("explicit HTTP shutdown", () => !pidIsAlive(manualHealth.webuiPid));
225
+ await waitFor("explicit Pi cleanup", () => !pidIsAlive(observedPiPid), { timeoutMs: 8_000 });
226
+ await waitFor("supervisor state cleanup", async () => {
227
+ const remainingState = await readSupervisorState(paths);
228
+ if (!remainingState) return true;
229
+ if (!pidIsAlive(remainingState.pid)) throw new Error(`dead supervisor ${remainingState.pid} left stale state`);
230
+ return false;
231
+ }, { timeoutMs: 12_000 });
232
+ const exitEntries = (await readLog(logFile)).filter((entry) => entry.direction === "exit" && entry.pid === observedPiPid);
233
+ assert.ok(exitEntries.some((entry) => entry.signal === "SIGTERM"), "explicit shutdown must produce the fake-Pi termination marker");
234
+ console.log(`durable-rpc-supervisor-harness.test.mjs passed (Pi PID ${observedPiPid}; tab ${observedTabId})`);
235
+ } finally {
236
+ const liveServer = manualServer?.exitCode === null ? manualServer : initialServer?.exitCode === null ? initialServer : null;
237
+ if (liveServer) {
238
+ try { await request("/api/shutdown", { method: "POST", timeoutMs: 1_000 }); } catch {
239
+ try { liveServer.kill("SIGKILL"); } catch {}
240
+ }
241
+ }
242
+ const remaining = await readSupervisorState(paths).catch(() => null);
243
+ if (remaining) {
244
+ const cleanupClient = await connectRpcSupervisor({ agentDir, port, controllerId: "durable-harness-cleanup", connectTimeoutMs: 1_000 }).catch(() => null);
245
+ if (cleanupClient) {
246
+ try { await cleanupClient.shutdown(); } catch {}
247
+ cleanupClient.close();
248
+ }
249
+ }
250
+ await delay(150);
251
+ await rm(work, { recursive: true, force: true });
252
+ }
@@ -149,10 +149,10 @@ assert.match(app, /fastOutputModeSelect\?\.addEventListener\("change", \(\) => \
149
149
  assert.match(app, /refreshSidebarOutputMode\(\)\.catch[\s\S]*?initializeTabs\(\)/, "sidebar output mode should initialize with the WebUI");
150
150
 
151
151
  assert.match(helper, /FAST_OUTPUT_FLUSH_INTERVAL_MS = 100/, "the live scheduler should retain the exact 100 ms sustained-output bound");
152
- assert.match(worker, /pi-webui-pwa-v44[\s\S]*?"\/fast-output-live\.mjs"/, "PWA cache identity and app shell should include the compact helper");
152
+ assert.match(worker, /pi-webui-pwa-v\d+[\s\S]*?"\/fast-output-live\.mjs"/, "PWA cache identity and app shell should include the compact helper");
153
153
  assert.match(html, /<label for="fastOutputModeSelect">Fast mode \(Experimental\)<\/label>/, "the sidebar should mark fast mode as experimental");
154
154
  assert.match(html, /Markdown final output; live thinking expanded; stored thinking grouped and collapsed/, "the sidebar should distinguish live and stored thinking defaults");
155
- assert.match(html, /<script type="module" src="\/app\.js\?v=91"><\/script>/, "the PWA entry point should cache-bust browser wiring");
155
+ assert.match(html, /id="webuiBootLoader"[^>]*data-app-src="\/app\.js\?v=91"/, "the guarded PWA entry point should cache-bust browser wiring");
156
156
  assert.match(JSON.parse(packageRaw).scripts.check, /node --check public\/fast-output-live\.mjs/, "package checks should parse the compact helper");
157
157
 
158
158
  const events = createFastModeOutputEvents();
File without changes
@@ -20,7 +20,9 @@ import { randomUUID } from "node:crypto";
20
20
  import { appendFileSync } from "node:fs";
21
21
 
22
22
  const sessionIndex = process.argv.indexOf("--session");
23
- const sessionFile = sessionIndex !== -1 ? process.argv[sessionIndex + 1] : undefined;
23
+ const sessionFile = sessionIndex !== -1
24
+ ? process.argv[sessionIndex + 1]
25
+ : process.env.FAKE_PI_CONTINUITY_MODE === "1" ? process.env.FAKE_PI_CONTINUITY_SESSION_FILE || undefined : undefined;
24
26
 
25
27
  let activeBash = 0;
26
28
  let peakBash = 0;
@@ -38,7 +40,13 @@ let enabledToolNames = new Set(fakeTools.map((tool) => tool.name));
38
40
  let enabledSkillNames = new Set(fakeSkills.map((skill) => skill.name));
39
41
 
40
42
  const voiceScriptsEnabled = process.env.FAKE_PI_VOICE_SCRIPTS === "1";
43
+ // The continuity harness opts into this behavior explicitly so existing fixture
44
+ // consumers retain their current timing and log shapes.
45
+ const continuityModeEnabled = process.env.FAKE_PI_CONTINUITY_MODE === "1";
46
+ const largePayloadsEnabled = process.env.FAKE_PI_LARGE_PAYLOADS === "1";
41
47
  const commandLogFile = process.env.FAKE_PI_LOG_FILE || "";
48
+ const largeRpcText = "large-rpc-payload:" + "λ".repeat(70_000);
49
+ const largeTokenSamples = Array.from({ length: 300 }, (_, index) => ({ index, input: index + 1, output: index + 2 }));
42
50
  const staticEntries = [
43
51
  { type: "message", id: "u0000001", parentId: null, timestamp: new Date(1000).toISOString(), message: { role: "user", content: "fake prompt", timestamp: 1000 } },
44
52
  { type: "message", id: "a0000001", parentId: "u0000001", timestamp: new Date(2000).toISOString(), message: { role: "assistant", content: [{ type: "text", text: "fake answer" }], timestamp: 2000 } },
@@ -48,6 +56,8 @@ const dynamicEntries = [];
48
56
  const dynamicMessages = [];
49
57
  let dynamicLeafId = "u0000002";
50
58
  let scriptedStreaming = false;
59
+ let continuityRun = 0;
60
+ let largeTranscriptEnabled = false;
51
61
 
52
62
  function allSessionEntries() {
53
63
  return [...staticEntries, ...dynamicEntries];
@@ -93,8 +103,25 @@ logJsonLine({
93
103
  direction: "startup",
94
104
  recoveryUrl: String(process.env.PI_WEBUI_RECOVERY_URL || ""),
95
105
  recoveryTokenConfigured: Boolean(process.env.PI_WEBUI_RECOVERY_TOKEN),
106
+ ...(continuityModeEnabled ? { pid: process.pid, continuityMode: true } : {}),
96
107
  });
97
108
 
109
+ function continuityExitMarker(signal) {
110
+ if (continuityModeEnabled) logJsonLine({ direction: "exit", signal, pid: process.pid });
111
+ }
112
+
113
+ if (continuityModeEnabled) {
114
+ process.on("SIGTERM", () => {
115
+ continuityExitMarker("SIGTERM");
116
+ process.exit(143);
117
+ });
118
+ process.on("SIGINT", () => {
119
+ continuityExitMarker("SIGINT");
120
+ process.exit(130);
121
+ });
122
+ }
123
+
124
+
98
125
  function respond(payload) {
99
126
  process.stdout.write(`${JSON.stringify(payload)}\n`);
100
127
  }
@@ -160,6 +187,45 @@ function runVoiceScriptFlow({ text, chunks, chunkSpacingMs = 60, toolPhase = fal
160
187
  runScriptedSteps(steps);
161
188
  }
162
189
 
190
+ function runContinuityDelayedStream() {
191
+ scriptedStreaming = true;
192
+ const text = "continuity stream complete";
193
+ const run = ++continuityRun;
194
+ const tagged = (payload) => ({ ...payload, continuityRun: run });
195
+ const steps = [
196
+ { afterMs: 80, run: () => emitScriptedEvent(tagged({ type: "agent_start", continuityStep: "start" })) },
197
+ { afterMs: 80, run: () => emitScriptedEvent(tagged({ type: "message_start", continuityStep: "message-start", message: { role: "assistant" } })) },
198
+ { afterMs: 300, run: () => emitScriptedEvent(tagged({ type: "message_update", continuityStep: "delta-1", assistantMessageEvent: { type: "text_delta", delta: "continuity " } })) },
199
+ { afterMs: 300, run: () => emitScriptedEvent(tagged({ type: "message_update", continuityStep: "delta-2", assistantMessageEvent: { type: "text_delta", delta: "stream " } })) },
200
+ { afterMs: 300, run: () => emitScriptedEvent(tagged({ type: "message_update", continuityStep: "delta-3", assistantMessageEvent: { type: "text_delta", delta: "complete" } })) },
201
+ { afterMs: 100, run: () => {
202
+ const message = { role: "assistant", content: [{ type: "text", text }], timestamp: Date.now() };
203
+ appendDynamicMessage(message);
204
+ emitScriptedEvent(tagged({ type: "message_end", continuityStep: "message-end", message }));
205
+ } },
206
+ { afterMs: 80, run: () => {
207
+ scriptedStreaming = false;
208
+ emitScriptedEvent(tagged({ type: "agent_end", continuityStep: "end" }));
209
+ } },
210
+ ];
211
+ runScriptedSteps(steps);
212
+ }
213
+
214
+ function handleContinuityPrompt(command, base) {
215
+ if (!continuityModeEnabled || String(command.message || "").trim() !== "fixture continuity delayed stream") return false;
216
+ appendDynamicMessage({ role: "user", content: String(command.message), timestamp: Date.now() });
217
+ respond({ ...base, data: { output: "fake continuity stream accepted", pid: process.pid } });
218
+ runContinuityDelayedStream();
219
+ return true;
220
+ }
221
+
222
+ function handleLargePayloadPrompt(command, base) {
223
+ if (!largePayloadsEnabled || String(command.message || "").trim() !== "fixture large rpc payload") return false;
224
+ largeTranscriptEnabled = true;
225
+ respond({ ...base, data: { output: largeRpcText, tokens: { input: 123456, output: 654321 }, samples: largeTokenSamples } });
226
+ return true;
227
+ }
228
+
163
229
  function handleVoiceScriptPrompt(command, base) {
164
230
  if (!voiceScriptsEnabled) return false;
165
231
  const message = String(command.message || "");
@@ -499,6 +565,7 @@ rl.on("line", (line) => {
499
565
  ...(Array.isArray(command.images) ? { images: command.images } : {}),
500
566
  ...(command.provider !== undefined ? { provider: String(command.provider) } : {}),
501
567
  ...(command.modelId !== undefined ? { modelId: String(command.modelId) } : {}),
568
+ ...(type === "extension_ui_response" ? { id: String(command.id), value: command.value, cancelled: command.cancelled === true } : {}),
502
569
  });
503
570
  const base = { type: "response", id, command: type, success: true };
504
571
 
@@ -531,6 +598,7 @@ rl.on("line", (line) => {
531
598
  { role: "assistant", content: [{ type: "text", text: "fake answer" }], timestamp: 2000 },
532
599
  { role: "user", content: "fake follow-up", timestamp: 3000 },
533
600
  ...dynamicMessages,
601
+ ...(largeTranscriptEnabled ? [{ role: "assistant", content: [{ type: "text", text: largeRpcText }], timestamp: 4000 }] : []),
534
602
  ],
535
603
  },
536
604
  });
@@ -573,6 +641,8 @@ rl.on("line", (line) => {
573
641
  if (handleDocumentArtifactFixturePrompt(command, base)) return;
574
642
  if (handleWorkflowFixturePrompt(command, base)) return;
575
643
  if (handleTalkPrompt(command, base)) return;
644
+ if (handleContinuityPrompt(command, base)) return;
645
+ if (handleLargePayloadPrompt(command, base)) return;
576
646
  if (handleVoiceScriptPrompt(command, base)) return;
577
647
  respond({ ...base, data: { output: "fake prompt accepted" } });
578
648
  return;
@@ -591,11 +661,20 @@ rl.on("line", (line) => {
591
661
  respond({ ...base, data: { models: [{ provider: "fake", id: "fake-model", name: "Fake Model" }] } });
592
662
  return;
593
663
  case "get_session_stats":
594
- respond({ ...base, data: { tokens: 0 } });
664
+ respond({
665
+ ...base,
666
+ data: largePayloadsEnabled
667
+ ? { tokens: { input: 123456, output: 654321, total: 777777 }, samples: largeTokenSamples }
668
+ : { tokens: 0 },
669
+ });
595
670
  return;
596
671
  case "get_last_assistant_text":
597
672
  respond({ ...base, data: { text: "fake last text" } });
598
673
  return;
674
+ case "extension_ui_response":
675
+ // Pi's extension UI response is a one-way RPC write. Deliberately emit
676
+ // no response so supervised HTTP coverage catches accidental waits.
677
+ return;
599
678
  case "bash": {
600
679
  activeBash += 1;
601
680
  peakBash = Math.max(peakBash, activeBash);