@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.
package/public/app.js CHANGED
@@ -5,6 +5,7 @@ const elements = {
5
5
  webuiDevBadge: $("#webuiDevBadge"),
6
6
  tabBar: $("#tabBar"),
7
7
  terminalTabsToggleButton: $("#terminalTabsToggleButton"),
8
+ splitTabButton: $("#splitTabButton"),
8
9
  newTabMenu: $("#newTabMenu"),
9
10
  newTabButton: $("#newTabButton"),
10
11
  newTabMenuPanel: $("#newTabMenuPanel"),
@@ -12,6 +13,11 @@ const elements = {
12
13
  newTabChooseDirectoryButton: $("#newTabChooseDirectoryButton"),
13
14
  newTabWorktreeButton: $("#newTabWorktreeButton"),
14
15
  closeAllTabsButton: $("#closeAllTabsButton"),
16
+ terminalSplitShell: $("#terminalSplitShell"),
17
+ terminalSplitFrame: $("#terminalSplitFrame"),
18
+ terminalSplitTitle: $("#terminalSplitTitle"),
19
+ terminalSplitMeta: $("#terminalSplitMeta"),
20
+ terminalSplitCloseButton: $("#terminalSplitCloseButton"),
15
21
  commandPaletteButton: $("#commandPaletteButton"),
16
22
  workspaceDashboardToggleButton: $("#workspaceDashboardToggleButton"),
17
23
  workspaceDashboard: $("#workspaceDashboard"),
@@ -70,6 +76,13 @@ const elements = {
70
76
  followUpButton: $("#followUpButton"),
71
77
  abortButton: $("#abortButton"),
72
78
  conversationModeEndButton: $("#conversationModeEndButton"),
79
+ conversationVoiceMenu: $("#conversationVoiceMenu"),
80
+ conversationVoiceButton: $("#conversationVoiceButton"),
81
+ conversationVoiceButtonLabel: $("#conversationVoiceButtonLabel"),
82
+ conversationVoiceMenuPanel: $("#conversationVoiceMenuPanel"),
83
+ remoteMicStreamingConsent: $("#remoteMicStreamingConsent"),
84
+ remoteMicStreamingConsentText: $("#remoteMicStreamingConsentText"),
85
+ remoteMicStreamingConsentButton: $("#remoteMicStreamingConsentButton"),
73
86
  newSessionButton: $("#newSessionButton"),
74
87
  compactButton: $("#compactButton"),
75
88
  gitWorkflowButton: $("#gitWorkflowButton"),
@@ -136,6 +149,7 @@ const elements = {
136
149
  themeSearchInput: $("#themeSearchInput"),
137
150
  themeSearchResults: $("#themeSearchResults"),
138
151
  themeSelect: $("#themeSelect"),
152
+ themeSchemeToggle: $("#themeSchemeToggle"),
139
153
  backgroundInput: $("#backgroundInput"),
140
154
  backgroundChooseButton: $("#backgroundChooseButton"),
141
155
  backgroundClearButton: $("#backgroundClearButton"),
@@ -313,6 +327,7 @@ let openTerminalTabGroupKey = null;
313
327
  let terminalCustomGroups = new Map();
314
328
  let terminalCustomGroupSerial = 1;
315
329
  let terminalTabDragId = null;
330
+ let splitTabId = null;
316
331
  let newTabMenuOpen = false;
317
332
  let nativeCommandMenuOpen = false;
318
333
  let appRunnerMenuOpen = false;
@@ -520,6 +535,17 @@ const LONG_INPUT_ATTACHMENT_MIME_TYPE = "text/plain";
520
535
  const INLINE_IMAGE_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
521
536
  const BACKGROUND_IMAGE_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
522
537
  const DEFAULT_THEME_NAME = "catppuccin-mocha";
538
+ // Theme scheme mode (Light / Dark / Auto). The picker chooses the theme for the
539
+ // active scheme; "auto" follows the OS prefers-color-scheme and swaps between the
540
+ // remembered light and dark picks. Existing users keep their theme (see migration
541
+ // in initializeThemes), so auto is strictly opt-in.
542
+ const THEME_MODE_STORAGE_KEY = "pi-webui-theme-mode";
543
+ const THEME_LIGHT_STORAGE_KEY = "pi-webui-theme-light";
544
+ const THEME_DARK_STORAGE_KEY = "pi-webui-theme-dark";
545
+ const THEME_LIGHT_DEFAULT = "catppuccin-latte";
546
+ const THEME_DARK_DEFAULT = "catppuccin-mocha";
547
+ const THEME_SCHEME_MODES = new Set(["light", "dark", "auto"]);
548
+ let themeSchemeMode = "light"; // "light" | "dark" | "auto"; finalized in initializeThemes
523
549
  const TERMINAL_TABS_LAYOUTS = new Set(["top", "left"]);
524
550
  const TERMINAL_TABS_LAYOUT_LABELS = { top: "Top bar", left: "Left sidebar" };
525
551
  const BUSY_PROMPT_BEHAVIOR_VALUES = new Set(["followUp", "steer"]);
@@ -566,6 +592,10 @@ const AGENT_DONE_NOTIFICATION_TAG_PREFIX = "pi-webui-agent-done";
566
592
  const BLOCKED_TAB_NOTIFICATION_ICON = "/icon-192.png";
567
593
  const mobileViewMedia = window.matchMedia?.(MOBILE_VIEW_QUERY) || null;
568
594
  const sidePanelOverlayMedia = window.matchMedia?.(SIDE_PANEL_OVERLAY_QUERY) || mobileViewMedia;
595
+ const colorSchemeMedia = window.matchMedia?.("(prefers-color-scheme: dark)") || null;
596
+ const initialUrlParams = new URLSearchParams(window.location.search);
597
+ const embeddedSplitMode = initialUrlParams.get("embed") === "split";
598
+ document.body.classList.toggle("embedded-split", embeddedSplitMode);
569
599
  const statusEntries = new Map();
570
600
  const widgets = new Map();
571
601
  const widgetsByTab = new Map();
@@ -751,6 +781,9 @@ const SETTINGS_AUTOCOMPLETE_OPTIONS = ["3", "5", "7", "10", "15", "20"];
751
781
  const optionalFeatureInstallInProgress = new Set();
752
782
  const optionalFeaturePackageStatuses = new Map();
753
783
  const optionalFeatureInstallMessages = new Map();
784
+ const optionalFeatureInstallStates = new Map();
785
+ const optionalFeatureInstallProgressTimers = new Map();
786
+ let optionalFeaturePackageStatusError = "";
754
787
  const gitFooterPayloadRefreshInFlightByTab = new Set();
755
788
  const gitFooterSyncPushInFlightByTab = new Set();
756
789
  const gitFooterPiCalibrationInFlightByTab = new Set();
@@ -1026,6 +1059,7 @@ function isInteractiveDropdownOpen() {
1026
1059
  || nativeCommandMenuOpen
1027
1060
  || appRunnerMenuOpen
1028
1061
  || optionsMenuOpen
1062
+ || conversationVoiceMenuOpen
1029
1063
  || busyPromptBehaviorMenuOpen
1030
1064
  || newTabMenuOpen
1031
1065
  || isFooterPickerOpen()
@@ -1117,6 +1151,7 @@ function mobileDropdownConfigs() {
1117
1151
  { menu: elements.nativeCommandMenuButton?.parentElement, button: elements.nativeCommandMenuButton, panel: elements.nativeCommandMenuButton?.parentElement?.querySelector(".composer-publish-menu-panel") },
1118
1152
  { menu: elements.optionsMenuButton?.parentElement, button: elements.optionsMenuButton, panel: elements.optionsMenu },
1119
1153
  { menu: elements.appRunnerMenu, button: elements.appRunnerMenuButton, panel: elements.appRunnerMenuPanel },
1154
+ { menu: elements.conversationVoiceMenu, button: elements.conversationVoiceButton, panel: elements.conversationVoiceMenuPanel },
1120
1155
  ];
1121
1156
  }
1122
1157
 
@@ -2413,10 +2448,12 @@ function bindSidePanelOverlayViewChanges() {
2413
2448
  const syncForViewport = (event) => {
2414
2449
  if (event.matches) {
2415
2450
  setSidePanelCollapsed(true, { persist: false });
2451
+ updateTerminalSplitUi();
2416
2452
  return;
2417
2453
  }
2418
2454
  const stored = readStoredSidePanelCollapsed();
2419
2455
  setSidePanelCollapsed(stored ?? false, { persist: false });
2456
+ updateTerminalSplitUi();
2420
2457
  };
2421
2458
  if (typeof sidePanelOverlayMedia.addEventListener === "function") sidePanelOverlayMedia.addEventListener("change", syncForViewport);
2422
2459
  else sidePanelOverlayMedia.addListener?.(syncForViewport);
@@ -3072,15 +3109,15 @@ function renderUpdateNotification(status = latestUpdateStatus, { force = false }
3072
3109
  if (elements.updateNotificationMessage) {
3073
3110
  let message = "Updates are available. Direct Web UI updates are only enabled from localhost on the host machine.";
3074
3111
  if (canRunUpdate) {
3075
- if (hasPiUpdate && hasPackageUpdate) message = "Run pi update for Pi only, or pi update --all to include Web UI/package updates, then restart this Web UI server automatically.";
3076
- else if (hasPackageUpdate) message = "Run pi update --all to update Web UI/package entries, then restart this Web UI server automatically.";
3112
+ if (hasPiUpdate && hasPackageUpdate) message = "Run pi update for Pi only, or update all to include Web UI, Optional Features, configured Pi packages, and detected Pi package roots, then restart this Web UI server automatically.";
3113
+ else if (hasPackageUpdate) message = "Update all to refresh Web UI/package entries, Optional Features, configured Pi packages, and detected Pi package roots, then restart this Web UI server automatically.";
3077
3114
  else message = "Run pi update for Pi only, then restart this Web UI server automatically.";
3078
3115
  }
3079
3116
  elements.updateNotificationMessage.textContent = message;
3080
3117
  }
3081
3118
  const details = [
3082
3119
  items.join(" · "),
3083
- latestUpdateStatus.webuiDev && latestUpdateStatus.webui?.updateAvailable ? "The current Web UI is a dev checkout; pi update --all refreshes configured package dependencies when possible." : "",
3120
+ latestUpdateStatus.webuiDev && latestUpdateStatus.webui?.updateAvailable ? "The current Web UI is a dev checkout; update all also refreshes detected Web UI/Optional Feature Pi package dependencies when possible." : "",
3084
3121
  latestUpdateStatus.packages?.note || "",
3085
3122
  ].filter(Boolean).join(" ");
3086
3123
  if (elements.updateNotificationDetail) elements.updateNotificationDetail.textContent = details;
@@ -3129,8 +3166,9 @@ function piUpdateConfirmationText({ all = false } = {}) {
3129
3166
  const workingWarning = hasWorkingTab() ? "\n\nOne or more Pi tabs look busy or blocked. Finish or abort in-flight work before updating if you need to preserve it." : "";
3130
3167
  const versionText = items.length ? `\n\nDetected update: ${items.join(" · ")}.` : "";
3131
3168
  const command = all ? "pi update --all" : "pi update";
3132
- const scope = all ? "Pi and configured package updates" : "Pi only";
3133
- return `Run ${scope} now?${versionText}\n\nThis will run \"${command}\" on the Web UI host. After it finishes, Pi Web UI will restart itself. Browser clients will briefly disconnect, and managed Pi tabs/RPC processes will be restarted from saved session state when possible.${workingWarning}`;
3169
+ const scope = all ? "Pi, configured packages, Optional Features, and detected Pi package roots" : "Pi only";
3170
+ const extra = all ? " It will also run npm/bun package updates for detected Web UI, Optional Feature, agent, project, and global Pi package roots." : "";
3171
+ return `Run ${scope} now?${versionText}\n\nThis will run \"${command}\" on the Web UI host.${extra} After it finishes, Pi Web UI will restart itself. Browser clients will briefly disconnect, and managed Pi tabs/RPC processes will be restarted from saved session state when possible.${workingWarning}`;
3134
3172
  }
3135
3173
 
3136
3174
  async function runPiUpdateAndRestart({ all = false } = {}) {
@@ -4003,6 +4041,42 @@ function storeThemeName(name) {
4003
4041
  }
4004
4042
  }
4005
4043
 
4044
+ function storedThemeMode() {
4045
+ try {
4046
+ const raw = localStorage.getItem(THEME_MODE_STORAGE_KEY);
4047
+ return THEME_SCHEME_MODES.has(raw) ? raw : null;
4048
+ } catch {
4049
+ return null;
4050
+ }
4051
+ }
4052
+
4053
+ function storeThemeMode(mode) {
4054
+ try {
4055
+ localStorage.setItem(THEME_MODE_STORAGE_KEY, mode);
4056
+ } catch {
4057
+ // Ignore storage failures; the mode still applies for this page load.
4058
+ }
4059
+ }
4060
+
4061
+ function storedSchemeTheme(scheme) {
4062
+ const key = scheme === "dark" ? THEME_DARK_STORAGE_KEY : THEME_LIGHT_STORAGE_KEY;
4063
+ const fallback = scheme === "dark" ? THEME_DARK_DEFAULT : THEME_LIGHT_DEFAULT;
4064
+ try {
4065
+ return localStorage.getItem(key) || fallback;
4066
+ } catch {
4067
+ return fallback;
4068
+ }
4069
+ }
4070
+
4071
+ function storeSchemeTheme(scheme, name) {
4072
+ const key = scheme === "dark" ? THEME_DARK_STORAGE_KEY : THEME_LIGHT_STORAGE_KEY;
4073
+ try {
4074
+ localStorage.setItem(key, name);
4075
+ } catch {
4076
+ // Ignore storage failures.
4077
+ }
4078
+ }
4079
+
4006
4080
  function loadDisabledOptionalFeatures() {
4007
4081
  try {
4008
4082
  const parsed = JSON.parse(localStorage.getItem(OPTIONAL_FEATURES_STORAGE_KEY) || "[]");
@@ -4058,6 +4132,7 @@ function defaultConversationModeState(patch = {}) {
4058
4132
  enabled: false,
4059
4133
  uiState: "off",
4060
4134
  statusText: "",
4135
+ partialTranscript: "",
4061
4136
  allowedTools: ["read", "grep", "find", "ls"],
4062
4137
  provider: "browser-shell",
4063
4138
  startedAt: null,
@@ -4077,16 +4152,25 @@ function normalizeConversationModeState(value = {}) {
4077
4152
  enabled,
4078
4153
  uiState: enabled ? cleanStatusText(source.uiState || "listening").toLowerCase() || "listening" : "off",
4079
4154
  statusText: cleanStatusText(source.statusText || ""),
4155
+ partialTranscript: cleanStatusText(source.partialTranscript || ""),
4080
4156
  allowedTools: Array.isArray(source.allowedTools) && source.allowedTools.length ? source.allowedTools.map((name) => String(name)).filter(Boolean) : ["read", "grep", "find", "ls"],
4081
4157
  packageInstalled: source.packageInstalled === true,
4082
4158
  loadedCommands: Array.isArray(source.loadedCommands) ? source.loadedCommands.map((name) => String(name)).filter(Boolean) : [],
4083
4159
  });
4084
4160
  }
4085
4161
 
4086
- function updateConversationModeForTab(tabId = activeTabId, mode = {}, { render = true } = {}) {
4162
+ function updateConversationModeForTab(tabId = activeTabId, mode = {}, { render = true, voiceLoop = false } = {}) {
4087
4163
  if (!tabId) return normalizeConversationModeState(mode);
4088
4164
  const previous = conversationModeByTab.get(tabId) || tabs.find((tab) => tab.id === tabId)?.conversationMode || {};
4089
- const next = normalizeConversationModeState({ ...previous, ...mode });
4165
+ let patch = mode && typeof mode === "object" ? mode : {};
4166
+ if (!voiceLoop && patch.enabled !== false && voiceConversationActiveFor(tabId)) {
4167
+ // While the browser voice loop runs, it owns uiState/statusText; server
4168
+ // snapshots would otherwise reset "speaking"/"transcribing" to "listening".
4169
+ patch = { ...patch };
4170
+ delete patch.uiState;
4171
+ delete patch.statusText;
4172
+ }
4173
+ const next = normalizeConversationModeState({ ...previous, ...patch });
4090
4174
  conversationModeByTab.set(tabId, next);
4091
4175
  if (tabId === activeTabId && render) renderConversationModeControls();
4092
4176
  return next;
@@ -4108,8 +4192,41 @@ function conversationModeButtonLabel(mode = activeConversationMode()) {
4108
4192
  return mode.enabled ? "End Conversation" : "Start Conversation";
4109
4193
  }
4110
4194
 
4195
+ function conversationModePartialPreview(text = "") {
4196
+ const normalized = cleanStatusText(text || "");
4197
+ if (!normalized) return "";
4198
+ return normalized.length > 42 ? `${normalized.slice(0, 39)}…` : normalized;
4199
+ }
4200
+
4201
+ // Declared before renderConversationModeControls ever runs (it is called
4202
+ // during initial render passes) so the voice-menu block never hits a TDZ.
4203
+ let conversationVoiceSwitching = false;
4204
+ let conversationVoicesLoadedForTab = null;
4205
+ let conversationVoiceMenuOpen = false;
4206
+ let conversationVoiceLastData = null;
4207
+ let conversationVoicePending = null;
4208
+
4209
+ // Same open/close contract as the Common-Pi-options menu: click toggles the
4210
+ // panel (hover/focus-within still work on desktop via CSS), so it also works
4211
+ // on touch devices where :hover never fires.
4212
+ function setConversationVoiceMenuOpen(open) {
4213
+ conversationVoiceMenuOpen = !!open;
4214
+ elements.conversationVoiceButton?.setAttribute("aria-expanded", conversationVoiceMenuOpen ? "true" : "false");
4215
+ elements.conversationVoiceButton?.classList.toggle("menu-open", conversationVoiceMenuOpen);
4216
+ elements.conversationVoiceMenu?.classList.toggle("open", conversationVoiceMenuOpen);
4217
+ scheduleMobileDropdownScrollBoundsUpdate();
4218
+ }
4219
+
4111
4220
  function conversationModeDisplayText(mode = activeConversationMode()) {
4112
- return mode.enabled ? `Voice: ${mode.uiState || "listening"}` : "Voice: off";
4221
+ if (!mode.enabled) return "Voice: off";
4222
+ // Voice-switch progress ("downloading de_DE-thorsten-high 42%", "testing …")
4223
+ // arrives via the package status text; show it verbatim instead of the bare state.
4224
+ const progressDetail = /^voice\s*:\s*((?:downloading|testing)\s.+)$/i.exec(mode.statusText || "")?.[1];
4225
+ const uiState = progressDetail || mode.uiState || "listening";
4226
+ const provider = nativeConversationAudioEngaged() ? "native audio" : voiceConversationVisibleProviderLabel();
4227
+ const prefix = provider ? `Voice: ${uiState} · ${provider}` : `Voice: ${uiState}`;
4228
+ const partial = uiState === "transcribing" ? conversationModePartialPreview(mode.partialTranscript) : "";
4229
+ return partial ? `${prefix} — “${partial}”` : prefix;
4113
4230
  }
4114
4231
 
4115
4232
  function conversationModeUnavailableText() {
@@ -4132,15 +4249,17 @@ function renderConversationModeControls() {
4132
4249
  const tooltip = commandName
4133
4250
  ? `${active ? "End" : "Start"} Natural Conversation Mode for this Pi tab via /${commandName}. Safety is owned by @firstpick/pi-package-natural-conversation.`
4134
4251
  : conversationModeUnavailableText();
4135
- elements.optionsConversationModeButton.title = tooltip;
4136
- elements.optionsConversationModeButton.setAttribute("data-tooltip", tooltip);
4252
+ applyStyledTooltip(elements.optionsConversationModeButton, tooltip, { ariaLabel: false, align: "end" });
4137
4253
  elements.optionsConversationModeButton.setAttribute("aria-pressed", active ? "true" : "false");
4138
4254
  }
4139
4255
 
4140
4256
  if (elements.conversationModeChip) {
4141
4257
  elements.conversationModeChip.hidden = !active;
4142
4258
  elements.conversationModeChip.textContent = conversationModeDisplayText(mode);
4143
- elements.conversationModeChip.title = `Natural Conversation Mode is active in this tab. Thinking is forced off; tools are limited to ${mode.allowedTools.join(", ")}.`;
4259
+ elements.conversationModeChip.setAttribute("data-voice-state", active ? mode.uiState || "listening" : "off");
4260
+ const chipAction = mode.uiState === "paused" ? "Click to resume browser listening." : "Click to pause browser listening; use End conversation to leave the safe mode.";
4261
+ elements.conversationModeChip.title = `Natural Conversation Mode is active in this tab (${voiceConversationProviderLabel()}). Thinking is forced off; tools are limited to ${mode.allowedTools.join(", ")}. ${chipAction}`;
4262
+ elements.conversationModeChip.setAttribute("aria-label", `Natural Conversation Mode ${mode.uiState || "listening"}. ${chipAction}`);
4144
4263
  }
4145
4264
 
4146
4265
  if (elements.conversationModeEndButton) {
@@ -4148,6 +4267,27 @@ function renderConversationModeControls() {
4148
4267
  elements.conversationModeEndButton.disabled = !commandName;
4149
4268
  elements.conversationModeEndButton.title = commandName ? `End Natural Conversation Mode with /${commandName} off.` : conversationModeUnavailableText();
4150
4269
  }
4270
+
4271
+ if (elements.conversationVoiceMenu) {
4272
+ elements.conversationVoiceMenu.hidden = !active;
4273
+ if (!active && conversationVoiceMenuOpen) setConversationVoiceMenuOpen(false);
4274
+ if (elements.conversationVoiceButton) elements.conversationVoiceButton.disabled = conversationVoiceSwitching || !commandName;
4275
+ if (active && commandName && conversationVoicesLoadedForTab !== activeTabId) void loadConversationVoices();
4276
+ }
4277
+
4278
+ const awaitingRemoteMicConsent = active && !remoteMicConsentGranted(activeTabId);
4279
+ if (elements.remoteMicStreamingConsent) {
4280
+ elements.remoteMicStreamingConsent.hidden = !awaitingRemoteMicConsent;
4281
+ if (awaitingRemoteMicConsent && elements.remoteMicStreamingConsentText) {
4282
+ elements.remoteMicStreamingConsentText.textContent = remoteMicConsentDisclosureText();
4283
+ }
4284
+ }
4285
+ if (elements.remoteMicStreamingConsentButton) {
4286
+ // The consent button stays disabled unless its disclosure is visible.
4287
+ elements.remoteMicStreamingConsentButton.disabled = !awaitingRemoteMicConsent;
4288
+ }
4289
+
4290
+ syncVoiceConversationLoop();
4151
4291
  }
4152
4292
 
4153
4293
  function handleNaturalConversationStatus(statusText, tabId = activeTabId) {
@@ -4185,6 +4325,10 @@ async function setNaturalConversationModeEnabled(enabled) {
4185
4325
  }
4186
4326
  try {
4187
4327
  const response = await api("/api/conversation-mode", { method: "POST", body: { enabled: enabled === true }, tabId: tabContext.tabId });
4328
+ if (enabled !== true) {
4329
+ stopVoiceConversationLoop();
4330
+ remoteMicConsentTabs.delete(tabContext.tabId);
4331
+ }
4188
4332
  applyResponseTab(response);
4189
4333
  if (!isCurrentTabContext(tabContext)) return;
4190
4334
  updateConversationModeForTab(tabContext.tabId, response.data?.mode || {}, { render: true });
@@ -4201,6 +4345,449 @@ function toggleNaturalConversationMode() {
4201
4345
  return setNaturalConversationModeEnabled(!mode.enabled);
4202
4346
  }
4203
4347
 
4348
+ // --- Conversation voice dropdown (native Piper voices via /talk voice) -------
4349
+ // The list comes from GET /api/conversation-voices (server reads voice.json
4350
+ // and the piper voice directory); switching posts to /api/conversation-voice,
4351
+ // which runs `/talk voice <id>` in the package over RPC. Missing voices are
4352
+ // downloaded by the package; progress streams back through the voice chip's
4353
+ // status text ("Voice: downloading <id> <pct>%").
4354
+
4355
+ function conversationVoiceLanguageLabel(voiceId) {
4356
+ const locale = String(voiceId || "").split("-", 1)[0] || "";
4357
+ const language = locale.split("_")[0]?.toUpperCase() || "";
4358
+ return ["DE", "EN"].includes(language) ? language : language;
4359
+ }
4360
+
4361
+ function conversationVoiceGenderLabel(voiceId) {
4362
+ const id = String(voiceId || "").toLowerCase();
4363
+ if (id.includes("thorsten")) return "M";
4364
+ if (id.includes("lessac") || id.includes("alba")) return "F";
4365
+ return "";
4366
+ }
4367
+
4368
+ function conversationVoiceShortLabel(voiceId) {
4369
+ // "de_DE-thorsten-medium" → "DE M Thorsten med" keeps the controls compact.
4370
+ const text = String(voiceId || "").trim();
4371
+ if (!text) return "Voice";
4372
+ const parts = text.split("-").filter(Boolean);
4373
+ const language = conversationVoiceLanguageLabel(text);
4374
+ const gender = conversationVoiceGenderLabel(text);
4375
+ const quality = parts.at(-1) || "";
4376
+ const qualityLabel = quality === "medium" ? "med" : quality === "high" ? "high" : quality;
4377
+ const nameParts = parts.length >= 3 ? parts.slice(1, -1) : parts.slice(1);
4378
+ const name = nameParts.join(" ").replace(/\b\w/g, (char) => char.toUpperCase());
4379
+ return [language, gender, name, qualityLabel].filter(Boolean).join(" ") || text;
4380
+ }
4381
+
4382
+ function conversationVoiceById(data, voiceId) {
4383
+ const wanted = String(voiceId || "").trim();
4384
+ const voices = Array.isArray(data?.voices) ? data.voices : [];
4385
+ return voices.find((voice) => voice?.id === wanted) || null;
4386
+ }
4387
+
4388
+ function conversationVoiceDownloadSizeText(voice) {
4389
+ const sizeMb = Number(voice?.sizeMb);
4390
+ return Number.isFinite(sizeMb) && sizeMb > 0 ? ` (${sizeMb} MB)` : "";
4391
+ }
4392
+
4393
+ function conversationVoiceStartMessage(voice, voiceId) {
4394
+ const wanted = String(voiceId || voice?.id || "voice").trim();
4395
+ if (voice?.downloaded) return `Selecting conversation voice ${wanted}…`;
4396
+ return `Downloading conversation voice ${wanted}${conversationVoiceDownloadSizeText(voice)}, then selecting it…`;
4397
+ }
4398
+
4399
+ function showConversationVoiceFeedback(message, level = "info") {
4400
+ const text = cleanStatusText(message || "");
4401
+ if (!text) return;
4402
+ addEvent(text, level);
4403
+ addTransientMessage({ role: level === "error" ? "error" : "native", title: "/talk voice", content: text, level });
4404
+ }
4405
+
4406
+ function renderConversationVoicePanelNotice(message, level = "info") {
4407
+ const panel = elements.conversationVoiceMenuPanel;
4408
+ if (!panel) return;
4409
+ panel.innerHTML = "";
4410
+ const notice = document.createElement("div");
4411
+ notice.className = "composer-publish-menu-item composer-conversation-voice-item composer-conversation-voice-notice";
4412
+ notice.classList.toggle("error", level === "error");
4413
+ notice.setAttribute("role", level === "error" ? "alert" : "status");
4414
+ notice.textContent = message;
4415
+ panel.appendChild(notice);
4416
+ }
4417
+
4418
+ function renderConversationVoiceOptions(data = conversationVoiceLastData) {
4419
+ const panel = elements.conversationVoiceMenuPanel;
4420
+ if (!panel) return;
4421
+ const source = data || conversationVoiceLastData || {};
4422
+ conversationVoiceLastData = source;
4423
+ const voices = Array.isArray(source?.voices) ? source.voices : [];
4424
+ panel.innerHTML = "";
4425
+ if (elements.conversationVoiceButtonLabel) {
4426
+ elements.conversationVoiceButtonLabel.textContent = source?.current ? conversationVoiceShortLabel(source.current) : "Voice";
4427
+ }
4428
+ if (conversationVoicePending) {
4429
+ const pending = document.createElement("div");
4430
+ pending.className = "composer-publish-menu-item composer-conversation-voice-item composer-conversation-voice-notice pending";
4431
+ pending.setAttribute("role", "status");
4432
+ pending.setAttribute("aria-live", "polite");
4433
+ pending.textContent = conversationVoicePending.message;
4434
+ panel.appendChild(pending);
4435
+ }
4436
+ if (voices.length === 0) {
4437
+ const empty = document.createElement("button");
4438
+ empty.className = "composer-publish-menu-item composer-conversation-voice-item";
4439
+ empty.type = "button";
4440
+ empty.disabled = true;
4441
+ empty.textContent = "No Piper voices — run /talk setup";
4442
+ panel.appendChild(empty);
4443
+ return;
4444
+ }
4445
+ for (const voice of voices) {
4446
+ const item = document.createElement("button");
4447
+ const pendingForItem = conversationVoicePending?.voiceId === voice.id;
4448
+ item.className = "composer-publish-menu-item composer-conversation-voice-item";
4449
+ item.type = "button";
4450
+ item.setAttribute("role", "menuitem");
4451
+ item.dataset.voiceId = voice.id;
4452
+ item.classList.toggle("active", voice.current === true);
4453
+ item.classList.toggle("pending", pendingForItem);
4454
+ const label = conversationVoiceShortLabel(voice.id);
4455
+ item.textContent = pendingForItem
4456
+ ? conversationVoicePending.message
4457
+ : voice.current
4458
+ ? `${label} ✓`
4459
+ : voice.downloaded
4460
+ ? label
4461
+ : `${label} ↓${conversationVoiceDownloadSizeText(voice)}`;
4462
+ item.title = voice.current
4463
+ ? `${voice.note || voice.id} — current voice`
4464
+ : voice.downloaded
4465
+ ? `${voice.note || voice.id} — select this installed Piper voice`
4466
+ : `${voice.note || voice.id} — download and select with /talk voice ${voice.id}`;
4467
+ if (!voice.current) {
4468
+ item.setAttribute("aria-label", voice.downloaded ? `Select conversation voice ${voice.id}` : `Download and select conversation voice ${voice.id}`);
4469
+ }
4470
+ item.disabled = conversationVoiceSwitching || voice.current === true;
4471
+ let pointerActivated = false;
4472
+ const chooseVoice = (event) => {
4473
+ event.preventDefault();
4474
+ event.stopPropagation();
4475
+ void switchConversationVoice(voice.id);
4476
+ };
4477
+ item.addEventListener("pointerdown", (event) => {
4478
+ pointerActivated = true;
4479
+ chooseVoice(event);
4480
+ });
4481
+ item.addEventListener("click", (event) => {
4482
+ if (pointerActivated) {
4483
+ pointerActivated = false;
4484
+ event.preventDefault();
4485
+ event.stopPropagation();
4486
+ return;
4487
+ }
4488
+ chooseVoice(event);
4489
+ });
4490
+ panel.appendChild(item);
4491
+ }
4492
+ }
4493
+
4494
+ async function loadConversationVoices(tabContext = activeTabContext()) {
4495
+ if (!tabContext.tabId) return;
4496
+ try {
4497
+ const response = await api("/api/conversation-voices", { tabId: tabContext.tabId });
4498
+ if (!isCurrentTabContext(tabContext)) return;
4499
+ conversationVoicesLoadedForTab = tabContext.tabId;
4500
+ conversationVoiceLastData = response.data;
4501
+ renderConversationVoiceOptions(response.data);
4502
+ } catch (error) {
4503
+ if (isCurrentTabContext(tabContext)) {
4504
+ conversationVoicesLoadedForTab = null;
4505
+ const message = `conversation voice list failed: ${error.message || String(error)}`;
4506
+ addEvent(message, "warn");
4507
+ renderConversationVoicePanelNotice(message, "error");
4508
+ }
4509
+ }
4510
+ }
4511
+
4512
+ async function switchConversationVoice(voiceId) {
4513
+ const wanted = String(voiceId || "").trim();
4514
+ if (!wanted) return;
4515
+ if (conversationVoiceSwitching) {
4516
+ if (conversationVoicePending?.voiceId === wanted) return;
4517
+ addEvent(`Already switching conversation voice to ${conversationVoicePending?.voiceId || "another voice"}; wait for it to finish.`, "warn");
4518
+ return;
4519
+ }
4520
+ const tabContext = activeTabContext();
4521
+ if (!tabContext.tabId) return;
4522
+ const voice = conversationVoiceById(conversationVoiceLastData, wanted);
4523
+ const downloading = voice?.downloaded !== true;
4524
+ const startMessage = conversationVoiceStartMessage(voice, wanted);
4525
+ conversationVoiceSwitching = true;
4526
+ const label = conversationVoiceShortLabel(wanted);
4527
+ conversationVoicePending = { voiceId: wanted, phase: downloading ? "downloading" : "selecting", message: downloading ? `${label} ↓${conversationVoiceDownloadSizeText(voice)}…` : `${label}…` };
4528
+ setConversationVoiceMenuOpen(true);
4529
+ renderConversationVoiceOptions();
4530
+ if (elements.conversationVoiceButton) elements.conversationVoiceButton.disabled = true;
4531
+ if (elements.conversationVoiceButtonLabel) elements.conversationVoiceButtonLabel.textContent = `→ ${conversationVoiceShortLabel(wanted)}…`;
4532
+ updateConversationModeForTab(tabContext.tabId, {
4533
+ uiState: downloading ? "downloading" : "testing",
4534
+ statusText: downloading ? `Voice: downloading ${wanted} starting` : `Voice: testing ${wanted}`,
4535
+ }, { render: true, voiceLoop: true });
4536
+ showConversationVoiceFeedback(`${startMessage} Progress appears on the Voice chip.`, "info");
4537
+ try {
4538
+ const response = await api("/api/conversation-voice", { method: "POST", body: { voice: wanted }, tabId: tabContext.tabId });
4539
+ if (isCurrentTabContext(tabContext)) {
4540
+ applyResponseTab(response);
4541
+ conversationVoiceLastData = response.data;
4542
+ conversationVoicesLoadedForTab = tabContext.tabId;
4543
+ const current = response.data?.current || wanted;
4544
+ const output = cleanStatusText(response.data?.response?.data?.output || response.data?.response?.data?.message || "");
4545
+ renderConversationVoiceOptions(response.data);
4546
+ showConversationVoiceFeedback(`${downloading ? "Downloaded and selected" : "Selected"} conversation voice ${current}.${output ? ` ${output}` : ""}`, "info");
4547
+ setConversationVoiceMenuOpen(false);
4548
+ }
4549
+ } catch (error) {
4550
+ if (isCurrentTabContext(tabContext)) {
4551
+ updateConversationModeForTab(tabContext.tabId, { uiState: "error", statusText: "Voice: error" }, { render: true, voiceLoop: true });
4552
+ showConversationVoiceFeedback(`Voice switch failed: ${error.message || String(error)}`, "error");
4553
+ await loadConversationVoices(tabContext);
4554
+ }
4555
+ } finally {
4556
+ conversationVoiceSwitching = false;
4557
+ conversationVoicePending = null;
4558
+ if (isCurrentTabContext(tabContext)) {
4559
+ if (elements.conversationVoiceButton) elements.conversationVoiceButton.disabled = false;
4560
+ renderConversationVoiceOptions();
4561
+ renderConversationModeControls();
4562
+ }
4563
+ }
4564
+ }
4565
+
4566
+ // --- Natural Conversation browser voice loop (Phase 3) -----------------------
4567
+ // Browser Web Speech STT/TTS drives the active tab's conversation mode. The
4568
+ // controller logic lives in voice-conversation.mjs (dynamically imported so
4569
+ // app.js stays parseable as a plain script) and is tab-scoped: switching tabs
4570
+ // or disabling the mode tears the loop down.
4571
+
4572
+ const remoteMicConsentTabs = new Set();
4573
+ const VOICE_CONVERSATION_SILENCE_TIMEOUT_MS = 8000;
4574
+ let voiceConversation = null;
4575
+ let voiceConversationTabId = null;
4576
+ let voiceConversationStartToken = 0;
4577
+ let voiceConversationStartingForTab = null;
4578
+ let voiceConversationModulePromise = null;
4579
+
4580
+ function isLocalhostWebui() {
4581
+ const hostname = String(location.hostname || "").toLowerCase();
4582
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
4583
+ }
4584
+
4585
+ function remoteMicConsentGranted(tabId = activeTabId) {
4586
+ if (isLocalhostWebui()) return true;
4587
+ return !!tabId && remoteMicConsentTabs.has(tabId);
4588
+ }
4589
+
4590
+ function remoteMicConsentDisclosureText() {
4591
+ const host = location.host || "this Pi host";
4592
+ const provider = browserSpeechRecognitionCtor() ? "your browser's speech service" : "a browser speech service (unavailable in this browser)";
4593
+ return `Remote session: enabling the microphone captures audio in this browser tab and transcribes it with ${provider}; audio snippets may leave this device to your browser vendor. Only the resulting text transcripts are sent to Pi at ${host} — raw audio is never streamed to the Pi host. Consent applies to this tab only and ends with the conversation. Use End conversation to stop capture at any time.`;
4594
+ }
4595
+
4596
+ function browserSpeechRecognitionCtor() {
4597
+ return window.SpeechRecognition || window.webkitSpeechRecognition || null;
4598
+ }
4599
+
4600
+ function voiceConversationProviderLabel() {
4601
+ const stt = browserSpeechRecognitionCtor() ? "browser mic" : "no browser STT";
4602
+ const tts = window.speechSynthesis ? "browser voice" : "no browser TTS";
4603
+ return `${stt}, ${tts}`;
4604
+ }
4605
+
4606
+ function voiceConversationVisibleProviderLabel() {
4607
+ const hasStt = !!browserSpeechRecognitionCtor();
4608
+ const hasTts = !!window.speechSynthesis;
4609
+ if (hasStt && hasTts) return "browser STT/TTS";
4610
+ if (hasStt) return "browser STT";
4611
+ if (hasTts) return "browser TTS only";
4612
+ return "speech unsupported";
4613
+ }
4614
+
4615
+ function voiceConversationActiveFor(tabId = activeTabId) {
4616
+ return !!voiceConversation && !!tabId && voiceConversationTabId === tabId && voiceConversation.isActive();
4617
+ }
4618
+
4619
+ function updateVoiceConversationModeFromController(tabId = voiceConversationTabId) {
4620
+ if (!tabId || !voiceConversation) return;
4621
+ const state = voiceConversation.getState?.() || {};
4622
+ const uiState = state.uiState || "listening";
4623
+ updateConversationModeForTab(tabId, { uiState, statusText: `Voice: ${uiState}`, partialTranscript: state.partialTranscript || "" }, { render: true, voiceLoop: true });
4624
+ }
4625
+
4626
+ function toggleVoiceConversationPaused() {
4627
+ if (!activeTabId || !activeConversationMode().enabled) return;
4628
+ if (!voiceConversationActiveFor(activeTabId)) {
4629
+ if (!remoteMicConsentGranted(activeTabId)) {
4630
+ addEvent("Remote Web UI session: allow remote microphone streaming before resuming the browser voice loop.", "warn");
4631
+ renderConversationModeControls();
4632
+ return;
4633
+ }
4634
+ void startVoiceConversationLoop(activeTabId);
4635
+ return;
4636
+ }
4637
+ const next = voiceConversation.togglePaused?.();
4638
+ updateVoiceConversationModeFromController(activeTabId);
4639
+ addEvent(next?.userPaused ? "Browser voice loop paused; Natural Conversation safety remains active." : "Browser voice loop resumed.", "info");
4640
+ }
4641
+
4642
+ function loadVoiceConversationModule() {
4643
+ if (!voiceConversationModulePromise) {
4644
+ voiceConversationModulePromise = import("./voice-conversation.mjs?v=1");
4645
+ voiceConversationModulePromise.catch(() => {
4646
+ voiceConversationModulePromise = null;
4647
+ });
4648
+ }
4649
+ return voiceConversationModulePromise;
4650
+ }
4651
+
4652
+ function speakableTextFromMarkdown(text) {
4653
+ return String(text || "")
4654
+ .replace(/```[\s\S]*?```/g, " Code block omitted. ")
4655
+ .replace(/`([^`\n]+)`/g, "$1")
4656
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
4657
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
4658
+ .replace(/^#{1,6}\s+/gm, "")
4659
+ .replace(/^\s*[-*+]\s+/gm, "")
4660
+ .replace(/(\*\*|__|\*|_|~~)(\S(?:[^*_~]*\S)?)\1/g, "$2")
4661
+ .replace(/\s+/g, " ")
4662
+ .trim();
4663
+ }
4664
+
4665
+ function latestAssistantSpokenText() {
4666
+ for (let index = latestMessages.length - 1; index >= 0; index -= 1) {
4667
+ const message = latestMessages[index];
4668
+ if (message?.role !== "assistant") continue;
4669
+ const finalMessage = assistantDisplayMessages(message).find((item) => item?.title === "final output");
4670
+ return finalMessage ? textFromContent(finalMessage.content) : "";
4671
+ }
4672
+ return "";
4673
+ }
4674
+
4675
+ function assistantTextAsksQuestion(text) {
4676
+ const lines = String(text || "").trim().split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
4677
+ const lastLine = lines[lines.length - 1] || "";
4678
+ return /\?["')\]]*$/.test(lastLine);
4679
+ }
4680
+
4681
+ async function startVoiceConversationLoop(tabId = activeTabId) {
4682
+ if (!tabId || voiceConversationActiveFor(tabId) || voiceConversationStartingForTab === tabId) return;
4683
+ if (voiceConversation) stopVoiceConversationLoop();
4684
+ if (!remoteMicConsentGranted(tabId)) {
4685
+ const mode = normalizeConversationModeState(conversationModeByTab.get(tabId) || {});
4686
+ if (mode.uiState !== "paused") {
4687
+ updateConversationModeForTab(tabId, { uiState: "paused", statusText: "Voice: paused" }, { render: true, voiceLoop: true });
4688
+ addEvent("Remote Web UI session: the microphone stays off until you allow remote microphone streaming for this tab.", "warn");
4689
+ }
4690
+ return;
4691
+ }
4692
+ const token = ++voiceConversationStartToken;
4693
+ voiceConversationStartingForTab = tabId;
4694
+ let module = null;
4695
+ try {
4696
+ module = await loadVoiceConversationModule();
4697
+ } catch (error) {
4698
+ addEvent(`failed to load the voice conversation module: ${error?.message || String(error)}`, "error");
4699
+ return;
4700
+ } finally {
4701
+ voiceConversationStartingForTab = null;
4702
+ }
4703
+ if (token !== voiceConversationStartToken || tabId !== activeTabId) return;
4704
+ if (!activeConversationMode().enabled) return;
4705
+ const controller = module.createVoiceConversationController({
4706
+ recognitionFactory: () => {
4707
+ const Recognition = browserSpeechRecognitionCtor();
4708
+ if (!Recognition) return null;
4709
+ try {
4710
+ const recognition = new Recognition();
4711
+ recognition.lang = navigator.language || "en-US";
4712
+ return recognition;
4713
+ } catch {
4714
+ return null;
4715
+ }
4716
+ },
4717
+ synthesis: window.speechSynthesis || null,
4718
+ utteranceFactory: (text) => new SpeechSynthesisUtterance(text),
4719
+ sendTranscript: async (text, { reason } = {}) => {
4720
+ if (!voiceConversationActiveFor(tabId) || tabId !== activeTabId) return;
4721
+ if (reason === "interrupt" && currentState?.isStreaming) {
4722
+ await sendPrompt("steer", `[Voice interruption: the user started speaking over the current answer.] ${text}`, { targetTabId: tabId, throwOnError: true });
4723
+ return;
4724
+ }
4725
+ await sendPrompt("prompt", text, { targetTabId: tabId, throwOnError: true });
4726
+ },
4727
+ sendSilenceEvent: async ({ silentSeconds } = {}) => {
4728
+ if (!voiceConversationActiveFor(tabId) || tabId !== activeTabId) return;
4729
+ await sendPrompt("prompt", module.voiceSilenceEventMessage(silentSeconds), { targetTabId: tabId, throwOnError: true });
4730
+ },
4731
+ onPartialTranscript: (partialTranscript) => {
4732
+ if (voiceConversationTabId !== tabId) return;
4733
+ updateConversationModeForTab(tabId, { uiState: partialTranscript ? "transcribing" : undefined, partialTranscript }, { render: true, voiceLoop: true });
4734
+ },
4735
+ onStateChange: (uiState, state = {}) => {
4736
+ if (voiceConversationTabId !== tabId || uiState === "off") return;
4737
+ updateConversationModeForTab(tabId, { uiState, statusText: `Voice: ${uiState}`, partialTranscript: state.partialTranscript || "" }, { render: true, voiceLoop: true });
4738
+ },
4739
+ onEvent: (message, level = "info") => addEvent(message, level),
4740
+ bargeInEnabled: false,
4741
+ silenceTimeoutMs: VOICE_CONVERSATION_SILENCE_TIMEOUT_MS,
4742
+ });
4743
+ voiceConversation = controller;
4744
+ voiceConversationTabId = tabId;
4745
+ controller.start();
4746
+ }
4747
+
4748
+ function stopVoiceConversationLoop() {
4749
+ voiceConversationStartToken += 1;
4750
+ const controller = voiceConversation;
4751
+ voiceConversation = null;
4752
+ voiceConversationTabId = null;
4753
+ if (controller) {
4754
+ try {
4755
+ controller.stop();
4756
+ } catch {
4757
+ // Tearing down a broken speech engine must not break the UI.
4758
+ }
4759
+ }
4760
+ }
4761
+
4762
+ // The package's native audio loop (mic + Piper TTS on the Pi host) announces
4763
+ // itself through its "natural-conversation-audio" widget. While it is armed —
4764
+ // listening or paused — the browser Web Speech loop must stand down entirely,
4765
+ // otherwise both loops transcribe the same speech and speak every answer twice
4766
+ // (native Piper voice + browser voice).
4767
+ function nativeConversationAudioEngaged() {
4768
+ return widgets.has("natural-conversation-audio");
4769
+ }
4770
+
4771
+ function syncVoiceConversationLoop() {
4772
+ const mode = activeConversationMode();
4773
+ const shouldRun = mode.enabled === true && !!activeTabId && !nativeConversationAudioEngaged();
4774
+ if (voiceConversation && (!shouldRun || voiceConversationTabId !== activeTabId)) stopVoiceConversationLoop();
4775
+ if (shouldRun && !voiceConversationActiveFor(activeTabId)) void startVoiceConversationLoop(activeTabId);
4776
+ }
4777
+
4778
+ async function handleVoiceConversationTurnEnd(tabContext = activeTabContext()) {
4779
+ const tabId = tabContext.tabId;
4780
+ if (!voiceConversationActiveFor(tabId)) return;
4781
+ try {
4782
+ await refreshMessages(tabContext);
4783
+ } catch {
4784
+ // Speak whatever transcript state we already have.
4785
+ }
4786
+ if (!isCurrentTabContext(tabContext) || !voiceConversationActiveFor(tabId)) return;
4787
+ const spoken = speakableTextFromMarkdown(latestAssistantSpokenText());
4788
+ voiceConversation.handleAssistantTurnEnd(spoken, { askedQuestion: assistantTextAsksQuestion(spoken) });
4789
+ }
4790
+
4204
4791
  function renderOptionalFeatureDependentDisplays() {
4205
4792
  renderOptionalFeatureControls();
4206
4793
  renderThemeSelect();
@@ -4339,7 +4926,7 @@ function rgbaColor(rgb, alpha) {
4339
4926
  }
4340
4927
 
4341
4928
  function relativeLuminance(color) {
4342
- const rgb = hexToRgb(color);
4929
+ const rgb = cssColorToRgb(color);
4343
4930
  if (!rgb) return 0;
4344
4931
  const channel = (value) => {
4345
4932
  const normalized = value / 255;
@@ -4449,10 +5036,103 @@ function applyTheme(theme, { persist = false, announce = false } = {}) {
4449
5036
  document.querySelector('meta[name="theme-color"]')?.setAttribute("content", pageBg);
4450
5037
  currentThemeName = theme.name;
4451
5038
  if (elements.themeSelect && elements.themeSelect.value !== theme.name) elements.themeSelect.value = theme.name;
4452
- if (persist) storeThemeName(theme.name);
5039
+ if (persist) {
5040
+ storeSchemeTheme(isLight ? "light" : "dark", theme.name);
5041
+ storeThemeName(theme.name);
5042
+ }
4453
5043
  if (announce) addEvent(`theme changed to ${theme.label || displayThemeName(theme.name) || theme.name}`);
4454
5044
  }
4455
5045
 
5046
+ function osPrefersDark() {
5047
+ return !!(colorSchemeMedia && colorSchemeMedia.matches);
5048
+ }
5049
+
5050
+ function effectiveScheme() {
5051
+ if (themeSchemeMode === "auto") return osPrefersDark() ? "dark" : "light";
5052
+ return themeSchemeMode === "dark" ? "dark" : "light";
5053
+ }
5054
+
5055
+ function themeIsLight(theme) {
5056
+ if (!theme) return false;
5057
+ return relativeLuminance(themeExportColor(theme, "pageBg", "#11111b")) > 0.62;
5058
+ }
5059
+
5060
+ function effectiveThemeName() {
5061
+ const scheme = effectiveScheme();
5062
+ const name = storedSchemeTheme(scheme);
5063
+ if (availableThemes.some((theme) => theme.name === name)) return name;
5064
+ const fallback = scheme === "dark" ? THEME_DARK_DEFAULT : THEME_LIGHT_DEFAULT;
5065
+ if (availableThemes.some((theme) => theme.name === fallback)) return fallback;
5066
+ return availableThemes[0]?.name || fallback;
5067
+ }
5068
+
5069
+ function renderThemeSchemeToggle() {
5070
+ const group = elements.themeSchemeToggle;
5071
+ if (!group) return;
5072
+ for (const button of group.querySelectorAll("[data-scheme-mode]")) {
5073
+ const active = button.dataset.schemeMode === themeSchemeMode;
5074
+ button.classList.toggle("active", active);
5075
+ button.setAttribute("aria-pressed", String(active));
5076
+ }
5077
+ }
5078
+
5079
+ // Apply the theme for the current scheme (mode + OS). Never persists: the scheme
5080
+ // slots and the legacy key only record explicit user picks, so one degraded theme
5081
+ // bundle load cannot clobber stored choices.
5082
+ async function applySchemeTheme(options = {}) {
5083
+ await setThemeByName(effectiveThemeName(), { ...options, persist: false });
5084
+ }
5085
+
5086
+ // A theme picked from the selector/search is assigned to its own light/dark slot.
5087
+ // Persistence happens inside applyTheme, only after the theme was validated and applied.
5088
+ async function chooseTheme(name, options = {}) {
5089
+ await setThemeByName(name, { ...options, persist: true });
5090
+ }
5091
+
5092
+ function handleOsSchemeChange() {
5093
+ if (themeSchemeMode !== "auto") return;
5094
+ applySchemeTheme({ announce: true }).catch((error) => addEvent(error.message || String(error), "error"));
5095
+ }
5096
+
5097
+ function updateColorSchemeListener() {
5098
+ if (!colorSchemeMedia) return;
5099
+ if (typeof colorSchemeMedia.addEventListener === "function") {
5100
+ colorSchemeMedia.removeEventListener("change", handleOsSchemeChange);
5101
+ if (themeSchemeMode === "auto") colorSchemeMedia.addEventListener("change", handleOsSchemeChange);
5102
+ } else {
5103
+ colorSchemeMedia.removeListener?.(handleOsSchemeChange);
5104
+ if (themeSchemeMode === "auto") colorSchemeMedia.addListener?.(handleOsSchemeChange);
5105
+ }
5106
+ }
5107
+
5108
+ async function setThemeSchemeMode(mode, { announce = false } = {}) {
5109
+ if (!THEME_SCHEME_MODES.has(mode)) return;
5110
+ if (themeSchemeMode === mode) {
5111
+ renderThemeSchemeToggle();
5112
+ return;
5113
+ }
5114
+ themeSchemeMode = mode;
5115
+ storeThemeMode(mode);
5116
+ updateColorSchemeListener();
5117
+ renderThemeSchemeToggle();
5118
+ await applySchemeTheme({ announce });
5119
+ }
5120
+
5121
+ // First run with the scheme switch: migrate a pre-existing single theme into the slot
5122
+ // matching its own light/dark scheme and default the mode to that scheme, so existing
5123
+ // users see no change and auto stays opt-in.
5124
+ function seedThemeSchemeFromStoredTheme() {
5125
+ const stored = storedThemeName();
5126
+ const storedTheme = availableThemes.find((theme) => theme.name === stored);
5127
+ // Degraded load (empty bundle or stored theme missing): fall back for this page
5128
+ // load only, without persisting, so the migration retries once the bundle is healthy.
5129
+ if (!storedTheme) return "dark";
5130
+ const scheme = themeIsLight(storedTheme) ? "light" : "dark";
5131
+ storeSchemeTheme(scheme, stored);
5132
+ storeThemeMode(scheme);
5133
+ return scheme;
5134
+ }
5135
+
4456
5136
  function themeDisplayLabel(theme) {
4457
5137
  return theme?.label || displayThemeName(theme?.name) || theme?.name || "";
4458
5138
  }
@@ -4477,10 +5157,13 @@ function renderThemeSearchResults(themes = []) {
4477
5157
  button.setAttribute("role", "option");
4478
5158
  button.setAttribute("aria-selected", String(selected));
4479
5159
  button.title = themeSearchText(theme);
4480
- button.append(make("span", "model-search-result-main", themeDisplayLabel(theme)));
5160
+ const title = make("span", "theme-search-result-title");
5161
+ title.append(make("span", "model-search-result-main", themeDisplayLabel(theme)));
5162
+ title.append(make("span", `theme-search-result-scheme ${themeIsLight(theme) ? "light" : "dark"}`, themeIsLight(theme) ? "Light" : "Dark"));
5163
+ button.append(title);
4481
5164
  button.addEventListener("click", () => {
4482
5165
  if (elements.themeSelect) elements.themeSelect.value = theme.name;
4483
- setThemeByName(theme.name, { persist: true, announce: true }).catch((error) => addEvent(error.message || String(error), "error"));
5166
+ chooseTheme(theme.name, { announce: true }).catch((error) => addEvent(error.message || String(error), "error"));
4484
5167
  });
4485
5168
  elements.themeSearchResults.append(button);
4486
5169
  }
@@ -4582,11 +5265,11 @@ async function initializeThemes() {
4582
5265
  availableThemes = Array.isArray(response.data?.themes) ? response.data.themes : [];
4583
5266
  optionalFeatureAvailability.themeBundle = availableThemes.length > 0;
4584
5267
  renderOptionalFeatureControls();
4585
- const stored = storedThemeName();
4586
- currentThemeName = availableThemes.some((theme) => theme.name === stored) ? stored : DEFAULT_THEME_NAME;
5268
+ themeSchemeMode = storedThemeMode() ?? seedThemeSchemeFromStoredTheme();
4587
5269
  renderThemeSelect();
4588
- await setThemeByName(currentThemeName, { persist: false, includeLegacy: true });
4589
- if (isOptionalFeatureEnabled("themeBundle") && !availableThemes.some((theme) => theme.name === currentThemeName) && availableThemes[0]) await setThemeByName(availableThemes[0].name, { persist: false });
5270
+ renderThemeSchemeToggle();
5271
+ updateColorSchemeListener();
5272
+ await applySchemeTheme({ includeLegacy: true });
4590
5273
  if (!availableThemes.length) addEvent("theme bundle unavailable; using built-in default theme", "warn");
4591
5274
  }
4592
5275
 
@@ -4688,6 +5371,8 @@ function syncTabMetadata(nextTabs = []) {
4688
5371
  widgetsByTab.delete(tabId);
4689
5372
  appRunnerDataByTab.delete(tabId);
4690
5373
  conversationModeByTab.delete(tabId);
5374
+ remoteMicConsentTabs.delete(tabId);
5375
+ if (voiceConversationTabId === tabId) stopVoiceConversationLoop();
4691
5376
  clearGitWorkflowForTab(tabId);
4692
5377
  }
4693
5378
  }
@@ -4879,6 +5564,7 @@ function trackAutoRetryStateFromEvent(event) {
4879
5564
  }
4880
5565
 
4881
5566
  function rememberActiveTab() {
5567
+ if (embeddedSplitMode) return;
4882
5568
  try {
4883
5569
  if (activeTabId) localStorage.setItem(TAB_STORAGE_KEY, activeTabId);
4884
5570
  } catch {
@@ -5031,6 +5717,9 @@ function setWidgetForTab(tabId, widgetKey, request) {
5031
5717
  if (targetTabId === activeTabId) {
5032
5718
  if (hasLines) widgets.set(widgetKey, request);
5033
5719
  else widgets.delete(widgetKey);
5720
+ // Native audio starting/stopping must immediately re-arbitrate which
5721
+ // voice loop (native vs. browser Web Speech) owns this conversation.
5722
+ if (widgetKey === "natural-conversation-audio") queueMicrotask(() => renderConversationModeControls());
5034
5723
  }
5035
5724
 
5036
5725
  return true;
@@ -5429,6 +6118,7 @@ function setNewTabMenuOpen(open) {
5429
6118
 
5430
6119
  function initializeTerminalHeaderTooltips() {
5431
6120
  applyStyledTooltip(elements.newTabButton, "Start a separate isolated Pi terminal", { ariaLabel: "Start a separate isolated Pi terminal" });
6121
+ applyStyledTooltip(elements.splitTabButton, "Split the active terminal to the right", { ariaLabel: "Split the active terminal to the right" });
5432
6122
  applyStyledTooltip(elements.closeAllTabsButton, "Close all terminal tabs", { ariaLabel: "Close all terminal tabs" });
5433
6123
  }
5434
6124
 
@@ -5492,6 +6182,7 @@ function renderTabs() {
5492
6182
  elements.tabBar.append(elements.newTabMenu);
5493
6183
  elements.closeAllTabsButton.disabled = tabs.length === 0;
5494
6184
  updateTerminalTabGroupOpenState();
6185
+ reconcileTerminalSplitState();
5495
6186
  setMobileTabsExpanded(mobileTabsExpanded);
5496
6187
  updateDocumentTitle();
5497
6188
  renderWorkspaceDashboard();
@@ -5526,10 +6217,12 @@ async function switchTab(tabId) {
5526
6217
  footerThinkingPickerOpen = false;
5527
6218
  footerBranchPickerOpen = false;
5528
6219
  footerBranchPickerRequestSerial += 1;
6220
+ if (tabId === splitTabId) closeTerminalSplitView();
5529
6221
  saveActiveDraft();
5530
6222
  cacheMessagesForTab(activeTabId);
5531
6223
  cacheWidgetsForTab(activeTabId);
5532
6224
  const tabContext = setActiveTabId(tabId, { remember: true });
6225
+ if (voiceConversation && voiceConversationTabId !== tabId) stopVoiceConversationLoop();
5533
6226
  resetActiveTabUi();
5534
6227
  renderTabs();
5535
6228
  restoreActiveDraft();
@@ -5543,6 +6236,95 @@ function currentDirectoryForNewTab() {
5543
6236
  return latestWorkspace?.cwd || activeTab()?.cwd || "";
5544
6237
  }
5545
6238
 
6239
+ function terminalSplitTab() {
6240
+ return splitTabId ? tabs.find((tab) => tab.id === splitTabId) || null : null;
6241
+ }
6242
+
6243
+ function terminalSplitFrameUrl(tabId) {
6244
+ const url = new URL("/", window.location.href);
6245
+ url.searchParams.set("embed", "split");
6246
+ url.searchParams.set("tab", tabId);
6247
+ return `${url.pathname}${url.search}`;
6248
+ }
6249
+
6250
+ function updateTerminalSplitUi() {
6251
+ const tab = terminalSplitTab();
6252
+ const canShowSplit = !!tab && !embeddedSplitMode && !isSidePanelOverlayView();
6253
+ document.body.classList.toggle("terminal-split-open", canShowSplit);
6254
+ if (elements.terminalSplitShell) elements.terminalSplitShell.hidden = !canShowSplit;
6255
+ if (elements.splitTabButton) {
6256
+ elements.splitTabButton.disabled = embeddedSplitMode || isSidePanelOverlayView() || !activeTab();
6257
+ elements.splitTabButton.setAttribute("aria-pressed", canShowSplit ? "true" : "false");
6258
+ elements.splitTabButton.dataset.splitState = canShowSplit ? "unsplit" : "split";
6259
+ const label = canShowSplit ? `Close split view for ${tab.title}` : "Split the active terminal to the right";
6260
+ applyStyledTooltip(elements.splitTabButton, label, { ariaLabel: label });
6261
+ }
6262
+ if (!canShowSplit) return;
6263
+ if (elements.terminalSplitTitle) elements.terminalSplitTitle.textContent = tab.title || "Split terminal";
6264
+ if (elements.terminalSplitMeta) elements.terminalSplitMeta.textContent = [tab.running ? `pid ${tab.pid || "starting"}` : "stopped", normalizeDisplayPath(tab.cwd || "")].filter(Boolean).join(" · ");
6265
+ if (elements.terminalSplitFrame && elements.terminalSplitFrame.dataset.tabId !== tab.id) {
6266
+ elements.terminalSplitFrame.dataset.tabId = tab.id;
6267
+ elements.terminalSplitFrame.src = terminalSplitFrameUrl(tab.id);
6268
+ }
6269
+ }
6270
+
6271
+ function closeTerminalSplitView() {
6272
+ splitTabId = null;
6273
+ if (elements.terminalSplitFrame) {
6274
+ elements.terminalSplitFrame.removeAttribute("src");
6275
+ delete elements.terminalSplitFrame.dataset.tabId;
6276
+ }
6277
+ updateTerminalSplitUi();
6278
+ }
6279
+
6280
+ function setTerminalSplitTab(tabId) {
6281
+ splitTabId = tabId || null;
6282
+ updateTerminalSplitUi();
6283
+ }
6284
+
6285
+ function reconcileTerminalSplitState() {
6286
+ if (embeddedSplitMode) return;
6287
+ if (splitTabId && !tabs.some((tab) => tab.id === splitTabId)) {
6288
+ closeTerminalSplitView();
6289
+ return;
6290
+ }
6291
+ updateTerminalSplitUi();
6292
+ }
6293
+
6294
+ async function splitActiveTerminalTab({ triggerButton = elements.splitTabButton } = {}) {
6295
+ if (embeddedSplitMode) return;
6296
+ if (splitTabId) {
6297
+ closeTerminalSplitView();
6298
+ return;
6299
+ }
6300
+ const sourceTab = activeTab();
6301
+ let resolvedCwd = latestWorkspace?.cwd || sourceTab?.cwd || currentDirectoryForNewTab();
6302
+ setMobileTabsExpanded(false);
6303
+ setNewTabMenuOpen(false);
6304
+ if (!resolvedCwd) {
6305
+ resolvedCwd = await pickCwd(sourceTab || { id: "split-terminal", title: "split terminal" }, "", { title: "Choose CWD for split terminal" });
6306
+ if (!resolvedCwd) return;
6307
+ }
6308
+ const disabledButtons = new Set([elements.splitTabButton, triggerButton].filter(Boolean));
6309
+ for (const button of disabledButtons) button.disabled = true;
6310
+ try {
6311
+ const response = await api("/api/tabs", { method: "POST", body: { cwd: resolvedCwd }, scoped: false });
6312
+ tabs = response.data?.tabs || tabs;
6313
+ syncTabMetadata(tabs);
6314
+ const tab = response.data?.tab;
6315
+ if (tab?.id) {
6316
+ setTerminalSplitTab(tab.id);
6317
+ renderTabs();
6318
+ addEvent(`split ${sourceTab?.title || "terminal"} into independent ${tab.title}`, "info");
6319
+ }
6320
+ } catch (error) {
6321
+ addEvent(error.message, "error");
6322
+ } finally {
6323
+ for (const button of disabledButtons) button.disabled = false;
6324
+ updateTerminalSplitUi();
6325
+ }
6326
+ }
6327
+
5546
6328
  async function createTerminalTab(cwd = currentDirectoryForNewTab(), { triggerButton = elements.newTabButton, customGroupId = null } = {}) {
5547
6329
  setMobileTabsExpanded(false);
5548
6330
  setNewTabMenuOpen(false);
@@ -17351,9 +18133,88 @@ function optionalFeaturePackageVersionLabel(status) {
17351
18133
  return status.declaredSpec ? `${status.installedVersion} (expects ${status.declaredSpec})` : status.installedVersion;
17352
18134
  }
17353
18135
 
18136
+ function optionalFeatureInstallState(featureId) {
18137
+ return optionalFeatureInstallStates.get(featureId) || null;
18138
+ }
18139
+
18140
+ function optionalFeatureInstallIsActive(state) {
18141
+ return state && !["done", "failed"].includes(state.phase);
18142
+ }
18143
+
18144
+ function optionalFeatureInstallElapsed(state) {
18145
+ if (!state?.startedAt) return "";
18146
+ return formatDuration((state.endedAt || Date.now()) - state.startedAt);
18147
+ }
18148
+
18149
+ function optionalFeatureInstallPhaseLabel(state) {
18150
+ const actionLabel = state?.actionLabel || "Install";
18151
+ switch (state?.phase) {
18152
+ case "preparing": return `${actionLabel} starting`;
18153
+ case "installing": return `${actionLabel} running`;
18154
+ case "refreshing": return "Checking install";
18155
+ case "done": return `${actionLabel} done`;
18156
+ case "failed": return `${actionLabel} failed`;
18157
+ default: return actionLabel;
18158
+ }
18159
+ }
18160
+
18161
+ function optionalFeatureInstallDetail(state, fallback = "") {
18162
+ const detail = String(state?.detail || fallback || "").trim();
18163
+ const elapsed = optionalFeatureInstallElapsed(state);
18164
+ return [detail, elapsed ? `${state?.endedAt ? "finished after" : "elapsed"} ${elapsed}` : ""].filter(Boolean).join(" · ");
18165
+ }
18166
+
18167
+ function setOptionalFeatureInstallState(featureId, patch = {}) {
18168
+ const previous = optionalFeatureInstallState(featureId) || {};
18169
+ optionalFeatureInstallStates.set(featureId, { ...previous, ...patch });
18170
+ renderOptionalFeaturePanel();
18171
+ }
18172
+
18173
+ function clearOptionalFeatureInstallProgressTimer(featureId) {
18174
+ const timer = optionalFeatureInstallProgressTimers.get(featureId);
18175
+ if (timer) clearInterval(timer);
18176
+ optionalFeatureInstallProgressTimers.delete(featureId);
18177
+ }
18178
+
18179
+ function startOptionalFeatureInstallProgressTimer(featureId) {
18180
+ clearOptionalFeatureInstallProgressTimer(featureId);
18181
+ optionalFeatureInstallProgressTimers.set(featureId, setInterval(() => {
18182
+ if (!optionalFeatureInstallInProgress.has(featureId)) {
18183
+ clearOptionalFeatureInstallProgressTimer(featureId);
18184
+ return;
18185
+ }
18186
+ renderOptionalFeaturePanel();
18187
+ }, 1000));
18188
+ }
18189
+
18190
+ function optionalFeatureInstallFailureFromError(error) {
18191
+ const details = error?.data?.optionalFeatureInstall || {};
18192
+ const message = details.message || error?.message || String(error);
18193
+ const hint = details.hint || (error?.backendOffline
18194
+ ? "The Web UI server connection failed. Check that pi-webui is still running, then retry."
18195
+ : "Run the shown npm command manually from the Web UI host to inspect the full package-manager output.");
18196
+ return { ...details, message, hint, statusCode: error?.statusCode };
18197
+ }
18198
+
18199
+ async function copyOptionalFeatureInstallCommand(featureId) {
18200
+ const state = optionalFeatureInstallState(featureId);
18201
+ const command = String(state?.command || "").trim();
18202
+ if (!command) {
18203
+ addEvent("optional feature install command is not available yet", "warn");
18204
+ return;
18205
+ }
18206
+ try {
18207
+ await copyText(command);
18208
+ addEvent("copied optional feature install command", "info");
18209
+ } catch (error) {
18210
+ addEvent(`optional feature install command copy failed: ${error.message || String(error)}`, "warn");
18211
+ }
18212
+ }
18213
+
17354
18214
  async function refreshOptionalFeaturePackageStatuses({ announce = false } = {}) {
17355
18215
  try {
17356
18216
  const response = await api("/api/optional-features", { scoped: false });
18217
+ optionalFeaturePackageStatusError = "";
17357
18218
  optionalFeaturePackageStatuses.clear();
17358
18219
  for (const status of response.data?.features || []) {
17359
18220
  if (status?.featureId) optionalFeaturePackageStatuses.set(status.featureId, status);
@@ -17361,7 +18222,9 @@ async function refreshOptionalFeaturePackageStatuses({ announce = false } = {})
17361
18222
  renderOptionalFeatureControls();
17362
18223
  return true;
17363
18224
  } catch (error) {
17364
- if (announce) addEvent(`optional feature package status check failed: ${error.message || String(error)}`, "warn");
18225
+ optionalFeaturePackageStatusError = error.message || String(error);
18226
+ renderOptionalFeatureControls();
18227
+ if (announce) addEvent(`optional feature package status check failed: ${optionalFeaturePackageStatusError}`, "warn");
17365
18228
  return false;
17366
18229
  }
17367
18230
  }
@@ -17411,13 +18274,33 @@ function optionalFeatureStatus(featureId) {
17411
18274
  const disabled = isOptionalFeatureDisabled(featureId);
17412
18275
  const packageStatus = optionalFeaturePackageStatus(featureId);
17413
18276
  const installMessage = optionalFeatureInstallMessages.get(featureId);
18277
+ const installState = optionalFeatureInstallState(featureId);
18278
+ const installActive = optionalFeatureInstallInProgress.has(featureId) || optionalFeatureInstallIsActive(installState);
17414
18279
  const versionLabel = optionalFeaturePackageVersionLabel(packageStatus);
17415
18280
  const versionSuffix = versionLabel ? ` · package ${versionLabel}` : "";
17416
- if (optionalFeatureInstallInProgress.has(featureId)) return { label: "Installing", className: "updating", detail: installMessage || "npm install is running; waiting for the package manager to finish" };
18281
+ if (installActive) {
18282
+ return {
18283
+ label: optionalFeatureInstallPhaseLabel(installState),
18284
+ className: "updating",
18285
+ detail: optionalFeatureInstallDetail(installState, installMessage || "npm install is running; waiting for package-manager output"),
18286
+ hint: "The package manager may be quiet for a while; elapsed time updates here until npm exits.",
18287
+ command: installState?.command || "",
18288
+ };
18289
+ }
18290
+ if (installState?.phase === "failed") {
18291
+ return {
18292
+ label: optionalFeatureInstallPhaseLabel(installState),
18293
+ className: "failed",
18294
+ detail: optionalFeatureInstallDetail(installState, installState.detail || installMessage || "npm install failed"),
18295
+ hint: installState.hint || "Copy the npm command and run it manually from the Web UI host for full diagnostics.",
18296
+ command: installState.command || "",
18297
+ };
18298
+ }
18299
+ const doneDetail = installState?.phase === "done" ? optionalFeatureInstallDetail(installState, installMessage) : "";
17417
18300
  if (packageStatus?.updateAvailable) return { label: "Update available", className: "updating", detail: packageStatus.updateReason || `Installed package is older than the Web UI expects${versionSuffix}` };
17418
- if (detected && !disabled) return { label: "Enabled", className: "enabled", detail: `Detected and enabled in Web UI${versionSuffix}` };
18301
+ if (detected && !disabled) return { label: "Enabled", className: "enabled", detail: doneDetail || `Detected and enabled in Web UI${versionSuffix}`, command: installState?.command || "" };
17419
18302
  if (detected && disabled) return { label: "Disabled", className: "disabled", detail: `Detected, but disabled in Web UI${versionSuffix}` };
17420
- if (packageStatus?.installed) return { label: "Installed", className: "installed", detail: `Package is installed but not loaded in the active Pi tab${versionSuffix}` };
18303
+ if (packageStatus?.installed) return { label: "Installed", className: "installed", detail: doneDetail || `Package is installed but not loaded in the active Pi tab${versionSuffix}`, command: installState?.command || "" };
17421
18304
  return { label: "Install needed", className: "missing", detail: installMessage || "Package is not installed or not visible from the Web UI package root" };
17422
18305
  }
17423
18306
 
@@ -17426,12 +18309,14 @@ function optionalFeatureTooltip(feature, status) {
17426
18309
  feature.label,
17427
18310
  `Status: ${status.label}`,
17428
18311
  status.detail,
18312
+ status.hint,
18313
+ status.command ? `Command: ${status.command}` : "",
17429
18314
  "",
17430
18315
  feature.description,
17431
18316
  "",
17432
18317
  `Check: ${feature.capabilityLabel}`,
17433
18318
  `Package: ${feature.packageName}`,
17434
- ].join("\n");
18319
+ ].filter((line) => line !== undefined && line !== null).join("\n");
17435
18320
  }
17436
18321
 
17437
18322
  function optionalFeatureWidgetFeatureId(key) {
@@ -17453,10 +18338,26 @@ function renderOptionalFeaturePanel() {
17453
18338
  elements.optionalFeaturesBox.replaceChildren();
17454
18339
  elements.optionalFeaturesBox.classList.remove("muted");
17455
18340
 
18341
+ if (optionalFeaturePackageStatusError) {
18342
+ const notice = make("div", "optional-feature-panel-notice error");
18343
+ const copy = make("div", "optional-feature-panel-notice-copy");
18344
+ copy.append(
18345
+ make("strong", undefined, "Package status check failed"),
18346
+ make("span", undefined, optionalFeaturePackageStatusError),
18347
+ );
18348
+ const retry = make("button", "optional-feature-action setup", "Retry");
18349
+ retry.type = "button";
18350
+ retry.addEventListener("click", () => refreshOptionalFeaturePackageStatuses({ announce: true }));
18351
+ notice.append(copy, retry);
18352
+ elements.optionalFeaturesBox.append(notice);
18353
+ }
18354
+
17456
18355
  for (const feature of OPTIONAL_FEATURES) {
17457
18356
  const detected = isOptionalFeatureDetected(feature.id);
17458
18357
  const enabled = isOptionalFeatureEnabled(feature.id);
17459
- const installing = optionalFeatureInstallInProgress.has(feature.id);
18358
+ const installState = optionalFeatureInstallState(feature.id);
18359
+ const installing = optionalFeatureInstallInProgress.has(feature.id) || optionalFeatureInstallIsActive(installState);
18360
+ const failed = installState?.phase === "failed";
17460
18361
  const packageStatus = optionalFeaturePackageStatus(feature.id);
17461
18362
  const status = optionalFeatureStatus(feature.id);
17462
18363
  const row = make("div", `optional-feature-row ${status.className}`);
@@ -17469,13 +18370,37 @@ function renderOptionalFeaturePanel() {
17469
18370
  const title = make("div", "optional-feature-title");
17470
18371
  title.append(make("strong", undefined, feature.label), make("span", `optional-feature-pill ${status.className}`, status.label));
17471
18372
  main.append(title);
18373
+ if (status.detail) {
18374
+ const detail = make("div", `optional-feature-detail ${status.className === "failed" ? "error" : ""}`.trim(), status.detail);
18375
+ detail.setAttribute("aria-live", installing ? "polite" : "off");
18376
+ main.append(detail);
18377
+ }
18378
+ if (installing) {
18379
+ const progress = make("div", "optional-feature-progress");
18380
+ progress.setAttribute("aria-hidden", "true");
18381
+ progress.append(make("span"));
18382
+ main.append(progress);
18383
+ }
18384
+ if (status.hint) main.append(make("div", "optional-feature-hint", status.hint));
18385
+ if (status.command) {
18386
+ const command = make("div", "optional-feature-command");
18387
+ command.append(make("code", undefined, status.command));
18388
+ main.append(command);
18389
+ }
18390
+ if (failed && installState?.outputTail) main.append(make("pre", "optional-feature-error-output", installState.outputTail));
17472
18391
 
17473
18392
  const actions = make("div", "optional-feature-actions");
17474
18393
  const action = make("button", "optional-feature-action");
17475
18394
  action.type = "button";
17476
18395
  action.disabled = installing;
17477
18396
  if (installing) {
17478
- action.textContent = "Installing…";
18397
+ action.textContent = installState?.actionLabel === "Update" ? "Updating…" : "Installing…";
18398
+ action.setAttribute("aria-busy", "true");
18399
+ } else if (failed) {
18400
+ const retryAsUpdate = installState?.actionLabel === "Update" || packageStatus?.updateAvailable;
18401
+ action.textContent = "Retry…";
18402
+ action.classList.add(retryAsUpdate ? "update" : "install");
18403
+ action.addEventListener("click", () => installOptionalFeature(feature.id, { update: retryAsUpdate }));
17479
18404
  } else if (packageStatus?.updateAvailable) {
17480
18405
  action.textContent = "Update…";
17481
18406
  action.classList.add("update");
@@ -17492,6 +18417,12 @@ function renderOptionalFeaturePanel() {
17492
18417
  action.addEventListener("click", () => installOptionalFeature(feature.id));
17493
18418
  }
17494
18419
  actions.append(action);
18420
+ if (status.command) {
18421
+ const copyCommand = make("button", "optional-feature-action copy-command", "Copy cmd");
18422
+ copyCommand.type = "button";
18423
+ copyCommand.addEventListener("click", () => copyOptionalFeatureInstallCommand(feature.id));
18424
+ actions.append(copyCommand);
18425
+ }
17495
18426
 
17496
18427
  row.append(main, actions);
17497
18428
  elements.optionalFeaturesBox.append(row);
@@ -17601,27 +18532,67 @@ async function installOptionalFeature(featureId, { update = false } = {}) {
17601
18532
  "",
17602
18533
  `This will run npm install for ${feature.packageName} in the Web UI package install root.`,
17603
18534
  "It can download code from npm and modify the local Pi/Web UI npm installation.",
17604
- "Progress and failures will be shown in the optional-features row and activity log.",
18535
+ "Progress, elapsed time, the npm command, and actionable failures will be shown in the optional-features row and activity log.",
17605
18536
  "If this feature is already installed but disabled in Pi settings, cancel and enable it there instead.",
17606
18537
  "",
17607
18538
  "Continue?",
17608
18539
  ].join("\n");
17609
18540
  if (!confirm(warning)) return;
17610
18541
 
18542
+ const startedAt = Date.now();
17611
18543
  optionalFeatureInstallInProgress.add(featureId);
17612
- optionalFeatureInstallMessages.set(featureId, `${actionLabel} running via npm; waiting for package-manager output…`);
17613
- renderOptionalFeatureControls();
18544
+ optionalFeatureInstallMessages.set(featureId, `${actionLabel} preparing; resolving Web UI package install root…`);
18545
+ setOptionalFeatureInstallState(featureId, {
18546
+ phase: "preparing",
18547
+ actionLabel,
18548
+ startedAt,
18549
+ endedAt: 0,
18550
+ detail: "Resolving safe Web UI package install root…",
18551
+ hint: "The package manager has not started yet.",
18552
+ command: "",
18553
+ outputTail: "",
18554
+ });
18555
+ startOptionalFeatureInstallProgressTimer(featureId);
17614
18556
  addEvent(`${update ? "updating" : "installing"} optional feature ${feature.label} (${feature.packageName})…`, "warn");
18557
+ setTimeout(() => {
18558
+ const state = optionalFeatureInstallState(featureId);
18559
+ if (optionalFeatureInstallInProgress.has(featureId) && state?.startedAt === startedAt && state.phase === "preparing") {
18560
+ optionalFeatureInstallMessages.set(featureId, `${actionLabel} running via npm; waiting for package-manager output…`);
18561
+ setOptionalFeatureInstallState(featureId, {
18562
+ phase: "installing",
18563
+ detail: "npm install is running; waiting for package-manager output…",
18564
+ hint: "npm can be quiet while resolving packages. Keep this page open; elapsed time updates here.",
18565
+ });
18566
+ }
18567
+ }, 1200);
18568
+
17615
18569
  try {
17616
18570
  const response = await api("/api/optional-feature-install", { method: "POST", body: { featureId }, scoped: false });
18571
+ const command = response.data?.command || "";
17617
18572
  disabledOptionalFeatures.delete(featureId);
17618
18573
  storeDisabledOptionalFeatures();
17619
- const command = response.data?.command ? ` · ${response.data.command}` : "";
17620
- optionalFeatureInstallMessages.set(featureId, `${response.data?.message || `${actionLabel} finished`}${command}`);
18574
+ optionalFeatureInstallMessages.set(featureId, response.data?.message || `${actionLabel} finished`);
18575
+ setOptionalFeatureInstallState(featureId, {
18576
+ phase: "refreshing",
18577
+ actionLabel,
18578
+ startedAt,
18579
+ detail: "npm finished; checking package status and refreshed Web UI capabilities…",
18580
+ hint: "If the package is installed but not detected, reload the active Pi tab.",
18581
+ command,
18582
+ outputTail: "",
18583
+ });
17621
18584
  addEvent(response.data?.message || `${update ? "updated" : "installed"} ${feature.packageName}`, "info");
17622
18585
  const output = [response.data?.stderr, response.data?.stdout].filter(Boolean).join("\n").trim();
17623
18586
  if (output) addEvent(`npm output for ${feature.packageName}:\n${output.slice(-4000)}`, "info");
17624
18587
  await refreshOptionalFeaturePackageStatuses({ announce: true });
18588
+ setOptionalFeatureInstallState(featureId, {
18589
+ phase: "done",
18590
+ actionLabel,
18591
+ endedAt: Date.now(),
18592
+ detail: response.data?.message || `${actionLabel} finished. Reload the active Pi tab to load newly installed resources.`,
18593
+ hint: "Use Reload if this row still says Installed instead of Enabled.",
18594
+ command,
18595
+ });
17625
18596
  if (confirm(`${feature.label} ${actionLabel.toLowerCase()} finished. Reload the active Pi tab now to enable newly loaded resources?`)) {
17626
18597
  sendPrompt("prompt", "/reload");
17627
18598
  } else {
@@ -17630,10 +18601,22 @@ async function installOptionalFeature(featureId, { update = false } = {}) {
17630
18601
  if (isCurrentTabContext(tabContext)) renderOptionalFeatureControls();
17631
18602
  }
17632
18603
  } catch (error) {
17633
- optionalFeatureInstallMessages.set(featureId, `${actionLabel} failed: ${error.message || String(error)}`);
17634
- addEvent(error.message || String(error), "error");
18604
+ const failure = optionalFeatureInstallFailureFromError(error);
18605
+ optionalFeatureInstallMessages.set(featureId, `${actionLabel} failed: ${failure.message}`);
18606
+ setOptionalFeatureInstallState(featureId, {
18607
+ phase: "failed",
18608
+ actionLabel,
18609
+ endedAt: Date.now(),
18610
+ detail: failure.message,
18611
+ hint: failure.hint,
18612
+ command: failure.command || optionalFeatureInstallState(featureId)?.command || "",
18613
+ outputTail: failure.outputTail || "",
18614
+ errorKind: failure.kind || "unknown",
18615
+ });
18616
+ addEvent(`${actionLabel.toLowerCase()} optional feature ${feature.label} failed: ${failure.message}${failure.hint ? `\nHint: ${failure.hint}` : ""}`, "error");
17635
18617
  } finally {
17636
18618
  optionalFeatureInstallInProgress.delete(featureId);
18619
+ clearOptionalFeatureInstallProgressTimer(featureId);
17637
18620
  renderOptionalFeatureControls();
17638
18621
  }
17639
18622
  }
@@ -17849,7 +18832,7 @@ function openNativeThemeSelector() {
17849
18832
  activeId: currentThemeName,
17850
18833
  onSelect: async (item) => {
17851
18834
  try {
17852
- await setThemeByName(item.theme.name, { persist: true, announce: true });
18835
+ await chooseTheme(item.theme.name, { announce: true });
17853
18836
  addTransientMessage({ role: "native", title: "/theme", content: `Theme set to ${item.label}.`, level: "info" });
17854
18837
  closeNativeCommandDialog();
17855
18838
  } catch (error) {
@@ -20243,7 +21226,7 @@ function updateServerActionButton() {
20243
21226
  button.classList.toggle("danger", action === "stop");
20244
21227
  if (action === "restart") setServerActionStatus("Ready to restart the Web UI server.", "info");
20245
21228
  else if (action === "update") setServerActionStatus("Ready to run pi update for Pi only, then restart the Web UI server.", "info");
20246
- else if (action === "update-all") setServerActionStatus("Ready to run pi update --all for Pi and configured packages, then restart the Web UI server.", "info");
21229
+ else if (action === "update-all") setServerActionStatus("Ready to run pi update --all plus detected Web UI/Optional Feature Pi package root updates, then restart the Web UI server.", "info");
20247
21230
  else if (action === "stop") setServerActionStatus("Ready to stop the Web UI server.", "info");
20248
21231
  else setServerActionStatus();
20249
21232
  }
@@ -20553,6 +21536,7 @@ async function sendPrompt(kind = "prompt", explicitMessage, { targetTabId = acti
20553
21536
  const rawMessage = usesPromptInput ? elements.promptInput.value : explicitMessage;
20554
21537
  const originalMessage = String(rawMessage || "").trim();
20555
21538
  if (!targetTabId) return;
21539
+ if (voiceConversationActiveFor(targetTabId)) voiceConversation.handleUserActivity();
20556
21540
  const tabContext = activeTabContext(targetTabId);
20557
21541
  const attachments = usesPromptInput ? [...attachmentsForTab(targetTabId)] : [];
20558
21542
  if (!originalMessage && attachments.length === 0) return;
@@ -20987,6 +21971,7 @@ function handleEvent(event) {
20987
21971
  break;
20988
21972
  case "agent_start":
20989
21973
  if (currentState) currentState = { ...currentState, isStreaming: true };
21974
+ if (voiceConversationActiveFor(event.tabId || activeTabId)) voiceConversation.setAssistantActivity({ streaming: true });
20990
21975
  setRunIndicatorActivity("Agent run started; waiting for first output or action…");
20991
21976
  addEvent("agent started");
20992
21977
  scheduleRefreshState();
@@ -20999,6 +21984,10 @@ function handleEvent(event) {
20999
21984
  notifyAgentDone(event.tabId || activeTabId, { activity: event.tabActivity, tabTitle: event.tabTitle });
21000
21985
  clearContextUsageUnknownAfterCompaction(event.tabId || activeTabId);
21001
21986
  if (currentState) currentState = { ...currentState, isStreaming: false };
21987
+ // handleAssistantTurnEnd resets the controller's streaming/tool flags and
21988
+ // flushes queued interruptions itself; calling setAssistantActivity here
21989
+ // first would flush the queue and then speak the interrupted answer.
21990
+ if (voiceConversationActiveFor(event.tabId || activeTabId)) void handleVoiceConversationTurnEnd(tabContext);
21002
21991
  clearRunIndicatorActivity();
21003
21992
  markTabOutputSeen();
21004
21993
  requestGitFooterWebuiPayload(tabContext, { force: true });
@@ -21038,6 +22027,7 @@ function handleEvent(event) {
21038
22027
  break;
21039
22028
  case "tool_execution_start":
21040
22029
  streamToolCallSeen = true;
22030
+ if (voiceConversationActiveFor(event.tabId || activeTabId)) voiceConversation.setAssistantActivity({ toolRunning: true });
21041
22031
  suppressStreamingAssistantTextBeforeToolCall();
21042
22032
  removeStreamingToolCallCard();
21043
22033
  handleToolExecutionStart(event);
@@ -21049,6 +22039,7 @@ function handleEvent(event) {
21049
22039
  setRunIndicatorActivity(`Running tool: ${runIndicatorToolName(event.toolName)}…`, { scroll: false });
21050
22040
  break;
21051
22041
  case "tool_execution_end":
22042
+ if (voiceConversationActiveFor(event.tabId || activeTabId)) voiceConversation.setAssistantActivity({ toolRunning: false });
21052
22043
  handleToolExecutionEnd(event);
21053
22044
  setRunIndicatorActivity(`Tool ${runIndicatorToolName(event.toolName)} ${event.isError ? "failed" : "finished"}; waiting for the agent's next step…`);
21054
22045
  addEvent(`tool ${event.toolName} ${event.isError ? "failed" : "finished"}`, event.isError ? "error" : "info");
@@ -21312,6 +22303,8 @@ elements.newTabMenu?.addEventListener("focusout", () => {
21312
22303
  elements.newTabCurrentDirectoryButton?.addEventListener("click", () => createTerminalTab(currentDirectoryForNewTab(), { triggerButton: elements.newTabCurrentDirectoryButton }));
21313
22304
  elements.newTabChooseDirectoryButton?.addEventListener("click", () => createTerminalTabFromChosenDirectory({ triggerButton: elements.newTabChooseDirectoryButton }));
21314
22305
  elements.newTabWorktreeButton?.addEventListener("click", () => openBranchWorktreePicker());
22306
+ elements.splitTabButton?.addEventListener("click", () => splitActiveTerminalTab());
22307
+ elements.terminalSplitCloseButton?.addEventListener("click", () => closeTerminalSplitView());
21315
22308
  elements.closeAllTabsButton.addEventListener("click", () => closeAllTerminalTabs());
21316
22309
  elements.commandPaletteButton?.addEventListener("click", () => openCommandPalette());
21317
22310
  elements.workspaceDashboardToggleButton?.addEventListener("click", () => setWorkspaceDashboardCollapsed(!workspaceDashboardCollapsed));
@@ -21442,8 +22435,27 @@ elements.nativeSkillsButton.addEventListener("click", () => runNativeCommandMenu
21442
22435
  elements.nativeToolsButton.addEventListener("click", () => runNativeCommandMenu("/tools"));
21443
22436
  elements.optionsCommandPaletteButton.addEventListener("click", () => openCommandPalette());
21444
22437
  elements.optionsConversationModeButton?.addEventListener("click", () => toggleNaturalConversationMode());
21445
- elements.conversationModeChip?.addEventListener("click", () => toggleNaturalConversationMode());
22438
+ elements.conversationModeChip?.addEventListener("click", () => toggleVoiceConversationPaused());
21446
22439
  elements.conversationModeEndButton?.addEventListener("click", () => setNaturalConversationModeEnabled(false));
22440
+ // The voice menu opens on click (and on hover/focus via CSS on desktop);
22441
+ // refresh the voice list whenever it is opened so download states stay fresh.
22442
+ elements.conversationVoiceButton?.addEventListener("click", () => {
22443
+ setConversationVoiceMenuOpen(!conversationVoiceMenuOpen);
22444
+ if (conversationVoiceMenuOpen && !conversationVoiceSwitching) void loadConversationVoices();
22445
+ });
22446
+ elements.conversationVoiceMenu?.addEventListener("pointerenter", () => {
22447
+ if (!conversationVoiceSwitching) void loadConversationVoices();
22448
+ });
22449
+ elements.conversationVoiceMenu?.addEventListener("pointerleave", () => setConversationVoiceMenuOpen(false));
22450
+ elements.conversationVoiceMenu?.addEventListener("focusin", () => {
22451
+ if (!conversationVoiceSwitching) void loadConversationVoices();
22452
+ });
22453
+ elements.remoteMicStreamingConsentButton?.addEventListener("click", () => {
22454
+ if (!activeTabId) return;
22455
+ remoteMicConsentTabs.add(activeTabId);
22456
+ addEvent("Remote microphone streaming allowed for this tab. Consent ends with the conversation or the tab.", "info");
22457
+ renderConversationModeControls();
22458
+ });
21447
22459
  elements.optionsResumeButton.addEventListener("click", () => runNativeCommandMenu("/resume"));
21448
22460
  elements.optionsReloadButton.addEventListener("click", () => runNativeCommandMenu("/reload"));
21449
22461
  elements.optionsRemoteButton.addEventListener("click", () => runNativeCommandMenu("/remote"));
@@ -21838,7 +22850,7 @@ elements.themeSearchInput?.addEventListener("keydown", (event) => {
21838
22850
  if (event.key === "Enter") {
21839
22851
  event.preventDefault();
21840
22852
  const [theme] = populateThemeSelect(availableThemes, elements.themeSearchInput.value);
21841
- if (theme) setThemeByName(theme.name, { persist: true, announce: true }).catch((error) => addEvent(error.message || String(error), "error"));
22853
+ if (theme) chooseTheme(theme.name, { announce: true }).catch((error) => addEvent(error.message || String(error), "error"));
21842
22854
  } else if (event.key === "Escape") {
21843
22855
  elements.themeSearchInput.value = "";
21844
22856
  populateThemeSelect(availableThemes, "");
@@ -21846,7 +22858,12 @@ elements.themeSearchInput?.addEventListener("keydown", (event) => {
21846
22858
  }
21847
22859
  });
21848
22860
  elements.themeSelect.addEventListener("change", () => {
21849
- setThemeByName(elements.themeSelect.value, { persist: true, announce: true }).catch((error) => addEvent(error.message || String(error), "error"));
22861
+ chooseTheme(elements.themeSelect.value, { announce: true }).catch((error) => addEvent(error.message || String(error), "error"));
22862
+ });
22863
+ elements.themeSchemeToggle?.querySelectorAll("[data-scheme-mode]").forEach((button) => {
22864
+ button.addEventListener("click", () => {
22865
+ setThemeSchemeMode(button.dataset.schemeMode, { announce: true }).catch((error) => addEvent(error.message || String(error), "error"));
22866
+ });
21850
22867
  });
21851
22868
  if (elements.backgroundChooseButton && elements.backgroundInput) {
21852
22869
  elements.backgroundChooseButton.addEventListener("click", () => elements.backgroundInput.click());
@@ -21942,6 +22959,9 @@ document.addEventListener("pointerdown", (event) => {
21942
22959
  if (optionsMenuOpen && !event.target?.closest?.(".composer-options-menu")) {
21943
22960
  setOptionsMenuOpen(false);
21944
22961
  }
22962
+ if (conversationVoiceMenuOpen && !event.target?.closest?.(".composer-conversation-voice-menu")) {
22963
+ setConversationVoiceMenuOpen(false);
22964
+ }
21945
22965
  if (busyPromptBehaviorMenuOpen && !event.target?.closest?.(".composer-context-tags, .composer-busy-mode-menu")) {
21946
22966
  setBusyPromptBehaviorMenuOpen(false);
21947
22967
  }
@@ -22168,6 +23188,10 @@ window.addEventListener("keydown", (event) => {
22168
23188
  setOptionsMenuOpen(false);
22169
23189
  return;
22170
23190
  }
23191
+ if (conversationVoiceMenuOpen) {
23192
+ setConversationVoiceMenuOpen(false);
23193
+ return;
23194
+ }
22171
23195
  if (busyPromptBehaviorMenuOpen) {
22172
23196
  setBusyPromptBehaviorMenuOpen(false);
22173
23197
  elements.busyPromptBehaviorTag?.focus({ preventScroll: true });