@firstpick/pi-package-webui 0.5.9 → 0.6.1

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.
@@ -1,5 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { spawn, spawnSync } from "node:child_process";
3
+ import { createServer } from "node:http";
3
4
  import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
4
5
  import { networkInterfaces, tmpdir } from "node:os";
5
6
  import path from "node:path";
@@ -72,6 +73,28 @@ const cwd = await mkdtemp(path.join(tmpdir(), "pi-webui-http-harness-"));
72
73
  const settingsFile = path.join(cwd, "webui-settings.json");
73
74
  await chmod(fakePi, 0o755);
74
75
 
76
+ const voiceProviderRequests = [];
77
+ const voiceProvider = createServer(async (req, res) => {
78
+ const chunks = [];
79
+ for await (const chunk of req) chunks.push(chunk);
80
+ const body = Buffer.concat(chunks);
81
+ voiceProviderRequests.push({ method: req.method, url: req.url, contentType: req.headers["content-type"], bodyLength: body.length });
82
+ if (req.url === "/stt") {
83
+ res.writeHead(200, { "content-type": "application/json" });
84
+ res.end(JSON.stringify({ text: "fake transcript from local stt" }));
85
+ return;
86
+ }
87
+ if (req.url === "/tts") {
88
+ res.writeHead(200, { "content-type": "audio/mpeg" });
89
+ res.end(Buffer.from("fake mp3 bytes"));
90
+ return;
91
+ }
92
+ res.writeHead(404, { "content-type": "application/json" });
93
+ res.end(JSON.stringify({ error: "not found" }));
94
+ });
95
+ await new Promise((resolve) => voiceProvider.listen(0, "127.0.0.1", resolve));
96
+ const voiceProviderPort = voiceProvider.address().port;
97
+
75
98
  const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "0.0.0.0", "--port", String(port), "--pi", fakePi], {
76
99
  stdio: ["ignore", "pipe", "pipe"],
77
100
  env: {
@@ -81,6 +104,8 @@ const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "0.
81
104
  GIT_COMMITTER_NAME: "Pi WebUI Test",
82
105
  GIT_COMMITTER_EMAIL: "pi-webui-test@example.invalid",
83
106
  PI_WEBUI_SETTINGS_FILE: settingsFile,
107
+ PI_VOICE_STT_URL: `http://127.0.0.1:${voiceProviderPort}/stt`,
108
+ PI_VOICE_TTS_URL: `http://127.0.0.1:${voiceProviderPort}/tts`,
84
109
  },
85
110
  });
86
111
  let serverOutput = "";
@@ -140,6 +165,17 @@ try {
140
165
  assert.equal(gzipResponse.headers.get("content-encoding"), "gzip", "styles.css should fall back to gzip");
141
166
  await gzipResponse.arrayBuffer();
142
167
 
168
+ // The browser voice loop is dynamically imported by app.js; a missing static
169
+ // allowlist entry would 404 the module and silently disable voice mode.
170
+ const voiceModuleResponse = await fetch(`http://127.0.0.1:${port}/voice-conversation.mjs`, {
171
+ signal: AbortSignal.timeout(5_000),
172
+ });
173
+ assert.equal(voiceModuleResponse.status, 200, "voice-conversation.mjs must be served for the Natural Conversation browser voice loop");
174
+ assert.match(voiceModuleResponse.headers.get("content-type") || "", /text\/javascript/, "voice-conversation.mjs should use a JavaScript MIME type");
175
+ const voiceModuleBody = await voiceModuleResponse.arrayBuffer();
176
+ const rawVoiceModuleSize = (await stat(join(root, "public", "voice-conversation.mjs"))).size;
177
+ assert.equal(voiceModuleBody.byteLength, rawVoiceModuleSize, "served voice-conversation.mjs should match the raw file byte-for-byte in size");
178
+
143
179
  const mermaidModuleResponse = await fetch(`http://127.0.0.1:${port}/vendor/mermaid/mermaid.esm.min.mjs`, {
144
180
  signal: AbortSignal.timeout(5_000),
145
181
  });
@@ -665,6 +701,19 @@ try {
665
701
  assert.ok(conversationFeature.body?.data?.commands?.includes("talk"), "Natural Conversation feature data should expose loaded /talk commands");
666
702
  assert.equal(conversationFeature.body?.data?.mode?.enabled, false, "Natural Conversation should start disabled per tab");
667
703
 
704
+ const conversationVoices = await request("127.0.0.1", `/api/conversation-voices?tab=${encodeURIComponent(tabId)}`);
705
+ assert.equal(conversationVoices.status, 200);
706
+ assert.ok(Array.isArray(conversationVoices.body?.data?.voices), "conversation-voices should return a voices array");
707
+ assert.ok(
708
+ conversationVoices.body.data.voices.some((voice) => voice.id === "de_DE-thorsten-medium"),
709
+ "conversation-voices should include the mirrored Piper catalog",
710
+ );
711
+ const badVoice = await request("127.0.0.1", "/api/conversation-voice", {
712
+ method: "POST",
713
+ body: { voice: "../etc/passwd; rm -rf", tab: tabId },
714
+ });
715
+ assert.equal(badVoice.status, 400, "conversation-voice must reject ids that are not plain voice names");
716
+
668
717
  const conversationOn = await request("127.0.0.1", "/api/conversation-mode", {
669
718
  method: "POST",
670
719
  body: { enabled: true, tab: tabId },
@@ -692,9 +741,18 @@ try {
692
741
  const allowedConversationPrompt = await request("127.0.0.1", "/api/prompt", { method: "POST", body: { message: "Explain the current repo briefly", tab: tabId } });
693
742
  assert.equal(allowedConversationPrompt.status, 200, "ordinary prompts remain allowed while Natural Conversation is active");
694
743
 
695
- const sttPlaceholder = await request("127.0.0.1", "/api/stt/transcribe", { method: "POST", body: { tab: tabId } });
696
- assert.equal(sttPlaceholder.status, 501, "hosted/local STT placeholder route should be explicit and non-operational");
697
- assert.match(String(sttPlaceholder.body?.error || ""), /STT\/TTS fallbacks are not implemented/);
744
+ const localStt = await request("127.0.0.1", "/api/stt/transcribe", { method: "POST", body: { tab: tabId, provider: "local", mimeType: "audio/webm", audioBase64: Buffer.from("fake audio").toString("base64") } });
745
+ assert.equal(localStt.status, 200, `local STT fallback should transcribe through the configured endpoint: ${localStt.body?.error || ""}`);
746
+ assert.equal(localStt.body?.data?.provider, "local");
747
+ assert.equal(localStt.body?.data?.text, "fake transcript from local stt");
748
+ assert.ok(voiceProviderRequests.some((item) => item.url === "/stt" && /multipart\/form-data/.test(String(item.contentType || ""))), "local STT should receive a multipart audio upload");
749
+
750
+ const localTts = await request("127.0.0.1", "/api/tts/speech", { method: "POST", body: { tab: tabId, provider: "local", text: "Say this aloud" } });
751
+ assert.equal(localTts.status, 200, `local TTS fallback should synthesize through the configured endpoint: ${localTts.body?.error || ""}`);
752
+ assert.equal(localTts.body?.data?.provider, "local");
753
+ assert.equal(localTts.body?.data?.contentType, "audio/mpeg");
754
+ assert.equal(Buffer.from(localTts.body?.data?.audioBase64 || "", "base64").toString("utf8"), "fake mp3 bytes");
755
+ assert.ok(voiceProviderRequests.some((item) => item.url === "/tts" && /application\/json/.test(String(item.contentType || ""))), "local TTS should receive a JSON text synthesis request");
698
756
 
699
757
  const conversationOff = await request("127.0.0.1", "/api/conversation-mode", {
700
758
  method: "POST",
@@ -738,6 +796,20 @@ try {
738
796
  const remoteHealthBeforeAuth = await request(lan, "/api/health");
739
797
  assert.equal(remoteHealthBeforeAuth.status, 200, "LAN clients should connect without a PIN while auth is off");
740
798
 
799
+ const remoteSttWithoutConsent = await request(lan, "/api/stt/transcribe", {
800
+ method: "POST",
801
+ body: { tab: tabId, provider: "local", mimeType: "audio/webm", audioBase64: Buffer.from("fake remote audio").toString("base64") },
802
+ });
803
+ assert.equal(remoteSttWithoutConsent.status, 403, "remote STT uploads must require explicit microphone streaming consent");
804
+ assert.match(String(remoteSttWithoutConsent.body?.error || ""), /explicit.*remote microphone streaming consent/i);
805
+
806
+ const remoteSttWithConsent = await request(lan, "/api/stt/transcribe", {
807
+ method: "POST",
808
+ body: { tab: tabId, provider: "local", mimeType: "audio/webm", audioBase64: Buffer.from("fake remote audio").toString("base64"), remoteMicStreamingConsentAccepted: true },
809
+ });
810
+ assert.equal(remoteSttWithConsent.status, 200, "remote STT uploads should proceed after explicit per-request consent");
811
+ assert.equal(remoteSttWithConsent.body?.data?.text, "fake transcript from local stt");
812
+
741
813
  const remoteDelete = await request(lan, "/api/session-delete", {
742
814
  method: "POST",
743
815
  body: { sessionPath: path.join(cwd, "outside.jsonl"), confirmed: true, tab: tabId },
@@ -829,6 +901,7 @@ try {
829
901
  child.kill("SIGKILL");
830
902
  await new Promise((resolve) => child.once("exit", resolve));
831
903
  }
904
+ await new Promise((resolve) => voiceProvider.close(() => resolve()));
832
905
  await rmWithRetry(cwd);
833
906
  }
834
907
 
@@ -157,6 +157,21 @@ assert.ok(
157
157
  assert.match(html, /id="optionsConversationModeButton"[^>]*data-command="\/talk"[^>]*hidden[\s\S]*?<span>Start Conversation<\/span>/, "Options menu should include the feature-gated Natural Conversation toggle");
158
158
  assert.match(html, /id="conversationModeChip" class="composer-conversation-mode-chip"[\s\S]*hidden>Voice: off<\/button>/, "composer should expose a hidden-until-active conversation status chip");
159
159
  assert.match(html, /id="conversationModeEndButton" class="composer-conversation-end-button"[\s\S]*hidden>End conversation<\/button>/, "composer should expose a persistent End conversation button while active");
160
+ assert.match(html, /id="conversationVoiceMenu" class="composer-publish-menu composer-conversation-voice-menu" hidden>[\s\S]*id="conversationVoiceButton"[\s\S]*id="conversationVoiceMenuPanel" class="composer-publish-menu-panel[\s\S]*id="conversationModeEndButton"/, "composer should expose the conversation voice menu (publish-menu pattern) next to the End conversation button");
161
+ assert.match(app, /conversationVoiceMenuPanel: \$\("#conversationVoiceMenuPanel"\)/, "frontend should register the conversation voice menu panel");
162
+ assert.match(app, /\/api\/conversation-voices/, "frontend should load the Piper voice list from the server");
163
+ assert.match(app, /\/api\/conversation-voice"/, "frontend should switch voices through the conversation-voice endpoint");
164
+ assert.match(app, /void switchConversationVoice\(voice\.id\);/, "voice menu item clicks should trigger the voice switch");
165
+ assert.match(app, /elements\.conversationVoiceButton\?\.addEventListener\("click", \(\) => \{\n\s*setConversationVoiceMenuOpen\(!conversationVoiceMenuOpen\);/, "voice menu must open on click like the Common-Pi-options menu (touch devices have no hover)");
166
+ assert.match(app, /\{ menu: elements\.conversationVoiceMenu, button: elements\.conversationVoiceButton, panel: elements\.conversationVoiceMenuPanel \}/, "voice menu should participate in mobile dropdown height bounding");
167
+ assert.match(app, /function conversationVoiceLanguageLabel\(voiceId\)/, "voice labels should include a compact DE/EN language indicator");
168
+ assert.match(app, /function conversationVoiceGenderLabel\(voiceId\)/, "voice labels should include a compact M/F gender indicator");
169
+ assert.match(app, /\$\{label\} ↓\$\{conversationVoiceDownloadSizeText\(voice\)\}/, "voices that are not downloaded yet should use compact labels with a download marker and size");
170
+ assert.match(app, /showConversationVoiceFeedback/, "voice selection and download should surface explicit user feedback");
171
+ assert.match(app, /event\.stopPropagation\(\);\n\s*void switchConversationVoice\(voice\.id\);/, "voice menu item clicks should not be swallowed by surrounding dropdown handlers");
172
+ assert.match(app, /downloading\|testing/, "voice-switch progress from the package status text should surface on the conversation chip");
173
+ assert.match(app, /function nativeConversationAudioEngaged\(\)[\s\S]*widgets\.has\("natural-conversation-audio"\)/, "frontend should detect the package's native audio loop via its widget");
174
+ assert.match(app, /mode\.enabled === true && !!activeTabId && !nativeConversationAudioEngaged\(\)/, "browser Web Speech loop must stand down while native audio is armed (no double voices)");
160
175
  assert.match(html, /id="appRunnerMenuPanel"[^>]*aria-label="Detected app runners"/, "app-runner dropdown should render detected runner choices only from JS data");
161
176
  assert.match(html, /id="appRunnerInfoDialog"[\s\S]*id="appRunnerInfoBody"/, "app-runner explanation popup should have a dynamic details body");
162
177
  assert.match(app, /\.pi-webui-runners\.json/, "app-runner popup should explain the project-local custom runner config file");
@@ -298,7 +313,7 @@ assert.match(css, /\.composer-publish-menu:hover > \.composer-publish-button\[da
298
313
  assert.match(css, /\.composer-publish-menu-panel \{[\s\S]*?display:\s*none;[\s\S]*?flex-direction:\s*column/, "Publish workflow menu should hide when closed and expand like grouped tabs");
299
314
  assert.match(css, /\.composer-publish-menu:hover \.composer-publish-menu-panel,[\s\S]*?\.composer-publish-menu:focus-within \.composer-publish-menu-panel,[\s\S]*?\.composer-publish-menu\.open \.composer-publish-menu-panel \{\n\s+display:\s*flex;/, "Publish workflow menu should open on hover, focus, or explicit open state");
300
315
  assert.match(css, /\.composer-native-command-button \{[\s\S]*?color:\s*var\(--ctp-mauve\)/, "skills/tools command menu should have a distinct slash-command button style");
301
- assert.match(css, /\.composer-options-menu-panel \{[\s\S]*?max-height:\s*min\(calc\(var\(--visual-viewport-height, 100dvh\) - 2rem\), 44rem\)/, "Options menu should be tall enough for common commands without scrolling on normal viewports");
316
+ assert.match(css, /\.composer-options-menu-panel \{[\s\S]*?max-height:\s*min\(calc\(var\(--visual-viewport-height, 100dvh\) - 2rem\), 48rem\)/, "Options menu should be tall enough for common commands without scrolling on normal viewports");
302
317
  assert.match(css, /\.composer-publish-menu-panel \{[\s\S]*?overscroll-behavior:\s*contain;[\s\S]*?-webkit-overflow-scrolling:\s*touch/, "dropdown panels should use contained momentum scrolling when their options overflow");
303
318
  assert.match(css, /\.composer-actions-panel > \.composer-publish-menu \.composer-publish-menu-panel \{[\s\S]*?max-height:\s*min\(var\(--mobile-dropdown-max-height, 34dvh\), calc\(var\(--visual-viewport-height, 100dvh\) - 2rem\)\)/, "mobile composer dropdowns should clamp to an in-viewport scroll height");
304
319
  assert.match(css, /\.composer-actions-panel > \.composer-options-menu \.composer-publish-menu-panel,\n\s+\.composer-actions-panel > \.composer-app-runner-menu \.composer-publish-menu-panel \{\n\s+inset-inline:\s*auto 0;/, "mobile Options and app-runner dropdowns should share the clamped scrollable popover placement");
@@ -403,6 +418,9 @@ assert.match(css, /(?:^|\n)\s*\.side-panel\s*\{[\s\S]*?position:\s*fixed/, "mobi
403
418
  assert.match(css, /\.extension-dialog[\s\S]*?max-height:\s*calc\(var\(--visual-viewport-height/, "dialogs should fit the visual viewport on mobile");
404
419
  assert.match(css, /\.extension-dialog[\s\S]*?inset:\s*auto 0 0 0/, "mobile dialogs should behave like bottom sheets");
405
420
  assert.match(css, /#dialogMessage \{[\s\S]*?white-space:\s*pre-wrap/, "extension dialog messages should preserve multiline prompts");
421
+ assert.match(css, /\.edit-retry-dialog \{[\s\S]*?width:\s*min\(44rem, calc\(100vw - 2rem\)\);[\s\S]*?max-height:\s*calc\(var\(--visual-viewport-height, 100dvh\) - 2rem\);[\s\S]*?overflow:\s*hidden/, "edit/retry dialog should stay bounded by the viewport instead of bleeding off-screen");
422
+ assert.match(css, /\.edit-retry-dialog form \{[\s\S]*?display:\s*grid;[\s\S]*?grid-template-rows:\s*auto auto minmax\(0, 1fr\) auto auto;[\s\S]*?max-height:\s*calc\(var\(--visual-viewport-height, 100dvh\) - 4rem\);[\s\S]*?min-height:\s*0/, "edit/retry dialog form should let the editor row shrink inside the modal");
423
+ assert.match(css, /\.edit-retry-text \{[\s\S]*?min-width:\s*0;[\s\S]*?max-height:\s*min\(32rem, 48vh\);[\s\S]*?overflow-x:\s*hidden;[\s\S]*?overflow-y:\s*auto;[\s\S]*?overflow-wrap:\s*anywhere;[\s\S]*?white-space:\s*pre-wrap/, "edit/retry editor should wrap long prompts and scroll vertically without expanding the modal");
406
424
  assert.match(css, /\.native-command-dialog \{[\s\S]*?width:\s*min\(56rem/, "native slash selector dialog should have roomy desktop layout");
407
425
  assert.match(css, /\.extension-dialog\.remote-qr-dialog \{[\s\S]*?width:\s*min\(34rem/, "remote QR popup should have a bounded modal layout");
408
426
  assert.match(css, /\.remote-qr-loading \{[\s\S]*?display:\s*flex/, "remote QR popup should style its loading placeholder");
@@ -496,11 +514,13 @@ assert.match(server, /url\.pathname === "\/api\/restart" && req\.method === "POS
496
514
  assert.match(server, /PI_WEBUI_RESTORE_TABS: JSON\.stringify\(restorableTabs \|\| \[\]\)/, "server restart should preserve restorable tab metadata");
497
515
  assert.match(server, /if \(webuiDevServer\) env\.PI_WEBUI_DEV = "1";/, "server restart should explicitly preserve dev mode");
498
516
  assert.match(server, /const updateArgs = all \? \["update", "--all"\] : \["update"\]/, "server update should use pi update by default and pi update --all for package-inclusive updates");
499
- assert.match(server, /async function resolveUpdateTasks\(\{ all = false \} = \{\}\)[\s\S]*await resolvePiUpdateCommand\(\{ all \}\)/, "server update should resolve a single Pi update command with the selected all mode");
517
+ assert.match(server, /async function resolveUpdateTasks\(\{ all = false \} = \{\}\)[\s\S]*if \(!all\) return uniqueUpdateTasks\(\[piTask\]\)[\s\S]*currentWebuiPackageUpdateTask\(\)[\s\S]*agentPackageRootUpdateTask\(\)[\s\S]*projectPackageRootUpdateTasks\(\)[\s\S]*npmGlobalPackageRootUpdateTask\(\)[\s\S]*bunGlobalPackageRootUpdateTask\(\)/, "server all-update should run pi update plus detected local/global Pi package root tasks");
518
+ assert.match(server, /const UPDATE_PACKAGE_NAMES = \[\.\.\.new Set\(\[[\s\S]*WEBUI_CONTROLLED_PACKAGES[\s\S]*OPTIONAL_FEATURE_PACKAGES\.values\(\)/, "package-inclusive updates should include Web UI controlled Optional Feature packages");
500
519
  assert.match(app, /const command = all \? "pi update --all" : "pi update"/, "frontend update confirmation should describe self-only and all update commands");
520
+ assert.match(app, /Optional Features, and detected Pi package roots/, "frontend all-update confirmation should describe optional-feature and detected-root coverage");
501
521
  assert.match(app, /api\(all \? "\/api\/update\?all=1" : "\/api\/update"/, "frontend all update should call the explicit all-mode endpoint");
502
522
  assert.match(html, /<option value="update-all">Update Pi \+ Packages &amp; Restart<\/option>/, "side panel should expose pi update --all as a separate server action");
503
- assert.match(readme, /`pi update` for Pi-only updates[\s\S]*`pi update --all` for Pi plus configured packages/, "README should document self-only and all update modes");
523
+ assert.match(readme, /`pi update` for Pi-only updates[\s\S]*`pi update --all` plus detected Web UI\/Optional Feature package-root updates/, "README should document self-only and expanded all update modes");
504
524
  assert.match(server, /async function closeNetworkAccess\(\)/, "server should expose a local-only rebind helper for closing network access");
505
525
  assert.match(server, /url\.pathname === "\/api\/network\/close" && req\.method === "POST"/, "server should route network close requests");
506
526
  assert.match(server, /server\.closeAllConnections\?\.\(\)/, "network rebind should force-close long-lived clients so close-to-localhost can complete");
@@ -704,6 +724,35 @@ assert.match(app, /const conversationModeByTab = new Map\(\)/, "frontend should
704
724
  assert.match(app, /function defaultConversationModeState[\s\S]*allowedTools: \["read", "grep", "find", "ls"\]/, "frontend Natural Conversation defaults should mirror the read-only tool allowlist");
705
725
  assert.match(app, /function renderConversationModeControls\(\)[\s\S]*document\.body\.classList\.toggle\("conversation-mode-active", active\)[\s\S]*optionsConversationModeButton[\s\S]*conversationModeChip[\s\S]*conversationModeEndButton/, "frontend should render active Natural Conversation controls and page\/composer state");
706
726
  assert.match(app, /async function setNaturalConversationModeEnabled\(enabled\)[\s\S]*api\("\/api\/conversation-mode", \{ method: "POST"/, "frontend Natural Conversation toggle should use the WebUI shell endpoint");
727
+ // Phase 3: browser voice loop (Web Speech STT/TTS) wiring.
728
+ const voiceModule = await readFile(join(root, "public", "voice-conversation.mjs"), "utf8");
729
+ assert.match(voiceModule, /export function createVoiceConversationController\(options = \{\}\)/, "voice loop should live in a dependency-injected module for Node tests");
730
+ assert.match(voiceModule, /if \(state\.assistantStreaming && state\.toolRunning\) \{[\s\S]*queuedInterrupt/, "voice transcripts during tool phases must be queued, not injected");
731
+ assert.match(voiceModule, /if \(!bargeInEnabled\) stopRecognition\(\{ forSpeech: true \}\)/, "microphone must pause during TTS unless barge-in is enabled");
732
+ assert.match(voiceModule, /function pause\(\{ reason = "manual" \} = \{\}\)[\s\S]*stopRecognition\(\{ forSpeech: true \}\)[\s\S]*setUiState\("paused"/, "voice loop should support manual pause without disabling safe mode");
733
+ assert.match(voiceModule, /function resume\(\)[\s\S]*state\.userPaused = false[\s\S]*resumeListeningAfterTurn\(\)/, "voice loop should support manual resume back to listening");
734
+ assert.match(voiceModule, /togglePaused/, "voice controller should expose a pause/resume toggle");
735
+ assert.match(voiceModule, /if \(!transcript \|\| !state\.active \|\| state\.userPaused\) return/, "paused voice loop should drop speech transcripts");
736
+ assert.match(voiceModule, /if \(state\.userPaused\) return snapshot\(\)/, "paused voice loop should not speak a completed assistant turn");
737
+ assert.match(voiceModule, /export function voiceSilenceEventMessage/, "silence events should use a shared structured message");
738
+ assert.match(app, /import\("\.\/voice-conversation\.mjs\?v=\d+"\)/, "app.js should lazy-load the voice module with a cache-busted dynamic import");
739
+ assert.match(app, /function syncVoiceConversationLoop\(\)[\s\S]*stopVoiceConversationLoop\(\)[\s\S]*startVoiceConversationLoop\(activeTabId\)/, "voice loop should follow per-tab conversation mode state");
740
+ assert.match(app, /function toggleVoiceConversationPaused\(\)[\s\S]*togglePaused\?\.\(\)[\s\S]*Browser voice loop paused/, "composer voice chip should be wired to pause or resume browser listening");
741
+ assert.match(app, /function conversationModeDisplayText\(mode = activeConversationMode\(\)\)[\s\S]*voiceConversationVisibleProviderLabel\(\)[\s\S]*browser STT\/TTS/, "conversation status chip should show the active browser voice provider state");
742
+ assert.match(app, /conversationModeChip\?\.addEventListener\("click", \(\) => toggleVoiceConversationPaused\(\)\)/, "conversation chip should pause/resume the browser voice loop instead of ending safe mode");
743
+ assert.match(app, /async function startVoiceConversationLoop\(tabId = activeTabId\)[\s\S]*remoteMicConsentGranted\(tabId\)/, "voice loop must gate remote sessions behind explicit microphone consent");
744
+ assert.match(app, /function isLocalhostWebui\(\)[\s\S]*127\.0\.0\.1/, "remote-consent detection should treat localhost as implicitly consented");
745
+ assert.match(app, /function latestAssistantSpokenText\(\)[\s\S]*assistantDisplayMessages\(message\)\.find\(\(item\) => item\?\.title === "final output"\)/, "spoken text must come from final output only, never thinking or tool payloads");
746
+ assert.match(app, /function speakableTextFromMarkdown\(text\)[\s\S]*Code block omitted/, "spoken text should strip code blocks and markdown syntax");
747
+ assert.match(app, /case "agent_end":[\s\S]*handleVoiceConversationTurnEnd\(tabContext\)/, "agent_end should hand the finished turn to the voice loop");
748
+ assert.match(app, /case "tool_execution_start":[\s\S]*setAssistantActivity\(\{ toolRunning: true \}\)/, "tool execution start should mark the voice loop tool phase");
749
+ assert.match(app, /case "tool_execution_end":[\s\S]*setAssistantActivity\(\{ toolRunning: false \}\)/, "tool execution end should clear the voice loop tool phase");
750
+ assert.match(html, /id="remoteMicStreamingConsentButton"[^>]*disabled>Allow remote microphone streaming</, "remote mic consent button should exist, start disabled, and use action-specific copy");
751
+ assert.match(html, /id="remoteMicStreamingConsent" class="composer-remote-mic-consent" role="alert" hidden/, "remote mic consent disclosure container should exist and start hidden");
752
+ assert.match(css, /\.composer-remote-mic-consent[\s\S]*\.composer-remote-mic-consent-button/, "remote mic consent banner should have dedicated styles");
753
+ assert.match(css, /\.composer-conversation-mode-chip\[data-voice-state="speaking"\]/, "conversation chip should style voice states");
754
+ assert.match(serviceWorker.toString(), /\/voice-conversation\.mjs/, "service worker app shell should include the voice module");
755
+ assert.ok(pkg.scripts.check.includes("node --check public/voice-conversation.mjs"), "npm run check should parse the voice module");
707
756
  assert.match(app, /function updateOptionalFeatureAvailability\(\)[\s\S]*hasAvailableCommand\("git-staged-msg"\)[\s\S]*hasAvailableCommand\("release-npm"\)[\s\S]*hasAvailableCommand\("release-aur"\)[\s\S]*hasAvailableCommand\("safety-guard"\)[\s\S]*hasLoadedRpcCommand\("skills"\)[\s\S]*hasAvailableCommand\("todo-progress-status"\)[\s\S]*hasLoadedRpcCommand\("tools"\)[\s\S]*hasAvailableCommand\("remote"\)[\s\S]*NATURAL_CONVERSATION_COMMAND_NAMES\.some\(\(name\) => hasAvailableCommand\(name\)\)/, "optional feature detection should call RPC-visible commands directly and distinguish native resource selectors from TUI companions");
708
757
  assert.match(app, /hasRemoteWebuiCommand = isOptionalFeatureEnabled\("remoteWebui"\) && hasAvailableCommand\("remote"\)[\s\S]*optionsRemoteButton\.hidden = !hasRemoteWebuiCommand[\s\S]*syncRemoteWebuiControlVisibility\(hasRemoteWebuiCommand\)/, "Options menu should track /remote availability and delegate network card visibility");
709
758
  assert.match(app, /function syncRemoteWebuiControlVisibility[\s\S]*networkControlField\.hidden = !hasRemoteWebuiCommand/, "Remote WebUI network card should render whenever the optional feature and /remote command are enabled");
@@ -754,7 +803,7 @@ assert.match(app, /addGitWorkflowAction\("Push and Create PR", \(\) => pushAndCr
754
803
  assert.match(app, /async function runGitPrPrompt\(tabId = gitWorkflowActionTabId\(\), \{ prefixOutput = "" \} = \{\}\)[\s\S]*body: \{ message: "\/pr" \}/, "guided git workflow should generate PR descriptions with /pr");
755
804
  assert.match(server, /case "\/api\/git-workflow\/branch-name":[\s\S]*readGitWorkflowBranchName\(cwd\)/, "server should expose generated branch-name file loading for the guided PR workflow");
756
805
  assert.match(server, /case "\/api\/git-workflow\/branch":[\s\S]*createGitWorkflowBranchWorktree\(tab, body\)/, "server should route guided PR branch creation through worktree tabs");
757
- assert.match(server, /async function createGitWorkflowBranchWorktree\(tab, body = \{\}\)[\s\S]*snapshotGitWorkflowBranchState\(root\)[\s\S]*applyGitWorkflowBranchStateToWorktree\(snapshot, worktreePath\)[\s\S]*openWorktreeResultForTab\(tab, createdResult/, "guided PR worktree creation should copy staged state before opening the worktree tab");
806
+ assert.match(server, /async function createGitWorkflowBranchWorktree\(tab, body = \{\}\)[\s\S]*snapshotGitWorkflowBranchState\(root, tab\.cwd\)[\s\S]*applyGitWorkflowBranchStateToWorktree\(snapshot, worktreePath\)[\s\S]*openWorktreeResultForTab\(tab, createdResult/, "guided PR worktree creation should copy staged state before opening the worktree tab");
758
807
  assert.match(server, /case "\/api\/git-workflow\/create-pr":[\s\S]*runGitHubWorkflowCommand\(\["pr", "create"/, "server should create PRs with the GitHub CLI after confirmation");
759
808
  assert.doesNotMatch(app, /gitWorkflowVisibleTabId|Workflow belongs to/, "guided git workflow should not pin or show workflows outside their owning terminal tab");
760
809
  assert.match(app, /function renderReleaseNpmOutputWidget\(\)/, "release-npm live output should use a specialized Web UI renderer");
@@ -971,7 +1020,7 @@ assert.match(app, /async function sendBtwQuestion\(question,[\s\S]*?`\/btw \$\{c
971
1020
  assert.match(app, /async function sendBtwPromptFromButton\(\)[\s\S]*?if \(!question\) \{\n\s+openBtwComposerWidget\(\);/, "empty /btw button should open the side-question widget input");
972
1021
  assert.match(app, /function renderBtwComposerForm\(\)[\s\S]*?form\.requestSubmit\(\)[\s\S]*?sendBtwQuestion\(question\)/, "/btw widget input should submit each message as a /btw trigger");
973
1022
  assert.match(app, /function makeBtwTransferIcon\(\)[\s\S]*?class", "btw-transfer-icon"[\s\S]*?function transferBtwContextToMain\(button, \{ transferMode = "full" \} = \{\}\)[\s\S]*?`\/btw-transfer \$\{encoded\}`[\s\S]*?streamingBehavior: "steer"[\s\S]*?Summarize & Steer/, "/btw widget should expose full-context and summary transfer actions that send steering context during active runs");
974
- assert.match(app, /async function sendPrompt\(kind = "prompt", explicitMessage, \{ targetTabId = activeTabId, throwOnError = false, streamingBehavior \} = \{\}\)[\s\S]*?if \(targetWasStreaming\) body\.streamingBehavior = streamingBehavior \|\| busyBehavior/, "prompt sending should support a per-call streaming behavior override");
1023
+ assert.match(app, /async function sendPrompt\(kind = "prompt", explicitMessage, \{ targetTabId = activeTabId, throwOnError = false, streamingBehavior \} = \{\}\)[\s\S]*?if \(targetWasBusy\) body\.streamingBehavior = streamingBehavior \|\| busyBehavior/, "prompt sending should support a per-call streaming behavior override");
975
1024
  assert.match(app, /function runPublishWorkflow\(command\)[\s\S]*?sendPrompt\("prompt", `\/\$\{resolvedCommandName\}\$\{commandRest\}`\)/, "Publish workflows should send resolved slash commands directly without replacing the draft");
976
1025
  assert.match(app, /async function runNativeCommandMenu\(command\)[\s\S]*?await handleNativeSlashSelectorCommand\(command\)/, "skills/tools command menu should open native selector dialogs directly");
977
1026
  assert.match(app, /async function runNativeCommandMenu\(command\)[\s\S]*?sendPrompt\("prompt", command\)/, "generic native command menu should fall back to slash-command prompt execution");
@@ -1286,10 +1335,12 @@ assert.match(server, /\["tuiSkillsCommand", "@firstpick\/pi-extension-setup-skil
1286
1335
  assert.match(server, /\["tuiToolsCommand", "@firstpick\/pi-extension-tools"\]/, "server should allow installing the TUI tools optional feature");
1287
1336
  assert.match(server, /\["naturalConversation", "@firstpick\/pi-package-natural-conversation"\]/, "server should know the standalone Natural Conversation package for status\/install guidance without making it WebUI-owned");
1288
1337
  assert.match(server, /const NATURAL_CONVERSATION_COMMAND_NAMES = \["talk", "voice", "conversation"\]/, "server should detect Natural Conversation from RPC-visible command aliases");
1289
- assert.match(server, /function naturalConversationFeatureData\(tab[\s\S]*getCommandData\(tab\)[\s\S]*available[\s\S]*mode/, "server should expose a capability-based Natural Conversation feature snapshot");
1338
+ assert.match(server, /function naturalConversationFeatureData\(tab[\s\S]*getCommandData\(tab, \{ annotateSkills: false \}\)[\s\S]*available[\s\S]*mode/, "server should expose a capability-based Natural Conversation feature snapshot");
1290
1339
  assert.match(server, /url\.pathname === "\/api\/features\/natural-conversation" && req\.method === "GET"[\s\S]*naturalConversationFeatureData\(tab\)/, "server should expose Natural Conversation feature metadata");
1291
1340
  assert.match(server, /url\.pathname === "\/api\/conversation-mode" && req\.method === "POST"[\s\S]*setNaturalConversationMode\(tab, body\)/, "server should toggle Natural Conversation through the package-owned slash command");
1292
- assert.match(server, /url\.pathname === "\/api\/stt\/transcribe" \|\| url\.pathname === "\/api\/tts\/speech"[\s\S]*501[\s\S]*hosted\/local STT\/TTS fallbacks are not implemented/, "server STT\/TTS routes should be explicit later-phase placeholders");
1341
+ assert.match(server, /url\.pathname === "\/api\/stt\/transcribe"[\s\S]*handleNaturalConversationSttTranscribe[\s\S]*url\.pathname === "\/api\/tts\/speech"[\s\S]*handleNaturalConversationTtsSpeech/, "server should expose opt-in Natural Conversation STT/TTS fallback routes");
1342
+ assert.match(server, /PI_VOICE_STT_URL[\s\S]*PI_VOICE_TTS_URL[\s\S]*GROQ_API_KEY[\s\S]*OPENAI_API_KEY[\s\S]*CLOUDFLARE_API_TOKEN/, "server voice fallbacks should be gated by server-side provider environment variables");
1343
+ assert.match(server, /function requireRemoteMicConsentForStt\(req, body = \{\}\)[\s\S]*remoteMicStreamingConsentAccepted/, "server STT fallback should require explicit remote microphone streaming consent for remote clients");
1293
1344
  assert.match(server, /function ensureNaturalConversationPromptSafety\(tab, command\)[\s\S]*setThinkingLevelForTab\(tab, "off"/, "server should force thinking off before WebUI prompts while conversation mode is active");
1294
1345
  assert.match(server, /function enforceNaturalConversationCommandAllowed\(tab, command\)[\s\S]*thinking is forced off[\s\S]*slash commands are blocked from the Web UI shell/, "server should block unsafe direct RPC\/WebUI commands while conversation mode is active");
1295
1346
  assert.match(server, /function optionalFeaturePackageStatus\(featureId\)/, "server should report optional feature package install\/update status");
@@ -0,0 +1,132 @@
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
+ // Static guard for the Light / Dark / Auto theme scheme switch: the picker stores
7
+ // theme picks in the matching light/dark slot, "auto" follows the OS prefers-color-scheme,
8
+ // and existing users keep their theme (auto is opt-in). This locks the wiring across
9
+ // app.js / index.html / styles.css, including the persistence rules: theme names are
10
+ // only stored after a pick was validated and applied, never from degraded loads.
11
+
12
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
13
+ const app = await readFile(join(root, "public", "app.js"), "utf8");
14
+ const html = await readFile(join(root, "public", "index.html"), "utf8");
15
+ const css = await readFile(join(root, "public", "styles.css"), "utf8");
16
+
17
+ // ── app.js: state, storage, and scheme resolution ────────────────────────────
18
+ for (const decl of [
19
+ 'const THEME_MODE_STORAGE_KEY = "pi-webui-theme-mode"',
20
+ 'const THEME_LIGHT_STORAGE_KEY = "pi-webui-theme-light"',
21
+ 'const THEME_DARK_STORAGE_KEY = "pi-webui-theme-dark"',
22
+ 'const THEME_SCHEME_MODES = new Set(["light", "dark", "auto"])',
23
+ 'window.matchMedia?.("(prefers-color-scheme: dark)")',
24
+ ]) {
25
+ assert.ok(app.includes(decl), `app.js should declare: ${decl}`);
26
+ }
27
+
28
+ for (const fn of [
29
+ "function osPrefersDark(",
30
+ "function effectiveScheme(",
31
+ "function effectiveThemeName(",
32
+ "function renderThemeSchemeToggle(",
33
+ "async function applySchemeTheme(",
34
+ "async function chooseTheme(",
35
+ "function handleOsSchemeChange(",
36
+ "function updateColorSchemeListener(",
37
+ "async function setThemeSchemeMode(",
38
+ "function seedThemeSchemeFromStoredTheme(",
39
+ "function storedThemeMode(",
40
+ "function storedSchemeTheme(",
41
+ ]) {
42
+ assert.ok(app.includes(fn), `app.js should define ${fn.replace(/\($/, "")}`);
43
+ }
44
+
45
+ // Auto follows the OS only while the auto mode is active.
46
+ assert.match(
47
+ app,
48
+ /function updateColorSchemeListener\(\)[\s\S]*?addEventListener\("change", handleOsSchemeChange\)/,
49
+ "auto mode should attach an OS prefers-color-scheme listener",
50
+ );
51
+ assert.match(
52
+ app,
53
+ /function handleOsSchemeChange\(\)\s*\{\s*if \(themeSchemeMode !== "auto"\) return;/,
54
+ "OS listener must be a no-op outside auto mode",
55
+ );
56
+
57
+ // Existing users keep their theme: migration seeds the matching slot, mode is the
58
+ // stored theme's own scheme (never forced to auto).
59
+ assert.match(
60
+ app,
61
+ /themeSchemeMode = storedThemeMode\(\) \?\? seedThemeSchemeFromStoredTheme\(\)/,
62
+ "init should reuse a stored mode or migrate the existing theme",
63
+ );
64
+ assert.ok(
65
+ !/seedThemeSchemeFromStoredTheme[\s\S]*?return "auto"/.test(app),
66
+ "migration must not default existing users to auto",
67
+ );
68
+ assert.match(
69
+ app,
70
+ /function seedThemeSchemeFromStoredTheme\(\)[\s\S]*?if \(!storedTheme\) return "dark";[\s\S]*?storeThemeMode\(scheme\);/,
71
+ "migration must not persist mode or slots when the stored theme is unresolvable (degraded bundle load)",
72
+ );
73
+
74
+ // Persistence lives inside applyTheme's validated persist branch (matching light/dark
75
+ // scheme slot + legacy key), reached only after setThemeByName found and classified
76
+ // the theme. chooseTheme is the single persist:true entry point; applySchemeTheme
77
+ // (init, mode switches, OS changes) never persists, so a degraded bundle load cannot
78
+ // clobber stored picks.
79
+ assert.match(
80
+ app,
81
+ /if \(persist\) \{\s*storeSchemeTheme\(isLight \? "light" : "dark", theme\.name\);\s*storeThemeName\(theme\.name\);\s*\}/,
82
+ "applyTheme's persist branch must write the theme's matching scheme slot and the legacy key",
83
+ );
84
+ assert.equal(
85
+ (app.match(/persist: true/g) || []).length,
86
+ 1,
87
+ "chooseTheme must be the only persist:true call site",
88
+ );
89
+ assert.match(
90
+ app,
91
+ /async function chooseTheme\(name, options = \{\}\) \{\s*await setThemeByName\(name, \{ \.\.\.options, persist: true \}\);\s*\}/,
92
+ "chooseTheme should delegate persistence to the validated setThemeByName path",
93
+ );
94
+ assert.match(
95
+ app,
96
+ /async function applySchemeTheme\(options = \{\}\) \{\s*await setThemeByName\(effectiveThemeName\(\), \{ \.\.\.options, persist: false \}\);\s*\}/,
97
+ "applySchemeTheme must never persist",
98
+ );
99
+
100
+ // Auto mode also works on MediaQueryList implementations without addEventListener
101
+ // (legacy addListener API), matching the mobileViewMedia wiring.
102
+ assert.match(
103
+ app,
104
+ /colorSchemeMedia\.addListener\?\.\(handleOsSchemeChange\)/,
105
+ "updateColorSchemeListener should fall back to the legacy addListener API",
106
+ );
107
+ assert.match(app, /elements\.themeSelect\.addEventListener\("change"[\s\S]*?chooseTheme\(/, "select change should call chooseTheme");
108
+ assert.match(
109
+ app,
110
+ /elements\.themeSchemeToggle\?\.querySelectorAll\("\[data-scheme-mode\]"\)[\s\S]*?setThemeSchemeMode\(button\.dataset\.schemeMode/,
111
+ "toggle buttons should call setThemeSchemeMode",
112
+ );
113
+ assert.ok(app.includes('themeSchemeToggle: $("#themeSchemeToggle")'), "themeSchemeToggle element should be registered");
114
+ assert.match(
115
+ app,
116
+ /theme-search-result-scheme[\s\S]*?themeIsLight\(theme\) \? "Light" : "Dark"/,
117
+ "theme search rows should show a Light/Dark scheme label next to each theme name",
118
+ );
119
+
120
+ // ── index.html: the switch markup ────────────────────────────────────────────
121
+ assert.match(html, /id="themeSchemeToggle"[^>]*role="group"/, "index.html should contain the theme scheme toggle group");
122
+ for (const mode of ["light", "dark", "auto"]) {
123
+ assert.match(html, new RegExp(`data-scheme-mode="${mode}"`), `toggle should have a ${mode} button`);
124
+ }
125
+
126
+ // ── styles.css: the switch styling ───────────────────────────────────────────
127
+ assert.match(css, /\.theme-scheme-toggle\s*\{/, "styles.css should style the toggle");
128
+ assert.match(css, /\.theme-scheme-toggle button\.active\s*\{/, "styles.css should style the active mode");
129
+ assert.match(css, /\.theme-search-result-title\s*\{[\s\S]*?grid-template-columns:\s*minmax\(0, 1fr\) auto;/, "theme rows should place the scheme label beside the name");
130
+ assert.match(css, /\.theme-search-result-scheme\s*\{/, "styles.css should style theme scheme labels");
131
+
132
+ console.log("theme-scheme-mode: all assertions passed");