Skip to content

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.

feat(windows): in-app "Prepare for update" + session-host shutdown command (#829)

review83827a27ef3e
diff --git a/CLAUDE.md b/CLAUDE.md
index 35ed39d83..1eebac9ee 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -8573,6 +8573,36 @@ verify and stop any remaining host. Never recommend **End session** (it deletes
resume depends on supported, saved conversation history; it does not preserve running tasks.
See `docs/windows-session-host.md` for the user-controlled preparation/recovery steps and limits.
+**Prepare for update (#829 step 2).** The in-app answer to the refusal above, Windows only.
+Rules a refactor must not undo:
+- **The host's `shutdown` command is the only thing that stops the host**, and only on a connection
+ that negotiated the `shutdown` hello feature (`SESSION_HOST_FEATURES`). An older host answers
+ `host-unsupported` and the dialog shows `MANUAL_UPDATE_STEPS` — never a taskkill/name-based
+ fallback from the app. The host ends every session through the SAME `handleKill` path (taskkill
+ of the tree, then node-pty's onExit as proof), refuses attach/attachExisting/executeLaunch while
+ it runs, bounds each kill at 20 s, and on ANY unconfirmed kill answers `ok:false` naming the
+ sessions and keeps serving. It exits only after the success reply is flushed (`socket.end`), and
+ removes its state/token files. It touches no node metadata; nodes cold-restore next launch.
+- **Inspection never launches a host** (`SessionHostClient.inspectForUpdate` /
+ `shutdownForUpdate` read the published state first; absent = `no-host`). Once `shutdown` is
+ sent the client latches `shutDownForUpdate` so a dropped connection cannot reconnect into a
+ freshly launched host that re-locks the install dir; only the host's explicit refusal (or a frame
+ provably never sent) clears it. "Shut down" means reply AND state file gone AND pid dead.
+- **Busy blocks, from either source**: `planUpdatePrep` (`renderer/lib/updatePrep.ts`, pure)
+ refuses on working / waiting / blocked / a held question or approval ticket, read from the
+ renderer store AND core's mirror (`app:update-prep-inspect` carries `mirror` per session) — an
+ unmounted node's renderer state is cleared, so the mirror is the only witness for closed/other
+ projects. Only a MOUNTED node can be asked to quit (`registerAgentUpdateExit` in TerminalNode:
+ Pause's exit half with its refusals, marking SLEEPING not PAUSED so cold restore resumes it);
+ every other agent is disclosed as "stopped without a clean exit".
+- The confirm is a danger `ConfirmDialog` with `enterConfirms={false}` (Cancel focused) and says
+ plainly that shells and their unsaved work stop and that nodes are kept. Never route anything
+ through End session / node deletion.
+- IPC (`app:update-prep-*`) is raw `ipcMain`, main-window senders only, and in
+ `HOST_ONLY_CHANNELS`. Server Edition: the bridge stub answers `unsupported` (Linux tmux, no
+ installer; a browser must never end every session on the server). Mobile: N/A — a phone cannot
+ authorize an update shutdown; it sees its sessions end like any other end.
+
**Follow-ups, in order:** code signing, then Windows auto-update wiring (electron-updater NSIS leg
+ `latest.yml` on the nodeterm.dev feed — blocked on signing: an unsigned auto-update is a
downgrade in trust), and the fork's PE-identity polish (electron-builder leaves `OriginalFilename`
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index cafbf9fdc..66a258c63 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -93,6 +93,15 @@ verify and stop any remaining host. Never recommend **End session** (it deletes
resume depends on supported, saved conversation history; it does not preserve running tasks.
See `docs/windows-session-host.md` for the user-controlled preparation/recovery steps and limits.
+**Prepare for update** (#829 step 2, Windows only): ⌘K / the update card run
+`components/PrepareUpdateDialog.tsx` over the pure `lib/updatePrep.ts` plan. It refuses while any
+session's agent is working or waiting on the user (renderer store OR core mirror — unmounted nodes
+have no renderer state), asks idle mounted agents to `/exit` through `registerAgentUpdateExit`,
+confirms what still stops (Cancel focused), then sends the host's `shutdown` command and quits only
+once the host process is confirmed gone. `shutdown` is a negotiated hello feature: never send it to
+a host that did not advertise it, and never add a taskkill/name-kill fallback — an older host gets
+the manual steps. The flow never deletes a node. Server Edition: degraded stub (`unsupported`).
+
## Three surfaces
A feature is not done until you have decided how it behaves on each — even if the decision is "not
diff --git a/build/installer.nsh b/build/installer.nsh
index e70ab69b7..ee6e81e65 100644
--- a/build/installer.nsh
+++ b/build/installer.nsh
@@ -13,7 +13,7 @@
SetErrorLevel 2
IfSilent nodeterm_preflight_cancel
${If} $R0 == 10
- MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "nodeterm or a process using its installation is running. Closing the app keeps sessions alive.$\r$\n$\r$\nCancel to save work in every local session. Exit agents and shells normally; keep canvas nodes. Quit nodeterm and wait at least 30 seconds.$\r$\n$\r$\nIf the host remains, verify its user and executable path in Task Manager Details, then end only that host. All processes it owns will stop. Saved nodes remain; agent resume needs supported, saved conversation history and cannot recover unsaved work.$\r$\n$\r$\nOther installations/users must prepare their own sessions too. Retry from Downloads, outside the install directory. This installer will not stop your sessions for you." /SD IDCANCEL IDRETRY nodeterm_preflight_retry
+ MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "nodeterm or a process using its installation is running. Closing the app keeps sessions alive.$\r$\n$\r$\nCancel, open nodeterm, and run Prepare for update (Ctrl+K, or the update card): it waits for busy agents, exits idle agents cleanly, stops the session host and quits. Canvas nodes are kept.$\r$\n$\r$\nWith an older nodeterm: save work, exit agents and shells normally, quit nodeterm and wait at least 30 seconds. If the host remains, verify its user and executable path in Task Manager Details, then end only that host. All processes it owns will stop. Saved nodes remain; agent resume needs supported, saved conversation history and cannot recover unsaved work.$\r$\n$\r$\nOther installations/users must prepare their own sessions too. Retry from Downloads, outside the install directory. This installer will not stop your sessions for you." /SD IDCANCEL IDRETRY nodeterm_preflight_retry
${Else}
MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "nodeterm could not verify whether the app or its background session host is running. No sessions have been stopped.$\r$\n$\r$\nCancel and check that Windows PowerShell and process queries are available. If another Windows user is running nodeterm, ask them to save work, exit agents and shells normally, and quit nodeterm. If their host remains, its owner must verify and stop it in Task Manager before retrying; keep saved canvas nodes." /SD IDCANCEL IDRETRY nodeterm_preflight_retry
${EndIf}
diff --git a/docs/windows-session-host.md b/docs/windows-session-host.md
index d8fe9cdba..1d2069b44 100644
--- a/docs/windows-session-host.md
+++ b/docs/windows-session-host.md
@@ -418,7 +418,28 @@ path prefix without a directory boundary. Another installation (even a sibling d
name begins with this installation's name) can therefore block an update. The new preflight must
cover those legacy targets before invoking the old executable; it never stops them on your behalf.
-To update while keeping your saved canvas:
+**The in-app way (nodeterm with the `shutdown` host feature):** open the command palette
+(Ctrl+K) → **Prepare for update…**, or the button on the update card. It:
+
+1. lists every session the host holds — every project, closed ones too — and waits while any agent
+ is working or waiting for your answer (each listed with a **Go** button; **Check again** when
+ it is done);
+2. asks each idle agent whose terminal is open on the canvas to exit normally (`/exit`, `/quit`;
+ Gemini's bare `/quit`, never `--delete`) so its conversation is saved, and reports any that did
+ not;
+3. shows what will still stop — shells and anything running in them (unsaved work there is lost),
+ agents it could not exit — and asks you to confirm (Cancel is the default);
+4. sends the host its `shutdown` command: the host ends every session with its ordinary kill path,
+ replies, removes its state files and exits. nodeterm confirms the process is gone, then quits
+ (optionally opening the download page).
+
+Canvas nodes are kept; on the next launch every terminal cold-starts and agents resume with
+`--resume` where their CLI and saved history allow. If the host cannot end a session it says which
+and keeps running — nothing is quit. A host started by an older nodeterm does not have the
+command; the dialog then shows the manual steps below. nodeterm never kills the host process
+itself. The installer's own refusal is unchanged.
+
+To update by hand (older host, or the in-app flow did not finish), while keeping your saved canvas:
1. Cancel the installer and reopen nodeterm if you already quit it. Save work in every local
terminal and agent, including closed/other projects and sessions accessed from a phone.
diff --git a/src/core/session-host-backend.ts b/src/core/session-host-backend.ts
index aa80eedeb..8e9ee810c 100644
--- a/src/core/session-host-backend.ts
+++ b/src/core/session-host-backend.ts
@@ -8,7 +8,9 @@ import type { TextDeliveryResult } from '../shared/text-delivery'
import { platform } from './platform'
import {
SessionHostClient,
- SessionHostProtocolCompatibilityError
+ SessionHostProtocolCompatibilityError,
+ type HostShutdownOutcome,
+ type HostUpdateInspection
} from './session-host-client'
import { SessionHostPty } from './session-host-pty'
import type { ExecuteLaunchResult, SessionHostSpawnOptions } from '../session-host/protocol'
@@ -141,3 +143,13 @@ export async function sessionHostHasSession(name: string): Promise<boolean> {
export async function sessionHostListSessions(): Promise<string[]> {
return getClient().listSessions()
}
+
+/** Prepare-for-update (issue #829): what the running host holds, without ever launching one. */
+export async function sessionHostInspectForUpdate(): Promise<HostUpdateInspection> {
+ return getClient().inspectForUpdate()
+}
+
+/** Prepare-for-update (issue #829): ask the running host to end every session and exit. */
+export async function sessionHostShutdownForUpdate(): Promise<HostShutdownOutcome> {
+ return getClient().shutdownForUpdate()
+}
diff --git a/src/core/session-host-client-geometry.test.ts b/src/core/session-host-client-geometry.test.ts
index 513cae2c8..17c1ac92b 100644
--- a/src/core/session-host-client-geometry.test.ts
+++ b/src/core/session-host-client-geometry.test.ts
@@ -210,7 +210,7 @@ describe('SessionHostClient geometry (issue #914)', () => {
const client = new SessionHostClient({ userDataDir })
await view(client, userDataDir, 80, 24)
const hello = host.requests.find((request) => request.cmd === 'hello')
- expect(hello).toMatchObject({ features: ['geometry'] })
+ expect((hello as { features?: string[] }).features).toContain('geometry')
})
it('gives the session to a view that types, but not to one that only answers a query', async () => {
diff --git a/src/core/session-host-client-shutdown.test.ts b/src/core/session-host-client-shutdown.test.ts
new file mode 100644
index 000000000..cd9b01741
--- /dev/null
+++ b/src/core/session-host-client-shutdown.test.ts
@@ -0,0 +1,159 @@
+// Issue #829: the client half of prepare-for-update. Drives the real SessionHostClient against a
+// fake host over a real socket. The rules: inspection never LAUNCHES a host; `shutdown` is sent
+// only to a host that advertised it; only a reply plus a gone process counts as shut down; a host
+// that refused stays usable; and once shut down, nothing reconnects (which would launch a new host
+// and re-lock the install directory).
+import fs from 'fs'
+import net from 'net'
+import os from 'os'
+import path from 'path'
+import { spawnSync } from 'child_process'
+import { afterEach, describe, expect, it } from 'vitest'
+import { sessionHostPaths } from '../session-host/paths'
+import {
+ SESSION_HOST_PROTOCOL_VERSION,
+ LineFramer,
+ encodeFrame,
+ type SessionHostRequest
+} from '../session-host/protocol'
+import { SessionHostClient } from './session-host-client'
+
+const servers = new Set<net.Server>()
+const sockets = new Set<net.Socket>()
+const dirs = new Set<string>()
+
+afterEach(() => {
+ for (const s of sockets) s.destroy()
+ sockets.clear()
+ for (const s of servers) s.close()
+ servers.clear()
+ for (const d of dirs) fs.rmSync(d, { recursive: true, force: true })
+ dirs.clear()
+})
+
+/** A pid that is certainly not running any more. */
+function deadPid(): number {
+ return spawnSync(process.execPath, ['-e', '']).pid as number
+}
+
+function fixture(publish: boolean, pid = deadPid()): { userDataDir: string; endpoint: string } {
+ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-shutdown-client-'))
+ dirs.add(userDataDir)
+ const paths = sessionHostPaths(userDataDir)
+ if (publish) {
+ fs.writeFileSync(paths.tokenPath, 'a'.repeat(64))
+ fs.writeFileSync(
+ paths.statePath,
+ JSON.stringify({
+ pid,
+ endpoint: paths.endpoint,
+ tokenPath: paths.tokenPath,
+ startedAt: Date.now(),
+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION
+ })
+ )
+ }
+ return { userDataDir, endpoint: paths.endpoint }
+}
+
+async function fakeHost(
+ userDataDir: string,
+ endpoint: string,
+ opts: { shutdown: boolean; refuse?: boolean }
+): Promise<SessionHostRequest[]> {
+ const requests: SessionHostRequest[] = []
+ const server = net.createServer((socket) => {
+ sockets.add(socket)
+ const framer = new LineFramer()
+ socket.on('data', (chunk: Buffer) => {
+ for (const req of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {
+ requests.push(req)
+ const reply = (body: Record<string, unknown>): void => {
+ socket.write(encodeFrame({ id: req.id, ...body }))
+ }
+ if (req.cmd === 'hello') {
+ reply({
+ ok: true,
+ result: {
+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION,
+ features: opts.shutdown ? ['geometry', 'shutdown'] : ['geometry']
+ }
+ })
+ } else if (req.cmd === 'listSessions') {
+ reply({ ok: true, result: { names: ['nt-a', 'nt-b'] } })
+ } else if (req.cmd === 'shutdown') {
+ if (opts.refuse) {
+ reply({ ok: false, error: 'session-host could not end: nt-b' })
+ } else {
+ reply({ ok: true, result: { ended: ['nt-a', 'nt-b'] } })
+ const paths = sessionHostPaths(userDataDir)
+ fs.rmSync(paths.statePath, { force: true })
+ fs.rmSync(paths.tokenPath, { force: true })
+ socket.end()
+ server.close()
+ }
+ } else {
+ reply({ ok: true })
+ }
+ }
+ })
+ })
+ servers.add(server)
+ await new Promise<void>((resolve) => server.listen(endpoint, resolve))
+ return requests
+}
+
+describe('SessionHostClient prepare-for-update (issue #829)', () => {
+ it('reports no host and never launches one when nothing is published', async () => {
+ const { userDataDir } = fixture(false)
+ // No bundle paths: a launch attempt would throw "bundle not found" instead of answering.
+ const client = new SessionHostClient({ userDataDir })
+ await expect(client.inspectForUpdate()).resolves.toEqual({ running: false })
+ await expect(client.shutdownForUpdate()).resolves.toEqual({ kind: 'no-host' })
+ expect(fs.existsSync(sessionHostPaths(userDataDir).statePath)).toBe(false)
+ })
+
+ it('never sends shutdown to a host that did not advertise it', async () => {
+ const { userDataDir, endpoint } = fixture(true)
+ const requests = await fakeHost(userDataDir, endpoint, { shutdown: false })
+ const client = new SessionHostClient({ userDataDir })
+ await expect(client.inspectForUpdate()).resolves.toEqual({
+ running: true,
+ sessions: ['nt-a', 'nt-b'],
+ shutdown: false
+ })
+ await expect(client.shutdownForUpdate()).resolves.toEqual({ kind: 'unsupported' })
+ expect(requests.some((r) => r.cmd === 'shutdown')).toBe(false)
+ })
+
+ 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 })
+ const client = new SessionHostClient({ userDataDir })
+ expect(await client.inspectForUpdate()).toMatchObject({ shutdown: true })
+ await expect(client.shutdownForUpdate({ exitWaitMs: 2_000 })).resolves.toEqual({
+ kind: 'shut-down',
+ ended: ['nt-a', 'nt-b']
+ })
+ expect(requests.filter((r) => r.cmd === 'shutdown')).toHaveLength(1)
+ await expect(client.listSessions()).rejects.toThrow(/shut down to prepare for an update/)
+ })
+
+ it('reports a host that is still alive after its reply as unconfirmed', async () => {
+ const { userDataDir, endpoint } = fixture(true, process.pid)
+ await fakeHost(userDataDir, endpoint, { shutdown: true })
+ const client = new SessionHostClient({ userDataDir })
+ const outcome = await client.shutdownForUpdate({ exitWaitMs: 300 })
+ expect(outcome.kind).toBe('unconfirmed')
+ })
+
+ it('a host that refused is still usable', async () => {
+ const { userDataDir, endpoint } = fixture(true)
+ await fakeHost(userDataDir, endpoint, { shutdown: true, refuse: true })
+ const client = new SessionHostClient({ userDataDir })
+ const outcome = await client.shutdownForUpdate()
+ expect(outcome).toMatchObject({ kind: 'failed' })
+ expect((outcome as { error: string }).error).toContain('nt-b')
+ await expect(client.listSessions()).resolves.toEqual(['nt-a', 'nt-b'])
+ })
+})
diff --git a/src/core/session-host-client.ts b/src/core/session-host-client.ts
index 6aeb2d7fd..48052ce38 100644
--- a/src/core/session-host-client.ts
+++ b/src/core/session-host-client.ts
@@ -4,6 +4,7 @@ import type { TextDeliveryResult } from '../shared/text-delivery'
// ordinary traffic through a replacement connection.
import net from 'net'
+import fs from 'fs'
import type { PaneOwner } from '../shared/agents/pane-owner-predicate'
import { randomUUID } from 'crypto'
// The REAL scheduler, immune to vi.useFakeTimers (which patches the global, not this module's
@@ -33,7 +34,8 @@ import {
type CaptureResult,
type KillSessionResult,
type ExecuteLaunchResult,
- type ListSessionsResult
+ type ListSessionsResult,
+ type ShutdownResult
} from '../session-host/protocol'
import { resolveSessionHostScript, spawnSessionHost } from './session-host-launcher'
import { latestClaimSize, type SizeClaim } from './pty-size'
@@ -54,6 +56,51 @@ export interface SessionSubscriber {
}
export const SESSION_HOST_REQUEST_TIMEOUT_MS = 10_000
+/** A `shutdown` ends every session (each kill confirmed by the host within its own 20 s bound),
+ * so it gets a longer deadline than an ordinary request. */
+export const SHUTDOWN_REQUEST_TIMEOUT_MS = 45_000
+
+export type HostUpdateInspection =
+ | { running: false }
+ | { running: true; sessions: string[]; shutdown: boolean }
+
+export type HostShutdownOutcome =
+ | { kind: 'no-host' }
+ | { kind: 'unsupported' }
+ | { kind: 'shut-down'; ended: string[] }
+ | { kind: 'failed'; error: string }
+ | { kind: 'unconfirmed'; error: string }
+
+function pidAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0)
+ return true
+ } catch (error) {
+ // EPERM: the pid exists but belongs to someone else — still alive as far as a lock goes.
+ return (error as NodeJS.ErrnoException).code === 'EPERM'
+ }
+}
+
+/** Bounded wait for a host that answered `shutdown` to be gone: its state file removed (it deletes
+ * it on the way out) AND, when its pid is known, that pid no longer running. */
+async function waitForHostExit(
+ statePath: string,
+ pid: number | null,
+ waitMs: number
+): Promise<boolean> {
+ const deadline = Date.now() + waitMs
+ for (;;) {
+ let stateGone = false
+ try {
+ fs.statSync(statePath)
+ } catch (error) {
+ stateGone = (error as NodeJS.ErrnoException).code === 'ENOENT'
+ }
+ if (stateGone && (pid === null || !pidAlive(pid))) return true
+ if (Date.now() >= deadline) return false
+ await sleep(100)
+ }
+}
const RECONNECT_DELAYS_MS = [50, 100, 250, 500, 1_000, 2_000] as const
const RECONNECT_REPAINT_PREFIX = '\x1b[3J\x1b[2J\x1b[H'
@@ -245,6 +292,17 @@ export class SessionHostClient {
* size. On a host that predates it, the size this client last requested IS the pty's size as
* long as this is the host's only connection — the common case, and the one issue #914 is. */
private hostGeometryEvents = false
+ /** The current connection negotiated `shutdown` (issue #829): only then may prepare-for-update
+ * ask the host to end every session and exit. An older host lacks it, and the app then falls
+ * back to the manual steps — never to killing the host itself. */
+ private hostShutdownFeature = false
+ /** The pid the host published in its state file for the current connection. Read only to
+ * confirm a shutdown actually ended the process. */
+ private hostPid: number | null = null
+ /** Latched once a `shutdown` was sent: the app is about to quit for an update, and a reconnect
+ * must not LAUNCH a fresh host (which would re-lock the install directory). Cleared again only
+ * when the host answered that it could not end everything and is still serving. */
+ private shutDownForUpdate = false
/** Monotonic activity clock for `SizeClaim.recency`. */
private claimClock = 0
private nextId = 1
@@ -377,6 +435,9 @@ export class SessionHostClient {
}
private async ensureConnected(): Promise<void> {
+ if (this.shutDownForUpdate) {
+ throw new Error('session-host was shut down to prepare for an update; restart nodeterm')
+ }
// A newly authenticated socket is visible while its reconnect restoration is still running.
// The barrier wins over the raw socket check so no later request can overtake replay.
if (this.connecting) return this.connecting
@@ -510,6 +571,7 @@ export class SessionHostClient {
const helloId = this.nextId++
let protocolVersion: 1 | 2 | null = null
let geometryEvents = false
+ let shutdownFeature = false
const finish = (ok: boolean, trailing: SessionHostFrame[] = []): void => {
if (settled) return
settled = true
@@ -523,6 +585,8 @@ export class SessionHostClient {
failHandshake(new Error('session-host hello did not negotiate a protocol version'))
return
}
+ this.hostShutdownFeature = shutdownFeature
+ this.hostPid = Number.isInteger(identity.state.pid) ? identity.state.pid : null
this.attachSocket(socket, protocolVersion, geometryEvents)
for (const frame of trailing) this.handleFrame(socket, frame)
} else {
@@ -619,6 +683,7 @@ export class SessionHostClient {
protocolVersion = negotiated
const features = (frame.result as HelloResult | undefined)?.features
geometryEvents = Array.isArray(features) && features.includes('geometry')
+ shutdownFeature = Array.isArray(features) && features.includes('shutdown')
finish(true, frames.slice(index + 1))
} else {
failHandshake(new Error(`session-host hello rejected: ${frame.error}`))
@@ -842,7 +907,8 @@ export class SessionHostClient {
private async request<T>(
request: SessionHostRequestBody,
onSuccess?: (result: T, socket: net.Socket) => void,
- onSent?: () => void
+ onSent?: () => void,
+ timeoutMs = SESSION_HOST_REQUEST_TIMEOUT_MS
): Promise<T> {
// A peer-initiated close races the client's own 'close' event: a cached socket can look live
// here while the peer already hung up, and a frame written into that gap fails (EPIPE) for
@@ -863,7 +929,7 @@ export class SessionHostClient {
const socket = this.socket
if (!socket) throw new Error('session-host: not connected')
try {
- return await this.requestOnSocket(socket, request, onSuccess, onSent)
+ return await this.requestOnSocket(socket, request, onSuccess, onSent, timeoutMs)
} catch (error) {
if (!(error instanceof SessionHostRequestNotDeliveredError)) throw error
if (attempt + 1 >= SESSION_HOST_RESEND_ATTEMPTS) throw error.original
@@ -878,7 +944,8 @@ export class SessionHostClient {
socket: net.Socket,
request: SessionHostRequestBody,
onSuccess?: (result: T, socket: net.Socket) => void,
- onSent?: () => void
+ onSent?: () => void,
+ timeoutMs = SESSION_HOST_REQUEST_TIMEOUT_MS
): Promise<T> {
if (this.socket !== socket || socket.destroyed) {
return Promise.reject(
@@ -911,7 +978,7 @@ export class SessionHostClient {
this.pending.delete(id)
pending.reject(deadline)
this.dropSocket(socket, deadline, true)
- }, SESSION_HOST_REQUEST_TIMEOUT_MS)
+ }, timeoutMs)
pending.timer.unref?.()
this.pending.set(id, pending)
// The send is deferred one REAL event-loop turn (immune to fake timers — the deadline above
@@ -1794,6 +1861,87 @@ export class SessionHostClient {
this.stopReconnectIfIdle()
}
+ /**
+ * Prepare-for-update, step 1 (issue #829): is a host running, which sessions does it hold, and
+ * can it shut itself down? NEVER launches a host: with no published state file there is nothing
+ * to ask, and starting one just to answer would re-lock the very directory the update needs.
+ */
+ async inspectForUpdate(): Promise<HostUpdateInspection> {
+ const paths = sessionHostPaths(this.deps.userDataDir)
+ const identity = readExistingSessionHostIdentity(paths.statePath, {
+ expectedEndpoint: paths.endpoint,
+ expectedTokenPath: paths.tokenPath
+ })
+ 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 }
+ }
+
+ /**
+ * Prepare-for-update, final step (issue #829): ask the host to end every session's process tree
+ * and exit, then confirm the process is actually gone. Every answer short of `shut-down` leaves
+ * the caller with a host that may still hold the install directory, so it must not quit and
+ * claim the update can proceed. There is deliberately no fallback that kills the host process:
+ * a host without the feature answers `unsupported`, and the caller shows the manual steps.
+ */
+ async shutdownForUpdate(options: { timeoutMs?: number; exitWaitMs?: number } = {}): Promise<
+ HostShutdownOutcome
+ > {
+ const paths = sessionHostPaths(this.deps.userDataDir)
+ const identity = readExistingSessionHostIdentity(paths.statePath, {
+ expectedEndpoint: paths.endpoint,
+ expectedTokenPath: paths.tokenPath
+ })
+ if (identity.kind === 'absent') return { kind: 'no-host' }
+ await this.ensureConnected()
+ if (!this.hostShutdownFeature) return { kind: 'unsupported' }
+ const socket = this.socket
+ if (!socket) return { kind: 'unconfirmed', error: 'session-host connection lost' }
+ const pid = this.hostPid
+ // Latched BEFORE the request leaves, so a connection that drops mid-shutdown cannot reconnect
+ // into a freshly launched host. The request itself goes on the socket already in hand (never
+ // through `request`, whose reconnect path the latch now refuses) and is never resent.
+ this.shutDownForUpdate = true
+ let result: ShutdownResult
+ try {
+ result = await this.requestOnSocket<ShutdownResult>(
+ socket,
+ { cmd: 'shutdown' },
+ undefined,
+ undefined,
+ options.timeoutMs ?? SHUTDOWN_REQUEST_TIMEOUT_MS
+ )
+ } catch (error) {
+ const message =
+ error instanceof SessionHostRequestNotDeliveredError
+ ? error.original.message
+ : asError(error).message
+ // The host's own refusal: it said which sessions it could not end, and it is still serving.
+ if (/could not end|already shutting down|shutdown requires/.test(message)) {
+ this.shutDownForUpdate = false
+ return { kind: 'failed', error: message }
+ }
+ // The frame provably never left: nothing was asked, the host is untouched and still usable.
+ if (error instanceof SessionHostRequestNotDeliveredError) {
+ this.shutDownForUpdate = false
+ return { kind: 'unconfirmed', error: message }
+ }
+ // A lost reply or a timeout says nothing about whether the host is still up. The latch STAYS
+ // set: if it did exit, a reconnect must not launch a replacement that re-locks the install
+ // directory. The caller tells the user to quit and check; a restart clears the latch.
+ return { kind: 'unconfirmed', error: message }
+ }
+ const gone = await waitForHostExit(paths.statePath, pid, options.exitWaitMs ?? 10_000)
+ if (!gone) {
+ return {
+ kind: 'unconfirmed',
+ error: 'the session host reported its sessions ended but has not exited yet'
+ }
+ }
+ return { kind: 'shut-down', ended: result.ended }
+ }
+
async listSessions(): Promise<string[]> {
const result = await this.request<ListSessionsResult>({ cmd: 'listSessions' })
return result.names
diff --git a/src/core/tmux-naming.ts b/src/core/tmux-naming.ts
index fd7197500..98b5a6afa 100644
--- a/src/core/tmux-naming.ts
+++ b/src/core/tmux-naming.ts
@@ -2,12 +2,13 @@
// No native/electron imports, so this module is safe to import from unit tests.
import { randomBytes } from 'crypto'
import { sanitizePasteText } from './paste-injection'
+import { nodeSessionName } from '../shared/session-name'
export const TMUX_SOCKET = 'node-terminal'
/** Per-node tmux session name. Must stay stable — it is the persistence key. */
export function sessionName(persistKey: string): string {
- return `nt-${persistKey.replace(/[^a-zA-Z0-9_-]/g, '_')}`
+ return nodeSessionName(persistKey)
}
/**
diff --git a/src/main/index.ts b/src/main/index.ts
index 2e3238ea2..849ce2305 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1,3 +1,4 @@
+import { registerUpdatePrepIpc } from './update-prep'
import { createRemoteContextEnsure } from '../core/remote-context-ensure'
import { isKnownRemoteCodexAccount } from '../core/remote-ssh/codex-home'
import { createRemoteCodexContext, type RemoteCodexContextTarget } from '../core/remote-ssh/codex-context'
@@ -2191,6 +2192,18 @@ app.whenReady().then(async () => {
quitting = true
skipQuitConfirmation = true
})
+ // Prepare-for-update (Windows session host, issue #829). The user confirmed the whole flow in
+ // its own dialog, so the quit at its end skips the ordinary quit confirmation, like the
+ // restart-to-update above.
+ registerUpdatePrepIpc({
+ mainWebContents: () => getMainWindow()?.webContents,
+ persistentSessions: () => settingsStore.get().tmuxEnabled !== false,
+ quit: () => {
+ quitting = true
+ skipQuitConfirmation = true
+ app.quit()
+ }
+ })
// Mirror live agent status to <userData>/agent-status.json for the external mobile host agent.
initAgentStatusMirror()
// The orchestration facts an earlier run left on disk, in THIS order: station reports first
diff --git a/src/main/update-prep.test.ts b/src/main/update-prep.test.ts
new file mode 100644
index 000000000..c53d0ee8e
--- /dev/null
+++ b/src/main/update-prep.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it, vi } from 'vitest'
+
+vi.mock('electron', () => ({ ipcMain: { handle: vi.fn(), on: vi.fn() } }))
+
+import { updatePrepApplies } from './update-prep'
+import { HOST_ONLY_CHANNELS } from '../shared/host-control'
+import { IPC } from '../shared/ipc'
+
+describe('prepare-for-update gating (issue #829)', () => {
+ it('applies only on Windows with persistent sessions and the host bundle present', () => {
+ expect(updatePrepApplies({ platform: 'win32', persistentSessions: true, bundleAvailable: true })).toBe(true)
+ expect(updatePrepApplies({ platform: 'linux', persistentSessions: true, bundleAvailable: true })).toBe(false)
+ expect(updatePrepApplies({ platform: 'darwin', persistentSessions: true, bundleAvailable: true })).toBe(false)
+ expect(updatePrepApplies({ platform: 'win32', persistentSessions: false, bundleAvailable: true })).toBe(false)
+ expect(updatePrepApplies({ platform: 'win32', persistentSessions: true, bundleAvailable: false })).toBe(false)
+ })
+
+ it('no relay peer may inspect, shut down the host, or quit the app', () => {
+ expect(HOST_ONLY_CHANNELS.has(IPC.appUpdatePrepInspect)).toBe(true)
+ expect(HOST_ONLY_CHANNELS.has(IPC.appUpdatePrepShutdown)).toBe(true)
+ expect(HOST_ONLY_CHANNELS.has(IPC.appUpdatePrepQuit)).toBe(true)
+ })
+})
diff --git a/src/main/update-prep.ts b/src/main/update-prep.ts
new file mode 100644
index 000000000..961f9b967
--- /dev/null
+++ b/src/main/update-prep.ts
@@ -0,0 +1,89 @@
+// Prepare-for-update (Windows session host, issue #829) — the desktop main-process leg. Three raw
+// ipcMain handlers, each refusing any sender that is not the live main window: a `<webview>` guest
+// is a webContents in this process too, and this ends every session on the machine. Not on the
+// platform table, so no relay peer and no Server Edition browser can reach them (they are also in
+// HOST_ONLY_CHANNELS as a belt).
+//
+// The only thing that ever stops the host here is the host's own `shutdown` command, and only on a
+// host that advertised it. There is deliberately no taskkill/name-based fallback: a host started by
+// an older build answers `host-unsupported`, and the renderer shows the manual steps.
+
+import { ipcMain, type IpcMainInvokeEvent } from 'electron'
+import { IPC } from '../shared/ipc'
+import type { UpdatePrepInspection, UpdatePrepShutdown } from '../shared/update-prep'
+import {
+ sessionHostInspectForUpdate,
+ sessionHostShutdownForUpdate,
+ sessionHostSupported
+} from '../core/session-host-backend'
+import { mirrorEntry, pendingTicketsFor } from '../core/agent-status-mirror'
+
+export interface UpdatePrepDeps {
+ mainWebContents: () => { id?: number } | undefined
+ /** `settings.tmuxEnabled` — off means no persistent backend, so no session host is in use. */
+ persistentSessions: () => boolean
+ /** Quit without the quit confirmation (the user already confirmed in the prepare dialog). */
+ quit: () => void
+ platform?: NodeJS.Platform
+}
+
+/** Is the session host the backend this app runs local terminals on? Pure for tests. */
+export function updatePrepApplies(d: {
+ platform: NodeJS.Platform
+ persistentSessions: boolean
+ bundleAvailable: boolean
+}): boolean {
+ return d.platform === 'win32' && d.persistentSessions && d.bundleAvailable
+}
+
+export function registerUpdatePrepIpc(deps: UpdatePrepDeps): void {
+ const fromMain = (event: IpcMainInvokeEvent | Electron.IpcMainEvent): boolean =>
+ deps.mainWebContents()?.id === event.sender.id
+ const applies = (): boolean =>
+ updatePrepApplies({
+ platform: deps.platform ?? process.platform,
+ persistentSessions: deps.persistentSessions(),
+ bundleAvailable: sessionHostSupported()
+ })
+
+ ipcMain.handle(IPC.appUpdatePrepInspect, async (event): Promise<UpdatePrepInspection> => {
+ if (!fromMain(event) || !applies()) return { kind: 'unsupported' }
+ try {
+ const inspection = await sessionHostInspectForUpdate()
+ if (!inspection.running) return { kind: 'no-host' }
+ const mirror: Record<string, { state?: string; attention: boolean }> = {}
+ for (const session of inspection.sessions) {
+ if (!session.startsWith('nt-')) continue
+ const nodeId = session.slice(3)
+ const entry = mirrorEntry(nodeId)
+ mirror[session] = {
+ state: entry?.state,
+ attention: !!entry?.pendingQuestion || pendingTicketsFor(nodeId).length > 0
+ }
+ }
+ return {
+ kind: 'host',
+ sessions: inspection.sessions,
+ shutdownSupported: inspection.shutdown,
+ mirror
+ }
+ } catch (error) {
+ return { kind: 'error', error: error instanceof Error ? error.message : String(error) }
+ }
+ })
+
+ ipcMain.handle(IPC.appUpdatePrepShutdown, async (event): Promise<UpdatePrepShutdown> => {
+ if (!fromMain(event) || !applies()) return { kind: 'unsupported' }
+ try {
+ const outcome = await sessionHostShutdownForUpdate()
+ return outcome.kind === 'unsupported' ? { kind: 'host-unsupported' } : outcome
+ } catch (error) {
+ return { kind: 'unconfirmed', error: error instanceof Error ? error.message : String(error) }
+ }
+ })
+
+ ipcMain.on(IPC.appUpdatePrepQuit, (event) => {
+ if (!fromMain(event)) return
+ deps.quit()
+ })
+}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index a06629180..4e29f05b7 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -476,7 +476,10 @@ const api: NodeTerminalApi = {
check: () => ipcRenderer.send(IPC.appCheckForUpdates),
getVersion: () => ipcRenderer.invoke(IPC.appGetVersion),
getPolicy: () => ipcRenderer.invoke(IPC.appUpdatePolicy),
- restart: () => ipcRenderer.send(IPC.appRestartToUpdate)
+ restart: () => ipcRenderer.send(IPC.appRestartToUpdate),
+ prepareInspect: () => ipcRenderer.invoke(IPC.appUpdatePrepInspect),
+ prepareShutdownHost: () => ipcRenderer.invoke(IPC.appUpdatePrepShutdown),
+ prepareQuit: () => ipcRenderer.send(IPC.appUpdatePrepQuit)
},
license: {
upgrade: (target?: 'pro' | 'seats') => ipcRenderer.invoke(IPC.licenseUpgrade, target),
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index db4414503..d80d8382b 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -240,7 +240,14 @@ export function buildStubApi(): Omit<
// server handler for the update policy (the browser cannot self-install anyway), so the
// honest answer is the shape's own "no policy" value: nothing mandatory, no minimum.
getPolicy: (): Promise<UpdatePolicy> => Promise.resolve({ minSupported: null, mandatory: false }),
- restart: noop
+ restart: noop,
+ // Prepare-for-update is a Windows session-host concern (issue #829). The Server Edition runs
+ // on Linux with tmux, has no installer to unblock, and a browser tab must never be able to
+ // end every session on the server. Documented degrade: `unsupported`, so the entry points
+ // never render.
+ prepareInspect: () => Promise.resolve({ kind: 'unsupported' as const }),
+ prepareShutdownHost: () => Promise.resolve({ kind: 'unsupported' as const }),
+ prepareQuit: noop
},
announcements: {
fetch: () => Promise.resolve([])
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 4b531bde3..91778ee77 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -1,3 +1,5 @@
+import { PrepareUpdateDialog } from '../components/PrepareUpdateDialog'
+import type { PrepNode } from '../lib/updatePrep'
import { reportTextDelivery } from '../lib/textDelivery'
import { useDevPortScanner } from './useDevPortScanner'
import { withCodexNoDaemon } from '@shared/agents/codex-daemon'
@@ -16838,6 +16840,47 @@ export function Canvas() {
travelToNodeRef.current = travelToNode
})
+ // Prepare-for-update (Windows session host, issue #829). Opened from the update card or ⌘K via
+ // `nodeterm:prepare-update`. `prepareUpdateAvailable` gates the ⌘K entry: the main process answers
+ // `unsupported` off Windows, when the session host is not the backend, and in the Server Edition.
+ const [prepareUpdateOpen, setPrepareUpdateOpen] = useState(false)
+ const [prepareUpdateAvailable, setPrepareUpdateAvailable] = useState(false)
+ useEffect(() => {
+ let live = true
+ void window.nodeTerminal.updates
+ .prepareInspect()
+ .then((r) => {
+ if (live) setPrepareUpdateAvailable(r.kind !== 'unsupported')
+ })
+ .catch(() => {})
+ const open = (): void => setPrepareUpdateOpen(true)
+ window.addEventListener('nodeterm:prepare-update', open)
+ return () => {
+ live = false
+ window.removeEventListener('nodeterm:prepare-update', open)
+ }
+ }, [])
+ const collectUpdatePrepNodes = useCallback((): PrepNode[] => {
+ // The active project's live nodes first reach the store, so a node created a moment ago is
+ // matched to its host session like every other.
+ commitActiveToStore()
+ const out: PrepNode[] = []
+ for (const p of useProjects.getState().projects) {
+ for (const n of p.nodes) {
+ if (n.kind !== 'terminal') continue
+ out.push({
+ nodeId: n.id,
+ projectId: p.id,
+ projectName: p.name,
+ projectClosed: !!p.closed,
+ title: n.title,
+ agentId: n.agentId
+ })
+ }
+ }
+ return out
+ }, [commitActiveToStore])
+
// ── "Open recent": resume a past agent conversation from its CLI's own history ──────────────
// The list is THIS machine's (window.nodeTerminal: the desktop's core, or the Server Edition's
// host), read on demand — one read per welcome-screen appearance and per palette open, never a
@@ -17478,6 +17521,16 @@ export function Canvas() {
]
: []),
{ id: 'zoom-100', label: 'Zoom to 100%', icon: <IconFit />, run: zoomTo100 },
+ ...(prepareUpdateAvailable
+ ? [
+ {
+ id: 'prepare-update',
+ label: 'Prepare for update…',
+ hint: 'install update installer stop session host windows quit',
+ run: () => setPrepareUpdateOpen(true)
+ } as Command
+ ]
+ : []),
// Layouts mirror the Dock's menu, and both are withheld on a relay tab for the same reason:
// it is a live connection to another machine, never a workspace on this disk. The Dock says
// so on a disabled button; the palette has no disabled row, so the entries are omitted.
@@ -17628,7 +17681,8 @@ export function Canvas() {
hostedBookmarks,
copyHostedInviteCode,
forgetHostedTeam,
- confirmStopAllLiveLinks
+ confirmStopAllLiveLinks,
+ prepareUpdateAvailable
])
// Build the palette's command list only when its inputs change — the inline `buildCommands()`
@@ -18466,6 +18520,14 @@ export function Canvas() {
be open — see components/SetupConsentDialog.tsx. */}
<SetupConsentDialog />
+ {prepareUpdateOpen && (
+ <PrepareUpdateDialog
+ collectNodes={collectUpdatePrepNodes}
+ onTravel={travelToNode}
+ onClose={() => setPrepareUpdateOpen(false)}
+ />
+ )}
+
{confirm && (
<ConfirmDialog
message={confirm.message}
diff --git a/src/renderer/components/PrepareUpdateDialog.tsx b/src/renderer/components/PrepareUpdateDialog.tsx
new file mode 100644
index 000000000..5ab1a28af
--- /dev/null
+++ b/src/renderer/components/PrepareUpdateDialog.tsx
@@ -0,0 +1,366 @@
+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 { useAgentStatus } from '../state/agentStatus'
+import { agentUpdateExitFn } from '../terminal/agent-restart'
+import { RELEASES_URL } from '../state/pendingUpdate'
+import {
+ planUpdatePrep,
+ updatePrepStopSummary,
+ type PrepNode,
+ type PrepRow,
+ type UpdatePrepPlan
+} from '../lib/updatePrep'
+
+// Prepare-for-update (Windows session host, issue #829). The session host outlives the app by
+// design and holds the install directory, so the installer refuses to run while it is up. This
+// dialog walks the user out of that state WITHOUT deleting a node:
+// 1. list every session the host holds (all projects, closed ones too) and refuse while any agent
+// is working or waiting on the user — each one is listed with a "Go" button;
+// 2. ask each idle, resumable agent on a mounted node to quit cleanly (`/exit`, `/quit`, …);
+// 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.
+// There is no path here that kills the host process or ends a session through node deletion.
+
+type Phase =
+ | { k: 'inspecting' }
+ | { k: 'inspected'; inspection: UpdatePrepInspection; plan: UpdatePrepPlan | null }
+ | { k: 'exiting'; done: number; total: number }
+ | { k: 'confirm'; plan: UpdatePrepPlan; exited: number }
+ | { k: 'shutting' }
+ | { k: 'failed'; message: string }
+
+interface Props {
+ /** Every terminal node in every project (closed ones included), the active one committed. */
+ collectNodes: () => PrepNode[]
+ onTravel: (nodeId: string) => void
+ onClose: () => void
+}
+
+function planFor(inspection: UpdatePrepInspection, nodes: PrepNode[]): UpdatePrepPlan | null {
+ if (inspection.kind !== 'host') return null
+ const byId = useAgentStatus.getState().byId
+ return planUpdatePrep({
+ sessions: inspection.sessions,
+ nodes,
+ statusOf: (id) => byId[id],
+ mirrorOf: (session) => inspection.mirror[session],
+ canExitInPlace: (id) => !!agentUpdateExitFn(id)
+ })
+}
+
+function rowLabel(row: PrepRow): string {
+ if (!row.node) return row.session
+ const where = row.node.projectClosed
+ ? `${row.node.projectName} (closed)`
+ : row.node.projectName
+ return `${row.node.title || row.node.nodeId} — ${where}`
+}
+
+export function PrepareUpdateDialog({ collectNodes, onTravel, onClose }: Props): JSX.Element {
+ const [phase, setPhase] = useState<Phase>({ k: 'inspecting' })
+ const [openDownload, setOpenDownload] = useState(true)
+ const busyRef = useRef(false)
+ const isTop = useDialogStack()
+
+ const inspect = useCallback(async (): Promise<{
+ inspection: UpdatePrepInspection
+ plan: UpdatePrepPlan | null
+ }> => {
+ const inspection = await window.nodeTerminal.updates
+ .prepareInspect()
+ .catch((e: unknown): UpdatePrepInspection => ({
+ kind: 'error',
+ error: e instanceof Error ? e.message : String(e)
+ }))
+ return { inspection, plan: planFor(inspection, collectNodes()) }
+ }, [collectNodes])
+
+ const refresh = useCallback(async () => {
+ setPhase({ k: 'inspecting' })
+ const r = await inspect()
+ setPhase({ k: 'inspected', ...r })
+ }, [inspect])
+
+ useEffect(() => {
+ void refresh()
+ }, [refresh])
+
+ const working = phase.k === 'exiting' || phase.k === 'shutting'
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent): void => {
+ if (!isTop() || e.key !== 'Escape' || working) return
+ e.preventDefault()
+ onClose()
+ }
+ window.addEventListener('keydown', onKey)
+ return () => window.removeEventListener('keydown', onKey)
+ }, [isTop, onClose, working])
+
+ const quit = useCallback(() => {
+ if (openDownload) window.open(RELEASES_URL, '_blank', 'noopener')
+ window.nodeTerminal.updates.prepareQuit()
+ }, [openDownload])
+
+ /** Step 2: clean exits, one node at a time (each is a choreography in its own pane). Then the
+ * host is asked again — something may have started working meanwhile — before the confirm. */
+ const runExits = useCallback(
+ async (plan: UpdatePrepPlan) => {
+ if (busyRef.current) return
+ busyRef.current = true
+ try {
+ let exited = 0
+ const total = plan.toExit.length
+ setPhase({ k: 'exiting', done: 0, total })
+ for (const [i, row] of plan.toExit.entries()) {
+ const fn = row.node ? agentUpdateExitFn(row.node.nodeId) : undefined
+ const outcome = fn ? await fn().catch(() => 'not-eligible' as const) : 'not-eligible'
+ if (outcome === 'exited') exited++
+ setPhase({ k: 'exiting', done: i + 1, total })
+ }
+ const r = await inspect()
+ if (r.inspection.kind !== 'host' || !r.plan || r.plan.blocking.length > 0 || !r.inspection.shutdownSupported) {
+ setPhase({ k: 'inspected', ...r })
+ return
+ }
+ setPhase({ k: 'confirm', plan: r.plan, exited })
+ } finally {
+ busyRef.current = false
+ }
+ },
+ [inspect]
+ )
+
+ /** Step 4: the host ends every session and exits; only a confirmed exit quits the app. */
+ const shutdown = useCallback(async () => {
+ if (busyRef.current) return
+ busyRef.current = true
+ setPhase({ k: 'shutting' })
+ try {
+ const outcome = await window.nodeTerminal.updates.prepareShutdownHost()
+ switch (outcome.kind) {
+ case 'shut-down':
+ case 'no-host':
+ quit()
+ return
+ case 'failed':
+ setPhase({
+ k: 'failed',
+ message: `The session host could not end every session and is still running (${outcome.error}). Nothing was quit.`
+ })
+ return
+ case 'unconfirmed':
+ setPhase({
+ k: 'failed',
+ message: `The session host did not confirm it shut down (${outcome.error}). Quit nodeterm and check Task Manager before installing.`
+ })
+ return
+ case 'host-unsupported':
+ setPhase({
+ k: 'failed',
+ message: 'This session host was started by an older nodeterm and cannot shut itself down.'
+ })
+ return
+ default:
+ setPhase({ k: 'failed', message: 'Preparing for an update is not available here.' })
+ }
+ } catch (e) {
+ setPhase({
+ k: 'failed',
+ message: `The session host did not answer (${e instanceof Error ? e.message : String(e)}).`
+ })
+ } finally {
+ busyRef.current = false
+ }
+ }, [quit])
+
+ if (phase.k === 'confirm') {
+ return (
+ <ConfirmDialog
+ message="Stop all sessions and quit to update?"
+ body={
+ <ul className="update-prep__list">
+ {updatePrepStopSummary(phase.plan, phase.exited).map((line) => (
+ <li key={line}>{line}</li>
+ ))}
+ </ul>
+ }
+ confirmLabel="Stop sessions and quit"
+ danger
+ enterConfirms={false}
+ option={{
+ label: 'Open the download page after quitting',
+ checked: openDownload,
+ onChange: setOpenDownload
+ }}
+ onConfirm={() => void shutdown()}
+ onCancel={onClose}
+ />
+ )
+ }
+
+ const manualSteps = (
+ <ol className="update-prep__list">
+ {MANUAL_UPDATE_STEPS.map((s) => (
+ <li key={s}>{s}</li>
+ ))}
+ </ol>
+ )
+
+ let content: JSX.Element
+ let actions: JSX.Element = (
+ <button className="confirm__btn" autoFocus onClick={onClose}>
+ Close
+ </button>
+ )
+ if (phase.k === 'inspecting') {
+ content = <p className="confirm__msg">Checking the session host…</p>
+ } else if (phase.k === 'exiting') {
+ content = (
+ <p className="confirm__msg">
+ Asking agents to exit so their conversations are saved… {phase.done} of {phase.total}
+ </p>
+ )
+ actions = <></>
+ } else if (phase.k === 'shutting') {
+ content = <p className="confirm__msg">Stopping sessions and the session host…</p>
+ actions = <></>
+ } else if (phase.k === 'failed') {
+ content = (
+ <>
+ <p className="confirm__msg">{phase.message}</p>
+ <p className="confirm__msg">To update by hand:</p>
+ {manualSteps}
+ </>
+ )
+ } else {
+ const { inspection, plan } = phase
+ if (inspection.kind === 'unsupported') {
+ content = (
+ <p className="confirm__msg">
+ Not needed here: this machine does not run terminals in the nodeterm session host.
+ </p>
+ )
+ } else if (inspection.kind === 'no-host') {
+ content = (
+ <p className="confirm__msg">
+ No session host is running, so nothing holds the installation. Quit nodeterm, then run
+ the installer.
+ </p>
+ )
+ actions = (
+ <>
+ <button className="confirm__btn" autoFocus onClick={onClose}>
+ Cancel
+ </button>
+ <button className="confirm__btn primary" onClick={quit}>
+ Quit nodeterm
+ </button>
+ </>
+ )
+ } else if (inspection.kind === 'error') {
+ content = (
+ <>
+ <p className="confirm__msg">Could not read the session host: {inspection.error}</p>
+ {manualSteps}
+ </>
+ )
+ } else if (plan && plan.blocking.length > 0) {
+ content = (
+ <>
+ <p className="confirm__msg">
+ Wait for these sessions first — stopping them now would abandon a running turn or an
+ unanswered question:
+ </p>
+ <ul className="update-prep__list">
+ {plan.blocking.map((row) => (
+ <li key={row.session} className="update-prep__row">
+ <span>
+ {rowLabel(row)} · {row.busyReason === 'working' ? 'working' : 'needs you'}
+ </span>
+ {row.node && (
+ <button
+ className="confirm__btn"
+ onClick={() => {
+ onTravel(row.node!.nodeId)
+ onClose()
+ }}
+ >
+ Go
+ </button>
+ )}
+ </li>
+ ))}
+ </ul>
+ </>
+ )
+ actions = (
+ <>
+ <button className="confirm__btn" autoFocus onClick={onClose}>
+ Close
+ </button>
+ <button className="confirm__btn primary" onClick={() => void refresh()}>
+ Check again
+ </button>
+ </>
+ )
+ } else if (!inspection.shutdownSupported) {
+ content = (
+ <>
+ <p className="confirm__msg">
+ The running session host was started by an older nodeterm and cannot shut itself down
+ from here. To update by hand:
+ </p>
+ {manualSteps}
+ </>
+ )
+ } else if (plan) {
+ const exitCount = plan.toExit.length
+ content = (
+ <>
+ <p className="confirm__msg">
+ The session host holds {plan.rows.length} session{plan.rows.length === 1 ? '' : 's'}{' '}
+ across your projects. The installer cannot run while it is up.
+ </p>
+ <p className="confirm__msg">
+ {exitCount > 0
+ ? `First, ${exitCount} idle agent${exitCount === 1 ? '' : 's'} will be asked to exit so ${exitCount === 1 ? 'its conversation is' : 'their conversations are'} saved. You confirm before anything else stops.`
+ : 'You confirm before anything stops.'}{' '}
+ Canvas nodes are kept.
+ </p>
+ </>
+ )
+ actions = (
+ <>
+ <button className="confirm__btn" autoFocus onClick={onClose}>
+ Cancel
+ </button>
+ <button className="confirm__btn primary" onClick={() => void runExits(plan)}>
+ Continue
+ </button>
+ </>
+ )
+ } else {
+ content = <p className="confirm__msg">Nothing to prepare.</p>
+ }
+ }
+
+ return createPortal(
+ <div className="confirm-overlay" onClick={working ? undefined : onClose}>
+ <div
+ className="confirm update-prep"
+ role="dialog"
+ aria-label="Prepare for update"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <h2 className="update-prep__title">Prepare for update</h2>
+ {content}
+ <div className="confirm__actions">{actions}</div>
+ </div>
+ </div>,
+ document.body
+ )
+}
diff --git a/src/renderer/components/UpdateCard.no-channel.test.tsx b/src/renderer/components/UpdateCard.no-channel.test.tsx
index 920cc1a2a..910f926f9 100644
--- a/src/renderer/components/UpdateCard.no-channel.test.tsx
+++ b/src/renderer/components/UpdateCard.no-channel.test.tsx
@@ -34,7 +34,10 @@ beforeEach(() => {
onNoChannel: sub('noChannel'),
getPolicy: () => Promise.resolve({ minSupported: null, mandatory: false }),
check: () => {},
- restart: () => {}
+ restart: () => {},
+ prepareInspect: () => Promise.resolve({ kind: 'unsupported' }),
+ prepareShutdownHost: () => Promise.resolve({ kind: 'unsupported' }),
+ prepareQuit: () => {}
}
}
window.open = ((url: string) => {
diff --git a/src/renderer/components/UpdateCard.tsx b/src/renderer/components/UpdateCard.tsx
index d1cbb2601..609cd9eff 100644
--- a/src/renderer/components/UpdateCard.tsx
+++ b/src/renderer/components/UpdateCard.tsx
@@ -26,6 +26,21 @@ export function UpdateCard(): JSX.Element | null {
const [status, setStatus] = useState<Status>({ kind: 'idle' })
const [minimized, setMinimized] = useState(false)
const upToDateTimer = useRef<number | null>(null)
+ // Windows session host (issue #829): the installer refuses to run while the host is up, so the
+ // card offers the in-app "Prepare for update" flow. Main answers `unsupported` everywhere else.
+ const [canPrepare, setCanPrepare] = useState(false)
+ useEffect(() => {
+ let live = true
+ void window.nodeTerminal.updates
+ .prepareInspect()
+ .then((r) => {
+ if (live) setCanPrepare(r.kind !== 'unsupported')
+ })
+ .catch(() => {})
+ return () => {
+ live = false
+ }
+ }, [])
useEffect(() => {
const offAvailable = window.nodeTerminal.updates.onAvailable((info) => {
@@ -128,6 +143,14 @@ export function UpdateCard(): JSX.Element | null {
if (status.kind === 'idle') return null
const openReleases = () => window.open(RELEASES_URL, '_blank', 'noopener')
+ const prepareButton = canPrepare ? (
+ <button
+ className="update-card__link"
+ onClick={() => window.dispatchEvent(new Event('nodeterm:prepare-update'))}
+ >
+ Prepare for update…
+ </button>
+ ) : null
const dismiss = () => setStatus({ kind: 'idle' })
if (minimized) {
@@ -217,6 +240,7 @@ export function UpdateCard(): JSX.Element | null {
<button className="update-card__btn" onClick={openReleases}>
{noSelfInstallCopy('manual-install', status.version).action}
</button>
+ {prepareButton}
</>
)}
@@ -226,6 +250,7 @@ export function UpdateCard(): JSX.Element | null {
<button className="update-card__btn" onClick={openReleases}>
{noSelfInstallCopy('no-channel').action}
</button>
+ {prepareButton}
</>
)}
@@ -267,6 +292,7 @@ export function UpdateCard(): JSX.Element | null {
<button className="update-card__link" onClick={openReleases}>
Download manually
</button>
+ {prepareButton}
</>
)}
</div>
diff --git a/src/renderer/lib/updatePrep.test.ts b/src/renderer/lib/updatePrep.test.ts
new file mode 100644
index 000000000..d9104130e
--- /dev/null
+++ b/src/renderer/lib/updatePrep.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from 'vitest'
+import { planUpdatePrep, updatePrepStopSummary, type PrepNode, type PrepStatus } from './updatePrep'
+
+const node = (nodeId: string, agentId?: string, extra: Partial<PrepNode> = {}): PrepNode => ({
+ nodeId,
+ projectId: 'p1',
+ projectName: 'Alpha',
+ projectClosed: false,
+ title: nodeId,
+ agentId,
+ ...extra
+})
+
+function plan(
+ sessions: string[],
+ nodes: PrepNode[],
+ status: Record<string, PrepStatus> = {},
+ mirror: Record<string, { state?: string; attention?: boolean }> = {},
+ mounted: string[] = nodes.map((n) => n.nodeId)
+) {
+ return planUpdatePrep({
+ sessions,
+ nodes,
+ statusOf: (id) => status[id],
+ mirrorOf: (s) => mirror[s],
+ canExitInPlace: (id) => mounted.includes(id)
+ })
+}
+
+describe('planUpdatePrep (issue #829)', () => {
+ it('blocks on a working agent, from the renderer OR the core mirror', () => {
+ const p = plan(
+ ['nt-a', 'nt-b'],
+ [node('a', 'claude'), node('b', 'claude', { projectClosed: true })],
+ { a: { state: 'working', sessionId: 's1' } },
+ { 'nt-b': { state: 'working' } },
+ ['a']
+ )
+ expect(p.blocking.map((r) => [r.session, r.busyReason])).toEqual([
+ ['nt-a', 'working'],
+ ['nt-b', 'working']
+ ])
+ expect(p.toExit).toEqual([])
+ })
+
+ it('blocks on a dialog: waiting, blocked, or a held question/approval ticket', () => {
+ const p = plan(
+ ['nt-a', 'nt-b', 'nt-c'],
+ [node('a', 'claude'), node('b', 'codex'), node('c', 'claude')],
+ { a: { state: 'blocked', sessionId: 's' }, b: { state: 'done', sessionId: 's' } },
+ { 'nt-b': { state: 'waiting' }, 'nt-c': { state: 'done', attention: true } }
+ )
+ expect(p.blocking.map((r) => r.busyReason)).toEqual(['needs-you', 'needs-you', 'needs-you'])
+ })
+
+ it('exits only idle, resumable, mounted agents whose CLI is still in the pane', () => {
+ const p = plan(
+ ['nt-idle', 'nt-off', 'nt-sleep', 'nt-nosess', 'nt-custom', 'nt-sh', 'nt-ghost'],
+ [
+ node('idle', 'claude'),
+ node('off', 'claude'),
+ node('sleep', 'claude'),
+ node('nosess', 'claude'),
+ node('custom', 'custom:nobase'),
+ node('sh')
+ ],
+ {
+ idle: { state: 'done', sessionId: 's1' },
+ off: { sessionId: 's2' },
+ sleep: { state: 'done', sessionId: 's3', hibernated: true },
+ nosess: { state: 'done' },
+ custom: { state: 'done', sessionId: 's4' }
+ },
+ {},
+ ['idle', 'sleep', 'nosess', 'custom', 'sh']
+ )
+ const kinds = Object.fromEntries(p.rows.map((r) => [r.session, r.kind]))
+ expect(kinds).toEqual({
+ 'nt-idle': 'exit',
+ 'nt-off': 'agent-unreachable',
+ 'nt-sleep': 'agent-exited',
+ 'nt-nosess': 'agent-no-resume',
+ 'nt-custom': 'agent-no-resume',
+ 'nt-sh': 'shell',
+ 'nt-ghost': 'orphan'
+ })
+ expect(p.toExit.map((r) => r.session)).toEqual(['nt-idle'])
+ expect(p.blocking).toEqual([])
+ })
+
+ it('maps sanitized node ids the way core names sessions', () => {
+ const p = plan(['nt-a_b'], [node('a.b')])
+ expect(p.rows[0]).toMatchObject({ kind: 'shell', node: { nodeId: 'a.b' } })
+ })
+
+ it('an orphan session the mirror says is working still blocks', () => {
+ const p = plan(['nt-x'], [], {}, { 'nt-x': { state: 'working' } })
+ expect(p.blocking).toHaveLength(1)
+ })
+
+ it('the stop summary always says nodes are kept and names what is lost', () => {
+ const p = plan(
+ ['nt-idle', 'nt-sh', 'nt-off'],
+ [node('idle', 'claude'), node('sh'), node('off', 'claude')],
+ { idle: { state: 'done', sessionId: 's' }, off: { state: 'done', sessionId: 's' } },
+ {},
+ ['idle', 'sh']
+ )
+ const text = updatePrepStopSummary(p, 0).join('\n')
+ expect(text).toContain('3 sessions will stop')
+ expect(text).toContain('1 agent did not exit')
+ expect(text).toContain('not open on the canvas')
+ expect(text).toContain('unsaved work in them is lost')
+ expect(text).toContain('Canvas nodes are kept')
+ expect(updatePrepStopSummary(p, 1).join('\n')).toContain('1 agent exited cleanly')
+ })
+})
diff --git a/src/renderer/lib/updatePrep.ts b/src/renderer/lib/updatePrep.ts
new file mode 100644
index 000000000..fcbebfe30
--- /dev/null
+++ b/src/renderer/lib/updatePrep.ts
@@ -0,0 +1,184 @@
+// Prepare-for-update (Windows session host, issue #829) — the PURE half of the flow: given what the
+// running host holds and what the app knows about each node, decide which sessions block the
+// update, which agents get asked to quit cleanly first, and what the confirm dialog must say will
+// stop. Every rule here is a refusal or a disclosure, never a guess:
+//
+// • a session whose agent is WORKING, waiting on a question or blocked on an approval blocks the
+// whole flow — ending it would abandon a turn or throw away the dialog's answer. Either source
+// saying so is enough: the renderer's store (live for mounted nodes) or core's status mirror
+// (which also covers nodes in projects that are not on screen, closed projects included);
+// • only a node that is MOUNTED can be asked to `/exit` (its pane closure is registered by the
+// node itself); an agent in an unmounted project is listed as "stops without a clean exit" —
+// its conversation resumes from its last saved turn;
+// • a host session no project knows (an orphan) is still ended and is counted, never hidden.
+//
+// Nothing here ever deletes a node: the update ends processes, and the canvas cold-restores.
+
+import { canResume } from '@shared/agents/config'
+import { nodeSessionName } from '@shared/session-name'
+import { exitSequence } from '../terminal/agent-restart'
+import { agentProcessInPane } from '../terminal/live-work'
+
+export interface PrepNode {
+ nodeId: string
+ projectId: string
+ projectName: string
+ /** The project is closed (parked in "Recently closed"); its sessions still run on the host. */
+ projectClosed: boolean
+ title: string
+ /** The agent the node runs (`data.agentId`); undefined for a plain terminal. */
+ agentId?: string
+}
+
+export interface PrepStatus {
+ state?: string
+ sessionId?: string
+ hibernated?: boolean
+ paused?: boolean
+ dropped?: boolean
+ sessionEnded?: boolean
+}
+
+export interface PrepMirror {
+ state?: string
+ /** An unanswered question or approval ticket is held for this node. */
+ attention?: boolean
+}
+
+export type PrepRowKind =
+ /** Working / waiting / blocked — the flow refuses until it settles. */
+ | 'busy'
+ /** Idle agent on a mounted node: will be asked to quit cleanly before the shutdown. */
+ | 'exit'
+ /** Idle agent that cannot be asked to quit (its project is not on screen): stops with the host. */
+ | 'agent-unreachable'
+ /** Agent CLI already left the pane (Eco, Pause, its own /exit): only the shell remains. */
+ | 'agent-exited'
+ /** Agent we cannot exit-and-resume (custom agent without a base, no session id yet). */
+ | 'agent-no-resume'
+ /** A plain terminal: its shell and anything running in it stop. */
+ | 'shell'
+ /** A host session no project knows. Still ended. */
+ | 'orphan'
+
+export interface PrepRow {
+ session: string
+ kind: PrepRowKind
+ node?: PrepNode
+ /** For `busy`: what it is doing, in words. */
+ busyReason?: 'working' | 'needs-you'
+}
+
+export interface UpdatePrepPlan {
+ rows: PrepRow[]
+ blocking: PrepRow[]
+ toExit: PrepRow[]
+}
+
+const BUSY_STATES = new Set(['working'])
+const ATTENTION_STATES = new Set(['waiting', 'blocked'])
+
+export function planUpdatePrep(input: {
+ sessions: readonly string[]
+ nodes: readonly PrepNode[]
+ statusOf: (nodeId: string) => PrepStatus | undefined
+ mirrorOf: (session: string) => PrepMirror | undefined
+ /** A mounted node registered its update-exit closure. */
+ canExitInPlace: (nodeId: string) => boolean
+}): UpdatePrepPlan {
+ const byName = new Map<string, PrepNode>()
+ for (const node of input.nodes) {
+ const name = nodeSessionName(node.nodeId)
+ // First one wins: two projects holding the same node id (a worktree checkout) attach the same
+ // session, and either is a correct name for it.
+ if (!byName.has(name)) byName.set(name, node)
+ }
+ const rows: PrepRow[] = []
+ for (const session of input.sessions) {
+ const node = byName.get(session)
+ const mirror = input.mirrorOf(session)
+ if (!node) {
+ // A session the canvas does not know can still carry a live agent the mirror reports.
+ const busy = busyReason(undefined, mirror)
+ rows.push(busy ? { session, kind: 'busy', busyReason: busy } : { session, kind: 'orphan' })
+ continue
+ }
+ const status = input.statusOf(node.nodeId)
+ const busy = busyReason(status, mirror)
+ if (busy) {
+ rows.push({ session, node, kind: 'busy', busyReason: busy })
+ continue
+ }
+ if (!node.agentId) {
+ rows.push({ session, node, kind: 'shell' })
+ continue
+ }
+ if (!agentProcessInPane(node.agentId, status)) {
+ rows.push({ session, node, kind: 'agent-exited' })
+ continue
+ }
+ if (!canResume(node.agentId) || !exitSequence(node.agentId) || !status?.sessionId) {
+ rows.push({ session, node, kind: 'agent-no-resume' })
+ continue
+ }
+ rows.push({
+ session,
+ node,
+ kind: input.canExitInPlace(node.nodeId) ? 'exit' : 'agent-unreachable'
+ })
+ }
+ return {
+ rows,
+ blocking: rows.filter((r) => r.kind === 'busy'),
+ toExit: rows.filter((r) => r.kind === 'exit')
+ }
+}
+
+function busyReason(
+ status: PrepStatus | undefined,
+ mirror: PrepMirror | undefined
+): PrepRow['busyReason'] {
+ if (mirror?.attention) return 'needs-you'
+ if (ATTENTION_STATES.has(status?.state ?? '') || ATTENTION_STATES.has(mirror?.state ?? ''))
+ return 'needs-you'
+ if (BUSY_STATES.has(status?.state ?? '') || BUSY_STATES.has(mirror?.state ?? '')) return 'working'
+ return undefined
+}
+
+/** The confirm dialog's sentences about what will stop, by count. Pure so the wording is tested.
+ * `plan` is the one taken AFTER the clean exits ran, so any row still `exit` is an agent that did
+ * not quit; `exited` is how many did. */
+export function updatePrepStopSummary(plan: UpdatePrepPlan, exited: number): string[] {
+ const count = (k: PrepRowKind): number => plan.rows.filter((r) => r.kind === k).length
+ const lines: string[] = []
+ const shells = count('shell')
+ const unreachable = count('agent-unreachable') + count('agent-no-resume')
+ const exitFailed = count('exit')
+ if (plan.rows.length > 0) {
+ lines.push(
+ `Every process still running in these ${plan.rows.length} session${
+ plan.rows.length === 1 ? '' : 's'
+ } will stop.`
+ )
+ }
+ if (exited > 0) lines.push(`${exited} agent${exited === 1 ? '' : 's'} exited cleanly and will resume.`)
+ if (exitFailed > 0)
+ lines.push(
+ `${exitFailed} agent${exitFailed === 1 ? '' : 's'} did not exit and will be stopped; ` +
+ 'each resumes from its last saved turn where its CLI supports --resume.'
+ )
+ if (unreachable > 0)
+ lines.push(
+ `${unreachable} agent${unreachable === 1 ? ' is' : 's are'} not open on the canvas (or cannot be ` +
+ 'exited cleanly) and will be stopped; they resume from their last saved turn where supported.'
+ )
+ if (shells > 0)
+ lines.push(
+ `${shells} plain terminal${shells === 1 ? '' : 's'}: anything running there stops and unsaved ` +
+ 'work in them is lost.'
+ )
+ if (count('orphan') > 0)
+ lines.push(`${count('orphan')} session${count('orphan') === 1 ? '' : 's'} not on any canvas will also stop.`)
+ lines.push('Canvas nodes are kept. Agents resume with --resume on the next launch.')
+ return lines
+}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index e04554e97..7fb22d4d6 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -184,6 +184,7 @@ import {
queryPaneWithin,
registerAgentHibernate,
registerAgentPause,
+ registerAgentUpdateExit,
registerAgentRestart,
clearEnvEligibility,
restartEligibility,
@@ -4757,6 +4758,35 @@ export function TerminalNode({
return 'paused'
})
})
+ // Prepare-for-update (Windows session host, issue #829): ask an idle agent to quit cleanly so
+ // its conversation is saved before the host ends every session. The same exit half as Pause,
+ // with the same refusals (busy, not resumable, no session id, CLI not in this pane), but it
+ // records the node as SLEEPING rather than PAUSED: the update ends the session anyway, and on
+ // the next launch the cold restore (`fresh` clears `hibernated`) resumes it with `--resume`.
+ const unregisterUpdateExit = registerAgentUpdateExit(
+ id,
+ guardConcurrentRestart(id, async (): Promise<ExitPhaseOutcome> => {
+ const st = useAgentStatus.getState().byId[id]
+ const agentSessionId = st?.sessionId
+ const gate = restartEligibility(agentId, st?.state, agentSessionId)
+ if (!gate.ok || !agentId || !agentSessionId || !restartTarget()) return 'not-eligible'
+ if (!agentProcessInPane(agentId, st)) return 'exited'
+ if (decideHibernateExit(await readPaneOwner(), agentId, paneBinaries()) !== 'agent-owns-pane')
+ return 'not-eligible'
+ const outcome = await performExitPhase({
+ agentId,
+ sessionId: agentSessionId,
+ io: restartIo,
+ paneCommand: () => api.pty.paneCommand(id),
+ isLive: restartTarget
+ })
+ if (outcome === 'exited') {
+ useAgentStatus.getState().setHibernatedContext(id, captureWakeContext(await readPaneOwner()))
+ useAgentStatus.getState().setHibernated(id, true)
+ }
+ return outcome
+ })
+ )
// Coalesce observer bursts: dragging the NodeResizer fires per animation frame, and every
// call is a full cell-geometry measure + a resize IPC → node-pty → tmux (which redraws the
@@ -4940,6 +4970,7 @@ export function TerminalNode({
// node as unwired (`planHibernation` refuses it) and the wake finds nothing to resume into.
unregisterHibernate()
unregisterPause()
+ unregisterUpdateExit()
observer.disconnect()
rootObserver.disconnect()
// The visibility observer is NOT disconnected here — it is mount-stable and must outlive an
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index bf522c5cb..c68bff80e 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -6459,6 +6459,32 @@ body,
background: var(--accent-hover);
}
+.update-prep__title {
+ margin: 0 0 12px;
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--text);
+}
+
+/* Prepare-for-update (issue #829): the busy-session list and the stop summary. No fill of its own:
+ it sits inside `.confirm`, which owns the surface in every appearance. */
+.update-prep__list {
+ margin: 0 0 16px;
+ padding-left: 18px;
+ font-size: 13px;
+ line-height: 1.5;
+ color: var(--text);
+ max-height: 40vh;
+ overflow-y: auto;
+}
+
+.update-prep__row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+}
+
.confirm__msg {
margin: 0 0 16px;
/* The scrollable region once the box hits its max-height, so the action buttons
diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.ts
index feebee91a..1115da644 100644
--- a/src/renderer/terminal/agent-restart.ts
+++ b/src/renderer/terminal/agent-restart.ts
@@ -666,6 +666,26 @@ export function agentPauseFns(nodeId: string): AgentPauseFns | undefined {
return pauseFns.get(nodeId)
}
+/** Prepare-for-update (Windows session host, issue #829): one mounted node's "quit the CLI cleanly
+ * so the conversation is saved" closure. Its own registry rather than `agentPauseFns`: a pause
+ * marks the node PAUSED, which would stop the cold restore from resuming it after the update —
+ * the opposite of what the update flow promises. `'exited'` also answers a node whose CLI had
+ * already left the pane (nothing to do). */
+export type AgentUpdateExitFn = () => Promise<ExitPhaseOutcome>
+
+const updateExitFns = new Map<string, AgentUpdateExitFn>()
+
+export function registerAgentUpdateExit(nodeId: string, fn: AgentUpdateExitFn): () => void {
+ updateExitFns.set(nodeId, fn)
+ return () => {
+ if (updateExitFns.get(nodeId) === fn) updateExitFns.delete(nodeId)
+ }
+}
+
+export function agentUpdateExitFn(nodeId: string): AgentUpdateExitFn | undefined {
+ return updateExitFns.get(nodeId)
+}
+
/** TEST ONLY (house pattern: webgl-budget's `__resetWebglBudgetForTests`): the maps above are
* module-global, so a test that leaves a restart in flight would otherwise refuse the next
* test's restart of the same node id. */
@@ -674,6 +694,7 @@ export function __resetAgentRestartForTests(): void {
restartFns.clear()
hibernateFns.clear()
pauseFns.clear()
+ updateExitFns.clear()
}
// ── Bulk run: who gets restarted, and how the run is summed up ──────────────────────────
diff --git a/src/session-host/host.ts b/src/session-host/host.ts
index 755a8e133..a06d1a9d0 100644
--- a/src/session-host/host.ts
+++ b/src/session-host/host.ts
@@ -30,7 +30,8 @@ import {
type PaneCommandResult,
type CaptureResult,
type KillSessionResult,
- type ListSessionsResult
+ type ListSessionsResult,
+ type ShutdownResult
} from './protocol'
import { HostSession } from './session'
import { sendTextWhenSettled } from '../core/settled-text'
@@ -71,6 +72,11 @@ function tokenMatches(received: unknown, expected: string): boolean {
return a.length === b.length && crypto.timingSafeEqual(a, b)
}
+/** How long a `shutdown` waits for any one session's kill to be CONFIRMED (node-pty's onExit)
+ * before reporting it as not ended. Without a bound one wedged process would leave the host
+ * refusing every new session for the rest of its life. */
+const SHUTDOWN_KILL_DEADLINE_MS = 20_000
+
const COMPLETED_KILL_TTL_MS = 10 * 60_000
const MAX_COMPLETED_KILLS = 1_024
const REPLACEMENT_RESERVATION_TTL_MS = 30_000
@@ -332,6 +338,13 @@ async function main(): Promise<void> {
/** Connections that negotiated the `geometry` feature at hello. Only these may ever receive a
* `geometry` push: an older client reads any non-`data` push frame as an exit (issue #914). */
const geometrySockets = new WeakSet<net.Socket>()
+ /** Connections that negotiated the `shutdown` feature. Only these may ask the host to end every
+ * session and exit (issue #829): the command is destructive, so an app build that never asked
+ * for it can never trigger it by accident. */
+ const shutdownSockets = new WeakSet<net.Socket>()
+ /** Set while a `shutdown` is ending sessions. New sessions (attach / attachExisting / launches)
+ * are refused for its duration; cleared again only if the shutdown could not end everything. */
+ let shuttingDown = false
/** Tell every geometry-aware subscriber the size the pty now actually runs at. */
function publishGeometry(session: HostSession, geometry: { cols: number; rows: number }): void {
@@ -365,6 +378,7 @@ async function main(): Promise<void> {
? SESSION_HOST_FEATURES.filter((feature) => requested.includes(feature))
: []
if (features.includes('geometry')) geometrySockets.add(socket)
+ if (features.includes('shutdown')) shutdownSockets.add(socket)
return features.length > 0
? { protocolVersion: currentProtocolVersion(), features }
: { protocolVersion: currentProtocolVersion() }
@@ -809,11 +823,98 @@ async function main(): Promise<void> {
return promise
}
+ /** Prepare-for-update (issue #829). Ends every live session through the SAME kill path a single
+ * `killSession` takes (taskkill of the process tree on Windows, then node-pty's real onExit as
+ * the proof), so a shutdown claims nothing a kill would not. Persisted node metadata belongs to
+ * the app and is untouched: the nodes stay on the canvas and cold-restore on the next launch.
+ * If ANY session could not be confirmed ended, the shutdown fails, names them, and the host
+ * keeps serving — the caller must not quit the app believing the install directory is free. */
+ async function handleShutdown(socket: net.Socket): Promise<ShutdownResult> {
+ if (!shutdownSockets.has(socket)) {
+ throw new Error('shutdown requires the shutdown feature negotiated at hello')
+ }
+ if (shuttingDown) throw new Error('session-host is already shutting down')
+ shuttingDown = true
+ cancelGraceExit()
+ const targets = [...sessions.values()]
+ const endOne = async (session: HostSession): Promise<string> => {
+ const inFlight = ending.get(session.name)
+ if (inFlight) await inFlight.promise
+ else if (session.exited || session.retiring) await session.ending
+ else await handleKill(session.name, crypto.randomUUID(), session.generation, false)
+ return session.name
+ }
+ const withDeadline = (p: Promise<string>): Promise<string> =>
+ new Promise<string>((resolve, reject) => {
+ const timer = setTimeout(
+ () => reject(new Error('kill not confirmed in time')),
+ SHUTDOWN_KILL_DEADLINE_MS
+ )
+ timer.unref?.()
+ p.then(
+ (v) => {
+ clearTimeout(timer)
+ resolve(v)
+ },
+ (e) => {
+ clearTimeout(timer)
+ reject(e)
+ }
+ )
+ })
+ const results = await Promise.allSettled(targets.map((session) => withDeadline(endOne(session))))
+ const failed: string[] = []
+ const ended: string[] = []
+ results.forEach((r, i) => {
+ if (r.status === 'fulfilled') ended.push(r.value)
+ else failed.push(targets[i].name)
+ })
+ // A session that slipped in through a path the guard does not cover would still be running.
+ for (const session of sessions.values()) {
+ if (!session.exited && !failed.includes(session.name)) failed.push(session.name)
+ }
+ if (failed.length > 0) {
+ shuttingDown = false
+ scheduleGraceExitIfEmpty()
+ log(`shutdown incomplete — still running: ${failed.join(', ')}`)
+ throw new Error(`session-host could not end: ${failed.join(', ')}`)
+ }
+ log(`shutdown: ended ${ended.length} session(s)`)
+ return { ended }
+ }
+
+ /** Exit after the shutdown reply has been FLUSHED to the requester — the reply is the caller's
+ * only proof the sessions ended, so it must not be lost to process exit. Bounded: a peer that
+ * never reads cannot hold the host up. */
+ function exitAfterShutdown(socket: net.Socket): void {
+ try {
+ server.close()
+ } catch {
+ /* already closed */
+ }
+ for (const other of liveSockets) if (other !== socket) other.destroy()
+ let done = false
+ const finish = (): void => {
+ if (done) return
+ done = true
+ cleanupFiles()
+ process.exit(0)
+ }
+ setTimeout(finish, 2_000).unref?.()
+ socket.end(finish)
+ }
+
async function dispatch(
req: SessionHostRequest,
socket: net.Socket,
clientProtocolVersion: 1 | 2
): Promise<{ ok: true; result?: unknown } | { ok: false; error: string }> {
+ if (
+ shuttingDown &&
+ (req.cmd === 'attach' || req.cmd === 'attachExisting' || req.cmd === 'executeLaunch')
+ ) {
+ return { ok: false, error: 'session-host is shutting down for an update' }
+ }
switch (req.cmd) {
case 'attach':
return { ok: true, result: withGeometry(req.name, socket, await handleAttach(req, socket)) }
@@ -956,6 +1057,8 @@ async function main(): Promise<void> {
return { ok: true, result: { names: [...sessions.keys()] } satisfies ListSessionsResult }
case 'ping':
return { ok: true }
+ case 'shutdown':
+ return { ok: true, result: await handleShutdown(socket) }
default:
return { ok: false, error: `unknown command` }
}
@@ -977,6 +1080,7 @@ async function main(): Promise<void> {
encodeFrame({ id: req.id, ...res }),
sessions.values()
)
+ if (req.cmd === 'shutdown' && res.ok) exitAfterShutdown(socket)
} catch (e) {
writeSessionHostFrame(
socket,
diff --git a/src/session-host/protocol.ts b/src/session-host/protocol.ts
index 14e17421f..5bdae9e02 100644
--- a/src/session-host/protocol.ts
+++ b/src/session-host/protocol.ts
@@ -128,6 +128,12 @@ export type SessionHostRequest =
| { id: number; cmd: 'detach'; name: string }
| { id: number; cmd: 'listSessions' }
| { id: number; cmd: 'ping' }
+ /** Prepare-for-update (issue #829): end EVERY session's process tree through the ordinary kill
+ * path, reply, then exit the host process. Accepted only from a connection that negotiated the
+ * `shutdown` feature at hello — an older client never sends it, and an older host answers
+ * `unknown command` without the app ever asking. Persisted node metadata is the APP's and is
+ * never touched here: nodes stay on the canvas and cold-restore on the next launch. */
+ | { id: number; cmd: 'shutdown' }
/** Host → client response to a request, correlated by `id`. */
export type SessionHostResponse =
@@ -199,8 +205,16 @@ export interface AttachResult {
geometry?: { cols: number; rows: number }
}
/** Additive, independently negotiated capabilities (see the `hello` request). */
-export type SessionHostFeature = 'geometry'
-export const SESSION_HOST_FEATURES: readonly SessionHostFeature[] = ['geometry']
+export type SessionHostFeature = 'geometry' | 'shutdown'
+export const SESSION_HOST_FEATURES: readonly SessionHostFeature[] = ['geometry', 'shutdown']
+
+/** `result` of a successful `shutdown`: the session names whose process trees were ended. The
+ * host exits right after this reply is flushed. A shutdown that could not confirm every kill
+ * answers `ok: false` naming the sessions it could not end, and the host STAYS UP (accepting
+ * attaches again) — a partial shutdown must never be reported as done. */
+export interface ShutdownResult {
+ ended: string[]
+}
/** `result` of a v2 `hello`. `features` is absent from a host that predates feature negotiation. */
export interface HelloResult {
diff --git a/src/session-host/shutdown-host.test.ts b/src/session-host/shutdown-host.test.ts
new file mode 100644
index 000000000..a06fe82c4
--- /dev/null
+++ b/src/session-host/shutdown-host.test.ts
@@ -0,0 +1,261 @@
+// Issue #829: the prepare-for-update `shutdown` command, driven against the REAL bundled host over
+// its socket protocol (the same harness as geometry-host.test.ts). The rules it pins: only a
+// connection that negotiated the feature may ask, every session ends through the ordinary kill
+// path (an exit frame each) before the reply, the host exits only after a COMPLETE shutdown, and a
+// kill it cannot confirm fails the whole shutdown by name while the host keeps serving.
+import { afterEach, describe, expect, it } from 'vitest'
+import { spawn, type ChildProcess } from 'child_process'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'fs'
+import net, { type Socket } from 'net'
+import os from 'os'
+import path from 'path'
+import { build, type Plugin } from 'esbuild'
+import {
+ LineFramer,
+ SESSION_HOST_PROTOCOL_VERSION,
+ encodeFrame,
+ type SessionHostEvent,
+ type SessionHostFrame,
+ type SessionHostResponse,
+ type SessionHostSpawnOptions
+} from './protocol'
+import { sessionHostPaths, type SessionHostState } from './paths'
+
+function fakePtyPlugin(): Plugin {
+ return {
+ name: 'session-host-shutdown-fake-pty',
+ setup(bundle) {
+ bundle.onResolve({ filter: /^node-pty$/ }, () => ({ path: 'node-pty', namespace: 'sd' }))
+ bundle.onLoad({ filter: /^node-pty$/, namespace: 'sd' }, () => ({
+ loader: 'js',
+ contents: `
+ export function spawn(file) {
+ let onExit
+ return {
+ pid: 4343,
+ onData() {},
+ onExit(cb) { onExit = cb },
+ write() {},
+ resize() {},
+ pause() {},
+ resume() {},
+ kill() {
+ if (file === 'unkillable-shell') throw new Error('kill refused')
+ setTimeout(() => onExit?.({ exitCode: 0 }), 20)
+ }
+ }
+ }
+ `
+ }))
+ }
+ }
+}
+
+async function waitForIdentity(dataDir: string): Promise<{ state: SessionHostState; token: string }> {
+ const paths = sessionHostPaths(dataDir)
+ for (let attempt = 0; attempt < 200; attempt++) {
+ try {
+ const state = JSON.parse(readFileSync(paths.statePath, 'utf8')) as SessionHostState
+ const token = readFileSync(paths.tokenPath, 'utf8').trim()
+ if (state.endpoint && token) return { state, token }
+ } catch {
+ /* publication is asynchronous by design; keep polling within the test bound */
+ }
+ await new Promise((resolve) => setTimeout(resolve, 20))
+ }
+ throw new Error('session host did not publish its identity')
+}
+
+type Connection = {
+ socket: Socket
+ events: SessionHostEvent[]
+ request(frame: Record<string, unknown> & { id: number }): Promise<SessionHostResponse>
+}
+
+function connect(endpoint: string): Promise<Connection> {
+ return new Promise((resolve, reject) => {
+ const socket = net.connect(endpoint)
+ const framer = new LineFramer()
+ const events: SessionHostEvent[] = []
+ const waiters = new Map<number, (frame: SessionHostResponse) => void>()
+ socket.on('data', (chunk: Buffer) => {
+ for (const frame of framer.push<SessionHostFrame>(chunk.toString('utf8'))) {
+ if ('type' in frame) {
+ events.push(frame)
+ continue
+ }
+ waiters.get(frame.id)?.(frame)
+ waiters.delete(frame.id)
+ }
+ })
+ socket.once('error', reject)
+ socket.once('connect', () =>
+ resolve({
+ socket,
+ events,
+ request: (frame) =>
+ new Promise<SessionHostResponse>((done, fail) => {
+ const timer = setTimeout(() => fail(new Error(`timed out on ${frame.id}`)), 4_000)
+ waiters.set(frame.id, (response) => {
+ clearTimeout(timer)
+ done(response)
+ })
+ socket.write(encodeFrame(frame))
+ })
+ })
+ )
+ })
+}
+
+function waitForExit(child: ChildProcess): Promise<void> {
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve()
+ return new Promise((resolve) => child.once('exit', () => resolve()))
+}
+
+const SPAWN: SessionHostSpawnOptions = {
+ cwd: '.',
+ shell: 'fake-shell',
+ args: [],
+ env: {},
+ cols: 80,
+ rows: 24
+}
+
+const cleanupPaths: string[] = []
+afterEach(() => {
+ for (const target of cleanupPaths.splice(0)) {
+ rmSync(target, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 })
+ }
+})
+
+
+const SHUTDOWN_FEATURES = ['geometry', 'shutdown']
+
+async function startHost(): Promise<{
+ child: ChildProcess
+ dataDir: string
+ state: SessionHostState
+ token: string
+}> {
+ const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-shutdown-'))
+ cleanupPaths.push(fixtureDir)
+ const dataDir = path.join(fixtureDir, 'user-data')
+ mkdirSync(dataDir)
+ const paths = sessionHostPaths(dataDir)
+ if (process.platform !== 'win32') cleanupPaths.push(paths.endpoint)
+ const bundlePath = path.join(fixtureDir, 'host.cjs')
+ await build({
+ absWorkingDir: process.cwd(),
+ entryPoints: ['src/session-host/host.ts'],
+ outfile: bundlePath,
+ bundle: true,
+ platform: 'node',
+ format: 'cjs',
+ plugins: [fakePtyPlugin()],
+ logLevel: 'silent'
+ })
+ const child = spawn(process.execPath, [bundlePath, dataDir], {
+ cwd: process.cwd(),
+ stdio: 'ignore',
+ windowsHide: true
+ })
+ const { state, token } = await waitForIdentity(dataDir)
+ return { child, dataDir, state, token }
+}
+
+async function hello(conn: Connection, token: string, features?: string[]): Promise<void> {
+ const res = await conn.request({
+ id: 1,
+ cmd: 'hello',
+ token,
+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION,
+ ...(features ? { features } : {})
+ })
+ expect(res.ok).toBe(true)
+}
+
+describe('session-host shutdown (issue #829)', () => {
+ it('ends every session, replies with their names, then exits and removes its identity', async () => {
+ const { child, dataDir, state, token } = await startHost()
+ const sockets: Socket[] = []
+ try {
+ const conn = await connect(state.endpoint)
+ sockets.push(conn.socket)
+ const res = await conn.request({
+ id: 1,
+ cmd: 'hello',
+ token,
+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION,
+ features: SHUTDOWN_FEATURES
+ })
+ expect(res).toMatchObject({ ok: true, result: { features: SHUTDOWN_FEATURES } })
+ for (const [id, name] of [[2, 'nt-a'], [3, 'nt-b']] as const) {
+ const created = await conn.request({ id, cmd: 'attach', name, spawn: SPAWN, scrollback: 100 })
+ expect(created.ok).toBe(true)
+ }
+ const exited = waitForExit(child)
+ const done = await conn.request({ id: 4, cmd: 'shutdown' })
+ expect(done.ok).toBe(true)
+ expect(((done as { result: { ended: string[] } }).result.ended).sort()).toEqual(['nt-a', 'nt-b'])
+ await exited
+ expect(child.exitCode).toBe(0)
+ // Each session got its ordinary exit frame first: the client sees a normal session end.
+ expect(conn.events.filter((e) => e.type === 'exit').map((e) => e.name).sort()).toEqual([
+ 'nt-a',
+ 'nt-b'
+ ])
+ expect(existsSync(sessionHostPaths(dataDir).statePath)).toBe(false)
+ expect(existsSync(sessionHostPaths(dataDir).tokenPath)).toBe(false)
+ } finally {
+ for (const socket of sockets) socket.destroy()
+ child.kill()
+ await waitForExit(child)
+ }
+ }, 30_000)
+
+ it('refuses a connection that did not negotiate the feature, and keeps serving', async () => {
+ const { child, state, token } = await startHost()
+ const sockets: Socket[] = []
+ try {
+ const conn = await connect(state.endpoint)
+ sockets.push(conn.socket)
+ await hello(conn, token, ['geometry'])
+ const created = await conn.request({ id: 2, cmd: 'attach', name: 'nt-a', spawn: SPAWN, scrollback: 100 })
+ expect(created.ok).toBe(true)
+ const refused = await conn.request({ id: 3, cmd: 'shutdown' })
+ expect(refused).toMatchObject({ ok: false })
+ const still = await conn.request({ id: 4, cmd: 'hasSession', name: 'nt-a' })
+ expect(still).toMatchObject({ ok: true, result: { exists: true } })
+ expect(child.exitCode).toBeNull()
+ } finally {
+ for (const socket of sockets) socket.destroy()
+ child.kill()
+ await waitForExit(child)
+ }
+ }, 30_000)
+
+ it('names a session it could not end, stays up, and accepts attaches again', async () => {
+ const { child, state, token } = await startHost()
+ const sockets: Socket[] = []
+ try {
+ const conn = await connect(state.endpoint)
+ sockets.push(conn.socket)
+ await hello(conn, token, SHUTDOWN_FEATURES)
+ expect((await conn.request({ id: 2, cmd: 'attach', name: 'nt-ok', spawn: SPAWN, scrollback: 100 })).ok).toBe(true)
+ const stuck = { ...SPAWN, shell: 'unkillable-shell' }
+ expect((await conn.request({ id: 3, cmd: 'attach', name: 'nt-stuck', spawn: stuck, scrollback: 100 })).ok).toBe(true)
+ const res = await conn.request({ id: 4, cmd: 'shutdown' })
+ expect(res.ok).toBe(false)
+ expect((res as { error: string }).error).toContain('nt-stuck')
+ expect((res as { error: string }).error).not.toContain('nt-ok')
+ // Not shutting down any more: a new session can be created.
+ const again = await conn.request({ id: 5, cmd: 'attach', name: 'nt-new', spawn: SPAWN, scrollback: 100 })
+ expect(again.ok).toBe(true)
+ expect(child.exitCode).toBeNull()
+ } finally {
+ for (const socket of sockets) socket.destroy()
+ child.kill()
+ await waitForExit(child)
+ }
+ }, 30_000)
+})
diff --git a/src/shared/host-control.ts b/src/shared/host-control.ts
index efa682d02..748ac0039 100644
--- a/src/shared/host-control.ts
+++ b/src/shared/host-control.ts
@@ -74,6 +74,12 @@ export const HOST_ONLY_CHANNELS: ReadonlySet<string> = new Set([
IPC.projectSetupConsentSubmit,
IPC.projectSetupRequestTrust,
IPC.ptyLaunchHeadless,
+ // Prepare-for-update ends EVERY session on this machine's session host and quits the app. Only
+ // the host's own user may do that. Raw ipcMain handlers (no peer reaches them); listed here too
+ // so moving them onto the platform table later cannot quietly open them.
+ IPC.appUpdatePrepInspect,
+ IPC.appUpdatePrepShutdown,
+ IPC.appUpdatePrepQuit,
// A board comment that @mentions a session types into that session's pane. Only the host's own
// user may do that: a relay peer's comment is display-only. Registered with a raw ipcMain handler
// (so no peer can reach it at all); listed here too, so moving it onto the platform table later
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 5f38439bf..d13ac03a3 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -329,6 +329,10 @@ export const IPC = {
appGetVersion: 'app:get-version',
appUserDataDir: 'app:user-data-dir',
appUpdatePolicy: 'app:update-policy',
+ // Prepare-for-update (Windows, issue #829). Raw ipcMain handlers, main-window senders only.
+ appUpdatePrepInspect: 'app:update-prep-inspect',
+ appUpdatePrepShutdown: 'app:update-prep-shutdown',
+ appUpdatePrepQuit: 'app:update-prep-quit',
licenseActivate: 'license:activate',
licenseDeactivate: 'license:deactivate',
licenseStatus: 'license:status',
diff --git a/src/shared/session-name.ts b/src/shared/session-name.ts
new file mode 100644
index 000000000..00d04ad59
--- /dev/null
+++ b/src/shared/session-name.ts
@@ -0,0 +1,6 @@
+/** Per-node persistent session name (tmux, Zellij and the Windows session host all use it). Must
+ * stay stable — it is the persistence key. Lives in `src/shared` so the renderer can map a host's
+ * session list back to canvas nodes with the exact rule core used to name them. */
+export function nodeSessionName(persistKey: string): string {
+ return `nt-${persistKey.replace(/[^a-zA-Z0-9_-]/g, '_')}`
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 7b117fc41..349ef7a0f 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2763,6 +2763,13 @@ export interface UpdateApi {
getPolicy(): Promise<UpdatePolicy>
/** Quit and install the staged update. */
restart(): void
+ /** Prepare-for-update (Windows session host, issue #829): what the running host holds. Never
+ * launches a host. Answers `unsupported` off Windows and in the Server Edition. */
+ prepareInspect(): Promise<import('./update-prep').UpdatePrepInspection>
+ /** Prepare-for-update: ask the host to end every session and exit, and confirm it did. */
+ prepareShutdownHost(): Promise<import('./update-prep').UpdatePrepShutdown>
+ /** Prepare-for-update: quit the app (no quit confirmation) once the host is gone. */
+ prepareQuit(): void
}
/** A single news/announcement item, fetched from the remote announcements feed. */
diff --git a/src/shared/update-prep.ts b/src/shared/update-prep.ts
new file mode 100644
index 000000000..fdb8e7fad
--- /dev/null
+++ b/src/shared/update-prep.ts
@@ -0,0 +1,46 @@
+// Prepare-for-update (issue #829, step 2): the wire shapes between the desktop main process and
+// the renderer's prepare flow. Windows only — there the session host outlives the app by design
+// and holds the install directory, so the installer's preflight refuses to run until it is gone.
+// The flow ends every session through the host's own `shutdown` command (never a name-based kill,
+// never node deletion) after giving each idle agent a chance to exit cleanly.
+
+/** What the running host holds right now. Asked without ever launching a host. */
+export type UpdatePrepInspection =
+ /** Not Windows, or the session-host backend is not the one this app uses. */
+ | { kind: 'unsupported' }
+ /** No host is running: nothing holds the install directory on its behalf. */
+ | { kind: 'no-host' }
+ | {
+ kind: 'host'
+ /** Host session names (`nt-<nodeId>`), every project's — closed ones included. */
+ sessions: string[]
+ /** The host speaks `shutdown`. False for a host started by an older build, which must be
+ * handled by the manual steps — the app never kills a host by itself. */
+ shutdownSupported: boolean
+ /** Core's status mirror per session: the only state source for nodes whose project is not
+ * 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 }>
+ }
+ | { kind: 'error'; error: string }
+
+export type UpdatePrepShutdown =
+ | { kind: 'unsupported' }
+ | { kind: 'no-host' }
+ /** The host ended every session and its process exited. */
+ | { kind: 'shut-down'; ended: string[] }
+ /** The host answered that it could not end some sessions; it is still running and serving. */
+ | { kind: 'failed'; error: string }
+ /** No answer we can trust (timeout, lost connection, host still alive after its reply). */
+ | { kind: 'unconfirmed'; error: string }
+ /** The host predates the `shutdown` feature. */
+ | { kind: 'host-unsupported' }
+
+/** 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[] = [
+ 'Save work in every terminal and agent, and exit each program and its shell normally. Do not use End session or delete nodes — those remove the nodes.',
+ 'Quit nodeterm and wait at least 30 seconds: an empty session host shuts itself down.',
+ 'If nodeterm-session-host.exe is still running, open Task Manager → Details, verify it is this installation’s host for your user, and end only that process (every process it owns stops).',
+ 'Run the installer. Your canvas nodes stay; agents resume from their saved conversations on the next launch.'
+]