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(lifecycle): theme quit and close-behavior confirms (#1714)
Lan24493f9c53ad
diff --git a/apps/desktop/electron/main/bootstrap/close-behavior.ts b/apps/desktop/electron/main/bootstrap/close-behavior.tsindex 6b1ca20c6..e52e9b947 100644--- a/apps/desktop/electron/main/bootstrap/close-behavior.ts+++ b/apps/desktop/electron/main/bootstrap/close-behavior.ts@@ -1,17 +1,20 @@-import { dialog, type BrowserWindow } from "electron";+import { dialog, type BrowserWindow, type WebContents } from "electron";import { catalogs, resolveLocale } from "@pi-desktop/i18n";-import type { CloseBehavior } from "@pi-desktop/shared";+import { IPC, type CloseBehavior, type LifecycleDialogChoice, type LifecycleDialogKind } from "@pi-desktop/shared";+import type { Logger } from "../logger";import {readCloseBehavior,writeCloseBehavior,} from "../window-preferences";import type { WindowLifecycleState } from "./window";+import { createLifecycleDialogBroker } from "./lifecycle-dialog";export type CloseBehaviorDependencies = {state: WindowLifecycleState;dataDir: string;getLocale: () => string;createTray: () => void;+ logger: Pick<Logger, "app">;};export function createCloseBehaviorRuntime({@@ -19,41 +22,101 @@ export function createCloseBehaviorRuntime({dataDir,getLocale,createTray,+ logger,}: CloseBehaviorDependencies) {+ const lifecycleDialogs = createLifecycleDialogBroker({+ onError: (error) => {+ logger.app("lifecycle", "warn", "lifecycle dialog fallback failed", {+ data: String(error),+ });+ },+ });+ const observedWebContents = new WeakSet<WebContents>();+const applyCloseBehavior = (next: CloseBehavior): void => {state.closeBehavior = next;writeCloseBehavior(dataDir, next);if (next === "tray") createTray();};- const askCloseBehavior = async (+ const markLifecycleDialogRendererReady = (window: BrowserWindow): boolean => {+ if (window !== state.mainWindow || window.isDestroyed()) return false;+ const contents = window.webContents;+ if (contents.isDestroyed()) return false;+ if (!observedWebContents.has(contents)) {+ observedWebContents.add(contents);+ const windowId = contents.id;+ contents.on("did-start-navigation", (_event, _url, _inPlace, isMainFrame) => {+ if (isMainFrame) lifecycleDialogs.markUnavailable(windowId);+ });+ contents.on("render-process-gone", () => lifecycleDialogs.markUnavailable(windowId));+ contents.once("destroyed", () => lifecycleDialogs.markUnavailable(windowId));+ }+ lifecycleDialogs.markReady(contents.id);+ return true;+ };++ const respondLifecycleDialog = (+ senderWindowId: number,+ requestId: unknown,+ choice: unknown,+ ): boolean => lifecycleDialogs.respond(senderWindowId, requestId, choice);++ const showLifecycleDialog = (window: BrowserWindow,- ): Promise<"tray" | "quit" | null> => {+ kind: LifecycleDialogKind,+ fallback: () => Promise<LifecycleDialogChoice>,+ ): Promise<LifecycleDialogChoice> =>+ lifecycleDialogs.request({+ windowId: window.webContents.id,+ kind,+ send: (request) => window.webContents.send(IPC.event.lifecycleDialogRequest, request),+ dismiss: (requestId) => window.webContents.send(IPC.event.lifecycleDialogDismiss, { requestId }),+ fallback,+ });++ const showNativeCloseBehaviorDialog = async (+ window: BrowserWindow,+ ): Promise<LifecycleDialogChoice> => {const labels = catalogs[resolveLocale(getLocale())];const { response } = await dialog.showMessageBox(window, {type: "question",title: labels.tray.askTitle,- message: labels.tray.askTitle,- detail: labels.tray.askBody,+ message: labels.tray.askBody,buttons: [labels.common.cancel, labels.tray.closeToTray, labels.tray.quit],defaultId: 1,cancelId: 0,noLink: true,});- return response === 1 ? "tray" : response === 2 ? "quit" : null;+ return response === 1 ? "tray" : response === 2 ? "quit" : "cancel";};- const confirmQuitDialog = async (): Promise<boolean> => {+ const askCloseBehavior = async (+ window: BrowserWindow,+ ): Promise<"tray" | "quit" | null> => {+ try {+ const choice = await showLifecycleDialog(+ window,+ "close-behavior",+ () => showNativeCloseBehaviorDialog(window),+ );+ return choice === "tray" || choice === "quit" ? choice : null;+ } catch (error) {+ logger.app("lifecycle", "warn", "close behavior confirmation failed; allowing quit", {+ data: String(error),+ });+ return "quit";+ }+ };++ const showNativeQuitDialog = async (+ parent: BrowserWindow | undefined,+ ): Promise<LifecycleDialogChoice> => {const labels = catalogs[resolveLocale(getLocale())];- const parent =- state.mainWindow && !state.mainWindow.isDestroyed()- ? state.mainWindow- : undefined;const options = {type: "warning" as const,title: labels.tray.confirmQuitTitle,- message: labels.tray.confirmQuitTitle,- detail: labels.tray.confirmQuitBody,+ message: labels.tray.confirmQuitBody,buttons: [labels.common.cancel, labels.tray.confirmQuit],defaultId: 0,cancelId: 0,@@ -62,13 +125,37 @@ export function createCloseBehaviorRuntime({const { response } = parent? await dialog.showMessageBox(parent, options): await dialog.showMessageBox(options);- return response === 1;+ return response === 1 ? "confirm" : "cancel";+ };++ const confirmQuitDialog = async (): Promise<boolean> => {+ try {+ const parent = state.mainWindow && !state.mainWindow.isDestroyed()+ ? state.mainWindow+ : undefined;+ if (parent && (parent.isMinimized() || !parent.isVisible())) {+ parent.isMinimized() ? parent.restore() : parent.show();+ parent.focus();+ }+ const fallback = () => showNativeQuitDialog(parent);+ const choice = parent+ ? await showLifecycleDialog(parent, "quit-confirmation", fallback)+ : await fallback();+ return choice === "confirm";+ } catch (error) {+ logger.app("lifecycle", "warn", "quit confirmation failed; allowing shutdown", {+ data: String(error),+ });+ return true;+ }};return {applyCloseBehavior,askCloseBehavior,confirmQuitDialog,+ markLifecycleDialogRendererReady,+ respondLifecycleDialog,readCloseBehavior: () => readCloseBehavior(dataDir),};}diff --git a/apps/desktop/electron/main/bootstrap/lifecycle-dialog.ts b/apps/desktop/electron/main/bootstrap/lifecycle-dialog.tsnew file mode 100644index 000000000..8f3e52c37--- /dev/null+++ b/apps/desktop/electron/main/bootstrap/lifecycle-dialog.ts@@ -0,0 +1,164 @@+import { randomUUID } from "node:crypto";+import type {+ LifecycleDialogChoice,+ LifecycleDialogKind,+ LifecycleDialogRequest,+} from "@pi-desktop/shared";++export const LIFECYCLE_DIALOG_TIMEOUT_MS = 10_000;++type TimerHandle = ReturnType<typeof setTimeout>;+type LifecycleDialogRequestOptions = {+ windowId: number;+ kind: LifecycleDialogKind;+ send: (request: LifecycleDialogRequest) => void;+ dismiss: (requestId: string) => void;+ fallback: () => Promise<LifecycleDialogChoice>;+};++type PendingRequest = {+ requestId: string;+ windowId: number;+ kind: LifecycleDialogKind;+ dismiss: LifecycleDialogRequestOptions["dismiss"];+ fallback: LifecycleDialogRequestOptions["fallback"];+ resolve: (choice: LifecycleDialogChoice) => void;+ timer: TimerHandle | null;+ active: boolean;+};++type LifecycleDialogBrokerOptions = {+ timeoutMs?: number;+ createRequestId?: () => string;+ onError?: (error: unknown) => void;+ schedule?: (callback: () => void, delayMs: number) => TimerHandle;+ cancelSchedule?: (timer: TimerHandle) => void;+};++function isChoiceForKind(+ kind: LifecycleDialogKind,+ choice: unknown,+): choice is LifecycleDialogChoice {+ if (kind === "quit-confirmation") {+ return choice === "cancel" || choice === "confirm";+ }+ return choice === "cancel" || choice === "tray" || choice === "quit";+}++function failOpenChoice(kind: LifecycleDialogKind): LifecycleDialogChoice {+ return kind === "quit-confirmation" ? "confirm" : "quit";+}++/** Routes lifecycle decisions to the ready main renderer, with a bounded native fallback. */+export function createLifecycleDialogBroker({+ timeoutMs = LIFECYCLE_DIALOG_TIMEOUT_MS,+ createRequestId = randomUUID,+ onError,+ schedule = setTimeout,+ cancelSchedule = clearTimeout,+}: LifecycleDialogBrokerOptions = {}) {+ let readyWindowId: number | null = null;+ const pending = new Map<string, PendingRequest>();++ const report = (error: unknown) => {+ try {+ onError?.(error);+ } catch {+ // A logging failure must not keep the app from exiting.+ }+ };++ const fallbackChoice = async (+ kind: LifecycleDialogKind,+ fallback: LifecycleDialogRequestOptions["fallback"],+ ): Promise<LifecycleDialogChoice> => {+ try {+ const choice = await fallback();+ if (isChoiceForKind(kind, choice)) return choice;+ report(new Error("lifecycle dialog fallback returned an invalid choice"));+ } catch (error) {+ report(error);+ }+ return failOpenChoice(kind);+ };++ const settle = (request: PendingRequest, choice: LifecycleDialogChoice) => {+ if (!request.active) return;+ request.active = false;+ pending.delete(request.requestId);+ if (request.timer !== null) cancelSchedule(request.timer);+ request.resolve(choice);+ };++ const useFallback = (request: PendingRequest) => {+ if (!request.active) return;+ request.active = false;+ pending.delete(request.requestId);+ if (request.timer !== null) cancelSchedule(request.timer);+ try {+ request.dismiss(request.requestId);+ } catch (error) {+ report(error);+ }+ void fallbackChoice(request.kind, request.fallback).then(request.resolve);+ };++ return {+ markReady(windowId: number): void {+ readyWindowId = windowId;+ },++ markUnavailable(windowId: number): void {+ if (readyWindowId === windowId) readyWindowId = null;+ for (const request of pending.values()) {+ if (request.windowId === windowId) useFallback(request);+ }+ },++ respond(+ senderWindowId: number,+ requestId: unknown,+ choice: unknown,+ ): boolean {+ if (typeof requestId !== "string" || !requestId) return false;+ const request = pending.get(requestId);+ if (+ !request ||+ request.windowId !== senderWindowId ||+ !isChoiceForKind(request.kind, choice)+ ) {+ return false;+ }+ settle(request, choice);+ return true;+ },++ request({ windowId, kind, send, dismiss, fallback }: LifecycleDialogRequestOptions) {+ if (readyWindowId !== windowId || pending.size > 0) {+ return fallbackChoice(kind, fallback);+ }++ return new Promise<LifecycleDialogChoice>((resolve) => {+ const requestId = createRequestId();+ const current: PendingRequest = {+ requestId,+ windowId,+ kind,+ dismiss,+ fallback,+ resolve,+ timer: null,+ active: true,+ };+ pending.set(requestId, current);++ try {+ current.timer = schedule(() => useFallback(current), timeoutMs);+ send({ requestId, kind });+ } catch {+ useFallback(current);+ }+ });+ },+ };+}diff --git a/apps/desktop/electron/main/bootstrap/shutdown.ts b/apps/desktop/electron/main/bootstrap/shutdown.tsindex 930ed98ad..dfd668358 100644--- a/apps/desktop/electron/main/bootstrap/shutdown.ts+++ b/apps/desktop/electron/main/bootstrap/shutdown.ts@@ -77,6 +77,7 @@ export function registerShutdownHandlers({liveCallService,disposeSystemProxyRelay,}: ShutdownDependencies): void {+ let quitConfirmationPending = false;app.on("window-all-closed", () => {// The D216 tray is resident on every platform, so its presence says nothing// about whether the app should survive a closed window — the user's close@@ -95,7 +96,7 @@ export function registerShutdownHandlers({if (!hasSingleInstanceLock) return;if (state.shutdownComplete) return;event.preventDefault();- if (state.shutdownPromise) return;+ if (state.shutdownPromise || quitConfirmationPending) return;// Show a confirmation dialog on the first explicit quit (Cmd+Q, tray quit,// application-menu Quit). The data-saving shutdown runs after confirmation.@@ -113,14 +114,25 @@ export function registerShutdownHandlers({const isUpdateRestart = updater.isInstallingUpdate();if (!state.quitConfirmed && !isAutomatedMode && !isUpdateRestart) {state.quitConfirmed = true;- void confirmQuitDialog().then((confirmed) => {- if (confirmed) {+ quitConfirmationPending = true;+ void confirmQuitDialog().then(+ (confirmed) => {+ quitConfirmationPending = false;+ if (confirmed) {+ app.quit();+ } else {+ // User cancelled: allow future quit requests to prompt again.+ state.quitConfirmed = false;+ }+ },+ (error: unknown) => {+ quitConfirmationPending = false;+ logger.app("lifecycle", "warn", "quit confirmation failed; allowing shutdown", {+ data: String(error),+ });app.quit();- } else {- // User cancelled: allow future quit requests to prompt again.- state.quitConfirmed = false;- }- });+ },+ );return;}diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex 8f834cac2..78189811d 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -554,10 +554,13 @@ closeBehaviorRuntime = createCloseBehaviorRuntime({dataDir,getLocale: () => mainState.updaterLocale,createTray,+ logger,});const {applyCloseBehavior,confirmQuitDialog,+ markLifecycleDialogRendererReady,+ respondLifecycleDialog,} = closeBehaviorRuntime;const createdLauncher = createLauncher({@@ -911,6 +914,8 @@ function registerIpc() {applyCloseBehavior,getCloseBehavior: () => mainState.closeBehavior,markMenuRendererReady,+ markLifecycleDialogRendererReady,+ respondLifecycleDialog,executeNativeMenuAction,scheduledRunsBySession,isQuitting: () => mainState.quitting,diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.tsindex b45d6bb25..bd718f67c 100644--- a/apps/desktop/electron/main/ipc/register.ts+++ b/apps/desktop/electron/main/ipc/register.ts@@ -1,6 +1,6 @@import { join } from "node:path";import { dialog, shell, type BrowserWindow, type IpcMain, type IpcMainInvokeEvent } from "electron";-import { err, ErrorCodes, IPC, ok, type Result } from "@pi-desktop/shared";+import { err, ErrorCodes, IPC, ok, type LifecycleDialogChoice, type Result } from "@pi-desktop/shared";import type { AgentHostBridge } from "../agent-host-bridge";import type { AgentSidecar } from "../agent-sidecar";import type { HostProcess } from "../host-process";@@ -67,6 +67,8 @@ export type RegisterIpcDependencies = {liveVoiceWidget?: LiveVoiceWidget;restartForStorage: () => void;mcpOAuth?: McpOAuthManager;+ markLifecycleDialogRendererReady: (window: BrowserWindow) => boolean;+ respondLifecycleDialog: (senderWindowId: number, requestId: unknown, choice: LifecycleDialogChoice) => boolean;[name: string]: any;};@@ -140,6 +142,8 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {applyCloseBehavior,getCloseBehavior,markMenuRendererReady,+ markLifecycleDialogRendererReady,+ respondLifecycleDialog,traySessions,taskbarUnreadBadge,executeNativeMenuAction,@@ -344,6 +348,8 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {applyCloseBehavior,getCloseBehavior,markMenuRendererReady,+ markLifecycleDialogRendererReady,+ respondLifecycleDialog,executeNativeMenuAction,});registerScheduledIpc({diff --git a/apps/desktop/electron/main/ipc/window-ipc.ts b/apps/desktop/electron/main/ipc/window-ipc.tsindex 50a8b560b..e9050bfe0 100644--- a/apps/desktop/electron/main/ipc/window-ipc.ts+++ b/apps/desktop/electron/main/ipc/window-ipc.ts@@ -10,6 +10,7 @@ import {parseTraySessionPreferences,type NativeMenuAction,type WindowControlAction,+ type LifecycleDialogChoice,type TraySessionPreferences,} from "@pi-desktop/shared";import {@@ -34,6 +35,8 @@ export type WindowIpcDependencies = {getWorkPanelChatWidthSetter: () => ((width: number) => number) | null;applyCloseBehavior: (behavior: "tray" | "quit") => void;getCloseBehavior: () => "ask" | "tray" | "quit";+ markLifecycleDialogRendererReady: (window: BrowserWindow) => boolean;+ respondLifecycleDialog: (senderWindowId: number, requestId: unknown, choice: LifecycleDialogChoice) => boolean;markMenuRendererReady: (window: BrowserWindow) => boolean;executeNativeMenuAction: (action: NativeMenuAction) => unknown;setTraySessionPreferences: (preferences: TraySessionPreferences) => Promise<void>;@@ -50,6 +53,8 @@ export function registerWindowIpc({applyCloseBehavior,getCloseBehavior,markMenuRendererReady,+ markLifecycleDialogRendererReady,+ respondLifecycleDialog,executeNativeMenuAction,setTraySessionPreferences,}: WindowIpcDependencies): void {@@ -205,6 +210,37 @@ export function registerWindowIpc({return { behavior };});+ handleWithEvent(IPC.invoke.lifecycleDialogReady, async (event) => {+ registrar.assertMainWindowSender(event);+ const window = BrowserWindow.fromWebContents(event.sender);+ if (!window || !markLifecycleDialogRendererReady(window)) {+ throw Object.assign(new Error("lifecycle dialog renderer is not ready"), {+ errorCode: ErrorCodes.INTERNAL,+ });+ }+ return { ready: true };+ });++ handleWithEvent(IPC.invoke.lifecycleDialogRespond, async (event, input: unknown = {}) => {+ registrar.assertMainWindowSender(event);+ const value = input && typeof input === "object"+ ? input as Record<string, unknown>+ : null;+ if (+ !value ||+ typeof value.requestId !== "string" ||+ !value.requestId ||+ value.requestId.length > 64 ||+ (value.choice !== "cancel" && value.choice !== "confirm" && value.choice !== "tray" && value.choice !== "quit")+ ) {+ throw Object.assign(new Error("invalid lifecycle dialog response"), {+ errorCode: ErrorCodes.INVALID_ARGUMENT,+ });+ }+ return {+ accepted: respondLifecycleDialog(event.sender.id, value.requestId, value.choice as LifecycleDialogChoice),+ };+ });handleWithEvent(IPC.invoke.menuRendererReady, async (event) => {const window = BrowserWindow.fromWebContents(event.sender);const mainWindow = getMainWindow();diff --git a/apps/desktop/src/components/LifecycleConfirmationDialog.tsx b/apps/desktop/src/components/LifecycleConfirmationDialog.tsxnew file mode 100644index 000000000..d588b1bfc--- /dev/null+++ b/apps/desktop/src/components/LifecycleConfirmationDialog.tsx@@ -0,0 +1,158 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import type {+ LifecycleDialogChoice,+ LifecycleDialogRequest,+} from "@pi-desktop/shared";+import { useBlockingOverlay } from "../lib/blocking-overlay";+import { api } from "../lib/api";+import { Button, OverlayBackdrop, portalOverlay } from "./ui";++type DialogSurfaceProps = {+ request: LifecycleDialogRequest;+ onRespond: (choice: LifecycleDialogChoice) => void;+};++function DialogSurface({ request, onRespond }: DialogSurfaceProps) {+ const { t } = useTranslation();+ const cancelButton = useRef<HTMLButtonElement | null>(null);+ const dialog = useRef<HTMLDivElement | null>(null);+ const isCloseBehavior = request.kind === "close-behavior";+ const title = isCloseBehavior ? t("tray.askTitle") : t("tray.confirmQuitTitle");+ const description = isCloseBehavior ? t("tray.askBody") : t("tray.confirmQuitBody");+ useBlockingOverlay();++ useEffect(() => {+ const previouslyFocused = document.activeElement instanceof HTMLElement+ ? document.activeElement+ : null;+ const frame = window.requestAnimationFrame(() => cancelButton.current?.focus());+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ onRespond("cancel");+ return;+ }+ if (event.key !== "Tab") return;+ const focusable = dialog.current?.querySelectorAll<HTMLButtonElement>(+ "button:not([disabled])",+ );+ if (!focusable?.length) return;+ const first = focusable[0];+ const last = focusable[focusable.length - 1];+ const activeIndex = Array.from(focusable).indexOf(+ document.activeElement as HTMLButtonElement,+ );+ if (event.shiftKey && activeIndex <= 0) {+ event.preventDefault();+ last.focus();+ } else if (!event.shiftKey && (activeIndex === -1 || activeIndex === focusable.length - 1)) {+ event.preventDefault();+ first.focus();+ }+ };+ window.addEventListener("keydown", onKeyDown);+ return () => {+ window.cancelAnimationFrame(frame);+ window.removeEventListener("keydown", onKeyDown);+ if (previouslyFocused?.isConnected) previouslyFocused.focus();+ };+ }, [request.requestId, onRespond]);++ return portalOverlay(+ <OverlayBackdrop+ className="overlay lifecycle-confirmation-overlay"+ role="presentation"+ onClick={() => onRespond("cancel")}+ >+ <div+ ref={dialog}+ className="dialog lifecycle-confirmation-dialog"+ role="dialog"+ aria-modal="true"+ aria-labelledby="lifecycle-confirmation-title"+ aria-describedby="lifecycle-confirmation-description"+ onClick={(event) => event.stopPropagation()}+ >+ <div className="lifecycle-confirmation-heading">+ <h2 id="lifecycle-confirmation-title">{title}</h2>+ <p id="lifecycle-confirmation-description">{description}</p>+ </div>+ <div className="lifecycle-confirmation-actions">+ <Button+ ref={cancelButton}+ type="button"+ variant="ghost"+ onClick={() => onRespond("cancel")}+ >+ {t("common.cancel")}+ </Button>+ {isCloseBehavior ? (+ <>+ <Button+ type="button"+ variant="secondary"+ onClick={() => onRespond("tray")}+ >+ {t("tray.closeToTray")}+ </Button>+ <Button+ type="button"+ variant="primary"+ onClick={() => onRespond("quit")}+ >+ {t("tray.quit")}+ </Button>+ </>+ ) : (+ <Button+ type="button"+ variant="primary"+ onClick={() => onRespond("confirm")}+ >+ {t("tray.confirmQuit")}+ </Button>+ )}+ </div>+ </div>+ </OverlayBackdrop>,+ );+}++export function LifecycleConfirmationDialog() {+ const [request, setRequest] = useState<LifecycleDialogRequest | null>(null);+ const activeRequest = useRef<LifecycleDialogRequest | null>(null);++ const respond = useCallback((choice: LifecycleDialogChoice) => {+ const current = activeRequest.current;+ if (!current) return;+ activeRequest.current = null;+ setRequest(null);+ void api.respondLifecycleDialog(current.requestId, choice).catch((error: unknown) => {+ console.error("Failed to resolve lifecycle dialog", error);+ });+ }, []);++ useEffect(() => {+ const unsubscribeRequest = api.onLifecycleDialogRequest((next) => {+ activeRequest.current = next;+ setRequest(next);+ });+ const unsubscribeDismiss = api.onLifecycleDialogDismiss((requestId) => {+ if (activeRequest.current?.requestId !== requestId) return;+ activeRequest.current = null;+ setRequest(null);+ });+ void api.markLifecycleDialogRendererReady().catch((error: unknown) => {+ console.error("Failed to register lifecycle dialog renderer", error);+ });+ return () => {+ unsubscribeRequest();+ unsubscribeDismiss();+ activeRequest.current = null;+ };+ }, []);++ return request ? <DialogSurface request={request} onRespond={respond} /> : null;+}diff --git a/apps/desktop/src/features/app/AppShell.tsx b/apps/desktop/src/features/app/AppShell.tsxindex 2e52ceb9c..0b405f543 100644--- a/apps/desktop/src/features/app/AppShell.tsx+++ b/apps/desktop/src/features/app/AppShell.tsx@@ -7,6 +7,7 @@ import {IconPanel,IconPanelOpen,} from "../../components/icons";+import { LifecycleConfirmationDialog } from "../../components/LifecycleConfirmationDialog";import { ProjectCreateDialog } from "../../components/ProjectCreateDialog";import { SearchDialog } from "../../components/SearchDialog";import { Sidebar } from "../../components/Sidebar";@@ -376,6 +377,7 @@ export function AppShell() {<WindowControls />) : null}<ProjectCreateDialog />+ <LifecycleConfirmationDialog />{splash}{startupRecovery}</div>diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex a01f68476..0772271cb 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -133,6 +133,9 @@ import type {UpdateState,WindowControlAction,CloseBehavior,+ LifecycleDialogChoice,+ LifecycleDialogKind,+ LifecycleDialogRequest,ConfigSyncApprovalInput,ConfigSyncChangePasswordInput,ConfigSyncHistoryEntry,@@ -1584,6 +1587,31 @@ export const api = {invoke<{ behavior: CloseBehavior }>(IPC.invoke.closeBehaviorSet, {behavior,}),+ markLifecycleDialogRendererReady: () =>+ invoke<{ ready: boolean }>(IPC.invoke.lifecycleDialogReady),+ respondLifecycleDialog: (requestId: string, choice: LifecycleDialogChoice) =>+ invoke<{ accepted: boolean }>(IPC.invoke.lifecycleDialogRespond, { requestId, choice }),+ onLifecycleDialogRequest: (listener: (request: LifecycleDialogRequest) => void) => {+ if (!window.piDesktop?.on) return () => undefined;+ return window.piDesktop.on(IPC.event.lifecycleDialogRequest, (payload) => {+ if (!payload || typeof payload !== "object") return;+ const value = payload as Record<string, unknown>;+ if (+ typeof value.requestId !== "string" ||+ !value.requestId ||+ (value.kind !== "quit-confirmation" && value.kind !== "close-behavior")+ ) return;+ listener({ requestId: value.requestId, kind: value.kind as LifecycleDialogKind });+ });+ },+ onLifecycleDialogDismiss: (listener: (requestId: string) => void) => {+ if (!window.piDesktop?.on) return () => undefined;+ return window.piDesktop.on(IPC.event.lifecycleDialogDismiss, (payload) => {+ if (!payload || typeof payload !== "object") return;+ const requestId = (payload as Record<string, unknown>).requestId;+ if (typeof requestId === "string" && requestId) listener(requestId);+ });+ },getTokenUsageHistory: (query?: { startDate?: number; endDate?: number; bucket?: "day" | "week" | "month" }) =>invoke<import("@pi-desktop/shared").TokenUsageHistoryResult>(IPC.invoke.statsGetTokenUsageHistory,diff --git a/apps/desktop/src/styles/overlays.css b/apps/desktop/src/styles/overlays.cssindex da53d9cf5..e1d1d5989 100644--- a/apps/desktop/src/styles/overlays.css+++ b/apps/desktop/src/styles/overlays.css@@ -842,3 +842,38 @@transform: translateY(0) scale(1);}}+.lifecycle-confirmation-overlay {+ z-index: 65;+}++.lifecycle-confirmation-dialog {+ width: min(100%, 420px);+}++.lifecycle-confirmation-heading {+ min-width: 0;+ overflow-wrap: anywhere;+}++.lifecycle-confirmation-heading h2 {+ margin: 0;+ color: var(--ds-text-primary);+ font-size: var(--text-lg);+ font-weight: var(--font-weight-strong);+ line-height: var(--leading-heading);+}++.lifecycle-confirmation-heading p {+ margin: 8px 0 0;+ color: var(--ds-text-secondary);+ font-size: var(--text-sm-plus);+ line-height: var(--leading-body);+}++.lifecycle-confirmation-actions {+ display: flex;+ flex-wrap: wrap;+ justify-content: flex-end;+ gap: 8px;+ margin-top: 20px;+}diff --git a/apps/desktop/test/close-behavior-tray.test.mjs b/apps/desktop/test/close-behavior-tray.test.mjsindex 95242fc31..c7308d658 100644--- a/apps/desktop/test/close-behavior-tray.test.mjs+++ b/apps/desktop/test/close-behavior-tray.test.mjs@@ -157,3 +157,15 @@ test("macOS tray keeps the native status item instead of mouse-enter tracking",);assert.equal((body.match(/on\("mouse-enter"/g) || []).length, 1);});++test("lifecycle dialog responses stay bound to the ready main renderer", async () => {+ const brokerSource = await readMainModule("bootstrap/lifecycle-dialog.ts");+ const windowIpcSource = await readMainModule("ipc/window-ipc.ts");+ assert.match(brokerSource, /LIFECYCLE_DIALOG_TIMEOUT_MS = 10_000/);+ assert.match(brokerSource, /request\.windowId !== senderWindowId/);+ assert.match(brokerSource, /request\.dismiss\(request\.requestId\)/);+ assert.match(+ windowIpcSource,+ /IPC\.invoke\.lifecycleDialogRespond[\s\S]*?registrar\.assertMainWindowSender\(event\)[\s\S]*?respondLifecycleDialog\(event\.sender\.id, value\.requestId/,+ );+});diff --git a/apps/desktop/test/lifecycle-close-behavior-runtime.test.mjs b/apps/desktop/test/lifecycle-close-behavior-runtime.test.mjsnew file mode 100644index 000000000..9821bf659--- /dev/null+++ b/apps/desktop/test/lifecycle-close-behavior-runtime.test.mjs@@ -0,0 +1,145 @@+import assert from "node:assert/strict";+import { after, test } from "node:test";+import { createRequire } from "node:module";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { pathToFileURL } from "node:url";+import { repositoryRoot } from "../../../scripts/e2e/boot.mjs";++const root = repositoryRoot();+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");+const temp = await mkdtemp(join(tmpdir(), "pi-lifecycle-close-runtime-"));+after(async () => rm(temp, { recursive: true, force: true }));+const electronStub = join(temp, "electron-stub.mjs");+await writeFile(electronStub, `+export const dialog = {+ async showMessageBox(...args) {+ const options = args.length > 1 ? args[1] : args[0];+ globalThis.__nativeDialogOptions.push(options);+ if (globalThis.__nativeDialogFailure) throw new Error("native dialog unavailable");+ return { response: globalThis.__nativeDialogResponses.shift() ?? 0 };+ },+};`);+const bundlePath = join(temp, "close-behavior.mjs");+await build({+ entryPoints: [join(root, "apps/desktop/electron/main/bootstrap/close-behavior.ts")],+ outfile: bundlePath,+ bundle: true,+ platform: "node",+ format: "esm",+ alias: {+ electron: electronStub,+ "@pi-desktop/i18n": join(root, "packages/i18n/src"),+ "@pi-desktop/shared": join(root, "packages/shared/src"),+ },+ nodePaths: [join(root, "apps/desktop/node_modules")],+});+const { createCloseBehaviorRuntime } = await import(pathToFileURL(bundlePath).href);++function fakeWindow({ visible = true, minimized = false } = {}) {+ const events = [];+ const listeners = new Map();+ const onceListeners = new Map();+ const contents = {+ id: 41,+ isDestroyed: () => false,+ send(channel, payload) { events.push({ channel, payload }); },+ on(event, listener) {+ const current = listeners.get(event) ?? [];+ current.push(listener);+ listeners.set(event, current);+ },+ once(event, listener) {+ const current = onceListeners.get(event) ?? [];+ current.push(listener);+ onceListeners.set(event, current);+ },+ emit(event, ...args) {+ for (const listener of listeners.get(event) ?? []) listener(...args);+ for (const listener of onceListeners.get(event) ?? []) listener(...args);+ onceListeners.delete(event);+ },+ };+ const window = {+ webContents: contents,+ restoreCount: 0,+ showCount: 0,+ focusCount: 0,+ isDestroyed: () => false,+ isMinimized: () => minimized,+ isVisible: () => visible,+ restore() { this.restoreCount += 1; minimized = false; visible = true; },+ show() { this.showCount += 1; visible = true; },+ focus() { this.focusCount += 1; },+ };+ return { window, events, emit: contents.emit };+}++function createRuntime(window, dataDir) {+ const logs = [];+ let trayCreations = 0;+ const runtime = createCloseBehaviorRuntime({+ state: { mainWindow: window, closeBehavior: "ask" },+ dataDir,+ getLocale: () => "en",+ createTray: () => { trayCreations += 1; },+ logger: { app: (...entry) => logs.push(entry) },+ });+ return { runtime, logs, trayCreations: () => trayCreations };+}++function lastEvent(events, channel) {+ return events.findLast((event) => event.channel === channel);+}++test("renderer choices drive close and quit while unavailable renderers use native fallback", async () => {+ globalThis.__nativeDialogOptions = [];+ globalThis.__nativeDialogResponses = [];+ globalThis.__nativeDialogFailure = false;+ const { window, events, emit } = fakeWindow({ visible: false, minimized: true });+ const { runtime, trayCreations } = createRuntime(window, join(temp, "profile"));+ assert.equal(runtime.markLifecycleDialogRendererReady(window), true);++ const quitCancelled = runtime.confirmQuitDialog();+ assert.equal(window.restoreCount, 1);+ assert.equal(window.focusCount, 1);+ const firstQuit = lastEvent(events, "pi-desktop/window/event/lifecycleDialogRequest");+ assert.equal(firstQuit.payload.kind, "quit-confirmation");+ assert.equal(runtime.respondLifecycleDialog(99, firstQuit.payload.requestId, "confirm"), false);+ assert.equal(runtime.respondLifecycleDialog(41, firstQuit.payload.requestId, "cancel"), true);+ assert.equal(await quitCancelled, false);++ const quitConfirmed = runtime.confirmQuitDialog();+ const secondQuit = lastEvent(events, "pi-desktop/window/event/lifecycleDialogRequest");+ assert.equal(runtime.respondLifecycleDialog(41, secondQuit.payload.requestId, "confirm"), true);+ assert.equal(await quitConfirmed, true);++ const closeChoice = runtime.askCloseBehavior(window);+ const closeRequest = lastEvent(events, "pi-desktop/window/event/lifecycleDialogRequest");+ assert.equal(closeRequest.payload.kind, "close-behavior");+ assert.equal(runtime.respondLifecycleDialog(41, closeRequest.payload.requestId, "tray"), true);+ assert.equal(await closeChoice, "tray");+ runtime.applyCloseBehavior("tray");+ assert.equal(runtime.readCloseBehavior(), "tray");+ assert.equal(trayCreations(), 1);++ globalThis.__nativeDialogResponses.push(2);+ const fallbackChoice = runtime.askCloseBehavior(window);+ const fallbackRequest = lastEvent(events, "pi-desktop/window/event/lifecycleDialogRequest");+ emit("render-process-gone");+ assert.equal(await fallbackChoice, "quit");+ assert.equal(+ lastEvent(events, "pi-desktop/window/event/lifecycleDialogDismiss").payload.requestId,+ fallbackRequest.payload.requestId,+ );+ const nativeAsk = globalThis.__nativeDialogOptions.at(-1);+ assert.equal(nativeAsk.title, "Keep PI-Desktop running in the background?");+ assert.equal(nativeAsk.message.startsWith("When you close the window"), true);++ globalThis.__nativeDialogResponses.push(0);+ assert.equal(await runtime.confirmQuitDialog(), false);+ const nativeQuit = globalThis.__nativeDialogOptions.at(-1);+ assert.equal(nativeQuit.title, "Quit PI-Desktop?");+ assert.notEqual(nativeQuit.message, nativeQuit.title);+});diff --git a/apps/desktop/test/lifecycle-confirmation-dialog-user-path.test.mjs b/apps/desktop/test/lifecycle-confirmation-dialog-user-path.test.mjsnew file mode 100644index 000000000..a1add14fd--- /dev/null+++ b/apps/desktop/test/lifecycle-confirmation-dialog-user-path.test.mjs@@ -0,0 +1,218 @@+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createRequire } from "node:module";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { repositoryRoot, resolveElectronBinary } from "../../../scripts/e2e/boot.mjs";++const root = repositoryRoot();+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");+const fixture = String.raw`+import React from "react";+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import i18n from "i18next";+import { initReactI18next } from "react-i18next";+import { catalogs, flattenCatalog } from "@pi-desktop/i18n";+import { LifecycleConfirmationDialog } from "../../apps/desktop/src/components/LifecycleConfirmationDialog";++await i18n.use(initReactI18next).init({ lng: "en", keySeparator: false,+ resources: { en: { translation: flattenCatalog(catalogs.en) } },+ interpolation: { escapeValue: false } });+const listeners = new Map();+const responses = [];+let readyCalls = 0;+window.piDesktop = {+ platform: "darwin",+ on(channel, listener) {+ const channelListeners = listeners.get(channel) ?? new Set();+ channelListeners.add(listener);+ listeners.set(channel, channelListeners);+ return () => channelListeners.delete(listener);+ },+ invoke(channel, payload) {+ if (channel.endsWith("/ready")) readyCalls += 1;+ if (channel.endsWith("/respond")) responses.push(payload);+ return Promise.resolve({ ok: true, data: channel.endsWith("/ready")+ ? { ready: true } : { accepted: true } });+ },+};+const rootNode = createRoot(document.getElementById("root"));+flushSync(() => rootNode.render(React.createElement(React.Fragment, null,+ React.createElement("button", { id: "prior-focus" }, "Previously focused"),+ React.createElement(LifecycleConfirmationDialog))));+const frame = () => new Promise(requestAnimationFrame);+async function settle() { await frame(); await frame(); }+function check(condition, message) { if (!condition) throw new Error(message); }+async function until(predicate, message) {+ for (let n = 0; n < 120; n += 1) {+ if (predicate()) return;+ await frame();+ }+ throw new Error(message + " body=" + document.body.textContent);+}+function emit(channel, payload) {+ for (const listener of listeners.get(channel) ?? []) listener(payload);+}+function request(kind, requestId) {+ emit("pi-desktop/window/event/lifecycleDialogRequest", { requestId, kind });+}+function dismiss(requestId) {+ emit("pi-desktop/window/event/lifecycleDialogDismiss", { requestId });+}+function activeButtonName() { return document.activeElement?.textContent?.trim(); }+function clickButton(name) {+ const button = [...document.querySelectorAll('[role="dialog"] button')]+ .find((item) => item.textContent.trim() === name);+ check(button, "button not found: " + name);+ flushSync(() => button.click());+}+window.lifecycleDialogProbe = async () => {+ const prior = document.getElementById("prior-focus");+ prior.focus();+ await settle();+ check(readyCalls === 1, "renderer did not acknowledge readiness");++ request("quit-confirmation", "quit-cancel");+ await until(() => document.querySelector('[role="dialog"]'), "quit confirmation did not render");+ await settle();+ let dialog = document.querySelector('[role="dialog"]');+ check(dialog.getAttribute("aria-modal") === "true", "dialog is not modal");+ check(dialog.getAttribute("aria-labelledby") && dialog.getAttribute("aria-describedby"), "dialog lacks accessible labels");+ check(document.querySelector("h2").textContent === "Quit PI-Desktop?", "quit title is incorrect");+ check(document.querySelector("h2").textContent !== document.querySelector("p").textContent, "title and body are duplicated");+ check(activeButtonName() === "Cancel", "Cancel is not the initial focus target");+ flushSync(() => window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true })));+ await until(() => !document.querySelector('[role="dialog"]'), "Escape did not cancel");+ check(responses.at(-1).choice === "cancel", "Escape did not resolve as cancel");+ check(document.activeElement === prior, "focus was not restored after cancellation");++ request("quit-confirmation", "quit-confirm");+ await until(() => document.querySelector('[role="dialog"]'), "quit confirmation did not reopen");+ await settle();+ flushSync(() => window.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", shiftKey: true, bubbles: true, cancelable: true })));+ check(activeButtonName() === "Quit", "Shift+Tab did not wrap to the final action");+ flushSync(() => window.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true })));+ check(activeButtonName() === "Cancel", "Tab did not wrap back to Cancel");+ clickButton("Quit");+ check(responses.at(-1).choice === "confirm", "quit action did not confirm");+ await until(() => !document.querySelector('[role="dialog"]'), "confirmed dialog stayed open");++ request("close-behavior", "close-dismiss");+ await until(() => document.querySelector('[role="dialog"]'), "timed-out dialog did not render");+ const responsesBeforeDismiss = responses.length;+ dismiss("close-dismiss");+ await until(() => !document.querySelector('[role="dialog"]'), "fallback dismissal left a stale overlay");+ check(responses.length === responsesBeforeDismiss, "main fallback dismissal was incorrectly treated as a user choice");++ request("close-behavior", "close-backdrop");+ await until(() => document.querySelector('[role="dialog"]'), "close behavior dialog did not render");+ await settle();+ dialog = document.querySelector('[role="dialog"]');+ check(document.querySelector("h2").textContent === "Keep PI-Desktop running in the background?", "close title is incorrect");+ check(dialog.querySelectorAll("button").length === 3, "close behavior does not offer all three choices");+ const overlay = document.querySelector(".lifecycle-confirmation-overlay");+ const pointer = (type) => new PointerEvent(type, {+ bubbles: true, cancelable: true, pointerId: 1, pointerType: "mouse", isPrimary: true, button: 0,+ });+ flushSync(() => {+ overlay.dispatchEvent(pointer("pointerdown"));+ overlay.dispatchEvent(pointer("pointerup"));+ overlay.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));+ });+ check(responses.at(-1).choice === "cancel", "backdrop click did not cancel");+ await until(() => !document.querySelector('[role="dialog"]'), "backdrop left dialog open");++ request("close-behavior", "close-tray");+ await until(() => document.querySelector('[role="dialog"]'), "close behavior dialog did not reopen");+ clickButton("Close to tray");+ check(responses.at(-1).choice === "tray", "close-to-tray choice was not returned");+ await until(() => !document.querySelector('[role="dialog"]'), "tray choice left dialog open");++ request("close-behavior", "close-quit");+ await until(() => document.querySelector('[role="dialog"]'), "close behavior dialog did not reopen for quit");+ clickButton("Quit PI-Desktop");+ check(responses.at(-1).choice === "quit", "first-close Quit choice was not returned");+ await settle();+ flushSync(() => rootNode.unmount());+ return { passed: true, responses };+};+`;++test("lifecycle dialogs support accessible keyboard, backdrop, and decision paths", {+ skip: process.platform === "linux" && !process.env.DISPLAY ? "Electron requires a display" : false,+}, async () => {+ const temp = await mkdtemp(join(tmpdir(), "pi-lifecycle-dialog-ui-"));+ try {+ await build({+ stdin: { contents: fixture, resolveDir: join(root, "scripts/e2e"), loader: "tsx" },+ outfile: join(temp, "renderer.js"),+ bundle: true,+ platform: "browser",+ format: "esm",+ jsx: "automatic",+ define: { "process.env.NODE_ENV": '"production"' },+ alias: {+ "@pi-desktop/i18n": join(root, "packages/i18n/src"),+ "@pi-desktop/shared": join(root, "packages/shared/src"),+ react: join(root, "apps/desktop/node_modules/react"),+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),+ i18next: join(root, "apps/desktop/node_modules/i18next"),+ "react-i18next": join(root, "apps/desktop/node_modules/react-i18next"),+ },+ nodePaths: [join(root, "apps/desktop/node_modules")],+ });+ await writeFile(join(temp, "index.html"),+ '<!doctype html><meta charset="utf-8"><div id="root"></div><script type="module" src="renderer.js"></script>');+ await writeFile(join(temp, "main.cjs"), `+const { app, BrowserWindow } = require("electron");+const path = require("node:path");+app.setPath("userData", path.join(__dirname, "profile"));+app.whenReady().then(async () => {+ const win = new BrowserWindow({ show: false, width: 720, height: 520,+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });+ try {+ await win.loadFile(path.join(__dirname, "index.html"));+ console.log("LIFECYCLE_DIALOG_PROBE " + JSON.stringify(await win.webContents.executeJavaScript("window.lifecycleDialogProbe()")));+ app.exit(0);+ } catch (error) { console.error(error?.stack ?? error); app.exit(1); }+});`);+ const env = { ...process.env };+ delete env.ELECTRON_RUN_AS_NODE;+ const child = spawn(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], {+ env,+ stdio: ["ignore", "pipe", "pipe"],+ });+ let output = "";+ for (const stream of [child.stdout, child.stderr]) {+ stream.setEncoding("utf8");+ stream.on("data", (chunk) => { output += chunk; });+ }+ const timer = setTimeout(() => child.kill("SIGKILL"), 45_000);+ let code;+ try {+ code = await new Promise((resolve, reject) => {+ child.once("error", reject);+ child.once("close", resolve);+ });+ } finally {+ clearTimeout(timer);+ }+ assert.equal(code, 0, output.slice(-6000));+ const line = output.split(/\r?\n/).find((item) => item.startsWith("LIFECYCLE_DIALOG_PROBE "));+ assert.ok(line, output.slice(-6000));+ const result = JSON.parse(line.slice("LIFECYCLE_DIALOG_PROBE ".length));+ assert.equal(result.passed, true);+ assert.deepEqual(result.responses.map(({ requestId, choice }) => ({ requestId, choice })), [+ { requestId: "quit-cancel", choice: "cancel" },+ { requestId: "quit-confirm", choice: "confirm" },+ { requestId: "close-backdrop", choice: "cancel" },+ { requestId: "close-tray", choice: "tray" },+ { requestId: "close-quit", choice: "quit" },+ ]);+ } finally {+ await rm(temp, { recursive: true, force: true });+ }+});diff --git a/apps/desktop/test/lifecycle-dialog-broker.test.mjs b/apps/desktop/test/lifecycle-dialog-broker.test.mjsnew file mode 100644index 000000000..3f7faec75--- /dev/null+++ b/apps/desktop/test/lifecycle-dialog-broker.test.mjs@@ -0,0 +1,121 @@+import assert from "node:assert/strict";+import { after, test } from "node:test";+import { createRequire } from "node:module";+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { pathToFileURL } from "node:url";+import { repositoryRoot } from "../../../scripts/e2e/boot.mjs";++const root = repositoryRoot();+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");+const temp = await mkdtemp(join(tmpdir(), "pi-lifecycle-dialog-broker-"));+after(async () => rm(temp, { recursive: true, force: true }));+const bundlePath = join(temp, "lifecycle-dialog.mjs");+await build({+ entryPoints: [join(root, "apps/desktop/electron/main/bootstrap/lifecycle-dialog.ts")],+ outfile: bundlePath,+ bundle: true,+ platform: "node",+ format: "esm",+});+const { createLifecycleDialogBroker } = await import(pathToFileURL(bundlePath).href);++function createBroker() {+ const scheduled = [];+ const cancelled = [];+ const errors = [];+ let sequence = 0;+ const broker = createLifecycleDialogBroker({+ createRequestId: () => `request-${++sequence}`,+ schedule(callback) {+ const timer = { callback };+ scheduled.push(timer);+ return timer;+ },+ cancelSchedule(timer) {+ cancelled.push(timer);+ },+ onError(error) {+ errors.push(error);+ },+ });+ return { broker, scheduled, cancelled, errors };+}++const options = (overrides = {}) => ({+ windowId: 17,+ kind: "quit-confirmation",+ send() {},+ dismiss() {},+ fallback: async () => "cancel",+ ...overrides,+});++test("uses native fallback until the main renderer has acknowledged readiness", async () => {+ const { broker } = createBroker();+ let sent = false;+ let fallbackCount = 0;+ let dismissCount = 0;+ const result = await broker.request(options({+ send() { sent = true; },+ dismiss() { dismissCount += 1; },+ fallback: async () => { fallbackCount += 1; return "cancel"; },+ }));+ assert.equal(result, "cancel");+ assert.equal(sent, false);+ assert.equal(fallbackCount, 1);+ assert.equal(dismissCount, 0);+});++test("accepts only a valid response from the requesting renderer", async () => {+ const { broker, scheduled, cancelled } = createBroker();+ broker.markReady(17);+ let emitted;+ const pending = broker.request(options({ send(request) { emitted = request; } }));+ assert.deepEqual(emitted, { requestId: "request-1", kind: "quit-confirmation" });+ assert.equal(broker.respond(99, emitted.requestId, "confirm"), false);+ assert.equal(broker.respond(17, emitted.requestId, "tray"), false);+ assert.equal(broker.respond(17, emitted.requestId, "cancel"), true);+ assert.equal(await pending, "cancel");+ assert.deepEqual(cancelled, [scheduled[0]]);+});++test("dismisses stale renderer UI and falls back on timeout or process loss", async () => {+ const timed = createBroker();+ timed.broker.markReady(17);+ let timeoutFallbacks = 0;+ let timedDismissed;+ const timeoutResult = timed.broker.request(options({+ dismiss(requestId) { timedDismissed = requestId; },+ fallback: async () => { timeoutFallbacks += 1; return "confirm"; },+ }));+ timed.scheduled[0].callback();+ assert.equal(await timeoutResult, "confirm");+ assert.equal(timeoutFallbacks, 1);+ assert.equal(timedDismissed, "request-1");+ assert.equal(timed.broker.respond(17, "request-1", "cancel"), false);++ const crashed = createBroker();+ crashed.broker.markReady(17);+ let crashFallbacks = 0;+ let crashDismissed;+ const crashResult = crashed.broker.request(options({+ kind: "close-behavior",+ dismiss(requestId) { crashDismissed = requestId; },+ fallback: async () => { crashFallbacks += 1; return "quit"; },+ }));+ crashed.broker.markUnavailable(17);+ assert.equal(await crashResult, "quit");+ assert.equal(crashFallbacks, 1);+ assert.equal(crashDismissed, "request-1");+});++test("fails open and records an unusable native fallback", async () => {+ const { broker, errors } = createBroker();+ const result = await broker.request(options({+ fallback: async () => { throw new Error("native dialog unavailable"); },+ }));+ assert.equal(result, "confirm");+ assert.equal(errors.length, 1);+});diff --git a/apps/desktop/test/rpc-lifecycle-contract.test.mjs b/apps/desktop/test/rpc-lifecycle-contract.test.mjsindex 8cb12dc4c..360f2363a 100644--- a/apps/desktop/test/rpc-lifecycle-contract.test.mjs+++ b/apps/desktop/test/rpc-lifecycle-contract.test.mjs@@ -219,7 +219,7 @@ test("app quit waits for one idempotent teardown before allowing the follow-up qassert.match(shutdownModuleSource, /shutdownPromise: Promise<void> \| null/);assert.match(shutdownSource, /if \(state\.shutdownComplete\) return/);assert.match(shutdownSource, /event\.preventDefault\(\)/);- assert.match(shutdownSource, /if \(state\.shutdownPromise\) return/);+ assert.match(shutdownSource, /if \(state\.shutdownPromise \|\| quitConfirmationPending\) return/);assert.ok(shutdownSource.indexOf('logger.app("lifecycle", "info", "app shutdown")') <shutdownSource.indexOf("await liveCallService?.endForLifecycle"),@@ -227,7 +227,7 @@ test("app quit waits for one idempotent teardown before allowing the follow-up q);assert.ok(shutdownSource.indexOf("event.preventDefault()") <- shutdownSource.indexOf("if (state.shutdownPromise) return"),+ shutdownSource.indexOf("if (state.shutdownPromise || quitConfirmationPending) return"),"the first quit must be prevented before the idempotence guard returns",);// Panel windows and docked views are the only pages that call the host and thediff --git a/apps/desktop/test/shutdown-regenerate-persistence.test.mjs b/apps/desktop/test/shutdown-regenerate-persistence.test.mjsindex e5556b64a..a0d630373 100644--- a/apps/desktop/test/shutdown-regenerate-persistence.test.mjs+++ b/apps/desktop/test/shutdown-regenerate-persistence.test.mjs@@ -136,3 +136,87 @@ test(`quit settles a regenerated branch when the host is ${outcome}`, async (t)assert.equal(hostDisposed, true);});}++test("a repeated before-quit cannot bypass the pending renderer confirmation", async (t) => {+ app.removeAllListeners();+ const originalQuit = app.quit;+ const probeKeys = [+ "PI_DESKTOP_BOOT_PROBE",+ "PI_DESKTOP_SUPERVISION_PROBE",+ "PI_DESKTOP_CAPTURE",+ ];+ const originalProbeValues = probeKeys.map((key) => process.env[key]);+ for (const key of probeKeys) delete process.env[key];+ const confirmations = [];+ let confirmationCount = 0;+ const state = {+ shutdownComplete: false,+ shutdownPromise: null,+ quitting: false,+ quitConfirmed: false,+ closeBehavior: "quit",+ tray: null,+ pluginLauncherAccelerator: null,+ toggleWindowAccelerator: null,+ };+ const dispose = () => undefined;+ app.quit = () => {+ app.emit("before-quit", { preventDefault() {} });+ };+ registerShutdownHandlers({+ hasSingleInstanceLock: true,+ state,+ getHost: () => null,+ getSidecar: () => null,+ getMcpControl: () => null,+ activeTurns: new Map(),+ persistenceOutbox: { flush: async () => {}, size: () => 0 },+ inflightCheckpointer: { flushAll: async () => {}, dispose },+ flushEventPersistence: async () => {},+ pluginPanels: { closeAll: async () => {} },+ plugins: { disposeAll: async () => {} },+ userMcp: { disposeAll: dispose },+ browserHost: { dispose },+ pluginViews: { dispose: async () => {} },+ updater: { dispose, isInstallingUpdate: () => false },+ logger: { app() {} },+ confirmQuitDialog: () => {+ confirmationCount += 1;+ return new Promise((resolve) => confirmations.push(resolve));+ },+ disposePowerSaveBlockers: dispose,+ });+ const requestQuit = () => {+ let prevented = false;+ app.emit("before-quit", { preventDefault() { prevented = true; } });+ return prevented;+ };+ t.after(() => {+ app.removeAllListeners();+ app.quit = originalQuit;+ for (let index = 0; index < probeKeys.length; index += 1) {+ const value = originalProbeValues[index];+ if (value === undefined) delete process.env[probeKeys[index]];+ else process.env[probeKeys[index]] = value;+ }+ });++ assert.equal(requestQuit(), true);+ assert.equal(confirmationCount, 1);+ assert.equal(requestQuit(), true);+ assert.equal(confirmationCount, 1);+ assert.equal(state.shutdownPromise, null);+ assert.equal(state.quitting, false);++ confirmations[0](false);+ await Promise.resolve();+ assert.equal(state.quitConfirmed, false);+ assert.equal(requestQuit(), true);+ assert.equal(confirmationCount, 2);++ confirmations[1](true);+ await Promise.resolve();+ assert.ok(state.shutdownPromise);+ await state.shutdownPromise;+ assert.equal(state.shutdownComplete, true);+});diff --git a/docs/adr/0090-user-configurable-close-behavior-close-to-tray.md b/docs/adr/0090-user-configurable-close-behavior-close-to-tray.mdindex 9de627778..309d9bbda 100644--- a/docs/adr/0090-user-configurable-close-behavior-close-to-tray.md+++ b/docs/adr/0090-user-configurable-close-behavior-close-to-tray.md@@ -31,10 +31,11 @@ matches the desired behavior.icon and keeps the app running; the tray menu restores the window orquits the app.- `quit`: legacy behavior — closing the window exits the app.-2. The first close with an unset preference shows a native modal dialog- (main process) with Cancel / Close to tray / Quit. Picking a non-cancel- option persists it forever; Cancel keeps the window open and leaves the- preference unset (so the next close prompts again).+2. The first close with an unset preference shows a themed in-app dialog+ (Cancel / Close to tray / Quit). Picking a non-cancel option persists it+ forever; Cancel keeps the window open and leaves the preference unset. If+ the renderer is not ready or becomes unavailable, Main uses a bounded native+ fallback; if that also fails, it allows Quit rather than trapping the close.3. The preference is stored by Electron main in`<data>/close-behavior.json` (same ownership pattern as`window-state.json`), NOT in host-core settings: it is app-shell@@ -70,14 +71,21 @@ matches the desired behavior.Windows force-terminates the session after its shutdown timeout, so nodata is lost, but shutdown is not accelerated by the app.+9. The first-close and explicit-quit dialogs render in the main renderer using+ the existing theme. Main owns each decision and accepts only a matching+ request ID from the main window after its readiness handshake. An unanswered+ request uses a native fallback after ten seconds; failure to show that+ fallback allows Quit to proceed. Tray Quit restores a hidden main window+ before presenting the confirmation. These additive Electron channels do not+ change host RPC, storage schema, or macOS close behavior.## Alternatives considered- **Store the preference in host-core settings (`AppSettings`):** rejectedbecause it would add a Rust schema field and host RPC surface for pureshell lifecycle state that only Electron main consumes.-- **Renderer-drawn first-close dialog:** rejected because the window is- closing; a native modal keeps the decision in the process that owns the- close lifecycle and works before the renderer has mounted.+- **Renderer dialog without readiness and fallback handling:** rejected+ because a missed request could block close. The adopted dialog waits for a+ ready renderer, correlates responses, and uses a bounded native fallback.- **Always close-to-tray without a choice:** rejected — it changes themeaning of the close button for users who expect exit.- **Tray icon reconciled with the preference:** rejected; D216 keeps onediff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex 4d4a72303..8467ed21f 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -2050,6 +2050,16 @@ macOS, where there is no close behavior to configure. Setting a behavior doesnot touch the tray icon: D216 (ADR 0078) creates one at startup on everyplatform, and minimize-to-tray needs it whichever close behavior is stored.+Lifecycle close/quit prompts use additive main-window-only Electron IPC. Main sends+`pi-desktop/window/event/lifecycleDialogRequest` with `{ requestId, kind }` after the+renderer acknowledges `pi-desktop/window/lifecycleDialog/ready`; the renderer returns+`{ requestId, choice }` through `pi-desktop/window/lifecycleDialog/respond`. If Main+falls back, it sends `pi-desktop/window/event/lifecycleDialogDismiss` with the+request ID so the renderer removes any stale overlay. Main validates the sender and+pending request ID. A missing/unresponsive renderer falls back to the native dialog+after a bounded timeout; if that fallback also fails, shutdown proceeds rather than+remaining blocked. Tray Quit restores a hidden main+window before showing its in-app confirmation. This does not change host RPC or storage.Maximize/unmaximize changes also emit`window/event/maximized`. Unknown actions fail. These window-control channelsremain Electron-only and do not change the host RPC protocol version.diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 3c6921c27..f1fa074ba 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -191,10 +191,12 @@ Outer frame that positions Topbar, Sidebar, MainChat, and WorkPanel. Owns resizefocused Windows taskbar button also uses native minimize; a second clickrestores/focuses the same window, while clicking a covered window brings itto the front. Tray activation restores and focuses tray-hidden windows; Quit- remains explicit and, except for automated probes, confirms with a native- warning before shutdown (D363). On macOS the tray uses a transparent monochrome template- of the PI mark rather than the rounded application tile, so it remains- readable in the menu bar.+ remains explicit and, except for automated probes, restores a tray-hidden main+ window before showing a themed confirmation with Cancel focused. Escape or a+ backdrop click cancels. If the main renderer is unavailable, a native warning+ is the bounded fallback before shutdown (D363). On macOS the tray uses a+ transparent monochrome template of the PI mark rather than the rounded+ application tile, so it remains readable in the menu bar.- Windows/Linux do not render File/Edit/View/Window/Help in the titlebar anddo not reserve left-side space for an application menubar. F10 andShift+F10 remain available to focused content.diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex b9926b327..0180a490c 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -143,21 +143,20 @@ recency only breaks ties between equally relevant matches.restores/focuses the same window, while clicking the entry for a merelycovered window keeps the normal bring-to-front behavior (D252 / ADR 0117).macOS native minimize remains tray-resident. Windows/Linux close behavior is user-configurable- (ADR 0090): an unset preference asks once via a native prompt (Cancel / Close- to tray / Quit); `tray` hides the window under that same tray icon, whose- click restores the window; `quit` exits the app. Close behavior never creates- or destroys the tray — D216 owns it, so the icon is resident under either- choice. The choice is persisted, revisitable in Settings → General, and- applied by both the close button and the close shortcut. Explicit quit- (Cmd+Q, application-menu Quit, tray Quit) is a separate confirm step- (D363): Cancel leaves the app running; Confirm runs the ordered shutdown.- A D230 window-close Quit does not ask again. Automated boot, supervision,- and capture probes skip the dialog, as does the restart that installs an- already-downloaded update — its installer is already running and gives up- when the app stays alive. macOS keeps the- native Dock lifecycle (close keeps the app in the Dock; activating recreates- the window). The bounds watchdog never restores a minimized or tray-hidden- window.+ (ADR 0090): an unset preference asks once via a themed in-app dialog (Cancel / Close to tray / Quit).+ If the renderer is unavailable, the native dialog remains the bounded fallback. Escape and a+ backdrop click cancel; Cancel is initially focused and leaves the preference unset. `tray` hides+ the window under that same tray icon, whose click restores the window; `quit` exits the app.+ Close behavior never creates or destroys the tray — D216 owns it, so the icon is resident under+ either choice. The choice is persisted, revisitable in Settings → General, and applied by both+ the close button and the close shortcut. Explicit quit (Cmd+Q, application-menu Quit, tray Quit)+ is a separate themed confirmation step (D363): a tray-hidden main window is restored first;+ Escape, backdrop click, or Cancel leaves the app running, while Confirm runs the ordered shutdown.+ A D230 window-close Quit does not ask again. Automated boot, supervision, and capture probes skip+ the dialog, as does the restart that installs an already-downloaded update — its installer is+ already running and gives up when the app stays alive. macOS keeps the native Dock lifecycle+ (close keeps the app in the Dock; activating recreates the window). The bounds watchdog never+ restores a minimized or tray-hidden window.### 1.5.1 Tray-resident and taskbar minimizediff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 89654cfdd..31c474820 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -5598,10 +5598,10 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.`close-behavior.json`); the main window is visible; Settings → General isreachable. macOS is excluded: it keeps the native Dock lifecycle.- **Steps**: 1) With the preference unset, click the close button (or press- the close-window shortcut) and answer the prompt: Cancel keeps the window- open and the preference unset; Close to tray hides the window, shows the- tray icon, and the app keeps running (a turn in flight stays live); Quit- exits the app. 2) Re-run each choice and verify it is remembered across a+ the close-window shortcut) and verify the themed in-app dialog opens with Cancel focused. Escape, a+ backdrop click, or Cancel keeps the window open and preference unset; Close to+ tray hides the window, shows the tray icon, and leaves a live turn running;+ Quit exits the app. Renderer-unavailable behavior uses the native fallback. 2) Re-run each choice and verify it is remembered across afull restart and that no second prompt ever appears once a choice exists.3) With `tray` set, click the tray icon: the windowrestores, shows, and focuses; the tray context menu offers Open and Quit,@@ -5617,8 +5617,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.covered separately by E2E-124. 7) Invoke unknown values and `"ask"` on`pi-desktop/window/closeBehavior/set` and verify they fail closed, andverify the channel is rejected outright on macOS.-- **Expected**: The first close prompts exactly once per unset state and- Cancel never persists a choice. Tray mode keeps the app alive with a+- **Expected**: The first close renders the themed dialog exactly once per unset state. Escape, backdrop click, or Cancel never persists a choice; if the renderer is unavailable, a bounded native fallback is used, and failure to show it does not trap close. Tray mode keeps the app alive with alocalized tooltip/menu and no data loss; switching to Quit app leaves thetray icon in place, because close-to-tray and macOS minimize still need arestore surface. The preference survives restarts and is honored by both@@ -5634,38 +5633,50 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.ADR 0123- **Acceptance**: A (app startup), Quality- **Milestone**: M5 on Windows/Linux (release qualification)-- **Status**: Draft+- **Status**: Themed renderer path, broker fallback, and Main close/quit choices+ are covered by `lifecycle-confirmation-dialog-user-path.test.mjs`,+ `lifecycle-dialog-broker.test.mjs`, and `lifecycle-close-behavior-runtime.test.mjs`;+ the full persisted close-behavior journey remains Draft.#### E2E-204: Explicit quit confirms before shutdown (D363)- **Preconditions**: A normal interactive session is running (not a boot,supervision, or capture probe). The main window may be visible or tray-hidden.- **Steps**: 1) Choose Quit from the tray menu, or press Cmd+Q / the- application-menu Quit item. 2) Cancel the native warning and confirm the- window, tray, host-core, and sidecar remain. 3) Repeat and confirm Quit;- confirm the ordered shutdown runs. 4) On Windows/Linux with close behavior- unset, close the window and choose Quit on the D230 dialog; confirm no- second warning. 5) Launch with `PI_DESKTOP_BOOT_PROBE=1` (and the- supervision/capture equivalents) and confirm `app.quit()` exits without a- dialog. 6) On a packaged Windows NSIS or Linux AppImage install, download an- update and choose Restart to update; confirm the quit warning never appears- and the installer finishes the upgrade and relaunch.-- **Expected**: Accidental explicit quit is cancellable. A user who already- chose Quit on the close-behavior dialog is not asked again. Probes used by- automation never block on the warning. An in-app update restart is never- deferred behind the warning either: the platform installer is spawned before- `app.quit()` and aborts once the app outlives its wait window, so the- update-triggered quit must run the ordered shutdown immediately — the user- already committed to the restart by choosing that action.+ application-menu Quit item. If tray-hidden, confirm the main window is restored.+ 2) Verify the themed in-app confirmation, Cancel as initial focus, and distinct+ title/body. While it is open, issue a second Quit request and verify the same+ decision remains pending: no duplicate dialog and no shutdown bypass. Exercise+ Escape and a backdrop click; confirm the window, tray, host-core, and sidecar+ remain. 3) Repeat and Confirm; verify ordered shutdown. 4) On Windows/Linux+ with close behavior unset, close the window. Verify the themed D230 dialog+ offers Cancel / Close to tray / Quit: cancel leaves the preference unset, and+ choosing Quit causes no second dialog. 5) Launch with `PI_DESKTOP_BOOT_PROBE=1`+ (and supervision/capture equivalents) and confirm `app.quit()` exits without a+ dialog. 6) On packaged Windows NSIS or Linux AppImage, restart to install an+ update; confirm no quit warning appears and the installer completes upgrade+ and relaunch.+- **Expected**: Accidental explicit quit is cancellable. Repeated quit requests+ cannot duplicate or bypass an outstanding confirmation; Cancel clears the+ pending decision so a later quit asks again. Tray Quit presents the dialog+ even when the main window was hidden. A D230 Quit is not re-confirmed. When the+ renderer is unavailable, crashes, or fails to answer, the bounded native+ fallback is used; failure to show it does not hold shutdown. Probes never+ block on the warning. An in-app update restart is never deferred: the installer+ is spawned before `app.quit()` and aborts if the app stays alive past its wait+ window, so that quit goes directly into ordered shutdown.- **Specs linked**: `04-ux/08-component-spec.md`,`04-ux/09-interaction-patterns.md`, `08-meta/decisions-log.md` (D216, D230,- D363), ADR 0022+ D363), ADR 0022, ADR 0090- **Acceptance**: A (app startup), Quality- **Milestone**: M5-- **Status**: Unit-covered (`close-behavior-tray.test.mjs` asserts the- probe and update-restart exemptions; `auto-update.test.mjs` asserts the- install latch is set before `quitAndInstall`); native dialog journey Draft- (run only in a capable environment when this surface changes)+- **Status**: Broker, renderer user path, Main close/quit runtime, and pending+ shutdown lifecycle covered (`lifecycle-dialog-broker.test.mjs`,+ `lifecycle-confirmation-dialog-user-path.test.mjs`,+ `lifecycle-close-behavior-runtime.test.mjs`, `close-behavior-tray.test.mjs`,+ `shutdown-regenerate-persistence.test.mjs`). Full application shutdown and+ packaged update journey remains Draft; run in a capable release environment+ when lifecycle wiring changes.#### E2E-067A: Prerelease install discovers newer stable release (D120)diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 0f4a3bdd2..e4ee12866 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -412,8 +412,8 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.| D343 | Custom global UI type scale | **Settings → General → Appearance gains a Font size row under Font. Starbucks-style cup presets (Tall / Grande / Venti / Trenta) plus a percentage slider persist as optional `AppSettings.fontScale` (`1` = product ramp, absent = 1, range 0.8–1.5 in 0.025 steps). The renderer sets `--font-scale` on the root; every `--text-*` token and `--leading-row` is `calc(<product px> * var(--font-scale))`, and shared Lucide wrappers size glyphs with the same multiplier, so body, chrome, headings, code, and icons stay in proportion without a reload. The UI never asks for a px value. Window Zoom In/Out/Reset stays independent. An unreleased leftover `fontSize` px field migrates as `px / 14` when `fontScale` is absent. No host protocol or storage schema version bump.** | The `--text-*` ramp is a frozen set of relative sizes; a single multiplier scales every step at once. Window zoom still scales layout. A reading-only px field would leave two type sizes in one window and force the user to pick a number that only matches `--text-base` (ADR 0180). || D232 | Custom global UI font | *(amended by D598)* **Settings → Basics → Appearance gains a searchable Font picker (trigger previews the current family). Selections persist as `AppSettings.fontFamily`, a CSS stack; absent means the built-in `--font-sans` token stack, and the renderer applies the stack by overriding `--font-sans` on the root element without a reload. Four bundled families — Geist, Inter, Noto Sans SC, LXGW WenKai — ship locally as woff2 under the SIL OFL 1.1 with license texts; every custom stack appends a CJK fallback tier and the mono stack is unchanged. Installed system families are enumerated by Electron main using platform tooling only (macOS: `osascript` JXA bridging the CoreText query `CTFontManagerCopyAvailableFontFamilyNames` — the same API dbx's `font_kit::all_families()` calls — with `system_profiler` as a slow fallback; Windows: PowerShell; Linux: `fc-list`), deduplicated/sorted/filtered and cached 60 s, exposed through the additive allowlisted channel `pi-desktop/app/systemFonts`; host protocol v9 and storage schema v10 are unchanged.** | Users want a Codex/dbx-style global font preference, but the sandboxed renderer cannot enumerate OS fonts and the host RPC should stay unchanged for a renderer-only preference. Bundling OFL-licensed families keeps every offered font commercially safe and offline, while the fast CoreText path returns the canonical CSS family names (e.g. PingFang SC) in tens of milliseconds and the 60 s cache bounds repeated enumeration (ADR 0083). || D598 | The app ships no fonts | **Amend D232 / ADR 0083: every bundled family is removed. `apps/desktop/src/assets/fonts/` (the four `woff2` files and their OFL license texts), `apps/desktop/src/styles/fonts.css`, and the `@import "./fonts.css";` line in `styles/globals.css` are deleted, and `BUNDLED_FONTS`, the `BundledFont` type, `FontOption.license`, the picker's license badge, and `settings.fontBundled` in all eight locale catalogs go with them. The picker keeps System default (persisted as the empty string) followed by installed system families, enumerated exactly as before through the allowlisted `pi-desktop/app/systemFonts` channel, and a stored stack that matches no option still appears first under Saved (`custom`). Every generated stack now appends the system-only CJK tier `"PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif` with no bundled family in front of it. A previously stored bundled stack (e.g. `"Geist", "PingFang SC", …`) is preserved byte for byte, shows under Saved, and renders through that tier. No protocol version, schema version, or storage migration change.** | Four OFL faces duplicated coverage every target OS already provides, cost about 15.7 MiB of `woff2` in `out/renderer` (7.6 MiB LXGW WenKai plus 7.4 MiB Noto Sans SC), and carried font-file notice obligations for four options beside the list the OS already installs. See ADR 0298, E2E-126, and E2E-092. |-| D230 | User-configurable close behavior with close-to-tray | **Windows/Linux close behavior is a persisted preference stored by Electron main in `<data>/close-behavior.json`. `ask` is the transient unset state: the first close shows a native modal (Cancel / Close to tray / Quit); picking one persists it forever, Cancel keeps the window open and unset. Only `tray` and `quit` are ever settable — Settings -> General renders a two-option radio segment (Close to tray / Quit app) for Windows/Linux only, and `pi-desktop/window/closeBehavior/set` rejects `ask`, so a choice can be switched but never reverted to prompting. `tray` hides the window under the resident D216 tray icon (click restores, menu shows or quits); switching to `quit` leaves that icon in place, because minimize-to-tray still needs it. Close interception runs for every non-macOS close that is not already an approved quit; `quitting` and macOS closes fall through, a `quit` close calls `app.quit()` itself, and `window-all-closed` stays silent only under `tray`, so the boot probe and explicit quits are unaffected and a resident tray never keeps a `quit` session alive. `closeBehavior/set` also fails with `INVALID_ARGUMENT` on macOS. The bounds watchdog skips minimized and hidden windows so a tray-hidden window is never force-restored. macOS keeps the native Dock lifecycle (D216, ADR 0078, ADR 0090).** | Minimizing already hides the window into the D216 tray; the gap was close: it quit outright on Windows/Linux. A fixed close-to-tray would surprise users who expect exit, so the choice is asked once, remembered, and revisitable in Settings — matching how Codex-style shells keep long-running sessions alive without taking over the close button. |-| D363 | Explicit quit confirms before shutdown | **Amend D230 / D216: Cmd+Q, the application-menu Quit item, and the tray Quit item show one native warning (Cancel / Quit). Cancel leaves the app running and allows a later quit to prompt again. Confirm runs the ordered `before-quit` shutdown. A window-close path that already chose Quit in the D230 dialog sets `quitConfirmed` and does not ask again. Boot, supervision, and capture probes skip the dialog, and so does the quit an in-app update performs: `autoUpdater.quitAndInstall()` spawns the platform installer before `app.quit()`, and that installer aborts once the app outlives its wait window, so the update restart must reach the ordered shutdown without a prompt. No IPC, storage, or host-protocol change. See E2E-204.** | An explicit quit tears down host-core, the sidecar, and in-flight work; a one-step confirm prevents an accidental Cmd+Q or tray Quit from doing that, without re-prompting a user who already chose Quit on the close-behavior dialog. |+| D230 | User-configurable close behavior with close-to-tray | **Windows/Linux close behavior is a persisted preference stored by Electron main in `<data>/close-behavior.json`. `ask` is the transient unset state: the first close shows a themed in-app modal (Cancel / Close to tray / Quit), with a native fallback when the renderer is unavailable; picking one persists it forever, Cancel keeps the window open and unset. Only `tray` and `quit` are ever settable — Settings -> General renders a two-option radio segment (Close to tray / Quit app) for Windows/Linux only, and `pi-desktop/window/closeBehavior/set` rejects `ask`, so a choice can be switched but never reverted to prompting. `tray` hides the window under the resident D216 tray icon (click restores, menu shows or quits); switching to `quit` leaves that icon in place, because minimize-to-tray still needs it. Close interception runs for every non-macOS close that is not already an approved quit; `quitting` and macOS closes fall through, a `quit` close calls `app.quit()` itself, and `window-all-closed` stays silent only under `tray`, so the boot probe and explicit quits are unaffected and a resident tray never keeps a `quit` session alive. `closeBehavior/set` also fails with `INVALID_ARGUMENT` on macOS. The bounds watchdog skips minimized and hidden windows so a tray-hidden window is never force-restored. macOS keeps the native Dock lifecycle (D216, ADR 0078, ADR 0090).** | Minimizing already hides the window into the D216 tray; the gap was close: it quit outright on Windows/Linux. A fixed close-to-tray would surprise users who expect exit, so the choice is asked once, remembered, and revisitable in Settings — matching how Codex-style shells keep long-running sessions alive without taking over the close button. |+| D363 | Explicit quit confirms before shutdown | **Amend D230 / D216: Cmd+Q, the application-menu Quit item, and the tray Quit item show one themed in-app confirmation (Cancel / Quit), restoring a tray-hidden main window first and using a native fallback when the renderer is unavailable. Cancel leaves the app running and allows a later quit to prompt again. Confirm runs the ordered `before-quit` shutdown. A window-close path that already chose Quit in the D230 dialog sets `quitConfirmed` and does not ask again. Boot, supervision, and capture probes skip the dialog, and so does the quit an in-app update performs: `autoUpdater.quitAndInstall()` spawns the platform installer before `app.quit()`, and that installer aborts once the app outlives its wait window, so the update restart must reach the ordered shutdown without a prompt. Additive lifecycle-dialog IPC only; no storage or host-protocol change. See E2E-204.** | An explicit quit tears down host-core, the sidecar, and in-flight work; a one-step confirm prevents an accidental Cmd+Q or tray Quit from doing that, without re-prompting a user who already chose Quit on the close-behavior dialog. || D252 | Windows taskbar preserves native minimize/restore | *(Explicit renderer/menu minimize clauses superseded by D256 / ADR 0123)* **Amend D216 / ADR 0078: when the focused Windows main window is toggled from its taskbar button, Electron lets the native `minimize` transition complete instead of hiding the window. The taskbar entry remains available and the next taskbar click restores/focuses it. Explicit renderer/menu minimize actions still hide to the resident tray; macOS/Linux native minimize remains tray-resident. No IPC, storage, host protocol, or background-work changes.** | D216's unconditional `window.hide()` handled the taskbar-originated Windows `minimize` event as a tray hide, unexpectedly removing the taskbar entry and leaving the user with only the tray restore path. || D236 | One desktop instance per data directory | **Electron main takes `app.requestSingleInstanceLock()` during module evaluation — after `app.setName`, because the lock lives under the name-derived `userData` path, and before the logger, the persistence outbox, or any other data-directory access. A launch that does not take the lock calls `app.quit()` and boots nothing: the readiness and `before-quit` handlers both return early, so it creates no window, tray, child process, or log line inside the running instance's data directory. The lock holder answers `second-instance` by restoring and focusing its main window through the same path as the tray's Show action, which recreates a window that was closed or hidden into the tray. The lock is requested only when `PI_DESKTOP_DATA_DIR` is unset, so E2E harnesses, the capture rig, and deliberate side-by-side profiles keep the current start-anytime behavior. No IPC channel, host protocol, or storage schema changes.** | A second launch booted a complete second app: another host-core over the single-writer `pi.sqlite` (D002), another outbox and log tree in the same directory, another tray, launcher-chord registration, and updater, leaving two shells divergent over one database. Relaunching the app is a request to see the one already running, and scoping the lock to the installation keeps isolated-data-directory runs launchable (ADR 0094). || D367 | Host-owned plugin session import and ownership API | **`pi.session` gains `import`, `importBatch`, `list`, `get`, `listMessages`, `rename`, and `delete`; `contributes.sessionSources` is required for every source; host-core generates ids and scopes every operation to `(pluginId, source, externalId)` ownership; imports never activate project/provider/model bindings. Schema v14 adds `session_import_origins` and `sessions.deleted_at`; protocol v11 is unchanged. Trash keeps the transcript for owner-only purge.** | External-history plugins need durable import/read/update/delete, and the in-flight `session.getLlmContext` and core `session.import` boundaries are not safe plugin ownership boundaries (ADR 0200, E2E-214 / E2E-215) |diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.mdindex d5701d788..79a7716a2 100644--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md@@ -1526,6 +1526,14 @@ window/closeBehavior/set({ behavior: "tray" | "quit" })在每个平台上启动时都会创建一个,而无论存的是哪种关闭行为,最小化到托盘都需要它。+关闭行为与退出确认通过新增的、仅限主窗口的 Electron IPC 在应用内呈现。主进程+在 renderer 确认 `pi-desktop/window/lifecycleDialog/ready` 后发送+`pi-desktop/window/event/lifecycleDialogRequest`(`{ requestId, kind }`);renderer+通过 `pi-desktop/window/lifecycleDialog/respond` 返回 `{ requestId, choice }`。主进程+回退时会通过 `pi-desktop/window/event/lifecycleDialogDismiss` 发送 request ID,令 renderer+移除残留遮罩。主进程校验发送方和待处理的 request ID。renderer 缺失或无响应时,超时后+回退到原生弹窗;原生弹窗也失败时允许关机继续,不会卡住。托盘退出会先恢复隐藏的主窗口再显示应用内+确认框。此改动不影响 host RPC 或存储协议。Maximize/unmaximize 变化也会发出`window/event/maximized`。未知的操作失败。这些仅限电子的通道不要跨入 host-core,也不要更改主机 RPC 协议版本。diff --git a/docs/zh-CN/spec/04-ux/09-interaction-patterns.md b/docs/zh-CN/spec/04-ux/09-interaction-patterns.mdindex f6bf83370..f3c8bdbe4 100644--- a/docs/zh-CN/spec/04-ux/09-interaction-patterns.md+++ b/docs/zh-CN/spec/04-ux/09-interaction-patterns.md@@ -120,13 +120,15 @@窗口事件,因此恢复可供性永远不仅仅取决于乐观渲染器状态。- 最小化在每个平台上都把窗口隐藏进常驻托盘(D216,§1.5.1)。- Windows/Linux 的关闭行为由用户配置(ADR 0090):尚未设置的偏好通过原生- 提示只问一次(取消 / 关闭到托盘 / 退出);`tray` 把窗口隐藏到同一个托盘- 图标之下,点击它即可恢复窗口;`quit` 退出应用。关闭行为从不创建或销毁- 托盘 —— 图标归 D216 所有,两种选择下都常驻。这个选择会被持久化、可在- 设置 → 通用中回访,并且关闭按钮和关闭快捷键都遵循它。macOS 保持原生- Dock 生命周期(关闭后应用留在 Dock 中,激活时重建窗口)。边界看门狗- 永远不会恢复一个最小化或隐藏到托盘的窗口。+ Windows/Linux 的关闭行为由用户配置(ADR 0090):尚未设置的偏好在首次关闭时显示主题化应用内对话框+ (取消 / 关闭到托盘 / 退出);渲染进程不可用时限时回退到原生对话框。初始焦点为“取消”,按 Escape+ 或点击遮罩也会取消;取消后偏好仍未设置。`tray` 把窗口隐藏到同一个托盘图标之下,点击它即可恢复;+ `quit` 退出应用。关闭行为从不创建或销毁托盘 —— 图标归 D216 所有,两种选择下都常驻。这个选择会被+ 持久化、可在设置 → 通用中回访,并且关闭按钮和关闭快捷键都遵循它。显式退出(Cmd+Q、应用菜单退出、+ 托盘退出)是单独的主题化确认步骤(D363):窗口藏于托盘时先恢复主窗口;Escape、点击遮罩或取消会让+ 应用继续运行,确认才执行有序关机。已在 D230 选择退出的关窗路径不会再次询问。boot、supervision、+ capture 探针和应用内更新重启仍跳过该对话框。macOS 保持原生 Dock 生命周期(关闭后应用留在 Dock 中,+ 激活时重建窗口)。边界看门狗永远不会恢复一个最小化或隐藏到托盘的窗口。### 1.5.1 托盘驻留与任务栏最小化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 09968e7ad..0318d97b8 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@@ -3060,8 +3060,7 @@ PI-Desktop 图标;两个表面都不会暴露库存 Electron 名称或图标主窗口可见;可以进入设置 → 通用。macOS 不在范围内:它保持原生 Dock生命周期。- **步骤**:1)在偏好未设置时点击关闭按钮(或按关闭窗口快捷键)并回答提示:- 取消保持窗口打开且偏好仍未设置;关闭到托盘隐藏窗口、显示托盘图标,应用- 继续运行(进行中的一轮保持存活);退出则退出应用。2)逐个重跑每种选择,+ 确认显示主题化应用内对话框且初始焦点为“取消”;按 Escape、点击遮罩或取消都会保持窗口打开且偏好仍未设置;关闭到托盘隐藏窗口、显示托盘图标,应用继续运行(进行中的一轮保持存活);退出则退出应用。renderer 不可用时回退到原生对话框。2)逐个重跑每种选择,验证它在完整重启后仍被记住,并且一旦存在选择就再也不会出现第二次提示。3)在设为 `tray` 时点击托盘图标:窗口恢复、显示并获得焦点;托盘右键菜单提供打开和退出,退出会退出应用。4)在设置 → 通用中在关闭到托盘 / 退出应用@@ -3071,7 +3070,7 @@ PI-Desktop 图标;两个表面都不会暴露库存 Electron 名称或图标窗口隐藏进托盘(D216),并且点击托盘可以把它带回来。7)向`pi-desktop/window/closeBehavior/set` 传入未知值和 `"ask"`,验证它们失败关闭,并验证该通道在 macOS 上直接被拒绝。-- **预期**:每个未设置状态下首次关闭恰好提示一次,取消永远不会持久化选择。+- **预期**:每个未设置状态下首次关闭恰好显示一次主题化弹窗;Escape、点击遮罩或取消都不会持久化选择。renderer 不可用时限时回退到原生弹窗,原生弹窗也失败时不会卡住关闭。托盘模式让应用带着本地化的提示与菜单继续存活且不丢数据;切换到退出应用不会移除托盘图标,因为最小化到托盘仍然把它当作回到隐藏窗口的唯一途径。偏好在重启后仍然有效,窗口控制的关闭按钮和关闭快捷键都遵循它,存有@@ -3084,7 +3083,9 @@ PI-Desktop 图标;两个表面都不会暴露库存 Electron 名称或图标D230)、ADR 0078、ADR 0090- **验收**:A(应用程序启动)、质量- **里程碑**:Windows/Linux 上的 M5(发布资格)-- **状态**:草稿+- **状态**:`lifecycle-confirmation-dialog-user-path.test.mjs`、`lifecycle-dialog-broker.test.mjs`+ 与 `lifecycle-close-behavior-runtime.test.mjs` 覆盖主题化弹窗、兜底和主进程关闭/退出选择;+ 完整持久化关闭偏好旅程仍为草稿。#### E2E-067A:预发行安装发现更新的稳定版本 (D120)@@ -7777,12 +7778,12 @@ eleven-tool-round desktop paths are verified by#### E2E-204:显式退出在关机前确认(D363)- **前提条件**:普通交互会话正在运行(不是 boot / supervision / capture 探针)。主窗口可见或已藏到托盘。-- **步骤**:1) 从托盘菜单选择退出,或按 Cmd+Q / 应用菜单退出。2) 取消原生警告,确认窗口、托盘、host-core 和 sidecar 仍在。3) 再操作一次并确认退出,确认走有序关机。4) Windows/Linux 在关闭行为未设置时关窗,并在 D230 对话框选择退出;确认没有第二次警告。5) 以 `PI_DESKTOP_BOOT_PROBE=1`(及 supervision/capture 等价项)启动,确认 `app.quit()` 不弹对话框。6) 在打包的 Windows NSIS 或 Linux AppImage 安装上,下载更新并选择“重启以更新”;确认退出警告不再出现,安装器完成升级并重新拉起应用。-- **预期**:误触显式退出可以取消。已经在关闭行为对话框选择退出的用户不会再被问一次。自动化探针不会被警告挡住。应用内更新重启同样不会被警告推迟:平台安装器先于 `app.quit()` 启动,应用一旦超出其等待窗口安装器就会中止,因此更新触发的退出必须立即走有序关机 —— 用户选择该操作时已经确认了重启。见 ADR 0022。-- **链接规格**:`04-ux/08-component-spec.md`、`04-ux/09-interaction-patterns.md`、`08-meta/decisions-log.md`(D216、D230、D363)、ADR 0022+- **步骤**:1) 从托盘菜单选择退出,或按 Cmd+Q / 应用菜单退出;若窗口藏在托盘,确认主窗口先恢复。2) 确认显示主题化应用内弹窗、标题与正文分开且初始焦点为“取消”;弹窗打开时再次触发退出,确认仍只等待同一个决定,既不重复弹窗也不绕过确认。分别按 Escape、点击遮罩取消,确认窗口、托盘、host-core 和 sidecar 仍在。3) 再次操作并确认退出,验证有序关机。4) Windows/Linux 在关闭行为未设置时关窗,确认 D230 主题弹窗提供取消 / 关闭到托盘 / 退出;取消保持未设置,选择退出不会二次询问。5) 以 `PI_DESKTOP_BOOT_PROBE=1`(及 supervision/capture 等价项)启动,确认 `app.quit()` 不弹窗。6) 在打包的 Windows NSIS 或 Linux AppImage 安装上选择“重启以更新”,确认退出警告不出现且安装器完成升级和重启。+- **预期**:显式退出可取消;待确认期间的重复退出不会重复弹窗或绕过确认,取消后后续退出会再次询问。托盘退出即使窗口隐藏也能呈现弹窗。已在 D230 选择退出的关窗路径不会再次确认。renderer 不可用、崩溃或超时无响应时限时回退到原生弹窗;原生弹窗也不可用时不得阻塞退出。自动化探针和应用内更新重启均跳过警告,后者直接进入有序关机。+- **链接规格**:`04-ux/08-component-spec.md`、`04-ux/09-interaction-patterns.md`、`08-meta/decisions-log.md`(D216、D230、D363)、ADR 0022、ADR 0090- **验收**:A、质量- **里程碑**:M5-- **状态**:单元已覆盖(`close-behavior-tray.test.mjs` 断言探针与更新重启两项豁免,`auto-update.test.mjs` 断言安装闩锁先于 `quitAndInstall` 设置);原生对话框旅程为草稿+- **状态**:`lifecycle-dialog-broker.test.mjs`、`lifecycle-confirmation-dialog-user-path.test.mjs`、`lifecycle-close-behavior-runtime.test.mjs`、`close-behavior-tray.test.mjs` 和 `shutdown-regenerate-persistence.test.mjs` 覆盖 broker、renderer 用户旅程、主进程选择及待处理退出;完整应用关机和打包更新旅程仍为草稿,生命周期集成变更时需在可用发布环境运行。#### E2E-209:从本地智能体存储导入模型配置diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.mdindex 6f5dd088c..dc6872fca 100644--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@ -412,8 +412,8 @@| D343 | 自定义全局文字缩放 | **设置 → 常规 → 外观在字体行下增加字体大小。星巴克式杯型档位(中杯 / 大杯 / 超大杯 / 超超大杯)加上百分比滑杆,持久化为可选 `AppSettings.fontScale`(`1` = 产品字号阶,缺失 = 1,范围 0.8–1.5、步进 0.025)。渲染器在根元素设置 `--font-scale`;每个 `--text-*` 令牌和 `--leading-row` 都是 `calc(<产品 px> * var(--font-scale))`,共享 Lucide 图标使用同一倍率,正文、chrome、标题、代码和图标无需重载即保持相对阶。界面不出现 px 输入。窗口放大/缩小/重置仍独立。未发布的遗留 `fontSize` px 字段在没有 `fontScale` 时按 `px / 14` 迁移。无协议/存储版本升级。** | `--text-*` 阶本身就是一组相对尺寸;一个倍率可以一次缩放所有台阶。窗口缩放仍会缩放布局。只改阅读区的 px 会让同一窗口出现两套字号,还强迫用户填一个只对应 `--text-base` 的数字(ADR 0180)。 || D232 | 自定义全局界面字体 | *(由 D598 修订)* **设置 → 基础 → 外观新增可搜索的字体选择器(触发器以当前字体的字样预览)。选择结果持久化为 `AppSettings.fontFamily`(CSS 字体栈);缺失时保持内置 `--font-sans` 令牌栈,渲染器通过覆盖根元素的 `--font-sans` 应用字体栈,无需重载。四款内置字体——Geist、Inter、Noto Sans SC、LXGW WenKai——以 woff2 格式按 SIL OFL 1.1 本地发布并附许可证文本;每个自定义字体栈都追加 CJK 回退层,等宽字体栈保持不变。系统已安装字体由 Electron 主进程仅使用平台工具枚举(macOS 用 `system_profiler`、Windows 用 PowerShell、Linux 用 `fc-list`),去重/排序/过滤并缓存 60 秒,通过新增的允许通道 `pi-desktop/app/systemFonts` 暴露;主机协议 v9 与存储架构 v10 不变。** | 用户需要 Codex/dbx 风格的全局字体偏好,但沙盒化渲染器无法枚举系统字体,而针对仅渲染器偏好不应扩大主机 RPC 面。内置 OFL 许可字体保证每个可选字体均商用安全且可离线使用,60 秒缓存限制了 macOS 枚举的耗时(ADR 0083)。 || D598 | 应用不再随包发布任何字体 | **修订 D232 / ADR 0083:所有内置字体全部移除。`apps/desktop/src/assets/fonts/`(四个 `woff2` 文件及其 OFL 许可证文本)、`apps/desktop/src/styles/fonts.css` 以及 `styles/globals.css` 中的 `@import "./fonts.css";` 均已删除,`BUNDLED_FONTS`、`BundledFont` 类型、`FontOption.license`、选择器上的许可证角标,以及全部八份语言目录中的 `settings.fontBundled` 一并移除。选择器保留「跟随系统」(持久化为空字符串)与系统已安装字体两类选项,枚举机制完全不变,仍通过白名单通道 `pi-desktop/app/systemFonts` 获取;已保存的字体栈若不再匹配任何选项,仍在「已保存」(`custom`)分组中排在首位。每个生成的字体栈现在追加纯系统 CJK 回退层 `"PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif`,前面不再有内置字体。此前保存的指向内置字体的字体栈(例如 `"Geist", "PingFang SC", …`)按原样保留,显示在「已保存」分组,并穿过该回退层渲染。协议版本、schema 版本与存储迁移均不变。** | 四款 OFL 字体重复提供每个目标操作系统本就具备的字形覆盖,占用 `out/renderer` 约 15.7 MiB 的 `woff2`(LXGW WenKai 7.6 MiB、Noto Sans SC 7.4 MiB),并为操作系统已安装列表之外的四个选项承担字体文件许可证告知义务。见 ADR 0298、E2E-126 与 E2E-092。 |-| D230 | 用户可配置的关闭行为与关闭到托盘 | **Windows/Linux 的关闭行为是由 Electron 主进程存放在 `<data>/close-behavior.json` 的持久化偏好。`ask` 是尚未设置的过渡态:首次关闭弹出原生模态框(取消 / 关闭到托盘 / 退出),选定其一即永久保存,取消则保持窗口打开且偏好仍未设置。可设置的只有 `tray` 和 `quit` —— 设置 → 通用仅在 Windows/Linux 渲染两项单选段(关闭到托盘 / 退出应用),`pi-desktop/window/closeBehavior/set` 拒绝 `ask`,因此选择可以切换但无法退回到每次询问。`tray` 把窗口隐藏到 D216 常驻的托盘图标之下(点击恢复,菜单显示或退出);切换到 `quit` 不会销毁该图标,因为最小化到托盘仍然需要它。除了已经获准的退出之外,每一次非 macOS 的关闭都会被拦截;`quitting` 与 macOS 的关闭直接放行,`quit` 分支自己调用 `app.quit()`,而 `window-all-closed` 只在 `tray` 下保持沉默,因此启动探针与显式退出不受影响,常驻托盘也不会让 `quit` 会话继续活着。在 macOS 上 `closeBehavior/set` 同样以 `INVALID_ARGUMENT` 失败。边界看门狗跳过最小化和隐藏的窗口,所以隐藏到托盘的窗口不会被强制恢复。macOS 保持原生 Dock 生命周期(D216、ADR 0078、ADR 0090)。** | 最小化本来就把窗口收进 D216 的托盘;缺口在关闭:它在 Windows/Linux 上直接退出。固定的关闭到托盘会让期待退出的用户意外,所以这个选择只问一次、记住、并可在设置里回访 —— 与 Codex 风格外壳让长时会话继续存活但不接管关闭按钮的做法一致。 |-| D363 | 显式退出在关机前确认 | **修订 D230 / D216:Cmd+Q、应用菜单退出和托盘退出显示一次原生警告(取消 / 退出)。取消让应用继续运行,之后的退出会再次询问。确认走有序 `before-quit` 关机。已在 D230 对话框选择退出的关窗路径设置 `quitConfirmed`,不再问第二次。boot、supervision 和 capture 探针跳过对话框,应用内更新所执行的退出同样跳过:`autoUpdater.quitAndInstall()` 会先于 `app.quit()` 启动平台安装器,而该安装器一旦发现应用超出等待窗口就会中止,因此更新重启必须不经询问直接进入有序关机。见 E2E-204。** | 显式退出会拆掉 host-core、sidecar 和进行中的工作;一步确认避免误触 Cmd+Q 或托盘退出。 |+| D230 | 用户可配置的关闭行为与关闭到托盘 | **Windows/Linux 的关闭行为是由 Electron 主进程存放在 `<data>/close-behavior.json` 的持久化偏好。`ask` 是尚未设置的过渡态:首次关闭弹出主题化应用内对话框(取消 / 关闭到托盘 / 退出);渲染进程不可用时回退到原生对话框,选定其一即永久保存,取消则保持窗口打开且偏好仍未设置。可设置的只有 `tray` 和 `quit` —— 设置 → 通用仅在 Windows/Linux 渲染两项单选段(关闭到托盘 / 退出应用),`pi-desktop/window/closeBehavior/set` 拒绝 `ask`,因此选择可以切换但无法退回到每次询问。`tray` 把窗口隐藏到 D216 常驻的托盘图标之下(点击恢复,菜单显示或退出);切换到 `quit` 不会销毁该图标,因为最小化到托盘仍然需要它。除了已经获准的退出之外,每一次非 macOS 的关闭都会被拦截;`quitting` 与 macOS 的关闭直接放行,`quit` 分支自己调用 `app.quit()`,而 `window-all-closed` 只在 `tray` 下保持沉默,因此启动探针与显式退出不受影响,常驻托盘也不会让 `quit` 会话继续活着。在 macOS 上 `closeBehavior/set` 同样以 `INVALID_ARGUMENT` 失败。边界看门狗跳过最小化和隐藏的窗口,所以隐藏到托盘的窗口不会被强制恢复。macOS 保持原生 Dock 生命周期(D216、ADR 0078、ADR 0090)。** | 最小化本来就把窗口收进 D216 的托盘;缺口在关闭:它在 Windows/Linux 上直接退出。固定的关闭到托盘会让期待退出的用户意外,所以这个选择只问一次、记住、并可在设置里回访 —— 与 Codex 风格外壳让长时会话继续存活但不接管关闭按钮的做法一致。 |+| D363 | 显式退出在关机前确认 | **修订 D230 / D216:Cmd+Q、应用菜单退出和托盘退出显示一次主题化应用内确认框(取消 / 退出);主窗口藏于托盘时先恢复窗口,渲染进程不可用时回退到原生弹窗。取消让应用继续运行,之后的退出会再次询问。确认走有序 `before-quit` 关机。已在 D230 对话框选择退出的关窗路径设置 `quitConfirmed`,不再问第二次。boot、supervision 和 capture 探针跳过对话框,应用内更新所执行的退出同样跳过:`autoUpdater.quitAndInstall()` 会先于 `app.quit()` 启动平台安装器,而该安装器一旦发现应用超出等待窗口就会中止,因此更新重启必须不经询问直接进入有序关机。见 E2E-204。** | 显式退出会拆掉 host-core、sidecar 和进行中的工作;一步确认避免误触 Cmd+Q 或托盘退出。 || D252 | Windows 任务栏保留原生最小化/恢复 | *(显式的渲染器/菜单最小化条款被 D256 / ADR 0123 取代)* **修订 D216 / ADR 0078:当聚焦的 Windows 主窗口从它的任务栏按钮被切换时,Electron 让原生 `minimize` 过渡走完,而不是隐藏窗口。任务栏条目保持可用,下一次点击任务栏会恢复并聚焦它。显式的渲染器/菜单最小化操作仍然隐藏到常驻托盘;macOS/Linux 的原生最小化仍然驻留托盘。不改动 IPC、存储、主机协议或后台工作。** | D216 无条件的 `window.hide()` 把任务栏发起的 Windows `minimize` 事件当成托盘隐藏处理,意外移除了任务栏条目,只给用户留下托盘恢复这一条路。 || D236 | 每个数据目录只允许一个桌面实例 | **Electron 主进程在模块求值期间调用 `app.requestSingleInstanceLock()` —— 在 `app.setName` 之后(锁位于由应用名派生的 `userData` 路径下),且在 logger、持久化 outbox 或任何其他数据目录访问之前。没有拿到锁的启动直接调用 `app.quit()` 且不引导任何东西:readiness 与 `before-quit` 处理器都提前返回,因此它不会在运行中实例的数据目录内创建窗口、托盘、子进程或日志行。持有锁的实例通过与托盘“显示”操作相同的路径响应 `second-instance`,恢复并聚焦主窗口,若窗口已关闭或隐藏到托盘则重新创建。只有在未设置 `PI_DESKTOP_DATA_DIR` 时才请求该锁,因此 E2E 测试装置、截图装置和有意并行的 profile 保持原有的随时启动行为。IPC 通道、宿主协议和存储架构均未变化。** | 第二次启动会引导出一个完整的第二份应用:在单写者 `pi.sqlite`(D002)上再开一个 host-core,在同一目录下再建一份 outbox 和日志树,再加一个托盘、一次启动器快捷键注册和一个更新器,导致两个 shell 在同一个数据库上出现分歧。再次启动应用是想看到已经在运行的那一个,把锁的作用域限定在安装本身也让使用独立数据目录的运行仍可启动(ADR 0094)。 || D367 | 宿主拥有的插件会话导入与归属 API | **`pi.session` 增加 `import`、`importBatch`、`list`、`get`、`listMessages`、`rename`、`delete`;每个来源必须声明 `contributes.sessionSources`;host-core 生成 id,并把所有操作限定在 `(pluginId, source, externalId)` 归属内;导入永不激活项目/provider/模型绑定。Schema v14 增加 `session_import_origins` 与 `sessions.deleted_at`;协议 v11 不变。回收站保留转录,仅属主可清除。** | 外部历史插件需要持久的导入/读取/更新/删除,而进行中的 `session.getLlmContext` 与核心 `session.import` 边界不是安全的插件归属边界(ADR 0200,E2E-214 / E2E-215) |diff --git a/packages/shared/src/protocol.test.ts b/packages/shared/src/protocol.test.tsindex 7d0d746d7..6c6a0cb2b 100644--- a/packages/shared/src/protocol.test.ts+++ b/packages/shared/src/protocol.test.ts@@ -52,6 +52,18 @@ describe("Plan protocol contracts", () => {expect(IPC_WHITELIST.has(IPC.invoke.providersRefreshModelCatalog)).toBe(true);expect(IPC_WHITELIST.has(IPC.invoke.windowSetWorkPanelChatWidth)).toBe(true);expect(IPC_WHITELIST.has(IPC.event.windowWorkPanelResize)).toBe(true);+ expect(IPC.invoke.lifecycleDialogReady).toBe("pi-desktop/window/lifecycleDialog/ready");+ expect(IPC.invoke.lifecycleDialogRespond).toBe("pi-desktop/window/lifecycleDialog/respond");+ expect(IPC.event.lifecycleDialogRequest).toBe("pi-desktop/window/event/lifecycleDialogRequest");+ expect(IPC.event.lifecycleDialogDismiss).toBe("pi-desktop/window/event/lifecycleDialogDismiss");+ for (const channel of [+ IPC.invoke.lifecycleDialogReady,+ IPC.invoke.lifecycleDialogRespond,+ IPC.event.lifecycleDialogRequest,+ IPC.event.lifecycleDialogDismiss,+ ]) {+ expect(IPC_WHITELIST.has(channel)).toBe(true);+ }expect(IPC.invoke.appOpenFeedback).toBe("pi-desktop/app/openFeedback");expect(IPC_WHITELIST.has(IPC.invoke.appOpenFeedback)).toBe(true);expect(IPC.invoke.fsOpen).toBe("pi-desktop/fs/open");diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex 050bdff74..d5845b678 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -48,6 +48,13 @@ export const WINDOW_CONTROL_ACTIONS = [export type WindowControlAction = (typeof WINDOW_CONTROL_ACTIONS)[number];+export type LifecycleDialogKind = "quit-confirmation" | "close-behavior";+export type LifecycleDialogChoice = "cancel" | "confirm" | "tray" | "quit";+export type LifecycleDialogRequest = {+ requestId: string;+ kind: LifecycleDialogKind;+};+export type LifecycleDialogDismiss = { requestId: string };export const IPC = {invoke: {storageGet: "pi-desktop/storage/get",@@ -409,6 +416,8 @@ export const IPC = {windowControl: "pi-desktop/window/control",closeBehaviorGet: "pi-desktop/window/closeBehavior/get",closeBehaviorSet: "pi-desktop/window/closeBehavior/set",+ lifecycleDialogReady: "pi-desktop/window/lifecycleDialog/ready",+ lifecycleDialogRespond: "pi-desktop/window/lifecycleDialog/respond",menuRendererReady: "pi-desktop/menu/rendererReady",traySetSessionPreferences: "pi-desktop/tray/setSessionPreferences",nativeMenuAction: "pi-desktop/menu/nativeAction",@@ -443,6 +452,8 @@ export const IPC = {windowMaximized: "pi-desktop/window/event/maximized",windowFullScreen: "pi-desktop/window/event/fullscreen",windowWorkPanelResize: "pi-desktop/window/event/workPanelResize",+ lifecycleDialogRequest: "pi-desktop/window/event/lifecycleDialogRequest",+ lifecycleDialogDismiss: "pi-desktop/window/event/lifecycleDialogDismiss",menuCommand: "pi-desktop/menu/event/command",traySessionActivated: "pi-desktop/tray/event/sessionActivated",notificationChanged: "pi-desktop/notification/event/changed",