@firstpick/pi-package-webui 0.5.8 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,466 @@
1
+ // Browser voice loop for Natural Conversation Mode (Phase 3).
2
+ // The controller is dependency-injected: speech recognition, speech synthesis,
3
+ // timers, and delivery callbacks all arrive through options so Node tests can
4
+ // drive the full listen -> prompt -> speak -> listen loop without a browser.
5
+ //
6
+ // Turn-taking contract (see docs/webui/natural-conversation/NATURAL_CONVERSATION_MODE_PLAN.md):
7
+ // - Final transcripts while Pi is idle are sent as normal prompts.
8
+ // - Transcripts while the assistant streams final text are interruptions.
9
+ // - Transcripts during a tool call/execution are queued until the tool phase
10
+ // ends; they are never injected into an active tool phase.
11
+ // - While TTS is speaking, the microphone is paused unless barge-in is enabled.
12
+ // - After the assistant asks a question, silence past the timeout emits a
13
+ // single structured silence event instead of guessing user intent.
14
+ // - The browser voice loop can be manually paused/resumed without disabling the
15
+ // package-owned conversation-mode safety constraints.
16
+
17
+ export const VOICE_UI_STATES = [
18
+ "off",
19
+ "listening",
20
+ "transcribing",
21
+ "answering",
22
+ "speaking",
23
+ "interrupting",
24
+ "silence",
25
+ "paused",
26
+ "error",
27
+ ];
28
+
29
+ export const DEFAULT_SILENCE_TIMEOUT_MS = 8000;
30
+
31
+ export function voiceSilenceEventMessage(silentSeconds = Math.round(DEFAULT_SILENCE_TIMEOUT_MS / 1000)) {
32
+ const seconds = Number.isFinite(silentSeconds) && silentSeconds > 0 ? Math.round(silentSeconds) : 8;
33
+ return `[Conversation mode: the user stayed silent for ${seconds}s after your question. Treat the silence as possible confusion, discomfort, missing context, or an unneeded question; reframe, explain why you asked, or continue without pressuring the user. Do not invent intent from the silence.]`;
34
+ }
35
+
36
+ export function createVoiceConversationController(options = {}) {
37
+ const {
38
+ recognitionFactory = null,
39
+ synthesis = null,
40
+ utteranceFactory = null,
41
+ sendTranscript = async () => {},
42
+ sendSilenceEvent = async () => {},
43
+ onPartialTranscript = () => {},
44
+ onStateChange = () => {},
45
+ onEvent = () => {},
46
+ bargeInEnabled = false,
47
+ silenceTimeoutMs = DEFAULT_SILENCE_TIMEOUT_MS,
48
+ setTimeoutFn = (handler, delayMs) => setTimeout(handler, delayMs),
49
+ clearTimeoutFn = (id) => clearTimeout(id),
50
+ } = options;
51
+
52
+ const state = {
53
+ active: false,
54
+ uiState: "off",
55
+ sttAvailable: null,
56
+ ttsAvailable: !!(synthesis && typeof utteranceFactory === "function"),
57
+ assistantStreaming: false,
58
+ toolRunning: false,
59
+ speaking: false,
60
+ userPaused: false,
61
+ partialTranscript: "",
62
+ queuedInterrupt: "",
63
+ lastError: "",
64
+ };
65
+
66
+ let recognition = null;
67
+ let recognitionRunning = false;
68
+ let recognitionPausedForSpeech = false;
69
+ let silenceTimer = null;
70
+ let currentUtterance = null;
71
+
72
+ function snapshot() {
73
+ return { ...state };
74
+ }
75
+
76
+ function setUiState(uiState, detail = {}) {
77
+ state.uiState = uiState;
78
+ try {
79
+ onStateChange(uiState, { ...snapshot(), ...detail });
80
+ } catch {
81
+ // State listeners must never break the voice loop.
82
+ }
83
+ }
84
+
85
+ function emitEvent(message, level = "info") {
86
+ try {
87
+ onEvent(message, level);
88
+ } catch {
89
+ // Log listeners must never break the voice loop.
90
+ }
91
+ }
92
+
93
+ function setPartialTranscript(text = "") {
94
+ const partialTranscript = String(text || "").trim();
95
+ if (state.partialTranscript === partialTranscript) return;
96
+ state.partialTranscript = partialTranscript;
97
+ try {
98
+ onPartialTranscript(partialTranscript, snapshot());
99
+ } catch {
100
+ // Partial transcript listeners must never break the voice loop.
101
+ }
102
+ }
103
+
104
+ function clearPartialTranscript() {
105
+ setPartialTranscript("");
106
+ }
107
+
108
+ function clearSilenceTimer() {
109
+ if (silenceTimer === null) return;
110
+ clearTimeoutFn(silenceTimer);
111
+ silenceTimer = null;
112
+ }
113
+
114
+ function startSilenceTimer() {
115
+ clearSilenceTimer();
116
+ if (!state.active || !silenceTimeoutMs || silenceTimeoutMs <= 0) return;
117
+ silenceTimer = setTimeoutFn(() => {
118
+ silenceTimer = null;
119
+ if (!state.active || state.speaking || state.assistantStreaming) return;
120
+ if (state.uiState !== "listening" && state.uiState !== "transcribing") return;
121
+ setUiState("silence");
122
+ const silentSeconds = Math.round(silenceTimeoutMs / 1000);
123
+ Promise.resolve(sendSilenceEvent({ silentSeconds }))
124
+ .then(() => {
125
+ if (state.active && state.uiState === "silence") setUiState("answering", { reason: "silence" });
126
+ })
127
+ .catch((error) => {
128
+ emitEvent(`Failed to send voice silence event: ${error?.message || error}`, "warn");
129
+ if (state.active && state.uiState === "silence") setUiState("listening");
130
+ });
131
+ }, silenceTimeoutMs);
132
+ }
133
+
134
+ function ensureRecognition() {
135
+ if (recognition) return recognition;
136
+ if (typeof recognitionFactory !== "function") {
137
+ state.sttAvailable = false;
138
+ return null;
139
+ }
140
+ let created = null;
141
+ try {
142
+ created = recognitionFactory();
143
+ } catch {
144
+ created = null;
145
+ }
146
+ if (!created) {
147
+ state.sttAvailable = false;
148
+ return null;
149
+ }
150
+ recognition = created;
151
+ try {
152
+ recognition.continuous = true;
153
+ recognition.interimResults = true;
154
+ } catch {
155
+ // Some engines expose read-only configuration; keep their defaults.
156
+ }
157
+ recognition.onresult = handleRecognitionResult;
158
+ recognition.onerror = handleRecognitionError;
159
+ recognition.onend = handleRecognitionEnd;
160
+ return recognition;
161
+ }
162
+
163
+ function startRecognition() {
164
+ const instance = ensureRecognition();
165
+ if (!instance) return false;
166
+ recognitionPausedForSpeech = false;
167
+ if (recognitionRunning) return true;
168
+ try {
169
+ instance.start();
170
+ recognitionRunning = true;
171
+ } catch {
172
+ // start() throws InvalidStateError when already started; treat as running.
173
+ recognitionRunning = true;
174
+ }
175
+ state.sttAvailable = true;
176
+ return true;
177
+ }
178
+
179
+ function stopRecognition({ forSpeech = false } = {}) {
180
+ recognitionPausedForSpeech = forSpeech;
181
+ if (!recognition || !recognitionRunning) return;
182
+ recognitionRunning = false;
183
+ try {
184
+ if (typeof recognition.abort === "function") recognition.abort();
185
+ else recognition.stop();
186
+ } catch {
187
+ // Recognition may already be stopped by the engine.
188
+ }
189
+ }
190
+
191
+ function handleRecognitionEnd() {
192
+ recognitionRunning = false;
193
+ if (!state.active || state.userPaused || recognitionPausedForSpeech || state.uiState === "error") return;
194
+ // Browsers stop recognition spontaneously after silence; keep listening.
195
+ try {
196
+ recognition.start();
197
+ recognitionRunning = true;
198
+ } catch {
199
+ // Engine refused an immediate restart; the next turn end restarts it.
200
+ }
201
+ }
202
+
203
+ function handleRecognitionError(event) {
204
+ const code = String(event?.error || "");
205
+ if (code === "not-allowed" || code === "service-not-allowed") {
206
+ state.lastError = code;
207
+ // Enter the error state before stopping so onend does not auto-restart.
208
+ setUiState("error", { reason: code });
209
+ stopRecognition();
210
+ emitEvent("Microphone access was denied, so Natural Conversation Mode cannot listen. Allow microphone access for this site, then end and restart the conversation.", "error");
211
+ return;
212
+ }
213
+ if (code === "no-speech" || code === "aborted") return;
214
+ emitEvent(`Speech recognition error: ${code || "unknown"}`, "warn");
215
+ }
216
+
217
+ function handleRecognitionResult(event) {
218
+ if (!state.active) return;
219
+ const results = event?.results || [];
220
+ let finalText = "";
221
+ let interimText = "";
222
+ for (let index = event?.resultIndex || 0; index < results.length; index += 1) {
223
+ const result = results[index];
224
+ if (!result) continue;
225
+ const alternative = result[0];
226
+ const text = alternative && typeof alternative.transcript === "string" ? alternative.transcript : "";
227
+ if (result.isFinal) finalText += text;
228
+ else if (text.trim()) interimText += text;
229
+ }
230
+ if (finalText.trim()) {
231
+ clearPartialTranscript();
232
+ handleFinalTranscript(finalText.trim());
233
+ return;
234
+ }
235
+ if (interimText.trim()) {
236
+ setPartialTranscript(interimText.trim());
237
+ if (state.uiState === "listening") setUiState("transcribing");
238
+ }
239
+ }
240
+
241
+ function deliverTranscript(text, reason) {
242
+ Promise.resolve(sendTranscript(text, { reason }))
243
+ .then(() => {
244
+ if (state.active && state.uiState !== "error" && state.uiState !== "off") setUiState("answering", { reason });
245
+ })
246
+ .catch((error) => {
247
+ emitEvent(`Failed to send voice transcript: ${error?.message || error}`, "error");
248
+ if (state.active && state.uiState !== "error") setUiState("listening");
249
+ });
250
+ }
251
+
252
+ function handleFinalTranscript(text) {
253
+ const transcript = String(text || "").trim();
254
+ if (!transcript || !state.active || state.userPaused) return;
255
+ clearPartialTranscript();
256
+ clearSilenceTimer();
257
+ if (state.speaking) {
258
+ // Barge-in: only reachable when bargeInEnabled keeps the mic open during TTS.
259
+ stopSpeaking();
260
+ setUiState("interrupting", { transcript });
261
+ deliverTranscript(transcript, "interrupt");
262
+ return;
263
+ }
264
+ if (state.assistantStreaming && state.toolRunning) {
265
+ state.queuedInterrupt = state.queuedInterrupt ? `${state.queuedInterrupt} ${transcript}` : transcript;
266
+ setUiState("interrupting", { queued: true, transcript });
267
+ emitEvent("Voice interruption queued; it will be delivered after the current tool phase ends.", "info");
268
+ return;
269
+ }
270
+ if (state.assistantStreaming) {
271
+ setUiState("interrupting", { transcript });
272
+ deliverTranscript(transcript, "interrupt");
273
+ return;
274
+ }
275
+ setUiState("answering", { transcript });
276
+ deliverTranscript(transcript, "prompt");
277
+ }
278
+
279
+ function flushQueuedInterrupt() {
280
+ const text = state.queuedInterrupt;
281
+ state.queuedInterrupt = "";
282
+ if (!text || !state.active) return;
283
+ setUiState("interrupting", { queued: true });
284
+ deliverTranscript(text, state.assistantStreaming ? "interrupt" : "prompt");
285
+ }
286
+
287
+ function setAssistantActivity(patch = {}) {
288
+ if (!state.active) return snapshot();
289
+ const wasToolRunning = state.toolRunning;
290
+ const wasStreaming = state.assistantStreaming;
291
+ if (typeof patch.streaming === "boolean") state.assistantStreaming = patch.streaming;
292
+ if (typeof patch.toolRunning === "boolean") state.toolRunning = patch.toolRunning;
293
+ if (state.assistantStreaming && !wasStreaming) {
294
+ clearSilenceTimer();
295
+ if (!state.userPaused && !state.speaking && state.uiState !== "interrupting") setUiState("answering");
296
+ }
297
+ if (wasToolRunning && !state.toolRunning && state.queuedInterrupt) flushQueuedInterrupt();
298
+ else if (wasStreaming && !state.assistantStreaming && state.queuedInterrupt) flushQueuedInterrupt();
299
+ return snapshot();
300
+ }
301
+
302
+ function stopSpeaking() {
303
+ const utterance = currentUtterance;
304
+ currentUtterance = null;
305
+ state.speaking = false;
306
+ recognitionPausedForSpeech = false;
307
+ if (utterance) {
308
+ utterance.onend = null;
309
+ utterance.onerror = null;
310
+ }
311
+ try {
312
+ synthesis?.cancel?.();
313
+ } catch {
314
+ // Synthesis may already be idle.
315
+ }
316
+ }
317
+
318
+ function resumeListeningAfterTurn({ askedQuestion = false } = {}) {
319
+ if (!state.active) return;
320
+ if (state.userPaused) {
321
+ setUiState("paused", { reason: "manual" });
322
+ return;
323
+ }
324
+ const listening = startRecognition();
325
+ if (listening) setUiState("listening");
326
+ else if (state.uiState !== "error") setUiState("paused", { reason: "stt-unavailable" });
327
+ if (askedQuestion && listening) startSilenceTimer();
328
+ }
329
+
330
+ function speak(text, { askedQuestion = false } = {}) {
331
+ const spoken = String(text || "").trim();
332
+ if (state.userPaused) return;
333
+ if (!spoken || !state.ttsAvailable) {
334
+ resumeListeningAfterTurn({ askedQuestion: askedQuestion && !!spoken });
335
+ return;
336
+ }
337
+ stopSpeaking();
338
+ if (!bargeInEnabled) stopRecognition({ forSpeech: true });
339
+ let utterance = null;
340
+ try {
341
+ utterance = utteranceFactory(spoken);
342
+ } catch {
343
+ utterance = null;
344
+ }
345
+ if (!utterance) {
346
+ resumeListeningAfterTurn({ askedQuestion });
347
+ return;
348
+ }
349
+ state.speaking = true;
350
+ setUiState("speaking");
351
+ currentUtterance = utterance;
352
+ const finish = () => {
353
+ if (currentUtterance !== utterance) return;
354
+ currentUtterance = null;
355
+ state.speaking = false;
356
+ recognitionPausedForSpeech = false;
357
+ if (!state.active) return;
358
+ resumeListeningAfterTurn({ askedQuestion });
359
+ };
360
+ utterance.onend = finish;
361
+ utterance.onerror = finish;
362
+ try {
363
+ synthesis.speak(utterance);
364
+ } catch (error) {
365
+ emitEvent(`Speech synthesis failed: ${error?.message || error}`, "warn");
366
+ finish();
367
+ }
368
+ }
369
+
370
+ function handleAssistantTurnEnd(finalText, { askedQuestion = false } = {}) {
371
+ if (!state.active) return snapshot();
372
+ state.assistantStreaming = false;
373
+ state.toolRunning = false;
374
+ if (state.userPaused) return snapshot();
375
+ if (state.queuedInterrupt) {
376
+ flushQueuedInterrupt();
377
+ return snapshot();
378
+ }
379
+ speak(finalText, { askedQuestion });
380
+ return snapshot();
381
+ }
382
+
383
+ function handleUserActivity() {
384
+ clearSilenceTimer();
385
+ }
386
+
387
+ function start() {
388
+ if (state.active) return snapshot();
389
+ state.active = true;
390
+ state.userPaused = false;
391
+ state.queuedInterrupt = "";
392
+ state.assistantStreaming = false;
393
+ state.toolRunning = false;
394
+ state.lastError = "";
395
+ const listening = startRecognition();
396
+ if (listening) {
397
+ setUiState("listening");
398
+ } else if (state.ttsAvailable) {
399
+ setUiState("paused", { reason: "stt-unavailable" });
400
+ emitEvent("Browser speech recognition is unavailable here; Pi answers will still be spoken, but the microphone stays off. Type prompts normally or configure another STT provider in a later phase.", "warn");
401
+ } else {
402
+ setUiState("error", { reason: "speech-unsupported" });
403
+ emitEvent("This browser exposes neither speech recognition nor speech synthesis, so the Natural Conversation voice loop cannot run.", "error");
404
+ }
405
+ return snapshot();
406
+ }
407
+
408
+ function pause({ reason = "manual" } = {}) {
409
+ if (!state.active) return snapshot();
410
+ state.userPaused = true;
411
+ clearSilenceTimer();
412
+ clearPartialTranscript();
413
+ stopSpeaking();
414
+ stopRecognition({ forSpeech: true });
415
+ setUiState("paused", { reason });
416
+ return snapshot();
417
+ }
418
+
419
+ function resume() {
420
+ if (!state.active) return snapshot();
421
+ state.userPaused = false;
422
+ recognitionPausedForSpeech = false;
423
+ if (state.assistantStreaming) {
424
+ if (!state.toolRunning) startRecognition();
425
+ setUiState("answering", { reason: "manual-resume" });
426
+ return snapshot();
427
+ }
428
+ resumeListeningAfterTurn();
429
+ return snapshot();
430
+ }
431
+
432
+ function togglePaused() {
433
+ return state.userPaused ? resume() : pause();
434
+ }
435
+
436
+ function stop() {
437
+ if (!state.active) {
438
+ state.uiState = "off";
439
+ return snapshot();
440
+ }
441
+ state.active = false;
442
+ state.userPaused = false;
443
+ clearSilenceTimer();
444
+ clearPartialTranscript();
445
+ stopSpeaking();
446
+ stopRecognition();
447
+ state.assistantStreaming = false;
448
+ state.toolRunning = false;
449
+ state.queuedInterrupt = "";
450
+ setUiState("off");
451
+ return snapshot();
452
+ }
453
+
454
+ return {
455
+ start,
456
+ stop,
457
+ pause,
458
+ resume,
459
+ togglePaused,
460
+ getState: snapshot,
461
+ isActive: () => state.active,
462
+ setAssistantActivity,
463
+ handleAssistantTurnEnd,
464
+ handleUserActivity,
465
+ };
466
+ }
@@ -0,0 +1,114 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { chmod, mkdtemp, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import { setTimeout as delay } from "node:timers/promises";
7
+ import { dirname, join } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
11
+ const serverScript = join(root, "bin", "pi-webui.mjs");
12
+ const compactingPi = join(root, "tests", "fixtures", "compacting-pi.mjs");
13
+ const port = 30000 + Math.floor(Math.random() * 20000);
14
+ const COMPACTION_TRIGGER = "__pi_webui_test_start_compaction__";
15
+ const RESUME_PROMPT = "resume automatically after compaction";
16
+
17
+ async function request(pathname, { method = "GET", body, timeoutMs = 5_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 {
26
+ payload = await response.json();
27
+ } catch {
28
+ payload = undefined;
29
+ }
30
+ return { status: response.status, body: payload };
31
+ }
32
+
33
+ async function waitFor(description, probe, { attempts = 60, intervalMs = 100 } = {}) {
34
+ let last;
35
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
36
+ last = await probe();
37
+ if (last) return last;
38
+ await delay(intervalMs);
39
+ }
40
+ assert.fail(`${description} did not happen in time${last ? `; last=${JSON.stringify(last)}` : ""}`);
41
+ }
42
+
43
+ const cwd = await mkdtemp(path.join(tmpdir(), "pi-webui-compaction-resume-"));
44
+ const settingsFile = path.join(cwd, "webui-settings.json");
45
+ await chmod(compactingPi, 0o755);
46
+
47
+ const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "127.0.0.1", "--port", String(port), "--pi", compactingPi], {
48
+ stdio: ["ignore", "pipe", "pipe"],
49
+ env: { ...process.env, PI_WEBUI_SETTINGS_FILE: settingsFile },
50
+ });
51
+ let serverOutput = "";
52
+ child.stdout.on("data", (chunk) => { serverOutput += String(chunk); });
53
+ child.stderr.on("data", (chunk) => { serverOutput += String(chunk); });
54
+
55
+ try {
56
+ await waitFor("server health", async () => {
57
+ if (child.exitCode !== null) return false;
58
+ try {
59
+ const health = await request("/api/health", { timeoutMs: 1_000 });
60
+ return health.status === 200 && health.body?.ok === true ? health : false;
61
+ } catch {
62
+ return false;
63
+ }
64
+ }, { attempts: 100, intervalMs: 120 });
65
+
66
+ const tabsResponse = await request("/api/tabs");
67
+ assert.equal(tabsResponse.status, 200);
68
+ const tabId = tabsResponse.body?.data?.tabs?.[0]?.id || tabsResponse.body?.tabs?.[0]?.id;
69
+ assert.ok(tabId, "startup tab should have an id");
70
+
71
+ const startCompaction = await request("/api/prompt", {
72
+ method: "POST",
73
+ body: { tab: tabId, message: COMPACTION_TRIGGER },
74
+ });
75
+ assert.equal(startCompaction.status, 200, `compaction trigger should be accepted: ${startCompaction.body?.error || serverOutput}`);
76
+
77
+ await waitFor("compaction_start state", async () => {
78
+ const state = await request(`/api/state?tab=${encodeURIComponent(tabId)}`);
79
+ return state.body?.data?.isCompacting === true ? state : false;
80
+ });
81
+
82
+ const queuedPrompt = await request("/api/prompt", {
83
+ method: "POST",
84
+ body: { tab: tabId, message: RESUME_PROMPT },
85
+ });
86
+ assert.equal(queuedPrompt.status, 202, "prompt sent during compaction should be accepted into the Web UI resume queue");
87
+ assert.equal(queuedPrompt.body?.data?.queuedFor, "compaction");
88
+ assert.equal(queuedPrompt.body?.data?.queueLength, 1);
89
+
90
+ const messagesBeforeEnd = await request(`/api/messages?tab=${encodeURIComponent(tabId)}`);
91
+ assert.equal(messagesBeforeEnd.status, 200);
92
+ assert.equal((messagesBeforeEnd.body?.data?.messages || []).some((message) => String(message.content || "").includes(RESUME_PROMPT)), false, "queued prompt should not reach Pi before compaction_end");
93
+
94
+ await waitFor("compaction to finish", async () => {
95
+ const state = await request(`/api/state?tab=${encodeURIComponent(tabId)}`);
96
+ return state.body?.data?.isCompacting === false ? state : false;
97
+ }, { attempts: 80, intervalMs: 100 });
98
+
99
+ const resumedMessages = await waitFor("queued prompt to resume after compaction", async () => {
100
+ const messages = await request(`/api/messages?tab=${encodeURIComponent(tabId)}`);
101
+ const entries = messages.body?.data?.messages || [];
102
+ return entries.some((message) => String(message.content || "").includes(`prompt:${RESUME_PROMPT}`)) ? messages : false;
103
+ }, { attempts: 80, intervalMs: 100 });
104
+ assert.equal(resumedMessages.status, 200);
105
+
106
+ await request("/api/shutdown", { method: "POST" }).catch(() => undefined);
107
+ for (let attempt = 0; attempt < 50 && child.exitCode === null; attempt += 1) await delay(100);
108
+ assert.notEqual(child.exitCode, null, "server should exit after /api/shutdown");
109
+ } finally {
110
+ if (child.exitCode === null) child.kill("SIGKILL");
111
+ await rm(cwd, { recursive: true, force: true });
112
+ }
113
+
114
+ console.log("compaction-resume-harness.test.mjs passed");
@@ -0,0 +1,25 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const [server, app] = await Promise.all([
8
+ readFile(join(root, "bin", "pi-webui.mjs"), "utf8"),
9
+ readFile(join(root, "public", "app.js"), "utf8"),
10
+ ]);
11
+
12
+ assert.match(server, /function maybeQueueCommandDuringCompaction\(tab, command\)[\s\S]*tab\?\.lastState\?\.isCompacting[\s\S]*enqueueCommandUntilCompactionEnds/, "server should queue prompt-like commands while the tab is compacting");
13
+ assert.match(server, /url\.pathname === "\/api\/prompt" && req\.method === "POST"[\s\S]*maybeQueueCommandDuringCompaction\(tab, command\)[\s\S]*sendJson\(res, 202/, "POST /api/prompt should return 202 when a prompt is queued for post-compaction resume");
14
+ assert.match(server, /if \(command\) \{[\s\S]*maybeQueueCommandDuringCompaction\(tab, command\)[\s\S]*sendJson\(res, 202/, "generic prompt-like POST commands should share the compaction queue path");
15
+ assert.match(server, /event\?\.type === "compaction_end" && event\.aborted !== true\)[\s\S]*flushCompactionQueue\(tab, event\)/, "non-aborted compaction_end should flush the queued resume prompt");
16
+ assert.match(server, /async function flushCompactionQueue\(tab, event = \{\}\)[\s\S]*queuedRetryCommand\(item\)/, "compaction queue flush should resume queued commands into active auto-retry runs");
17
+ assert.match(server, /async function flushCompactionQueue\(tab, event = \{\}\)[\s\S]*queuedPromptCommand\(item\)/, "compaction queue flush should start a new prompt when no run resumes automatically");
18
+ assert.match(server, /async function flushCompactionQueue\(tab, event = \{\}\)[\s\S]*queuedStreamingCommand\(item\)/, "compaction queue flush should send later queued items as steering or follow-up messages");
19
+ assert.match(server, /function stateWithPendingThinking\(tab, state\)[\s\S]*compactionQueueForTab\(tab\)\.length[\s\S]*pendingMessageCount/, "state responses should include Web UI compaction queue length while prompts wait to resume");
20
+
21
+ assert.match(app, /function isRunActive\(\) \{\n\s+return !!currentState\?\.isStreaming \|\| !!currentState\?\.isCompacting/, "frontend should treat compaction as an active run for composer controls");
22
+ assert.match(app, /const targetWasCompacting = !!currentState\?\.isCompacting;[\s\S]*const targetWasBusy = targetWasStreaming \|\| targetWasCompacting[\s\S]*if \(targetWasBusy\) body\.streamingBehavior = streamingBehavior \|\| busyBehavior/, "prompt send should use busy behavior while streaming or compacting");
23
+ assert.match(app, /case "webui_compaction_queue_update":[\s\S]*renderQueue\(event\)[\s\S]*queued compaction prompt sent; Pi is resuming/, "frontend should surface compaction queue and resume events");
24
+
25
+ console.log("compaction-static.test.mjs passed");