Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(windows): staged-host-aware Prepare for update
reviewa0b60afb1e9b
diff --git a/src/core/session-host-backend.ts b/src/core/session-host-backend.tsindex 88328993b..3af430afe 100644--- a/src/core/session-host-backend.ts+++ b/src/core/session-host-backend.ts@@ -17,7 +17,11 @@ import {type SessionHostListing} from './session-host-client'import { SessionHostPty } from './session-host-pty'-import { ensureStagedHostRuntime } from './session-host-runtime'+import {+ ensureStagedHostRuntime,+ resolveHostStaging,+ stagedRuntimeRoot+} from './session-host-runtime'import type {CaptureVisibleResult,ExecuteLaunchResult,@@ -89,6 +93,21 @@ function getClient(): SessionHostClient {.catch(() => undefined)}})+ : undefined,+ // Prepare-for-update (U3): a host running from its staged copy does not block the+ // installer, so the dialog can offer a plain quit. Install dir = where this app's own+ // executable lives; a host older than the state file's `exe` falls back to a process query.+ hostStaging:+ process.platform === 'win32'+ ? (host) =>+ resolveHostStaging({+ exe: host.exe,+ pid: host.pid,+ installDir: path.dirname(process.execPath),+ stagedRoot: process.env.LOCALAPPDATA+ ? stagedRuntimeRoot(process.env.LOCALAPPDATA)+ : null+ }): undefined})}diff --git a/src/core/session-host-client-shutdown.test.ts b/src/core/session-host-client-shutdown.test.tsindex cd9b01741..a8c06b83f 100644--- a/src/core/session-host-client-shutdown.test.ts+++ b/src/core/session-host-client-shutdown.test.ts@@ -36,7 +36,11 @@ function deadPid(): number {return spawnSync(process.execPath, ['-e', '']).pid as number}-function fixture(publish: boolean, pid = deadPid()): { userDataDir: string; endpoint: string } {+function fixture(+ publish: boolean,+ pid = deadPid(),+ extra: Record<string, unknown> = {}+): { userDataDir: string; endpoint: string } {const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-shutdown-client-'))dirs.add(userDataDir)const paths = sessionHostPaths(userDataDir)@@ -49,7 +53,8 @@ function fixture(publish: boolean, pid = deadPid()): { userDataDir: string; endpendpoint: paths.endpoint,tokenPath: paths.tokenPath,startedAt: Date.now(),- protocolVersion: SESSION_HOST_PROTOCOL_VERSION+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION,+ ...extra}))}@@ -120,12 +125,47 @@ describe('SessionHostClient prepare-for-update (issue #829)', () => {await expect(client.inspectForUpdate()).resolves.toEqual({running: true,sessions: ['nt-a', 'nt-b'],- shutdown: false+ shutdown: false,+ // No classifier injected (every non-Windows client): never read as staged.+ staging: 'unknown'})await expect(client.shutdownForUpdate()).resolves.toEqual({ kind: 'unsupported' })expect(requests.some((r) => r.cmd === 'shutdown')).toBe(false)})+ it('classifies the host from the exe its state file publishes, for the pid it is connected to', async () => {+ const exe = 'C:\\Users\\me\\AppData\\Local\\nodeterm\\session-host\\0.4.4-abc\\nodeterm-sessionhost-v2.exe'+ const pid = deadPid()+ const { userDataDir, endpoint } = fixture(true, pid, { exe })+ await fakeHost(userDataDir, endpoint, { shutdown: true })+ const seen: Array<{ exe?: string; pid: number | null }> = []+ const client = new SessionHostClient({+ userDataDir,+ hostStaging: async (host) => {+ seen.push(host)+ return 'staged'+ }+ })+ expect(await client.inspectForUpdate()).toMatchObject({ running: true, staging: 'staged' })+ expect(seen).toEqual([{ exe, pid }])+ })++ it('an old host without exe is passed by pid alone; a throwing classifier is unknown', async () => {+ const pid = deadPid()+ const { userDataDir, endpoint } = fixture(true, pid)+ await fakeHost(userDataDir, endpoint, { shutdown: true })+ const seen: Array<{ exe?: string; pid: number | null }> = []+ const client = new SessionHostClient({+ userDataDir,+ hostStaging: async (host) => {+ seen.push(host)+ throw new Error('query denied')+ }+ })+ expect(await client.inspectForUpdate()).toMatchObject({ running: true, staging: 'unknown' })+ expect(seen).toEqual([{ exe: undefined, pid }])+ })+it('shuts down, confirms the host is gone, and then refuses to reconnect', async () => {const { userDataDir, endpoint } = fixture(true)const requests = await fakeHost(userDataDir, endpoint, { shutdown: true })diff --git a/src/core/session-host-client.ts b/src/core/session-host-client.tsindex ba9025c06..62b5c61fb 100644--- a/src/core/session-host-client.ts+++ b/src/core/session-host-client.ts@@ -51,6 +51,7 @@ export const STAGED_RUNTIME_WAIT_MS = 45_000import { latestClaimSize, type SizeClaim } from './pty-size'import { isTerminalReport } from './terminal-reports'import type { PreparedAgentLaunch } from './agent-launch'+import type { HostImageStaging } from './session-host-runtime'export interface SessionSubscriber {onData(data: string): void@@ -80,7 +81,14 @@ export const TERMINATE_OWNER_REQUEST_TIMEOUT_MS =export type HostUpdateInspection =| { running: false }- | { running: true; sessions: string[]; shutdown: boolean }+ | {+ running: true+ sessions: string[]+ shutdown: boolean+ /** Where the running host's executable lives (`classifyHostImage`). Only `staged` means a+ * plain quit lets the installer run; `unknown` is never read as staged. */+ staging: HostImageStaging+ }/*** What the running host holds, for the observability surfaces (session reaper, session-memory@@ -424,6 +432,9 @@ export class SessionHostClient {repoRoot?: string | null/** Stage (or reuse) a host runtime outside the install directory. Absent = legacy launch. */stageRuntime?: (script: string) => Promise<{ exe: string; script: string } | null>+ /** Classify the running host's image for prepare-for-update (`resolveHostStaging`). Absent+ * (every non-Windows or unpackaged client) ⇒ `unknown`. */+ hostStaging?: (host: { exe?: string; pid: number | null }) => Promise<HostImageStaging>}) {}@@ -2222,7 +2233,25 @@ export class SessionHostClient {if (identity.kind === 'absent') return { running: false }await this.ensureConnected()const result = await this.request<ListSessionsResult>({ cmd: 'listSessions' })- return { running: true, sessions: result.names, shutdown: this.hostShutdownFeature }+ return {+ running: true,+ sessions: result.names,+ shutdown: this.hostShutdownFeature,+ staging: await this.hostStagingFor(identity.state)+ }+ }++ /** The published state names a pid and (newer hosts) an image. Classified only when that pid is+ * the host this client is connected to: a host replaced between the read and the connect is+ * `unknown`, never someone else's answer. Any failure is `unknown`. */+ private async hostStagingFor(state: { pid: number; exe?: string }): Promise<HostImageStaging> {+ const classify = this.deps.hostStaging+ if (!classify || this.hostPid === null || state.pid !== this.hostPid) return 'unknown'+ try {+ return await classify({ exe: state.exe, pid: this.hostPid })+ } catch {+ return 'unknown'+ }}/**diff --git a/src/core/session-host-runtime.test.ts b/src/core/session-host-runtime.test.tsindex 13d28413c..77d85c780 100644--- a/src/core/session-host-runtime.test.ts+++ b/src/core/session-host-runtime.test.ts@@ -7,11 +7,13 @@ import {STAGED_HOST_EXE,RUNTIME_MARKER,SMOKE_OK,+ classifyHostImage,collectStagedRuntimes,ensureStagedHostRuntime,parseProcessJson,planRuntimeFiles,resetStagedHostRuntimeForTests,+ resolveHostStaging,runtimeKey,stageHostRuntime,stagedRuntimeRoot,@@ -276,3 +278,74 @@ describe('parseProcessJson', () => {for (const t of ['', 'not json', '[]', '[1]', '[{"ExecutablePath":"x"}]']) expect(parseProcessJson(t)).toBeNull()})})++describe('parseProcessJson pid', () => {+ it('keeps a positive integer ProcessId and ignores anything else', () => {+ expect(parseProcessJson('[{"Name":"a","ExecutablePath":null,"ProcessId":42},{"Name":"b","ExecutablePath":null,"ProcessId":"7"}]')).toEqual([+ { name: 'a', path: null, pid: 42 },+ { name: 'b', path: null }+ ])+ })+})++// U3: a staged host does not block the installer; everything else keeps the stop flow.+describe('classifyHostImage', () => {+ const install = 'C:\\Users\\me\\AppData\\Local\\Programs\\nodeterm'+ const root = 'C:\\Users\\me\\AppData\\Local\\nodeterm\\session-host'+ const staged = `${root}\\0.4.1-0123456789abcdef\\${STAGED_HOST_EXE}`+ it.each([+ ['staged copy', staged, 'staged'],+ ['mixed case, forward slashes', staged.toUpperCase().replace(/\\/g, '/'), 'staged'],+ ['sibling directory is not under the root', staged.replace('session-host\\', 'session-host-evil\\'), 'unknown'],+ ['staged root but another image name', `${root}\\0.4.1-x\\helper.exe`, 'unknown'],+ ['legacy hard-link host', `${install}\\nodeterm-session-host.exe`, 'install'],+ ['fallback host name anywhere', 'D:\\Other\\nodeterm.exe', 'install'],+ ['staged name inside the installation', `${install}\\${STAGED_HOST_EXE}`, 'install'],+ ['something else entirely', 'C:\\Temp\\x.exe', 'unknown'],+ ['no path', null, 'unknown'],+ ['blank path', ' ', 'unknown']+ ] as const)('%s', (_n, exe, want) => {+ expect(classifyHostImage(exe, install, root)).toBe(want)+ })+ it('an absent staged root never yields staged', () => {+ expect(classifyHostImage(staged, install, null)).toBe('unknown')+ })+})++describe('resolveHostStaging', () => {+ const install = 'C:\\Apps\\nodeterm'+ const root = 'C:\\L\\nodeterm\\session-host'+ const exe = `${root}\\v\\${STAGED_HOST_EXE}`+ it('prefers the published exe and does not query', async () => {+ let asked = false+ const query = async (): Promise<ProcessInfo[]> => {+ asked = true+ return []+ }+ expect(await resolveHostStaging({ exe, pid: 9, installDir: install, stagedRoot: root, query })).toBe('staged')+ expect(asked).toBe(false)+ })+ it('falls back to the process with that pid', async () => {+ const query = async (): Promise<ProcessInfo[]> => [+ { name: 'nodeterm.exe', path: `${install}\\nodeterm.exe`, pid: 8 },+ { name: STAGED_HOST_EXE, path: exe, pid: 9 }+ ]+ expect(await resolveHostStaging({ pid: 9, installDir: install, stagedRoot: root, query })).toBe('staged')+ expect(await resolveHostStaging({ pid: 8, installDir: install, stagedRoot: root, query })).toBe('install')+ expect(await resolveHostStaging({ pid: 7, installDir: install, stagedRoot: root, query })).toBe('unknown')+ })+ it('a failed, throwing or pid-less lookup is unknown', async () => {+ expect(await resolveHostStaging({ pid: 9, installDir: install, stagedRoot: root, query: async () => null })).toBe('unknown')+ expect(+ await resolveHostStaging({+ pid: 9,+ installDir: install,+ stagedRoot: root,+ query: async () => {+ throw new Error('denied')+ }+ })+ ).toBe('unknown')+ expect(await resolveHostStaging({ pid: null, installDir: install, stagedRoot: root, query: async () => [] })).toBe('unknown')+ })+})diff --git a/src/core/session-host-runtime.ts b/src/core/session-host-runtime.tsindex 3a6eb13e4..f89daaaf0 100644--- a/src/core/session-host-runtime.ts+++ b/src/core/session-host-runtime.ts@@ -398,6 +398,8 @@ export async function stageHostRuntime(opts: StageOptions): Promise<StagedHostRuexport interface ProcessInfo {name: stringpath: string | null+ /** Win32_Process.ProcessId, when the query reported one. */+ pid?: number}/** Answers every process, or null when the query failed. */export type ProcessQuery = () => Promise<ProcessInfo[] | null>@@ -413,7 +415,7 @@ export const defaultProcessQuery: ProcessQuery = () =>'-NoProfile','-NonInteractive','-Command',- "$ErrorActionPreference='Stop'; @(Get-CimInstance -ClassName Win32_Process | Select-Object Name, ExecutablePath) | ConvertTo-Json -Compress"+ "$ErrorActionPreference='Stop'; @(Get-CimInstance -ClassName Win32_Process | Select-Object Name, ExecutablePath, ProcessId) | ConvertTo-Json -Compress"],{ windowsHide: true, timeout: 20_000, maxBuffer: 16 * 1024 * 1024 },(err, stdout) => {@@ -436,11 +438,16 @@ export function parseProcessJson(text: string): ProcessInfo[] | null {const out: ProcessInfo[] = []for (const p of list) {if (!p || typeof p !== 'object') return null- const { Name, ExecutablePath } = p as { Name?: unknown; ExecutablePath?: unknown }+ const { Name, ExecutablePath, ProcessId } = p as {+ Name?: unknown+ ExecutablePath?: unknown+ ProcessId?: unknown+ }if (typeof Name !== 'string') return nullout.push({name: Name,- path: typeof ExecutablePath === 'string' && ExecutablePath.trim() ? ExecutablePath : null+ path: typeof ExecutablePath === 'string' && ExecutablePath.trim() ? ExecutablePath : null,+ ...(Number.isInteger(ProcessId) && (ProcessId as number) > 0 ? { pid: ProcessId as number } : {})})}return out@@ -547,6 +554,63 @@ export async function collectStagedRuntimes(opts: CollectOptions): Promise<Collereturn report}+/**+ * Where a RUNNING host's executable lives, for prepare-for-update (U3, issue #829):+ * - `staged` — `STAGED_HOST_EXE` inside the staged runtime root. It maps none of the installed+ * files, so the installer can replace them while the host keeps its sessions:+ * quitting the app is enough.+ * - `install` — inside the installation, or one of the names an installer/uninstaller matches+ * machine-wide (`nodeterm.exe`, `nodeterm-session-host.exe`): it blocks the update.+ * - `unknown` — anything else, including no path at all. Never treated as staged: the caller+ * falls back to today's stop-the-host flow.+ * Windows paths: case-insensitive, either separator, and a directory BOUNDARY (a sibling+ * `session-host-evil\…` is not under `session-host`). Pure; exported for tests.+ */+export type HostImageStaging = 'staged' | 'install' | 'unknown'++export function classifyHostImage(+ exe: string | null | undefined,+ installDir: string | null | undefined,+ stagedRoot: string | null | undefined+): HostImageStaging {+ if (typeof exe !== 'string' || !exe.trim()) return 'unknown'+ const image = norm(exe.trim())+ const base = image.slice(image.lastIndexOf('\\') + 1)+ const under = (dir: string | null | undefined): boolean =>+ typeof dir === 'string' && dir.trim().length > 0 && image.startsWith(norm(dir.trim()) + '\\')+ if (under(installDir) || base === 'nodeterm.exe' || base === 'nodeterm-session-host.exe') {+ return 'install'+ }+ if (base === STAGED_HOST_EXE && under(stagedRoot)) return 'staged'+ return 'unknown'+}++/**+ * Classify the running host from what it published (`exe` in its state file, hosts from this+ * build on) or, for a host that predates that field (0.4.1–0.4.3), from a process query by its+ * pid. A failed, throwing or pid-less query answers `unknown` — fail closed to the stop flow.+ */+export async function resolveHostStaging(opts: {+ exe?: string | null+ pid?: number | null+ installDir: string | null | undefined+ stagedRoot: string | null | undefined+ query?: ProcessQuery+}): Promise<HostImageStaging> {+ if (typeof opts.exe === 'string' && opts.exe.trim()) {+ return classifyHostImage(opts.exe, opts.installDir, opts.stagedRoot)+ }+ if (!Number.isInteger(opts.pid) || (opts.pid as number) <= 0) return 'unknown'+ let processes: ProcessInfo[] | null+ try {+ processes = await (opts.query ?? defaultProcessQuery)()+ } catch {+ return 'unknown'+ }+ const match = processes?.find((p) => p.pid === opts.pid)+ return match ? classifyHostImage(match.path, opts.installDir, opts.stagedRoot) : 'unknown'+}+let memo: { key: string; promise: Promise<StagedHostRuntime | null> } | null = null/**diff --git a/src/main/update-prep.staged.test.ts b/src/main/update-prep.staged.test.tsnew file mode 100644index 000000000..17fbc9435--- /dev/null+++ b/src/main/update-prep.staged.test.ts@@ -0,0 +1,58 @@+// U3: the inspect handler maps the client's host classification onto `staged`. Only an explicit+// `staged` answer may offer the plain-quit path; `install` and `unknown` keep the stop flow.+import { beforeEach, describe, expect, it, vi } from 'vitest'++const { handlers, inspect } = vi.hoisted(() => ({+ handlers: {} as Record<string, (...a: unknown[]) => unknown>,+ inspect: vi.fn()+}))++vi.mock('electron', () => ({+ ipcMain: {+ handle: (ch: string, fn: (...a: unknown[]) => unknown) => {+ handlers[ch] = fn+ },+ on: vi.fn()+ }+}))+vi.mock('../core/session-host-backend', () => ({+ sessionHostInspectForUpdate: inspect,+ sessionHostShutdownForUpdate: vi.fn(),+ sessionHostSupported: () => true+}))+vi.mock('../core/agent-status-mirror', () => ({+ mirrorEntry: () => undefined,+ pendingTicketsFor: () => []+}))++import { registerUpdatePrepIpc } from './update-prep'+import { IPC } from '../shared/ipc'++const event = { sender: { id: 1 } }++beforeEach(() => {+ inspect.mockReset()+ registerUpdatePrepIpc({+ mainWebContents: () => ({ id: 1 }),+ persistentSessions: () => true,+ quit: () => {},+ platform: 'win32'+ })+})++describe('prepare-for-update inspection: staged host (U3)', () => {+ it.each([+ ['staged', true],+ ['install', false],+ ['unknown', false]+ ] as const)('%s → staged=%s', async (staging, staged) => {+ inspect.mockResolvedValue({ running: true, sessions: ['nt-a'], shutdown: true, staging })+ const result = await handlers[IPC.appUpdatePrepInspect](event)+ expect(result).toMatchObject({ kind: 'host', sessions: ['nt-a'], shutdownSupported: true, staged })+ })++ it('no running host stays no-host', async () => {+ inspect.mockResolvedValue({ running: false })+ expect(await handlers[IPC.appUpdatePrepInspect](event)).toEqual({ kind: 'no-host' })+ })+})diff --git a/src/main/update-prep.ts b/src/main/update-prep.tsindex 961f9b967..20eaecb93 100644--- a/src/main/update-prep.ts+++ b/src/main/update-prep.ts@@ -65,7 +65,8 @@ export function registerUpdatePrepIpc(deps: UpdatePrepDeps): void {kind: 'host',sessions: inspection.sessions,shutdownSupported: inspection.shutdown,- mirror+ mirror,+ staged: inspection.staging === 'staged'}} catch (error) {return { kind: 'error', error: error instanceof Error ? error.message : String(error) }diff --git a/src/renderer/components/PrepareUpdateDialog.tsx b/src/renderer/components/PrepareUpdateDialog.tsxindex 5ab1a28af..da8c0f9ba 100644--- a/src/renderer/components/PrepareUpdateDialog.tsx+++ b/src/renderer/components/PrepareUpdateDialog.tsx@@ -2,12 +2,17 @@ import { useCallback, useEffect, useRef, useState } from 'react'import { createPortal } from 'react-dom'import { ConfirmDialog } from './ConfirmDialog'import { useDialogStack } from './dialog-stack'-import { MANUAL_UPDATE_STEPS, type UpdatePrepInspection } from '@shared/update-prep'+import {+ MANUAL_UPDATE_STEPS,+ STAGED_UPDATE_STEPS,+ type UpdatePrepInspection+} from '@shared/update-prep'import { useAgentStatus } from '../state/agentStatus'import { agentUpdateExitFn } from '../terminal/agent-restart'import { RELEASES_URL } from '../state/pendingUpdate'import {planUpdatePrep,+ prepareEntry,updatePrepStopSummary,type PrepNode,type PrepRow,@@ -23,6 +28,8 @@ import {// 3. say plainly what still stops (shells, unreachable agents) and confirm — Cancel is focused;// 4. ask the host to end every session and exit (`shutdown`), confirm it is gone, then quit.// A host from an older build cannot shut itself down: the dialog shows the manual steps instead.+// A host running from its STAGED copy (0.4.1+) does not block the installer at all: the dialog then+// leads with "Quit nodeterm (sessions keep running)", and stopping sessions is the secondary path.// There is no path here that kills the host process or ends a session through node deletion.type Phase =@@ -63,6 +70,8 @@ function rowLabel(row: PrepRow): string {export function PrepareUpdateDialog({ collectNodes, onTravel, onClose }: Props): JSX.Element {const [phase, setPhase] = useState<Phase>({ k: 'inspecting' })const [openDownload, setOpenDownload] = useState(true)+ /** The user chose to stop sessions even though the host is staged (U3). */+ const [stopAnyway, setStopAnyway] = useState(false)const busyRef = useRef(false)const isTop = useDialogStack()@@ -268,6 +277,43 @@ export function PrepareUpdateDialog({ collectNodes, onTravel, onClose }: Props):{manualSteps}</>)+ } else if (prepareEntry(inspection, stopAnyway) === 'quit-keeps-sessions') {+ const count = inspection.kind === 'host' ? inspection.sessions.length : 0+ content = (+ <>+ <p className="confirm__msg">+ Your {count} session{count === 1 ? '' : 's'} can keep running through the update: the+ session host runs from its own copy outside the installation, so it does not block the+ installer.+ </p>+ <ol className="update-prep__list">+ {STAGED_UPDATE_STEPS.map((s) => (+ <li key={s}>{s}</li>+ ))}+ </ol>+ <label className="confirm__option">+ <input+ type="checkbox"+ checked={openDownload}+ onChange={(e) => setOpenDownload(e.target.checked)}+ />+ Open the download page after quitting+ </label>+ </>+ )+ actions = (+ <>+ <button className="confirm__btn" onClick={onClose}>+ Cancel+ </button>+ <button className="confirm__btn" onClick={() => setStopAnyway(true)}>+ Stop all sessions instead…+ </button>+ <button className="confirm__btn primary" autoFocus onClick={quit}>+ Quit nodeterm (sessions keep running)+ </button>+ </>+ )} else if (plan && plan.blocking.length > 0) {content = (<>diff --git a/src/renderer/lib/updatePrep.test.ts b/src/renderer/lib/updatePrep.test.tsindex d9104130e..d1b32dbba 100644--- a/src/renderer/lib/updatePrep.test.ts+++ b/src/renderer/lib/updatePrep.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { planUpdatePrep, updatePrepStopSummary, type PrepNode, type PrepStatus } from './updatePrep'+import { planUpdatePrep, prepareEntry, updatePrepStopSummary, type PrepNode, type PrepStatus } from './updatePrep'const node = (nodeId: string, agentId?: string, extra: Partial<PrepNode> = {}): PrepNode => ({nodeId,@@ -115,3 +115,15 @@ describe('planUpdatePrep (issue #829)', () => {expect(updatePrepStopSummary(p, 1).join('\n')).toContain('1 agent exited cleanly')})})++describe('prepareEntry (U3: staged host)', () => {+ it('offers the plain quit only for a positively staged host', () => {+ expect(prepareEntry({ kind: 'host', staged: true }, false)).toBe('quit-keeps-sessions')+ expect(prepareEntry({ kind: 'host', staged: false }, false)).toBe('stop-sessions')+ expect(prepareEntry({ kind: 'host' }, false)).toBe('stop-sessions')+ expect(prepareEntry({ kind: 'no-host' }, false)).toBe('stop-sessions')+ })+ it('the user can still choose to stop sessions on a staged host', () => {+ expect(prepareEntry({ kind: 'host', staged: true }, true)).toBe('stop-sessions')+ })+})diff --git a/src/renderer/lib/updatePrep.ts b/src/renderer/lib/updatePrep.tsindex fcbebfe30..209ecb310 100644--- a/src/renderer/lib/updatePrep.ts+++ b/src/renderer/lib/updatePrep.ts@@ -182,3 +182,18 @@ export function updatePrepStopSummary(plan: UpdatePrepPlan, exited: number): strlines.push('Canvas nodes are kept. Agents resume with --resume on the next launch.')return lines}++/**+ * The prepare dialog's first screen for a running host (U3). A host running from its STAGED copy+ * (0.4.1+) maps none of the installed files, so a plain quit lets the installer run and every+ * session keeps running — that is offered first, and stopping sessions becomes the explicit+ * secondary path (`stopAnyway`). A legacy/install-dir host, or one whose location is unknown,+ * keeps the stop flow unchanged: `staged` is only ever true on a positive classification.+ */+export type PrepareEntry = 'quit-keeps-sessions' | 'stop-sessions'++export function prepareEntry(inspection: { kind: string; staged?: boolean }, stopAnyway: boolean): PrepareEntry {+ return inspection.kind === 'host' && inspection.staged === true && !stopAnyway+ ? 'quit-keeps-sessions'+ : 'stop-sessions'+}diff --git a/src/session-host/existing-host-state.test.ts b/src/session-host/existing-host-state.test.tsindex 8df4d30d0..7ea63f9cd 100644--- a/src/session-host/existing-host-state.test.ts+++ b/src/session-host/existing-host-state.test.ts@@ -51,6 +51,22 @@ describe('existing session-host ownership reads', () => {})})+ it('keeps a published exe and drops a malformed one without refusing the state', () => {+ const withExe = (exe: unknown): string =>+ JSON.stringify({ ...JSON.parse(validState), exe })+ const read = (raw: string) =>+ readExistingSessionHostIdentity(statePath, options(reader({ [statePath]: raw, [tokenPath]: bearerToken })))+ expect(read(withExe('C:\\x\\nodeterm-sessionhost-v2.exe'))).toMatchObject({+ kind: 'ready',+ state: { exe: 'C:\\x\\nodeterm-sessionhost-v2.exe' }+ })+ for (const bad of [42, '', ' ', null]) {+ const result = read(withExe(bad))+ expect(result.kind).toBe('ready')+ expect(result.kind === 'ready' && 'exe' in result.state).toBe(false)+ }+ })+it.each(['state', 'token'] as const)('treats only an ENOENT %s file as absent', (missing) => {const entries: Record<string, string | Error> = {[statePath]: missing === 'state' ? codedError('ENOENT') : validState,diff --git a/src/session-host/existing-host-state.ts b/src/session-host/existing-host-state.tsindex 367e6a472..f2f82e42c 100644--- a/src/session-host/existing-host-state.ts+++ b/src/session-host/existing-host-state.ts@@ -78,6 +78,11 @@ function parseState(raw: string): SessionHostState {) {throw invalidState('protocolVersion must be a positive integer')}+ // Optional and advisory (prepare-for-update only): a malformed value is dropped, never fatal —+ // refusing the whole state over it would make a working host unreachable.+ if (state.exe !== undefined && (typeof state.exe !== 'string' || state.exe.trim().length === 0)) {+ delete state.exe+ }return state as SessionHostState}diff --git a/src/session-host/host.ts b/src/session-host/host.tsindex a129b6e48..99b933fb2 100644--- a/src/session-host/host.ts+++ b/src/session-host/host.ts@@ -1362,7 +1362,8 @@ async function main(): Promise<void> {endpoint: paths.endpoint,tokenPath: paths.tokenPath,startedAt: Date.now(),- protocolVersion: currentProtocolVersion()+ protocolVersion: currentProtocolVersion(),+ exe: process.execPath}// Replace the empty startup-lock file atomically from a temp owned by THIS process. A fixed// `.tmp` lets racing/stale-reclaim hosts publish or remove one another's bytes; a bare renamediff --git a/src/session-host/paths.ts b/src/session-host/paths.tsindex 36c085324..66983956f 100644--- a/src/session-host/paths.ts+++ b/src/session-host/paths.ts@@ -52,6 +52,10 @@ export interface SessionHostState {tokenPath: stringstartedAt: numberprotocolVersion: number+ /** The host's own `process.execPath` (additive; absent from hosts before it was published).+ * Read only by prepare-for-update to tell a staged host from one that holds the install+ * directory — never to locate, launch or kill anything. */+ exe?: string}export function currentProtocolVersion(): number {diff --git a/src/session-host/shutdown-host.test.ts b/src/session-host/shutdown-host.test.tsindex 472f577ed..4b5df846d 100644--- a/src/session-host/shutdown-host.test.ts+++ b/src/session-host/shutdown-host.test.ts@@ -182,6 +182,18 @@ async function hello(conn: Connection, token: string, features?: string[]): Prom}describe('session-host shutdown (issue #829)', () => {+ // U3: prepare-for-update tells a staged host (a plain quit is enough) from one that holds the+ // installation by the image the host itself publishes. No kill involved, so it runs on Windows.+ it('publishes its own executable in the state file', async () => {+ const { child, state } = await startHost()+ try {+ expect(state.exe).toBe(process.execPath)+ } finally {+ child.kill()+ await waitForExit(child)+ }+ })+posixKillPath('ends every session, replies with their names, then exits and removes its identity', async () => {const { child, dataDir, state, token } = await startHost()const sockets: Socket[] = []diff --git a/src/shared/update-prep.ts b/src/shared/update-prep.tsindex fdb8e7fad..bd4b58166 100644--- a/src/shared/update-prep.ts+++ b/src/shared/update-prep.ts@@ -21,6 +21,10 @@ export type UpdatePrepInspection =* on screen (an unmounted node's renderer state is cleared). `attention` = an unanswered* question or approval ticket is held. */mirror: Record<string, { state?: string; attention: boolean }>+ /** The host runs from its staged copy outside the installation (0.4.1+), so it does not+ * block the installer: quitting nodeterm — from the tray too — is enough, and sessions keep+ * running. False for a legacy/install-dir host AND for one whose location is unknown. */+ staged: boolean}| { kind: 'error'; error: string }@@ -36,6 +40,14 @@ export type UpdatePrepShutdown =/** The host predates the `shutdown` feature. */| { kind: 'host-unsupported' }+/** The steps for a STAGED host: nothing has to stop. Kept beside the legacy steps so the dialog,+ * the installer text and the docs say the same thing. */+export const STAGED_UPDATE_STEPS: readonly string[] = [+ 'Quit nodeterm — if it keeps running in the system tray, right-click the tray icon and choose Quit.',+ 'Run the installer. Your sessions keep running in the background session host and reattach when nodeterm starts again.',+ 'Only if the installer still says nodeterm is running: reopen nodeterm and use Prepare for update to stop the sessions.'+]+/** The manual steps, for a host that cannot shut itself down (or did not confirm it did). Kept in* one place so the dialog and the docs say the same thing. */export const MANUAL_UPDATE_STEPS: readonly string[] = [