Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
refactor(architecture): decouple main state bridges and extract store transform helpers
Totopo27881e4c69765a
diff --git a/apps/desktop/electron/main/bootstrap/main-state.ts b/apps/desktop/electron/main/bootstrap/main-state.tsnew file mode 100644index 000000000..134969305--- /dev/null+++ b/apps/desktop/electron/main/bootstrap/main-state.ts@@ -0,0 +1,433 @@+import type { BrowserWindow, Tray } from "electron";+import { nativeTheme } from "electron";+import type {+ AppMenuCommand,+ CloseBehavior,+ WindowBounds,+ WorkPanelReservationState,+} from "@pi-desktop/shared";+import { emptyWorkPanelReservationState } from "../work-panel-window";+import type { WindowLifecycleState } from "./window";+import type { LauncherState } from "./launcher";+import type { RuntimeState } from "../runtime/context";+import type {+ ApplicationAppearanceState,+ ApplicationLifecycleState,+} from "./app-lifecycle";+import type { PlanRuntimeState } from "../runtime/plans";+import type { StartupState } from "./startup";+import type { ShutdownState } from "./shutdown";+import type { HostProcess } from "../host-process";+import type { AgentSidecar } from "../agent-sidecar";+import type { AgentHostBridge } from "../agent-host-bridge";+import type { McpControlController, McpControlServer } from "../mcp-control";+import type { BackendRouter } from "../remote/backend-router";++export type MenuRendererReadyGate = {+ window: BrowserWindow;+ ready: boolean;+ promise: Promise<void>;+ resolve: () => void;+};++export type PluginPanelTheme = "light" | "dark";++/**+ * Encapsulated mutable state container for the Electron main process.+ * Houses shared runtime references and provides bridge interfaces to subsystems.+ */+export class MainProcessState {+ mainWindow: BrowserWindow | null = null;+ tray: Tray | null = null;+ pluginLauncherWindow: BrowserWindow | null = null;+ pluginLauncherCreationPromise: Promise<BrowserWindow> | null = null;+ pluginLauncherAccelerator: string | null = null;+ pluginLauncherBinding: string | null = null;+ toggleWindowAccelerator: string | null = null;++ windowCreationPromise: Promise<void> | null = null;+ applicationBooted = false;+ pendingApplicationMenuCommands: AppMenuCommand[] = [];+ menuRendererReadyGate: MenuRendererReadyGate | null = null;+ appliedMenuSettings: string | null = null;++ requestedWorkPanelReservation = 0;+ workPanelReservation: WorkPanelReservationState = emptyWorkPanelReservationState();+ workPanelDisplayKey: string | null = null;+ workPanelBaseBounds: WindowBounds | null = null;+ workPanelLastAppliedBounds: WindowBounds | null = null;+ expectedWorkPanelBounds: WindowBounds | null = null;+ workPanelUserMovePending = false;+ workPanelNativeResizeActive = false;+ workPanelChatResizeActive = false;+ workPanelChatResizeTimer: NodeJS.Timeout | null = null;+ setWorkPanelChatWidthForWindow: ((width: number) => number) | null = null;++ host: HostProcess | null = null;+ sidecar: AgentSidecar | null = null;+ mcpControl: McpControlServer | null = null;+ agentHostBridge: AgentHostBridge | null = null;+ desktopControl: McpControlController | null = null;+ backendRouter: BackendRouter | null = null;++ quitting = false;+ shutdownComplete = false;+ shutdownPromise: Promise<void> | null = null;+ closeBehavior: CloseBehavior = "ask";+ closePromptOpen = false;+ quitConfirmed = false;+ developerMode = false;++ updaterLocale = "en";+ pluginPanelTheme: PluginPanelTheme = nativeTheme.shouldUseDarkColors ? "dark" : "light";+ appThemePreference = "system";+ broadcastAppearanceSignature = "";++ approvedExecutionDrain: Promise<void> | null = null;+ notificationViewingSessionId: string | null = null;+ readonly windowsAllowedToClose = new WeakSet<BrowserWindow>();++ readonly launcherState: LauncherState;+ readonly windowLifecycleState: WindowLifecycleState;+ readonly runtimeState: RuntimeState;+ readonly applicationLifecycleState: ApplicationLifecycleState;+ readonly applicationAppearanceState: ApplicationAppearanceState;+ readonly planRuntimeState: PlanRuntimeState;+ readonly startupState: StartupState;+ readonly shutdownState: ShutdownState;++ constructor() {+ const self = this;++ this.launcherState = {+ get creationPromise() {+ return self.pluginLauncherCreationPromise;+ },+ set creationPromise(value) {+ self.pluginLauncherCreationPromise = value;+ },+ get pluginLauncherAccelerator() {+ return self.pluginLauncherAccelerator;+ },+ set pluginLauncherAccelerator(value) {+ self.pluginLauncherAccelerator = value;+ },+ get toggleWindowAccelerator() {+ return self.toggleWindowAccelerator;+ },+ set toggleWindowAccelerator(value) {+ self.toggleWindowAccelerator = value;+ },+ };++ this.windowLifecycleState = {+ get mainWindow() {+ return self.mainWindow;+ },+ set mainWindow(value) {+ self.mainWindow = value;+ },+ get notificationViewingSessionId() {+ return self.notificationViewingSessionId;+ },+ set notificationViewingSessionId(value) {+ self.notificationViewingSessionId = value;+ },+ get requestedWorkPanelReservation() {+ return self.requestedWorkPanelReservation;+ },+ set requestedWorkPanelReservation(value) {+ self.requestedWorkPanelReservation = value;+ },+ get workPanelReservation() {+ return self.workPanelReservation;+ },+ set workPanelReservation(value) {+ self.workPanelReservation = value;+ },+ get workPanelDisplayKey() {+ return self.workPanelDisplayKey;+ },+ set workPanelDisplayKey(value) {+ self.workPanelDisplayKey = value;+ },+ get workPanelBaseBounds() {+ return self.workPanelBaseBounds;+ },+ set workPanelBaseBounds(value) {+ self.workPanelBaseBounds = value;+ },+ get workPanelLastAppliedBounds() {+ return self.workPanelLastAppliedBounds;+ },+ set workPanelLastAppliedBounds(value) {+ self.workPanelLastAppliedBounds = value;+ },+ get expectedWorkPanelBounds() {+ return self.expectedWorkPanelBounds;+ },+ set expectedWorkPanelBounds(value) {+ self.expectedWorkPanelBounds = value;+ },+ get workPanelUserMovePending() {+ return self.workPanelUserMovePending;+ },+ set workPanelUserMovePending(value) {+ self.workPanelUserMovePending = value;+ },+ get workPanelNativeResizeActive() {+ return self.workPanelNativeResizeActive;+ },+ set workPanelNativeResizeActive(value) {+ self.workPanelNativeResizeActive = value;+ },+ get workPanelChatResizeTimer() {+ return self.workPanelChatResizeTimer;+ },+ set workPanelChatResizeTimer(value) {+ self.workPanelChatResizeTimer = value;+ },+ get workPanelChatResizeActive() {+ return self.workPanelChatResizeActive;+ },+ set workPanelChatResizeActive(value) {+ self.workPanelChatResizeActive = value;+ },+ get setWorkPanelChatWidthForWindow() {+ return self.setWorkPanelChatWidthForWindow;+ },+ set setWorkPanelChatWidthForWindow(value) {+ self.setWorkPanelChatWidthForWindow = value;+ },+ get pluginLauncherBinding() {+ return self.pluginLauncherBinding;+ },+ set pluginLauncherBinding(value) {+ self.pluginLauncherBinding = value;+ },+ get closePromptOpen() {+ return self.closePromptOpen;+ },+ set closePromptOpen(value) {+ self.closePromptOpen = value;+ },+ get quitConfirmed() {+ return self.quitConfirmed;+ },+ set quitConfirmed(value) {+ self.quitConfirmed = value;+ },+ get menuRendererReadyGate() {+ return self.menuRendererReadyGate;+ },+ set menuRendererReadyGate(value) {+ self.menuRendererReadyGate = value;+ },+ get quitting() {+ return self.quitting;+ },+ set quitting(value) {+ self.quitting = value;+ },+ get tray() {+ return self.tray;+ },+ set tray(value) {+ self.tray = value;+ },+ get closeBehavior() {+ return self.closeBehavior;+ },+ set closeBehavior(value) {+ self.closeBehavior = value;+ },+ get developerMode() {+ return self.developerMode;+ },+ set developerMode(value) {+ self.developerMode = value;+ },+ get pluginLauncherWindow() {+ return self.pluginLauncherWindow;+ },+ set pluginLauncherWindow(value) {+ self.pluginLauncherWindow = value;+ },+ get host() {+ return self.host;+ },+ set host(value) {+ self.host = value;+ },+ };++ this.runtimeState = {+ get host() {+ return self.host;+ },+ set host(value) {+ self.host = value;+ },+ get sidecar() {+ return self.sidecar;+ },+ set sidecar(value) {+ self.sidecar = value;+ },+ get agentHostBridge() {+ return self.agentHostBridge;+ },+ set agentHostBridge(value) {+ self.agentHostBridge = value;+ },+ };++ this.applicationLifecycleState = {+ get windowCreationPromise() {+ return self.windowCreationPromise;+ },+ set windowCreationPromise(value) {+ self.windowCreationPromise = value;+ },+ get applicationBooted() {+ return self.applicationBooted;+ },+ set applicationBooted(value) {+ self.applicationBooted = value;+ },+ pendingApplicationMenuCommands: this.pendingApplicationMenuCommands,+ get appliedMenuSettings() {+ return self.appliedMenuSettings;+ },+ set appliedMenuSettings(value) {+ self.appliedMenuSettings = value;+ },+ };++ this.applicationAppearanceState = {+ get updaterLocale() {+ return self.updaterLocale;+ },+ set updaterLocale(value) {+ self.updaterLocale = value;+ },+ get pluginPanelTheme() {+ return self.pluginPanelTheme;+ },+ set pluginPanelTheme(value) {+ self.pluginPanelTheme = value;+ },+ get appThemePreference() {+ return self.appThemePreference;+ },+ set appThemePreference(value) {+ self.appThemePreference = value;+ },+ get broadcastAppearanceSignature() {+ return self.broadcastAppearanceSignature;+ },+ set broadcastAppearanceSignature(value) {+ self.broadcastAppearanceSignature = value;+ },+ };++ this.planRuntimeState = {+ get approvedExecutionDrain() {+ return self.approvedExecutionDrain;+ },+ set approvedExecutionDrain(value) {+ self.approvedExecutionDrain = value;+ },+ };++ this.startupState = {+ get applicationBooted() {+ return self.applicationBooted;+ },+ set applicationBooted(value) {+ self.applicationBooted = value;+ },+ get closeBehavior() {+ return self.closeBehavior;+ },+ set closeBehavior(value) {+ self.closeBehavior = value;+ },+ get agentHostBridge() {+ return self.agentHostBridge;+ },+ set agentHostBridge(value) {+ self.agentHostBridge = value;+ },+ get backendRouter() {+ return self.backendRouter;+ },+ set backendRouter(value) {+ self.backendRouter = value;+ },+ get desktopControl() {+ return self.desktopControl;+ },+ set desktopControl(value) {+ self.desktopControl = value;+ },+ get mcpControl() {+ return self.mcpControl;+ },+ set mcpControl(value) {+ self.mcpControl = value;+ },+ };++ this.shutdownState = {+ get shutdownComplete() {+ return self.shutdownComplete;+ },+ set shutdownComplete(value) {+ self.shutdownComplete = value;+ },+ get shutdownPromise() {+ return self.shutdownPromise;+ },+ set shutdownPromise(value) {+ self.shutdownPromise = value;+ },+ get quitting() {+ return self.quitting;+ },+ set quitting(value) {+ self.quitting = value;+ },+ get quitConfirmed() {+ return self.quitConfirmed;+ },+ set quitConfirmed(value) {+ self.quitConfirmed = value;+ },+ get closeBehavior() {+ return self.closeBehavior;+ },+ set closeBehavior(value) {+ self.closeBehavior = value;+ },+ get tray() {+ return self.tray;+ },+ set tray(value) {+ self.tray = value;+ },+ get pluginLauncherAccelerator() {+ return self.pluginLauncherAccelerator;+ },+ set pluginLauncherAccelerator(value) {+ self.pluginLauncherAccelerator = value;+ },+ get toggleWindowAccelerator() {+ return self.toggleWindowAccelerator;+ },+ set toggleWindowAccelerator(value) {+ self.toggleWindowAccelerator = value;+ },+ };+ }+}diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex 1e0680554..4c70a6695 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -48,7 +48,7 @@ import {import { PersistenceOutbox } from "./persistence-outbox";import { AgentSidecar } from "./agent-sidecar";import { Logger, ignoreBrokenStdio } from "./logger";-import { installMainProcessErrorHandlers } from "./main-process-errors";+import { describeError, installMainProcessErrorHandlers } from "./main-process-errors";import {isDbSchemaTooNewError,} from "./host-boot-diagnostics";@@ -90,6 +90,7 @@ import {planExecutionFromUnknown,} from "@pi-desktop/host-runtime";import { readWindowState, writeWindowState } from "./window-preferences";+import { withGitBranch } from "./workspace-git";import { applyDevelopmentUserData, desktopDataDir } from "./data-paths";import { createPlanUiProbe } from "./plan-ui-probe";import type { McpControlController, McpControlServer } from "./mcp-control";@@ -111,6 +112,7 @@ import { registerPullsIpc } from "./ipc/pulls-ipc";import { registerAgentIpc } from "./ipc/agent-ipc";import { registerIpcHandlers } from "./ipc/register";import { createVoiceService } from "./voice-service";+import { MainProcessState } from "./bootstrap/main-state";import {type WindowLifecycleState,} from "./bootstrap/window";@@ -204,248 +206,22 @@ const WINDOW_BOUNDS_SETTLE_MS = 300;const WORK_PANEL_NATIVE_RESIZE_SETTLE_MS = 180;const WORK_PANEL_CHAT_RESIZE_SETTLE_MS = WINDOW_BOUNDS_SETTLE_MS + 120;-let mainWindow: BrowserWindow | null = null;-let tray: Tray | null = null;-let pluginLauncherWindow: BrowserWindow | null = null;-let pluginLauncherCreationPromise: Promise<BrowserWindow> | null = null;-let pluginLauncherAccelerator: string | null = null;-let pluginLauncherBinding: string | null = null;-let toggleWindowAccelerator: string | null = null;-const launcherState: LauncherState = {- get creationPromise() {- return pluginLauncherCreationPromise;- },- set creationPromise(value) {- pluginLauncherCreationPromise = value;- },- get pluginLauncherAccelerator() {- return pluginLauncherAccelerator;- },- set pluginLauncherAccelerator(value) {- pluginLauncherAccelerator = value;- },- get toggleWindowAccelerator() {- return toggleWindowAccelerator;- },- set toggleWindowAccelerator(value) {- toggleWindowAccelerator = value;- },-};-let windowCreationPromise: Promise<void> | null = null;-let applicationBooted = false;-const pendingApplicationMenuCommands: AppMenuCommand[] = [];-type MenuRendererReadyGate = {- window: BrowserWindow;- ready: boolean;- promise: Promise<void>;- resolve: () => void;-};-let menuRendererReadyGate: MenuRendererReadyGate | null = null;-let requestedWorkPanelReservation = 0;-let workPanelReservation = emptyWorkPanelReservationState();-let workPanelDisplayKey: string | null = null;-// Base bounds are persistable; last-applied bounds isolate later native deltas.-let workPanelBaseBounds: WindowBounds | null = null;-let workPanelLastAppliedBounds: WindowBounds | null = null;-// A reservation changes native bounds intentionally. The next matching move-// event belongs to that mutation, not to a user dragging the window between-// displays.-let expectedWorkPanelBounds: WindowBounds | null = null;-// Set while a native `move` stream is unaccounted for, which is what separates-// a display change the user caused by dragging from one the OS imposed on-// bounds we asked for (D263). A flag rather than a deadline: attribution must-// not depend on how long the main process took to reach the classification.-let workPanelUserMovePending = false;-let workPanelNativeResizeActive = false;-let workPanelChatResizeActive = false;-let workPanelChatResizeTimer: NodeJS.Timeout | null = null;-let setWorkPanelChatWidthForWindow: ((width: number) => number) | null = null;-let host: HostProcess | null = null;-let sidecar: AgentSidecar | null = null;-let mcpControl: McpControlServer | null = null;-let agentHostBridge: AgentHostBridge | null = null;-let desktopControl: McpControlController | null = null;-let quitting = false;-let shutdownComplete = false;-let shutdownPromise: Promise<void> | null = null;-// User-chosen close behavior on Windows/Linux; "ask" prompts on first close.-// The tray itself is owned by D216 (always present on every platform), so-// close behavior only decides whether a close hides the window to it.-let closeBehavior: CloseBehavior = "ask";-let closePromptOpen = false;-// Set when the user has explicitly confirmed a quit through the confirmation-// dialog (Cmd+Q, tray quit, etc.). Prevents the dialog from showing again when-// `app.quit()` is re-issued after the user confirmed.-let quitConfirmed = false;-// Windows whose close handler has already decided to let the close through.-// Per-window rather than a module-level latch, so a real close never leaks-// permission to close into the next window `ensureWindow()` creates.-const windowsAllowedToClose = new WeakSet<BrowserWindow>();--// The window bootstrap owns this mutable boundary. Accessors keep the-// existing lifecycle state available to the remaining main-process services-// while preventing the bootstrap module from reaching into their globals.-const windowLifecycleState: WindowLifecycleState = {- get mainWindow() {- return mainWindow;- },- set mainWindow(value) {- mainWindow = value;- },- get notificationViewingSessionId() {- return notificationViewingSessionId;- },- set notificationViewingSessionId(value) {- notificationViewingSessionId = value;- },- get requestedWorkPanelReservation() {- return requestedWorkPanelReservation;- },- set requestedWorkPanelReservation(value) {- requestedWorkPanelReservation = value;- },- get workPanelReservation() {- return workPanelReservation;- },- set workPanelReservation(value) {- workPanelReservation = value;- },- get workPanelDisplayKey() {- return workPanelDisplayKey;- },- set workPanelDisplayKey(value) {- workPanelDisplayKey = value;- },- get workPanelBaseBounds() {- return workPanelBaseBounds;- },- set workPanelBaseBounds(value) {- workPanelBaseBounds = value;- },- get workPanelLastAppliedBounds() {- return workPanelLastAppliedBounds;- },- set workPanelLastAppliedBounds(value) {- workPanelLastAppliedBounds = value;- },- get expectedWorkPanelBounds() {- return expectedWorkPanelBounds;- },- set expectedWorkPanelBounds(value) {- expectedWorkPanelBounds = value;- },- get workPanelUserMovePending() {- return workPanelUserMovePending;- },- set workPanelUserMovePending(value) {- workPanelUserMovePending = value;- },- get workPanelNativeResizeActive() {- return workPanelNativeResizeActive;- },- set workPanelNativeResizeActive(value) {- workPanelNativeResizeActive = value;- },- get workPanelChatResizeTimer() {- return workPanelChatResizeTimer;- },- set workPanelChatResizeTimer(value) {- workPanelChatResizeTimer = value;- },- get workPanelChatResizeActive() {- return workPanelChatResizeActive;- },- set workPanelChatResizeActive(value) {- workPanelChatResizeActive = value;- },- get setWorkPanelChatWidthForWindow() {- return setWorkPanelChatWidthForWindow;- },- set setWorkPanelChatWidthForWindow(value) {- setWorkPanelChatWidthForWindow = value;- },- get pluginLauncherBinding() {- return pluginLauncherBinding;- },- set pluginLauncherBinding(value) {- pluginLauncherBinding = value;- },- get closePromptOpen() {- return closePromptOpen;- },- set closePromptOpen(value) {- closePromptOpen = value;- },- get quitConfirmed() {- return quitConfirmed;- },- set quitConfirmed(value) {- quitConfirmed = value;- },- get menuRendererReadyGate() {- return menuRendererReadyGate;- },- set menuRendererReadyGate(value) {- menuRendererReadyGate = value;- },- get quitting() {- return quitting;- },- set quitting(value) {- quitting = value;- },- get tray() {- return tray;- },- set tray(value) {- tray = value;- },- get closeBehavior() {- return closeBehavior;- },- set closeBehavior(value) {- closeBehavior = value;- },- get developerMode() {- return developerMode;- },- set developerMode(value) {- developerMode = value;- },- get pluginLauncherWindow() {- return pluginLauncherWindow;- },- set pluginLauncherWindow(value) {- pluginLauncherWindow = value;- },- get host() {- return host;- },- set host(value) {- host = value;- },-};+const mainState = new MainProcessState();+const {+ launcherState,+ windowLifecycleState,+ runtimeState,+ applicationLifecycleState,+ applicationAppearanceState,+ planRuntimeState,+ startupState,+ shutdownState,+ windowsAllowedToClose,+} = mainState;-const runtimeState: RuntimeState = {- get host() {- return host;- },- set host(value) {- host = value;- },- get sidecar() {- return sidecar;- },- set sidecar(value) {- sidecar = value;- },- get agentHostBridge() {- return agentHostBridge;- },- set agentHostBridge(value) {- agentHostBridge = value;- },-};+const getHost = () => mainState.host;+const getMainWindow = () => mainState.mainWindow;+const getSidecar = () => mainState.sidecar;let applicationLifecycle: ReturnType<typeof createApplicationLifecycle> | null = null;let launcherRuntime: ReturnType<typeof createLauncher> | null = null;@@ -496,7 +272,7 @@ const {const desktopServices = createDesktopServices({getLogger: () => logger,- getMainWindow: () => mainWindow,+ getMainWindow,});const {clipboardHistory,@@ -518,7 +294,9 @@ process.env.PI_DESKTOP_DATA_DIR = dataDir;// prompts between the two.const agentExtensions = new AgentExtensionBridge({hasRenderer: () =>- !!mainWindow && !mainWindow.isDestroyed() && !mainWindow.webContents.isDestroyed(),+ !!mainState.mainWindow &&+ !mainState.mainWindow.isDestroyed() &&+ !mainState.mainWindow.webContents.isDestroyed(),onChanged: () => sendToRenderer(IPC.event.pluginChanged, { reason: "agentExtensions" }),onPrompt: (prompt) => {logger.app("plugin", "info", "extension prompt", {@@ -551,7 +329,7 @@ const persistenceOutbox = new PersistenceOutbox(dataDir, (level, message, data)const steeringReplies = new Set<string>();const scheduledRuntime = createScheduledRuntime({dataDir,- getHost: () => host,+ getHost,logger,});const { importLegacyScheduled } = scheduledRuntime;@@ -561,8 +339,8 @@ const { importLegacyScheduled } = scheduledRuntime;// involved because a stale checkpoint must never be replayed after the final// row.const inflightCheckpointer = new InflightCheckpointer(async (checkpoint) => {- if (!host || !host.isAvailable()) return;- await host.call(+ if (!mainState.host || !mainState.host.isAvailable()) return;+ await mainState.host.call("session.saveInflightMessage",{sessionId: checkpoint.sessionId,@@ -573,23 +351,12 @@ const inflightCheckpointer = new InflightCheckpointer(async (checkpoint) => {);});-/** Product UI locale for shipped-locale update notes (mirrored from settings). */-let updaterLocale = "en";-type PluginPanelTheme = "light" | "dark";-let pluginPanelTheme: PluginPanelTheme = nativeTheme.shouldUseDarkColors- ? "dark"- : "light";-/** Raw theme preference from AppSettings.theme, surfaced by `app.getAppearance`. */-let appThemePreference: string = "system";-/** Last appearance broadcast to plugin panels; avoids redundant pushes. */-let broadcastAppearanceSignature = "";-const updater = new AppUpdaterController({logger,send: sendToRenderer,currentVersion: APP_VERSION,isPackaged: !isDevelopmentBuild,- getLocale: () => updaterLocale,+ getLocale: () => mainState.updaterLocale,});/**@@ -628,8 +395,8 @@ let sessionLaunchRuntime: ReturnType<typeof createSessionLaunchRuntime> | null =const pluginServices = createPluginServices({dataDir,logger,- getMainWindow: () => mainWindow,- getHost: () => host,+ getMainWindow,+ getHost,sendToRenderer,safeOpenExternal,stripWinLongPrefix,@@ -637,8 +404,8 @@ const pluginServices = createPluginServices({getPluginNotificationPermission,requestPluginNotificationPermission,showPluginNativeNotification,- getUpdaterLocale: () => updaterLocale,- getPluginPanelTheme: () => pluginPanelTheme,+ getUpdaterLocale: () => mainState.updaterLocale,+ getPluginPanelTheme: () => mainState.pluginPanelTheme,getAppearance: () => {if (!applicationLifecycle) {throw new Error("application lifecycle is not initialized");@@ -675,7 +442,7 @@ const {} = pluginServices;const providerCatalogRuntime = createProviderCatalogRuntime({- getHost: () => host,+ getHost,modelsDevCatalog,});const {@@ -773,7 +540,7 @@ function setCurrentWorkspacePath(path: string | null): void {// was already open sees them without waiting for the next switch; every later// switch finds the snapshot warm and broadcasts exactly once (ADR 0263).if (knownProjectGroups() === null) {- void refreshProjectGroups(host).then((changed) => {+ void refreshProjectGroups(mainState.host).then((changed) => {if (!changed) return;const enriched = pluginWorkspaceInfo(currentWorkspacePath());broadcastPluginPanelEvent("workspace:changed", enriched);@@ -782,12 +549,6 @@ function setCurrentWorkspacePath(path: string | null): void {}}-/** One-line message for an error of unknown shape, for user-facing lists. */-function describeError(error: unknown): string {- if (error instanceof Error) return error.message.slice(0, 300);- return String(error).slice(0, 300);-}-/** Pull the user's MCP server records from host-core into the local runtime. */function sendToRenderer(channel: string, payload: unknown) {applicationLifecycle?.traySessions.observeEvent(channel, payload);@@ -798,7 +559,7 @@ function sendToRenderer(channel: string, payload: unknown) {});}if (!IPC_WHITELIST.has(channel)) return;- const window = mainWindow;+ const window = mainState.mainWindow;if (!window ||window.isDestroyed() ||@@ -820,64 +581,6 @@ function sendToRenderer(channel: string, payload: unknown) {installInsecureEndpointNotice(sendToRenderer);-let appliedMenuSettings: string | null = null;--/**- * Devtools stay locked until the user opts in via settings (D-dev mode);- * mirrors `AppSettings.developerMode` so the IPC handler, the F12 shortcut- * and the macOS View menu all read one flag.- */-let developerMode = false;--const applicationLifecycleState: ApplicationLifecycleState = {- get windowCreationPromise() {- return windowCreationPromise;- },- set windowCreationPromise(value) {- windowCreationPromise = value;- },- get applicationBooted() {- return applicationBooted;- },- set applicationBooted(value) {- applicationBooted = value;- },- pendingApplicationMenuCommands,- get appliedMenuSettings() {- return appliedMenuSettings;- },- set appliedMenuSettings(value) {- appliedMenuSettings = value;- },-};--const applicationAppearanceState: ApplicationAppearanceState = {- get updaterLocale() {- return updaterLocale;- },- set updaterLocale(value) {- updaterLocale = value;- },- get pluginPanelTheme() {- return pluginPanelTheme;- },- set pluginPanelTheme(value) {- pluginPanelTheme = value;- },- get appThemePreference() {- return appThemePreference;- },- set appThemePreference(value) {- appThemePreference = value;- },- get broadcastAppearanceSignature() {- return broadcastAppearanceSignature;- },- set broadcastAppearanceSignature(value) {- broadcastAppearanceSignature = value;- },-};-applicationLifecycle = createApplicationLifecycle({getRunningSessionIds: () => activeTurns.keys(),state: windowLifecycleState,@@ -908,7 +611,7 @@ applicationLifecycle = createApplicationLifecycle({applyPluginLauncherShortcut: applyPluginLauncherShortcutForLifecycle,applyToggleWindowShortcut: applyToggleWindowShortcutForLifecycle,broadcastPluginPanelEvent,- getHost: () => host,+ getHost,});const {applyDevelopmentBranding,@@ -997,19 +700,8 @@ const pendingExecutionFinishes = new Map<{ status: PlanExecutionFinishStatus; errorCode?: string }>();const inFlightExecutionFinishes = new Set<string>();-let approvedExecutionDrain: Promise<void> | null = null;-const planRuntimeState: PlanRuntimeState = {- get approvedExecutionDrain() {- return approvedExecutionDrain;- },- set approvedExecutionDrain(value) {- approvedExecutionDrain = value;- },-};/** sessionId → scheduled task_run id awaiting completion. */const scheduledRunsBySession = new Map<string, string>();-/** Session currently rendered on the chat page; focus remains Main-owned. */-let notificationViewingSessionId: string | null = null;/** Preserve tool metadata until the result is persisted at tool_end. Subagent* calls also carry their attribution, which is what lets a permission request* name the delegate that asked (ADR 0062). */@@ -1027,8 +719,8 @@ const activeToolCalls = new Map<const sessionCoordination = createSessionCoordination({activeTurns,- getMainWindow: () => mainWindow,- getViewingSessionId: () => notificationViewingSessionId,+ getMainWindow,+ getViewingSessionId: () => mainState.notificationViewingSessionId,});const {turnSettlements,@@ -1045,24 +737,6 @@ const {isStaleTerminalEvent,} = sessionCoordination;-async function withGitBranch<T extends { path?: string; name?: string } | null | undefined>(- workspace: T,-): Promise<T> {- if (!workspace || !workspace.path) return workspace;- try {- const { readFile } = await import("node:fs/promises");- const { join } = await import("node:path");- const head = await readFile(join(workspace.path, ".git/HEAD"), "utf8");- const match = head.match(/ref:\s*refs\/heads\/(.+)$/m);- return {- ...workspace,- branch: match?.[1]?.trim() || "detached",- };- } catch {- return { ...workspace, branch: undefined };- }-}-/*** Applies a close-behavior choice. The tray icon is owned by D216 and stays* resident on every platform, so switching to "quit" must not destroy it —@@ -1077,20 +751,20 @@ const superviseRestart = (kind: "host" | "sidecar"): Promise<void> => {};const planUiProbe = createPlanUiProbe({- getHost: () => host,- getSidecar: () => sidecar,+ getHost,+ getSidecar,logger,});let emitAgentEvent: (envelope: AgentEventEnvelope) => void = () => undefined;const sessionCollaboration = createSessionCollaborationService({- getHost: () => host,- getSidecar: () => sidecar,- getBridge: () => agentHostBridge,+ getHost,+ getSidecar,+ getBridge: () => mainState.agentHostBridge,getActiveTurn: (sessionId) => activeTurns.get(sessionId),flushTranscript: async () => {- await persistenceOutbox.flush(() => host);+ await persistenceOutbox.flush(getHost);return persistenceOutbox.size() === 0;},isPluginLoaded: (pluginId) => plugins.listLoaded().some((plugin) => plugin.manifest.id === pluginId),@@ -1167,7 +841,7 @@ const sidecarRuntime = createSidecarRuntime({isStaleTerminalEvent,finishApprovedExecution,superviseRestart,- isQuitting: () => quitting,+ isQuitting: () => mainState.quitting,dataDir,agentExtensions,vendorOAuth,@@ -1207,7 +881,7 @@ const { wireHost, startHost } = createHostRuntime({claimedExecutionSessions,importLegacyScheduled,superviseRestart,- isQuitting: () => quitting,+ isQuitting: () => mainState.quitting,});runtimeLifecycle = createRuntimeLifecycle({@@ -1223,28 +897,28 @@ runtimeLifecycle = createRuntimeLifecycle({setCurrentWorkspacePath,rememberPluginScopes,refreshUserMcp,- isQuitting: () => quitting,+ isQuitting: () => mainState.quitting,getDisplayLocale: () => applicationAppearanceState.updaterLocale,});const { bootHostStatus, runtimeArch, bootBackends } = runtimeLifecycle;-const voiceService = createVoiceService(dataDir + "/voice-models", () => mainWindow);+const voiceService = createVoiceService(dataDir + "/voice-models", getMainWindow);function registerIpc() {return registerIpcHandlers({traySessions: applicationLifecycle!.traySessions,taskbarUnreadBadge: applicationLifecycle!.taskbarUnreadBadge,ipcMain,- getMainWindow: () => mainWindow,- getHost: () => host,- getSidecar: () => sidecar,- getAgentHostBridge: () => agentHostBridge,+ getMainWindow,+ getHost,+ getSidecar,+ getAgentHostBridge: () => mainState.agentHostBridge,getBackendRouter: () => startupState.backendRouter,- getNotificationViewingSessionId: () => notificationViewingSessionId,+ getNotificationViewingSessionId: () => mainState.notificationViewingSessionId,setNotificationViewingSessionId: (sessionId: string | null) => {- notificationViewingSessionId = sessionId;+ mainState.notificationViewingSessionId = sessionId;},- getPluginLauncherWindow: () => pluginLauncherWindow,+ getPluginLauncherWindow: () => mainState.pluginLauncherWindow,togglePluginLauncher,safeOpenExternal,updater,@@ -1279,20 +953,20 @@ function registerIpc() {agentExtensions,activeUserSkills,pluginActiveInProject,- getWorkPanelReservationWidth: () => requestedWorkPanelReservation,+ getWorkPanelReservationWidth: () => mainState.requestedWorkPanelReservation,setWorkPanelReservationWidth: (width: number) => {- requestedWorkPanelReservation = width;+ mainState.requestedWorkPanelReservation = width;},setWorkPanelReservation: (state: WorkPanelReservationState) => {- workPanelReservation = state;+ mainState.workPanelReservation = state;},- getWorkPanelChatWidthSetter: () => setWorkPanelChatWidthForWindow,+ getWorkPanelChatWidthSetter: () => mainState.setWorkPanelChatWidthForWindow,applyCloseBehavior,- getCloseBehavior: () => closeBehavior,+ getCloseBehavior: () => mainState.closeBehavior,markMenuRendererReady,executeNativeMenuAction,scheduledRunsBySession,- isQuitting: () => quitting,+ isQuitting: () => mainState.quitting,isDevelopmentBuild,browserHost,clipboardHistory,@@ -1320,9 +994,9 @@ function registerIpc() {pluginScopes,rememberPluginScopes,pluginPanels,- getUpdaterLocale: () => updaterLocale,- getPluginPanelTheme: () => pluginPanelTheme,- isDeveloperMode: () => developerMode,+ getUpdaterLocale: () => mainState.updaterLocale,+ getPluginPanelTheme: () => mainState.pluginPanelTheme,+ isDeveloperMode: () => mainState.developerMode,sendToRenderer,voiceService,});@@ -1339,40 +1013,6 @@ app.on("web-contents-created", (_event, contents) => {});});-const startupState: StartupState = {- get applicationBooted() {- return applicationLifecycleState.applicationBooted;- },- set applicationBooted(value) {- applicationLifecycleState.applicationBooted = value;- },- get closeBehavior() {- return closeBehavior;- },- set closeBehavior(value) {- closeBehavior = value;- },- get agentHostBridge() {- return agentHostBridge;- },- set agentHostBridge(value) {- agentHostBridge = value;- },- backendRouter: null,- get desktopControl() {- return desktopControl;- },- set desktopControl(value) {- desktopControl = value;- },- get mcpControl() {- return mcpControl;- },- set mcpControl(value) {- mcpControl = value;- },-};-registerApplicationStartup({hasSingleInstanceLock,state: startupState,@@ -1383,8 +1023,8 @@ registerApplicationStartup({plugins,activeTurns,isSessionBusy,- getHost: () => host,- getMainWindow: () => mainWindow,+ getHost,+ getMainWindow,sendToRenderer,applyDevelopmentBranding,createTray,@@ -1411,63 +1051,12 @@ registerApplicationStartup({},});-const shutdownState: ShutdownState = {- get shutdownComplete() {- return shutdownComplete;- },- set shutdownComplete(value) {- shutdownComplete = value;- },- get shutdownPromise() {- return shutdownPromise;- },- set shutdownPromise(value) {- shutdownPromise = value;- },- get quitting() {- return quitting;- },- set quitting(value) {- quitting = value;- },- get quitConfirmed() {- return quitConfirmed;- },- set quitConfirmed(value) {- quitConfirmed = value;- },- get closeBehavior() {- return closeBehavior;- },- set closeBehavior(value) {- closeBehavior = value;- },- get tray() {- return tray;- },- set tray(value) {- tray = value;- },- get pluginLauncherAccelerator() {- return pluginLauncherAccelerator;- },- set pluginLauncherAccelerator(value) {- pluginLauncherAccelerator = value;- },- get toggleWindowAccelerator() {- return toggleWindowAccelerator;- },- set toggleWindowAccelerator(value) {- toggleWindowAccelerator = value;- },-};-registerShutdownHandlers({hasSingleInstanceLock,state: shutdownState,- getHost: () => host,- getSidecar: () => sidecar,- getMcpControl: () => mcpControl,+ getHost,+ getSidecar,+ getMcpControl: () => mainState.mcpControl,activeTurns,persistenceOutbox,inflightCheckpointer,diff --git a/apps/desktop/electron/main/main-process-errors.ts b/apps/desktop/electron/main/main-process-errors.tsindex e2822be69..0dac2d1e8 100644--- a/apps/desktop/electron/main/main-process-errors.ts+++ b/apps/desktop/electron/main/main-process-errors.ts@@ -128,3 +128,9 @@ export function installMainProcessErrorHandlers(next?: MainProcessErrorSink): voreportMainProcessError("unhandledRejection", reason);});}++/** One-line message for an error of unknown shape, for user-facing lists. */+export function describeError(error: unknown): string {+ if (error instanceof Error) return error.message.slice(0, 300);+ return String(error).slice(0, 300);+}diff --git a/apps/desktop/electron/main/workspace-git.ts b/apps/desktop/electron/main/workspace-git.tsnew file mode 100644index 000000000..d0770134b--- /dev/null+++ b/apps/desktop/electron/main/workspace-git.ts@@ -0,0 +1,21 @@+/**+ * Resolve the active git branch for a workspace path by reading `.git/HEAD`.+ * Returns the enriched workspace object with `branch` set, or undefined if unresolvable.+ */+export async function withGitBranch<T extends { path?: string; name?: string } | null | undefined>(+ workspace: T,+): Promise<T> {+ if (!workspace || !workspace.path) return workspace;+ try {+ const { readFile } = await import("node:fs/promises");+ const { join } = await import("node:path");+ const head = await readFile(join(workspace.path, ".git/HEAD"), "utf8");+ const match = head.match(/ref:\s*refs\/heads\/(.+)$/m);+ return {+ ...workspace,+ branch: match?.[1]?.trim() || "detached",+ };+ } catch {+ return { ...workspace, branch: undefined };+ }+}diff --git a/apps/desktop/src/stores/app-store.ts b/apps/desktop/src/stores/app-store.tsindex d27cbe8cf..c0f42ca93 100644--- a/apps/desktop/src/stores/app-store.ts+++ b/apps/desktop/src/stores/app-store.ts@@ -243,164 +243,33 @@ function promptAttachmentsFromMessage(}));}-// Sessions created before locale switches keep their old default title, so-// match against every locale's defaults (case-insensitive), not just the-// active locale's.-function withoutRecordKey<T>(record: Record<string, T>, key: string): Record<string, T> {- const next = { ...record };- delete next[key];- return next;-}+import {+ withoutRecordKey,+ viewingSessionIdForPrompt,+ messageErrorFromUnknown,+ assistantErrorMessage,+ sessionModeForPlanningState,+ openPlanArtifact,+ decorateSessions,+ promoteProjectPath,+ removeProjectPath,+ upsertWorkspace,+ withProjectDisplayName,+ preferencesFromState,+ withCompactionMark,+} from "./helpers/store-helpers";-function viewingSessionIdForPrompt(- state: Pick<AppState, "page" | "activeSessionId">,- sessionId: string,-): string | null {- return state.page === "chat" && state.activeSessionId === sessionId- ? sessionId- : null;-}+export type AppState = import("./app-state").AppState;export const SESSION_TRANSCRIPT_PAGE_SIZE = 100;export const SESSION_TRANSCRIPT_CONTENT_LIMIT = 64 * 1024;export { RETAINED_SESSION_PANE_LIMIT };-// Preserve the original 320px tool-content minimum beside the 44px activity rail.export { WORK_PANEL_DEFAULT_WIDTH, WORK_PANEL_MIN_WIDTH };-function messageErrorFromUnknown(error: unknown): AppError {- const value = error as {- code?: string;- message?: string;- retriable?: boolean;- };- return {- code: value?.code || "INTERNAL",- message:- error instanceof Error- ? error.message- : typeof value?.message === "string"- ? value.message- : String(error),- retriable: value?.retriable === true,- };-}--function assistantErrorMessage(error: AppError): UiMessage {- return {- id: crypto.randomUUID(),- role: "assistant",- content: "",- createdAt: new Date().toISOString(),- status: "error",- isError: true,- error,- };-}--/** Project planning state and proposal kind determine the durable mode shown in the sidebar. */-function sessionModeForPlanningState(- state: PlanningState,- kind: ProposalKind | undefined,-): Mode {- if (state === "inactive") return "agent";- return modeForProposalKind(kind ?? "plan");-}--export type AppState = import("./app-state").AppState;--function openPlanArtifact(- proposal: PlanProposal,- openWorkPanelTabForSession: AppState["openWorkPanelTabForSession"],- pluginViews: AppState["pluginViews"],-) {- const relativePath = proposal.artifact?.relativePath;- if (!relativePath) return;- openWorkPanelTabForSession(- proposal.sessionId,- preferredFileWorkPanelTab(relativePath, pluginViews),- );-}--function decorateSessions(- sessions: SessionSummary[],- meta: Record<string, SessionMeta>,-): SessionSummary[] {- return sessions.map((session) => ({- ...session,- pinned: sessionIsPinned(session.id, meta),- archived: sessionIsArchived(session.id, meta),- }));-}--function promoteProjectPath(paths: string[], rawPath: string): string[] {- const key = normalizeProjectPath(rawPath);- if (!key) return paths;- const withoutPath = paths.filter(- (path) => normalizeProjectPath(path) !== key,- );- return [...withoutPath, rawPath];-}--function removeProjectPath(paths: string[], rawPath: string): string[] {- const key = normalizeProjectPath(rawPath);- return key- ? paths.filter((path) => normalizeProjectPath(path) !== key)- : paths;-}--function upsertWorkspace(- projects: ProjectWorkspace[],- workspace: ProjectWorkspace,-): ProjectWorkspace[] {- const key = normalizeProjectPath(workspace.path);- if (!key) return projects;- const index = projects.findIndex((item) => normalizeProjectPath(item.path) === key);- if (index < 0) return [...projects, workspace];- const next = projects.slice();- next[index] = { ...next[index], ...workspace };- return next;-}--function withProjectDisplayName(- workspace: ProjectWorkspace,- projectMeta: Record<string, ProjectMeta>,-): ProjectWorkspace {- const key = normalizeProjectPath(workspace.path);- const name = key ? projectMeta[key]?.name : undefined;- return name ? { ...workspace, name } : workspace;-}--function preferencesFromState(state: Pick<- AppState,- | "sessionMeta"- | "projectMeta"- | "projectSort"- | "sessionView"- | "openProjectPaths"->) {- return {- sessionMeta: state.sessionMeta,- projectMeta: state.projectMeta,- projectSort: state.projectSort,- sessionView: state.sessionView,- openProjectPaths: state.openProjectPaths,- };-}-function persistCurrentSidebar(getState: () => AppState): void {saveSidebarPreferences(preferencesFromState(getState()));}-/** Append a freshly installed checkpoint, or replace a retried one by id. */-function withCompactionMark(- marks: AppState["sessionCompactions"][string] | undefined,- mark: AppState["sessionCompactions"][string][number],-): AppState["sessionCompactions"][string] {- const existing = marks?.find((m) => m.id === mark.id);- const merged = { ...mark, summary: mark.summary ?? existing?.summary };- return [...(marks ?? []).filter((m) => m.id !== mark.id), merged];-}-let storeAccess: StoreAccess | null = null;const runtimeStoreAccess: StoreAccess = {get: () => {diff --git a/apps/desktop/src/stores/helpers/store-helpers.ts b/apps/desktop/src/stores/helpers/store-helpers.tsnew file mode 100644index 000000000..63757e545--- /dev/null+++ b/apps/desktop/src/stores/helpers/store-helpers.ts@@ -0,0 +1,201 @@+import type {+ AgentPromptAttachment,+ AppError,+ Mode,+ PlanProposal,+ PlanningState,+ ProjectWorkspace,+ ProposalKind,+ SessionSummary,+ UiMessage,+} from "@pi-desktop/shared";+import { modeForProposalKind } from "@pi-desktop/shared";+import type { ComposerDraftSnapshot } from "../../lib/composer-smart-stop";+import { normalizeProjectPath } from "../../lib/sidebar-session-groups";+import {+ sessionIsArchived,+ sessionIsPinned,+ type ProjectMeta,+ type SessionMeta,+} from "../../lib/sidebar-preferences";+import { preferredFileWorkPanelTab } from "../../lib/work-panel-tabs";+import type { AppState } from "../app-state";++export function promptAttachmentsFromDraft(+ references: ComposerDraftSnapshot["fileReferences"],+): AgentPromptAttachment[] {+ return references.flatMap((reference) => {+ const kind =+ reference.kind ??+ (/\.(avif|bmp|gif|heic|jpe?g|png|tiff?|webp)$/i.test(reference.path)+ ? "image"+ : "file");+ // Inline chips use tokens for both files and images. Ordinary file chips+ // already serialize to @path text (the model can Read them); only image+ // chips need the structured transport for vision/fallback handling.+ if (reference.token && kind !== "image") return [];+ return [+ {+ path: reference.path,+ name: reference.name,+ kind,+ ...(reference.mimeType ? { mimeType: reference.mimeType } : {}),+ },+ ];+ });+}++export function promptAttachmentsFromMessage(+ attachments: UiMessage["attachments"],+): AgentPromptAttachment[] {+ return (attachments ?? []).map((attachment) => ({+ path: attachment.ref,+ name: attachment.name,+ kind: attachment.kind,+ ...(attachment.mimeType ? { mimeType: attachment.mimeType } : {}),+ ...(attachment.size !== undefined ? { size: attachment.size } : {}),+ }));+}++export function withoutRecordKey<T>(record: Record<string, T>, key: string): Record<string, T> {+ const next = { ...record };+ delete next[key];+ return next;+}++export function viewingSessionIdForPrompt(+ state: Pick<AppState, "page" | "activeSessionId">,+ sessionId: string,+): string | null {+ return state.page === "chat" && state.activeSessionId === sessionId+ ? sessionId+ : null;+}++export function messageErrorFromUnknown(error: unknown): AppError {+ const value = error as {+ code?: string;+ message?: string;+ retriable?: boolean;+ };+ return {+ code: value?.code || "INTERNAL",+ message:+ error instanceof Error+ ? error.message+ : typeof value?.message === "string"+ ? value.message+ : String(error),+ retriable: value?.retriable === true,+ };+}++export function assistantErrorMessage(error: AppError): UiMessage {+ return {+ id: crypto.randomUUID(),+ role: "assistant",+ content: "",+ createdAt: new Date().toISOString(),+ status: "error",+ isError: true,+ error,+ };+}++/** Project planning state and proposal kind determine the durable mode shown in the sidebar. */+export function sessionModeForPlanningState(+ state: PlanningState,+ kind: ProposalKind | undefined,+): Mode {+ if (state === "inactive") return "agent";+ return modeForProposalKind(kind ?? "plan");+}++export function openPlanArtifact(+ proposal: PlanProposal,+ openWorkPanelTabForSession: AppState["openWorkPanelTabForSession"],+ pluginViews: AppState["pluginViews"],+) {+ const relativePath = proposal.artifact?.relativePath;+ if (!relativePath) return;+ openWorkPanelTabForSession(+ proposal.sessionId,+ preferredFileWorkPanelTab(relativePath, pluginViews),+ );+}++export function decorateSessions(+ sessions: SessionSummary[],+ meta: Record<string, SessionMeta>,+): SessionSummary[] {+ return sessions.map((session) => ({+ ...session,+ pinned: sessionIsPinned(session.id, meta),+ archived: sessionIsArchived(session.id, meta),+ }));+}++export function promoteProjectPath(paths: string[], rawPath: string): string[] {+ const key = normalizeProjectPath(rawPath);+ if (!key) return paths;+ const withoutPath = paths.filter(+ (path) => normalizeProjectPath(path) !== key,+ );+ return [...withoutPath, rawPath];+}++export function removeProjectPath(paths: string[], rawPath: string): string[] {+ const key = normalizeProjectPath(rawPath);+ return key+ ? paths.filter((path) => normalizeProjectPath(path) !== key)+ : paths;+}++export function upsertWorkspace(+ projects: ProjectWorkspace[],+ workspace: ProjectWorkspace,+): ProjectWorkspace[] {+ const key = normalizeProjectPath(workspace.path);+ if (!key) return projects;+ const index = projects.findIndex((item) => normalizeProjectPath(item.path) === key);+ if (index < 0) return [...projects, workspace];+ const next = projects.slice();+ next[index] = { ...next[index], ...workspace };+ return next;+}++export function withProjectDisplayName(+ workspace: ProjectWorkspace,+ projectMeta: Record<string, ProjectMeta>,+): ProjectWorkspace {+ const key = normalizeProjectPath(workspace.path);+ const name = key ? projectMeta[key]?.name : undefined;+ return name ? { ...workspace, name } : workspace;+}++export function preferencesFromState(state: Pick<+ AppState,+ | "sessionMeta"+ | "projectMeta"+ | "projectSort"+ | "sessionView"+ | "openProjectPaths"+>) {+ return {+ sessionMeta: state.sessionMeta,+ projectMeta: state.projectMeta,+ projectSort: state.projectSort,+ sessionView: state.sessionView,+ openProjectPaths: state.openProjectPaths,+ };+}++/** Append a freshly installed checkpoint, or replace a retried one by id. */+export function withCompactionMark(+ marks: AppState["sessionCompactions"][string] | undefined,+ mark: AppState["sessionCompactions"][string][number],+): AppState["sessionCompactions"][string] {+ const existing = marks?.find((m) => m.id === mark.id);+ const merged = { ...mark, summary: mark.summary ?? existing?.summary };+ return [...(marks ?? []).filter((m) => m.id !== mark.id), merged];+}