diff --git a/src/main/daemon/daemon-init.ts b/src/main/daemon/daemon-init.ts index 620a650da..caa5c7172 100644 --- a/src/main/daemon/daemon-init.ts +++ b/src/main/daemon/daemon-init.ts @@ -212,8 +212,8 @@ export async function initDaemonPtyProvider(): Promise { // separate process and survives app quit — sessions stay alive for warm // reattach on next launch. Leave history sessions marked "unclean" here so a // later daemon crash while Orca is closed is still recoverable on next launch. -export function disconnectDaemon(): void { - adapter?.disconnectOnly() +export async function disconnectDaemon(): Promise { + await adapter?.disconnectOnly() adapter = null } diff --git a/src/main/daemon/daemon-pty-adapter.ts b/src/main/daemon/daemon-pty-adapter.ts index 6a6b55430..09e3a02d5 100644 --- a/src/main/daemon/daemon-pty-adapter.ts +++ b/src/main/daemon/daemon-pty-adapter.ts @@ -131,7 +131,13 @@ export class DaemonPtyAdapter implements IPtyProvider { // an unclean shutdown → return saved scrollback so the renderer can // display the previous terminal content. if (result.isNew && restoreInfo) { - const scrollback = restoreInfo.rehydrateSequences + restoreInfo.snapshotAnsi + // Why: if the checkpoint was captured while an alternate-screen app + // (vim, less, htop) was active, rehydrateSequences contains \x1b[?1049h + // which would reopen the alternate buffer in a fresh shell. The old + // scrollback fallback explicitly truncated alt-screen content; replaying + // it here would leave the terminal stuck behind stale TUI content. + const prefix = restoreInfo.modes.alternateScreen ? '' : restoreInfo.rehydrateSequences + const scrollback = prefix + restoreInfo.snapshotAnsi const coldRestore = { scrollback, cwd: restoreInfo.cwd } this.coldRestoreCache.set(sessionId, coldRestore) if (this.historyManager) { @@ -386,15 +392,17 @@ export class DaemonPtyAdapter implements IPtyProvider { // the next launch detects them as crash-recoverable. // We write a final checkpoint before disconnecting so that if the daemon // later crashes while Orca is closed, checkpoint.json has recovery data. - disconnectOnly(): void { + async disconnectOnly(): Promise { if (this.checkpointInterval) { clearInterval(this.checkpointInterval) this.checkpointInterval = null } // Why: without a final checkpoint, sessions opened after the last timer // tick have no checkpoint.json on disk. If the detached daemon later - // dies, detectColdRestore finds nothing to restore from. - this.checkpointAllSessions() + // dies, detectColdRestore finds nothing to restore from. Must await + // before disconnecting — fire-and-forget would race with client.disconnect() + // and the pending getSnapshot RPCs would be rejected. + await this.checkpointAllSessions() this.removeEventListener?.() this.removeEventListener = null this.client.disconnect() @@ -411,27 +419,32 @@ export class DaemonPtyAdapter implements IPtyProvider { return } this.checkpointInterval = setInterval(() => { - this.checkpointAllSessions() + void this.checkpointAllSessions() }, DaemonPtyAdapter.CHECKPOINT_INTERVAL_MS) } // Why: the adapter runs in the Electron main process and does not have direct // access to daemon Session objects. It calls the getSnapshot RPC over the - // daemon socket per session. - private checkpointAllSessions(): void { + // daemon socket per session. Returns a promise that resolves when all + // checkpoint writes complete (callers that don't need to wait can void it). + private async checkpointAllSessions(): Promise { if (!this.historyManager) { return } + const promises: Promise[] = [] for (const sessionId of this.activeSessionIds) { - void this.client - .request('getSnapshot', { sessionId }) - .then((result) => { - if (result.snapshot && this.historyManager) { - return this.historyManager.checkpoint(sessionId, result.snapshot) - } - }) - .catch((err) => console.warn('[history] checkpoint failed:', sessionId, err)) + promises.push( + this.client + .request('getSnapshot', { sessionId }) + .then((result) => { + if (result.snapshot && this.historyManager) { + return this.historyManager.checkpoint(sessionId, result.snapshot) + } + }) + .catch((err) => console.warn('[history] checkpoint failed:', sessionId, err)) + ) } + await Promise.all(promises) } // Why: when the daemon process dies, operations fail with ENOENT (socket diff --git a/src/main/daemon/daemon-pty-router.test.ts b/src/main/daemon/daemon-pty-router.test.ts index 5273440d1..1594da80d 100644 --- a/src/main/daemon/daemon-pty-router.test.ts +++ b/src/main/daemon/daemon-pty-router.test.ts @@ -73,7 +73,7 @@ function createAdapter( clearTombstone: vi.fn(), reconcileOnStartup: vi.fn(async () => reconcileResult ?? { alive: sessions, killed: [] }), dispose: vi.fn(), - disconnectOnly: vi.fn(), + disconnectOnly: vi.fn(async () => {}), emitData: (id: string, data: string) => { for (const listener of dataListeners) { listener({ id, data }) diff --git a/src/main/daemon/daemon-pty-router.ts b/src/main/daemon/daemon-pty-router.ts index 03edb07fd..e69b21aa6 100644 --- a/src/main/daemon/daemon-pty-router.ts +++ b/src/main/daemon/daemon-pty-router.ts @@ -180,13 +180,11 @@ export class DaemonPtyRouter implements IPtyProvider { } } - disconnectOnly(): void { + async disconnectOnly(): Promise { for (const unsubscribe of this.unsubscribers.splice(0)) { unsubscribe() } - for (const adapter of this.allAdapters()) { - adapter.disconnectOnly() - } + await Promise.all([...this.allAdapters()].map((adapter) => adapter.disconnectOnly())) } private adapterFor(sessionId: string): DaemonPtyAdapter { diff --git a/src/main/index.ts b/src/main/index.ts index 5027eb633..b7aeb1d60 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -479,7 +479,10 @@ app.on('will-quit', () => { // disconnectDaemon only tears down the client transport — it does NOT kill // the daemon process or mark its history as cleanly ended, preserving both // warm reattach and crash recovery on next launch. - disconnectDaemon() + // Why void: will-quit is synchronous in Electron, but the internal await + // ensures checkpoints complete before socket disconnect. The promise chain + // finishes on the event loop before the process actually exits. + void disconnectDaemon() void closeAllWatchers() if (runtimeRpc) { void runtimeRpc.stop().catch((error) => {