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(quit): flush pending canvas edits before quit and restart-to-update

review87b1352df098
diff --git a/src/core/check.test.ts b/src/core/check.test.ts
new file mode 100644
index 000000000..72ec9f271
--- /dev/null
+++ b/src/core/check.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest'
+import { sanitizeCheckForTest as sanitize } from './check'
+
+describe('/v1/check sanitize — update notes', () => {
+ it('carries notes only together with the version they describe', () => {
+ expect(sanitize({ update: { mandatory: false, notes: '- a', latestVersion: '1.2.0' } }).update).toEqual({
+ minSupported: null,
+ mandatory: false,
+ notes: '- a',
+ latestVersion: '1.2.0'
+ })
+ expect(sanitize({ update: { notes: '- a' } }).update).toEqual({ minSupported: null, mandatory: false })
+ expect(sanitize({ update: { notes: 3, latestVersion: '1.2.0' } }).update).toEqual({
+ minSupported: null,
+ mandatory: false
+ })
+ })
+
+ it('keeps the policy shape when the feed sends nothing', () => {
+ expect(sanitize(null).update).toEqual({ minSupported: null, mandatory: false })
+ expect(sanitize({ update: { minSupported: '0.5.0', mandatory: true } }).update).toEqual({
+ minSupported: '0.5.0',
+ mandatory: true
+ })
+ })
+
+ it('caps the notes', () => {
+ expect(sanitize({ update: { notes: 'x'.repeat(50_000), latestVersion: '1' } }).update.notes!.length).toBe(16 * 1024)
+ })
+})
diff --git a/src/core/check.ts b/src/core/check.ts
index b7aa0ff72..968038bc6 100644
--- a/src/core/check.ts
+++ b/src/core/check.ts
@@ -49,9 +49,20 @@ function sanitize(data: unknown): CheckResult {
minSupported: typeof u.minSupported === 'string' ? u.minSupported : null,
mandatory: u.mandatory === true
}
+ // Optional release highlights for the update card. Both or neither: notes without the version
+ // they describe could be pinned to the wrong card.
+ if (typeof u.notes === 'string' && u.notes.trim() && typeof u.latestVersion === 'string' && u.latestVersion) {
+ update.notes = u.notes.slice(0, NOTES_MAX)
+ update.latestVersion = u.latestVersion.slice(0, 64)
+ }
return { messages, update }
}
+const NOTES_MAX = 16 * 1024
+
+/** Test seam: the sanitizer is the whole contract with the feed's shape. */
+export const sanitizeCheckForTest = sanitize
+
let cache: { at: number; data: CheckResult } | null = null
export async function fetchCheck(): Promise<CheckResult> {
diff --git a/src/main/index.ts b/src/main/index.ts
index b23ed71b1..bb2b04583 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -164,6 +164,7 @@ import {
generateTerminalName
} from '../core/commit-message'
import { initUpdater } from './updater'
+import { requestRendererFlush } from './renderer-flush'
import { fetchCheck } from '../core/check'
import {
hookServer,
@@ -5347,7 +5348,15 @@ app.on('before-quit', (e) => {
// Pending throttled .nodeterm mirror writes must land BEFORE the ControlMasters die — killing
// a master mid-write used to leave a truncated project.json on the server. The masters are
// therefore kept up through the raced flush and dropped on the second before-quit pass.
- const flush = Promise.allSettled([remoteWorkspaceIO.flush(), ptyManager.killAll(), watchLinksStopped])
+ // The renderer's debounced canvas save rides the same race (src/main/renderer-flush.ts, capped
+ // at 1 s and never throwing): ⌘Q / tray Quit used to drop the last ~800 ms of canvas edits. A
+ // restart-to-update flushes earlier, in the updater — on macOS its windows are gone by now.
+ const flush = Promise.allSettled([
+ requestRendererFlush(getMainWindow()?.webContents, ipcMain),
+ remoteWorkspaceIO.flush(),
+ ptyManager.killAll(),
+ watchLinksStopped
+ ])
void Promise.race([flush, new Promise((r) => setTimeout(r, 1500))])
// Then let whisper go. A dictation still transcribing when Electron tears down the main
// process's node env aborts the WHOLE app from inside the native addon (SIGABRT in
diff --git a/src/main/renderer-flush.test.ts b/src/main/renderer-flush.test.ts
new file mode 100644
index 000000000..8b8501054
--- /dev/null
+++ b/src/main/renderer-flush.test.ts
@@ -0,0 +1,65 @@
+import { EventEmitter } from 'events'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { IPC } from '../shared/ipc'
+import { requestRendererFlush, type FlushIpc } from './renderer-flush'
+
+let ipc: EventEmitter & FlushIpc
+const sentIds: string[] = []
+const target = (opts: { destroyed?: boolean; reply?: 'ours' | 'stale' | 'none'; throws?: boolean } = {}) => ({
+ isDestroyed: () => !!opts.destroyed,
+ send: (channel: string, id: unknown) => {
+ if (opts.throws) throw new Error('Object has been destroyed')
+ expect(channel).toBe(IPC.appFlushRequest)
+ sentIds.push(id as string)
+ if (opts.reply === 'ours') queueMicrotask(() => ipc.emit(IPC.appFlushDone, {}, id))
+ if (opts.reply === 'stale') queueMicrotask(() => ipc.emit(IPC.appFlushDone, {}, 'flush-0'))
+ }
+})
+
+beforeEach(() => {
+ ipc = new EventEmitter() as EventEmitter & FlushIpc
+ sentIds.length = 0
+ vi.useFakeTimers()
+})
+afterEach(() => vi.useRealTimers())
+
+describe('requestRendererFlush', () => {
+ it('resolves flushed when the renderer answers with the same id', async () => {
+ await expect(requestRendererFlush(target({ reply: 'ours' }), ipc)).resolves.toBe('flushed')
+ expect(ipc.listenerCount(IPC.appFlushDone)).toBe(0)
+ })
+
+ it('times out (never hangs) when the renderer does not answer', async () => {
+ const p = requestRendererFlush(target({ reply: 'none' }), ipc, 1000)
+ vi.advanceTimersByTime(999)
+ let settled = false
+ void p.then(() => (settled = true))
+ await Promise.resolve()
+ expect(settled).toBe(false)
+ vi.advanceTimersByTime(1)
+ await expect(p).resolves.toBe('timeout')
+ expect(ipc.listenerCount(IPC.appFlushDone)).toBe(0)
+ })
+
+ it('ignores a stale reply for another request id', async () => {
+ const p = requestRendererFlush(target({ reply: 'stale' }), ipc, 1000)
+ await Promise.resolve()
+ vi.advanceTimersByTime(1000)
+ await expect(p).resolves.toBe('timeout')
+ })
+
+ it('answers no-window without a live target — and never throws', async () => {
+ await expect(requestRendererFlush(undefined, ipc)).resolves.toBe('no-window')
+ await expect(requestRendererFlush(target({ destroyed: true }), ipc)).resolves.toBe('no-window')
+ await expect(requestRendererFlush(target({ throws: true }), ipc)).resolves.toBe('no-window')
+ expect(ipc.listenerCount(IPC.appFlushDone)).toBe(0)
+ })
+
+ it('mints a distinct id per request', async () => {
+ await Promise.all([
+ requestRendererFlush(target({ reply: 'ours' }), ipc),
+ requestRendererFlush(target({ reply: 'ours' }), ipc)
+ ])
+ expect(new Set(sentIds).size).toBe(2)
+ })
+})
diff --git a/src/main/renderer-flush.ts b/src/main/renderer-flush.ts
new file mode 100644
index 000000000..8ab85152d
--- /dev/null
+++ b/src/main/renderer-flush.ts
@@ -0,0 +1,67 @@
+// Ask the renderer to write its pending canvas edits before the app goes away.
+//
+// Canvas saves are debounced (SAVE_DEBOUNCE_MS), and nothing flushed them on the way out, so a node
+// move / resize / rename / camera change in the last moments before a quit or a restart-to-update was
+// lost. Main sends a request id; the renderer persists (when dirty and no conflict bar is up) and
+// answers with the same id. The wait is capped and this NEVER throws or rejects: a wedged or absent
+// renderer must never be able to block a quit or an update install.
+//
+// On macOS `quitAndInstall()` closes every window BEFORE `before-quit` runs, so the restart path has
+// to flush before it calls quitAndInstall — a flush only in before-quit would find no renderer.
+import { IPC } from '../shared/ipc'
+
+export type FlushOutcome = 'flushed' | 'timeout' | 'no-window'
+
+/** The slice of WebContents this needs (`isDestroyed` optional: `getMainWindow()` already drops a
+ * destroyed window, and its structural webContents type does not carry the method). */
+export interface FlushTarget {
+ isDestroyed?(): boolean
+ send(channel: string, ...args: unknown[]): void
+}
+
+/** The slice of ipcMain this needs. */
+export interface FlushIpc {
+ on(channel: string, listener: (event: unknown, ...args: unknown[]) => void): unknown
+ removeListener(channel: string, listener: (event: unknown, ...args: unknown[]) => void): unknown
+}
+
+export const RENDERER_FLUSH_TIMEOUT_MS = 1000
+
+let seq = 0
+
+export function requestRendererFlush(
+ target: FlushTarget | null | undefined,
+ ipc: FlushIpc,
+ timeoutMs = RENDERER_FLUSH_TIMEOUT_MS
+): Promise<FlushOutcome> {
+ return new Promise<FlushOutcome>((resolve) => {
+ let alive = false
+ try {
+ alive = !!target && !target.isDestroyed?.()
+ } catch {
+ alive = false
+ }
+ if (!target || !alive) {
+ resolve('no-window')
+ return
+ }
+ const id = `flush-${++seq}`
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const finish = (outcome: FlushOutcome): void => {
+ if (timer) clearTimeout(timer)
+ ipc.removeListener(IPC.appFlushDone, onDone)
+ resolve(outcome)
+ }
+ // A reply for another (stale, timed-out) request is ignored — only ours settles this one.
+ const onDone = (_e: unknown, replyId?: unknown): void => {
+ if (replyId === id) finish('flushed')
+ }
+ ipc.on(IPC.appFlushDone, onDone)
+ timer = setTimeout(() => finish('timeout'), timeoutMs)
+ try {
+ target.send(IPC.appFlushRequest, id)
+ } catch {
+ finish('no-window')
+ }
+ })
+}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 04964624e..f1a036534 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -18,6 +18,7 @@ import type {
RemoteUsageQuery,
SessionMemoryQuery,
UpdateInfo,
+ UpdateInstalling,
UpdateProgress,
Workspace,
WorkspaceSaveOptions,
@@ -183,7 +184,19 @@ const api: NodeTerminalApi = {
// behalf. `HeadlessNodeFactory` is Server Edition only — the desktop's canvas-control verbs run
// through the renderer's own React Flow state, and its watcher path stays on onExternalChange.
// A real subscription would be dead wiring for a channel this main process never broadcasts.
- onServerChange: (_cb: (project: Project) => void) => () => {}
+ onServerChange: (_cb: (project: Project) => void) => () => {},
+ // Quit / restart-to-update flush (src/main/renderer-flush.ts): answer with the request id once
+ // the callback settles, whether it saved, had nothing to save, or failed.
+ onFlushRequest: (cb: () => Promise<unknown> | void) => {
+ const h = (_e: unknown, id: string) => {
+ void Promise.resolve()
+ .then(cb)
+ .catch(() => {})
+ .finally(() => ipcRenderer.send(IPC.appFlushDone, id))
+ }
+ ipcRenderer.on(IPC.appFlushRequest, h)
+ return () => ipcRenderer.removeListener(IPC.appFlushRequest, h)
+ }
},
projectSettings: {
read: (projectId: string) => ipcRenderer.invoke(IPC.projectSettingsRead, projectId),
@@ -499,6 +512,11 @@ const api: NodeTerminalApi = {
ipcRenderer.on(IPC.appUpdateNoChannel, handler)
return () => ipcRenderer.removeListener(IPC.appUpdateNoChannel, handler)
},
+ onInstalling: (listener) => {
+ const handler = (_e: unknown, s: UpdateInstalling) => listener(s)
+ ipcRenderer.on(IPC.appUpdateInstalling, handler)
+ return () => ipcRenderer.removeListener(IPC.appUpdateInstalling, handler)
+ },
check: () => ipcRenderer.send(IPC.appCheckForUpdates),
getVersion: () => ipcRenderer.invoke(IPC.appGetVersion),
getPolicy: () => ipcRenderer.invoke(IPC.appUpdatePolicy),
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index b450be182..c3b9cd351 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -246,6 +246,8 @@ export function buildStubApi(): Omit<
// Server Edition has no updater at all (initUpdater runs only in src/main) and a browser
// tab cannot self-install, so there is no channel state to report either way.
onNoChannel: noopUnsub,
+ // No self-install in a browser, so there is never an install in progress to report.
+ onInstalling: noopUnsub,
check: noop,
getVersion: U('updates.getVersion'),
// Boot path awaits this and reads `p.mandatory` UNGUARDED (UpdateCard.tsx), so the old
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index d70b36b6e..61d027b31 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -379,7 +379,10 @@ export function buildRealApi(
// REAL: Server Edition canvas control broadcasts its own persisted bridge/rope changes here —
// wider than the node-only canvas:mut vocabulary, but ours, so they must not travel the
// outside-edit channel and end up behind the conflict bar (see server/canvas-control.ts).
- onServerChange: (cb) => client.subscribe(IPC.workspaceServerChange, cb as Listener)
+ onServerChange: (cb) => client.subscribe(IPC.workspaceServerChange, cb as Listener),
+ // Documented degrade: the quit / restart-to-update flush is a desktop main-process request.
+ // The server never quits on a tab's behalf, and the debounced autosave covers a browser.
+ onFlushRequest: () => () => {}
}
// REAL: WorkspaceStore (core) registers the project-settings:* channels too — same
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index fd61ff8d3..09658578d 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -206,6 +206,7 @@ import { describeOs, REPO_URL } from '../lib/bugReport'
import { shouldReleasePaneFocus } from '../lib/paneFocus'
import {
autosaveDelay,
+ shouldFlushOnQuit,
nextSaveDelivery,
type SaveDelivery
} from '../lib/savePersistence'
@@ -4088,6 +4089,17 @@ export function Canvas() {
})
}, [])
+ // Quit / restart-to-update: main asks for the pending edits the debounce above still holds
+ // (src/main/renderer-flush.ts). Without this, the last ~800 ms of node moves / renames / camera
+ // changes were lost on every ⌘Q and every update restart. Same conflict rule as the autosave.
+ useEffect(
+ () =>
+ window.nodeTerminal.workspace.onFlushRequest(async () => {
+ if (shouldFlushOnQuit(dirtyRef.current, !!conflictRef.current)) await persist()
+ }),
+ [persist]
+ )
+
// Debounced auto-save for canvas edits. Suppressed while a conflict bar is up: the bar only ever
// appears WHILE dirty, so without this gate the 800ms timer would fire and silently "keep mine"
// (overwrite the external disk version) before the user can choose. `conflict` is a dep so
diff --git a/src/renderer/lib/savePersistence.test.ts b/src/renderer/lib/savePersistence.test.ts
index 07c51ec93..d21f0daf0 100644
--- a/src/renderer/lib/savePersistence.test.ts
+++ b/src/renderer/lib/savePersistence.test.ts
@@ -6,6 +6,7 @@ import {
nextSaveDelivery,
saveFailureMessage,
saveRetryDelay,
+ shouldFlushOnQuit,
SAVE_DEBOUNCE_MS,
SAVE_RETRY_ATTEMPTS,
type SaveDelivery
@@ -142,3 +143,12 @@ describe('the call site still honours the rule', () => {
expect(SRC).not.toContain('void api.workspace.save(')
})
})
+
+describe('shouldFlushOnQuit', () => {
+ it('writes only dirty edits, and never over an open conflict bar', () => {
+ expect(shouldFlushOnQuit(true, false)).toBe(true)
+ expect(shouldFlushOnQuit(false, false)).toBe(false)
+ expect(shouldFlushOnQuit(true, true)).toBe(false)
+ expect(shouldFlushOnQuit(false, true)).toBe(false)
+ })
+})
diff --git a/src/renderer/lib/savePersistence.ts b/src/renderer/lib/savePersistence.ts
index 56a71a8d5..480679015 100644
--- a/src/renderer/lib/savePersistence.ts
+++ b/src/renderer/lib/savePersistence.ts
@@ -77,6 +77,15 @@ export function autosaveDelay(
return saveRetryDelay(delivery.attempts)
}
+/**
+ * Whether main's quit / restart-to-update flush request (`workspace.onFlushRequest`) should write
+ * now. Same conflict rule as `autosaveDelay`: with the conflict bar up the user owes a decision,
+ * and a flush on the way out must not silently "keep mine" over the external version.
+ */
+export function shouldFlushOnQuit(dirty: boolean, conflictOpen: boolean): boolean {
+ return dirty && !conflictOpen
+}
+
/**
* The sentence the save-failure strip shows, or `null` while there is nothing to report.
*
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 60d0b0d4c..8f39d64c1 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -346,6 +346,12 @@ export const IPC = {
appUpdatePrepInspect: 'app:update-prep-inspect',
appUpdatePrepShutdown: 'app:update-prep-shutdown',
appUpdatePrepQuit: 'app:update-prep-quit',
+ /** main → renderer: restart-to-update was accepted; `{phase:'preparing'|'restarting', version}`. */
+ appUpdateInstalling: 'app:update-installing',
+ /** main → renderer: write any pending canvas edits now (payload: request id). Quit / restart. */
+ appFlushRequest: 'app:flush-request',
+ /** renderer → main: the flush for that request id settled. */
+ appFlushDone: 'app:flush-done',
licenseActivate: 'license:activate',
licenseDeactivate: 'license:deactivate',
licenseStatus: 'license:status',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 771ee3cd3..bafed0ac3 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1458,6 +1458,13 @@ export interface WorkspaceApi {
/** Fired when THIS core wrote the project itself (Server Edition headless canvas control: an agent
* opened, renamed, moved, closed…). Not an outside edit — the renderer merges it, never asks. */
onServerChange(cb: (project: Project) => void): () => void
+ /**
+ * Main asks for pending canvas edits to be written NOW — before a quit or a restart-to-update
+ * (`src/main/renderer-flush.ts`). The callback's settling is the answer; main waits at most ~1 s
+ * either way. Desktop only: the Server Edition has no main process to quit, so its bridge never
+ * fires it. Returns unsubscribe.
+ */
+ onFlushRequest(cb: () => Promise<unknown> | void): () => void
}
export interface ProjectSettingsApi {
@@ -2848,6 +2855,17 @@ export interface UpdatePolicy {
minSupported: string | null
/** True when the running version is below the minimum supported version. */
mandatory: boolean
+ /** Optional release highlights (markdown) the feed carries for `latestVersion`. */
+ notes?: string
+ /** The version `notes` describe. Notes are shown only on a card for this exact version. */
+ latestVersion?: string
+}
+
+/** Restart-to-update was accepted: `preparing` = waiting for the OS updater to stage it (macOS),
+ * `restarting` = the install is starting now. */
+export interface UpdateInstalling {
+ phase: 'preparing' | 'restarting'
+ version: string | null
}
export interface UpdateProgress {
@@ -2875,6 +2893,8 @@ export interface UpdateApi {
* and "we cannot look" are different facts with different remedies. Returns unsubscribe.
*/
onNoChannel(listener: () => void): () => void
+ /** Restart-to-update was accepted and is preparing / restarting. Returns unsubscribe. */
+ onInstalling(listener: (s: UpdateInstalling) => void): () => void
/** Trigger a manual update check. */
check(): void
/** The running app version. */