Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(renderer): preserve chat state and recover from crashes
vastsa9eaab83acdcb
diff --git a/apps/desktop/electron/main/bootstrap/window.ts b/apps/desktop/electron/main/bootstrap/window.tsindex 8db7ff8cb..6ff288512 100644--- a/apps/desktop/electron/main/bootstrap/window.ts+++ b/apps/desktop/electron/main/bootstrap/window.ts@@ -35,6 +35,7 @@ import {} from "../work-panel-window";import { readWindowState, writeWindowState } from "../window-preferences";import { suppressLinuxFramelessSystemMenu } from "../frameless-system-menu";+import { recoverRendererAfterGone } from "../renderer-recovery";function windowsIconPath(): string | undefined {if (process.platform !== "win32") return undefined;@@ -468,12 +469,36 @@ export async function createWindow({void safeOpenExternal(url).catch(() => undefined);return { action: "deny" };});+ let windowCloseAccepted = false;window.webContents.on("did-start-loading", () => {windowState.notificationViewingSessionId = null;if (windowState.mainWindow === window) resetMenuRendererReady(window);});- window.webContents.on("render-process-gone", () => {+ window.webContents.on("render-process-gone", (_event, details) => {windowState.notificationViewingSessionId = null;+ recoverRendererAfterGone(details, {+ isCurrentWindow: windowState.mainWindow === window,+ quitting: windowState.quitting,+ windowCloseAccepted,+ windowDestroyed: window.isDestroyed(),+ webContentsDestroyed: window.webContents.isDestroyed(),+ reload: () => window.webContents.reload(),+ log: (rendererDetails, reloaded) => {+ logger.app(+ "diagnostics",+ rendererDetails.reason === "clean-exit" ? "info" : "warn",+ "renderer process exited",+ {+ event: "rendererProcessGone",+ data: {+ reason: rendererDetails.reason,+ exitCode: rendererDetails.exitCode,+ reloaded,+ },+ },+ );+ },+ });});// Devtools shortcut, gated on developer mode. Frameless windows get no@@ -886,6 +911,7 @@ export async function createWindow({windowState.quitting ||windowsAllowedToClose.has(window)) {+ windowCloseAccepted = true;return;}event.preventDefault();diff --git a/apps/desktop/electron/main/renderer-recovery.ts b/apps/desktop/electron/main/renderer-recovery.tsnew file mode 100644index 000000000..e48bfe7d7--- /dev/null+++ b/apps/desktop/electron/main/renderer-recovery.ts@@ -0,0 +1,34 @@+export type RendererGoneDetails = Readonly<{+ reason: string;+ exitCode: number;+}>;++export type RendererRecoveryDependencies = Readonly<{+ isCurrentWindow: boolean;+ quitting: boolean;+ windowCloseAccepted: boolean;+ windowDestroyed: boolean;+ webContentsDestroyed: boolean;+ reload: () => void;+ log: (details: RendererGoneDetails, reloaded: boolean) => void;+}>;++/** Reload an unexpectedly exited renderer while its owning app window is live. */+export function recoverRendererAfterGone(+ details: RendererGoneDetails,+ dependencies: RendererRecoveryDependencies,+): boolean {+ const reloaded =+ details.reason !== "clean-exit" &&+ dependencies.isCurrentWindow &&+ !dependencies.quitting &&+ !dependencies.windowCloseAccepted &&+ !dependencies.windowDestroyed &&+ !dependencies.webContentsDestroyed;++ dependencies.log(details, reloaded);+ if (!reloaded) return false;++ dependencies.reload();+ return true;+}diff --git a/apps/desktop/src/components/ChatSurface.tsx b/apps/desktop/src/components/ChatSurface.tsxindex 92ef4476a..3832bda04 100644--- a/apps/desktop/src/components/ChatSurface.tsx+++ b/apps/desktop/src/components/ChatSurface.tsx@@ -44,7 +44,11 @@ function projectName(path?: string | null, name?: string | null) {* per-session drafts already, and remounting it on every switch discarded its* measured metrics and focus.*/-export const ChatSurface = memo(function ChatSurface() {+export const ChatSurface = memo(function ChatSurface({+ visible = true,+}: {+ visible?: boolean;+}) {const { t } = useTranslation();const activeSessionId = useAppStore((state) => state.activeSessionId);const selectingSessionId = useAppStore((state) => state.selectingSessionId);@@ -194,7 +198,7 @@ export const ChatSurface = memo(function ChatSurface() {<SessionPanekey={id}sessionId={id}- visible={id === visibleSessionId}+ visible={visible && id === visibleSessionId}/>))}</div>diff --git a/apps/desktop/src/components/ContextMenu.tsx b/apps/desktop/src/components/ContextMenu.tsxindex 85f546c0f..037322d55 100644--- a/apps/desktop/src/components/ContextMenu.tsx+++ b/apps/desktop/src/components/ContextMenu.tsx@@ -27,7 +27,7 @@ import {type MouseEvent as ReactMouseEvent,type ReactNode,} from "react";-import { createPortal } from "react-dom";+import { portalToBody } from "../lib/portal-visibility";import {placeContextMenu,type ContextMenuPlacement,@@ -324,7 +324,7 @@ export function ContextMenu({if (!state || typeof document === "undefined") return null;- return createPortal(+ return portalToBody(<divref={menuRef}className={`context-menu${placement ? " is-open" : ""}`}@@ -369,6 +369,5 @@ export function ContextMenu({</Fragment>))}</div>,- document.body,);}diff --git a/apps/desktop/src/components/ContextUsageInspector.tsx b/apps/desktop/src/components/ContextUsageInspector.tsxindex d1e36bb23..0c63f1bb8 100644--- a/apps/desktop/src/components/ContextUsageInspector.tsx+++ b/apps/desktop/src/components/ContextUsageInspector.tsx@@ -6,7 +6,7 @@ import {useRef,useState,} from "react";-import { createPortal } from "react-dom";+import { portalToBody } from "../lib/portal-visibility";import { useTranslation } from "react-i18next";import {formatCompactTokenCount,@@ -404,7 +404,7 @@ export function ContextUsageInspector({</span></TooltipButton>{popover && typeof document !== "undefined"- ? createPortal(popover, document.body)+ ? portalToBody(popover): null}</div>);diff --git a/apps/desktop/src/components/NotificationCenter.tsx b/apps/desktop/src/components/NotificationCenter.tsxindex ccdf184d9..b5c4f10f4 100644--- a/apps/desktop/src/components/NotificationCenter.tsx+++ b/apps/desktop/src/components/NotificationCenter.tsx@@ -7,7 +7,7 @@ import {useState,type KeyboardEvent as ReactKeyboardEvent,} from "react";-import { createPortal } from "react-dom";+import { portalToBody } from "../lib/portal-visibility";import type { AppNotification } from "@pi-desktop/shared";import { useTranslation } from "react-i18next";import { useAppStore } from "../stores/app-store";@@ -254,7 +254,7 @@ export function NotificationCenter({</span>{open && popoverPos && typeof document !== "undefined"- ? createPortal(+ ? portalToBody(<divref={popoverRef}id="notification-popover"@@ -387,7 +387,6 @@ export function NotificationCenter({</div>)}</div>,- document.body,): null}</div>diff --git a/apps/desktop/src/components/ProjectDeleteDialog.tsx b/apps/desktop/src/components/ProjectDeleteDialog.tsxindex 545ff13c1..8d61b7493 100644--- a/apps/desktop/src/components/ProjectDeleteDialog.tsx+++ b/apps/desktop/src/components/ProjectDeleteDialog.tsx@@ -1,5 +1,5 @@import { useEffect, useRef, useState } from "react";-import { createPortal } from "react-dom";+import { portalToBody } from "../lib/portal-visibility";import { useTranslation } from "react-i18next";import { ErrorCodes } from "@pi-desktop/shared";import { useAppStore } from "../stores/app-store";@@ -183,5 +183,5 @@ export function ProjectDeleteDialog({</div>);- return typeof document === "undefined" ? dialog : createPortal(dialog, document.body);+ return typeof document === "undefined" ? dialog : portalToBody(dialog);}diff --git a/apps/desktop/src/components/ProjectEditDialog.tsx b/apps/desktop/src/components/ProjectEditDialog.tsxindex 58a57288b..2014d6b25 100644--- a/apps/desktop/src/components/ProjectEditDialog.tsx+++ b/apps/desktop/src/components/ProjectEditDialog.tsx@@ -1,5 +1,5 @@import { useEffect, useEffectEvent, useRef, useState } from "react";-import { createPortal } from "react-dom";+import { portalToBody } from "../lib/portal-visibility";import { useTranslation } from "react-i18next";import type { ProjectGroupRecord, ProjectGroupRoot } from "@pi-desktop/shared";import { api } from "../lib/api";@@ -366,5 +366,5 @@ export function ProjectEditDialog({</div>);- return typeof document === "undefined" ? dialog : createPortal(dialog, document.body);+ return typeof document === "undefined" ? dialog : portalToBody(dialog);}diff --git a/apps/desktop/src/components/SessionRenameDialog.tsx b/apps/desktop/src/components/SessionRenameDialog.tsxindex a5094c5b7..5e4de76d3 100644--- a/apps/desktop/src/components/SessionRenameDialog.tsx+++ b/apps/desktop/src/components/SessionRenameDialog.tsx@@ -1,5 +1,5 @@import { useEffect, useRef, useState, type FormEvent } from "react";-import { createPortal } from "react-dom";+import { portalToBody } from "../lib/portal-visibility";import { useTranslation } from "react-i18next";import { MAX_SESSION_TITLE_LENGTH } from "@pi-desktop/shared";import type { SessionSummary } from "@pi-desktop/shared";@@ -179,7 +179,7 @@ function RenameDialog({return typeof document === "undefined"? dialog- : createPortal(dialog, document.body);+ : portalToBody(dialog);}export function SessionRenameDialog({diff --git a/apps/desktop/src/components/Sidebar.tsx b/apps/desktop/src/components/Sidebar.tsxindex 26542f295..7b3a8801c 100644--- a/apps/desktop/src/components/Sidebar.tsx+++ b/apps/desktop/src/components/Sidebar.tsx@@ -15,7 +15,7 @@ import { TooltipButton, cx } from "./ui";/** Default number of most-recent sessions shown per project group before the rest fold. */const MAX_VISIBLE_SESSIONS = 10;-import { createPortal } from "react-dom";+import { portalToBody } from "../lib/portal-visibility";import { useTranslation } from "react-i18next";import { api } from "../lib/api";import { SessionHoverCard } from "../features/sessions/SessionHoverCard";@@ -1849,7 +1849,7 @@ export function Sidebar({? t("nav.newTemporarySession"): t("nav.newProject");const Icon = isSessions ? IconNewSession : IconNewProject;- return createPortal(+ return portalToBody(<divclassName="sidebar-row-menu sidebar-floating-menu sidebar-section-menu"role="menu"@@ -1875,11 +1875,10 @@ export function Sidebar({<span>{label}</span></button></div>,- document.body,);}if (sortOpen) {- return createPortal(+ return portalToBody(<divclassName="sidebar-popover sidebar-sort-menu sidebar-floating-menu"role="menu"@@ -1904,7 +1903,6 @@ export function Sidebar({<span className={`sidebar-checkbox ${showArchived ? "checked" : ""}`}>{showArchived ? "✓" : ""}</span></button></div>,- document.body,);}const session = sessionMenu@@ -1914,7 +1912,7 @@ export function Sidebar({? projectEntries.find((item) => item.key === projectMenu): undefined;if (!session && !entry) return null;- return createPortal(+ return portalToBody(<divclassName="sidebar-row-menu sidebar-floating-menu"role="menu"@@ -2092,7 +2090,6 @@ export function Sidebar({</>) : null}</div>,- document.body,);};diff --git a/apps/desktop/src/components/ui.tsx b/apps/desktop/src/components/ui.tsxindex 84ebeb06a..463beb910 100644--- a/apps/desktop/src/components/ui.tsx+++ b/apps/desktop/src/components/ui.tsx@@ -11,6 +11,10 @@ import {type SelectHTMLAttributes,type TextareaHTMLAttributes,} from "react";+import {+ portalToBody,+ visiblePortalContent,+} from "../lib/portal-visibility";import { IconEye, IconEyeOff, IconHelp } from "./icons";@@ -31,7 +35,9 @@ function overlayRoot(): HTMLElement {/** Mount a modal overlay on a viewport-fixed host so a transformed ancestor cannot trap `position: fixed`. */export function portalOverlay(node: ReactNode) {- return typeof document === "undefined" ? node : createPortal(node, overlayRoot());+ return typeof document === "undefined"+ ? node+ : createPortal(visiblePortalContent(node), overlayRoot());}function setRef<T>(ref: Ref<T> | undefined, value: T | null) {@@ -338,7 +344,7 @@ function PortalTooltip({});}, [className, label, position.left, position.top]);- return createPortal(+ return portalToBody(<spanref={tooltipRef}className={cx("ui-tooltip", className)}@@ -351,7 +357,6 @@ function PortalTooltip({>{label}</span>,- document.body,);}diff --git a/apps/desktop/src/features/app/AppShell.tsx b/apps/desktop/src/features/app/AppShell.tsxindex 20f203454..496243b93 100644--- a/apps/desktop/src/features/app/AppShell.tsx+++ b/apps/desktop/src/features/app/AppShell.tsx@@ -10,14 +10,15 @@ import {import { ProjectCreateDialog } from "../../components/ProjectCreateDialog";import { SearchDialog } from "../../components/SearchDialog";import { Sidebar } from "../../components/Sidebar";+import { StartupRecovery } from "../../components/StartupRecovery";import { ToastHost } from "../../components/Toast";import { UpdateBanner } from "../../components/UpdateBanner";import { cx, TooltipButton } from "../../components/ui";-import { StartupRecovery } from "../../components/StartupRecovery";import { WindowControls } from "../../components/WindowControls";import { WorkPanel } from "../../components/workpanel/WorkPanel";import { useCopyTex } from "../../hooks/use-copy-tex";import { api } from "../../lib/api";+import { PortalVisibilityProvider } from "../../lib/portal-visibility";import { CollapsedTitlebarActions, RoutePending } from "./chrome";import { useAppShellRuntime } from "./useAppShellRuntime";@@ -106,212 +107,212 @@ export function AppShell() {let shell: ReactNode = null;if (ready) {- if (page === "settings") {- shell = (- <>- <Suspense fallback={<RoutePending />}>- <SettingsPage />- </Suspense>- <SearchDialog open={searchOpen} onClose={() => setSearchOpen(false)} />- <ToastHost />- <ExtensionPromptHost />- <UpdateBanner />- </>- );- } else {- shell = (- <>- {!sidebarCollapsed || sidebarExiting ? (- <Sidebar- className={cx(sidebarEntering && "is-entering", sidebarExiting && "is-exiting")}- onAnimationEnd={handleSidebarAnimationEnd}- onToggleSidebar={toggleSidebar}- sidebarToggleShortcut={sidebarToggleShortcut}- sidebarWidth={sidebarWidth}- widthMax={sidebarWidthMax}- onWidthChange={handleSidebarWidthChange}- onWidthCommit={handleSidebarWidthCommit}- onResizeCollapse={handleSidebarResizeCollapse}- />- ) : null}-- {workPanelMaximized && (- /* MainChat is absent; the panel header owns dragging while this- pass-through row keeps the shell controls available. */- <div- className={cx(- "window-chrome-row",- !sidebarCollapsed && "sidebar-expanded",- )}- >- {sidebarCollapsed && (- <CollapsedTitlebarActions- onToggleSidebar={toggleSidebar}- onNewTask={() => void runMenuCommand("newTask")}- sidebarToggleShortcut={sidebarToggleShortcut}- />- )}- {!sidebarCollapsed && (- <TooltipButton- type="button"- className="title-nav-btn"- tooltip={t("nav.newTask")}- ariaLabel={t("nav.newTask")}- data-nav="new-task"- onClick={() => void runMenuCommand("newTask")}- >- <IconNewSession size={15} />- </TooltipButton>- )}- <div className="window-chrome-drag" aria-hidden />- </div>- )}-- {!workPanelMaximized && (- <section className="main-pane">- {page === "chat" ? (- <ConversationTopbar- sidebarCollapsed={sidebarCollapsed}- workPanelOpen={presentedWorkPanelOpen}+ shell = (+ <>+ <PortalVisibilityProvider visible={page !== "settings"}>+ <div+ className="app-chat-shell"+ hidden={page === "settings"}+ inert={page === "settings" ? true : undefined}+ aria-hidden={page === "settings" ? true : undefined}+ >+ {!sidebarCollapsed || sidebarExiting ? (+ <Sidebar+ className={cx(sidebarEntering && "is-entering", sidebarExiting && "is-exiting")}+ onAnimationEnd={handleSidebarAnimationEnd}onToggleSidebar={toggleSidebar}- onNewTask={() => void runMenuCommand("newTask")}- onOpenSearch={() => setSearchOpen(true)}+ sidebarToggleShortcut={sidebarToggleShortcut}+ sidebarWidth={sidebarWidth}+ widthMax={sidebarWidthMax}+ onWidthChange={handleSidebarWidthChange}+ onWidthCommit={handleSidebarWidthCommit}+ onResizeCollapse={handleSidebarResizeCollapse}/>- ) : (+ ) : null}++ {workPanelMaximized && (+ /* MainChat is absent; the panel header owns dragging while this+ pass-through row keeps the shell controls available. */<divclassName={cx(- "main-titlebar",- presentedWorkPanelOpen && "work-panel-open",+ "window-chrome-row",+ !sidebarCollapsed && "sidebar-expanded",)}>{sidebarCollapsed && (- <div className="main-titlebar-left no-drag">- <CollapsedTitlebarActions- onToggleSidebar={reopenSidebar}- onNewTask={() => void runMenuCommand("newTask")}- sidebarToggleShortcut={sidebarToggleShortcut}- />- </div>+ <CollapsedTitlebarActions+ onToggleSidebar={toggleSidebar}+ onNewTask={() => void runMenuCommand("newTask")}+ sidebarToggleShortcut={sidebarToggleShortcut}+ />)}- </div>- )}- <UpdateBanner />-- {backendDown && (- <div- className={`backend-banner no-drag ${backendDown.fatal ? "fatal" : "warn"}`}- role="status"- >- <span className="backend-dot" aria-hidden />- <span>- {backendDown.fatal- ? backendDown.message === "GLIBC_UNSUPPORTED"- ? t("status.unsupportedGlibc")- : backendDown.message === "DB_SCHEMA_TOO_NEW"- ? t("status.dbSchemaTooNew", {- found: backendDown.schema?.found ?? "?",- supported: backendDown.schema?.supported ?? "?",- })- : t("status.fatal")- : t("status.restarting")}- </span>- {backendDown.fatal && (- <button+ {!sidebarCollapsed && (+ <TooltipButtontype="button"- className="backend-action"- onClick={() => void api.openLogs()}+ className="title-nav-btn"+ tooltip={t("nav.newTask")}+ ariaLabel={t("nav.newTask")}+ data-nav="new-task"+ onClick={() => void runMenuCommand("newTask")}>- {t("status.openLogs")}- </button>+ <IconNewSession size={15} />+ </TooltipButton>)}+ <div className="window-chrome-drag" aria-hidden /></div>)}- {archMismatch && (- <div className="backend-banner no-drag warn" role="status">- <span className="backend-dot" aria-hidden />- <span>- {t("status.archMismatch", {- buildArch: t(- `status.archNames.${archMismatch.platform}.${archMismatch.processArch}`,- { defaultValue: archMismatch.processArch },- ),- machineArch: t(- `status.archNames.${archMismatch.platform}.${archMismatch.machineArch}`,- { defaultValue: archMismatch.machineArch },- ),- })}- </span>- <button- type="button"- className="backend-action"- onClick={() => setArchMismatch(null)}- >- {t("status.dismissArchMismatch")}- </button>- </div>- )}+ {!workPanelMaximized && (+ <section className="main-pane">+ {page === "chat" ? (+ <ConversationTopbar+ sidebarCollapsed={sidebarCollapsed}+ workPanelOpen={presentedWorkPanelOpen}+ onToggleSidebar={toggleSidebar}+ onNewTask={() => void runMenuCommand("newTask")}+ onOpenSearch={() => setSearchOpen(true)}+ />+ ) : (+ <div+ className={cx(+ "main-titlebar",+ presentedWorkPanelOpen && "work-panel-open",+ )}+ >+ {sidebarCollapsed && (+ <div className="main-titlebar-left no-drag">+ <CollapsedTitlebarActions+ onToggleSidebar={reopenSidebar}+ onNewTask={() => void runMenuCommand("newTask")}+ sidebarToggleShortcut={sidebarToggleShortcut}+ />+ </div>+ )}+ </div>+ )}+ {page !== "settings" ? <UpdateBanner /> : null}- <Suspense fallback={<RoutePending />}>- {page === "pulls" ? (- <div className="route-surface route-page">- <PullRequestsPage />- </div>- ) : page === "scheduled" ? (- <div className="route-surface route-page">- <ScheduledPage />- </div>- ) : page === "plugins" ? (- <div className="route-surface route-page">- <PluginsPage />- </div>- ) : (- <ChatSurface />- )}- </Suspense>- </section>- )}+ {backendDown && (+ <div+ className={`backend-banner no-drag ${backendDown.fatal ? "fatal" : "warn"}`}+ role="status"+ >+ <span className="backend-dot" aria-hidden />+ <span>+ {backendDown.fatal+ ? backendDown.message === "GLIBC_UNSUPPORTED"+ ? t("status.unsupportedGlibc")+ : backendDown.message === "DB_SCHEMA_TOO_NEW"+ ? t("status.dbSchemaTooNew", {+ found: backendDown.schema?.found ?? "?",+ supported: backendDown.schema?.supported ?? "?",+ })+ : t("status.fatal")+ : t("status.restarting")}+ </span>+ {backendDown.fatal && (+ <button+ type="button"+ className="backend-action"+ onClick={() => void api.openLogs()}+ >+ {t("status.openLogs")}+ </button>+ )}+ </div>+ )}- {(presentedWorkPanelOpen || workPanelExiting) && (- <WorkPanel- panelBlocked={searchOpen}- exiting={workPanelExiting}- onExitAnimationEnd={() =>- finishWorkPanelExit(workPanelExitGeneration.current)- }- subagentPanel={subagentPanelOpen ? subagentPanel : null}- onCloseSubagentPanel={closeSubagentPanel}- containerWidth={shellWidth}- sidebarWidth={sidebarWidth}- sidebarCollapsed={sidebarCollapsed}- sidebarExiting={sidebarExiting}- onAutoCollapseSidebar={autoCollapseSidebar}- maximized={workPanelMaximized}- onToggleMaximize={toggleWorkPanelMaximize}- />- )}+ {archMismatch && (+ <div className="backend-banner no-drag warn" role="status">+ <span className="backend-dot" aria-hidden />+ <span>+ {t("status.archMismatch", {+ buildArch: t(+ `status.archNames.${archMismatch.platform}.${archMismatch.processArch}`,+ { defaultValue: archMismatch.processArch },+ ),+ machineArch: t(+ `status.archNames.${archMismatch.platform}.${archMismatch.machineArch}`,+ { defaultValue: archMismatch.machineArch },+ ),+ })}+ </span>+ <button+ type="button"+ className="backend-action"+ onClick={() => setArchMismatch(null)}+ >+ {t("status.dismissArchMismatch")}+ </button>+ </div>+ )}- <TooltipButton- type="button"- className="app-work-panel-toggle no-drag"- tooltip={workPanelToggleTooltip}- ariaLabel={workPanelToggleTooltip}- aria-pressed={workPanelOpen || presentedWorkPanelOpen}- disabled={!activeSessionId && !presentedWorkPanelOpen && !workPanelExiting}- onClick={togglePresentedWorkPanel}- >- <span className="app-work-panel-toggle-icon" aria-hidden>- <IconPanel size={15} />- <IconPanelOpen size={15} />- </span>- </TooltipButton>+ <Suspense fallback={<RoutePending />}>+ {page === "pulls" ? (+ <div className="route-surface route-page">+ <PullRequestsPage />+ </div>+ ) : page === "scheduled" ? (+ <div className="route-surface route-page">+ <ScheduledPage />+ </div>+ ) : page === "plugins" ? (+ <div className="route-surface route-page">+ <PluginsPage />+ </div>+ ) : (+ <ChatSurface visible={page === "chat"} />+ )}+ </Suspense>+ </section>+ )}- <SearchDialog open={searchOpen} onClose={() => setSearchOpen(false)} />- <ToastHost />- <ExtensionPromptHost />- </>- );- }+ {(presentedWorkPanelOpen || workPanelExiting) && (+ <WorkPanel+ panelBlocked={searchOpen}+ exiting={workPanelExiting}+ onExitAnimationEnd={() =>+ finishWorkPanelExit(workPanelExitGeneration.current)+ }+ subagentPanel={subagentPanelOpen ? subagentPanel : null}+ onCloseSubagentPanel={closeSubagentPanel}+ containerWidth={shellWidth}+ sidebarWidth={sidebarWidth}+ sidebarCollapsed={sidebarCollapsed}+ sidebarExiting={sidebarExiting}+ onAutoCollapseSidebar={autoCollapseSidebar}+ maximized={workPanelMaximized}+ onToggleMaximize={toggleWorkPanelMaximize}+ />+ )}++ <TooltipButton+ type="button"+ className="app-work-panel-toggle no-drag"+ tooltip={workPanelToggleTooltip}+ ariaLabel={workPanelToggleTooltip}+ aria-pressed={workPanelOpen || presentedWorkPanelOpen}+ disabled={!activeSessionId && !presentedWorkPanelOpen && !workPanelExiting}+ onClick={togglePresentedWorkPanel}+ >+ <span className="app-work-panel-toggle-icon" aria-hidden>+ <IconPanel size={15} />+ <IconPanelOpen size={15} />+ </span>+ </TooltipButton>+ </div>+ </PortalVisibilityProvider>+ {page === "settings" ? (+ <Suspense fallback={<RoutePending />}>+ <SettingsPage />+ </Suspense>+ ) : null}+ <SearchDialog open={searchOpen} onClose={() => setSearchOpen(false)} />+ <ToastHost />+ <ExtensionPromptHost />+ {page === "settings" ? <UpdateBanner /> : null}+ </>+ );}return (diff --git a/apps/desktop/src/features/chat/composer/ComposerImagePreview.tsx b/apps/desktop/src/features/chat/composer/ComposerImagePreview.tsxindex d561e65a1..aa03bd3b2 100644--- a/apps/desktop/src/features/chat/composer/ComposerImagePreview.tsx+++ b/apps/desktop/src/features/chat/composer/ComposerImagePreview.tsx@@ -1,10 +1,10 @@import { useEffect, useLayoutEffect, useRef, useState } from "react";-import { createPortal } from "react-dom";import { useTranslation } from "react-i18next";import { IconChevronLeft, IconChevronRight, IconClose, IconDownload, IconMinus, IconPlus } from "../../../components/icons";import { useBlockingOverlay } from "../../../lib/blocking-overlay";-import { useImagePreviewPan } from "./hooks/useImagePreviewPan";+import { portalToBody } from "../../../lib/portal-visibility";import type { ComposerImagePreviewController } from "./hooks/useComposerImagePreview";+import { useImagePreviewPan } from "./hooks/useImagePreviewPan";import "../../../styles/composer-image-preview.css";export function ComposerImagePreview({ controller }: { controller: ComposerImagePreviewController }) {@@ -94,7 +94,7 @@ function ImagePreviewDialog({ controller, preview }: {const dismissBackground = (event: React.MouseEvent<HTMLElement>) => {if (event.target === event.currentTarget) controller.close();};- return createPortal(+ return portalToBody(<dialogref={dialogRef}className="composer-image-preview"@@ -146,6 +146,6 @@ function ImagePreviewDialog({ controller, preview }: {<button type="button" disabled={!natural || failed || zoom >= 8} onClick={() => changeZoom(zoom * 1.25)} aria-label={t("menu.zoomIn")}><IconPlus size={18} /></button><button type="button" disabled={!natural || failed} onClick={() => { setManualZoom(null); pan.reset(); }}>{t("chat.imagePreview.fit")}</button></footer>- </dialog>, document.body,+ </dialog>,);}diff --git a/apps/desktop/src/features/sessions/SessionHoverCard.tsx b/apps/desktop/src/features/sessions/SessionHoverCard.tsxindex 5fa439301..d4b626e8f 100644--- a/apps/desktop/src/features/sessions/SessionHoverCard.tsx+++ b/apps/desktop/src/features/sessions/SessionHoverCard.tsx@@ -1,5 +1,5 @@import { useEffect, useLayoutEffect, useRef, useState } from "react";-import { createPortal } from "react-dom";+import { portalToBody } from "../../lib/portal-visibility";import { useTranslation } from "react-i18next";import type { ProjectWorkspace, SessionCollaborationSummary, SessionReference } from "@pi-desktop/shared";import { api } from "../../lib/api";@@ -99,7 +99,7 @@ export function SessionHoverCard({void onOpenSession(reference.sessionId);};- return createPortal(+ return portalToBody(<divref={elementRef}id={`session-hover-${session.id}`}@@ -248,6 +248,5 @@ export function SessionHoverCard({</div></div></div>,- document.body,);}diff --git a/apps/desktop/src/lib/portal-visibility.tsx b/apps/desktop/src/lib/portal-visibility.tsxnew file mode 100644index 000000000..c296e4969--- /dev/null+++ b/apps/desktop/src/lib/portal-visibility.tsx@@ -0,0 +1,32 @@+import { createContext, type ReactNode } from "react";+import { createPortal } from "react-dom";++export const PortalVisibilityContext = createContext(true);++export function PortalVisibilityProvider({+ visible,+ children,+}: {+ visible: boolean;+ children: ReactNode;+}) {+ return (+ <PortalVisibilityContext.Provider value={visible}>+ {children}+ </PortalVisibilityContext.Provider>+ );+}++export function visiblePortalContent(node: ReactNode) {+ return (+ <PortalVisibilityContext.Consumer>+ {(visible) => (visible ? node : null)}+ </PortalVisibilityContext.Consumer>+ );+}++export function portalToBody(node: ReactNode) {+ return typeof document === "undefined"+ ? node+ : createPortal(visiblePortalContent(node), document.body);+}diff --git a/apps/desktop/src/styles/base.css b/apps/desktop/src/styles/base.cssindex a95c08f47..d6e236e19 100644--- a/apps/desktop/src/styles/base.css+++ b/apps/desktop/src/styles/base.css@@ -170,6 +170,16 @@ html {color: var(--ds-text-primary);}+/* Keep the chat tree mounted while Settings is open without changing the+ shell's flex layout or exposing the hidden tree to focus and accessibility. */+.app-chat-shell {+ display: contents;+}++.app-chat-shell[hidden] {+ display: none;+}+.app-scenic-backdrop {position: fixed;inset: 0;diff --git a/apps/desktop/src/styles/chrome.css b/apps/desktop/src/styles/chrome.cssindex 2a96e807d..af8bb1437 100644--- a/apps/desktop/src/styles/chrome.css+++ b/apps/desktop/src/styles/chrome.css@@ -1102,7 +1102,7 @@}/* Follow the adjacent titlebar surface when the dock occupies the right edge. */-.app-shell:has(> .work-panel) > .window-controls {+.app-shell:has(.work-panel) > .window-controls {background: var(--ds-bg-dock-raised);}@@ -1225,7 +1225,7 @@/* Match the scenic backdrop's child-layer specificity so preview navigation* stays above the work panel while non-control pixels remain pass-through. */-.app-shell > .window-chrome-row {+.app-shell > :where(.app-chat-shell) > .window-chrome-row {position: absolute;top: 0;right: 0;diff --git a/apps/desktop/test/chat-context-menu-surface.test.mjs b/apps/desktop/test/chat-context-menu-surface.test.mjsindex 418d1a517..1df34d56e 100644--- a/apps/desktop/test/chat-context-menu-surface.test.mjs+++ b/apps/desktop/test/chat-context-menu-surface.test.mjs@@ -22,8 +22,7 @@ const assistantTurnSource = await readFile();test("the pointer-anchored menu portals, measures, and closes without trapping focus", () => {- assert.match(menuSource, /createPortal\(/);- assert.match(menuSource, /document\.body/);+ assert.match(menuSource, /portalToBody\(/);assert.match(menuSource, /placeContextMenu\(/);assert.match(menuSource, /className=\{`context-menu\$\{placement \? " is-open" : ""\}`\}/);assert.match(menuSource, /window\.addEventListener\("pointerdown", onOutside, true\)/);diff --git a/apps/desktop/test/interaction-performance.test.mjs b/apps/desktop/test/interaction-performance.test.mjsindex 11f8090d5..637c1f79e 100644--- a/apps/desktop/test/interaction-performance.test.mjs+++ b/apps/desktop/test/interaction-performance.test.mjs@@ -28,11 +28,12 @@ const [app, appShell, chatSurface, pane, transcript, toolRow, transcriptShared,]);test("streaming state stays inside the chat render boundary", () => {- assert.match(app, /<ChatSurface \/>/);+ assert.match(app, /<ChatSurface visible=\{page === "chat"\} \/>/);assert.doesNotMatch(app, /useAppStore\(\(s\) => s\.messages\)/);assert.doesNotMatch(app, /<ChatTranscript/);assert.match(chatSurface, /export const ChatSurface = memo/);assert.match(chatSurface, /const messages = useAppStore/);+ assert.match(chatSurface, /visible=\{visible && id === visibleSessionId\}/);assert.match(chatSurface, /const StableComposer = memo\(Composer\)/);});diff --git a/apps/desktop/test/notification-center.test.mjs b/apps/desktop/test/notification-center.test.mjsindex 38f1d16fa..48f52160c 100644--- a/apps/desktop/test/notification-center.test.mjs+++ b/apps/desktop/test/notification-center.test.mjs@@ -49,7 +49,7 @@ test("notification popover preserves keyboard and focus behavior", () => {assert.match(componentSource, /triggerRef\.current\?\.focus\(\)/);assert.match(componentSource, /rootRef\.current\?\.contains/);assert.match(componentSource, /popoverRef\.current\?\.contains/);- assert.match(componentSource, /createPortal/);+ assert.match(componentSource, /portalToBody/);assert.match(componentSource, /notification-popover-portaled/);assert.match(componentSource, /\.notification-item\.unread, \.notification-item/);assert.match(componentSource, /\.notification-filter\.active/);diff --git a/apps/desktop/test/project-delete.test.mjs b/apps/desktop/test/project-delete.test.mjsindex 46ee02749..b271b645b 100644--- a/apps/desktop/test/project-delete.test.mjs+++ b/apps/desktop/test/project-delete.test.mjs@@ -109,7 +109,7 @@ test("the delete dialog names the sessions and keeps the folder on disk", () =>assert.match(dialogSource, /t\("project\.deleteSessions", \{ count: project\.sessionCount \}\)/);assert.match(dialogSource, /t\("project\.deleteDescription", \{ name: project\.name \}\)/);assert.match(dialogSource, /t\("project\.deleteFolderKept"\)/);- assert.match(dialogSource, /createPortal\(dialog, document\.body\)/);+ assert.match(dialogSource, /portalToBody\(dialog\)/);});test("the delete dialog is a labelled modal that blocks cancel while busy", () => {diff --git a/apps/desktop/test/renderer-recovery.test.mjs b/apps/desktop/test/renderer-recovery.test.mjsnew file mode 100644index 000000000..382b48a50--- /dev/null+++ b/apps/desktop/test/renderer-recovery.test.mjs@@ -0,0 +1,54 @@+import assert from "node:assert/strict";+import test from "node:test";+import { recoverRendererAfterGone } from "../electron/main/renderer-recovery.ts";++function recovery(overrides = {}) {+ const calls = { reload: 0, logs: [] };+ const dependencies = {+ isCurrentWindow: true,+ quitting: false,+ windowCloseAccepted: false,+ windowDestroyed: false,+ webContentsDestroyed: false,+ reload: () => calls.reload++,+ log: (details, reloaded) => calls.logs.push({ details, reloaded }),+ ...overrides,+ };+ return { calls, dependencies };+}++test("unexpected renderer exits reload the live main window and preserve diagnostics", () => {+ const { calls, dependencies } = recovery();+ const details = { reason: "crashed", exitCode: 73 };++ assert.equal(recoverRendererAfterGone(details, dependencies), true);+ assert.equal(calls.reload, 1);+ assert.deepEqual(calls.logs, [{ details, reloaded: true }]);+});++test("clean exits and windows outside the live main lifecycle are not reloaded", () => {+ const cases = [+ [{ reason: "clean-exit", exitCode: 0 }, {}],+ [{ reason: "crashed", exitCode: 1 }, { isCurrentWindow: false }],+ [{ reason: "crashed", exitCode: 1 }, { quitting: true }],+ [{ reason: "crashed", exitCode: 1 }, { windowCloseAccepted: true }],+ [{ reason: "crashed", exitCode: 1 }, { windowDestroyed: true }],+ [{ reason: "crashed", exitCode: 1 }, { webContentsDestroyed: true }],+ ];++ for (const [details, overrides] of cases) {+ const { calls, dependencies } = recovery(overrides);+ assert.equal(recoverRendererAfterGone(details, dependencies), false);+ assert.equal(calls.reload, 0);+ assert.deepEqual(calls.logs, [{ details, reloaded: false }]);+ }+});++test("new renderer exit reasons remain recoverable by default", () => {+ const { calls, dependencies } = recovery();+ assert.equal(+ recoverRendererAfterGone({ reason: "future-electron-reason", exitCode: 2 }, dependencies),+ true,+ );+ assert.equal(calls.reload, 1);+});diff --git a/apps/desktop/test/session-switch-performance.test.mjs b/apps/desktop/test/session-switch-performance.test.mjsindex 4e52bab77..99330c6c1 100644--- a/apps/desktop/test/session-switch-performance.test.mjs+++ b/apps/desktop/test/session-switch-performance.test.mjs@@ -119,7 +119,7 @@ test("each retained session keeps its own mounted pane", () => {// already-painted pane instead of re-pointing one transcript (ADR 0137).assert.match(chatSurface,- /retainedSessionIds\.map\(\(id\) => \(\s*<SessionPane\s*key=\{id\}\s*sessionId=\{id\}\s*visible=\{id === visibleSessionId\}\s*\/>/,+ /retainedSessionIds\.map\(\(id\) => \(\s*<SessionPane\s*key=\{id\}\s*sessionId=\{id\}\s*visible=\{visible && id === visibleSessionId\}\s*\/>/,);assert.match(chatSurface, /const visibleSessionId = retainedSessionIds\[0\]/);// The retention bound lives in a pure module, so eviction is unit-testablediff --git a/apps/desktop/test/sidebar-settings-return.test.mjs b/apps/desktop/test/sidebar-settings-return.test.mjsindex e7f3e9228..d14e26a1c 100644--- a/apps/desktop/test/sidebar-settings-return.test.mjs+++ b/apps/desktop/test/sidebar-settings-return.test.mjs@@ -6,6 +6,26 @@ import { loadStyles } from "./helpers/styles.mjs";const idle = (collapsed = false, presented = true) => ({ collapsed, presented, phase: "idle" });+test("Settings hides the mounted chat shell and keeps its portal layers out of view", async () => {+ const [appShell, styles, portalVisibility] = await Promise.all([+ readFile(new URL("../src/features/app/AppShell.tsx", import.meta.url), "utf8"),+ loadStyles(),+ readFile(new URL("../src/lib/portal-visibility.tsx", import.meta.url), "utf8"),+ ]);+ assert.match(appShell, /<PortalVisibilityProvider visible=\{page !== "settings"\}>/);+ assert.match(appShell, /className="app-chat-shell"[\s\S]*?hidden=\{page === "settings"\}/);+ assert.match(appShell, /inert=\{page === "settings" \? true : undefined\}/);+ assert.match(appShell, /aria-hidden=\{page === "settings" \? true : undefined\}/);+ assert.match(appShell, /className="app-chat-shell"[\s\S]*?<ChatSurface visible=\{page === "chat"\} \/>/);+ assert.match(appShell, /\{page === "settings" \? \([\s\S]*?<SettingsPage \/>/);+ assert.match(appShell, /<ChatSurface visible=\{page === "chat"\} \/>/);+ assert.match(appShell, /<SearchDialog open=\{searchOpen\}/);+ assert.match(styles, /\.app-chat-shell\s*\{\s*display:\s*contents;/);+ assert.match(styles, /\.app-chat-shell\[hidden\]\s*\{\s*display:\s*none;/);+ assert.match(portalVisibility, /<PortalVisibilityContext\.Consumer>[\s\S]*visible \? node : null/);+ assert.match(portalVisibility, /createPortal\(visiblePortalContent\(node\), document\.body\)/);+});+test("initial shell presentation and settings return never play sidebar entrance", () => {assert.deepEqual(nextSidebarTransition(idle(false, false), false, true), idle());for (const collapsed of [false, true]) {diff --git a/apps/desktop/test/transcript-style.test.mjs b/apps/desktop/test/transcript-style.test.mjsindex 1115885ec..effedd231 100644--- a/apps/desktop/test/transcript-style.test.mjs+++ b/apps/desktop/test/transcript-style.test.mjs@@ -396,7 +396,7 @@ test("assistant context inspector keeps a compact summary and retry action wiredassert.match(inspectorSource, /contextOccupancyTokens\(usage\)/);assert.match(inspectorSource, /usage\.cacheReadTokens/);assert.doesNotMatch(inspectorSource, /turnUsage\.cacheReadTokens/);- assert.match(inspectorSource, /createPortal\(popover, document\.body\)/);+ assert.match(inspectorSource, /portalToBody\(popover\)/);assert.match(inspectorSource, /getBoundingClientRect\(\)/);assert.match(inspectorSource, /addEventListener\("scroll", handleViewportChange, true\)/);assert.match(inspectorSource, /ResizeObserver\(updatePopoverPosition\)/);diff --git a/docs/spec/03-runtime/07-process-model.md b/docs/spec/03-runtime/07-process-model.mdindex e95a689b4..0039381f4 100644--- a/docs/spec/03-runtime/07-process-model.md+++ b/docs/spec/03-runtime/07-process-model.md@@ -92,7 +92,7 @@ errors remain readable instead of becoming replacement characters.| Crash | Policy ||---|---|-| Renderer crash | reload window, keep host/agent processes; same-host reload restores only live pending Plan/Goal approvals and their deadlines, not terminal cards |+| Renderer crash | reload the current window after an unexpected renderer exit, unless the window is closing or the app is quitting; keep host/agent processes; same-host reload restores only live pending Plan/Goal approvals and their deadlines, not terminal cards || Rust host crash | mark app degraded, interrupt pending/queued/running approval work, keep pending sessions in their contract mode (Plan or Goal) and already-approved sessions in Agent, attempt restart host, and fail active sessions closed || Node agent crash | abort active turns and live approval waiters/queue entries, keep pending sessions in their contract mode, preserve already-approved Agent mode in Rust, restart sidecar, and never replay an execution || Electron main crash | full app exit |@@ -100,6 +100,9 @@ errors remain readable instead of becoming replacement characters.Crashpad is started local-only (`uploadToServer: false`) before `ready`, anddumps are stored under `<data_dir>/crash-dumps` (D602) so a`PI_DESKTOP_DATA_DIR` profile does not share dumps with another installation.+An unexpected renderer exit records its reason and exit code, then reloads the+current main window when it is still live. A clean renderer exit and an accepted+window close do not trigger recovery.The next launch that holds the single-instance lock writes one diagnosticsline for dumps newer than `crash-dumps.json`. Crashpad recordsChromium-process crashes (main, renderer, GPU, utility); a renderer crash thediff --git a/docs/spec/03-runtime/09-logging-and-observability.md b/docs/spec/03-runtime/09-logging-and-observability.mdindex 13cd81fe6..fad46b88e 100644--- a/docs/spec/03-runtime/09-logging-and-observability.md+++ b/docs/spec/03-runtime/09-logging-and-observability.md@@ -81,6 +81,10 @@ The application categories are:`byProcessType`, `directory`, and `newestMtimeMs`. A recovered renderer crashis therefore not reported as the previous app run aborting. A scan failure isone `crashDumpReportFailed` warn and never blocks the first window (D602).+ Each renderer `render-process-gone` event records one `renderer.process.gone`+ entry with the Electron exit `reason` and `exitCode`, plus whether the current+ main window was reloaded. Clean exits are informational; unexpected exits are+ warnings.- `runtime` — host/sidecar lifecycle, uncategorized child output, andmain-process `uncaughtException` / `unhandledRejection` recordsdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 6fdcc9d86..3b35677a6 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -8229,6 +8229,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.| C / G / Quality — Plugins navigation | E2E-NAV-plugins-button-goes-back || C / D / Quality — Sidebar row states | E2E-LAYOUT-sidebar-row-states || A / C / Quality — Sidebar material and settings return | E2E-LAYOUT-sidebar-settings |+| A / H / Quality — Renderer process crash recovery | E2E-RUNTIME-renderer-crash-recovery || B / F / Security — Provider copy | E2E-PROVIDER-copy-config-without-credentials || B / F / Quality — Selected model order | E2E-MODEL-selected-order-persists || A — App startup | E2E-001, E2E-002, E2E-003, E2E-004, E2E-067, E2E-076, E2E-079, E2E-092, E2E-097, E2E-143, E2E-150, E2E-168, E2E-204 |@@ -13640,7 +13641,10 @@ plugin-form fixtures in an isolated temporary directory at runtime.1. In dark/light palettes and darwin/win32/linux CSS branches, compare thehome sidebar and Settings rail color, image layers, size and position.Inspect transparent ancestors and opaque settings content/titlebar.- 2. Return through Back to app while tracing sidebar insertion, width and+ 2. Before entering Settings, retain the current .chat-surface DOM node. While+ Settings is open, verify the chat shell is hidden, inert, and still+ contains that connected node. Return through Back to app and verify the+ same node is revealed while tracing sidebar insertion, width andanimationstart events. Repeat quick round trips, a previously collapsedsidebar, and settings navigation interrupting an entrance.3. Explicitly reopen a collapsed sidebar, then repeat settings return with@@ -13655,6 +13659,9 @@ plugin-form fixtures in an isolated temporary directory at runtime.stays at 275px without sidebar-in events; a collapsed sidebar stays absent.A real reopen still produces sidebar-in and a width ramp. Legacy theme colorinput remains supported for both rails, and a canonical override wins.+ Portaled layers owned by the hidden chat surface stay hidden while Settings is+ open; the shared app-level search, toast, and extension-prompt layers remain+ available.- **Specs linked**: `04-ux/06-settings-ia.md`, `04-ux/07-ui-design-system.md`,`04-ux/08-component-spec.md` §1.4 and §1.7- **Acceptance**: A, C, Quality@@ -13668,10 +13675,30 @@ plugin-form fixtures in an isolated temporary directory at runtime.Windows/Linux or OS material/theme validation. Optional`PI_DESKTOP_LAYOUT_ARTIFACT_DIR` captures renderer screenshots. State tests in`sidebar-settings-return.test.mjs` cover initial presentation, both interrupted- phases, hidden-state changes and reversals. `settings-dialog-overlay.test.mjs`+ phases, hidden-state changes and reversals. The CDP layout journey verifies+ that Settings preserves the same chat surface node across round trips.+ `settings-dialog-overlay.test.mjs`covers the full-window overlay contract. `pnpm test:e2e:theme-surfaces`verifies the opaque fallback and legacy theme override in real Chromium.+#### E2E-RUNTIME-renderer-crash-recovery++- **Preconditions**: Built desktop with an isolated profile, the main window+ ready on chat, and CDP enabled by the E2E harness.+- **Steps**: Set a renderer-only sentinel, trigger `Page.crash`, then reconnect+ to the existing page target if the renderer's CDP connection closes. Wait for+ the chat surface to return and inspect the isolated diagnostics log.+- **Expected**: The renderer document is recreated in the same app window, the+ chat surface becomes usable, and `renderer.process.gone` records the exit+ reason, exit code, and reload decision. The app does not open a second window.+- **Specs linked**: `03-runtime/07-process-model.md`,+ `03-runtime/09-logging-and-observability.md`+- **Acceptance**: A, H, Quality+- **Milestone**: Post-M6 desktop shell maintenance+- **Status**: Automated by `pnpm test:e2e:layout` with CDP `Page.crash`; the+ deterministic `renderer-recovery.test.mjs` covers clean exit, accepted close,+ app shutdown, stale windows, destroyed contents, and future Electron reasons.+#### E2E-AGENT-alt-enter-steers-active-turn: Enter follows up and Alt+Enter steers the active turn- **Preconditions**: A session with a configured model and a controllablediff --git a/scripts/e2e-three-column-layout.mjs b/scripts/e2e-three-column-layout.mjsindex f5bdc47b6..438065402 100644--- a/scripts/e2e-three-column-layout.mjs+++ b/scripts/e2e-three-column-layout.mjs@@ -19,6 +19,7 @@*/import { spawn } from "node:child_process";import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs";+import { readFile } from "node:fs/promises";import { tmpdir } from "node:os";import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";@@ -174,6 +175,7 @@ async function seedSidebarProjects(hostBinary, dataDir, tempDirs) {class CdpClient {constructor(ws) {this.ws = ws;+ this.closed = false;this.seq = 0;this.pending = new Map();this.console = [];@@ -195,6 +197,13 @@ class CdpClient {if (message.error) entry.reject(new Error(JSON.stringify(message.error)));else entry.resolve(message.result);};+ ws.onclose = () => {+ this.closed = true;+ for (const entry of this.pending.values()) {+ entry.reject(new Error("CDP websocket closed"));+ }+ this.pending.clear();+ };}static connect(url) {@@ -206,6 +215,7 @@ class CdpClient {}send(method, params = {}) {+ if (this.closed) return Promise.reject(new Error("CDP websocket closed"));const id = ++this.seq;return new Promise((resolve, reject) => {this.pending.set(id, { resolve, reject });@@ -259,9 +269,12 @@ const MEASURE = `(() => {const main = document.querySelector(".main-pane");const panel = document.querySelector('[data-testid="work-panel"]');const sidebar = document.querySelector(".sidebar, .sidebar-rail");+ const chatShell = document.querySelector(".app-chat-shell");const handle = document.querySelector(".work-panel-resize");return {windowWidth: window.innerWidth,+ chatHidden: chatShell?.hidden ?? null,+ settings: Boolean(document.querySelector(".settings-shell")),sidebar: round(sidebar),sidebarKind: sidebar ? String(sidebar.className).split(" ")[0] : null,main: round(main),@@ -1734,11 +1747,75 @@ async function main() {);await cdp.evaluate(`document.documentElement.dataset.theme = ${JSON.stringify(originalTheme)}`);- await checkSidebarRowStates({ cdp, check, waitFor, seed: sidebarSeed });await checkSidebarSettings({cdp, check, waitFor, artifactDir: process.env.PI_DESKTOP_LAYOUT_ARTIFACT_DIR,});+ const crashSentinel = `renderer-crash-${Date.now()}`;+ await cdp.evaluate(+ `window.__PI_E2E_RENDERER_CRASH_SENTINEL = ${JSON.stringify(crashSentinel)}`,+ );+ void cdp.send("Page.crash").catch(() => undefined);+ let recoveryCdp = cdp;+ const recoveryState = await waitFor(async () => {+ if (recoveryCdp.closed) {+ const page = (await listTargets(cdpPort).catch(() => [])).find(+ (candidate) => candidate.type === "page" && candidate.id === target.id,+ );+ if (!page?.webSocketDebuggerUrl) return false;+ const connected = await CdpClient.connect(page.webSocketDebuggerUrl).catch(+ () => null,+ );+ if (!connected) return false;+ recoveryCdp = connected;+ activeCdp = recoveryCdp;+ await recoveryCdp.send("Runtime.enable").catch(() => undefined);+ }+ const state = await recoveryCdp+ .evaluate(`({+ sentinel: window.__PI_E2E_RENDERER_CRASH_SENTINEL,+ chatSurface: Boolean(document.querySelector('.chat-surface')),+ splash: Boolean(document.querySelector('.startup-splash')),+ })`)+ .catch(() => null);+ return state?.chatSurface && !state.splash && state.sentinel !== crashSentinel+ ? state+ : false;+ }, "the renderer automatically reloads after a crash", 90_000);+ const recoveredTarget = (await listTargets(cdpPort).catch(() => [])).find(+ (candidate) => candidate.type === "page" && candidate.id === target.id,+ );+ check(+ recoveryState.chatSurface && recoveredTarget?.id === target.id,+ "the existing app window restores the chat after a renderer crash",+ JSON.stringify({ recoveryState, targetId: recoveredTarget?.id }),+ );+ const diagnostics = await readFile(+ join(dataDir, "logs", "app", "diagnostics.log"),+ "utf8",+ ).catch(() => "");+ const rendererRecoveryLog = diagnostics+ .split("\n")+ .filter(Boolean)+ .map((line) => {+ try {+ return JSON.parse(line);+ } catch {+ return null;+ }+ })+ .find(+ (entry) =>+ entry?.event === "renderer.process.gone" && entry.data?.reloaded === true,+ );+ check(+ Boolean(rendererRecoveryLog?.data?.reason),+ "renderer crash recovery records the exit reason and reload decision",+ JSON.stringify(rendererRecoveryLog),+ );++ await checkSidebarRowStates({ cdp: recoveryCdp, check, waitFor, seed: sidebarSeed });+const failed = results.filter((entry) => !entry.ok);console.log(`\nE2E-LAYOUT-three-column-width-priority: ${results.length - failed.length}/${results.length} checks passed`,diff --git a/scripts/e2e/sidebar-row-states.mjs b/scripts/e2e/sidebar-row-states.mjsindex 4df7ec1fe..ab87bdd50 100644--- a/scripts/e2e/sidebar-row-states.mjs+++ b/scripts/e2e/sidebar-row-states.mjs@@ -44,6 +44,15 @@ export async function checkSidebarRowStates({ cdp, check, waitFor, seed }) {await delay(180);};const hover = async (selector) => {+ if (selector.endsWith(".sidebar-session-group-add")) {+ const header = selector.replace(/\s+\.sidebar-session-group-add$/, "");+ const headerTarget = await point(header);+ await move(headerTarget.x, headerTarget.y);+ await waitFor(+ () => cdp.evaluate(`getComputedStyle(document.querySelector(${JSON.stringify(selector)})).pointerEvents === 'auto'`),+ `row-state action is revealed: ${selector}`,+ );+ }const target = await point(selector);await move(target.x, target.y);};@@ -183,9 +192,18 @@ export async function checkSidebarRowStates({ cdp, check, waitFor, seed }) {await click('[data-nav="settings"]');await waitFor(() => cdp.evaluate("!!document.querySelector('.settings-shell')"), "settings opens");await move(600, 120);+ const hiddenChatState = await cdp.evaluate(`(() => {+ const chatShell = document.querySelector('.app-chat-shell');+ const sidebar = chatShell?.querySelector('.sidebar');+ return {+ hidden: chatShell?.hidden === true && chatShell.getAttribute('aria-hidden') === 'true' && chatShell.inert,+ sidebarRetained: sidebar?.isConnected === true,+ };+ })()`);check(- (await selectedIds()).length === 0 && await cdp.evaluate("!document.querySelector('.sidebar')"),- `${theme} settings replaces navigation without leaving stale selected rows`,+ hiddenChatState.hidden && hiddenChatState.sidebarRetained,+ `${theme} settings hides the mounted chat and sidebar`,+ JSON.stringify({ hiddenChatState, selectedIds: await selectedIds() }),);await click('[data-nav="back-to-app"]');await waitFor(() => cdp.evaluate("!!document.querySelector('.sidebar')"), "sidebar returns from settings");diff --git a/scripts/e2e/sidebar-settings.mjs b/scripts/e2e/sidebar-settings.mjsindex f2d123d23..a22f6f6b5 100644--- a/scripts/e2e/sidebar-settings.mjs+++ b/scripts/e2e/sidebar-settings.mjs@@ -99,9 +99,33 @@ export async function checkSidebarSettings({ cdp, check, waitFor, artifactDir })})()`);};const returnToApp = async (width, label, collapsed = false) => {+ const retainedChat = await cdp.evaluate(`(() => {+ const chatShell = document.querySelector('.app-chat-shell');+ const chatSurface = chatShell?.querySelector('.chat-surface');+ window.__settingsReturnChatSurface = chatSurface ?? null;+ return {+ hidden: chatShell?.hidden === true,+ mounted: chatSurface?.isConnected === true,+ };+ })()`);+ check(+ retainedChat.hidden && retainedChat.mounted,+ `${label}: Settings hides the chat while keeping it mounted`,+ JSON.stringify(retainedChat),+ );await startTrace();await click('[data-nav="back-to-app"]');await waitFor(() => cdp.evaluate("!document.querySelector('.settings-shell')"), "settings closes");+ const sameChat = await cdp.evaluate(`(() => {+ const original = window.__settingsReturnChatSurface;+ delete window.__settingsReturnChatSurface;+ return Boolean(original?.isConnected && document.querySelector('.chat-surface') === original);+ })()`);+ check(+ sameChat,+ `${label}: returning from Settings reveals the same chat surface`,+ String(sameChat),+ );const trace = await finishTrace();check(trace.animations.length === 0 && (collapsed