diff --git a/src/main/daemon/protocol/daemon-protocol-version.ts b/src/main/daemon/protocol/daemon-protocol-version.ts index d105b2de723..ddb82c4e367 100644 --- a/src/main/daemon/protocol/daemon-protocol-version.ts +++ b/src/main/daemon/protocol/daemon-protocol-version.ts @@ -1,4 +1,5 @@ // Why: daemons survive app updates, so wire behavior must be version-gated. +// v56 accepts `reportFocusLost`; v55 daemons from 1.4.251 predate it and reject the request. // v55 observes the foreground group at the physical PTY owner. // v54 reads the macOS process table in process instead of forking setuid ps on every poll (#31783). // v53 rolls the daemon-side terminal fixes since v1.4.241 (foreground confirmation for chat continuation, ConPTY reflow, WSL malloc tunables) into a fresh daemon. @@ -13,7 +14,8 @@ // v43 dropped it with the revert); v41 stages long startup commands as sourced scripts; v40 rolled // the #25130/#24636 shell-wrapper changes and the wider agent list into a fresh daemon; older owners // stay attachable. -export const PROTOCOL_VERSION = 55 +export const PROTOCOL_VERSION = 56 +export const FOCUS_LOSS_REPORT_PROTOCOL_VERSION = 56 export const PTY_FOREGROUND_OBSERVATION_PROTOCOL_VERSION = 55 export const FENCED_TERMINATION_PROTOCOL_VERSION = 51 export const CLAUDE_ACCOUNT_FUNCTION_DAEMON_PROTOCOL_VERSION = 42 @@ -50,7 +52,7 @@ export const MODE_2031_UNSUBSCRIBE_FACT_PROTOCOL_VERSION = 29 export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, - 52, 53, 54 + 52, 53, 54, 55 ] as const export function supportsColorQueryReplyColors(protocolVersion: number): boolean { @@ -64,3 +66,13 @@ export function supportsPtyStartupIngress(protocolVersion: number): boolean { export function supportsMode2031UnsubscribeFact(protocolVersion: number): boolean { return protocolVersion >= MODE_2031_UNSUBSCRIBE_FACT_PROTOCOL_VERSION } + +export type DaemonRequestSupport = 'supported' | 'unsupported' | 'ask' + +/** `reportFocusLost` shipped inside v55 (1.4.252) without a bump, so only a v55 daemon can tell. */ +export function focusLossReportSupport(protocolVersion: number): DaemonRequestSupport { + if (protocolVersion >= FOCUS_LOSS_REPORT_PROTOCOL_VERSION) { + return 'supported' + } + return protocolVersion === FOCUS_LOSS_REPORT_PROTOCOL_VERSION - 1 ? 'ask' : 'unsupported' +} diff --git a/src/main/daemon/protocol/daemon-rpc-contract.ts b/src/main/daemon/protocol/daemon-rpc-contract.ts index 16d9f117b96..583c1fb41d5 100644 --- a/src/main/daemon/protocol/daemon-rpc-contract.ts +++ b/src/main/daemon/protocol/daemon-rpc-contract.ts @@ -175,7 +175,7 @@ export type TerminalBufferActionRequest = { } } -// Viewers live above the daemon on orcad; an older daemon rejects this, which callers ignore. +// Viewers live above the daemon on orcad; gated by focusLossReportSupport (v56, some v55). export type ReportFocusLostRequest = { id: string type: 'reportFocusLost' diff --git a/src/main/daemon/providers/adapter/daemon-pty-connection-lifecycle.ts b/src/main/daemon/providers/adapter/daemon-pty-connection-lifecycle.ts index 549b224a66f..17a5682b972 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-connection-lifecycle.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-connection-lifecycle.ts @@ -70,8 +70,9 @@ export abstract class DaemonPtyConnectionLifecycle extends DaemonPtyEventSubscri return } if (previous) { - // Recheck capabilities for each incarnation: the replacement may support getSize. + // Recheck capabilities for each incarnation: the replacement may support them. this.getSizeUnsupported = false + this.focusLossReportRejected = false } this.lastAuthenticatedIdentity = { ...current } this.exactDaemonIncarnation = exactDaemonIncarnationForPidRecord(current, this.pidRecord) diff --git a/src/main/daemon/providers/adapter/daemon-pty-runtime-state.ts b/src/main/daemon/providers/adapter/daemon-pty-runtime-state.ts index f0b27ba2992..b6df8de284a 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-runtime-state.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-runtime-state.ts @@ -123,6 +123,7 @@ export abstract class DaemonPtyRuntimeState { }) protected activeSessionIds = new Set() protected getSizeUnsupported = false + protected focusLossReportRejected = false protected sessionsAwaitingDaemonRecovery = new Set() protected sessionIncarnations = new Map() protected readonly ptyInventory = new DaemonPtyInventoryObservation( diff --git a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-focus-loss.test.ts b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-focus-loss.test.ts index dbcc32fec7e..636ce242edf 100644 --- a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-focus-loss.test.ts +++ b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-focus-loss.test.ts @@ -1,34 +1,47 @@ import '../../../pty-subprocess/testing/mock-descendant-sweep' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { rmSync } from 'node:fs' -import type { DaemonServer } from '../../../server/daemon-server' +import { DaemonServer } from '../../../server/daemon-server' import type { DaemonPtyAdapter } from '../daemon-pty-adapter' -import { createMockSubprocess, startDaemonAdapterHarness } from './daemon-pty-adapter-test-harness' +import { + createMockSubprocess, + startDaemonAdapterHarness, + type DaemonAdapterHarness +} from './daemon-pty-adapter-test-harness' const FOCUS_IN = '\x1b[I' const FOCUS_OUT = '\x1b[O' +// 1.4.251 shipped v55 without the request; 1.4.252 added it inside v55. +const UNVERSIONED_FOCUS_LOSS_PROTOCOL_VERSION = 55 describe('DaemonPtyAdapter.reportFocusLost', () => { - let dir: string - let server: DaemonServer - let adapter: DaemonPtyAdapter + let harness: DaemonAdapterHarness | undefined + let server: DaemonServer | undefined let subprocess: ReturnType - beforeEach(async () => { - const harness = await startDaemonAdapterHarness(() => { - subprocess = createMockSubprocess() - return subprocess - }) - ;({ dir, server, adapter } = harness) - }) + async function start(protocolVersion?: number): Promise { + harness = await startDaemonAdapterHarness( + () => { + subprocess = createMockSubprocess() + return subprocess + }, + protocolVersion === undefined ? {} : { protocolVersion } + ) + server = harness.server + return harness.adapter + } afterEach(async () => { - adapter?.dispose() + harness?.adapter.dispose() await server?.shutdown() - rmSync(dir, { recursive: true, force: true }) + if (harness) { + rmSync(harness.dir, { recursive: true, force: true }) + } + harness = undefined + server = undefined }) - async function focusedSession(): Promise { + async function focusedSession(adapter: DaemonPtyAdapter): Promise { const { id } = await adapter.spawn({ cols: 80, rows: 24 }) subprocess._simulateData('\x1b[?1004h') adapter.write(id, FOCUS_IN) @@ -36,19 +49,11 @@ describe('DaemonPtyAdapter.reportFocusLost', () => { return id } - it('tells the program focus is gone', async () => { - const id = await focusedSession() - - await adapter.reportFocusLost(id) - - expect(subprocess.write).toHaveBeenLastCalledWith(FOCUS_OUT) - }) - - it('leaves a daemon that predates the request, and its session, working', async () => { - const id = await focusedSession() + /** Stands in for a daemon whose router predates the request and rejects it as unknown. */ + function rejectFocusLossReports(daemon: DaemonServer): ReturnType { const router = // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: stands in for an older daemon's router, whose default branch rejects unknown types. - (server as unknown as { requestRouter: { route: (...args: never[]) => unknown } }) + (daemon as unknown as { requestRouter: { route: (...args: never[]) => unknown } }) .requestRouter const route = router.route.bind(router) const rejected = vi.fn() @@ -60,14 +65,62 @@ describe('DaemonPtyAdapter.reportFocusLost', () => { } return route(clientId, request) } + return rejected + } + + it('tells the program focus is gone', async () => { + const adapter = await start() + const id = await focusedSession(adapter) + + await adapter.reportFocusLost(id) + + expect(subprocess.write).toHaveBeenLastCalledWith(FOCUS_OUT) + }) + + it('never asks a daemon from before the request existed', async () => { + const adapter = await start(UNVERSIONED_FOCUS_LOSS_PROTOCOL_VERSION - 1) + const id = await focusedSession(adapter) + const rejected = rejectFocusLossReports(server!) await expect(adapter.reportFocusLost(id)).resolves.toBeUndefined() - await expect(adapter.reportFocusLost(id)).resolves.toBeUndefined() - adapter.write(id, 'ls\n') - await vi.waitFor(() => expect(subprocess.write).toHaveBeenLastCalledWith('ls\n')) - expect(subprocess.write).not.toHaveBeenCalledWith(FOCUS_OUT) - // The rejection is remembered for this client, so no further requests reach the old daemon. + expect(rejected).not.toHaveBeenCalled() + }) + + it('stops asking a v55 daemon that rejects the request, but asks its replacement', async () => { + const adapter = await start(UNVERSIONED_FOCUS_LOSS_PROTOCOL_VERSION) + const firstId = await focusedSession(adapter) + const rejected = rejectFocusLossReports(server!) + + await expect(adapter.reportFocusLost(firstId)).resolves.toBeUndefined() + await expect(adapter.reportFocusLost(firstId)).resolves.toBeUndefined() expect(rejected).toHaveBeenCalledTimes(1) + expect(subprocess.write).not.toHaveBeenCalledWith(FOCUS_OUT) + + // A v55 daemon from a later build accepts the request at the same endpoint. + const firstIdentity = adapter.getLastAuthenticatedDaemonIdentity() + await server!.shutdown() + server = new DaemonServer({ + socketPath: harness!.socketPath, + tokenPath: harness!.tokenPath, + protocolVersion: UNVERSIONED_FOCUS_LOSS_PROTOCOL_VERSION, + launchNonce: 'replacement-launch', + startedAtMs: (firstIdentity?.startedAtMs ?? 0) + 10_000, + log: harness!.daemonLog, + spawnSubprocess: () => { + subprocess = createMockSubprocess() + return subprocess + } + }) + await server.start() + await vi.waitFor(async () => { + await adapter.listProcesses() + expect(adapter.getLastAuthenticatedDaemonIdentity()?.launchNonce).toBe('replacement-launch') + }) + const replacementId = await focusedSession(adapter) + + await adapter.reportFocusLost(replacementId) + + expect(subprocess.write).toHaveBeenLastCalledWith(FOCUS_OUT) }) }) diff --git a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-test-harness.ts b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-test-harness.ts index eba2692c31d..d68a8b1834d 100644 --- a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-test-harness.ts +++ b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-test-harness.ts @@ -85,7 +85,7 @@ export async function startDaemonAdapterHarness( spawnSubprocess: SpawnSubprocess, adapterOptions: Pick< DaemonPtyAdapterOptions, - 'readRunningWslDistros' | 'historyPath' | 'wslBridgeBootIdentity' + 'readRunningWslDistros' | 'historyPath' | 'wslBridgeBootIdentity' | 'protocolVersion' > = {}, serverOptions: { onPtySessionExit?: (sessionId: string) => void } = {} ): Promise { @@ -102,6 +102,10 @@ export async function startDaemonAdapterHarness( tokenPath, log: daemonLog, spawnSubprocess, + // A daemon and the adapter that reaches it speak the same protocol generation. + ...(adapterOptions.protocolVersion !== undefined + ? { protocolVersion: adapterOptions.protocolVersion } + : {}), ...serverOptions }) await server.start() diff --git a/src/main/daemon/providers/checkpointing/daemon-pty-buffer-snapshots.ts b/src/main/daemon/providers/checkpointing/daemon-pty-buffer-snapshots.ts index c353e9bb36f..3786b13b3c0 100644 --- a/src/main/daemon/providers/checkpointing/daemon-pty-buffer-snapshots.ts +++ b/src/main/daemon/providers/checkpointing/daemon-pty-buffer-snapshots.ts @@ -3,7 +3,7 @@ import { parseTerminalKittyKeyboardFlags } from '../../../../shared/terminal/pro import { boundSnapshot } from './daemon-durable-history-snapshot' import { DaemonPtySessionControl } from '../adapter/daemon-pty-session-control' import { isUnknownRequestTypeError } from '../../endpoint/identity/daemon-endpoint-errors' -import type { DaemonClient } from '../../transport/client/daemon-client' +import { focusLossReportSupport } from '../../protocol/daemon-protocol-version' import { DAEMON_SESSION_SCROLLBACK_ROWS } from '../../sessions/daemon-session-scrollback-window' import type { GetSnapshotResult } from '../../protocol/daemon-rpc-contract' import type { PtyProviderBufferSnapshot } from '../../../providers/pty-provider-contract' @@ -11,8 +11,6 @@ import type { PtyProviderBufferSnapshot } from '../../../providers/pty-provider- const DURABLE_HISTORY_OVERLAY_DEADLINE_MS = 5_000 export abstract class DaemonPtyBufferSnapshots extends DaemonPtySessionControl { - private focusLossUnsupportedBy: DaemonClient | null = null - async getBufferSnapshot( id: string, opts: { scrollbackRows?: number } = {} @@ -186,18 +184,18 @@ export abstract class DaemonPtyBufferSnapshots extends DaemonPtySessionControl { } async reportFocusLost(id: string): Promise { - const client = this.client - if (this.focusLossUnsupportedBy === client) { + const support = focusLossReportSupport(this.protocolVersion) + if (support === 'unsupported' || (support === 'ask' && this.focusLossReportRejected)) { return } try { - await client.request('reportFocusLost', { sessionId: id }) + await this.client.request('reportFocusLost', { sessionId: id }) } catch (error) { - if (!isUnknownRequestTypeError(error)) { + if (support !== 'ask' || !isUnknownRequestTypeError(error)) { throw error } - // Shipped without a protocol bump; recheck once a new client reaches a replacement daemon. - this.focusLossUnsupportedBy = client + // A v55 daemon from 1.4.251 predates the request; its replacement is asked again. + this.focusLossReportRejected = true } } diff --git a/src/shared/local-build-compatibility-contract.json b/src/shared/local-build-compatibility-contract.json index 046d29c6685..0cc7c9f4b0f 100644 --- a/src/shared/local-build-compatibility-contract.json +++ b/src/shared/local-build-compatibility-contract.json @@ -3,10 +3,10 @@ "appId": "com.stablyai.orca", "stateSchemaVersion": 1, "readableStateSchemaVersions": [1], - "daemonProtocolVersion": 55, + "daemonProtocolVersion": 56, "attachableDaemonProtocolVersions": [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 54, 55 + 51, 52, 53, 54, 55, 56 ] } diff --git a/src/shared/local-build-compatibility-contract.ts b/src/shared/local-build-compatibility-contract.ts index 55f5434432d..a208d577989 100644 --- a/src/shared/local-build-compatibility-contract.ts +++ b/src/shared/local-build-compatibility-contract.ts @@ -3,10 +3,10 @@ export const LOCAL_BUILD_COMPATIBILITY_CONTRACT = { appId: 'com.stablyai.orca', stateSchemaVersion: 1, readableStateSchemaVersions: [1], - daemonProtocolVersion: 55, + daemonProtocolVersion: 56, attachableDaemonProtocolVersions: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 54, 55 + 51, 52, 53, 54, 55, 56 ] } as const