Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(live-voice): dock the call bar as a global desktop widget
vastsaa875e4931998
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex f7cdf9a21..bf86467a6 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -53,6 +53,7 @@ import { registerIpcHandlers } from "./ipc/register";import { createVoiceService } from "./voice-service";import { MicrophoneLeaseRegistry } from "./live-voice/microphone-lease";import { createLiveCallService } from "./live-voice/runtime";+import { createLiveVoiceWidget } from "./live-voice/widget-window";import { getActiveRemoteHostsBoot } from "./bootstrap/remote-hosts";import { installLiveMicrophonePermissionHandlers } from "./live-voice/microphone-permissions";import { MainProcessState } from "./bootstrap/main-state";@@ -835,6 +836,16 @@ const voiceService = createVoiceService((token) => microphoneLeases.acquire("dictation", token),);voiceServiceReference = voiceService;+// The docked call widget: a desktop-level window that shows the call chrome+// wherever the user put it and sends every action back to this window, which+// stays the Live Voice owner (media, microphone lease, work scope).+const liveVoiceWidget = createLiveVoiceWidget({+ getMainWindow,+ dataDir,+ safeOpenExternal,+ log: (message, data) => logger.app("diagnostics", "warn", message, data ? { data } : undefined),+});+const liveCallService = createLiveCallService({getHost,getMainWindow,@@ -852,6 +863,7 @@ const liveCallService = createLiveCallService({});},log: (level, message, data) => logger.app("provider", level, message, { data }),+ onCallView: (view) => liveVoiceWidget.publish(view),});function registerIpc() {@@ -950,6 +962,7 @@ function registerIpc() {sendToRenderer,voiceService,liveCallService,+ liveVoiceWidget,});}@@ -994,6 +1007,9 @@ app.once("ready", () => {powerMonitor.on("lock-screen", () => void liveCallService.endForLifecycle("app-suspended"));});+// The widget is chrome for a call this window owns; it must never outlive the app.+app.once("will-quit", () => liveVoiceWidget.close());+registerApplicationStartup({hasSingleInstanceLock,state: startupState,diff --git a/apps/desktop/electron/main/ipc/live-voice-ipc.ts b/apps/desktop/electron/main/ipc/live-voice-ipc.tsindex 123bf0b62..7505e0f95 100644--- a/apps/desktop/electron/main/ipc/live-voice-ipc.ts+++ b/apps/desktop/electron/main/ipc/live-voice-ipc.ts@@ -1,8 +1,10 @@import type { BrowserWindow, IpcMainInvokeEvent } from "electron";-import { IPC, type LiveEndReason } from "@pi-desktop/shared";+import { IPC, type LiveEndReason, type LiveVoiceWidgetAction } from "@pi-desktop/shared";import type { LiveCallService as LiveCallServiceImpl, LiveOwner } from "../live-voice/call-service";import { liveOwnerFromInvoke } from "../live-voice/owner";import type { IpcRegistrar } from "./types";+import type { LiveVoiceWidget } from "../live-voice/widget-window";+import type { LiveVoiceWidgetSize } from "../live-voice/widget-geometry";const END_REASONS = new Set(["user-ended", "user-cancelled-start", "window-hidden", "window-navigated", "renderer-gone",@@ -14,13 +16,25 @@ export function registerLiveVoiceIpc(input: {registrar: IpcRegistrar;service: LiveCallServiceImpl;getMainWindow: () => BrowserWindow | null;+ /** The docked widget window: not a call owner, but allowed to drive its chrome. */+ widget: Pick<LiveVoiceWidget, "owns" | "setPresentation" | "requestAction" | "setIssue">;}): void {- const { registrar, service, getMainWindow } = input;+ const { registrar, service, getMainWindow, widget } = input;const owner = (event: IpcMainInvokeEvent): LiveOwner => {registrar.assertMainWindowSender(event);return liveOwnerFromInvoke(event, getMainWindow());};+ // The widget window is not the call owner: it may only ask the owner frame to+ // run an action and report the box its own content needs.+ const assertWidgetSender = (event: IpcMainInvokeEvent): void => {+ if (!widget.owns(event.sender.id)) {+ throw Object.assign(new Error("renderer is not the Live Voice widget"), {+ errorCode: "PERMISSION_DENIED",+ });+ }+ };+registrar.handleWithEvent(IPC.invoke.liveVoiceStatus, async (event) => {owner(event);return service.status();@@ -65,6 +79,27 @@ export function registerLiveVoiceIpc(input: {registrar.handleWithEvent(IPC.invoke.liveVoiceCancelQueuedOperation, async (event, raw: unknown) => {return service.cancelQueuedWorkOperation(owner(event), parseWorkOperationControl(raw));});+ // The widget's own two channels: it reports the box its content needs and the+ // actions its buttons ask for. Actions run in the owner frame, never here.+ registrar.handleWithEvent(IPC.invoke.liveVoiceWidgetVisibility, async (event, raw: unknown) => {+ assertWidgetSender(event);+ const presentation = parseWidgetPresentation(raw);+ widget.setPresentation(presentation.visible, presentation);+ return { ok: true };+ });+ registrar.handleWithEvent(IPC.invoke.liveVoiceWidgetAction, async (event, raw: unknown) => {+ assertWidgetSender(event);+ widget.requestAction(parseWidgetAction(raw));+ return { ok: true };+ });+ // The owner frame's own failure code: a refused action is local to the frame+ // that ran it and never appears in the call view, so the widget can only name+ // it if the owner reports it here.+ registrar.handleWithEvent(IPC.invoke.liveVoiceWidgetIssue, async (event, raw: unknown) => {+ registrar.assertMainWindowSender(event);+ widget.setIssue(parseWidgetIssue(raw));+ return { ok: true };+ });}export function parseWorkOperationControl(raw: unknown): { callId: string; operationId: string } {@@ -212,3 +247,31 @@ function callId(value: unknown): string {function invalid(): never {throw Object.assign(new Error("Live Voice request is invalid"), { errorCode: "LIVE_PROTOCOL_ERROR" });}++const WIDGET_ACTIONS = new Set<LiveVoiceWidgetAction>(["cancel", "mute", "resume", "end", "details", "settings"]);++export function parseWidgetAction(raw: unknown): LiveVoiceWidgetAction {+ const input = record(raw);+ exactKeys(input, ["action"]);+ if (typeof input.action !== "string" || !WIDGET_ACTIONS.has(input.action as LiveVoiceWidgetAction)) return invalid();+ return input.action as LiveVoiceWidgetAction;+}++/**+ * The widget's own measured content box. Sizes outside the bar's own range are+ * clamped by the window layer, so only the shape is validated here.+ */+export function parseWidgetPresentation(raw: unknown): { visible: boolean } & LiveVoiceWidgetSize {+ const input = record(raw);+ exactKeys(input, ["visible", "width", "height"]);+ if (typeof input.visible !== "boolean" || !Number.isFinite(input.width) || !Number.isFinite(input.height)) return invalid();+ return { visible: input.visible, width: input.width as number, height: input.height as number };+}++/** The owner frame's own failure code for the call it is running. */+export function parseWidgetIssue(raw: unknown): { callId: string; code: string | null } {+ const input = record(raw);+ exactKeys(input, ["callId", "code"]);+ if (input.code !== null && (typeof input.code !== "string" || !input.code || input.code.length > 80)) return invalid();+ return { callId: callId(input.callId), code: input.code as string | null };+}diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.tsindex 5cd6004cc..b46aed90a 100644--- a/apps/desktop/electron/main/ipc/register.ts+++ b/apps/desktop/electron/main/ipc/register.ts@@ -33,6 +33,7 @@ import { registerSpeechIpc } from "./speech-ipc";import { registerVoiceIpc } from "./voice-ipc";import { registerLiveVoiceIpc } from "./live-voice-ipc";import type { LiveCallService } from "../live-voice/call-service";+import type { LiveVoiceWidget } from "../live-voice/widget-window";import type { IpcRegistrar } from "./types";import type { createTraySessions } from "../tray-sessions";import type { createTaskbarUnreadBadge } from "../taskbar-unread-badge";@@ -58,6 +59,7 @@ export type RegisterIpcDependencies = {activeUserSubagentDocuments: (...args: any[]) => Promise<any>;disabledBuiltinSubagents: () => Promise<string[]>;liveCallService?: LiveCallService;+ liveVoiceWidget?: LiveVoiceWidget;mcpOAuth?: McpOAuthManager;[name: string]: any;};@@ -163,6 +165,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {sendToRenderer,voiceService,liveCallService,+ liveVoiceWidget,} = dependencies;@@ -467,8 +470,8 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {if (voiceService) {registerVoiceIpc({ registrar, voiceService });}- if (liveCallService) {- registerLiveVoiceIpc({ registrar, service: liveCallService, getMainWindow });+ if (liveCallService && liveVoiceWidget) {+ registerLiveVoiceIpc({ registrar, service: liveCallService, getMainWindow, widget: liveVoiceWidget });}registerRemoteHostIpc({ registrar });diff --git a/apps/desktop/electron/main/live-voice/runtime.ts b/apps/desktop/electron/main/live-voice/runtime.tsindex 89a0f0506..90fb99d5a 100644--- a/apps/desktop/electron/main/live-voice/runtime.ts+++ b/apps/desktop/electron/main/live-voice/runtime.ts@@ -1,5 +1,5 @@import { net, type BrowserWindow, type WebContents } from "electron";-import { IPC, type AppSettings } from "@pi-desktop/shared";+import { IPC, type AppSettings, type LiveCallView } from "@pi-desktop/shared";import type { VendorOAuth } from "../oauth";import type { HostProcess } from "../host-process";import type { AgentHostBridge } from "../agent-host-bridge";@@ -31,6 +31,12 @@ export function createLiveCallService(input: {getBackendRouter?: () => BackendRouter | null;getRemoteHosts?: () => RemoteHostsBoot | null;vendorOAuth: Pick<VendorOAuth, "resolveAuth">;+ /**+ * Every published call view, for chrome outside the owner frame — the docked+ * Live Voice widget window. The owner frame keeps receiving the same view+ * through `IPC.event.liveVoiceChanged`.+ */+ onCallView?: (view: LiveCallView | null) => void;microphoneLeases: MicrophoneLeaseRegistry;resolveAgentRuntimeLaunch: (sessionId: string,@@ -155,7 +161,10 @@ export function createLiveCallService(input: {ownerFrame: frame,});},- sendView: (owner, view) => sendToOwner(input.getMainWindow(), owner, IPC.event.liveVoiceChanged, view),+ sendView: (owner, view) => {+ sendToOwner(input.getMainWindow(), owner, IPC.event.liveVoiceChanged, view);+ input.onCallView?.(view);+ },sendControl: (owner, event) => sendToOwner(input.getMainWindow(), owner, IPC.event.liveVoiceControl, event),sendTranscript: (owner, event) => sendToOwner(input.getMainWindow(), owner, IPC.event.liveVoiceTranscript, event),ownerAlive: (owner) => liveOwnerFrame(input.getMainWindow(), owner) !== null,diff --git a/apps/desktop/electron/main/live-voice/widget-geometry.ts b/apps/desktop/electron/main/live-voice/widget-geometry.tsnew file mode 100644index 000000000..3afa3f3ed--- /dev/null+++ b/apps/desktop/electron/main/live-voice/widget-geometry.ts@@ -0,0 +1,73 @@+/**+ * Geometry for the docked Live Voice widget window.+ *+ * Kept apart from the window module so the placement arithmetic can be proven+ * without Electron. The window itself is frameless, transparent, always on top+ * and dragged through its own app-region handle, so the only geometry left to+ * decide is where a saved placement and the widget's own reported box may land:+ * a placement saved on a wider display, or by a hand-edited preference file,+ * must never strand the call controls off-screen.+ */++/** Smallest gap the widget keeps to any edge of the work area. */+export const LIVE_VOICE_WIDGET_MARGIN = 8;+/** Default content box before the widget has reported its own measured size. */+export const LIVE_VOICE_WIDGET_SIZE = { width: 420, height: 64 };+export const LIVE_VOICE_WIDGET_MIN_WIDTH = 220;+export const LIVE_VOICE_WIDGET_MAX_WIDTH = 680;+export const LIVE_VOICE_WIDGET_MIN_HEIGHT = 40;+export const LIVE_VOICE_WIDGET_MAX_HEIGHT = 260;++export type LiveVoiceWidgetPosition = { x: number; y: number };+export type LiveVoiceWidgetSize = { width: number; height: number };+/** A display's usable box; Electron reports this shape as `Rectangle`. */+export type LiveVoiceWidgetWorkArea = { x: number; y: number; width: number; height: number };++function finite(value: unknown): number | null {+ return typeof value === "number" && Number.isFinite(value) ? value : null;+}++/** Parse a stored position, treating anything malformed as "never dragged". */+export function parseLiveVoiceWidgetPosition(raw: string | null): LiveVoiceWidgetPosition | null {+ if (!raw) return null;+ try {+ const parsed: unknown = JSON.parse(raw);+ if (!parsed || typeof parsed !== "object") return null;+ const record = parsed as Record<string, unknown>;+ const x = finite(record.x);+ const y = finite(record.y);+ if (x === null || y === null) return null;+ return { x: Math.round(x), y: Math.round(y) };+ } catch {+ return null;+ }+}++/** Keep a whole window inside the work area, never off its edges. */+export function clampLiveVoiceWidgetPosition(+ position: LiveVoiceWidgetPosition,+ size: LiveVoiceWidgetSize,+ workArea: LiveVoiceWidgetWorkArea,+ margin = LIVE_VOICE_WIDGET_MARGIN,+): LiveVoiceWidgetPosition {+ const left = workArea.x + margin;+ const top = workArea.y + margin;+ // A widget wider or taller than the work area pins to the leading edge instead+ // of computing a maximum past it.+ const maximumX = Math.max(left, workArea.x + workArea.width - size.width - margin);+ const maximumY = Math.max(top, workArea.y + workArea.height - size.height - margin);+ return {+ x: Math.round(Math.min(Math.max(position.x, left), maximumX)),+ y: Math.round(Math.min(Math.max(position.y, top), maximumY)),+ };+}++/** A measured content box from the widget, bounded to what the bar can need. */+export function clampLiveVoiceWidgetSize(size: LiveVoiceWidgetSize): LiveVoiceWidgetSize {+ const width = finite(size.width) ?? LIVE_VOICE_WIDGET_SIZE.width;+ const height = finite(size.height) ?? LIVE_VOICE_WIDGET_SIZE.height;+ return {+ width: Math.round(Math.min(Math.max(width, LIVE_VOICE_WIDGET_MIN_WIDTH), LIVE_VOICE_WIDGET_MAX_WIDTH)),+ height: Math.round(Math.min(Math.max(height, LIVE_VOICE_WIDGET_MIN_HEIGHT), LIVE_VOICE_WIDGET_MAX_HEIGHT)),+ };+}diff --git a/apps/desktop/electron/main/live-voice/widget-window.ts b/apps/desktop/electron/main/live-voice/widget-window.tsnew file mode 100644index 000000000..f48fa7788--- /dev/null+++ b/apps/desktop/electron/main/live-voice/widget-window.ts@@ -0,0 +1,304 @@+import { app, BrowserWindow, screen, type Rectangle } from "electron";+import { readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { IPC, type LiveCallView, type LiveVoiceWidgetAction } from "@pi-desktop/shared";+import { getModuleDirectory } from "../module-path";+import { suppressLinuxFramelessSystemMenu } from "../frameless-system-menu";++/**+ * The docked Live Voice widget: the call chrome as a desktop-level window.+ *+ * The call itself stays owned by the main window (media, microphone lease,+ * provider transport and the work scope all live there), so this window is+ * presentation plus a thin remote control: main pushes the authoritative call+ * state in, the widget sends actions back out, and every action is executed by+ * the main window's controller. Nothing here mutates the call.+ *+ * The window is frameless, transparent and always on top, and it is dragged+ * through the renderer's `app-region: drag` handle, so the only geometry this+ * module owns is the remembered position: the widget reports the size its own+ * content needs, and both the size and the position are clamped into the work+ * area so a saved placement can never strand the controls off-screen.+ */++export const LIVE_VOICE_WIDGET_STATE_FILE = "live-voice-widget.json";+import {+ LIVE_VOICE_WIDGET_MAX_HEIGHT,+ LIVE_VOICE_WIDGET_MAX_WIDTH,+ LIVE_VOICE_WIDGET_MIN_HEIGHT,+ LIVE_VOICE_WIDGET_MIN_WIDTH,+ LIVE_VOICE_WIDGET_SIZE,+ clampLiveVoiceWidgetPosition,+ clampLiveVoiceWidgetSize,+ parseLiveVoiceWidgetPosition,+ type LiveVoiceWidgetPosition,+ type LiveVoiceWidgetSize,+} from "./widget-geometry";++export type LiveVoiceWidget = {+ /** Push the authoritative call view; the window appears on the first call. */+ publish: (view: LiveCallView | null) => void;+ /**+ * The owner frame's own failure code for this call (`LIVE_PLAYBACK_FAILED`, a+ * refused action). It never appears in the call view — it is local to the+ * frame that ran the action — so the widget can only name it if the owner+ * reports it, and it is dropped as soon as the call it belongs to changes.+ */+ setIssue: (issue: { callId: string; code: string | null }) => void;+ /** True when these contents are the widget window's own renderer. */+ owns: (webContentsId: number) => boolean;+ /** Follow the widget's own presentation decision and measured content box. */+ setPresentation: (visible: boolean, size: LiveVoiceWidgetSize) => void;+ /** Ask the owner frame (the main window) to run a call action. */+ requestAction: (action: LiveVoiceWidgetAction) => void;+ close: () => void;+};++export function createLiveVoiceWidget(input: {+ getMainWindow: () => BrowserWindow | null;+ dataDir: string;+ safeOpenExternal: (rawUrl: unknown) => Promise<void>;+ log?: (message: string, data?: Record<string, unknown>) => void;+}): LiveVoiceWidget {+ let window: BrowserWindow | null = null;+ let creation: Promise<BrowserWindow | null> | null = null;+ let loaded = false;+ let lastView: LiveCallView | null = null;+ let lastErrorCode: string | undefined;+ let visible = false;+ let size: LiveVoiceWidgetSize = { ...LIVE_VOICE_WIDGET_SIZE };+ let saveTimer: ReturnType<typeof setTimeout> | null = null;++ const statePath = join(input.dataDir, LIVE_VOICE_WIDGET_STATE_FILE);++ function readPosition(): LiveVoiceWidgetPosition | null {+ try {+ return parseLiveVoiceWidgetPosition(readFileSync(statePath, "utf8"));+ } catch {+ return null;+ }+ }++ function writePosition(position: LiveVoiceWidgetPosition): void {+ try {+ writeFileSync(statePath, `${JSON.stringify(position)}\n`, "utf8");+ } catch (error) {+ // A position that cannot be written costs the remembered placement only.+ input.log?.("live voice widget position was not saved", { data: String(error) });+ }+ }++ function workAreaFor(position: LiveVoiceWidgetPosition | null): Rectangle {+ const fallback = screen.getPrimaryDisplay();+ if (!position) return fallback.workArea;+ return screen.getDisplayMatching({ x: position.x, y: position.y, width: 1, height: 1 }).workArea;+ }++ function initialBounds(): { x: number; y: number; width: number; height: number } {+ const stored = readPosition();+ const workArea = workAreaFor(stored);+ const preferred = stored ?? {+ x: workArea.x + workArea.width - size.width,+ y: workArea.y + workArea.height - size.height,+ };+ const position = clampLiveVoiceWidgetPosition(preferred, size, workArea);+ return { ...position, ...size };+ }++ function savePosition(): void {+ const current = window;+ if (!current || current.isDestroyed()) return;+ const bounds = current.getBounds();+ writePosition({ x: bounds.x, y: bounds.y });+ }++ function schedulePositionSave(): void {+ if (saveTimer) clearTimeout(saveTimer);+ saveTimer = setTimeout(() => {+ saveTimer = null;+ savePosition();+ }, 400);+ }++ function sendView(): void {+ const current = window;+ if (!current || current.isDestroyed() || !loaded || !lastView) return;+ current.webContents.send(IPC.event.liveVoiceWidgetState, {+ call: lastView,+ ...(lastErrorCode ? { errorCode: lastErrorCode } : {}),+ });+ }++ async function ensureWindow(): Promise<BrowserWindow | null> {+ if (window && !window.isDestroyed()) return window;+ if (creation) return creation;+ const promise = (async () => {+ const created = new BrowserWindow({+ ...initialBounds(),+ title: "PI-Desktop Live Voice",+ show: false,+ frame: false,+ transparent: true,+ backgroundColor: "#00000000",+ hasShadow: false,+ resizable: true,+ minimizable: false,+ maximizable: false,+ fullscreenable: false,+ skipTaskbar: true,+ alwaysOnTop: true,+ autoHideMenuBar: true,+ minWidth: LIVE_VOICE_WIDGET_MIN_WIDTH,+ maxWidth: LIVE_VOICE_WIDGET_MAX_WIDTH,+ minHeight: LIVE_VOICE_WIDGET_MIN_HEIGHT,+ maxHeight: LIVE_VOICE_WIDGET_MAX_HEIGHT,+ useContentSize: true,+ ...(process.platform === "darwin" ? { type: "panel" as const } : {}),+ webPreferences: {+ preload: join(getModuleDirectory(import.meta.url), "../preload/index.cjs"),+ contextIsolation: true,+ nodeIntegration: false,+ sandbox: true,+ additionalArguments: [`--pi-desktop-locale=${app.getLocale()}`],+ },+ });+ window = created;+ suppressLinuxFramelessSystemMenu(created);++ if (process.platform === "darwin") {+ // Follow the launcher (ADR 0086): join every Space and float above this+ // app's own fullscreen window without transforming the whole process+ // into a UI-element application.+ created.setVisibleOnAllWorkspaces(true, {+ visibleOnFullScreen: true,+ skipTransformProcessType: true,+ });+ }+ created.webContents.setWindowOpenHandler(({ url }) => {+ void input.safeOpenExternal(url).catch(() => undefined);+ return { action: "deny" };+ });+ created.webContents.on("will-navigate", (event, url) => {+ const devOrigin = process.env.ELECTRON_RENDERER_URL;+ if (devOrigin && url.startsWith(devOrigin)) return;+ event.preventDefault();+ });+ created.webContents.on("did-finish-load", () => {+ loaded = true;+ sendView();+ });+ created.on("moved", schedulePositionSave);+ created.on("closed", () => {+ if (window === created) window = null;+ loaded = false;+ });++ try {+ if (process.env.ELECTRON_RENDERER_URL) {+ const url = new URL(process.env.ELECTRON_RENDERER_URL);+ url.searchParams.set("surface", "live-voice-widget");+ await created.loadURL(url.toString());+ } else {+ await created.loadFile(+ join(getModuleDirectory(import.meta.url), "../renderer/index.html"),+ { query: { surface: "live-voice-widget" } },+ );+ }+ return created;+ } catch (error) {+ if (!created.isDestroyed()) created.destroy();+ if (window === created) window = null;+ input.log?.("live voice widget window failed to load", { data: String(error) });+ return null;+ }+ })();+ creation = promise;+ void promise.then(() => {+ if (creation === promise) creation = null;+ });+ return promise;+ }++ function applyBounds(next: { x: number; y: number; width: number; height: number }): void {+ const current = window;+ if (!current || current.isDestroyed()) return;+ const bounds = current.getBounds();+ if (bounds.x === next.x && bounds.y === next.y && bounds.width === next.width && bounds.height === next.height) return;+ current.setBounds(next, false);+ }++ return {+ publish(view) {+ // A new call starts blank: the previous call's failure must not be named+ // over the next one.+ if (view?.callId !== lastView?.callId) lastErrorCode = undefined;+ lastView = view;+ if (view || window) void ensureWindow().then(sendView);+ },+ setIssue(issue) {+ if (lastView?.callId !== issue.callId) return;+ lastErrorCode = issue.code ?? undefined;+ sendView();+ },+ owns(webContentsId) {+ return Boolean(window && !window.isDestroyed() && window.webContents.id === webContentsId);+ },+ setPresentation(nextVisible, nextSize) {+ visible = nextVisible;+ size = clampLiveVoiceWidgetSize(nextSize);+ const current = window;+ if (!visible) {+ if (current && !current.isDestroyed() && current.isVisible()) {+ // Hiding keeps the renderer warm for the next call and saves the+ // placement the user dragged to.+ savePosition();+ current.hide();+ }+ return;+ }+ void ensureWindow().then((created) => {+ if (!created || created.isDestroyed() || !visible) return;+ const workArea = screen.getDisplayMatching({+ x: created.getBounds().x,+ y: created.getBounds().y,+ width: 1,+ height: 1,+ }).workArea;+ const position = clampLiveVoiceWidgetPosition(+ { x: created.getBounds().x, y: created.getBounds().y },+ size,+ workArea,+ );+ applyBounds({ ...position, ...size });+ if (!created.isVisible()) {+ // Appearing must not steal focus from whatever the user is doing.+ created.showInactive();+ }+ sendView();+ });+ },+ requestAction(action) {+ const main = input.getMainWindow();+ if (!main || main.isDestroyed()) return;+ if (action === "details" || action === "settings") {+ // The details surface and the Settings route live in the main window,+ // so the action has to hand the user over to it.+ if (main.isMinimized()) main.restore();+ if (!main.isVisible()) main.show();+ main.focus();+ }+ main.webContents.send(IPC.event.liveVoiceWidgetAction, { action });+ },+ close() {+ if (saveTimer) {+ clearTimeout(saveTimer);+ saveTimer = null;+ }+ savePosition();+ const current = window;+ window = null;+ loaded = false;+ if (current && !current.isDestroyed()) current.destroy();+ },+ };+}diff --git a/apps/desktop/src/features/voice/live/LiveVoiceCallBar.tsx b/apps/desktop/src/features/voice/live/LiveVoiceCallBar.tsxindex cfd366728..4dca7dd55 100644--- a/apps/desktop/src/features/voice/live/LiveVoiceCallBar.tsx+++ b/apps/desktop/src/features/voice/live/LiveVoiceCallBar.tsx@@ -1,9 +1,8 @@-import { useEffect, useRef, type RefObject } from "react";+import { type RefObject } from "react";import type { TFunction } from "i18next";import { IconClose, IconInfo, IconMic, IconMicOff, IconPhoneOff, IconSettings, IconVolume, IconWaveform } from "../../../components/icons";import { TooltipButton } from "../../../components/ui";import type { LiveVoiceSnapshot } from "./live-call-controller";-import { useAppStore } from "../../../stores/app-store";import { liveVoiceMode, type liveVoiceIssue } from "./live-voice-presentation";type CallBarProps = {@@ -22,36 +21,18 @@ type CallBarProps = {onDismiss: () => void;};+/**+ * The compact call bar, drawn by the docked widget window from the state main+ * pushes. It is presentation only — the widget owns no media and is not the+ * call owner, so every button forwards an action instead of reaching a+ * controller — and it is the only call chrome the user sees. A failure that+ * outlives a toast is therefore drawn in place next to its verbatim `LIVE_*`+ * code, because nothing else on screen could name it.+ */export function LiveVoiceCallBar({t, snapshot, issue, detailsOpen, detailsRef, actionPending,onCancel, onMute, onEnd, onDetails, onResume, onSettings, onDismiss,}: CallBarProps) {- // Live Voice failures are one-shot results of the call actions, so they are- // reported through the global toast together with their allow-listed code.- // Only call states that outlive a toast stay in the bar: the playback hint and- // the quarantine that still has to confirm the microphone was released.- const issueStaysInline = !issue || issue.warning || issue.code === "LIVE_MEDIA_RELEASE_UNCONFIRMED";- const showToast = useAppStore((state) => state.showToast);- const reportedIssue = useRef<string | null>(null);- // Starting an action clears the mark: a retry that fails the same way is a new- // failure and has to speak up again, not be swallowed as a repeat of the last- // one. The call itself is preserved across a reconnect, so the key alone- // cannot tell the two apart.- const previousActionPending = useRef(actionPending);- useEffect(() => {- const startedAttempt =- actionPending !== null && previousActionPending.current === null;- previousActionPending.current = actionPending;- if (startedAttempt) reportedIssue.current = null;- if (issueStaysInline || !issue) {- reportedIssue.current = null;- return;- }- if (reportedIssue.current === issue.key) return;- reportedIssue.current = issue.key;- showToast(`${t(issue.message)} (${issue.code})`, { variant: "error" });- }, [actionPending, issue, issueStaysInline, showToast, t]);-const mode = liveVoiceMode(snapshot);const call = snapshot.call;const status = mode === "stopping" ? "liveVoice.phase.closing"@@ -123,7 +104,7 @@ export function LiveVoiceCallBar({) : null}</div></div>- {issue && issueStaysInline ? (+ {issue ? (<p className={issue.warning ? "live-voice-feedback live-voice-hint" : "live-voice-feedback live-voice-error"} role={issue.warning ? "status" : "alert"}>{t(issue.message)}{/* The localized sentence alone cannot say whether authentication,diff --git a/apps/desktop/src/features/voice/live/LiveVoiceDetails.tsx b/apps/desktop/src/features/voice/live/LiveVoiceDetails.tsxindex 49035c950..b792f43a6 100644--- a/apps/desktop/src/features/voice/live/LiveVoiceDetails.tsx+++ b/apps/desktop/src/features/voice/live/LiveVoiceDetails.tsx@@ -16,7 +16,7 @@ export function LiveVoiceDetails({ t, call, status, transcripts, open, onClose,transcripts: LiveTranscriptSegment[];open: boolean;onClose: () => void;- anchorRef: RefObject<HTMLButtonElement | null>;+ anchorRef: RefObject<HTMLElement | null>;}) {const activeSessionId = useAppStore((state) => state.activeSessionId);const sessions = useAppStore((state) => state.sessions);diff --git a/apps/desktop/src/features/voice/live/LiveVoicePreparation.tsx b/apps/desktop/src/features/voice/live/LiveVoicePreparation.tsxindex 350645dab..1d9612824 100644--- a/apps/desktop/src/features/voice/live/LiveVoicePreparation.tsx+++ b/apps/desktop/src/features/voice/live/LiveVoicePreparation.tsx@@ -1,4 +1,4 @@-import { useId, useState } from "react";+import { useState } from "react";import type { TFunction } from "i18next";import type { LiveStatus } from "@pi-desktop/shared";import { IconClose, IconPlay, IconSettings } from "../../../components/icons";@@ -14,7 +14,6 @@ export function LiveVoicePreparation({ t, status, workSessionId, onClose }: {onClose: () => void;}) {const [shareSelectedSessionContext, setShareSelectedSessionContext] = useState(false);- const consentId = useId();const binding = selectedLiveBinding(status);const readinessMessage = liveReadinessMessage(status);@@ -35,16 +34,16 @@ export function LiveVoicePreparation({ t, status, workSessionId, onClose }: {<IconSettings size={16} aria-hidden="true" /></TooltipButton></div>+ {/* Only a blocking cause earns a line here: the panel states what the call+ will do and what it will not share through its own controls, so a+ paragraph of prose above Start would only push Start out of reach. */}{readinessMessage ? <p className="live-voice-hint" role="status">{t(readinessMessage)}</p> : null}- <p className="live-voice-hint" role="status">{t("liveVoice.sessionSelectionVoice")}</p><div className="live-voice-work-setup"><Checkboxchecked={shareSelectedSessionContext}label={t("liveVoice.shareContext")}- aria-describedby={consentId}onChange={(event) => setShareSelectedSessionContext(event.currentTarget.checked)}/>- <p id={consentId} className="live-voice-hint">{t("liveVoice.contextConsent")}</p></div><Buttontype="button"diff --git a/apps/desktop/src/features/voice/live/LiveVoiceStatusHost.tsx b/apps/desktop/src/features/voice/live/LiveVoiceStatusHost.tsxindex 6b4e18866..ffac77a38 100644--- a/apps/desktop/src/features/voice/live/LiveVoiceStatusHost.tsx+++ b/apps/desktop/src/features/voice/live/LiveVoiceStatusHost.tsx@@ -1,84 +1,101 @@import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";import { useTranslation } from "react-i18next";-import { useAppStore } from "../../../stores/app-store";+import type { LiveVoiceWidgetAction } from "@pi-desktop/shared";import { getLiveCallController } from "./live-call-controller";+import { liveVoiceApi } from "./live-voice-api";import { openLiveVoiceSettings } from "./live-voice-navigation";-import { hasUnconfirmedMediaRelease, liveVoiceIssue, liveVoiceMode } from "./live-voice-presentation";-import { LiveVoiceCallBar } from "./LiveVoiceCallBar";+import { liveVoiceIssue, liveVoiceMode } from "./live-voice-presentation";import { LiveVoiceDetails } from "./LiveVoiceDetails";import "../../../styles/voice.css";-/** Call chrome survives route changes; mounting it never owns or starts media. */+/**+ * The main window's half of the call chrome.+ *+ * The call cannot move to the widget window: this frame owns the microphone,+ * the media, the provider transport and the call-scoped work. So the docked+ * widget draws the compact bar and forwards each press, and this host runs the+ * action with the real controller — including the failures only this frame can+ * observe, which it reports so the widget can name them in place — and keeps the+ * details surface, whose provider, transcript and work targets come from this+ * window's store.+ */export function LiveVoiceStatusHost() {const { t } = useTranslation();- const page = useAppStore((state) => state.page);const controller = getLiveCallController();const snapshot = useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);const [detailsOpen, setDetailsOpen] = useState(false);- const [dismissedIssue, setDismissedIssue] = useState<string | null>(null);- const [actionPending, setActionPending] = useState<"mute" | "playback" | null>(null);const [actionFailure, setActionFailure] = useState<{ callId?: string; code: string } | null>(null);- const hostRef = useRef<HTMLDivElement>(null);- const detailsRef = useRef<HTMLButtonElement>(null);+ const anchorRef = useRef<HTMLDivElement>(null);+ const snapshotRef = useRef(snapshot);const mode = liveVoiceMode(snapshot);- const previousMode = useRef(mode);const callId = snapshot.call?.callId;+ snapshotRef.current = snapshot;+ // A refused action is local to this frame: the call view never carries it, so+ // it is folded into the issue the widget is told to draw.const issue = liveVoiceIssue(actionFailure && actionFailure.callId === callId? { ...snapshot, errorCode: snapshot.errorCode ?? actionFailure.code }: snapshot);- const closeDetails = useCallback(() => setDetailsOpen(false), []);useEffect(() => {setDetailsOpen(false);- setDismissedIssue(null);setActionFailure(null);- setActionPending(null);}, [callId]);useEffect(() => {- if (mode === "connecting") setDismissedIssue(null);if (mode === "stopping" || mode === "idle") setDetailsOpen(false);- if ((mode === "connecting" && previousMode.current === "idle") ||- (mode === "connected" && document.activeElement === document.body)) {- hostRef.current?.querySelector<HTMLButtonElement>("button:not(:disabled)")?.focus();- }- previousMode.current = mode;}, [mode]);- const runAction = (action: () => Promise<void>, pending?: "mute" | "playback") => {+ // The widget window is the only call chrome, so the failure this frame owns —+ // a refused mute, a playback retry that failed — has to reach it.+ useEffect(() => {+ if (!callId) return;+ void liveVoiceApi.reportWidgetIssue({ callId, code: issue?.code ?? null }).catch(() => undefined);+ }, [callId, issue?.code]);++ const runAction = useCallback((action: () => Promise<void>, pending?: "mute" | "playback") => {setActionFailure(null);- if (pending) setActionPending(pending);+ const startedFor = controller.getSnapshot().call?.callId;void action().catch(() => {- if (controller.getSnapshot().call?.callId === callId) {- setActionFailure({ callId, code: pending === "playback" ? "LIVE_PLAYBACK_FAILED" : "LIVE_CALL_ACTION_FAILED" });+ if (controller.getSnapshot().call?.callId === startedFor) {+ setActionFailure({+ callId: startedFor,+ code: pending === "playback" ? "LIVE_PLAYBACK_FAILED" : "LIVE_CALL_ACTION_FAILED",+ });}- }).finally(() => {- if (controller.getSnapshot().call?.callId === callId) setActionPending(null);});- };+ }, [controller]);- const releaseUnconfirmed = hasUnconfirmedMediaRelease(snapshot);- const hasVisibleIssue = issue && (releaseUnconfirmed || issue.key !== dismissedIssue) &&- (snapshot.status?.enabled === true || snapshot.call?.error || releaseUnconfirmed);- if (mode === "idle" && !hasVisibleIssue) return null;+ // The widget window owns the buttons; every press arrives here as an action.+ useEffect(() => liveVoiceApi.onWidgetAction(({ action }: { action: LiveVoiceWidgetAction }) => {+ const current = snapshotRef.current;+ switch (action) {+ case "cancel":+ runAction(() => (current.starting ? controller.cancelStart() : controller.end()));+ break;+ case "mute":+ runAction(() => controller.toggleMute(), "mute");+ break;+ case "resume":+ runAction(() => controller.resumePlayback(), "playback");+ break;+ case "end":+ runAction(() => controller.end());+ break;+ case "details":+ setDetailsOpen(true);+ break;+ case "settings":+ openLiveVoiceSettings();+ break;+ }+ }), [controller, runAction]);return (- <div ref={hostRef} className="live-voice-status-host" data-chat={page === "chat"} role="region" aria-label={t("liveVoice.title")}>- <LiveVoiceCallBar- t={t}- snapshot={snapshot}- issue={issue}- detailsOpen={detailsOpen}- detailsRef={detailsRef}- actionPending={actionPending}- onCancel={() => runAction(() => snapshot.starting ? controller.cancelStart() : controller.end())}- onMute={() => runAction(() => controller.toggleMute(), "mute")}- onEnd={() => runAction(() => controller.end())}- onDetails={() => setDetailsOpen((value) => !value)}- onResume={() => runAction(() => controller.resumePlayback(), "playback")}- onSettings={openLiveVoiceSettings}- onDismiss={() => { setDismissedIssue(issue?.key ?? null); setDetailsOpen(false); }}- />+ <>+ {/* Details has no trigger in this window any more — the widget's button+ opens it — so it hangs from a fixed point the shell can still show,+ just above the composer. */}+ <div ref={anchorRef} className="live-voice-details-anchor" aria-hidden="true" />{snapshot.call ? (<LiveVoiceDetailskey={snapshot.call.callId}@@ -87,10 +104,10 @@ export function LiveVoiceStatusHost() {status={snapshot.status}transcripts={snapshot.transcripts}open={detailsOpen}- onClose={closeDetails}- anchorRef={detailsRef}+ onClose={() => setDetailsOpen(false)}+ anchorRef={anchorRef}/>) : null}- </div>+ </>);}diff --git a/apps/desktop/src/features/voice/live/LiveVoiceWidget.tsx b/apps/desktop/src/features/voice/live/LiveVoiceWidget.tsxnew file mode 100644index 000000000..d8ed5dc4b--- /dev/null+++ b/apps/desktop/src/features/voice/live/LiveVoiceWidget.tsx@@ -0,0 +1,112 @@+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { IPC, type AppSettings, type LiveCallView, type LiveVoiceWidgetAction } from "@pi-desktop/shared";+import { LiveVoiceCallBar } from "./LiveVoiceCallBar";+import { liveVoiceApi } from "./live-voice-api";+import { applyAppLanguage } from "../../../lib/app-language";+import { liveVoiceIssue, liveVoiceWidgetSnapshot, liveVoiceWidgetVisible } from "./live-voice-presentation";+import "../../../styles/voice.css";+import "../../../styles/live-voice-widget.css";++type WidgetState = { call: LiveCallView | null; errorCode?: string };++/**+ * The docked call widget: the call chrome as its own always-on-top window, so a+ * running call stays visible and controllable while the user works in another+ * application.+ *+ * The window is a view, never an owner. Main pushes the authoritative call view+ * in (plus the owner frame's own failure code, which the call view cannot+ * carry); this component decides whether there is anything to show at all,+ * reports the exact box its content needs — a transparent window must not keep+ * dead space that swallows clicks — and forwards every button to main, which+ * runs it in the main window: the frame that owns the microphone, the media and+ * the call-scoped work.+ */+export function LiveVoiceWidget() {+ const { t } = useTranslation();+ const [state, setState] = useState<WidgetState>({ call: null });+ const [dismissedIssue, setDismissedIssue] = useState<string | null>(null);+ const shellRef = useRef<HTMLDivElement>(null);+ const detailsRef = useRef<HTMLButtonElement>(null);++ const snapshot = useMemo(() => liveVoiceWidgetSnapshot(state.call, state.errorCode), [state]);+ const issue = liveVoiceIssue(snapshot);+ const visible = liveVoiceWidgetVisible(snapshot, dismissedIssue);++ // The widget window is not the app shell: it never boots the shared settings+ // store, so the persisted language is applied here and refreshed whenever a+ // call brings the widget back on screen (the setting may have changed since).+ useEffect(() => {+ if (!visible) return;+ let cancelled = false;+ void (async () => {+ const result = await window.piDesktop+ ?.invoke<AppSettings>(IPC.invoke.settingsGet)+ .catch(() => null);+ if (cancelled || !result?.ok) return;+ applyAppLanguage(result.data?.language);+ })();+ return () => { cancelled = true; };+ }, [visible]);++ const callId = state.call?.callId;++ useEffect(() => liveVoiceApi.onWidgetState((next) => setState(next)), []);++ // Every call starts with a clean presentation: a failure the user dismissed+ // during the last call must not stay silent during the next one.+ useEffect(() => {+ setDismissedIssue(null);+ }, [callId]);+ // The window follows the content: main shows exactly the box drawn here, and+ // the bar grows when a failure line or a wider action row appears.+ useLayoutEffect(() => {+ const shell = shellRef.current;+ if (!shell) return;+ const report = () => {+ const rect = shell.getBoundingClientRect();+ // A status row that must not fold can still be wider than the window the+ // bar is currently drawn in: the scroll box is the width it needs, so the+ // window grows to the content instead of clipping the controls away.+ void liveVoiceApi.setWidgetPresentation({+ visible,+ width: Math.ceil(Math.max(rect.width, shell.scrollWidth)),+ height: Math.ceil(Math.max(rect.height, shell.scrollHeight)),+ }).catch(() => undefined);+ };+ report();+ if (typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(report);+ observer.observe(shell);+ return () => observer.disconnect();+ }, [issue?.key, state, visible]);++ const request = useCallback((action: LiveVoiceWidgetAction) => {+ void liveVoiceApi.requestWidgetAction(action).catch(() => undefined);+ }, []);++ return (+ <div className="live-voice-widget" ref={shellRef}>+ {/* Nothing to show means nothing drawn: a hidden widget must not keep the+ bar's box alive for main to show or to swallow desktop clicks. */}+ {visible ? (+ <LiveVoiceCallBar+ t={t}+ snapshot={snapshot}+ issue={issue}+ detailsOpen={false}+ detailsRef={detailsRef}+ actionPending={null}+ onCancel={() => request("cancel")}+ onMute={() => request("mute")}+ onEnd={() => request("end")}+ onDetails={() => request("details")}+ onResume={() => request("resume")}+ onSettings={() => request("settings")}+ onDismiss={() => setDismissedIssue(issue?.key ?? null)}+ />+ ) : null}+ </div>+ );+}diff --git a/apps/desktop/src/features/voice/live/live-voice-api.ts b/apps/desktop/src/features/voice/live/live-voice-api.tsindex 034f4c20f..e59d96ecf 100644--- a/apps/desktop/src/features/voice/live/live-voice-api.ts+++ b/apps/desktop/src/features/voice/live/live-voice-api.ts@@ -13,6 +13,7 @@ import {type LiveTranscriptEvent,type LiveWorkCancelQueuedOperationResult,type LiveWorkStopOperationResult,+ type LiveVoiceWidgetAction,} from "@pi-desktop/shared";import type { LiveCallView } from "@pi-desktop/shared";@@ -43,9 +44,21 @@ export const liveVoiceApi = {>(IPC.invoke.liveVoiceResolveWorkSelection, input),stopWorkOperation: (input: { callId: string; operationId: string }) => invoke<LiveWorkStopOperationResult>(IPC.invoke.liveVoiceStopWorkOperation, input),cancelQueuedWorkOperation: (input: { callId: string; operationId: string }) => invoke<LiveWorkCancelQueuedOperationResult>(IPC.invoke.liveVoiceCancelQueuedOperation, input),+ // The docked widget window: main pushes the owner's call view in, and the+ // widget asks the owner frame (through main) to run the actions it owns.+ setWidgetPresentation: (input: { visible: boolean; width: number; height: number }) =>+ invoke<{ ok: true }>(IPC.invoke.liveVoiceWidgetVisibility, input),+ requestWidgetAction: (action: LiveVoiceWidgetAction) =>+ invoke<{ ok: true }>(IPC.invoke.liveVoiceWidgetAction, { action }),+ reportWidgetIssue: (input: { callId: string; code: string | null }) =>+ invoke<{ ok: true }>(IPC.invoke.liveVoiceWidgetIssue, input),onView: (listener: (view: LiveCallView) => void) => subscribe(IPC.event.liveVoiceChanged, listener),onControl: (listener: (event: LiveControlEvent) => void) => subscribe(IPC.event.liveVoiceControl, listener),onTranscript: (listener: (event: LiveTranscriptEvent) => void) => subscribe(IPC.event.liveVoiceTranscript, listener),+ onWidgetState: (listener: (state: { call: LiveCallView | null; errorCode?: string }) => void) =>+ subscribe(IPC.event.liveVoiceWidgetState, listener),+ onWidgetAction: (listener: (event: { action: LiveVoiceWidgetAction }) => void) =>+ subscribe(IPC.event.liveVoiceWidgetAction, listener),};function subscribe<T>(channel: string, listener: (value: T) => void): () => void {diff --git a/apps/desktop/src/features/voice/live/live-voice-presentation.ts b/apps/desktop/src/features/voice/live/live-voice-presentation.tsindex 4869a7ddf..2dd652f06 100644--- a/apps/desktop/src/features/voice/live/live-voice-presentation.ts+++ b/apps/desktop/src/features/voice/live/live-voice-presentation.ts@@ -1,4 +1,4 @@-import type { LiveStatus } from "@pi-desktop/shared";+import type { LiveCallView, LiveStatus } from "@pi-desktop/shared";import type { LiveVoiceSnapshot } from "./live-call-controller";import { liveVoiceErrorKey } from "./live-voice-error";@@ -82,3 +82,42 @@ export function formatWorkSessionLabel(projectPath: string | undefined, title: sconst sessionLabel = title.trim() || untitledLabel;return projectLabel ? `${projectLabel} / ${sessionLabel}` : sessionLabel;}++/**+ * The docked widget window renders the view main pushes; it never runs the call+ * (media, microphone lease and work scope stay in the owner frame), so the+ * owner's local lifecycle flags cannot cross to it. Both are recoverable from+ * the view: a closing phase is stopping, and so is a terminal phase whose+ * renderer release is still pending — the bar keeps saying "Ending" until the+ * release is confirmed rather than dropping the controls early.+ */+export function liveVoiceWidgetSnapshot(view: LiveCallView | null, ownerErrorCode?: string): LiveVoiceSnapshot {+ const stopping = view?.phase === "closing" ||+ ((view?.phase === "ended" || view?.phase === "failed") && view?.mediaRelease === "pending");+ // The owner frame's own failure wins: a refused action is local to the frame+ // that ran it and never reaches the call view. The quarantine is a+ // `mediaRelease` value in the view and a code everywhere else, so it is+ // translated here — the widget must keep that one failure on screen until the+ // app restarts, and it can only do that by code.+ const errorCode = view?.mediaRelease === "unconfirmed"+ ? "LIVE_MEDIA_RELEASE_UNCONFIRMED"+ : ownerErrorCode ?? view?.error?.code;+ return {+ status: null,+ call: view,+ transcripts: [],+ starting: false,+ stopping,+ ...(errorCode ? { errorCode } : {}),+ };+}++/** Whether the docked widget has anything to show at all. */+export function liveVoiceWidgetVisible(snapshot: LiveVoiceSnapshot, dismissedIssue: string | null): boolean {+ if (liveVoiceMode(snapshot) !== "idle") return true;+ const issue = liveVoiceIssue(snapshot);+ if (!issue) return false;+ // An unconfirmed media release cannot be dismissed into a reusable call slot,+ // so it stays on screen until the app restarts.+ return hasUnconfirmedMediaRelease(snapshot) || issue.key !== dismissedIssue;+}diff --git a/apps/desktop/src/main.tsx b/apps/desktop/src/main.tsxindex 035eb5599..3c7361566 100644--- a/apps/desktop/src/main.tsx+++ b/apps/desktop/src/main.tsx@@ -6,6 +6,7 @@ import { catalogs, flattenCatalog, resolveLocale } from "@pi-desktop/i18n";import { MAC_TRAFFIC_LIGHT_EDGE_DIP } from "@pi-desktop/shared";import App from "./App";import { PluginLauncher } from "./components/PluginLauncher";+import { LiveVoiceWidget } from "./features/voice/live/LiveVoiceWidget";import { initLanguageSync, resolveOsLocale } from "./lib/app-language";import { installScrollbarReveal } from "./lib/scrollbar-reveal";import "./styles/globals.css";@@ -57,7 +58,8 @@ if (!rootEl) {try {ReactDOM.createRoot(rootEl).render(<React.StrictMode>- {rendererSurface === "plugin-launcher" ? <PluginLauncher /> : <App />}+ {rendererSurface === "plugin-launcher" ? <PluginLauncher /> :+ rendererSurface === "live-voice-widget" ? <LiveVoiceWidget /> : <App />}</React.StrictMode>,);} catch (error) {diff --git a/apps/desktop/src/styles/live-voice-widget.css b/apps/desktop/src/styles/live-voice-widget.cssnew file mode 100644index 000000000..c16fb85bc--- /dev/null+++ b/apps/desktop/src/styles/live-voice-widget.css@@ -0,0 +1,59 @@+/*+ * The docked Live Voice widget window (04-ux/08-component-spec § 11.7.1).+ *+ * The window is frameless and transparent, so the bar is the only surface and+ * the window's own drag handle: everything the user can press has to opt out of+ * the drag region, or the press would move the widget instead of the control.+ * A transparent window must also hold no dead space it does not draw — main+ * sizes it to the box this shell reports.+ */+html[data-surface="live-voice-widget"],+html[data-surface="live-voice-widget"] body,+html[data-surface="live-voice-widget"] #root {+ background: transparent;+ overflow: hidden;+}++/*+ * One row, never folded: main sizes the window to the box this shell reports, so+ * a status line allowed to wrap would shrink the window and wrap again. The+ * status keeps its own width and the window grows to it, up to the size cap —+ * a folded status line reads as two rows of chrome on the desktop.+ */+.live-voice-widget .live-voice-call-row {+ flex-wrap: nowrap;+}++.live-voice-widget .live-voice-call-status {+ flex-shrink: 0;+ white-space: nowrap;+}++/* The failure line is a sentence: it may still wrap, and the window follows it. */++.live-voice-widget {+ display: inline-flex;+ padding: 6px;+ -webkit-app-region: drag;+ app-region: drag;+ cursor: grab;+ /* A touch on the bar moves the window instead of scrolling what is behind it. */+ touch-action: none;+}++.live-voice-widget .live-voice-call-bar {+ max-width: none;+ /* The bar sits on the desktop, not on an app surface: it needs the elevation+ a floating card would have inside a window. */+ box-shadow: var(--ds-shadow-dialog);+}++.live-voice-widget .live-voice-call-bar button,+.live-voice-widget .live-voice-call-bar code {+ -webkit-app-region: no-drag;+ app-region: no-drag;+}++.live-voice-widget .live-voice-call-bar button {+ cursor: pointer;+}diff --git a/apps/desktop/src/styles/voice.css b/apps/desktop/src/styles/voice.cssindex ad3eb6beb..bca10ccd5 100644--- a/apps/desktop/src/styles/voice.css+++ b/apps/desktop/src/styles/voice.css@@ -196,18 +196,14 @@gap: 8px;}-.live-voice-status-host {+/* Details has no trigger row in this window any more: the docked widget's+ button opens it, so it hangs from a fixed point above the composer. */+.live-voice-details-anchor {position: fixed;- z-index: 35;left: 50%;- bottom: 20px;- width: max-content;- max-width: calc(100vw - 32px);- transform: translateX(-50%);-}--.live-voice-status-host[data-chat="true"] {bottom: calc(var(--composer-dock-height, 168px) + 12px);+ width: 1px;+ height: 1px;}.live-voice-call-bar {@@ -271,8 +267,8 @@}@media (prefers-reduced-motion: reduce) {- .live-voice-status-host .voice-spinner,- .live-voice-status-host .voice-mic-active,+ .live-voice-widget .voice-spinner,+ .live-voice-widget .voice-mic-active,.live-voice-preparation .voice-spinner {animation: none;}diff --git a/apps/desktop/test/fixtures/live-voice-interaction-runner.cjs b/apps/desktop/test/fixtures/live-voice-interaction-runner.cjsindex 80675880c..df2dea6a6 100644--- a/apps/desktop/test/fixtures/live-voice-interaction-runner.cjs+++ b/apps/desktop/test/fixtures/live-voice-interaction-runner.cjs@@ -88,6 +88,7 @@ async function selectOption(expression, value) {if (!result.ok) throw new Error(result.error);await frame();}+async function fresh(enabled = true) {await win.loadURL(process.env.PI_LIVE_VOICE_FIXTURE_URL);if (!win.isVisible()) win.show();@@ -145,13 +146,18 @@ async function clean() {async function preparationScenario() {await fresh(false);await check("disabled Live Voice has neither Live nor work icons",- `ui.all('button', undefined, '[data-fixture-composer]').length === 0 && !ui.visible(document.querySelector('.live-voice-status-host')) && ${noMedia}`);+ `ui.all('button', undefined, '[data-fixture-composer]').length === 0 && !s.widget.visible && ${noMedia}`);await evaluate("window.liveVoiceFixture.configure({ enabled: true })");await check("enabling exposes exactly one idle trigger",`s.snapshot.status.enabled && ui.all('button', undefined, '[data-fixture-composer]').length === 1 && ${button("Live voice")}`);await openPreparation();- await check("preparation defaults to the Composer session without a work-access gate",- `document.querySelector(${JSON.stringify(prep)})?.textContent.includes('The current Composer session is the default') && !${button("Allow work requests", prep)} && ${checkbox("Share limited recent conversation context")}?.checked === false && ${noMedia}`);+ await check("preparation carries no explanatory prose around its controls",+ `(() => {+ const text = document.querySelector(${JSON.stringify(prep)})?.textContent ?? '';+ return !text.includes('The current Composer session is the default') && !text.includes('up to six recent plain-text') &&+ text.includes('Selected fixture account') && !${button("Allow work requests", prep)} &&+ ${checkbox("Share limited recent conversation context")}?.checked === false && ${noMedia};+ })()`);await click(button("Close", prep));await check("closing preparation acquires no media", `${noDialog} && ${noMedia}`);await openPreparation();@@ -199,12 +205,35 @@ async function connectedScenario() {await start();await connected();await check("connected call starts muted with no details dialog", `${button("Unmute microphone", bar)} && s.snapshot.call.muted && ${noDialog}`);+ // The bar is drawn inside a fixed-width window, so its status and controls must+ // stay on one row: a folded status line reads as two rows of chrome. Narrowing+ // the window proves the bar neither folds the row nor under-reports the width it+ // needs — that report is what lets main grow the window to the content.+ await evaluate("window.liveVoiceFixture.setWidgetWindowWidth(240)");+ await frame();+ await check("a status line too wide for the window stays one row and reports its width",+ `(() => {+ const status = document.querySelector('.live-voice-call-status > span');+ const actions = document.querySelector('.live-voice-call-actions');+ const report = window.liveVoiceFixture.inspect().widget.presentation;+ if (!status || !actions || !report) return false;+ return status.getClientRects().length === 1 &&+ Math.abs(status.getBoundingClientRect().top - actions.getBoundingClientRect().top) < 6 &&+ report.width >= Math.ceil(status.scrollWidth) - 2;+ })()`);+ await evaluate("window.liveVoiceFixture.setWidgetWindowWidth(420)");+ await frame();await capture("call-connected");await evaluate("window.liveVoiceFixture.setPhase('reconnecting')");await check("reconnecting keeps an explicit End action", `ui.state('reconnecting') && ${button("End call", bar)} && !${button("Cancel", bar)} && !${button("Unmute microphone", bar)}`);await evaluate("window.liveVoiceFixture.setPhase('connected')");await connected();await click(button("Unmute microphone", bar));+ // The press left the widget as an action, and the widget reported the visible+ // box main has to show: the widget window is not the call owner and never+ // reaches the controller itself.+ await check("a widget press travels to the owner frame as an action",+ "s.widget.actions.includes('mute') && s.widget.visible && s.widget.presentation.width > 0 && s.widget.presentation.height > 0");await check("unmute opens the real controller capture gate", `${button("Mute microphone", bar)} && !s.snapshot.call.muted && s.tracks[0].enabled && s.counts.mute === 1`);await click(button("Mute microphone", bar));await check("mute immediately closes the capture gate", `${button("Unmute microphone", bar)} && s.snapshot.call.muted && !s.tracks[0].enabled && s.counts.mute === 2`);@@ -234,8 +263,13 @@ async function playbackScenario() {await check("blocked output exposes Resume sound with details closed",`s.snapshot.call.playbackBlocked && ${button("Resume sound")} && ${noDialog}`);await click(button("Resume sound"));+ // The retry is refused in the owner frame, which is the only place that knows+ // it: it reports the code and the widget names it in place, so the failure is+ // visible without the details surface.await check("failed playback retry is visible without opening details",- `s.snapshot.errorCode === 'LIVE_PLAYBACK_FAILED' && ui.all('[role=alert]').length > 0 && ${button("Resume sound")} && ${noDialog} && s.counts.play >= 2`);+ `s.snapshot.errorCode === 'LIVE_PLAYBACK_FAILED' && document.body.textContent.includes('LIVE_PLAYBACK_FAILED') && ui.all('[role=status]').length > 0 && ${button("Resume sound")} && ${noDialog} && s.counts.play >= 2`);+ await check("failed playback retry is visible without opening details",+ `s.snapshot.errorCode === 'LIVE_PLAYBACK_FAILED' && document.body.textContent.includes('LIVE_PLAYBACK_FAILED') && ui.all('[role=status]').length > 0 && ${button("Resume sound")} && ${noDialog} && s.counts.play >= 2`);await evaluate("window.liveVoiceFixture.blockPlayback(false)");await click(button("Resume sound"));await check("successful user retry clears playback blockage and error",@@ -280,7 +314,7 @@ async function unconfirmedReleaseScenario() {"s.snapshot.stopping && s.counts.released === 1 && s.contexts[0].state === 'closed' && ui.state('stopping')");await evaluate("window.liveVoiceFixture.terminalUnconfirmed()");await check("unconfirmed release stays visible and suppresses another Start",- `!s.snapshot.stopping && s.snapshot.call?.error?.code === 'LIVE_MEDIA_RELEASE_UNCONFIRMED' && ui.visible(document.querySelector('.live-voice-status-host')) && ui.all('[role="alert"]').some(element => element.textContent.includes('Microphone release could not be confirmed')) && !${button("Live voice")} && !${button("Dismiss", bar)}`);+ `!s.snapshot.stopping && s.snapshot.call?.error?.code === 'LIVE_MEDIA_RELEASE_UNCONFIRMED' && s.widget.visible && ui.all('[role="alert"]').some(element => element.textContent.includes('Microphone release could not be confirmed')) && !${button("Live voice")} && !${button("Dismiss", bar)}`);await capture("call-release-quarantined");const attempt = await evaluate("window.liveVoiceFixture.attemptStart()");assert.equal(attempt, "LIVE_MEDIA_RELEASE_UNCONFIRMED");@@ -288,7 +322,6 @@ async function unconfirmedReleaseScenario() {"s.counts.prepare === 1 && s.snapshot.call?.error?.code === 'LIVE_MEDIA_RELEASE_UNCONFIRMED'");await clean();}-async function shellAndDisableScenario() {await fresh();await enableWork();@@ -296,7 +329,7 @@ async function shellAndDisableScenario() {await connected();await click(button("Fixture toggle composer visibility"));await check("global status survives the simulated hidden composer boundary",- "document.querySelector('[data-fixture-composer]')?.hidden && ui.state('connected') && ui.visible(document.querySelector('.live-voice-status-host'))");+ "document.querySelector('[data-fixture-composer]')?.hidden && ui.state('connected') && s.widget.visible");await click(button("Fixture settings route"));await check("global status survives simulated route unmount",`!document.querySelector('[data-fixture-composer]') && ui.state('connected') && ${button("End call", bar)} && s.counts.end === 0`);@@ -313,7 +346,7 @@ async function shellAndDisableScenario() {"s.counts.released === 1 && s.contexts[0].state === 'closed' && s.snapshot.stopping && ui.state('stopping')");await evaluate("window.liveVoiceFixture.release('released')");await check("disabled status disappears only after local cleanup settles",- "!s.snapshot.stopping && !ui.visible(document.querySelector('.live-voice-status-host')) && s.tracks.every(track => track.readyState === 'ended')");+ "!s.snapshot.stopping && !s.widget.visible && s.tracks.every(track => track.readyState === 'ended')");await click(button("Fixture chat route"));await check("returning to composer while disabled leaves no Live or work icons","ui.all('button', undefined, '[data-fixture-composer]').length === 0 && s.counts.prepare === 1 && s.counts.getUserMedia === 1");diff --git a/apps/desktop/test/fixtures/live-voice-interaction.jsx b/apps/desktop/test/fixtures/live-voice-interaction.jsxindex 4531c1a30..3234e0e89 100644--- a/apps/desktop/test/fixtures/live-voice-interaction.jsx+++ b/apps/desktop/test/fixtures/live-voice-interaction.jsx@@ -9,6 +9,7 @@ import { PortalVisibilityProvider } from "../../src/lib/portal-visibility";import { LiveVoiceControls } from "../../src/features/voice/live/LiveVoiceControls";import { ToastHost } from "../../src/components/Toast";import { LiveVoiceStatusHost } from "../../src/features/voice/live/LiveVoiceStatusHost";+import { LiveVoiceWidget } from "../../src/features/voice/live/LiveVoiceWidget";import { getLiveCallController } from "../../src/features/voice/live/live-call-controller";import { runLiveVoiceShortcut } from "../../src/features/voice/live/live-voice-shortcuts";@@ -29,7 +30,7 @@ const settings = {{ id: "fixture-selected", adapterId: "codex-live", providerId: "fixture-provider", voice: "cove" },{ id: "fixture-other", adapterId: "codex-live", providerId: "fixture-other-provider", voice: "cove" },] },- voice: { deviceId: null }, keybindings: {},+ voice: { deviceId: null }, keybindings: {}, language: "en",};const status = {enabled: false, settingsRevision: 1, selectedBindingId: "fixture-selected", call: null,@@ -47,14 +48,26 @@ let callNumber = 0;let rejectPlayback = false;let rejectReleaseReport = false;const ending = new Map();+// The widget window is a view of the call: main pushes the owner's view into it+// and forwards its presses back to the owner frame. Both directions are faked+// here so the mounted production widget runs its real code path.+const widgetReports = { presentation: null, actions: [], errorCode: undefined };const emit = (channel, value) => {for (const listener of listeners.get(channel) ?? []) listener(structuredClone(value));};const waitAt = (name) => gates.get(name)?.promise ?? Promise.resolve();+function pushWidgetState() {+ emit(IPC.event.liveVoiceWidgetState, {+ call,+ ...(widgetReports.errorCode ? { errorCode: widgetReports.errorCode } : {}),+ });+}function updateCall(patch) {call = { ...call, ...patch, revision: (call?.revision ?? 0) + 1 };status.call = call;emit(IPC.event.liveVoiceChanged, call);+ // Main forwards the same authoritative view to the docked widget.+ pushWidgetState();return structuredClone(call);}function beginClosing() {@@ -79,6 +92,8 @@ async function handleInvoke(channel, request) {contextEnabled: request.shareSelectedSessionContext === true,} } : {}),};+ // A new call starts blank: main drops the previous call's failure code.+ widgetReports.errorCode = undefined;updateCall({});const prepared = {callId: call.callId, requestId: request.requestId, bindingId: call.bindingId,@@ -123,6 +138,22 @@ async function handleInvoke(channel, request) {case IPC.invoke.liveVoiceReportPlayback:case IPC.invoke.liveVoiceReportControlApplied:return { ok: true };+ case IPC.invoke.liveVoiceWidgetVisibility:+ // Main turns the widget's measured box into the window's bounds.+ widgetReports.presentation = structuredClone(request);+ return { ok: true };+ case IPC.invoke.liveVoiceWidgetAction:+ // Main validates the sender, then hands the press to the owner frame.+ widgetReports.actions.push(request.action);+ emit(IPC.event.liveVoiceWidgetAction, { action: request.action });+ return { ok: true };+ case IPC.invoke.liveVoiceWidgetIssue:+ // The owner frame's own failure code, cached for the call it belongs to+ // and pushed into the widget exactly as main does.+ if (request.callId !== call?.callId) return { ok: true };+ widgetReports.errorCode = request.code ?? undefined;+ pushWidgetState();+ return { ok: true };default:requests.unexpected.push(channel);throw new Error(`Unexpected fixture IPC: ${channel}`);@@ -201,9 +232,19 @@ await i18n.use(initReactI18next).init({});useAppStore.setState({ sessions, activeSessionId: sessions[0].id, settings });const controller = getLiveCallController();+/** Set by the fixture shell so a scenario can resize the emulated widget window. */+let setFixtureWidgetWidth = () => {};+function SimulatedShell() {const [route, setRoute] = useState("chat");const [hidden, setHidden] = useState(false);+ // The window main gives the widget is a fixed width until the bar reports the+ // box it needs; the scenario can narrow it to prove the bar neither folds nor+ // under-reports its width.+ const [widgetWidth, setWidgetWidth] = useState(420);+ useEffect(() => {+ setFixtureWidgetWidth = setWidgetWidth;+ }, []);const activeSessionId = useAppStore((state) => state.activeSessionId);useEffect(() => {useAppStore.setState({ page: route });@@ -237,6 +278,14 @@ function SimulatedShell() {</PortalVisibilityProvider>) : <p data-fixture-settings>Settings route: composer unmounted</p>}<LiveVoiceStatusHost />+ {/* The docked widget window, mounted in the same document: it is the call+ chrome now, and its presses travel through the widget IPC channels.+ The wrapper is the fixed-width surface the real window is: without it a+ wrapped status line would go unnoticed, because the fixture document is+ wider than the window the bar is drawn in. */}+ <div data-fixture-widget-window style={{ width: widgetWidth, overflow: "hidden" }}>+ <LiveVoiceWidget />+ </div><ToastHost /></div>);@@ -284,12 +333,20 @@ window.liveVoiceFixture = {emit(IPC.event.liveVoiceTranscript, { callId: call.callId,segment: { id: "fixture-transcript", role: "assistant", text, final: true, timestamp: 0 } });},+ // Narrow the window main gives the widget, so a status line no longer fits: a+ // bar that folds or under-reports its width fails the assertion after it.+ setWidgetWindowWidth(width) { setFixtureWidgetWidth(width); },inspect() {return {snapshot: controller.getSnapshot(), counts, requests, errors,tracks: tracks.map(({ enabled, readyState }) => ({ enabled, readyState })),contexts: contexts.map(({ state }) => ({ state })),peers: peers.map(({ connectionState }) => ({ connectionState })), held: [...gates.keys()],+ widget: {+ presentation: widgetReports.presentation,+ actions: [...widgetReports.actions],+ visible: widgetReports.presentation?.visible === true,+ },};},};diff --git a/apps/desktop/test/live-voice-controls.test.mjs b/apps/desktop/test/live-voice-controls.test.mjsindex 9adbf005a..fe5ba67d7 100644--- a/apps/desktop/test/live-voice-controls.test.mjs+++ b/apps/desktop/test/live-voice-controls.test.mjs@@ -4,12 +4,16 @@ import test from "node:test";import { fileURLToPath } from "node:url";import { createServer } from "vite";-// The bar owns the call chrome; the failure text and its code are asserted-// through the source, because the toast itself is the store's surface.+// The widget window draws the bar; the owner frame (the main window) runs the+// actions and owns the toast surface, so both sources are read here.const callBarSource = readFileSync(new URL("../src/features/voice/live/LiveVoiceCallBar.tsx", import.meta.url),"utf8",);+const hostSource = readFileSync(+ new URL("../src/features/voice/live/LiveVoiceStatusHost.tsx", import.meta.url),+ "utf8",+);const binding = { bindingId: "voice-a", adapterId: "codex-live", configured: true, credentialsPresent: true, selectable: true, providerLabel: "Fixture voice" };const status = { enabled: true, settingsRevision: 1, selectedBindingId: binding.bindingId, bindings: [binding], call: null };@@ -55,7 +59,7 @@ test("Live Voice separates idle entry and compact call presentation", async (t)const { LiveVoiceControls } = await server.ssrLoadModule("/src/features/voice/live/LiveVoiceControls.tsx");const { LiveVoiceCallBar } = await server.ssrLoadModule("/src/features/voice/live/LiveVoiceCallBar.tsx");const { getLiveCallController } = await server.ssrLoadModule("/src/features/voice/live/live-call-controller.ts");- const { liveVoiceMode, liveVoiceIssue, liveReadinessMessage, hasUnconfirmedMediaRelease } = await server.ssrLoadModule("/src/features/voice/live/live-voice-presentation.ts");+ const { liveVoiceMode, liveVoiceIssue, liveReadinessMessage, hasUnconfirmedMediaRelease, liveVoiceWidgetSnapshot, liveVoiceWidgetVisible } = await server.ssrLoadModule("/src/features/voice/live/live-voice-presentation.ts");const translate = (key) => key;const controller = getLiveCallController();const renderEntry = () => renderToStaticMarkup(React.createElement(LiveVoiceControls, { t: translate, workSessionId: "work-a" }));@@ -133,22 +137,19 @@ test("Live Voice separates idle entry and compact call presentation", async (t)assert.equal(liveVoiceIssue({ ...snapshot, call: { ...call, playbackBlocked: false, notice: { code: "LIVE_PLAYBACK_BLOCKED", retriable: true } } }), null);assert.equal(liveVoiceIssue({ ...snapshot, call: { ...call, notice: { code: "LIVE_EXECUTION_NOT_CONNECTED", retriable: false } } }).message, "liveVoice.workNotConnected");});- await t.test("a stopped call names its real cause and carries its code to the toast", () => {+ await t.test("a stopped call names its real cause and carries its code in the bar", () => {const failed = { ...snapshot, call: { ...call, phase: "failed", error: { code: "LIVE_NETWORK_ERROR", retriable: true } } };assert.equal(liveVoiceIssue(failed).message, "errors.NETWORK_ERROR");- // A transport failure is a one-shot result, so the bar reports it through- // the global toast together with the verbatim, allow-listed code.+ // The widget window draws the only call chrome left, so a cause that used to+ // travel through the main window's toast is named in place, with its+ // verbatim allow-listed code next to it.const html = renderBar(failed);- assert.doesNotMatch(html, /errors\.NETWORK_ERROR/);- assert.doesNotMatch(html, /role="alert"/);- assert.match(- callBarSource,- /showToast\(`\$\{t\(issue\.message\)\} \(\$\{issue\.code\}\)`, \{ variant: "error" \}\)/,- );- // A retry that fails the same way is a new failure: starting an action drops- // the mark, because the call is preserved and the key alone cannot say so.- assert.match(callBarSource, /actionPending !== null && previousActionPending\.current === null/);- assert.match(callBarSource, /if \(startedAttempt\) reportedIssue\.current = null;/);+ assert.match(html, /role="alert"/);+ assert.match(html, /errors\.NETWORK_ERROR/);+ assert.match(html, /LIVE_NETWORK_ERROR/);+ // A failure only the owner frame can see — a refused action — reaches the+ // widget as a reported code, because the call view never carries it.+ assert.match(hostSource, /liveVoiceApi\.reportWidgetIssue\(\{ callId, code: issue\?\.code \?\? null \}\)/);// account failures read as account failures, not as generic configuration adviceconst auth = liveVoiceIssue({ ...snapshot, call: { ...call, phase: "failed", error: { code: "LIVE_AUTH_REQUIRED", retriable: false } } });assert.equal(auth.message, "liveVoice.authRequired");@@ -157,4 +158,24 @@ test("Live Voice separates idle entry and compact call presentation", async (t)assert.equal(unknown.message, "liveVoice.errorGeneric");assert.equal(unknown.code, "LIVE_SOMETHING_NEW");});+ await t.test("the docked widget shows what main pushed and hides the rest", () => {+ // A call in flight is on screen from the view alone.+ assert.equal(liveVoiceMode(liveVoiceWidgetSnapshot({ ...call, phase: "connected" })), "connected");+ assert.equal(liveVoiceWidgetVisible(liveVoiceWidgetSnapshot({ ...call, phase: "connected" }), null), true);+ // An ending call keeps saying Ending until the renderer release settles: the+ // owner's local stopping flag never crosses to the widget.+ assert.equal(liveVoiceMode(liveVoiceWidgetSnapshot({ ...call, phase: "closing" })), "stopping");+ assert.equal(liveVoiceMode(liveVoiceWidgetSnapshot({ ...call, phase: "ended", mediaRelease: "pending" })), "stopping");+ assert.equal(liveVoiceMode(liveVoiceWidgetSnapshot({ ...call, phase: "ended", mediaRelease: "confirmed" })), "idle");+ assert.equal(liveVoiceWidgetVisible(liveVoiceWidgetSnapshot(null), null), false, "no call is nothing to show");+ // A failure the owner frame reported — never present in the call view — is+ // named until the user dismisses it.+ const failed = liveVoiceWidgetSnapshot({ ...call, phase: "failed" }, "LIVE_PLAYBACK_FAILED");+ assert.equal(liveVoiceIssue(failed).code, "LIVE_PLAYBACK_FAILED");+ assert.equal(liveVoiceWidgetVisible(failed, null), true);+ assert.equal(liveVoiceWidgetVisible(failed, liveVoiceIssue(failed).key), false);+ // A quarantined microphone cannot be dismissed into a reusable call slot.+ const quarantined = liveVoiceWidgetSnapshot({ ...call, phase: "failed", mediaRelease: "unconfirmed" });+ assert.equal(liveVoiceWidgetVisible(quarantined, liveVoiceIssue(quarantined).key), true);+ });});diff --git a/apps/desktop/test/live-voice-widget.test.mjs b/apps/desktop/test/live-voice-widget.test.mjsnew file mode 100644index 000000000..62d848672--- /dev/null+++ b/apps/desktop/test/live-voice-widget.test.mjs@@ -0,0 +1,100 @@+import assert from "node:assert/strict";+import test from "node:test";+import { fileURLToPath } from "node:url";+import { createServer } from "vite";++// The docked Live Voice widget is a desktop-level window: frameless, always on+// top, transparent, dragged through its own app-region handle. What can be+// proven without a display is the arithmetic that keeps a saved placement and+// the widget's self-reported box on screen, plus the validation of the two+// channels the widget may use. The window itself is covered by the Live Voice+// e2e run against the real app.++async function desktopModules(t) {+ const server = await createServer({+ root: fileURLToPath(new URL("..", import.meta.url)),+ configFile: false,+ server: { middlewareMode: true, hmr: false, ws: false },+ appType: "custom",+ optimizeDeps: { noDiscovery: true, include: [] },+ });+ t.after(() => server.close());+ return {+ placement: await server.ssrLoadModule("/electron/main/live-voice/widget-geometry.ts"),+ ipc: await server.ssrLoadModule("/electron/main/ipc/live-voice-ipc.ts"),+ };+}++test("a dragged Live Voice widget stays inside the work area", async (t) => {+ const { placement } = await desktopModules(t);+ const primary = { x: 0, y: 0, width: 1440, height: 900 };+ const bar = { width: 420, height: 64 };+ const clamp = placement.clampLiveVoiceWidgetPosition;++ assert.deepEqual(clamp({ x: 400, y: 300 }, bar, primary), { x: 400, y: 300 },+ "a placement the user picked inside the work area is kept");+ assert.deepEqual(clamp({ x: -120, y: -40 }, bar, primary), { x: 8, y: 8 },+ "dragging past the top-left edge pins the widget to the margin");+ assert.deepEqual(clamp({ x: 9000, y: 9000 }, bar, primary), { x: 1012, y: 828 },+ "dragging past the bottom-right edge keeps the whole widget inside");+ // A second display has its own origin: the clamp follows the work area it was+ // measured against, not the primary 0,0.+ const secondary = { x: 1600, y: -200, width: 1280, height: 800 };+ assert.deepEqual(clamp({ x: 0, y: -900 }, bar, secondary), { x: 1608, y: -192 },+ "the margin is relative to the work area the widget is on");+ assert.deepEqual(clamp({ x: 40, y: 40 }, { width: 2000, height: 1000 }, primary), { x: 8, y: 8 },+ "a widget larger than the work area cannot compute a negative maximum");++ assert.equal(placement.parseLiveVoiceWidgetPosition(null), null, "no saved placement is the default corner");+ assert.equal(placement.parseLiveVoiceWidgetPosition("not json"), null, "unreadable text is the default corner");+ assert.equal(placement.parseLiveVoiceWidgetPosition("[10,20]"), null, "a value that is not a placement is ignored");+ assert.equal(placement.parseLiveVoiceWidgetPosition('{"x":10}'), null, "a half-written placement is ignored");+ assert.equal(placement.parseLiveVoiceWidgetPosition('{"x":"10","y":20}'), null, "a non-numeric coordinate is ignored");+ assert.deepEqual(placement.parseLiveVoiceWidgetPosition('{"x":10.6,"y":-3.2}'), { x: 11, y: -3 },+ "a saved placement is a whole pixel");+});++test("the widget reports the box its own content needs, bounded to the bar", async (t) => {+ const { placement } = await desktopModules(t);+ const size = placement.clampLiveVoiceWidgetSize;++ assert.deepEqual(size({ width: 380, height: 60 }), { width: 380, height: 60 }, "a measured box is used as-is");+ assert.deepEqual(size({ width: 10, height: 4 }), { width: 220, height: 40 },+ "a box too small to hold the controls grows to the minimum");+ assert.deepEqual(size({ width: 5000, height: 5000 }), { width: 680, height: 260 },+ "a box the bar cannot need is capped");+ assert.deepEqual(size({ width: Number.NaN, height: Number.NaN }), { width: 420, height: 64 },+ "an unmeasurable box falls back to the default");+});++test("only the widget's own actions and box are accepted on its channels", async (t) => {+ const { ipc } = await desktopModules(t);++ for (const action of ["cancel", "mute", "resume", "end", "details", "settings"]) {+ assert.equal(ipc.parseWidgetAction({ action }), action, action);+ }+ assert.throws(() => ipc.parseWidgetAction({ action: "prepare" }), { errorCode: "LIVE_PROTOCOL_ERROR" },+ "the widget cannot drive call setup by naming an owner action");+ assert.throws(() => ipc.parseWidgetAction({}), { errorCode: "LIVE_PROTOCOL_ERROR" });+ assert.throws(() => ipc.parseWidgetAction({ action: 42 }), { errorCode: "LIVE_PROTOCOL_ERROR" });+ assert.throws(() => ipc.parseWidgetAction({ action: "end", callId: "call-a" }), { errorCode: "LIVE_PROTOCOL_ERROR" },+ "an action carries nothing else: the owner frame resolves the call");++ assert.deepEqual(+ ipc.parseWidgetPresentation({ visible: true, width: 380, height: 60 }),+ { visible: true, width: 380, height: 60 },+ );+ assert.deepEqual(+ ipc.parseWidgetPresentation({ visible: false, width: 220, height: 40 }),+ { visible: false, width: 220, height: 40 },+ "hiding is a presentation report too, so the placement can be saved",+ );+ assert.throws(() => ipc.parseWidgetPresentation({ visible: true, width: 380 }), { errorCode: "LIVE_PROTOCOL_ERROR" });+ assert.throws(() => ipc.parseWidgetPresentation({ visible: "yes", width: 380, height: 60 }), { errorCode: "LIVE_PROTOCOL_ERROR" });+ assert.throws(() => ipc.parseWidgetPresentation({ visible: true, width: Number.NaN, height: 60 }), { errorCode: "LIVE_PROTOCOL_ERROR" });+ assert.throws(+ () => ipc.parseWidgetPresentation({ visible: true, width: 380, height: 60, x: 10 }),+ { errorCode: "LIVE_PROTOCOL_ERROR" },+ "the widget cannot move itself: the window layer owns the position",+ );+});diff --git a/docs/adr/0314-live-voice-docked-widget.md b/docs/adr/0314-live-voice-docked-widget.mdnew file mode 100644index 000000000..2150ff164--- /dev/null+++ b/docs/adr/0314-live-voice-docked-widget.md@@ -0,0 +1,86 @@+# ADR 0314: The Live Voice call bar is a docked desktop widget window++- Status: Accepted+- Date: 2026-10-01+- Deciders: PI-Desktop core+- Related: [ADR 0086](0086-macos-regular-activation-policy.md) ·+ [ADR 0275](0275-plugin-panel-floating-widget.md) ·+ [03-runtime/live-voice](../spec/03-runtime/live-voice.md) ·+ [03-runtime/01-ipc-protocol](../spec/03-runtime/01-ipc-protocol.md) ·+ [04-ux/08-component-spec](../spec/04-ux/08-component-spec.md)++## Context++The compact call bar was AppShell chrome inside the main window. That satisfies+"in-app navigation cannot hide the call controls", but not the case users+actually hit: working in another application while a call is running. A bar+painted inside the app window is invisible the moment the app is not the+foreground window, and it can never be moved out of the app's rectangle.++The call itself cannot move with it. The main window is the call owner: it holds+the renderer-side capture gating, the `WebRTC`/PCM media, the microphone lease+and the call-scoped work. Every owner-validated Live Voice channel rejects+another window with `PERMISSION_DENIED`, and `isTrustedRendererUrl` treats a+renderer URL with a query string as untrusted — so a second window can neither+become the owner nor quietly drive the owner channels.++## Decision++1. The call chrome is drawn by its own frameless, transparent, always-on-top+ `panel` window, following the plugin launcher's window recipe — with its+ activation-policy constraint from ADR 0086: it joins every Space, floats above+ other applications, and never lets Electron transform the process type. It+ loads the existing renderer bundle through+ `?surface=live-voice-widget`, the surface dispatch the plugin launcher already+ uses, so no second HTML entry, preload or build change is introduced.+2. The bar is its own drag handle (`app-region: drag` on the bar, `no-drag` on+ its controls). The placement is remembered in `live-voice-widget.json` in the+ app data directory and clamped to the work area it was measured against; the+ window is sized to the box the widget reports for the content it draws, so a+ transparent window keeps no invisible hit area over the desktop.+3. The widget never owns the call. Main pushes the authoritative call view to it+ (`voice/live/event/widgetState`); every press travels back+ (`voice/live/widget/action`) and is executed by the main window's controller+ in the owner frame. Mute therefore still gates the renderer's own capture+ before the IPC request, and the owner contract keeps one owner per call.+4. A failure only the owner frame can observe — a refused mute, a playback retry+ that failed — is reported back (`voice/live/widget/issue`) so the bar can name+ it in place next to its verbatim `LIVE_*` code. The widget is the only call+ chrome the user sees, so nothing that used to be drawn there may disappear+ with it.+5. The main window draws no call bar. It stays the frame that runs the actions+ and keeps the details surface, which the widget's Details action opens after+ bringing that window forward.+6. The widget's channels are validated as the widget window and never enter owner+ derivation: any other renderer using them is refused exactly like any other+ untrusted caller.++## Consequences++- A call stays visible and controllable while the user works in another+ application, and the chrome can be placed anywhere on the desktop.+- One additional renderer process appears with the first call and stays warm+ while the widget is hidden; that idle cost buys a bar that appears without a+ navigation or load delay mid-call.+- The widget is not the app shell, so it does not boot the settings store. It+ applies the persisted language itself when it becomes visible, and the window+ is created with the OS locale as its starting point.+- New IPC surface: two widget channels, one owner-report channel and two events.+ The preload whitelist is derived from `IPC`, so only `packages/shared` needs+ the channel names.+- The details surface lost its in-window trigger; it is opened from the widget+ and hangs from a fixed anchor above the composer.++## Alternatives++- Keep the bar in AppShell and make it draggable inside the window: it can never+ leave the app rectangle or survive another app owning the foreground, which is+ the whole request (rejected).+- Let the widget window own the call: it would have to hold media, the+ microphone lease and the work scope, duplicating the owner contract and+ breaking the single-owner rule (rejected).+- Capture media in an offscreen renderer while the widget draws chrome: it+ contradicts the existing ownership model without buying anything the owner+ frame does not already provide (rejected).+- Draw the details surface inside the widget: its work actions need the main+ window's session, project and navigation store (rejected).diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 066c5749a..88d76ab53 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -351,3 +351,4 @@ Each ADR includes:| provider-system-certificates | [Desktop sidecar uses OS-trusted certificates](provider-system-certificates.md) | Accepted || image-generation-capability | [Image generation as a configured Agent capability](image-generation-capability.md) | Accepted || retained-browser-pages-per-tab | [Retain a host-owned browser page per resource tab](retained-browser-pages-per-tab.md) | Accepted |+| 0314 | [The Live Voice call bar is a docked desktop widget window](0314-live-voice-docked-widget.md) | Accepted |diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex e44da0ae8..93d13148c 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -2386,12 +2386,14 @@ watching.## 16. Live Voice API-Live Voice is a main-window-only, app-owned call path described in-[live-voice.md](live-voice.md). Its DTOs are defined in+Live Voice is an app-owned call path described in [live-voice.md](live-voice.md)+whose ownership is bound to the main window. Its DTOs are defined in`packages/shared/src/types/live-voice.ts`; the preload exposes only theallowlisted channels below. Main derives the owner from the invoking trustedframe and sends call events only to that frame. No payload can supply an owner-identity or credentials.+identity or credentials. The docked widget window draws the call chrome without+owning the call, so its three channels are validated separately and never enter+owner derivation.| IPC channel | Direction | contract ||---|---|---|@@ -2409,6 +2411,11 @@ identity or credentials.| `pi-desktop/voice/live/event/port` | Main → Renderer | transfers exactly one call-scoped `MessagePort` with its call ID and one-time nonce || `pi-desktop/voice/live/event/control` | Main → Renderer | provider control request, limited to the explicit v1 control vocabulary || `pi-desktop/voice/live/event/transcript` | Main → Renderer | transient bounded transcript event for the current call |+| `pi-desktop/voice/live/widget/visibility` | Widget → Main | the docked widget's own presentation decision and the content box it needs; Main shows or hides that window accordingly |+| `pi-desktop/voice/live/widget/action` | Widget → Main | a call action pressed in the docked widget; Main validates the sender and forwards it to the owner frame, which runs it |+| `pi-desktop/voice/live/widget/issue` | Main window → Main | the owner frame's own failure code for its call (for example a refused mute), which the call view never carries |+| `pi-desktop/voice/live/event/widgetState` | Main → Widget | the authoritative call view plus the owner's failure code, pushed to the docked widget window |+| `pi-desktop/voice/live/event/widgetAction` | Main → Main window | the forwarded widget action the owner frame has to run |The `MessagePort` is provisioned only after successful owner validation, thenrelayed by preload to the renderer window. The owner echoes the per-call nonce@@ -2418,3 +2425,11 @@ epochs, release acknowledgements, playback cursors and protocol readinesssignals. It is not a generic IPC tunnel: it carries no providercredentials, arbitrary commands, workspace paths, Agent messages or durabletranscripts. A port is closed on call end or owner loss.++The docked widget window is not a call owner and can never become one: it is+refused on every owner-validated channel with `PERMISSION_DENIED`, exactly like+any other renderer. Main answers its two channels only when the sender is that+window, and the owner's own failure code arrives through the main window, which+is the frame that ran the action. A widget action never changes call state by+itself: it is forwarded to the owner frame, and the resulting state reaches the+widget through the same authoritative view the owner receives.diff --git a/docs/spec/03-runtime/live-voice.md b/docs/spec/03-runtime/live-voice.mdindex 3e100b4c4..8600a1b3c 100644--- a/docs/spec/03-runtime/live-voice.md+++ b/docs/spec/03-runtime/live-voice.md@@ -68,9 +68,14 @@ persisted settings:consent and grants no work permission.3. **Call in progress:** a stable global compact bar shows startup with Cancel,connected state with mute/unmute, End and Details, and stopping with an- explicit Ending state. It is mounted in persistent AppShell chrome outside- the visibility-gated chat and Composer subtree, so in-app navigation cannot- hide the call controls.+ explicit Ending state. The bar is drawn by its own frameless, transparent,+ always-on-top desktop widget window rather than by AppShell: it floats above+ other applications, keeps the call visible while the user works elsewhere,+ and in-app navigation cannot hide the call controls because they are not+ inside the app window. The widget owns no part of the call: its presses are+ forwarded to the main window, which stays the owner of the microphone, the+ media and the call-scoped work, and a failure only that frame can observe is+ reported back so the bar names it.Playback blocking and errors, including playback-resume failure, are visibledirectly in the bar instead of requiring Details. The bar pairs thelocalized message with the verbatim `LIVE_*` error code, so a failure whosediff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex cb792fdda..c8a31be77 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -3166,8 +3166,8 @@ has four presentation states:| State | Surface and allowed interaction ||---|---|| Disabled | No Live Voice or Live Work Composer icons. Enable only in Settings → Voice. |-| Enabled, idle | One Live Voice icon opens preparation, not a call. Show the exact selected provider and readiness cause, an explicit Start action, the current Composer session as the default work target when present, and separate default-off bounded-context consent. |-| Call in progress | One global compact bar: Connecting with Cancel; connected with mute/unmute, End, and Details; Ending until Main and renderer cleanup both settle. |+| Enabled, idle | One Live Voice icon opens preparation, not a call. Show the exact selected provider and its readiness cause, one default-off bounded-context consent checkbox, and an explicit Start action. The panel carries no explanatory prose: only a blocking cause is stated, because a paragraph of text pushes Start out of reach. |+| Call in progress | One docked desktop widget window: Connecting with Cancel; connected with mute/unmute, End, and Details; Ending until Main and renderer cleanup both settle. || Details open | Deliberately opened transcript/provider/work inspection surface; dismissing it does not end the call. |- The preparation popup uses shared controls and a localized accessible title.@@ -3175,7 +3175,7 @@ has four presentation states:initialize media, or contact a voice provider. Start is unavailable when theexact selected binding is not ready, even if another binding is ready; showthe actual readiness cause and a Settings action instead of silently falling- back to another account.+ back to another account. Beyond that it carries no explanatory prose.- Start defaults to muted and uses the current Composer session as the worktarget after Main validates it against the fresh multi-backend catalog. Noper-call work-access checkbox or mandatory preselection is required. If there@@ -3184,16 +3184,29 @@ has four presentation states:- Bounded session-context sharing remains a separate, unchecked call consent.It reads only the current target's bounded plain-text history and resets whenthe call ends; it does not grant work permissions or approve actions.-- The compact bar is persistent AppShell chrome outside the visibility-gated- chat and Composer subtree. It stays available across Settings, Plugins, and- project/session navigation. Feature disable hides the idle icon but not the- stopping bar. Late Main terminal events and renderer media release cannot- briefly expose a second Start. Unconfirmed media release remains visible as- an error, suppresses another Start until restart, and cannot be cleared into a- reusable call slot by dismissing the presentation.-- Playback paused state, Resume sound, playback-resume failure and call errors- are visible directly in the bar. Status is announced accessibly; icon-only- controls have localized names and tooltips, and muted state is explicit.+- The compact bar is its own frameless, transparent, always-on-top desktop+ window, not AppShell chrome. It joins every Space and floats above other+ applications, so a call stays visible and controllable while the user works+ elsewhere; in-app navigation cannot hide it, because it is not inside the app+ window at all. The window is dragged through the bar itself and sized to what+ the bar draws, and its placement is remembered and clamped to the work area,+ so a position saved on a wider display can never strand the controls. The+ status row and its controls stay on one row — a folded status line would read+ as two rows of chrome — so the bar reports the width it needs and the window+ grows to it.+- The widget is a view of the call, never its owner. Every press is forwarded to+ the main window, which owns the microphone, the media and the call-scoped+ work, and the resulting state returns through the same authoritative view the+ owner receives. A failure only the owner frame can observe — a refused mute, a+ playback retry that failed — is reported so the bar names it in place next to+ its verbatim `LIVE_*` code; the bar is the only call chrome the user sees.+- The main window draws no call bar. It keeps the details surface, which the+ widget's Details action opens after bringing that window forward, and it stays+ the frame that runs the actions. Feature disable hides the idle icon; the+ widget disappears once the call and its renderer cleanup settle. Late Main+ terminal events and renderer media release cannot briefly expose a second+ Start. Unconfirmed media release remains visible, cannot be dismissed into a+ reusable call slot, and suppresses another Start until restart.- Details never opens automatically during startup or connection. It owns thebounded transient transcript (including an empty state), provider identity,current work target, per-operation targets, work actions and results. Targetdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 243854e62..d1d515661 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -94,7 +94,10 @@4. Open Details, inspect transcript/provider/work state, and dismiss it withClose, outside press, and Escape. Keep the call connected; use the bar toresume blocked sound, observe a rejected resume, and recover explicitly.- 5. Navigate between chat, Settings, Plugins, and sessions. End or disable the+ 5. Navigate between chat, Settings, Plugins, and sessions. The call chrome is+ a docked desktop widget window, so drag it by its own bar, verify the+ position survives that navigation and is clamped back inside the work area,+ and verify the main window draws no call bar. End or disable thefeature with delayed Main termination and renderer cleanup, in eithercompletion order. Keep Ending visible and prevent another Start until bothsettle. Exercise unconfirmed release and verify visible blocked recovery.diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.mdindex 59673d326..d6bb8a073 100644--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md@@ -1867,7 +1867,7 @@ unchanged. See [provider configuration](12-provider-config-schema.md).## 16. 实时语音 API-实时语音是仅供主窗口使用、由应用管理的通话通路,详见[live-voice.md](live-voice.md)。DTO 定义在 `packages/shared/src/types/live-voice.ts`;preload 只暴露下表列出的白名单通道。Main 从调用 IPC 的受信 frame 推导 owner,并只向该 frame 发送通话事件。payload 不能提供 owner 身份或凭证。+实时语音是应用管理的通话通路,其所有权绑定在主窗口上,详见[live-voice.md](live-voice.md)。DTO 定义在 `packages/shared/src/types/live-voice.ts`;preload 只暴露下表列出的白名单通道。Main 从调用 IPC 的受信 frame 推导 owner,并只向该 frame 发送通话事件。payload 不能提供 owner 身份或凭证。停靠挂件窗口只绘制通话控件、不拥有通话,因此它的三条通道单独校验,且永不进入 owner 推导。| IPC 通道 | 方向 | 契约 ||---|---|---|@@ -1885,5 +1885,12 @@ unchanged. See [provider configuration](12-provider-config-schema.md).| `pi-desktop/voice/live/event/port` | Main → Renderer | 转交一个通话专用 `MessagePort`,附带 call ID 和一次性 nonce || `pi-desktop/voice/live/event/control` | Main → Renderer | Provider 控制请求,仅包含 v1 明确允许的控制类型 || `pi-desktop/voice/live/event/transcript` | Main → Renderer | 当前通话的临时、有界字幕事件 |+| `pi-desktop/voice/live/widget/visibility` | 挂件 → Main | 挂件自身的展示决定与所需内容盒尺寸;Main 据此显示或隐藏该窗口 |+| `pi-desktop/voice/live/widget/action` | 挂件 → Main | 在挂件中按下的通话操作;Main 校验发送方后转发给 owner frame 执行 |+| `pi-desktop/voice/live/widget/issue` | 主窗口 → Main | owner frame 自身为该通话记录的错误码(例如被拒绝的静音),通话视图不会携带它 |+| `pi-desktop/voice/live/event/widgetState` | Main → 挂件 | 权威通话视图加上 owner 的错误码,推送给停靠挂件窗口 |+| `pi-desktop/voice/live/event/widgetAction` | Main → 主窗口 | 需要 owner frame 执行的挂件操作 |只有 owner 验证成功后才会创建 `MessagePort`,之后由 preload 中继到 renderer 窗口。owner 在首个 `hello` 中回送每通电话独有的 nonce;Main 仅在 call ID 和 nonce 均匹配时接受该端口一次。二进制帧包含有界 PCM 音频、采集 epoch、释放确认、播放游标和协议就绪信号。它不是通用 IPC 隧道:不会传输 Provider 凭证、任意命令、工作区路径、Agent 消息或持久化字幕。通话结束或 owner 丢失时会关闭端口。++停靠挂件窗口不是通话 owner,也不可能成为 owner:它在所有经过 owner 校验的通道上都会像任何其他 renderer 一样被以 `PERMISSION_DENIED` 拒绝。Main 只在该窗口作为发送方时响应它的两条通道;owner 自身的错误码经由主窗口传入,因为执行操作的是该 frame。挂件操作本身不会改变通话状态:它被转发给 owner frame,结果状态再通过 owner 收到的同一份权威视图回到挂件。diff --git a/docs/zh-CN/spec/03-runtime/live-voice.md b/docs/zh-CN/spec/03-runtime/live-voice.mdindex 435ab7e8a..c2fcec272 100644--- a/docs/zh-CN/spec/03-runtime/live-voice.md+++ b/docs/zh-CN/spec/03-runtime/live-voice.md@@ -38,7 +38,7 @@ PCM 采集使用 AudioWorklet,依据实际 `AudioContext.sampleRate` 进行有Voice 在开发构建和打包构建中均向普通用户开放,不再要求开发者模式。实验标记用于提示可用性限制,不是访问门槛。实时语音仍默认关闭,开启设置不会开始采集麦克风。需要配置或恢复账号时,Composer 提供“打开设置”操作。云同步和 Remote Hosts 保留各自的开发构建限制。-账号列表明确区分加载中、可重试的加载失败和无兼容账号。加载失败不会清除已保存的绑定。设置页提供现有模型配置入口,用于登录和管理账号。通话错误区分缺少认证、账号访问被拒、协议不支持、网络/限流及麦克风故障,不显示服务响应内容或凭证。通话条会在本地化文案旁同时显示对应的 `LIVE_*` 错误码本身,因此没有专属文案的失败也能从截图或工单中定位;该错误码背后的原始原因不进入任何视图,只写入脱敏后的 `provider` 日志。+账号列表明确区分加载中、可重试的加载失败和无兼容账号。加载失败不会清除已保存的绑定。设置页提供现有模型配置入口,用于登录和管理账号。通话错误区分缺少认证、账号访问被拒、协议不支持、网络/限流及麦克风故障,不显示服务响应内容或凭证。通话条会在本地化文案旁同时显示对应的 `LIVE_*` 错误码本身,因此没有专属文案的失败也能从截图或工单中定位;该错误码背后的原始原因不进入任何视图,只写入脱敏后的 `provider` 日志。通话条本身是该应用的一个独立、无边框、始终置顶的桌面窗口,不拥有通话:它的每次按键都转发给持有麦克风、媒体和按通话隔离工作的主窗口,且只显示主窗口推送的权威状态与错误码。Voice 设置入口现在只展示实时语音:用户可绑定现有兼容 Provider、选择下次通话使用的绑定,以及设置模型、音色和 Realtime profile。通话进行中,当前绑定不可修改。关闭实时语音会结束通话。Provider 凭证继续由现有 Provider/secret 或 VendorOAuth 系统管理。旧的本地 Dictation 设置和 Composer 入口已隐藏;已有 `voice` 设置值及底层 Dictation 能力保持不变,不会因 UI 调整而删除或改写。旧设置中没有 `liveVoice` 时,会按关闭且无绑定处理。diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 30dafbaea..af1950944 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -2179,24 +2179,34 @@ Live Voice 受现有开发者模式和开发构建门控约束,包含四种展| 状态 | 展示界面和允许的交互 ||---|---|| 已禁用 | Composer 中不显示 Live Voice 或 Live Work 图标。只能在「设置 → 语音」中启用。 |-| 已启用,空闲 | 一个 Live Voice 图标打开准备界面,但不会开始通话。显示确切选中的服务商及其未就绪原因、明确的开始操作,以及初始折叠的可选工作控制项。 |-| 通话进行中 | 一个全局紧凑栏:连接中时提供取消;连接后提供静音/取消静音、结束和详情;结束中会一直显示,直到 Main 和 Renderer 的清理都完成。 |+| 已启用,空闲 | 一个 Live Voice 图标打开准备界面,但不会开始通话。显示确切选中的服务商及其未就绪原因、一个默认未勾选的有界上下文确认选项,以及明确的开始操作。面板不承载解释性文案:只陈述阻塞原因,因为一段说明会把开始操作挤出视野。 |+| 通话进行中 | 一个停靠的桌面挂件窗口:连接中时提供取消;连接后提供静音/取消静音、结束和详情;结束中会一直显示,直到 Main 和 Renderer 的清理都完成。 || 详情已打开 | 用户主动打开的转录/服务商/工作检查界面;关闭详情不会结束通话。 |- 准备弹窗使用共享控件和本地化的无障碍标题。打开或关闭弹窗不得准备通话、请求麦克风权限、初始化媒体或联系语音服务商。即使另一个绑定已就绪,如果确切选中的绑定未就绪,也必须禁用开始操作;应显示实际未就绪原因和- 前往设置的操作,不能静默切换到其他账号。+ 前往设置的操作,不能静默切换到其他账号。面板除此之外不显示解释性文字。- 开始通话时默认静音。工作折叠区包含独立且默认未勾选的 **允许工作请求**选择项、有效的本地会话目标,以及单独且默认未勾选的上下文共享确认。展开该区域或选择目标都不构成授权。缺少目标时应提供选择或创建指引。上下文确认仅对下一次通话有效,并会在关闭准备界面、重新打开、目标变更或创建、取消工作授权,以及通话完成或取消时重置。-- 紧凑栏是位于 AppShell 中、独立于受可见性门控的聊天和 Composer 子树之外的- 持久界面。用户切换到设置、插件、项目或会话时,紧凑栏仍然可用。禁用该功能- 会隐藏空闲图标,但不会隐藏结束中的通话栏。延迟到达的 Main 终态事件和- Renderer 媒体释放不能短暂开放第二个开始入口。若无法确认媒体已释放,错误- 必须持续可见,直到重启后才能再次开始;关闭界面不能把通话槽位恢复为可用。+- 紧凑栏本身是一个无边框、透明、始终置顶的桌面窗口,而不是 AppShell 界面的一部分。+ 它加入所有 Space 并浮现在其他应用之上,用户在其他应用中工作时通话仍然可见可操作;+ 应用内导航无法隐藏它,因为它根本不在应用窗口内。窗口通过通话栏自身拖动,+ 尺寸跟随通话栏绘制的内容,位置会被记住并夹取到工作区内,因此在更宽屏幕上保存的位置+ 不会把控件丢到屏幕外。状态行与其控件始终保持在同一条行内——折行的状态行在桌面上看起来+ 像两行控件——因此通话栏会报告自己需要的宽度,窗口随之增长。+- 挂件只是通话的视图,绝不是 owner。每次按键都转发给主窗口——麦克风、媒体和按通话隔离的+ 工作都由主窗口持有——结果状态再通过 owner 收到的同一份权威视图回到挂件。只有 owner frame+ 才能观察到的失败(被拒绝的静音、恢复播放失败)会被上报,于是通话栏就地在旁边标出该失败+ 及其原样的 `LIVE_*` 错误码;通话栏是用户能看到的唯一通话控件。+- 主窗口不再绘制通话栏。它保留详情界面——挂件的“详情”操作会把主窗口带到前台并打开它——+ 并继续是执行这些操作的 frame。禁用该功能会隐藏空闲图标;通话与其 Renderer 清理结束后+ 挂件消失。延迟到达的 Main 终态事件和 Renderer 媒体释放不能短暂开放第二个开始入口。+ 若无法确认媒体已释放,错误必须持续可见,关闭界面不能把通话槽位恢复为可用,+ 且必须重启后才能再次开始。- 播放暂停、恢复声音、恢复播放失败以及通话错误都直接显示在通话栏中。状态会通过无障碍方式播报;纯图标控件带有本地化名称和工具提示,并明确标示静音状态。- 启动或连接时不会自动打开详情。详情负责显示有界的临时转录(包括空状态)、diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex dbabe91c5..5c2893ca1 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -92,7 +92,9 @@4. 打开详情,检查转录、服务商和工作状态,然后分别通过关闭、点击外部和Escape 关闭详情。通话保持连接;通过通话栏恢复暂停的声音,观察恢复失败,再明确重试并恢复。- 5. 在聊天、设置、插件和会话间导航。在 Main 延迟终止和 Renderer 延迟清理的+ 5. 在聊天、设置、插件和会话间导航。通话控件是停靠的桌面挂件窗口:拖动它自身的+ 通话栏,确认位置在这些导航后仍然保留、并会被夹取回工作区内,同时确认主窗口+ 不再绘制任何通话栏。在 Main 延迟终止和 Renderer 延迟清理的情况下结束通话或禁用功能,并分别测试两种清理完成顺序。在两者完成前,始终显示「结束中」,且不允许再次开始。模拟释放未确认,确认阻止状态可见。6. 重新打开准备界面,确认工作授权和上下文确认均未勾选。仅展开区域或选择diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex f2fcef2f3..9abd56f8c 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -2445,7 +2445,6 @@ sklm: {callActionFailed: "Der Anruf konnte nicht aktualisiert werden. Versuche es erneut oder beende ihn.",workNotConnected: "Dieser Anruf ist nicht mit einer Arbeitssitzung verbunden.",workOptions: "Arbeitssitzung verbinden",- sessionSelectionVoice: "Die aktuelle Composer-Sitzung ist das Standardziel. Sage während des Anrufs 'Sitzungen auflisten' und wähle einen Namen, um das Ziel zu wechseln.",noWorkTarget: "Keine Sitzung ausgewählt. Sage Sitzungen auflisten und wähle eine anhand des Namens.",workStatusTitle: "Ausgewählte Arbeitssitzung und Aktivität",sessionSource: { desktop: "Desktop", "pi-native": "Native Pi", remote: "Remote-Host" },@@ -2461,7 +2460,6 @@ sklm: {muted: "Mikrofon stummgeschaltet",selectWorkSession: "Arbeitssitzung für den nächsten Anruf",shareContext: "Begrenzten aktuellen Gesprächskontext teilen",- contextConsent: "Wenn aktiviert, können bis zu sechs aktuelle reine Textnachrichten von Nutzer und Assistent aus der aktuellen Arbeitssitzung zur Anfrageklassifizierung mit Live geteilt werden. Standard ist die aktuelle Composer-Sitzung; eine Sprachwahl ändert das Ziel. Werkzeugausgaben, Anhänge und Sprachnachrichten werden nie geteilt. Diese Zustimmung gilt nur für diesen Anruf und erteilt keine Berechtigungen oder Genehmigungen.",contextShared: "Begrenzter aktueller Gesprächskontext wurde für diesen Anruf geteilt.",contextNotShared: "Der aktuelle Gesprächsverlauf wurde für diesen Anruf nicht geteilt.",createWorkSession: "Neue Arbeitssitzung erstellen",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex ce63a8f31..baa33f368 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -2491,7 +2491,6 @@ importConfirm: "Imported extensions run inside the agent process with the same acallActionFailed: "Couldn't update the call. Try again or end it.",workNotConnected: "This call isn't connected to a work session.",workOptions: "Connect a work session",- sessionSelectionVoice: "The current Composer session is the default. Say 'list sessions' and choose a name to switch targets.",noWorkTarget: "No session selected. Say list sessions and choose one by name.",workStatusTitle: "Selected work session and activity",sessionSource: { desktop: "Desktop", "pi-native": "Native Pi", remote: "Remote host" },@@ -2546,7 +2545,6 @@ importConfirm: "Imported extensions run inside the agent process with the same aworkSessionNoContext: "Recent chat history is not shared with this call.",selectWorkSession: "Work session for the next call",shareContext: "Share limited recent conversation context",- contextConsent: "If enabled, up to six recent plain-text user and assistant messages from the current work session may be shared with Live to classify requests. The Composer session is the default target; voice selection changes it. Tool output, attachments, and voice messages are never shared. This call-only consent does not grant permission or approve actions.",contextShared: "Limited recent conversation context was shared for this call.",contextNotShared: "Recent conversation history was not shared for this call.",createWorkSession: "Create a new work session",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 5bf7b6ab1..c33a91a43 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -2447,7 +2447,6 @@ sklm: {workStatusTitle: "Sesión de trabajo seleccionada y actividad",sessionSource: { desktop: "Desktop", "pi-native": "Pi nativo", remote: "Host remoto" },noWorkTarget: "No hay ninguna sesión seleccionada. Di listar sesiones y elige una por nombre.",- sessionSelectionVoice: "La sesión actual de Composer es el destino predeterminado. Di 'listar sesiones' durante la llamada y elige un nombre para cambiarlo.",allowWork: "Permitir solicitudes de trabajo",noWorkSession: "Elige o crea una sesión de trabajo local.",playbackBlocked: "El sonido está en pausa",@@ -2460,7 +2459,6 @@ sklm: {muted: "Micrófono silenciado",selectWorkSession: "Sesión de trabajo para la próxima llamada",shareContext: "Compartir contexto reciente limitado de la conversación",- contextConsent: "Si se activa, se pueden compartir con Live hasta seis mensajes de texto recientes del usuario y del asistente de la sesión de trabajo actual para clasificar solicitudes. La sesión actual de Composer es el destino predeterminado; la selección por voz lo cambia. Nunca se comparten resultados de herramientas, adjuntos ni mensajes de voz. Este consentimiento solo dura esta llamada y no concede permisos ni aprueba acciones.",contextShared: "Se compartió contexto reciente limitado de la conversación para esta llamada.",contextNotShared: "No se compartió el historial reciente de la conversación para esta llamada.",createWorkSession: "Crear una sesión de trabajo",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 4e1284b07..edf40be8d 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -2447,7 +2447,6 @@ sklm: {workStatusTitle: "Session de travail sélectionnée et activité",sessionSource: { desktop: "Desktop", "pi-native": "Pi natif", remote: "Hôte distant" },noWorkTarget: "Aucune session sélectionnée. Dites lister les sessions puis choisissez par nom.",- sessionSelectionVoice: "La session Composer actuelle est la cible par défaut. Dites 'lister les sessions' pendant l’appel, puis choisissez un nom pour changer de cible.",allowWork: "Autoriser les demandes de travail",noWorkSession: "Choisissez ou créez une session de travail locale.",playbackBlocked: "Le son est en pause",@@ -2460,7 +2459,6 @@ sklm: {muted: "Microphone coupé",selectWorkSession: "Session de travail pour le prochain appel",shareContext: "Partager un contexte récent limité de la conversation",- contextConsent: "Si cette option est activée, jusqu’à six messages textuels récents de l’utilisateur et de l’assistant de la session de travail actuelle peuvent être partagés avec Live pour classer les demandes. La session Composer actuelle est la cible par défaut ; la sélection vocale la modifie. Les sorties d’outils, pièces jointes et messages vocaux ne sont jamais partagés. Ce consentement vaut pour cet appel uniquement et n’accorde aucune permission ni approbation.",contextShared: "Un contexte récent limité de la conversation a été partagé pour cet appel.",contextNotShared: "L’historique récent de la conversation n’a pas été partagé pour cet appel.",createWorkSession: "Créer une session de travail",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex d9b778d4a..a6521bd58 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -2483,7 +2483,6 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이workStatusTitle: "선택한 작업 세션 및 활동",sessionSource: { desktop: "Desktop", "pi-native": "Native Pi", remote: "원격 호스트" },noWorkTarget: "선택된 세션이 없습니다. 세션 목록이라고 말하고 이름으로 선택하세요.",- sessionSelectionVoice: "현재 Composer 세션이 기본 대상입니다. 통화 중 세션 목록이라고 말한 다음 이름을 골라 대상을 바꿀 수 있습니다.",allowWork: "작업 요청 허용",noWorkSession: "로컬 작업 세션을 선택하거나 만드세요.",playbackBlocked: "소리 재생이 일시 중지되었습니다",@@ -2496,7 +2495,6 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이muted: "마이크 음소거됨",selectWorkSession: "다음 통화에 사용할 작업 세션",shareContext: "제한된 최근 대화 맥락 공유",- contextConsent: "켜면 현재 작업 세션의 최근 일반 사용자/도우미 텍스트 메시지를 최대 6개까지 요청 분류를 위해 Live와 공유할 수 있습니다. 기본 대상은 현재 Composer 세션이며 음성 선택으로 변경됩니다. 도구 출력, 첨부 파일, 음성 메시지는 공유하지 않습니다. 이 동의는 이번 통화에만 적용되며 권한을 부여하거나 작업을 승인하지 않습니다.",contextShared: "이 통화에 제한된 최근 대화 맥락을 공유했습니다.",contextNotShared: "이 통화에는 최근 대화 기록을 공유하지 않았습니다.",createWorkSession: "새 작업 세션 만들기",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex b30eb63d9..1561ddbb7 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -2403,7 +2403,6 @@ export const ptBR = {workStatusTitle: "Sessão de trabalho selecionada e atividade",sessionSource: { desktop: "Desktop", "pi-native": "Pi nativo", remote: "Host remoto" },noWorkTarget: "Nenhuma sessão selecionada. Diga listar sessões e escolha pelo nome.",- sessionSelectionVoice: "A sessão atual do Composer é o destino padrão. Durante a chamada, diga 'listar sessões' e escolha um nome para trocar de destino.",allowWork: "Permitir solicitações de trabalho",noWorkSession: "Escolha ou crie uma sessão de trabalho local.",playbackBlocked: "O som está pausado",@@ -2416,7 +2415,6 @@ export const ptBR = {muted: "Microfone silenciado",selectWorkSession: "Sessão de trabalho para a próxima chamada",shareContext: "Compartilhar contexto recente limitado da conversa",- contextConsent: "Se ativado, até seis mensagens recentes em texto simples do usuário e do assistente da sessão de trabalho atual podem ser compartilhadas com Live para classificar solicitações. A sessão atual do Composer é o destino padrão; a seleção por voz altera o destino. Saídas de ferramentas, anexos e mensagens de voz nunca são compartilhados. Esse consentimento vale só para esta chamada e não concede permissões nem aprova ações.",contextShared: "Um contexto recente limitado da conversa foi compartilhado nesta chamada.",contextNotShared: "O histórico recente da conversa não foi compartilhado nesta chamada.",createWorkSession: "Criar uma sessão de trabalho",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 01b93205a..ee01f0498 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -2473,7 +2473,6 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araçworkStatusTitle: "Seçili çalışma oturumu ve etkinlik",sessionSource: { desktop: "Desktop", "pi-native": "Yerel Pi", remote: "Uzak ana makine" },noWorkTarget: "Seçili oturum yok. Oturumları listele deyip ada göre seçim yapın.",- sessionSelectionVoice: "Geçerli Composer oturumu varsayılan hedeftir. Arama sırasında oturumları listele deyin ve hedefi değiştirmek için bir ad seçin.",allowWork: "Çalışma isteklerine izin ver",noWorkSession: "Yerel bir çalışma oturumu seçin veya oluşturun.",playbackBlocked: "Ses duraklatıldı",@@ -2486,7 +2485,6 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araçmuted: "Mikrofon sessizde",selectWorkSession: "Sonraki arama için çalışma oturumu",shareContext: "Son konuşmadan sınırlı bağlam paylaş",- contextConsent: "Etkinleştirilirse, mevcut çalışma oturumundaki en fazla altı yakın tarihli düz metin kullanıcı/asistan mesajı istekleri sınıflandırmak için Live ile paylaşılabilir. Varsayılan hedef geçerli Composer oturumudur; sesle seçim hedefi değiştirir. Araç çıktıları, ekler ve ses mesajları asla paylaşılmaz. Bu onay yalnızca bu arama için geçerlidir; izin vermez veya eylemleri onaylamaz.",contextShared: "Bu arama için son konuşmadan sınırlı bağlam paylaşıldı.",contextNotShared: "Bu arama için son konuşma geçmişi paylaşılmadı.",createWorkSession: "Yeni çalışma oturumu oluştur",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 7d5fa6819..4a0501a80 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -2437,7 +2437,6 @@ sklm: {workStatusTitle: "工作目标与进度",sessionSource: { desktop: "Desktop", "pi-native": "原生 Pi", remote: "远程主机" },noWorkTarget: "尚未选择会话。说“列出会话”并按名称选择。",- sessionSelectionVoice: "通话默认使用 Composer 当前会话。可在通话中说“列出会话”,再按名称切换目标。",allowWork: "允许发起工作请求",noWorkSession: "请选择或创建本地工作会话。",playbackBlocked: "声音播放已暂停",@@ -2485,7 +2484,6 @@ sklm: {workSessionNoContext: "此通话不会共享最近的聊天记录。",selectWorkSession: "下次通话使用的工作会话",shareContext: "共享有限的近期对话上下文",- contextConsent: "开启后,当前工作会话最多 6 条近期纯文本用户/助手消息可用于识别请求;默认目标是 Composer 当前会话,语音切换后随之改变。不会共享工具输出、附件或语音消息。此授权仅限本次通话,不授予操作权限或代替审批。",contextShared: "本次通话共享了有限的近期对话上下文。",contextNotShared: "本次通话没有共享近期对话历史。",createWorkSession: "新建工作会话",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex f24087f92..b96ce6042 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -2435,7 +2435,6 @@ sklm: {workStatusTitle: "工作目標與進度",sessionSource: { desktop: "Desktop", "pi-native": "原生 Pi", remote: "遠端主機" },noWorkTarget: "尚未選取工作階段。說「列出工作階段」並依名稱選擇。",- sessionSelectionVoice: "通話預設使用 Composer 目前的工作階段。通話中可說「列出工作階段」,再依名稱切換目標。",allowWork: "允許發起工作請求",noWorkSession: "請選擇或建立本機工作階段。",playbackBlocked: "聲音播放已暫停",@@ -2448,7 +2447,6 @@ sklm: {muted: "麥克風已靜音",selectWorkSession: "下次通話使用的工作階段",shareContext: "分享有限的近期對話上下文",- contextConsent: "開啟後,目前工作階段最多 6 則近期純文字使用者/助理訊息可用於判斷請求;預設目標是 Composer 目前的工作階段,語音切換後也會變更。工具輸出、附件與語音訊息不會分享。此授權僅限本次通話,不會授予操作權限或取代核准流程。",contextShared: "本次通話分享了有限的近期對話上下文。",contextNotShared: "本次通話未分享近期對話記錄。",createWorkSession: "建立工作階段",diff --git a/packages/i18n/test/catalogs.test.mjs b/packages/i18n/test/catalogs.test.mjsindex abe46c174..4d42dabfa 100644--- a/packages/i18n/test/catalogs.test.mjs+++ b/packages/i18n/test/catalogs.test.mjs@@ -37,7 +37,7 @@ test("Live Voice preparation and call recovery copy is localized in every shippe"playbackBlocked", "playbackFailed", "mediaReleaseUnconfirmed","callActionFailed", "workNotConnected", "transcript", "transcriptEmpty","userSpeaking", "assistantSpeaking", "muted", "resumePlayback",- "selectWorkSession", "shareContext", "contextConsent", "contextShared",+ "selectWorkSession", "shareContext", "contextShared","contextNotShared", "createWorkSession", "viewWorkSession", "enableDetail","microphoneDenied", "microphoneUnavailable", "microphoneBusy","phase.connecting", "phase.closing",diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex 0107bc43f..4cb3a6740 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -104,6 +104,9 @@ export const IPC = {liveVoiceResolveWorkSelection: "pi-desktop/voice/live/work/resolveSelection",liveVoiceStopWorkOperation: "pi-desktop/voice/live/work/stopOperation",liveVoiceCancelQueuedOperation: "pi-desktop/voice/live/work/cancelQueuedOperation",+ liveVoiceWidgetAction: "pi-desktop/voice/live/widget/action",+ liveVoiceWidgetIssue: "pi-desktop/voice/live/widget/issue",+ liveVoiceWidgetVisibility: "pi-desktop/voice/live/widget/visibility",agentCompact: "pi-desktop/agent/compact",agentAbort: "pi-desktop/agent/abort",agentStop: "pi-desktop/agent/stop",@@ -407,6 +410,8 @@ export const IPC = {liveVoicePort: "pi-desktop/voice/live/event/port",liveVoiceControl: "pi-desktop/voice/live/event/control",liveVoiceTranscript: "pi-desktop/voice/live/event/transcript",+ liveVoiceWidgetState: "pi-desktop/voice/live/event/widgetState",+ liveVoiceWidgetAction: "pi-desktop/voice/live/event/widgetAction",},} as const;diff --git a/packages/shared/src/types/live-voice.ts b/packages/shared/src/types/live-voice.tsindex 95cefc2c7..18a4f2c66 100644--- a/packages/shared/src/types/live-voice.ts+++ b/packages/shared/src/types/live-voice.ts@@ -314,3 +314,10 @@ export type LiveTranscriptEvent = {callId: string;segment: LiveTranscriptSegment;};++/**+ * The call actions a docked Live Voice widget can ask for. The widget window+ * owns no media and is not the Live Voice call owner, so every action travels+ * to the main window (the owner frame) and runs there.+ */+export type LiveVoiceWidgetAction = "cancel" | "mute" | "resume" | "end" | "details" | "settings";diff --git a/scripts/e2e-live-voice.mjs b/scripts/e2e-live-voice.mjsindex b6fb5cf78..7a5f03259 100644--- a/scripts/e2e-live-voice.mjs+++ b/scripts/e2e-live-voice.mjs@@ -32,11 +32,29 @@ const legacyVoice = { enabled: false, languages: ["en"] };const pass = (name) => { results.push(name); console.log(`PASS ${name}`); };const settings = () => desktop.invoke("settingsGet");const status = () => desktop.invoke("liveVoiceStatus");+// The call chrome lives in the docked widget window now: bar controls and the+// bar's own failure text are asserted there, while the composer, preparation+// menu and details surface stay in the main window.+let widget = null;+const useWidget = async () => (widget = await desktop.useWidget());+// The widget window is a separate renderer that fetches the persisted language+// itself, so the bar is addressed by its configured-language aria-labels.+const clickBar = (label) => widget.clickSelector(`.live-voice-call-bar button[aria-label="${label}"]`);+// A released call can still leave the bar on screen: the widget keeps drawing a+// failed call's LIVE_* code until the user dismisses it, so "released" means no+// bar in an active state — the same predicate the in-app bar used before the+// call chrome moved into its own window.+const ACTIVE_CALL_BAR = ["connecting", "connected", "reconnecting", "stopping"]+ .map((state) => `.live-voice-call-bar[data-state="${state}"]`)+ .join(", ");const waitIdle = () => waitFor(async () => {const call = (await status()).call;const mediaReleased = !call || (["ended", "failed"].includes(call.phase) && !call.microphoneActive);if (!mediaReleased) return false;- return desktop.evaluate("!document.querySelector('.live-voice-call-bar[data-state=\"connecting\"], .live-voice-call-bar[data-state=\"connected\"], .live-voice-call-bar[data-state=\"reconnecting\"], .live-voice-call-bar[data-state=\"stopping\"]') && !!document.querySelector('.live-voice-control button')");+ if (!await desktop.evaluate("!!document.querySelector('.live-voice-control button')")) return false;+ return widget+ ? widget.evaluate(`!document.querySelector('${ACTIVE_CALL_BAR}')`)+ : true;}, 12_000, "Live call media and Composer controls released");const navVoice = () => desktop.clickText("Live voice", ".settings-nav-label");const openSettings = async () => {@@ -52,13 +70,21 @@ const startCall = async () => {await waitFor(() => desktop.evaluate("!!document.querySelector('.live-voice-preparation .live-voice-start')"),5_000, "Live Voice preparation menu");await desktop.clickSelector(".live-voice-preparation .live-voice-start");+ // Starting the call is what creates the widget window; the bar is asserted+ // there from now on.+ await useWidget();await waitFor(async () => {- const [live, error] = await Promise.all([- status(), desktop.evaluate("!!document.querySelector('.live-voice-feedback[role=\"alert\"]')"),- ]);+ const live = await status();+ const alert = await widget.evaluate("!!document.querySelector('.live-voice-feedback[role=\"alert\"]')");const newCall = Boolean(live.call && live.call.callId !== previousCallId);- return newCall && (live.call?.phase === "connected" || (error && ["ended", "failed"].includes(live.call?.phase)));+ return newCall && (live.call?.phase === "connected" || (alert && ["ended", "failed"].includes(live.call?.phase)));}, 30_000, "local Realtime connected or startup failed");+ // The widget window has no app shell and fetches the persisted language+ // itself, so its chrome must come up in the configured language rather than+ // in the OS locale.+ await waitFor(() => widget.evaluate(`document.documentElement.lang === 'en'+ && !!document.querySelector('.live-voice-call-bar button[aria-label="Call details"]')`),+ 10_000, "widget chrome follows the configured language");assert.equal((await status()).call?.phase, "connected", "local Realtime call connected");};const openRealtimePicker = () => desktop.click(`@@ -129,22 +155,22 @@ try {await startCall();assert.equal((await status()).call.muted, true);assert.equal((await status()).call.workBinding, undefined);- await desktop.clickSelector('.live-voice-call-bar button[aria-label="Unmute microphone"]');+ await clickBar("Unmute microphone");await waitFor(() => fixture.stats.inputFrames > 0, 10_000, "synthetic microphone reaches the real WSS transport");await waitFor(async () => (await status()).call?.phase === "connected" && fixture.active() === 1,2_000, "uplink credit keeps the call and provider socket connected");fixture.reply();- await desktop.clickSelector('.live-voice-call-bar button[aria-label="Call details"]');+ await clickBar("Call details");await waitFor(() => desktop.evaluate("document.querySelector('.live-voice-transcripts')?.textContent.includes('Local voice fixture reply.')"), 8_000, "provider transcript reaches Renderer");await desktop.screenshot("live-voice-connected.png");await desktop.clickSelector('.live-voice-details-popup button[aria-label="Close"]');- await desktop.clickSelector('.live-voice-call-bar button[aria-label="Mute microphone"]');+ await clickBar("Mute microphone");await waitFor(async () => (await status()).call?.muted === true, 5_000, "microphone muted");await delay(200);const mutedFrames = fixture.stats.inputFrames;await delay(300);assert.equal(fixture.stats.inputFrames, mutedFrames, "muting stops new provider audio frames");- await desktop.clickSelector('.live-voice-call-bar button[aria-label="End call"]');+ await clickBar("End call");await waitIdle();await waitFor(() => fixture.active() === 0, 5_000, "provider socket closes after hangup");assert.deepEqual((await desktop.invoke("sessionList")).sessions, [], "voice-only call creates no Agent session");@@ -154,7 +180,10 @@ try {await desktop.clickSelector(".live-voice-control button");await desktop.clickSelector(".live-voice-preparation .live-voice-start");await waitFor(async () => (await status()).call?.phase === "connecting", 15_000, "delayed provider startup");- await desktop.clickSelector('.live-voice-call-bar button[aria-label="Cancel"]');+ // The widget window exists once the call view has been published; the bar is+ // the only place Cancel can be pressed.+ await useWidget();+ await clickBar("Cancel");await waitIdle();await waitFor(() => fixture.active() === 0, 5_000, "cancelled provider socket closes");await startCall();@@ -164,12 +193,14 @@ try {await delay(500);assert.equal(fixture.stats.connections, disconnectedConnections, "provider failure never auto-reconnects");await startCall();- await desktop.clickSelector('.live-voice-call-bar button[aria-label="End call"]');+ await clickBar("End call");await waitIdle();pass("cancelled startup and provider failure release resources for explicit reconnect");await desktop.close();desktop = await launch();+ // A relaunch has its own windows: the previous widget connection is gone.+ widget = null;const restored = await settings();assert.equal(restored.developerMode, false);assert.equal(restored.liveVoice.enabled, true);diff --git a/scripts/e2e/live-voice-desktop.mjs b/scripts/e2e/live-voice-desktop.mjsindex d3a8584b9..bbc7f7465 100644--- a/scripts/e2e/live-voice-desktop.mjs+++ b/scripts/e2e/live-voice-desktop.mjs@@ -49,19 +49,22 @@ export async function launchLiveVoiceDesktop({ root, dataDir, profile, home, cerchild.once("error", (error) => { launchError = error; });child.stdout.resume();child.stderr.resume();- let socket;- const pending = new Map();- let sequence = 0;+ // Each CDP target (the main window, the docked widget window) keeps its own+ // connection, so a step always acts on the surface it names.+ const connections = new Set();let closed = false;const close = async () => {if (closed) return;closed = true;- for (const entry of pending.values()) {- clearTimeout(entry.timer);- entry.reject(new Error("Live Voice test browser closed"));+ for (const connection of connections) {+ for (const entry of connection.pending.values()) {+ clearTimeout(entry.timer);+ entry.reject(new Error("Live Voice test browser closed"));+ }+ connection.pending.clear();+ connection.socket.close();}- pending.clear();- socket?.close();+ connections.clear();if (child.exitCode === null) {child.kill();await Promise.race([exit, delay(5_000)]);@@ -73,91 +76,113 @@ export async function launchLiveVoiceDesktop({ root, dataDir, profile, home, cerassert.ok(child.exitCode !== null || child.signalCode !== null, "isolated Electron exited");};try {- let target;- await waitFor(async () => {- if (launchError) throw launchError;- if (child.exitCode !== null || child.signalCode !== null) throw new Error("isolated Electron exited before its UI was ready");- try {- const response = await fetch(`http://127.0.0.1:${port}/json/list`);- target = (await response.json()).find((entry) => entry.type === "page" &&- entry.url.includes("index.html") && !entry.url.includes("plugin-launcher"));- return Boolean(target);- } catch { return false; }- }, 45_000, "isolated Live Voice desktop CDP target");- socket = new WebSocket(target.webSocketDebuggerUrl);- await once(socket, "open");- socket.onmessage = ({ data }) => {- const message = JSON.parse(data);- const entry = pending.get(message.id);- if (!entry) return;- pending.delete(message.id);- clearTimeout(entry.timer);- if (message.error) entry.reject(new Error(`CDP request failed: ${message.error.code}`));- else entry.resolve(message.result);- };- const send = (method, params = {}) => new Promise((resolve, reject) => {- const id = ++sequence;- const timer = setTimeout(() => {- pending.delete(id);- reject(new Error(`CDP ${method} timed out`));- }, 15_000);- pending.set(id, { resolve, reject, timer });- socket.send(JSON.stringify({ id, method, params }));- });- const evaluate = async (expression) => {- const result = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });- if (result.exceptionDetails) throw new Error("Live Voice browser assertion failed");- return result.result.value;- };- const click = async (expression) => {- let point;+ // The main window and the docked widget window are separate CDP targets, and+ // The main window and the docked widget window are separate CDP targets, and+ // each gets its own connection, so a step always acts on the surface it+ // names: the composer, preparation menu and details in the main window, the+ // call bar in the widget.+ const attach = async (pick, label) => {+ let target;await waitFor(async () => {- point = await evaluate(`(() => {- const el = (${expression});- if (!el || el.disabled) return null;- el.scrollIntoView({ block: 'center', behavior: 'instant' });- const r = el.getBoundingClientRect();- const x = r.left + r.width / 2, y = r.top + r.height / 2;- return r.width && r.height && el.contains(document.elementFromPoint(x, y)) ? { x, y } : null;- })()`);- return Boolean(point);- }, 10_000, "clickable Live Voice control");- for (const type of ["mousePressed", "mouseReleased"]) {- await send("Input.dispatchMouseEvent", { type, ...point, button: "left", clickCount: 1 });- }- };- const clickSelector = (selector) => click(`document.querySelector(${JSON.stringify(selector)})`);- const clickText = (text, selector = "button") => click(- `[...document.querySelectorAll(${JSON.stringify(selector)})].find(el => el.textContent.trim() === ${JSON.stringify(text)})?.closest('button')`,- );- const input = async (selector, value) => {- await clickSelector(selector);- await evaluate(`(() => document.querySelector(${JSON.stringify(selector)})?.select())()`);- if (value) await send("Input.insertText", { text: value });- else {- for (const type of ["keyDown", "keyUp"]) {- await send("Input.dispatchKeyEvent", { type, key: "Backspace", code: "Backspace", windowsVirtualKeyCode: 8 });+ if (launchError) throw launchError;+ if (child.exitCode !== null || child.signalCode !== null) throw new Error("isolated Electron exited before its UI was ready");+ try {+ const response = await fetch(`http://127.0.0.1:${port}/json/list`);+ target = (await response.json()).find((entry) => entry.type === "page" && pick(entry));+ return Boolean(target);+ } catch { return false; }+ }, 45_000, label);+ const socket = new WebSocket(target.webSocketDebuggerUrl);+ const pending = new Map();+ let sequence = 0;+ const connection = { socket, pending };+ connections.add(connection);+ socket.addEventListener("close", () => connections.delete(connection));+ await once(socket, "open");+ socket.onmessage = ({ data }) => {+ const message = JSON.parse(data);+ const entry = pending.get(message.id);+ if (!entry) return;+ pending.delete(message.id);+ clearTimeout(entry.timer);+ if (message.error) entry.reject(new Error(`CDP request failed: ${message.error.code}`));+ else entry.resolve(message.result);+ };+ const send = (method, params = {}) => new Promise((resolve, reject) => {+ const id = ++sequence;+ const timer = setTimeout(() => {+ pending.delete(id);+ reject(new Error(`CDP ${method} timed out`));+ }, 15_000);+ pending.set(id, { resolve, reject, timer });+ socket.send(JSON.stringify({ id, method, params }));+ });+ const evaluate = async (expression) => {+ const result = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });+ if (result.exceptionDetails) throw new Error("Live Voice browser assertion failed");+ return result.result.value;+ };+ const click = async (expression) => {+ let point;+ await waitFor(async () => {+ point = await evaluate(`(() => {+ const el = (${expression});+ if (!el || el.disabled) return null;+ el.scrollIntoView({ block: 'center', behavior: 'instant' });+ const r = el.getBoundingClientRect();+ const x = r.left + r.width / 2, y = r.top + r.height / 2;+ return r.width && r.height && el.contains(document.elementFromPoint(x, y)) ? { x, y } : null;+ })()`);+ return Boolean(point);+ }, 10_000, "clickable Live Voice control");+ for (const type of ["mousePressed", "mouseReleased"]) {+ await send("Input.dispatchMouseEvent", { type, ...point, button: "left", clickCount: 1 });}- }- };- const invoke = async (channel, ...args) => {- const result = await evaluate(`window.piDesktop.invoke(window.piDesktop.channels.invoke[${JSON.stringify(channel)}], ...${JSON.stringify(args)})`);- if (!result.ok) {- const code = typeof result.error?.code === "string" && /^[A-Z][A-Z0-9_]{0,80}$/.test(result.error.code)- ? result.error.code : "UNKNOWN";- throw new Error(`Live Voice IPC ${channel} failed: ${code}`);- }- return result.data;- };- const screenshot = async (name) => {- const result = await send("Page.captureScreenshot", { format: "png" });- await writeFile(join(evidence, name), Buffer.from(result.data, "base64"));+ };+ const clickSelector = (selector) => click(`document.querySelector(${JSON.stringify(selector)})`);+ const clickText = (text, selector = "button") => click(+ `[...document.querySelectorAll(${JSON.stringify(selector)})].find(el => el.textContent.trim() === ${JSON.stringify(text)})?.closest('button')`,+ );+ const input = async (selector, value) => {+ await clickSelector(selector);+ await evaluate(`(() => document.querySelector(${JSON.stringify(selector)})?.select())()`);+ if (value) await send("Input.insertText", { text: value });+ else {+ for (const type of ["keyDown", "keyUp"]) {+ await send("Input.dispatchKeyEvent", { type, key: "Backspace", code: "Backspace", windowsVirtualKeyCode: 8 });+ }+ }+ };+ const invoke = async (channel, ...args) => {+ const result = await evaluate(`window.piDesktop.invoke(window.piDesktop.channels.invoke[${JSON.stringify(channel)}], ...${JSON.stringify(args)})`);+ if (!result.ok) {+ const code = typeof result.error?.code === "string" && /^[A-Z][A-Z0-9_]{0,80}$/.test(result.error.code)+ ? result.error.code : "UNKNOWN";+ throw new Error(`Live Voice IPC ${channel} failed: ${code}`);+ }+ return result.data;+ };+ const screenshot = async (name) => {+ const result = await send("Page.captureScreenshot", { format: "png" });+ await writeFile(join(evidence, name), Buffer.from(result.data, "base64"));+ };+ await send("Runtime.enable");+ await send("Page.enable");+ return { evaluate, click, clickSelector, clickText, input, invoke, screenshot };};- await send("Runtime.enable");- await send("Page.enable");- await waitFor(() => evaluate(`!!document.querySelector('[data-nav="settings"]') && !document.querySelector('.startup-splash')`),+ const isMainWindow = (entry) => entry.url.includes("index.html") &&+ !entry.url.includes("plugin-launcher") && !entry.url.includes("live-voice-widget");+ const isWidgetWindow = (entry) => entry.url.includes("surface=live-voice-widget");+ const mainWindow = await attach(isMainWindow, "isolated Live Voice desktop CDP target");+ await waitFor(() => mainWindow.evaluate(`!!document.querySelector('[data-nav="settings"]') && !document.querySelector('.startup-splash')`),35_000, "Live Voice app navigation");- return { close, evaluate, click, clickSelector, clickText, input, invoke, screenshot };+ let widgetWindow = null;+ return {+ close,+ ...mainWindow,+ /** The docked widget window: it appears when a call starts. */+ useWidget: async () => (widgetWindow ??= await attach(isWidgetWindow, "isolated Live Voice widget CDP target")),+ };} catch (error) {await close();throw error;