From 58ff3e65af13237838997f78a32809c53aa30891 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 20 Oct 2026 21:27:52 -0700 Subject: [PATCH 01/15] feat: configure the running terminal limit for each host --- .../daemon/daemon-automatic-work-guard.ts | 4 + .../daemon/daemon-automatic-work-resume.ts | 10 +- src/main/daemon/daemon-control-request.ts | 28 ++ src/main/daemon/daemon-pty-adapter.ts | 28 ++ src/main/daemon/daemon-request-deadline.ts | 16 +- src/main/daemon/daemon-server-options.ts | 2 + src/main/daemon/daemon-server.ts | 53 ++-- .../daemon/daemon-terminal-limit-protocol.ts | 48 ++++ src/main/daemon/daemon-terminal-limit.test.ts | 84 ++++++ src/main/daemon/host-terminal-ledger.ts | 6 +- src/main/daemon/host-terminal-policy.test.ts | 124 +++++++++ src/main/daemon/host-terminal-policy.ts | 142 ++++++++++ src/main/daemon/system-pty-limit.ts | 64 +++++ .../daemon/terminal-spawn-admission-mode.ts | 21 ++ src/main/daemon/terminal-spawn-gate.ts | 58 ++-- src/main/daemon/terminal-spawn-host-share.ts | 4 +- src/main/ipc/pty/runtime/controller.ts | 2 + src/main/runtime/orca-runtime-get-status.ts | 25 +- .../runtime/orca-runtime-pty-controller.ts | 29 ++ .../runtime/rpc/methods/terminal-daemon.ts | 13 + .../runtime-pty-controller-contract.ts | 2 + src/main/window/owned-temp-staging-root.ts | 14 +- .../settings/TerminalAdvancedSection.tsx | 6 + .../settings/TerminalLimitSetting.test.tsx | 166 ++++++++++++ .../settings/TerminalLimitSetting.tsx | 249 ++++++++++++++++++ .../src/components/settings/TerminalPane.tsx | 4 + ...gs-interface-primary-section-renderers.tsx | 1 + .../terminal-advanced-platform-search.ts | 8 + .../settings/terminal-limit-transport.ts | 27 ++ src/renderer/src/i18n/locales/en.json | 13 + src/renderer/src/i18n/locales/es.json | 13 + src/renderer/src/i18n/locales/fr.json | 13 + src/renderer/src/i18n/locales/ja.json | 13 + src/renderer/src/i18n/locales/ko.json | 13 + src/renderer/src/i18n/locales/zh.json | 13 + src/shared/owned-private-directory.ts | 11 + .../rpc-params-catalog.generated.ts | 3 + .../rpc-contract/terminal-limit-params.ts | 7 + src/shared/terminal-limit-policy.ts | 25 ++ src/shared/terminal-runtime-capabilities.ts | 2 + 40 files changed, 1261 insertions(+), 103 deletions(-) create mode 100644 src/main/daemon/daemon-control-request.ts create mode 100644 src/main/daemon/daemon-terminal-limit-protocol.ts create mode 100644 src/main/daemon/daemon-terminal-limit.test.ts create mode 100644 src/main/daemon/host-terminal-policy.test.ts create mode 100644 src/main/daemon/host-terminal-policy.ts create mode 100644 src/main/daemon/system-pty-limit.ts create mode 100644 src/main/daemon/terminal-spawn-admission-mode.ts create mode 100644 src/main/runtime/orca-runtime-pty-controller.ts create mode 100644 src/renderer/src/components/settings/TerminalLimitSetting.test.tsx create mode 100644 src/renderer/src/components/settings/TerminalLimitSetting.tsx create mode 100644 src/renderer/src/components/settings/terminal-limit-transport.ts create mode 100644 src/shared/owned-private-directory.ts create mode 100644 src/shared/rpc-contract/terminal-limit-params.ts create mode 100644 src/shared/terminal-limit-policy.ts diff --git a/src/main/daemon/daemon-automatic-work-guard.ts b/src/main/daemon/daemon-automatic-work-guard.ts index 7edea9212325..2a91b8173560 100644 --- a/src/main/daemon/daemon-automatic-work-guard.ts +++ b/src/main/daemon/daemon-automatic-work-guard.ts @@ -10,12 +10,14 @@ import type { AutomaticWorkRequestType } from './daemon-automatic-work-protocol' import { DaemonProcessGrowthMonitor } from './daemon-process-growth-monitor' import { HostTerminalLedger, resolveMaxHostTerminals } from './host-terminal-ledger' import { LegacyRestoreRecords, legacyRestoreRecordsPathFor } from './legacy-restore-records' +import type { HostTerminalPolicy } from './host-terminal-policy' import { TerminalSpawnGate, type TerminalSpawnAdmissionMode } from './terminal-spawn-gate' type DaemonAutomaticWorkGuardOptions = { markerPath: string | undefined /** Where every daemon on this host shares its terminal count; undefined caps this one alone. */ hostTerminalLedgerDir?: string | undefined + terminalPolicy?: HostTerminalPolicy mode: TerminalSpawnAdmissionMode log: { log: (event: string, details: Record) => void } listSessions: () => readonly { sessionId: string; pid: number | null }[] @@ -50,6 +52,7 @@ export class DaemonAutomaticWorkGuard { onLevelChanged: (level) => this.onPressureChanged(level), onTrip: (trips) => this.onTrip(trips) }) + const policy = options.terminalPolicy this.gate = new TerminalSpawnGate({ log: (event, details) => options.log.log(event, details), mode: options.mode, @@ -57,6 +60,7 @@ export class DaemonAutomaticWorkGuard { automaticWorkMode: () => this.automaticWorkMode(), armAutomaticWork: () => this.marker.arm(), legacyRestores: this.legacyRestores, + resolveMaximum: policy ? () => policy.admissionMaximum() : undefined, hostTerminals: new HostTerminalLedger({ dir: options.hostTerminalLedgerDir ?? null, maxTerminals: resolveMaxHostTerminals(), diff --git a/src/main/daemon/daemon-automatic-work-resume.ts b/src/main/daemon/daemon-automatic-work-resume.ts index 4ab6e71c5647..29e67b333720 100644 --- a/src/main/daemon/daemon-automatic-work-resume.ts +++ b/src/main/daemon/daemon-automatic-work-resume.ts @@ -1,3 +1,4 @@ +import type { TerminalLimitStatus, TerminalLimitUpdate } from '../../shared/terminal-limit-policy' import type { AutomaticWorkResumeOutcome, AutomaticWorkStatus @@ -10,7 +11,7 @@ import { DegradedDaemonPtyProvider } from './degraded-daemon-pty-provider' type LocalDaemons = { current: DaemonPtyAdapter; legacy: readonly DaemonPtyAdapter[] } /** The daemons behind the local provider; null for the in-process fallback, which has no gate. */ -function localDaemons(provider: IPtyProvider): LocalDaemons | null { +export function localDaemons(provider: IPtyProvider): LocalDaemons | null { if (provider instanceof DaemonPtyAdapter) { return { current: provider, legacy: [] } } @@ -47,3 +48,10 @@ export async function resumeLocalAutomaticWork( } return current.value } + +export async function localTerminalLimit( + provider: IPtyProvider, + update?: TerminalLimitUpdate +): Promise { + return (await localDaemons(provider)?.current.terminalLimit(update)) ?? null +} diff --git a/src/main/daemon/daemon-control-request.ts b/src/main/daemon/daemon-control-request.ts new file mode 100644 index 000000000000..bbd0a50a901e --- /dev/null +++ b/src/main/daemon/daemon-control-request.ts @@ -0,0 +1,28 @@ +import type { Socket } from 'node:net' +import { NOTIFY_PREFIX, type DaemonRequest } from './types' +import { encodeNdjson } from './ndjson' + +export async function answerDaemonControlRequest( + socket: Socket, + request: DaemonRequest, + route: () => Promise, + onReply: () => void +): Promise { + const isNotify = request.id.startsWith(NOTIFY_PREFIX) + try { + const result = await route() + if (!isNotify) { + socket.write(encodeNdjson({ id: request.id, ok: true, payload: result }), onReply) + } + } catch (error) { + if (!isNotify) { + socket.write( + encodeNdjson({ + id: request.id, + ok: false, + error: error instanceof Error ? error.message : String(error) + }) + ) + } + } +} diff --git a/src/main/daemon/daemon-pty-adapter.ts b/src/main/daemon/daemon-pty-adapter.ts index 3ebccf283115..27e1924bbb4e 100644 --- a/src/main/daemon/daemon-pty-adapter.ts +++ b/src/main/daemon/daemon-pty-adapter.ts @@ -13,6 +13,7 @@ import { } from '../../shared/host-spawn-admission' import { isUnknownRequestTypeError } from './daemon-endpoint-errors' import type { AutomaticWorkRequestType } from './daemon-automatic-work-protocol' +import type { TerminalLimitStatus, TerminalLimitUpdate } from '../../shared/terminal-limit-policy' import type { DaemonAsyncIoStatus } from '../../shared/daemon-async-io-health' export class DaemonPtyAdapter extends DaemonPtyDaemonRecovery implements IPtyProvider { @@ -171,6 +172,33 @@ export class DaemonPtyAdapter extends DaemonPtyDaemonRecovery implements IPtyPro }) } + async terminalLimit(update?: TerminalLimitUpdate): Promise { + await this.ensureConnected() + const identity = this.getDaemonIdentity() + if (update && identity?.launchNonce !== update.daemonNonce) { + throw new Error('Terminal host changed. Refresh the setting and try again.') + } + try { + const status = await this.client.request( + update ? 'setTerminalLimit' : 'terminalLimitStatus', + update + ) + if ( + !identity || + this.getDaemonIdentity()?.launchNonce !== identity.launchNonce || + status.daemonNonce !== identity.launchNonce + ) { + throw new Error('Terminal host changed. Refresh the setting and try again.') + } + return status + } catch (error) { + if (isUnknownRequestTypeError(error)) { + return null + } + throw error + } + } + async getAutomaticWorkStatus(): Promise { const status = await this.requestAutomaticWork('automaticWorkStatus') return status === AUTOMATIC_WORK_RESUME_UNSUPPORTED ? null : status diff --git a/src/main/daemon/daemon-request-deadline.ts b/src/main/daemon/daemon-request-deadline.ts index d98c1c5f7dd7..69b11ca9b1b6 100644 --- a/src/main/daemon/daemon-request-deadline.ts +++ b/src/main/daemon/daemon-request-deadline.ts @@ -9,13 +9,23 @@ export async function awaitDaemonWorkWithinCallerDeadline( work: Promise, deadlineMs: number ): Promise { + return (await awaitDaemonValueWithinCallerDeadline(work, deadlineMs)).completed +} + +export async function awaitDaemonValueWithinCallerDeadline( + work: Promise, + deadlineMs: number +): Promise<{ completed: true; value: T } | { completed: false }> { void work.catch(() => {}) let timer: ReturnType | undefined try { return await Promise.race([ - work.then(() => true), - new Promise((resolve) => { - timer = setTimeout(() => resolve(false), Math.max(1, deadlineMs - Date.now())) + work.then((value) => ({ completed: true as const, value })), + new Promise<{ completed: false }>((resolve) => { + timer = setTimeout( + () => resolve({ completed: false }), + Math.max(1, deadlineMs - Date.now()) + ) timer.unref?.() }) ]) diff --git a/src/main/daemon/daemon-server-options.ts b/src/main/daemon/daemon-server-options.ts index ca08680f26b1..3cb8bb77d1ce 100644 --- a/src/main/daemon/daemon-server-options.ts +++ b/src/main/daemon/daemon-server-options.ts @@ -1,6 +1,7 @@ import type { DaemonFileLog } from './daemon-file-log' import type { SubprocessHandle } from './session-subprocess-handle' import type { TerminalSpawnAdmissionMode } from './terminal-spawn-gate' +import type { HostTerminalPolicy } from './host-terminal-policy' export type DaemonServerOptions = { socketPath: string @@ -35,6 +36,7 @@ export type DaemonServerOptions = { automaticWorkMarkerPath?: string /** Where every daemon on this host shares its terminal count for the host cap. */ hostTerminalLedgerDir?: string + terminalLimitPolicy?: HostTerminalPolicy spawnSubprocess: (opts: { sessionId: string cols: number diff --git a/src/main/daemon/daemon-server.ts b/src/main/daemon/daemon-server.ts index 95b1f3639025..32da927a241e 100644 --- a/src/main/daemon/daemon-server.ts +++ b/src/main/daemon/daemon-server.ts @@ -23,13 +23,10 @@ import { TerminalHistorySeedTransferRegistry } from './terminal-history-seed-tra import { TerminalHost } from './terminal-host' import { DaemonAutomaticWorkGuard } from './daemon-automatic-work-guard' import { answerAutomaticWorkRequest } from './daemon-automatic-work-protocol' -import { - CLEAN_DISCONNECT_PROTOCOL_VERSION, - NOTIFY_PREFIX, - PROTOCOL_VERSION, - type DaemonRequest -} from './types' -import { encodeNdjson } from './ndjson' +import { HostTerminalPolicy } from './host-terminal-policy' +import { answerTerminalLimitRequest } from './daemon-terminal-limit-protocol' +import { CLEAN_DISCONNECT_PROTOCOL_VERSION, PROTOCOL_VERSION, type DaemonRequest } from './types' +import { answerDaemonControlRequest } from './daemon-control-request' export class DaemonServer { private static readonly INITIAL_ADOPTION_TIMEOUT_MS = 2 * 60 * 1000 @@ -48,12 +45,16 @@ export class DaemonServer { private readonly admission: DaemonTerminalAdmission private readonly requestRouter: DaemonRequestRouter private stopStreamBacklogProbe: () => void = () => {} + private readonly terminalPolicy: HostTerminalPolicy + private terminalPolicyNonce = '' constructor(options: DaemonServerOptions) { this.log = options.log ?? createNoopDaemonFileLog() + this.terminalPolicy = options.terminalLimitPolicy ?? new HostTerminalPolicy() this.automaticWork = new DaemonAutomaticWorkGuard({ markerPath: options.automaticWorkMarkerPath, hostTerminalLedgerDir: options.hostTerminalLedgerDir, + terminalPolicy: this.terminalPolicy, mode: options.spawnAdmission ?? 'observe', log: this.log, listSessions: () => this.host.listSessions(), @@ -120,6 +121,7 @@ export class DaemonServer { (protocolVersion >= CLEAN_DISCONNECT_PROTOCOL_VERSION ? Date.now() - process.uptime() * 1000 : null) + this.terminalPolicyNonce = launchNonce ?? randomUUID() const token = randomUUID() this.connections = new DaemonClientConnections({ @@ -289,26 +291,23 @@ export class DaemonServer { clientId: string, request: DaemonRequest ): Promise { - const isNotify = request.id.startsWith(NOTIFY_PREFIX) - try { - const result = - answerAutomaticWorkRequest(request, this.automaticWork, this.endpoint) ?? - (await this.requestRouter.route(clientId, request)) - if (!isNotify) { - socket.write(encodeNdjson({ id: request.id, ok: true, payload: result }), () => { - this.lifecycle.startPendingShutdownReply(clientId, request.id) - }) - } - } catch (error) { - if (!isNotify) { - socket.write( - encodeNdjson({ - id: request.id, - ok: false, - error: error instanceof Error ? error.message : String(error) - }) + return answerDaemonControlRequest( + socket, + request, + async () => { + const limitRequest = answerTerminalLimitRequest( + request, + this.terminalPolicy, + this.terminalPolicyNonce, + () => !this.endpoint.hasLostOwnership() ) - } - } + return ( + limitRequest ?? + answerAutomaticWorkRequest(request, this.automaticWork, this.endpoint) ?? + this.requestRouter.route(clientId, request) + ) + }, + () => this.lifecycle.startPendingShutdownReply(clientId, request.id) + ) } } diff --git a/src/main/daemon/daemon-terminal-limit-protocol.ts b/src/main/daemon/daemon-terminal-limit-protocol.ts new file mode 100644 index 000000000000..b9bc66109a40 --- /dev/null +++ b/src/main/daemon/daemon-terminal-limit-protocol.ts @@ -0,0 +1,48 @@ +import { + isConfiguredTerminalLimit, + type TerminalLimitStatus +} from '../../shared/terminal-limit-policy' +import type { HostTerminalPolicy } from './host-terminal-policy' +import { awaitDaemonValueWithinCallerDeadline } from './daemon-request-deadline' + +/** New requests remain unknown on older daemons; no protocol-generation change or replacement. */ +export function answerTerminalLimitRequest( + request: { type: string; payload?: unknown }, + policy: HostTerminalPolicy, + nonce: string, + isCurrent: () => boolean +): Promise | undefined { + if (request.type !== 'terminalLimitStatus' && request.type !== 'setTerminalLimit') { + return undefined + } + const work = async (): Promise => { + if (!isCurrent()) { + throw new Error('Terminal host changed. Refresh the setting and try again.') + } + if (request.type === 'setTerminalLimit') { + const update = request.payload + if ( + typeof update !== 'object' || + update === null || + !('maxTerminals' in update) || + !isConfiguredTerminalLimit(update.maxTerminals) || + !('daemonNonce' in update) || + update.daemonNonce !== nonce + ) { + throw new Error('Terminal setting changed. Refresh the setting and try again.') + } + await policy.save(update.maxTerminals, isCurrent) + } + const status = await policy.status(nonce) + if (!isCurrent()) { + throw new Error('Terminal host changed. Refresh the setting and try again.') + } + return status + } + return awaitDaemonValueWithinCallerDeadline(work(), Date.now() + 2_000).then((result) => { + if (!result.completed) { + throw new Error('Couldn’t confirm the terminal setting. Refresh and try again.') + } + return result.value + }) +} diff --git a/src/main/daemon/daemon-terminal-limit.test.ts b/src/main/daemon/daemon-terminal-limit.test.ts new file mode 100644 index 000000000000..93b0c4219833 --- /dev/null +++ b/src/main/daemon/daemon-terminal-limit.test.ts @@ -0,0 +1,84 @@ +import './mock-descendant-sweep' +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { DaemonClient } from './client' +import { DaemonPtyAdapter } from './daemon-pty-adapter' +import { DaemonServer } from './daemon-server' +import { getDaemonSocketPath } from './daemon-spawner' +import { createMockSubprocess } from './daemon-pty-adapter-test-harness' +import { HostTerminalPolicy } from './host-terminal-policy' +import { SystemPtyLimit } from './system-pty-limit' +import type { TerminalLimitStatus } from '../../shared/terminal-limit-policy' + +let server: DaemonServer | undefined +let client: DaemonClient | undefined +let directory: string | undefined +afterEach(async () => { + client?.disconnect() + await server?.shutdown() + if (directory) { + rmSync(directory, { recursive: true, force: true }) + } + vi.restoreAllMocks() +}) + +it('reads and saves on the attached daemon socket, refusing stale identity and lost endpoint writes', async () => { + directory = mkdtempSync(join(tmpdir(), 'terminal-limit-rpc-')) + const path = join(directory, 'policy', 'terminals.json') + server = new DaemonServer({ + socketPath: getDaemonSocketPath(directory), + tokenPath: join(directory, 'token'), + terminalLimitPolicy: new HostTerminalPolicy(path, {}, new SystemPtyLimit(async () => 511)), + spawnSubprocess: async () => createMockSubprocess() + }) + await server.start() + client = new DaemonClient({ + socketPath: getDaemonSocketPath(directory), + tokenPath: join(directory, 'token') + }) + await client.ensureConnected() + const before = await client.request('terminalLimitStatus', undefined) + expect(before).toMatchObject({ + maxTerminals: 256, + systemPtyLimit: 511, + source: 'default', + editable: true + }) + const update = { daemonNonce: before.daemonNonce, maxTerminals: 384 } + await expect(client.request('setTerminalLimit', update)).resolves.toMatchObject({ + maxTerminals: 384, + source: 'saved' + }) + const saved = readFileSync(path, 'utf8') + await expect( + client.request('setTerminalLimit', { ...update, maxTerminals: 512 }) + ).rejects.toThrow('capacity') + await expect( + client.request('setTerminalLimit', { ...update, daemonNonce: 'other-daemon', maxTerminals: 20 }) + ).rejects.toThrow('changed') + vi.spyOn(server['endpoint'], 'hasLostOwnership').mockReturnValue(true) + await expect(client.request('setTerminalLimit', { ...update, maxTerminals: 20 })).rejects.toThrow( + 'host changed' + ) + expect(readFileSync(path, 'utf8')).toBe(saved) +}) + +it('recognizes an older daemon without replacement and preserves real transport failures', async () => { + vi.spyOn(DaemonClient.prototype, 'ensureConnected').mockResolvedValue() + const request = vi + .spyOn(DaemonClient.prototype, 'request') + .mockRejectedValue(new Error('Unknown request type: terminalLimitStatus')) + const adapter = new DaemonPtyAdapter({ + socketPath: '/tmp/orca-limit-old.sock', + tokenPath: '/tmp/orca-limit-old.token' + }) + try { + await expect(adapter.terminalLimit()).resolves.toBeNull() + request.mockRejectedValue(new Error('socket closed')) + await expect(adapter.terminalLimit()).rejects.toThrow('socket closed') + } finally { + adapter.dispose() + } +}) diff --git a/src/main/daemon/host-terminal-ledger.ts b/src/main/daemon/host-terminal-ledger.ts index 4f27dc2ac3d4..2ff5947dd5c9 100644 --- a/src/main/daemon/host-terminal-ledger.ts +++ b/src/main/daemon/host-terminal-ledger.ts @@ -114,12 +114,12 @@ export class HostTerminalLedger { } /** `own` excludes the terminal being reserved; on false its previous share is restored. */ - tryReserve(own: HostTerminalShare): boolean { - if (own.terminals + 1 > this.options.maxTerminals) { + tryReserve(own: HostTerminalShare, maximum = this.options.maxTerminals): boolean { + if (own.terminals + 1 > maximum) { return false } this.write({ ...own, terminals: own.terminals + 1 }) - if (own.terminals + 1 + this.readOthers().terminals <= this.options.maxTerminals) { + if (own.terminals + 1 + this.readOthers().terminals <= maximum) { return true } this.write(own) diff --git a/src/main/daemon/host-terminal-policy.test.ts b/src/main/daemon/host-terminal-policy.test.ts new file mode 100644 index 000000000000..34c379bdb51c --- /dev/null +++ b/src/main/daemon/host-terminal-policy.test.ts @@ -0,0 +1,124 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { HostTerminalPolicy, hostTerminalPolicyPath } from './host-terminal-policy' +import { SystemPtyLimit, parseLinuxPtyLimit } from './system-pty-limit' +import { HostTerminalLedger } from './host-terminal-ledger' +import { TerminalSpawnGate } from './terminal-spawn-gate' +import type { SpawnRequestFacts } from '../../shared/host-spawn-admission' + +const facts: SpawnRequestFacts = { + clientId: 'user', + declaredIntent: null, + hasAgentSessionClaim: false, + hasHistorySeed: false, + deadlineAt: Number.POSITIVE_INFINITY +} +const system = () => new SystemPtyLimit(async () => 511) +const directories: string[] = [] +afterEach(async () => { + vi.useRealTimers() + await Promise.all(directories.splice(0).map((path) => rm(path, { recursive: true, force: true }))) +}) + +async function home(): Promise { + const path = await mkdtemp(join(tmpdir(), 'orca-terminal-policy-')) + directories.push(path) + return path +} + +describe('host terminal policy', () => { + it('shares live raises and decreases across daemons and retains the policy after reconstruction', async () => { + const root = await home() + const path = hostTerminalPolicyPath(root, 'machine-a') + const first = new HostTerminalPolicy(path, {}, system()) + const second = new HostTerminalPolicy(path, {}, system()) + const gate = (policy: HostTerminalPolicy, pid: number) => + new TerminalSpawnGate({ + log: vi.fn(), + resolveMaximum: () => policy.admissionMaximum(), + hostTerminals: new HostTerminalLedger({ + dir: join(root, 'ledger'), + pid, + maxTerminals: 256, + isProcessAlive: () => true, + log: vi.fn() + }) + }) + const desktop = gate(first, 100) + const server = gate(second, 200) + await first.save(1, () => true) + const running = await desktop.admit(facts) + running.commit('existing-shell', true) + await expect(server.admit(facts)).rejects.toThrow() + await first.save(2, () => true) + const setup = await server.admit(facts) + setup.commit('setup-script', true) + await first.save(1, () => true) + await expect(server.admit(facts)).rejects.toThrow() + expect(desktop.snapshot().terminals).toBe(1) + expect(server.snapshot().terminals).toBe(1) + const restarted = new HostTerminalPolicy(path, {}, system()) + expect(await restarted.admissionMaximum()).toBe(1) + desktop.onSessionExit('existing-shell') + await expect(server.admit(facts)).rejects.toThrow() + server.onSessionExit('setup-script') + const next = await server.admit(facts) + next.abandon() + desktop.stopHostTerminals() + server.stopHostTerminals() + }) + + it('validates the host ceiling, preserves environment priority and never shares a missing machine identity', async () => { + const root = await home() + const path = hostTerminalPolicyPath(root, 'machine-a') + expect(path).not.toBe(hostTerminalPolicyPath(root, 'machine-b')) + expect(hostTerminalPolicyPath(root, null)).toBeNull() + const policy = new HostTerminalPolicy(path, {}, system()) + await expect(policy.save(512, () => true)).rejects.toThrow('capacity') + await policy.save(384, () => true) + expect(await policy.status('nonce')).toMatchObject({ + maxTerminals: 384, + source: 'saved', + systemPtyLimit: 511 + }) + const override = new HostTerminalPolicy( + path, + { ORCA_DAEMON_MAX_HOST_TERMINALS: '600' }, + system() + ) + expect(await override.status('nonce')).toMatchObject({ + maxTerminals: 600, + source: 'environment', + editable: false + }) + await expect(override.save(20, () => true)).rejects.toThrow('unavailable') + const unidentified = new HostTerminalPolicy(null, {}, system()) + expect(await unidentified.status('nonce')).toMatchObject({ maxTerminals: 256, editable: false }) + await expect(unidentified.save(10, () => true)).rejects.toThrow() + const reduced = new HostTerminalPolicy(path, {}, new SystemPtyLimit(async () => 128)) + expect(await reduced.status('nonce')).toMatchObject({ maxTerminals: 384, systemPtyLimit: 128 }) + const defaults = new HostTerminalPolicy(null, {}, new SystemPtyLimit(async () => 128)) + expect(await defaults.status('nonce')).toMatchObject({ maxTerminals: 256, systemPtyLimit: 128 }) + }) + + it('bounds admission wait while retaining one stalled underlying read', async () => { + vi.useFakeTimers() + const read = vi.fn(() => new Promise(() => {})) + const policy = new HostTerminalPolicy('/unreachable/terminal-policy', {}, system(), read) + const attempts = Promise.all([policy.admissionMaximum(), policy.admissionMaximum()]) + await vi.advanceTimersByTimeAsync(251) + expect(await attempts).toEqual([256, 256]) + const retry = policy.admissionMaximum() + await vi.advanceTimersByTimeAsync(251) + expect(await retry).toBe(256) + expect(read).toHaveBeenCalledOnce() + }) + + it('reports Linux configured global and devpts capacity without subtracting namespace reserve', () => { + expect(parseLinuxPtyLimit('4096\n', 'devpts /dev/pts devpts rw,max=128 0 0')).toBe(128) + expect(parseLinuxPtyLimit('4096', 'devpts /dev/pts devpts rw 0 0')).toBe(4096) + expect(parseLinuxPtyLimit('garbage', '')).toBeNull() + }) +}) diff --git a/src/main/daemon/host-terminal-policy.ts b/src/main/daemon/host-terminal-policy.ts new file mode 100644 index 000000000000..5124d1e5d44a --- /dev/null +++ b/src/main/daemon/host-terminal-policy.ts @@ -0,0 +1,142 @@ +import { createHash, randomUUID } from 'node:crypto' +import { lstat, mkdir, rm, writeFile } from 'node:fs/promises' +import { homedir } from 'node:os' +import { dirname, join } from 'node:path' +import { InFlightPromiseDedupe } from '../../shared/in-flight-promise-dedupe' +import { readNodeFileWithinLimit } from '../../shared/node-bounded-file-reader' +import { renameFileWithWindowsRetryAsync } from '../../shared/windows-retry-file-operations' +import { + isConfiguredTerminalLimit, + terminalLimitInputMaximum, + type TerminalLimitStatus +} from '../../shared/terminal-limit-policy' +import { profileStateAccessMachineIdentity } from '../persistence/profile-state/profile-state-access-identity' +import { isSafeOwnedDirectory } from '../../shared/owned-private-directory' +import { awaitDaemonValueWithinCallerDeadline } from './daemon-request-deadline' +import { DEFAULT_MAX_HOST_TERMINALS, resolveMaxHostTerminals } from './host-terminal-ledger' +import { SystemPtyLimit } from './system-pty-limit' + +export function hostTerminalPolicyPath(home: string, machine: string | null): string | null { + if (!machine) { + return null + } + const key = createHash('sha256') + .update(`${process.platform}:${machine}`) + .digest('hex') + .slice(0, 16) + return join(home, '.orca', 'host-settings', key, 'terminals.json') +} + +async function readSavedMaximum(path: string): Promise { + try { + const { buffer, stats } = await readNodeFileWithinLimit(path, 1024, { regularFileOnly: true }) + if (process.getuid && stats.uid !== process.getuid()) { + throw new Error('Policy owner changed') + } + const saved: unknown = JSON.parse(buffer.toString('utf8')) + if ( + typeof saved !== 'object' || + saved === null || + !('schemaVersion' in saved) || + saved.schemaVersion !== 1 || + !('maxTerminals' in saved) || + !isConfiguredTerminalLimit(saved.maxTerminals) + ) { + throw new Error('Invalid terminal policy') + } + return saved.maxTerminals + } catch (error) { + if (error instanceof Error && 'code' in error && error.code === 'ENOENT') { + return null + } + throw error + } +} + +export class HostTerminalPolicy { + private readonly reads = new InFlightPromiseDedupe(0, 1) + private writing = false + private readonly environment: number | null + + constructor( + readonly path: string | null = hostTerminalPolicyPath( + homedir(), + profileStateAccessMachineIdentity() + ), + env: NodeJS.ProcessEnv = process.env, + private readonly system = new SystemPtyLimit(), + private readonly readSaved: (path: string) => Promise = readSavedMaximum + ) { + const raw = env.ORCA_DAEMON_MAX_HOST_TERMINALS?.trim() + this.environment = + raw && /^\d+$/.test(raw) && isConfiguredTerminalLimit(Number(raw)) + ? resolveMaxHostTerminals(env) + : null + } + + private saved(): Promise { + const path = this.path + return path ? this.reads.run('policy', () => this.readSaved(path)) : Promise.resolve(null) + } + + async admissionMaximum(): Promise { + if (this.environment !== null) { + return this.environment + } + try { + const read = await awaitDaemonValueWithinCallerDeadline(this.saved(), Date.now() + 250) + return (read.completed ? read.value : null) ?? DEFAULT_MAX_HOST_TERMINALS + } catch { + // Settings storage cannot prevent a user from starting a terminal. + return DEFAULT_MAX_HOST_TERMINALS + } + } + + async status(daemonNonce: string): Promise { + const [saved, systemPtyLimit] = await Promise.all([ + this.environment === null ? this.saved() : Promise.resolve(null), + this.system.read() + ]) + return { + maxTerminals: this.environment ?? saved ?? DEFAULT_MAX_HOST_TERMINALS, + source: this.environment !== null ? 'environment' : saved !== null ? 'saved' : 'default', + systemPtyLimit, + editable: this.environment === null && this.path !== null, + daemonNonce + } + } + + async save(maximum: number, isCurrent: () => boolean): Promise { + if (!this.path || this.environment !== null || this.writing) { + throw new Error('Terminal setting unavailable') + } + this.writing = true + let temporary: string | undefined + try { + // A read that started before the write must settle before authoritative readback. + await this.saved() + const ceiling = terminalLimitInputMaximum(await this.system.read()) + if (!isConfiguredTerminalLimit(maximum) || maximum > ceiling) { + throw new Error('Terminal limit exceeds host capacity') + } + const directory = dirname(this.path) + await mkdir(directory, { recursive: true, mode: 0o700 }) + if (!isSafeOwnedDirectory(await lstat(directory))) { + throw new Error('Terminal policy directory is not private') + } + temporary = `${this.path}.${process.pid}.${randomUUID()}.tmp` + await writeFile(temporary, JSON.stringify({ schemaVersion: 1, maxTerminals: maximum }), { + flag: 'wx', + mode: 0o600 + }) + if (!(await renameFileWithWindowsRetryAsync(temporary, this.path, isCurrent))) { + throw new Error('Terminal host changed') + } + } finally { + if (temporary) { + await rm(temporary, { force: true }).catch(() => undefined) + } + this.writing = false + } + } +} diff --git a/src/main/daemon/system-pty-limit.ts b/src/main/daemon/system-pty-limit.ts new file mode 100644 index 000000000000..de6ec55c2e17 --- /dev/null +++ b/src/main/daemon/system-pty-limit.ts @@ -0,0 +1,64 @@ +import { runProcess } from '@orca/process-host' +import { readNodeFileWithinLimit } from '../../shared/node-bounded-file-reader' +import { InFlightPromiseDedupe } from '../../shared/in-flight-promise-dedupe' +import { awaitDaemonValueWithinCallerDeadline } from './daemon-request-deadline' + +function positiveInteger(raw: string): number | null { + const text = raw.trim() + const value = Number(text) + return /^\d+$/.test(text) && Number.isSafeInteger(value) && value > 0 ? value : null +} + +export function parseLinuxPtyLimit(globalRaw: string, mounts: string): number | null { + const global = positiveInteger(globalRaw) + if (global === null) { + return null + } + const instance = mounts.split('\n').find((line) => { + const fields = line.split(/\s+/) + return fields[1] === '/dev/pts' && fields[2] === 'devpts' + }) + const maximum = instance + ?.split(/\s+/)[3] + ?.split(',') + .find((part) => part.startsWith('max=')) + const local = maximum ? positiveInteger(maximum.slice(4)) : null + // The reserve belongs to mount namespaces, not UIDs; this reports capacity, never free slots. + return maximum && local === null ? null : Math.min(global, local ?? global) +} + +async function probeSystemPtyLimit(): Promise { + if (process.platform === 'darwin') { + const result = await runProcess({ + program: '/usr/sbin/sysctl', + args: ['-n', 'kern.tty.ptmx_max'], + timeoutMs: 1_000, + maxOutputBytes: 1024 + }) + return result.code === 0 && !result.timedOut && !result.outputTruncated + ? positiveInteger(result.stdout) + : null + } + if (process.platform === 'linux') { + const [global, mounts] = await Promise.all([ + readNodeFileWithinLimit('/proc/sys/kernel/pty/max', 1024), + readNodeFileWithinLimit('/proc/self/mounts', 1024 * 1024) + ]) + return parseLinuxPtyLimit(global.buffer.toString('utf8'), mounts.buffer.toString('utf8')) + } + return null +} + +/** A stuck filesystem probe stays coalesced; caller deadlines never create more outstanding I/O. */ +export class SystemPtyLimit { + private readonly pending = new InFlightPromiseDedupe(0, 1) + constructor(private readonly probe: () => Promise = probeSystemPtyLimit) {} + + async read(): Promise { + const result = await awaitDaemonValueWithinCallerDeadline( + this.pending.run('system', () => this.probe().catch(() => null)), + Date.now() + 1_100 + ) + return result.completed ? result.value : null + } +} diff --git a/src/main/daemon/terminal-spawn-admission-mode.ts b/src/main/daemon/terminal-spawn-admission-mode.ts new file mode 100644 index 000000000000..e37a314859c0 --- /dev/null +++ b/src/main/daemon/terminal-spawn-admission-mode.ts @@ -0,0 +1,21 @@ +export type TerminalSpawnAdmissionMode = 'observe' | 'enforce' + +export const TERMINAL_SPAWN_ADMISSION_ARG = '--spawn-admission' + +// Rollback switch: `observe` makes newly launched daemons count decisions without pacing. +export const TERMINAL_SPAWN_ADMISSION_ENV_VAR = 'ORCA_TERMINAL_SPAWN_ADMISSION' + +/** The mode a launcher passes its daemon: enforce, unless the env var asks for `observe`. */ +export function resolveTerminalSpawnAdmissionMode( + env: NodeJS.ProcessEnv = process.env +): TerminalSpawnAdmissionMode { + return env[TERMINAL_SPAWN_ADMISSION_ENV_VAR]?.trim().toLowerCase() === 'observe' + ? 'observe' + : 'enforce' +} + +/** Reads the launcher's `--spawn-admission `; anything else observes. */ +export function readTerminalSpawnAdmissionArg(argv: readonly string[]): TerminalSpawnAdmissionMode { + const index = argv.indexOf(TERMINAL_SPAWN_ADMISSION_ARG) + return index !== -1 && argv[index + 1] === 'enforce' ? 'enforce' : 'observe' +} diff --git a/src/main/daemon/terminal-spawn-gate.ts b/src/main/daemon/terminal-spawn-gate.ts index c75b4c3e3dbc..ae54f2f3b820 100644 --- a/src/main/daemon/terminal-spawn-gate.ts +++ b/src/main/daemon/terminal-spawn-gate.ts @@ -24,32 +24,19 @@ import { admitRecordingLegacyRestore } from './legacy-restore-admission' import { TerminalSpawnWaiters } from './terminal-spawn-waiters' import { hostTerminalCapRefusal, TerminalSpawnHostShare } from './terminal-spawn-host-share' -export type TerminalSpawnAdmissionMode = 'observe' | 'enforce' +import type { TerminalSpawnAdmissionMode } from './terminal-spawn-admission-mode' +export { + TERMINAL_SPAWN_ADMISSION_ARG, + TERMINAL_SPAWN_ADMISSION_ENV_VAR, + resolveTerminalSpawnAdmissionMode, + readTerminalSpawnAdmissionArg +} from './terminal-spawn-admission-mode' +export type { TerminalSpawnAdmissionMode } from './terminal-spawn-admission-mode' const RECENT_AUTOMATIC_WORK_MS = 10 * 60_000 // Why poll: another daemon freeing a slot cannot wake this one's waiters. const OTHER_DAEMON_POLL_MS = 500 -export const TERMINAL_SPAWN_ADMISSION_ARG = '--spawn-admission' - -// Rollback switch: `observe` makes newly launched daemons count decisions without pacing. -export const TERMINAL_SPAWN_ADMISSION_ENV_VAR = 'ORCA_TERMINAL_SPAWN_ADMISSION' - -/** The mode a launcher passes its daemon: enforce, unless the env var asks for `observe`. */ -export function resolveTerminalSpawnAdmissionMode( - env: NodeJS.ProcessEnv = process.env -): TerminalSpawnAdmissionMode { - return env[TERMINAL_SPAWN_ADMISSION_ENV_VAR]?.trim().toLowerCase() === 'observe' - ? 'observe' - : 'enforce' -} - -/** Reads the launcher's `--spawn-admission `; anything else observes. */ -export function readTerminalSpawnAdmissionArg(argv: readonly string[]): TerminalSpawnAdmissionMode { - const index = argv.indexOf(TERMINAL_SPAWN_ADMISSION_ARG) - return index !== -1 && argv[index + 1] === 'enforce' ? 'enforce' : 'observe' -} - export type TerminalSpawnLease = { readonly charge: SpawnCharge /** The fork published a session; only a live automatic one holds a live-cap slot. */ @@ -81,6 +68,7 @@ type TerminalSpawnGateOptions = { /** Runs synchronously before the first automatic fork is admitted. */ armAutomaticWork?: () => void /** The execution host's terminal cap; defaults to capping this daemon alone. */ + resolveMaximum?: () => Promise hostTerminals?: HostTerminalLedger /** The host's copy of old-client restores it refused (owner decision Q9). */ legacyRestores?: LegacyRestoreRecords @@ -136,10 +124,13 @@ export class TerminalSpawnGate { ): TerminalSpawnLease | Promise { return admitRecordingLegacyRestore( () => { - const attempt = this.attempt(facts, cancel, false) - return attempt.kind === 'lease' - ? attempt.lease - : this.admitAfterWait(facts, cancel, attempt) + const admit = (maximum?: number): TerminalSpawnLease | Promise => { + const attempt = this.attempt(facts, cancel, false, maximum) + return attempt.kind === 'lease' + ? attempt.lease + : this.admitAfterWait(facts, cancel, attempt) + } + return this.options.resolveMaximum ? this.options.resolveMaximum().then(admit) : admit() }, this.options.legacyRestores, facts, @@ -155,7 +146,7 @@ export class TerminalSpawnGate { let attempt: ReturnType = first while (attempt.kind === 'wait') { await this.waiters.waitForChange(attempt.untilMs, cancel?.signal) - attempt = this.attempt(facts, cancel, true) + attempt = this.attempt(facts, cancel, true, await this.options.resolveMaximum?.()) } return attempt.lease } @@ -163,7 +154,8 @@ export class TerminalSpawnGate { private attempt( facts: SpawnRequestFacts, cancel: { signal: AbortSignal; error: () => Error } | undefined, - alreadyWaited: boolean + alreadyWaited: boolean, + maximum = this.host.maxTerminals ): { kind: 'lease'; lease: TerminalSpawnLease } | { kind: 'wait'; untilMs: number } { if (cancel?.signal.aborted) { throw cancel.error() @@ -190,8 +182,8 @@ export class TerminalSpawnGate { }) if (this.mode === 'observe' || decision.kind === 'admit') { // Why reserve before recording: a refused fork must not be logged as admitted. - if (!this.host.tryReserve(this.state)) { - this.refuseAtHostCap(facts, charge) + if (!this.host.tryReserve(this.state, maximum)) { + this.refuseAtHostCap(facts, charge, maximum) } this.record(decision, charge, facts, !alreadyWaited) return { kind: 'lease', lease: this.lease(facts, charge, now) } @@ -199,9 +191,9 @@ export class TerminalSpawnGate { // Why: a request that would only wait to be refused at the cap is told at once. if ( decision.kind === 'wait' && - this.host.terminals(this.state) + 1 + others.terminals > this.host.maxTerminals + this.host.terminals(this.state) + 1 + others.terminals > maximum ) { - this.refuseAtHostCap(facts, charge) + this.refuseAtHostCap(facts, charge, maximum) } this.record(decision, charge, facts, !alreadyWaited) if (decision.kind === 'defer') { @@ -268,14 +260,14 @@ export class TerminalSpawnGate { this.host.stop() } - private refuseAtHostCap(facts: SpawnRequestFacts, charge: SpawnCharge): never { + private refuseAtHostCap(facts: SpawnRequestFacts, charge: SpawnCharge, maximum: number): never { this.hostCapRefused += 1 try { this.options.log('host-terminal-cap-reached', { charge, declaredIntent: facts.declaredIntent, terminals: this.host.terminals(this.state), - maxTerminals: this.host.maxTerminals + maxTerminals: maximum }) } catch { // Diagnostics must never change the refusal. diff --git a/src/main/daemon/terminal-spawn-host-share.ts b/src/main/daemon/terminal-spawn-host-share.ts index c87f7ef238c7..a6728b5d5c2d 100644 --- a/src/main/daemon/terminal-spawn-host-share.ts +++ b/src/main/daemon/terminal-spawn-host-share.ts @@ -35,8 +35,8 @@ export class TerminalSpawnHostShare { return this.liveSessions.size + interactive + user + automatic } - tryReserve(state: SpawnAdmissionState): boolean { - return this.ledger.tryReserve(this.share(state)) + tryReserve(state: SpawnAdmissionState, maximum = this.maxTerminals): boolean { + return this.ledger.tryReserve(this.share(state), maximum) } recordAutomaticAdmit(now: number): void { diff --git a/src/main/ipc/pty/runtime/controller.ts b/src/main/ipc/pty/runtime/controller.ts index 1bf389cfeb0e..726b59689f03 100644 --- a/src/main/ipc/pty/runtime/controller.ts +++ b/src/main/ipc/pty/runtime/controller.ts @@ -3,6 +3,7 @@ import { createRuntimePtySpawnState } from './spawn-state' import { localProvider } from '../provider/registry' import { getLocalAutomaticWorkStatus, + localTerminalLimit, resumeLocalAutomaticWork } from '../../../daemon/daemon-automatic-work-resume' import { makePaneKey } from '../../../../shared/stable-pane-id' @@ -60,6 +61,7 @@ export function installPtyRuntimeController(deps: PtyRuntimeControllerDeps): voi }, spawn: async (args) => spawnPtyFromRuntimeController(deps, args), // Why the local owner only: an SSH host's gate belongs to that host's own runtime. + terminalLimit: (update) => localTerminalLimit(localProvider, update), getAutomaticWorkStatus: () => getLocalAutomaticWorkStatus(localProvider), resumeAutomaticWork: () => resumeLocalAutomaticWork(localProvider), write: (ptyId, data, inputKind) => writePtyFromRuntimeController(deps, ptyId, data, inputKind), diff --git a/src/main/runtime/orca-runtime-get-status.ts b/src/main/runtime/orca-runtime-get-status.ts index 049f7d7ea0f7..89812eecd89b 100644 --- a/src/main/runtime/orca-runtime-get-status.ts +++ b/src/main/runtime/orca-runtime-get-status.ts @@ -1,4 +1,4 @@ -import { OrcaRuntimeWithGetRuntimeId } from './workspaces/session-hosts/get-runtime-id' +import { OrcaRuntimeWithPtyController } from './orca-runtime-pty-controller' import type { RuntimeDegradation, RuntimeStatus } from '../../shared/runtime-types' import { runtimeBrowserCommandsFactoryIsHeadless, @@ -36,11 +36,6 @@ import { runtimeTerminalDegradation } from './native-terminal-availability' import { isWindowsProcessStartTimeAvailable } from '../windows/windows-process-table' import type { RuntimeWorktreeLifecycleEvent } from './orca-runtime-core' import { WORKTREE_CREATE_RESULT_TTL_MS } from './orca-runtime-core' -import type { RuntimePtyController } from './runtime-pty-controller-contract' -import type { - AutomaticWorkResumeOutcome, - AutomaticWorkStatus -} from '../../shared/host-spawn-admission' import type { RuntimeNotifier } from './runtime-notifier-contract' import type { AutomationsChangedPayload, @@ -76,7 +71,7 @@ function supportsDurableTerminalPromptDelivery(): boolean { } } -export abstract class OrcaRuntimeWithGetStatus extends OrcaRuntimeWithGetRuntimeId { +export abstract class OrcaRuntimeWithGetStatus extends OrcaRuntimeWithPtyController { private asRuntimeStatusHost(): RuntimeStatusHost { return this as unknown as RuntimeStatusHost } @@ -212,22 +207,6 @@ export abstract class OrcaRuntimeWithGetStatus extends OrcaRuntimeWithGetRuntime return this.machineName.readyWithin(MACHINE_NAME_PUBLISH_WAIT_MS) } - setPtyController(controller: RuntimePtyController | null): void { - // Why: CLI terminal writes must go through the main-owned PTY registry - // instead of tunneling back through renderer IPC, or live handles could - // drift from the process they are supposed to control during reloads. - this.ptyController = controller - } - - /** Null when the local terminal owner has no fork gate (in-process fallback, older daemon). */ - async getAutomaticWorkStatus(): Promise { - return (await this.ptyController?.getAutomaticWorkStatus?.()) ?? null - } - - async resumeAutomaticWork(): Promise { - return (await this.ptyController?.resumeAutomaticWork?.()) ?? null - } - setNotifier(notifier: RuntimeNotifier | null): void { this.notifier = notifier if (notifier) { diff --git a/src/main/runtime/orca-runtime-pty-controller.ts b/src/main/runtime/orca-runtime-pty-controller.ts new file mode 100644 index 000000000000..11e160494ca0 --- /dev/null +++ b/src/main/runtime/orca-runtime-pty-controller.ts @@ -0,0 +1,29 @@ +import { OrcaRuntimeWithGetRuntimeId } from './workspaces/session-hosts/get-runtime-id' +import type { RuntimePtyController } from './runtime-pty-controller-contract' +import type { + AutomaticWorkResumeOutcome, + AutomaticWorkStatus +} from '../../shared/host-spawn-admission' +import type { TerminalLimitStatus, TerminalLimitUpdate } from '../../shared/terminal-limit-policy' + +export abstract class OrcaRuntimeWithPtyController extends OrcaRuntimeWithGetRuntimeId { + setPtyController(controller: RuntimePtyController | null): void { + // Why: CLI terminal writes must go through the main-owned PTY registry + // instead of tunneling back through renderer IPC, or live handles could + // drift from the process they are supposed to control during reloads. + this.ptyController = controller + } + + /** Null when the local terminal owner has no fork gate (in-process fallback, older daemon). */ + async terminalLimit(update?: TerminalLimitUpdate): Promise { + return (await this.ptyController?.terminalLimit?.(update)) ?? null + } + + async getAutomaticWorkStatus(): Promise { + return (await this.ptyController?.getAutomaticWorkStatus?.()) ?? null + } + + async resumeAutomaticWork(): Promise { + return (await this.ptyController?.resumeAutomaticWork?.()) ?? null + } +} diff --git a/src/main/runtime/rpc/methods/terminal-daemon.ts b/src/main/runtime/rpc/methods/terminal-daemon.ts index 31f5a3fd3a8a..ebfd61bfdfb6 100644 --- a/src/main/runtime/rpc/methods/terminal-daemon.ts +++ b/src/main/runtime/rpc/methods/terminal-daemon.ts @@ -1,3 +1,4 @@ +import { TerminalLimitUpdateParams } from '../../../../shared/rpc-contract/terminal-limit-params' import { TerminalDaemonRestartSeveredParams } from '../../../../shared/rpc-contract/terminal-daemon-params' import { readSeveredDaemonStatus, @@ -6,6 +7,18 @@ import { import { defineMethod } from '../core' export const TERMINAL_DAEMON_METHODS = [ + defineMethod({ + name: 'terminalDaemon.limit', + permission: 'workspace', + params: null, + handler: async (_params, { runtime }) => runtime.terminalLimit() + }), + defineMethod({ + name: 'terminalDaemon.setLimit', + permission: 'host-admin', + params: TerminalLimitUpdateParams, + handler: async (params, { runtime }) => runtime.terminalLimit(params) + }), defineMethod({ name: 'terminalDaemon.severedStatus', permission: 'workspace', diff --git a/src/main/runtime/runtime-pty-controller-contract.ts b/src/main/runtime/runtime-pty-controller-contract.ts index 14fcdf300d52..23c1f6a57e12 100644 --- a/src/main/runtime/runtime-pty-controller-contract.ts +++ b/src/main/runtime/runtime-pty-controller-contract.ts @@ -1,3 +1,4 @@ +import type { TerminalLimitStatus, TerminalLimitUpdate } from '../../shared/terminal-limit-policy' import type { PaneSpawnOperation } from '../ipc/pty/pane/pane-spawn-operation' import type { AgentLaunchRuntime } from '../../shared/agent-launch-runtime' import type { @@ -120,6 +121,7 @@ export type RuntimePtyController = { agentSessionEnsure?: AgentSessionClaimedSpawnResult }> /** The local terminal owner's automatic-restore state; null when it has no fork gate. */ + terminalLimit?(update?: TerminalLimitUpdate): Promise getAutomaticWorkStatus?(): Promise resumeAutomaticWork?(): Promise write(ptyId: string, data: string, inputKind: TerminalInputKind): boolean diff --git a/src/main/window/owned-temp-staging-root.ts b/src/main/window/owned-temp-staging-root.ts index 695950fb2c01..091fedddde59 100644 --- a/src/main/window/owned-temp-staging-root.ts +++ b/src/main/window/owned-temp-staging-root.ts @@ -1,4 +1,6 @@ -import type { Dir, Stats } from 'node:fs' +import type { Dir } from 'node:fs' +import { isSafeOwnedDirectory } from '../../shared/owned-private-directory' +export { isSafeOwnedDirectory } from '../../shared/owned-private-directory' import { lstat, mkdir, opendir, rm } from 'node:fs/promises' import { dirname, join, resolve } from 'node:path' @@ -30,16 +32,6 @@ export async function ensureOwnedTempStagingRoot(stagingRoot: string): Promise) => void scrollbackMode: 'preset' | 'custom' @@ -35,6 +38,7 @@ function formatScrollbackRowsLabel(rows: number): string { } export function TerminalAdvancedSection({ + hostScope, settings, updateSettings, scrollbackMode, @@ -173,6 +177,8 @@ export function TerminalAdvancedSection({ /> + {hostScope ? : null} + ({ + readTerminalLimit: vi.fn(), + saveTerminalLimit: vi.fn() +})) +vi.mock('@/i18n/i18n', () => ({ + translate: (_key: string, fallback: string, values?: Record) => + fallback.replace('{{value}}', String(values?.value)) +})) +vi.mock('@/store', () => ({ + useAppStore: (select: (state: unknown) => unknown) => select({ runtimeEnvironments: [] }) +})) +vi.mock('@/store/host-catalog-fencing', () => ({ + captureHostIdentityFence: () => ({}), + isHostIdentityFenceCurrent: () => true +})) +vi.mock('./SearchableSetting', () => ({ + SearchableSetting: ({ children }: { children: React.ReactNode }) => children +})) + +const local: SettingsHostScope = { target: { kind: 'local' }, available: true } +const base: TerminalLimitStatus = { + maxTerminals: 256, + systemPtyLimit: 511, + source: 'default', + editable: true, + daemonNonce: 'daemon-a' +} +let container: HTMLDivElement +let root: Root +beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + vi.mocked(readTerminalLimit).mockReset().mockResolvedValue(base) + vi.mocked(saveTerminalLimit) + .mockReset() + .mockImplementation(async (_route, update) => ({ + ...base, + maxTerminals: update.maxTerminals, + source: 'saved' + })) +}) +afterEach(() => { + act(() => root.unmount()) + document.body.replaceChildren() +}) +async function render(scope = local): Promise { + await act(async () => root.render()) +} +function input(): HTMLInputElement { + const found = container.querySelector('input') + if (!found) { + throw new Error('No terminal limit input') + } + return found +} +async function type(value: string): Promise { + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set?.call(input(), value) + input().dispatchEvent(new Event('input', { bubbles: true })) + }) +} +async function enter(): Promise { + await act(async () => + input().dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })) + ) +} + +it('clamps in the input, confirms Enter and blur saves once, and omits the caption and reset', async () => { + await render() + expect(input().value).toBe('256') + expect(input().max).toBe('511') + expect(container.textContent).toContain('System PTY limit: 511') + expect(container.textContent).not.toMatch(/Reset|Default:|1–511/) + await type('9999') + expect(input().value).toBe('511') + await enter() + await act(async () => input().dispatchEvent(new FocusEvent('focusout', { bubbles: true }))) + expect(saveTerminalLimit).toHaveBeenCalledTimes(1) + expect(saveTerminalLimit).toHaveBeenLastCalledWith( + { target: { kind: 'local' }, at: 'local' }, + { maxTerminals: 511, daemonNonce: 'daemon-a' }, + expect.any(AbortSignal) + ) + await type('384') + await act(async () => input().dispatchEvent(new FocusEvent('focusout', { bubbles: true }))) + expect(input().value).toBe('384') +}) + +it('discards a late answer and draft when switching execution hosts', async () => { + let complete: ((value: TerminalLimitStatus) => void) | undefined + vi.mocked(readTerminalLimit).mockImplementationOnce( + () => + new Promise((resolve) => { + complete = resolve + }) + ) + await render() + expect(input().disabled).toBe(true) + expect(input().value).toBe('') + vi.mocked(readTerminalLimit).mockResolvedValue({ + ...base, + maxTerminals: 128, + systemPtyLimit: 256, + daemonNonce: 'daemon-b' + }) + await render({ target: { kind: 'environment', environmentId: 'server' }, available: true }) + await act(async () => complete?.(base)) + expect(input().value).toBe('128') + expect(input().max).toBe('256') + advanceRuntimeEnvironmentConnectionGeneration('server') + vi.mocked(readTerminalLimit).mockResolvedValue({ ...base, maxTerminals: 64 }) + await render({ target: { kind: 'environment', environmentId: 'server' }, available: true }) + expect(input().value).toBe('64') +}) + +it('retains a failed draft and ignores its late refresh after a successful retry', async () => { + await render() + let completeRefresh: ((value: TerminalLimitStatus) => void) | undefined + vi.mocked(readTerminalLimit).mockImplementationOnce( + () => + new Promise((resolve) => { + completeRefresh = resolve + }) + ) + vi.mocked(saveTerminalLimit).mockRejectedValueOnce(new Error('disk unavailable')) + await type('384') + await enter() + expect(input().value).toBe('384') + expect(container.textContent).toContain('Couldn’t confirm') + expect(container.textContent).not.toContain('saved') + await type('400') + await enter() + await act(async () => completeRefresh?.(base)) + expect(input().value).toBe('400') + expect(container.textContent).not.toContain('Couldn’t confirm') +}) + +it('keeps confirmed environment values above the bound and leaves old daemons uneditable', async () => { + vi.mocked(readTerminalLimit).mockResolvedValue({ + ...base, + maxTerminals: 600, + source: 'environment', + editable: false + }) + await render() + expect(input().value).toBe('600') + expect(input().disabled).toBe(true) + expect(container.textContent).toContain('environment') + vi.mocked(readTerminalLimit).mockResolvedValue(null) + await render({ target: { kind: 'environment', environmentId: 'old' }, available: true }) + expect(input().value).toBe('') + expect(input().disabled).toBe(true) + expect(container.textContent).toContain('does not support') +}) diff --git a/src/renderer/src/components/settings/TerminalLimitSetting.tsx b/src/renderer/src/components/settings/TerminalLimitSetting.tsx new file mode 100644 index 000000000000..4c0dffadf0c2 --- /dev/null +++ b/src/renderer/src/components/settings/TerminalLimitSetting.tsx @@ -0,0 +1,249 @@ +import { useEffect, useMemo, useRef, useState } from 'react' +import { + terminalLimitInputMaximum, + type TerminalLimitStatus +} from '../../../../shared/terminal-limit-policy' +import { Input } from '../ui/input' +import { Button } from '../ui/button' +import { SettingsRow } from './SettingsFormControls' +import { SearchableSetting } from './SearchableSetting' +import type { SettingsHostScope } from './settings-host-scope' +import { readTerminalLimit, saveTerminalLimit } from './terminal-limit-transport' +import { useAppStore } from '@/store' +import { getRuntimeEnvironmentConnectionGeneration } from '@/store/slices/runtime-status-connection-generation' +import { + captureHostIdentityFence, + isHostIdentityFenceCurrent, + type HostIdentityFence +} from '@/store/host-catalog-fencing' +import type { HostRoute } from '@/runtime/runtime-client-target' +import { translate } from '@/i18n/i18n' + +export function TerminalLimitSetting({ scope }: { scope: SettingsHostScope }): React.JSX.Element { + const environmentId = scope.target.kind === 'environment' ? scope.target.environmentId : null + const revision = useAppStore((state) => { + const host = state.runtimeEnvironments.find((item) => item.id === environmentId) + const pairing = host?.pairingRevision ?? host?.createdAt ?? 0 + const connection = environmentId ? getRuntimeEnvironmentConnectionGeneration(environmentId) : 0 + return `${pairing}:${connection}` + }) + return ( + + ) +} + +function TerminalLimitField({ scope }: { scope: SettingsHostScope }): React.JSX.Element { + const route = useMemo(() => ({ target: scope.target, at: 'local' }), [scope.target]) + const [status, setStatus] = useState() + const [draft, setDraft] = useState(null) + const [failed, setFailed] = useState(false) + const [busy, setBusy] = useState(false) + const controller = useRef(null) + const confirmedFence = useRef(null) + const saving = useRef(false) + const saveGeneration = useRef(0) + const [retry, setRetry] = useState(0) + useEffect(() => { + const request = new AbortController() + controller.current = request + const fence = captureHostIdentityFence(route) + setStatus(undefined) + setFailed(false) + if (scope.available) { + void readTerminalLimit(route, request.signal) + .then((value) => { + if (!request.signal.aborted && isHostIdentityFenceCurrent(fence)) { + confirmedFence.current = fence + setStatus(value) + } + }) + .catch(() => { + if (!request.signal.aborted) { + setFailed(true) + } + }) + } + return () => request.abort() + }, [route, scope.available, retry]) + + const maximum = terminalLimitInputMaximum(status?.systemPtyLimit ?? null) + const commit = async (): Promise => { + const request = controller.current + if ( + !status?.editable || + draft === null || + saving.current || + !request || + request.signal.aborted + ) { + return + } + if (!confirmedFence.current || !isHostIdentityFenceCurrent(confirmedFence.current)) { + setFailed(true) + return + } + if (draft === '' || !Number.isFinite(Number(draft))) { + setDraft(null) + return + } + const value = Math.max(1, Math.min(maximum, Math.trunc(Number(draft)))) + if (value === status.maxTerminals) { + setDraft(null) + return + } + saving.current = true + const generation = ++saveGeneration.current + setBusy(true) + setFailed(false) + try { + const confirmed = await saveTerminalLimit( + route, + { maxTerminals: value, daemonNonce: status.daemonNonce }, + request.signal + ) + if (!request.signal.aborted) { + if (!confirmed) { + throw new Error('Unsupported terminal service') + } + setStatus(confirmed) + setDraft(null) + } + } catch { + if (!request.signal.aborted) { + setFailed(true) + // Refresh a changed host bound, while retaining the user's draft for retry. + void readTerminalLimit(route, request.signal) + .then((fresh) => { + if (!request.signal.aborted && saveGeneration.current === generation) { + setStatus(fresh) + } + }) + .catch(() => undefined) + } + } finally { + saving.current = false + if (!request.signal.aborted) { + setBusy(false) + } + } + } + + const unavailable = !scope.available + ? translate( + 'settings.terminal.limit.disconnected', + 'This host is disconnected. Reconnect to view or change its terminal limit.' + ) + : status === null || (status?.editable === false && status.source !== 'environment') + ? translate( + 'settings.terminal.limit.unsupported', + 'This host’s terminal service does not support changing this limit yet.' + ) + : status?.source === 'environment' + ? translate( + 'settings.terminal.limit.environment', + 'This Orca instance has a terminal limit set by its environment. Remove the override on this host to edit it here.' + ) + : null + const label = translate('settings.terminal.limit.label', 'Maximum running terminals') + return ( + + + + {translate( + 'settings.terminal.limit.description', + 'Limits your running terminals across projects on this host.' + )} + + + {translate('settings.terminal.limit.system', 'System PTY limit: {{value}}', { + value: + status === undefined && scope.available && !failed + ? '…' + : (status?.systemPtyLimit?.toLocaleString() ?? + translate('settings.terminal.limit.unknown', 'Unavailable')) + })} + + + {translate( + 'settings.terminal.limit.shared', + 'Shared with other terminal apps. This is total capacity, not free slots.' + )} + + {unavailable ? {unavailable} : null} + {failed ? ( + + {translate( + 'settings.terminal.limit.failed', + 'Couldn’t confirm the terminal limit. Try again.' + )} + + ) : null} + {failed && status === undefined ? ( + + ) : null} + + } + control={ +
+ { + const raw = event.target.value + setDraft( + raw === '' ? '' : String(Math.max(1, Math.min(maximum, Math.trunc(Number(raw))))) + ) + setFailed(false) + }} + onBlur={() => void commit()} + onKeyDown={(event) => { + if (event.key === 'Enter') { + event.preventDefault() + void commit() + } + if (event.key === 'Escape') { + setDraft(null) + setFailed(false) + } + }} + className="number-input-clean w-24 tabular-nums" + /> + + {translate('settings.terminal.limit.unit', 'terminals')} + +
+ } + /> +
+ ) +} diff --git a/src/renderer/src/components/settings/TerminalPane.tsx b/src/renderer/src/components/settings/TerminalPane.tsx index ed17c1ece1e9..e4c31bd9c552 100644 --- a/src/renderer/src/components/settings/TerminalPane.tsx +++ b/src/renderer/src/components/settings/TerminalPane.tsx @@ -1,3 +1,4 @@ +import type { SettingsHostScope } from './settings-host-scope' import { useState } from 'react' import { ChevronDown } from 'lucide-react' import type { GlobalSettings } from '../../../../shared/global-settings-types' @@ -34,6 +35,7 @@ import { translate } from '@/i18n/i18n' import { translateSearchKeyword } from './settings-search-keywords' type TerminalPaneProps = { + hostScope?: SettingsHostScope settings: GlobalSettings updateSettings: (updates: Partial) => void scrollbackMode: 'preset' | 'custom' @@ -53,6 +55,7 @@ type TerminalPaneProps = { } export function TerminalPane({ + hostScope, settings, updateSettings, scrollbackMode, @@ -343,6 +346,7 @@ export function TerminalPane({ matchesSettingsSearch(searchQuery, getTerminalMacYenSearchEntries()))) ? ( {view.isSectionMounted('terminal') ? ( [ + { + title: translate('settings.terminal.limit.label', 'Maximum running terminals'), + description: translate( + 'settings.terminal.limit.description', + 'Limits your running terminals across projects on this host.' + ), + keywords: ['terminal', 'limit', 'maximum', 'pty', 'capacity'] + }, { title: translate('auto.components.settings.terminal.search.7674e758e1', 'Scrollback Rows'), description: translate( diff --git a/src/renderer/src/components/settings/terminal-limit-transport.ts b/src/renderer/src/components/settings/terminal-limit-transport.ts new file mode 100644 index 000000000000..56f0bf041ef8 --- /dev/null +++ b/src/renderer/src/components/settings/terminal-limit-transport.ts @@ -0,0 +1,27 @@ +import type { RuntimeStatus } from '../../../../shared/runtime-types' +import { + TERMINAL_LIMIT_RUNTIME_CAPABILITY, + type TerminalLimitStatus, + type TerminalLimitUpdate +} from '../../../../shared/terminal-limit-policy' +import { callHostRoute } from '@/runtime/host-route-call' +import type { HostRoute } from '@/runtime/runtime-client-target' + +export async function readTerminalLimit( + route: HostRoute, + signal: AbortSignal +): Promise { + const host = await callHostRoute(route, 'status.get', undefined, { signal }) + if (!host.capabilities?.includes(TERMINAL_LIMIT_RUNTIME_CAPABILITY)) { + return null + } + return callHostRoute(route, 'terminalDaemon.limit', undefined, { signal }) +} + +export function saveTerminalLimit( + route: HostRoute, + update: TerminalLimitUpdate, + signal: AbortSignal +): Promise { + return callHostRoute(route, 'terminalDaemon.setLimit', update, { signal }) +} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 7b360073e116..9392092a3ce9 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -260,6 +260,19 @@ "openManageSessions": "Open Manage Sessions", "administratorSearchDescription": "See Orca’s Windows permissions or restart with administrator approval.", "administratorApproval": "Windows will ask for approval. Use your usual account." + }, + "limit": { + "label": "Maximum running terminals", + "description": "Limits your running terminals across projects on this host.", + "system": "System PTY limit: {{value}}", + "unknown": "Unavailable", + "shared": "Shared with other terminal apps. This is total capacity, not free slots.", + "disconnected": "This host is disconnected. Reconnect to view or change its terminal limit.", + "unsupported": "This host’s terminal service does not support changing this limit yet.", + "environment": "This Orca instance has a terminal limit set by its environment. Remove the override on this host to edit it here.", + "failed": "Couldn’t confirm the terminal limit. Try again.", + "retry": "Retry", + "unit": "terminals" } }, "appearance": { diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 77281d5af5f3..97a77030186c 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -83,6 +83,19 @@ "runAdministratorHelp": "Guía de administrador", "standardStatus": "Usuario estándar", "unknownAdministrator": "No se puede determinar" + }, + "limit": { + "label": "Máximo de terminales en ejecución", + "description": "Limita las terminales en ejecución entre proyectos en este equipo.", + "system": "Límite de PTY del sistema: {{value}}", + "unknown": "No disponible", + "shared": "Compartido con otras aplicaciones de terminal. Es la capacidad total, no los espacios libres.", + "disconnected": "Este equipo está desconectado. Vuelve a conectarlo para ver o cambiar su límite de terminales.", + "unsupported": "El servicio de terminal de este equipo aún no permite cambiar este límite.", + "environment": "El entorno establece el límite de terminales de esta instancia de Orca. Elimina esa configuración en este equipo para editarlo aquí.", + "failed": "No se pudo confirmar el límite de terminales. Inténtalo de nuevo.", + "retry": "Reintentar", + "unit": "terminales" } }, "appearance": { diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index bb2a4719bd99..d94fd9f97d7d 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -187,6 +187,19 @@ "runAdministratorHelp": "Guide de l'administrateur", "standardStatus": "Utilisateur standard", "unknownAdministrator": "Impossible de déterminer" + }, + "limit": { + "label": "Nombre maximal de terminaux actifs", + "description": "Limite les terminaux actifs de tous les projets sur cet hôte.", + "system": "Limite PTY du système : {{value}}", + "unknown": "Indisponible", + "shared": "Partagée avec les autres applications de terminal. Il s’agit de la capacité totale, pas des places libres.", + "disconnected": "Cet hôte est déconnecté. Reconnectez-le pour consulter ou modifier sa limite de terminaux.", + "unsupported": "Le service de terminal de cet hôte ne permet pas encore de modifier cette limite.", + "environment": "L’environnement définit la limite de terminaux de cette instance d’Orca. Supprimez cette configuration sur cet hôte pour la modifier ici.", + "failed": "Impossible de confirmer la limite de terminaux. Réessayez.", + "retry": "Réessayer", + "unit": "terminaux" } }, "appearance": { diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 93bdbc507ff1..84fddad1530d 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -83,6 +83,19 @@ "runAdministratorHelp": "管理者ガイド", "standardStatus": "標準ユーザー", "unknownAdministrator": "判定できません" + }, + "limit": { + "label": "実行中のターミナルの上限", + "description": "このホスト上の全プロジェクトで実行中のターミナル数を制限します。", + "system": "システムのPTY上限: {{value}}", + "unknown": "取得できません", + "shared": "他のターミナルアプリと共有されます。空き数ではなく総容量です。", + "disconnected": "このホストは切断されています。再接続してターミナルの上限を確認または変更してください。", + "unsupported": "このホストのターミナルサービスは、まだ上限の変更に対応していません。", + "environment": "このOrcaインスタンスのターミナル上限は環境変数で設定されています。ここで編集するには、このホストの環境変数による設定を削除してください。", + "failed": "ターミナルの上限を確認できませんでした。もう一度お試しください。", + "retry": "再試行", + "unit": "ターミナル" } }, "appearance": { diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 06fb8754d616..fdd814bc0be3 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -83,6 +83,19 @@ "runAdministratorHelp": "관리자 가이드", "standardStatus": "표준 사용자", "unknownAdministrator": "확인할 수 없음" + }, + "limit": { + "label": "실행 중인 터미널 최대 개수", + "description": "이 호스트의 모든 프로젝트에서 실행 중인 터미널 수를 제한합니다.", + "system": "시스템 PTY 한도: {{value}}", + "unknown": "확인할 수 없음", + "shared": "다른 터미널 앱과 공유합니다. 남은 개수가 아닌 전체 용량입니다.", + "disconnected": "이 호스트의 연결이 끊겼습니다. 터미널 한도를 확인하거나 변경하려면 다시 연결하세요.", + "unsupported": "이 호스트의 터미널 서비스는 아직 한도 변경을 지원하지 않습니다.", + "environment": "이 Orca 인스턴스의 터미널 한도는 환경 변수로 설정되어 있습니다. 여기서 편집하려면 이 호스트에서 해당 설정을 제거하세요.", + "failed": "터미널 한도를 확인하지 못했습니다. 다시 시도하세요.", + "retry": "다시 시도", + "unit": "터미널" } }, "appearance": { diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 5d3749e13365..6335e8e580b7 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -83,6 +83,19 @@ "runAdministratorHelp": "管理员指南", "standardStatus": "标准用户", "unknownAdministrator": "无法确定" + }, + "limit": { + "label": "运行中终端的最大数量", + "description": "限制此主机上所有项目中正在运行的终端数量。", + "system": "系统 PTY 上限:{{value}}", + "unknown": "无法获取", + "shared": "与其他终端应用共享。这是总容量,并非可用数量。", + "disconnected": "此主机已断开连接。请重新连接以查看或更改终端上限。", + "unsupported": "此主机的终端服务尚不支持更改此上限。", + "environment": "此 Orca 实例的终端上限由环境变量设置。要在此编辑,请先移除此主机上的相应环境设置。", + "failed": "无法确认终端上限。请重试。", + "retry": "重试", + "unit": "个终端" } }, "appearance": { diff --git a/src/shared/owned-private-directory.ts b/src/shared/owned-private-directory.ts new file mode 100644 index 000000000000..b5c5dc977c94 --- /dev/null +++ b/src/shared/owned-private-directory.ts @@ -0,0 +1,11 @@ +import type { Stats } from 'node:fs' + +export function isSafeOwnedDirectory(stats: Stats): boolean { + if (!stats.isDirectory() || stats.isSymbolicLink()) { + return false + } + return ( + typeof process.getuid !== 'function' || + (stats.uid === process.getuid() && (stats.mode & 0o777) === 0o700) + ) +} diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts index e4edd4c1e8f5..514bc20ca528 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -568,6 +568,7 @@ import { QueuedMessageUpdateParams } from './structured-agent-session-queued-edit-params' import { TerminalDaemonRestartSeveredParams } from './terminal-daemon-params' +import { TerminalLimitUpdateParams } from './terminal-limit-params' import { TerminalAdoptOrphans } from './terminal-orphan-params' import { TerminalQuickCommandsUpdate } from './terminal-quick-command-params' import { @@ -1379,7 +1380,9 @@ export const RPC_PARAMS_BY_METHOD = { 'terminal.unsubscribe': TerminalUnsubscribe, 'terminal.updateViewport': TerminalUpdateViewport, 'terminal.wait': TerminalWait, + 'terminalDaemon.limit': null, 'terminalDaemon.restartSevered': TerminalDaemonRestartSeveredParams, + 'terminalDaemon.setLimit': TerminalLimitUpdateParams, 'terminalDaemon.severedStatus': null, 'ui.get': null, 'ui.getJiraQuickFilters': null, diff --git a/src/shared/rpc-contract/terminal-limit-params.ts b/src/shared/rpc-contract/terminal-limit-params.ts new file mode 100644 index 000000000000..942ad2eeca98 --- /dev/null +++ b/src/shared/rpc-contract/terminal-limit-params.ts @@ -0,0 +1,7 @@ +import { z } from 'zod' +import { MAX_CONFIGURED_TERMINALS } from '../terminal-limit-policy' + +export const TerminalLimitUpdateParams = z.object({ + maxTerminals: z.number().int().min(1).max(MAX_CONFIGURED_TERMINALS), + daemonNonce: z.string().min(1).max(128) +}) diff --git a/src/shared/terminal-limit-policy.ts b/src/shared/terminal-limit-policy.ts new file mode 100644 index 000000000000..800429839430 --- /dev/null +++ b/src/shared/terminal-limit-policy.ts @@ -0,0 +1,25 @@ +export const TERMINAL_LIMIT_RUNTIME_CAPABILITY = 'terminal.limit-policy.v1' as const +export const MAX_CONFIGURED_TERMINALS = 4096 + +export type TerminalLimitStatus = { + maxTerminals: number + systemPtyLimit: number | null + source: 'environment' | 'saved' | 'default' + editable: boolean + daemonNonce: string +} + +export type TerminalLimitUpdate = { maxTerminals: number; daemonNonce: string } + +export function isConfiguredTerminalLimit(value: unknown): value is number { + return ( + typeof value === 'number' && + Number.isSafeInteger(value) && + value >= 1 && + value <= MAX_CONFIGURED_TERMINALS + ) +} + +export function terminalLimitInputMaximum(systemPtyLimit: number | null): number { + return Math.min(MAX_CONFIGURED_TERMINALS, systemPtyLimit ?? MAX_CONFIGURED_TERMINALS) +} diff --git a/src/shared/terminal-runtime-capabilities.ts b/src/shared/terminal-runtime-capabilities.ts index 3eb0a8f34f2b..0b04f21f121f 100644 --- a/src/shared/terminal-runtime-capabilities.ts +++ b/src/shared/terminal-runtime-capabilities.ts @@ -1,3 +1,4 @@ +import { TERMINAL_LIMIT_RUNTIME_CAPABILITY } from './terminal-limit-policy' import { PROGRAM_STATUS_RUNTIME_CAPABILITY } from './program-status/protocol' import { TERMINAL_QUICK_COMMAND_RUNTIME_CAPABILITIES } from './terminal-quick-command-capabilities' @@ -24,6 +25,7 @@ export const TERMINAL_CREATE_SHELL_SELECTION_RUNTIME_CAPABILITY = 'terminal.create-shell-selection.v1' as const export const TERMINAL_RUNTIME_CAPABILITIES = [ + TERMINAL_LIMIT_RUNTIME_CAPABILITY, 'terminal.binary-stream.v1', PROGRAM_STATUS_RUNTIME_CAPABILITY, 'terminal.multiplex.v1', From 3c93d28991786c407e47d6c78f15f01f93673b40 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 20 Oct 2026 22:08:46 -0700 Subject: [PATCH 02/15] fix: bound terminal policy saves through fresh confirmation --- src/main/daemon/daemon-server.ts | 2 +- .../daemon/daemon-terminal-limit-protocol.ts | 17 +-- src/main/daemon/daemon-terminal-limit.test.ts | 59 +++++++ src/main/daemon/host-terminal-policy.test.ts | 138 ++++++++++++++++- src/main/daemon/host-terminal-policy.ts | 144 ++++++++++++++---- .../settings/TerminalLimitSetting.test.tsx | 100 ++++++++++-- .../settings/TerminalLimitSetting.tsx | 35 +++-- .../terminal-advanced-platform-search.ts | 12 +- src/renderer/src/i18n/locales/en.json | 8 +- src/renderer/src/i18n/locales/es.json | 8 +- src/renderer/src/i18n/locales/fr.json | 8 +- src/renderer/src/i18n/locales/ja.json | 8 +- src/renderer/src/i18n/locales/ko.json | 8 +- src/renderer/src/i18n/locales/zh.json | 8 +- 14 files changed, 476 insertions(+), 79 deletions(-) diff --git a/src/main/daemon/daemon-server.ts b/src/main/daemon/daemon-server.ts index 32da927a241e..6765f930de56 100644 --- a/src/main/daemon/daemon-server.ts +++ b/src/main/daemon/daemon-server.ts @@ -299,7 +299,7 @@ export class DaemonServer { request, this.terminalPolicy, this.terminalPolicyNonce, - () => !this.endpoint.hasLostOwnership() + () => this.lifecycle.isAcceptingWork() && !this.endpoint.hasLostOwnership() ) return ( limitRequest ?? diff --git a/src/main/daemon/daemon-terminal-limit-protocol.ts b/src/main/daemon/daemon-terminal-limit-protocol.ts index b9bc66109a40..ee005047c045 100644 --- a/src/main/daemon/daemon-terminal-limit-protocol.ts +++ b/src/main/daemon/daemon-terminal-limit-protocol.ts @@ -3,7 +3,6 @@ import { type TerminalLimitStatus } from '../../shared/terminal-limit-policy' import type { HostTerminalPolicy } from './host-terminal-policy' -import { awaitDaemonValueWithinCallerDeadline } from './daemon-request-deadline' /** New requests remain unknown on older daemons; no protocol-generation change or replacement. */ export function answerTerminalLimitRequest( @@ -15,6 +14,7 @@ export function answerTerminalLimitRequest( if (request.type !== 'terminalLimitStatus' && request.type !== 'setTerminalLimit') { return undefined } + const deadline = Date.now() + 2_000 const work = async (): Promise => { if (!isCurrent()) { throw new Error('Terminal host changed. Refresh the setting and try again.') @@ -31,18 +31,9 @@ export function answerTerminalLimitRequest( ) { throw new Error('Terminal setting changed. Refresh the setting and try again.') } - await policy.save(update.maxTerminals, isCurrent) + return policy.save(update.maxTerminals, isCurrent, nonce, deadline) } - const status = await policy.status(nonce) - if (!isCurrent()) { - throw new Error('Terminal host changed. Refresh the setting and try again.') - } - return status + return policy.status(nonce, isCurrent, deadline) } - return awaitDaemonValueWithinCallerDeadline(work(), Date.now() + 2_000).then((result) => { - if (!result.completed) { - throw new Error('Couldn’t confirm the terminal setting. Refresh and try again.') - } - return result.value - }) + return work() } diff --git a/src/main/daemon/daemon-terminal-limit.test.ts b/src/main/daemon/daemon-terminal-limit.test.ts index 93b0c4219833..7a7fefbdc974 100644 --- a/src/main/daemon/daemon-terminal-limit.test.ts +++ b/src/main/daemon/daemon-terminal-limit.test.ts @@ -1,5 +1,7 @@ +import type * as FileSystem from 'node:fs/promises' import './mock-descendant-sweep' import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' @@ -12,6 +14,11 @@ import { HostTerminalPolicy } from './host-terminal-policy' import { SystemPtyLimit } from './system-pty-limit' import type { TerminalLimitStatus } from '../../shared/terminal-limit-policy' +vi.mock('node:fs/promises', async (original) => { + const fs = await original() + return { ...fs, writeFile: vi.fn(fs.writeFile), rm: vi.fn(fs.rm) } +}) + let server: DaemonServer | undefined let client: DaemonClient | undefined let directory: string | undefined @@ -82,3 +89,55 @@ it('recognizes an older daemon without replacement and preserves real transport adapter.dispose() } }) + +it('fences an actual pending save when the server shuts down before replacement', async () => { + directory = mkdtempSync(join(tmpdir(), 'terminal-limit-shutdown-')) + const path = join(directory, 'policy', 'terminals.json') + server = new DaemonServer({ + socketPath: getDaemonSocketPath(directory), + tokenPath: join(directory, 'token'), + terminalLimitPolicy: new HostTerminalPolicy(path, {}, new SystemPtyLimit(async () => 511)), + spawnSubprocess: async () => createMockSubprocess() + }) + await server.start() + client = new DaemonClient({ + socketPath: getDaemonSocketPath(directory), + tokenPath: join(directory, 'token') + }) + await client.ensureConnected() + const before = await client.request('terminalLimitStatus', undefined) + let release!: () => void + let started!: () => void + const held = new Promise((done) => { + release = done + }) + const staging = new Promise((done) => { + started = done + }) + const fs = await vi.importActual('node:fs/promises') + vi.mocked(writeFile).mockImplementationOnce(async (...args) => { + started() + await held + await fs.writeFile(...args) + }) + let cleaned!: () => void + const cleanup = new Promise((done) => { + cleaned = done + }) + vi.mocked(rm).mockImplementationOnce(async (...args) => { + await fs.rm(...args) + cleaned() + }) + const save = client.request('setTerminalLimit', { + daemonNonce: before.daemonNonce, + maxTerminals: 10 + }) + const failed = expect(save).rejects.toThrow() + await staging + await server.shutdown() + release() + await failed + await cleanup + expect(await fs.readdir(join(directory, 'policy'))).toEqual([]) + expect(() => readFileSync(path)).toThrow() +}) diff --git a/src/main/daemon/host-terminal-policy.test.ts b/src/main/daemon/host-terminal-policy.test.ts index 34c379bdb51c..a68c78163cfd 100644 --- a/src/main/daemon/host-terminal-policy.test.ts +++ b/src/main/daemon/host-terminal-policy.test.ts @@ -1,4 +1,5 @@ -import { mkdtemp, rm } from 'node:fs/promises' +import type * as FileSystem from 'node:fs/promises' +import { mkdtemp, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -8,6 +9,19 @@ import { HostTerminalLedger } from './host-terminal-ledger' import { TerminalSpawnGate } from './terminal-spawn-gate' import type { SpawnRequestFacts } from '../../shared/host-spawn-admission' +vi.mock('node:fs/promises', async (original) => { + const fs = await original() + return { ...fs, writeFile: vi.fn(fs.writeFile), rename: vi.fn(fs.rename), rm: vi.fn(fs.rm) } +}) + +function deferred() { + let resolve!: (value: T) => void + const promise = new Promise((done) => { + resolve = done + }) + return { promise, resolve } +} + const facts: SpawnRequestFacts = { clientId: 'user', declaredIntent: null, @@ -19,7 +33,11 @@ const system = () => new SystemPtyLimit(async () => 511) const directories: string[] = [] afterEach(async () => { vi.useRealTimers() - await Promise.all(directories.splice(0).map((path) => rm(path, { recursive: true, force: true }))) + const fs = await vi.importActual('node:fs/promises') + await Promise.all( + directories.splice(0).map((path) => fs.rm(path, { recursive: true, force: true })) + ) + vi.resetAllMocks() }) async function home(): Promise { @@ -116,6 +134,122 @@ describe('host terminal policy', () => { expect(read).toHaveBeenCalledOnce() }) + it('drains a held admission snapshot after replacement before confirming the saved value', async () => { + const path = join(await home(), 'policy.json') + const old = deferred() + const read = vi + .fn() + .mockImplementationOnce(() => old.promise) + .mockImplementation(async () => JSON.parse(await readFile(path, 'utf8')).maxTerminals) + const policy = new HostTerminalPolicy(path, {}, system(), read) + const admission = policy.admissionMaximum() + const replaced = deferred() + const fs = await vi.importActual('node:fs/promises') + vi.mocked(rename).mockImplementationOnce(async (...args) => { + await fs.rename(...args) + replaced.resolve() + }) + const save = policy.save(3, () => true, 'nonce') + await replaced.promise + await new Promise(setImmediate) + old.resolve(2) + expect(await admission).toBe(2) + expect(await save).toMatchObject({ maxTerminals: 3, source: 'saved', daemonNonce: 'nonce' }) + expect(read).toHaveBeenCalledTimes(2) + }) + + it('expires staging without a late rename or orphan, and permits retry while cleanup stalls', async () => { + const path = join(await home(), 'policy.json') + const fs = await vi.importActual('node:fs/promises') + const started = deferred() + const release = deferred() + const staged = deferred() + const cleaned = deferred() + const cleanup = deferred() + let expiredTemporary: Parameters[0] + vi.mocked(writeFile).mockImplementationOnce(async (...args) => { + expiredTemporary = args[0] + started.resolve() + await release.promise + await fs.writeFile(...args) + staged.resolve() + }) + vi.mocked(rm).mockImplementation(async (...args) => { + if (args[0] !== expiredTemporary) { + await cleanup.promise + } + await fs.rm(...args) + if (args[0] === expiredTemporary) { + cleaned.resolve() + } + }) + vi.useFakeTimers() + const policy = new HostTerminalPolicy(path, {}, system()) + const save = policy.save(10, () => true) + const failed = expect(save).rejects.toThrow('confirm') + await started.promise + await vi.advanceTimersByTimeAsync(2_001) + await failed + expect(rename).not.toHaveBeenCalled() + expect(rm).not.toHaveBeenCalled() + vi.useRealTimers() + expect(await policy.save(20, () => true)).toMatchObject({ maxTerminals: 20 }) + expect(await policy.save(30, () => true)).toMatchObject({ maxTerminals: 30 }) + release.resolve() + await staged.promise + await cleaned.promise + cleanup.resolve() + expect(await policy.admissionMaximum()).toBe(30) + expect(rename).toHaveBeenCalledTimes(2) + expect(await readdir(join(path, '..'))).toEqual(['policy.json']) + }) + + it.each(['completed', 'retryable failure'])( + 'keeps an expired issued rename unconfirmed: %s', + async (outcome) => { + const path = join(await home(), 'policy.json') + const fs = await vi.importActual('node:fs/promises') + const started = deferred() + const release = deferred() + const cleaned = deferred() + let issuedTemporary: Parameters[0] + vi.mocked(rename).mockImplementationOnce(async (...args) => { + issuedTemporary = args[0] + started.resolve() + await release.promise + if (outcome === 'retryable failure') { + throw Object.assign(new Error('busy'), { code: 'EPERM' }) + } + await fs.rename(...args) + }) + vi.mocked(rm).mockImplementation(async (...args) => { + await fs.rm(...args) + if (args[0] === issuedTemporary) { + cleaned.resolve() + } + }) + const policy = new HostTerminalPolicy(path, {}, system()) + vi.useFakeTimers() + const save = policy.save(10, () => true) + const failed = expect(save).rejects.toThrow('confirm') + await started.promise + await vi.advanceTimersByTimeAsync(2_001) + await failed + expect(await policy.save(20, () => true)).toMatchObject({ maxTerminals: 20 }) + const platform = process.platform + try { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + release.resolve() + await vi.advanceTimersByTimeAsync(100) + await cleaned.promise + } finally { + Object.defineProperty(process, 'platform', { configurable: true, value: platform }) + } + expect(await policy.admissionMaximum()).toBe(outcome === 'completed' ? 10 : 20) + expect(rename).toHaveBeenCalledTimes(2) + } + ) + it('reports Linux configured global and devpts capacity without subtracting namespace reserve', () => { expect(parseLinuxPtyLimit('4096\n', 'devpts /dev/pts devpts rw,max=128 0 0')).toBe(128) expect(parseLinuxPtyLimit('4096', 'devpts /dev/pts devpts rw 0 0')).toBe(4096) diff --git a/src/main/daemon/host-terminal-policy.ts b/src/main/daemon/host-terminal-policy.ts index 5124d1e5d44a..60e21f36a4bf 100644 --- a/src/main/daemon/host-terminal-policy.ts +++ b/src/main/daemon/host-terminal-policy.ts @@ -53,9 +53,46 @@ async function readSavedMaximum(path: string): Promise { } } +type PolicyOperation = { + isCurrent: () => boolean + wait: (load: () => Promise) => Promise +} + +async function withPolicyOperation( + isHostCurrent: () => boolean, + deadline: number, + work: (operation: PolicyOperation) => Promise +): Promise { + let active = true + const isCurrent = (): boolean => active && Date.now() < deadline && isHostCurrent() + const check = (): void => { + if (!isCurrent()) { + throw new Error('Couldn’t confirm the terminal setting. Refresh and try again.') + } + } + const operation: PolicyOperation = { + isCurrent, + wait: async (load) => { + check() + const result = await awaitDaemonValueWithinCallerDeadline(load(), deadline) + check() + if (!result.completed) { + throw new Error('Couldn’t confirm the terminal setting. Refresh and try again.') + } + return result.value + } + } + try { + const result = await work(operation) + check() + return result + } finally { + active = false + } +} + export class HostTerminalPolicy { private readonly reads = new InFlightPromiseDedupe(0, 1) - private writing = false private readonly environment: number | null constructor( @@ -92,11 +129,11 @@ export class HostTerminalPolicy { } } - async status(daemonNonce: string): Promise { - const [saved, systemPtyLimit] = await Promise.all([ - this.environment === null ? this.saved() : Promise.resolve(null), - this.system.read() - ]) + private observedStatus( + saved: number | null, + systemPtyLimit: number | null, + daemonNonce: string + ): TerminalLimitStatus { return { maxTerminals: this.environment ?? saved ?? DEFAULT_MAX_HOST_TERMINALS, source: this.environment !== null ? 'environment' : saved !== null ? 'saved' : 'default', @@ -106,37 +143,78 @@ export class HostTerminalPolicy { } } - async save(maximum: number, isCurrent: () => boolean): Promise { - if (!this.path || this.environment !== null || this.writing) { - throw new Error('Terminal setting unavailable') - } - this.writing = true - let temporary: string | undefined - try { - // A read that started before the write must settle before authoritative readback. - await this.saved() - const ceiling = terminalLimitInputMaximum(await this.system.read()) - if (!isConfiguredTerminalLimit(maximum) || maximum > ceiling) { + status( + daemonNonce: string, + isCurrent: () => boolean = () => true, + deadline = Date.now() + 2_000 + ): Promise { + return withPolicyOperation(isCurrent, deadline, async (operation) => { + const [saved, systemPtyLimit] = await operation.wait(() => + Promise.all([ + this.environment === null ? this.saved() : Promise.resolve(null), + this.system.read() + ]) + ) + return this.observedStatus(saved, systemPtyLimit, daemonNonce) + }) + } + + save( + maximum: number, + isCurrent: () => boolean, + daemonNonce = '', + deadline = Date.now() + 2_000 + ): Promise { + return withPolicyOperation(isCurrent, deadline, async (operation) => { + const path = this.path + if (!path || this.environment !== null) { + throw new Error('Terminal setting unavailable') + } + const systemPtyLimit = await operation.wait(() => this.system.read()) + if ( + !isConfiguredTerminalLimit(maximum) || + maximum > terminalLimitInputMaximum(systemPtyLimit) + ) { throw new Error('Terminal limit exceeds host capacity') } - const directory = dirname(this.path) - await mkdir(directory, { recursive: true, mode: 0o700 }) - if (!isSafeOwnedDirectory(await lstat(directory))) { + const directory = dirname(path) + await operation.wait(() => mkdir(directory, { recursive: true, mode: 0o700 })) + if (!isSafeOwnedDirectory(await operation.wait(() => lstat(directory)))) { throw new Error('Terminal policy directory is not private') } - temporary = `${this.path}.${process.pid}.${randomUUID()}.tmp` - await writeFile(temporary, JSON.stringify({ schemaVersion: 1, maxTerminals: maximum }), { - flag: 'wx', - mode: 0o600 - }) - if (!(await renameFileWithWindowsRetryAsync(temporary, this.path, isCurrent))) { - throw new Error('Terminal host changed') + const temporary = `${path}.${process.pid}.${randomUUID()}.tmp` + let staging: Promise = Promise.resolve() + try { + await operation.wait(() => { + staging = writeFile( + temporary, + JSON.stringify({ schemaVersion: 1, maxTerminals: maximum }), + { + flag: 'wx', + mode: 0o600 + } + ) + return staging + }) + const replaced = await operation.wait(() => { + const rename = renameFileWithWindowsRetryAsync(temporary, path, operation.isCurrent) + staging = rename + return rename + }) + if (!replaced) { + throw new Error('Terminal host changed') + } + // Drain pre-replacement observations without evicting their raw I/O. + await operation.wait(() => this.saved().catch(() => null)) + const saved = await operation.wait(() => this.saved()) + return this.observedStatus(saved, systemPtyLimit, daemonNonce) + } finally { + // A late staging write must settle before removal can consume its temporary file. + void staging + .catch(() => undefined) + .then(() => rm(temporary, { force: true })) + .catch(() => undefined) } - } finally { - if (temporary) { - await rm(temporary, { force: true }).catch(() => undefined) - } - this.writing = false - } + }) } } diff --git a/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx b/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx index 1e54062297d5..fe0bbe3d074f 100644 --- a/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx +++ b/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx @@ -6,27 +6,36 @@ import { TerminalLimitSetting } from './TerminalLimitSetting' import { readTerminalLimit, saveTerminalLimit } from './terminal-limit-transport' import type { SettingsHostScope } from './settings-host-scope' import type { TerminalLimitStatus } from '../../../../shared/terminal-limit-policy' +import { useAppStore } from '@/store' +import { i18n } from '@/i18n/i18n' +import { getTerminalAdvancedSearchEntries } from './terminal-advanced-platform-search' +import { matchesSettingsSearch } from './settings-search' +import type { RuntimeStatus } from '../../../../shared/runtime-types' import { advanceRuntimeEnvironmentConnectionGeneration } from '@/store/slices/runtime-status-connection-generation' vi.mock('./terminal-limit-transport', () => ({ readTerminalLimit: vi.fn(), saveTerminalLimit: vi.fn() })) -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string, values?: Record) => - fallback.replace('{{value}}', String(values?.value)) -})) -vi.mock('@/store', () => ({ - useAppStore: (select: (state: unknown) => unknown) => select({ runtimeEnvironments: [] }) -})) +const search = vi.hoisted(() => ({ query: '' })) +vi.mock('sonner', () => ({ toast: { warning: vi.fn(), dismiss: vi.fn() } })) +vi.mock('@/store', async () => { + const { useStore } = await import('zustand') + const { createRuntimeStatusTestStore } = + await import('@/store/slices/runtime-status.test-fixture') + const store = createRuntimeStatusTestStore() + return { + useAppStore: Object.assign( + (select: (state: unknown) => unknown) => + useStore(store, (state) => select({ ...state, settingsSearchQuery: search.query })), + store + ) + } +}) vi.mock('@/store/host-catalog-fencing', () => ({ captureHostIdentityFence: () => ({}), isHostIdentityFenceCurrent: () => true })) -vi.mock('./SearchableSetting', () => ({ - SearchableSetting: ({ children }: { children: React.ReactNode }) => children -})) - const local: SettingsHostScope = { target: { kind: 'local' }, available: true } const base: TerminalLimitStatus = { maxTerminals: 256, @@ -37,7 +46,10 @@ const base: TerminalLimitStatus = { } let container: HTMLDivElement let root: Root -beforeEach(() => { +beforeEach(async () => { + await i18n.changeLanguage('en') + search.query = '' + useAppStore.setState({ runtimeStatusByEnvironmentId: new Map() }) globalThis.IS_REACT_ACT_ENVIRONMENT = true container = document.createElement('div') document.body.appendChild(container) @@ -115,6 +127,7 @@ it('discards a late answer and draft when switching execution hosts', async () = systemPtyLimit: 256, daemonNonce: 'daemon-b' }) + publish('server', true, 1) await render({ target: { kind: 'environment', environmentId: 'server' }, available: true }) await act(async () => complete?.(base)) expect(input().value).toBe('128') @@ -159,8 +172,71 @@ it('keeps confirmed environment values above the bound and leaves old daemons un expect(input().disabled).toBe(true) expect(container.textContent).toContain('environment') vi.mocked(readTerminalLimit).mockResolvedValue(null) + publish('old', true, 1) await render({ target: { kind: 'environment', environmentId: 'old' }, available: true }) expect(input().value).toBe('') expect(input().disabled).toBe(true) expect(container.textContent).toContain('does not support') }) + +const runtime: RuntimeStatus = { + runtimeId: 'same-runtime', + rendererGraphEpoch: 0, + graphStatus: 'ready', + authoritativeWindowId: null, + liveTabCount: 0, + liveLeafCount: 0 +} +function publish(id: string, live: boolean, checkedAt: number): void { + useAppStore.getState().setRuntimeEnvironmentStatus(id, { + status: live ? runtime : null, + checkedAt, + snapshot: { + environmentId: id, + pairingRevision: 1, + sequence: checkedAt, + checkedAt, + status: runtime, + verification: live ? 'verified' : 'unavailable', + transport: live ? 'ready' : 'disconnected' + } + }) +} + +it('disables on contact loss and reads again on a real same-runtime recovery publication', async () => { + publish('server', true, 1) + const scope: SettingsHostScope = { + target: { kind: 'environment', environmentId: 'server' }, + available: true + } + await render(scope) + await type('384') + const generation = useAppStore + .getState() + .runtimeStatusByEnvironmentId.get('server')?.connectionGeneration + await act(async () => publish('server', false, 2)) + expect(input().disabled).toBe(true) + expect(input().value).toBe('') + expect(container.textContent).toContain('disconnected') + vi.mocked(readTerminalLimit).mockResolvedValue({ ...base, maxTerminals: 64 }) + await act(async () => publish('server', true, 3)) + expect( + useAppStore.getState().runtimeStatusByEnvironmentId.get('server')?.connectionGeneration + ).toBe(generation) + expect(input().disabled).toBe(false) + expect(input().value).toBe('64') + expect(readTerminalLimit).toHaveBeenCalledTimes(2) +}) + +it('finds localized capacity in both the catalog and the rendered row filter', async () => { + await i18n.changeLanguage('fr') + search.query = 'capacité' + expect( + getTerminalAdvancedSearchEntries().some((entry) => matchesSettingsSearch(search.query, entry)) + ).toBe(true) + await render() + expect(input().value).toBe('256') + search.query = 'aucun-résultat' + await render() + expect(container.querySelector('input')).toBeNull() +}) diff --git a/src/renderer/src/components/settings/TerminalLimitSetting.tsx b/src/renderer/src/components/settings/TerminalLimitSetting.tsx index 4c0dffadf0c2..acf8db1330fd 100644 --- a/src/renderer/src/components/settings/TerminalLimitSetting.tsx +++ b/src/renderer/src/components/settings/TerminalLimitSetting.tsx @@ -18,6 +18,8 @@ import { } from '@/store/host-catalog-fencing' import type { HostRoute } from '@/runtime/runtime-client-target' import { translate } from '@/i18n/i18n' +import { runtimeHostContactForEntry } from '../../../../shared/runtime-host-contact' +import { getTerminalLimitSearchKeywords } from './terminal-advanced-platform-search' export function TerminalLimitSetting({ scope }: { scope: SettingsHostScope }): React.JSX.Element { const environmentId = scope.target.kind === 'environment' ? scope.target.environmentId : null @@ -25,12 +27,21 @@ export function TerminalLimitSetting({ scope }: { scope: SettingsHostScope }): R const host = state.runtimeEnvironments.find((item) => item.id === environmentId) const pairing = host?.pairingRevision ?? host?.createdAt ?? 0 const connection = environmentId ? getRuntimeEnvironmentConnectionGeneration(environmentId) : 0 - return `${pairing}:${connection}` + const contactEpoch = + state.runtimeStatusByEnvironmentId.get(environmentId ?? '')?.hostContactEpoch ?? 0 + return `${pairing}:${connection}:${contactEpoch}` }) + const contacted = useAppStore( + (state) => + environmentId === null || + runtimeHostContactForEntry(state.runtimeStatusByEnvironmentId.get(environmentId)).verdict === + 'live' + ) + const available = scope.available && contacted return ( ) } @@ -136,17 +147,19 @@ function TerminalLimitField({ scope }: { scope: SettingsHostScope }): React.JSX. 'settings.terminal.limit.disconnected', 'This host is disconnected. Reconnect to view or change its terminal limit.' ) - : status === null || (status?.editable === false && status.source !== 'environment') + : status === null ? translate( 'settings.terminal.limit.unsupported', 'This host’s terminal service does not support changing this limit yet.' ) - : status?.source === 'environment' - ? translate( - 'settings.terminal.limit.environment', - 'This Orca instance has a terminal limit set by its environment. Remove the override on this host to edit it here.' - ) - : null + : status?.editable === false && status.source !== 'environment' + ? translate('settings.terminal.limit.unknown', 'Unavailable') + : status?.source === 'environment' + ? translate( + 'settings.terminal.limit.environment', + 'This Orca instance has a terminal limit set by its environment. Remove the override on this host to edit it here.' + ) + : null const label = translate('settings.terminal.limit.label', 'Maximum running terminals') return ( [ { title: translate('settings.terminal.limit.label', 'Maximum running terminals'), @@ -9,7 +19,7 @@ export const getTerminalAdvancedSearchEntries = createLocalizedCatalog(() => [ 'settings.terminal.limit.description', 'Limits your running terminals across projects on this host.' ), - keywords: ['terminal', 'limit', 'maximum', 'pty', 'capacity'] + keywords: getTerminalLimitSearchKeywords() }, { title: translate('auto.components.settings.terminal.search.7674e758e1', 'Scrollback Rows'), diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 9392092a3ce9..de4da428119e 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -272,7 +272,13 @@ "environment": "This Orca instance has a terminal limit set by its environment. Remove the override on this host to edit it here.", "failed": "Couldn’t confirm the terminal limit. Try again.", "retry": "Retry", - "unit": "terminals" + "unit": "terminals", + "search": { + "limit": "limit", + "maximum": "maximum", + "pty": "pty", + "capacity": "capacity" + } } }, "appearance": { diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 97a77030186c..f8eb8fe7db8c 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -95,7 +95,13 @@ "environment": "El entorno establece el límite de terminales de esta instancia de Orca. Elimina esa configuración en este equipo para editarlo aquí.", "failed": "No se pudo confirmar el límite de terminales. Inténtalo de nuevo.", "retry": "Reintentar", - "unit": "terminales" + "unit": "terminales", + "search": { + "limit": "límite", + "maximum": "máximo", + "pty": "pty", + "capacity": "capacidad" + } } }, "appearance": { diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index d94fd9f97d7d..71b669037945 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -199,7 +199,13 @@ "environment": "L’environnement définit la limite de terminaux de cette instance d’Orca. Supprimez cette configuration sur cet hôte pour la modifier ici.", "failed": "Impossible de confirmer la limite de terminaux. Réessayez.", "retry": "Réessayer", - "unit": "terminaux" + "unit": "terminaux", + "search": { + "limit": "limite", + "maximum": "maximum", + "pty": "pty", + "capacity": "capacité" + } } }, "appearance": { diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 84fddad1530d..c3fc5aae3993 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -95,7 +95,13 @@ "environment": "このOrcaインスタンスのターミナル上限は環境変数で設定されています。ここで編集するには、このホストの環境変数による設定を削除してください。", "failed": "ターミナルの上限を確認できませんでした。もう一度お試しください。", "retry": "再試行", - "unit": "ターミナル" + "unit": "ターミナル", + "search": { + "limit": "上限", + "maximum": "最大", + "pty": "pty", + "capacity": "容量" + } } }, "appearance": { diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index fdd814bc0be3..46ddff92c923 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -95,7 +95,13 @@ "environment": "이 Orca 인스턴스의 터미널 한도는 환경 변수로 설정되어 있습니다. 여기서 편집하려면 이 호스트에서 해당 설정을 제거하세요.", "failed": "터미널 한도를 확인하지 못했습니다. 다시 시도하세요.", "retry": "다시 시도", - "unit": "터미널" + "unit": "터미널", + "search": { + "limit": "제한", + "maximum": "최대", + "pty": "pty", + "capacity": "용량" + } } }, "appearance": { diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 6335e8e580b7..d65c17f9e59a 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -95,7 +95,13 @@ "environment": "此 Orca 实例的终端上限由环境变量设置。要在此编辑,请先移除此主机上的相应环境设置。", "failed": "无法确认终端上限。请重试。", "retry": "重试", - "unit": "个终端" + "unit": "个终端", + "search": { + "limit": "限制", + "maximum": "最大值", + "pty": "pty", + "capacity": "容量" + } } }, "appearance": { From 51c0a9d145d44b058dde996b88c27046d93b3394 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 21 Oct 2026 11:45:06 -0700 Subject: [PATCH 03/15] Fix truncated zero-size system file reads --- .../node-bounded-file-reader-sync.test.ts | 14 +++++++++++ src/shared/node-bounded-file-reader.test.ts | 25 ++++++++++++++++++- src/shared/node-bounded-file-reader.ts | 6 +++-- 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/shared/node-bounded-file-reader-sync.test.ts b/src/shared/node-bounded-file-reader-sync.test.ts index 02a7d5c60dd9..934160977a60 100644 --- a/src/shared/node-bounded-file-reader-sync.test.ts +++ b/src/shared/node-bounded-file-reader-sync.test.ts @@ -41,6 +41,20 @@ describe('readNodeFileSyncWithinLimit', () => { expect(() => readNodeFileSyncWithinLimit(path, 1024)).toThrow(NodeFileReadTooLargeError) }) + + it('reads the full zero-size sysctl value when later reads return EOF', () => { + const path = createTempFile('4096\n') + const originalStat = fs.fstatSync + vi.spyOn(fs, 'fstatSync').mockImplementation((...args) => + Object.assign(originalStat(...args), { size: 0 }) + ) + const originalRead = fs.readSync + const read = vi + .spyOn(fs, 'readSync') + .mockImplementation((...args) => (read.mock.calls.length === 1 ? originalRead(...args) : 0)) + + expect(readNodeFileSyncWithinLimit(path, 1024).buffer.toString('utf8')).toBe('4096\n') + }) }) describe('regular file growth evidence', () => { diff --git a/src/shared/node-bounded-file-reader.test.ts b/src/shared/node-bounded-file-reader.test.ts index a01d8956d50f..0b276741346f 100644 --- a/src/shared/node-bounded-file-reader.test.ts +++ b/src/shared/node-bounded-file-reader.test.ts @@ -11,14 +11,24 @@ type FileHandleOptions = { initialSize?: number readError?: Error statError?: Error + firstReadOnly?: boolean } -function createFileHandle({ content, initialSize, readError, statError }: FileHandleOptions) { +function createFileHandle({ + content, + initialSize, + readError, + statError, + firstReadOnly +}: FileHandleOptions) { const close = vi.fn().mockResolvedValue(undefined) const read = vi.fn(async (target: Buffer, offset: number, length: number, position: number) => { if (readError) { throw readError } + if (firstReadOnly && position > 0) { + return { bytesRead: 0, buffer: target } + } const bytesRead = Math.min(length, Math.max(0, content.byteLength - position)) content.copy(target, offset, position, position + bytesRead) return { bytesRead, buffer: target } @@ -75,6 +85,19 @@ describe('readNodeFileWithinLimit', () => { expect(handle.close).toHaveBeenCalledOnce() }) + it('reads the full sysctl value when later offsets return EOF', async () => { + const handle = createFileHandle({ + content: Buffer.from('4096\n'), + initialSize: 0, + firstReadOnly: true + }) + openMock.mockResolvedValue(handle) + + const result = await readNodeFileWithinLimit('/proc/sys/kernel/pty/max', 1024) + + expect(result.buffer.toString('utf8')).toBe('4096\n') + }) + it('rejects growth beyond the limit without allocating the oversized content', async () => { const handle = createFileHandle({ content: Buffer.from('growth'), initialSize: 3 }) openMock.mockResolvedValue(handle) diff --git a/src/shared/node-bounded-file-reader.ts b/src/shared/node-bounded-file-reader.ts index 088a07fa2e56..482b325a4841 100644 --- a/src/shared/node-bounded-file-reader.ts +++ b/src/shared/node-bounded-file-reader.ts @@ -102,7 +102,8 @@ export async function readNodeFileHandleWithinLimit( } validateSize(stats.size, maxBytes) - let buffer = Buffer.allocUnsafe(stats.size) + // Sysctl files report zero size and may return EOF after a partial first read. + let buffer = Buffer.allocUnsafe(stats.size || Math.min(MIN_GROWTH_BYTES, maxBytes)) let offset = 0 while (true) { options.signal?.throwIfAborted() @@ -162,7 +163,8 @@ export function readNodeFileSyncWithinLimit( } validateSize(stats.size, maxBytes) - let buffer = Buffer.allocUnsafe(stats.size) + // Sysctl files report zero size and may return EOF after a partial first read. + let buffer = Buffer.allocUnsafe(stats.size || Math.min(MIN_GROWTH_BYTES, maxBytes)) let offset = 0 while (true) { while (offset < buffer.length) { From 8710e4871c6e4d1ca156ccb2a80947a974808b85 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:55:27 -0700 Subject: [PATCH 04/15] Load actual filesystem fixtures once per test module --- src/main/daemon/daemon-terminal-limit.test.ts | 3 ++- src/main/daemon/host-terminal-policy.test.ts | 6 ++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/daemon/daemon-terminal-limit.test.ts b/src/main/daemon/daemon-terminal-limit.test.ts index 7a7fefbdc974..2c6b48409cd7 100644 --- a/src/main/daemon/daemon-terminal-limit.test.ts +++ b/src/main/daemon/daemon-terminal-limit.test.ts @@ -19,6 +19,8 @@ vi.mock('node:fs/promises', async (original) => { return { ...fs, writeFile: vi.fn(fs.writeFile), rm: vi.fn(fs.rm) } }) +const fs = await vi.importActual('node:fs/promises') + let server: DaemonServer | undefined let client: DaemonClient | undefined let directory: string | undefined @@ -114,7 +116,6 @@ it('fences an actual pending save when the server shuts down before replacement' const staging = new Promise((done) => { started = done }) - const fs = await vi.importActual('node:fs/promises') vi.mocked(writeFile).mockImplementationOnce(async (...args) => { started() await held diff --git a/src/main/daemon/host-terminal-policy.test.ts b/src/main/daemon/host-terminal-policy.test.ts index a68c78163cfd..575f2ea3368e 100644 --- a/src/main/daemon/host-terminal-policy.test.ts +++ b/src/main/daemon/host-terminal-policy.test.ts @@ -14,6 +14,8 @@ vi.mock('node:fs/promises', async (original) => { return { ...fs, writeFile: vi.fn(fs.writeFile), rename: vi.fn(fs.rename), rm: vi.fn(fs.rm) } }) +const fs = await vi.importActual('node:fs/promises') + function deferred() { let resolve!: (value: T) => void const promise = new Promise((done) => { @@ -33,7 +35,6 @@ const system = () => new SystemPtyLimit(async () => 511) const directories: string[] = [] afterEach(async () => { vi.useRealTimers() - const fs = await vi.importActual('node:fs/promises') await Promise.all( directories.splice(0).map((path) => fs.rm(path, { recursive: true, force: true })) ) @@ -144,7 +145,6 @@ describe('host terminal policy', () => { const policy = new HostTerminalPolicy(path, {}, system(), read) const admission = policy.admissionMaximum() const replaced = deferred() - const fs = await vi.importActual('node:fs/promises') vi.mocked(rename).mockImplementationOnce(async (...args) => { await fs.rename(...args) replaced.resolve() @@ -160,7 +160,6 @@ describe('host terminal policy', () => { it('expires staging without a late rename or orphan, and permits retry while cleanup stalls', async () => { const path = join(await home(), 'policy.json') - const fs = await vi.importActual('node:fs/promises') const started = deferred() const release = deferred() const staged = deferred() @@ -208,7 +207,6 @@ describe('host terminal policy', () => { 'keeps an expired issued rename unconfirmed: %s', async (outcome) => { const path = join(await home(), 'policy.json') - const fs = await vi.importActual('node:fs/promises') const started = deferred() const release = deferred() const cleaned = deferred() From 42e45336498cfa5647459ece705ae63fc27a52c2 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:54:14 -0700 Subject: [PATCH 05/15] Preserve slept terminal ownership through capacity retries --- .../sleep/register-worktree-sleep-handlers.ts | 7 +- .../worktrees/sleep/resume-slept-pane.test.ts | 48 ++++ ...ssion-tabs-windowless-sleep-resume.spec.ts | 89 ++++++++ .../managed-workspace-operations.ts | 4 +- .../workspace-sleep-own-worktree.test.ts | 32 +++ .../workspaces/workspace-sleep-runtime.ts | 13 +- src/preload/api/worktree-api.ts | 5 +- src/preload/api/worktrees-bridge.ts | 3 +- ...-connection-hidden-sleeping-resume.spec.ts | 14 ++ ...ty-connection-spawn-deferred-sleep.test.ts | 215 ++++++++++++++++++ .../deferred-cold-restore-and-snapshot.ts | 10 +- .../pty-connection/fresh-spawn-start.ts | 35 ++- .../pty-connection/main-resumed-sleep-pane.ts | 50 +++- .../pty-connection/spawn-deferred-sleep.ts | 27 ++- 14 files changed, 506 insertions(+), 46 deletions(-) create mode 100644 src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts diff --git a/src/main/ipc/worktrees/sleep/register-worktree-sleep-handlers.ts b/src/main/ipc/worktrees/sleep/register-worktree-sleep-handlers.ts index 98c4425414dc..fea90d1d36c6 100644 --- a/src/main/ipc/worktrees/sleep/register-worktree-sleep-handlers.ts +++ b/src/main/ipc/worktrees/sleep/register-worktree-sleep-handlers.ts @@ -28,11 +28,14 @@ export function registerWorktreeSleepHandlers(context: WorktreeIpcContext): void context.runtime.noteWorkspaceReopened(worktreeId) ) // Main resumes the session before the renderer attaches its spawn. - ipcMain.handle('worktrees:resumeSleptPane', (_event, pane: unknown) => { + ipcMain.handle('worktrees:resumeSleptPane', (_event, pane: unknown, automatic: unknown) => { if (!isRestoredPane(pane)) { throw new Error('invalid_pane') } - return context.runtime.resumeSleptPane(pane) + if (automatic !== undefined && typeof automatic !== 'boolean') { + throw new Error('invalid_automatic') + } + return context.runtime.resumeSleptPane(pane, automatic) }) ipcMain.handle( 'worktrees:retireStrandedSleepRecord', diff --git a/src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts b/src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts new file mode 100644 index 000000000000..d43c49af336e --- /dev/null +++ b/src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts @@ -0,0 +1,48 @@ +import { beforeEach, expect, it, vi } from 'vitest' +import type { WorktreeIpcContext } from '../worktree-ipc-context' + +const { handlers } = vi.hoisted(() => ({ + handlers: new Map unknown>() +})) +vi.mock('electron', () => ({ + ipcMain: { + handle: (name: string, handler: (...args: unknown[]) => unknown) => handlers.set(name, handler) + }, + ipcRenderer: { + invoke: async (name: string, ...args: unknown[]) => handlers.get(name)?.({}, ...args) + } +})) +import { registerWorktreeSleepHandlers } from './register-worktree-sleep-handlers' +import { worktreesApi } from '../../../../preload/api/worktrees-bridge' + +beforeEach(() => handlers.clear()) + +it('validates the bundled bridge argument before the runtime receives any trigger authority', async () => { + const resumeSleptPane = vi.fn(async () => true) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: registration reads only runtime; this test invokes only resumeSleptPane. + registerWorktreeSleepHandlers({ runtime: { resumeSleptPane } } as unknown as WorktreeIpcContext) + const pane = { worktreeId: 'wt', tabId: 'tab', leafId: 'leaf' } + await expect(worktreesApi.resumeSleptPane(pane)).resolves.toBe(true) + for (const automatic of [undefined, false, true]) { + await expect(worktreesApi.resumeSleptPane(pane, automatic)).resolves.toBe(true) + expect(resumeSleptPane).toHaveBeenLastCalledWith(pane, automatic) + } + resumeSleptPane.mockClear() + for (const invalid of [ + null, + 0, + 1, + 'true', + [], + {}, + { automatic: true, targetsHost: true, targetGroupId: 'g' } + ]) { + await expect( + Reflect.apply(worktreesApi.resumeSleptPane, null, [pane, invalid]) + ).rejects.toThrow('invalid_automatic') + } + await expect( + Reflect.apply(worktreesApi.resumeSleptPane, null, [{ tabId: 'tab' }, true]) + ).rejects.toThrow('invalid_pane') + expect(resumeSleptPane).not.toHaveBeenCalled() +}) diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-windowless-sleep-resume.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-windowless-sleep-resume.spec.ts index 5f106b187a36..b186de35afe0 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-windowless-sleep-resume.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-windowless-sleep-resume.spec.ts @@ -1,3 +1,10 @@ +import { spawnWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' +import { + createSpawnAdmissionState, + DEFAULT_SPAWN_ADMISSION_LIMITS, + decideSpawnAdmission, + resolveSpawnCharge +} from '../../../shared/host-spawn-admission' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' import { describe, expect, it, vi } from 'vitest' import { OrcaRuntimeService, electronMocks } from '../orca-runtime-test-mocks.spec' @@ -284,6 +291,88 @@ describe('opening a workspace-slept running agent on a host with no window', () describe("the window's open of a slept pane (worktrees:resumeSleptPane)", () => { const pane = { worktreeId: TEST_WORKTREE_ID, tabId: 'host-tab', leafId: HEADLESS_LEAF_ID } + it('keeps the original provider and current retry intent through a refused main start', async () => { + const fixture = makeWorkingSleepStore() + const { runtime, spawn, opened } = openPane(fixture.runtimeStore, 'openable', { + withWindow: true, + tap: false + }) + await opened + const limits = DEFAULT_SPAWN_ADMISSION_LIMITS + const state = createSpawnAdmissionState(limits, 0) + state.liveAutomatic = limits.maxLiveAutomatic + spawn.mockImplementation(async (...args: unknown[]) => { + const request = args[0] + if (typeof request !== 'object' || request === null || !('spawnIntent' in request)) { + throw new Error('missing intent') + } + const declaredIntent = request.spawnIntent + if (declaredIntent !== 'user-resume' && declaredIntent !== 'automatic-restore') { + throw new Error('wrong intent') + } + const release = await runtime.acquireWorktreeTerminalSpawn( + spawnWorktreeTarget(TEST_WORKTREE_ID, null), + { + refuseSleptWorktree: + 'refuseSleptWorktree' in request && request.refuseSleptWorktree === true + } + ) + try { + const facts = { + clientId: 'resume-test', + declaredIntent, + hasAgentSessionClaim: false, + hasHistorySeed: false, + deadlineAt: 1000 + } + const decision = decideSpawnAdmission({ + state, + facts, + charge: resolveSpawnCharge(state, facts, limits, 0), + pressure: 'ok', + mode: { kind: 'normal' }, + limits, + now: 0 + }) + if (spawn.mock.calls.length === 1 || decision.kind === 'defer') { + throw new Error('terminal_spawn_deferred:live_cap') + } + return { id: 'persisted-pty' } + } finally { + release() + } + }) + await runtime.sleepTerminalsForWorktree(`id:${TEST_WORKTREE_ID}`) + await expect(runtime.resumeSleptPane(pane)).rejects.toThrow( + 'terminal_spawn_deferred:live_cap' + ) + expect(spawn).toHaveBeenLastCalledWith( + expect.objectContaining({ spawnIntent: 'user-resume' }) + ) + await expect(runtime.resumeSleptPane(pane, true)).rejects.toThrow( + 'terminal_spawn_deferred:live_cap' + ) + expect(spawn).toHaveBeenLastCalledWith( + expect.objectContaining({ + spawnIntent: 'automatic-restore', + refuseSleptWorktree: true + }) + ) + await runtime.sleepTerminalsForWorktree(`id:${TEST_WORKTREE_ID}`) + await expect(runtime.resumeSleptPane(pane, true)).rejects.toThrow( + 'worktree_terminals_sleeping' + ) + expect(spawn).toHaveBeenCalledTimes(3) + await expect(runtime.resumeSleptPane(pane, false)).resolves.toBe(true) + for (let call = 0; call < 4; call += 1) { + expect(spawnedCommand(spawn, call)).toContain('provider-session-1') + expect(spawnedCommand(spawn, call)).not.toContain('--dangerously-skip-permissions') + } + expect(spawn).toHaveBeenLastCalledWith( + expect.objectContaining({ spawnIntent: 'user-resume' }) + ) + }) + it('resumes once; a second open after it finished attaches to the same terminal', async () => { const fixture = makeWorkingSleepStore() const { runtime, spawn, opened } = openPane(fixture.runtimeStore, 'openable', { diff --git a/src/main/runtime/workspaces/managed-workspace-operations.ts b/src/main/runtime/workspaces/managed-workspace-operations.ts index 73355ae15898..42f72e52516c 100644 --- a/src/main/runtime/workspaces/managed-workspace-operations.ts +++ b/src/main/runtime/workspaces/managed-workspace-operations.ts @@ -262,8 +262,8 @@ export abstract class OrcaRuntimeWithListManagedWorktrees extends OrcaRuntimeWit } /** The window opened a slept pane; main resumes it and the window attaches. */ - resumeSleptPane(pane: RestoredPane): Promise { - return this.workspaceSleep.resumePane(pane) + resumeSleptPane(pane: RestoredPane, automatic?: boolean): Promise { + return this.workspaceSleep.resumePane(pane, automatic) } /** The window reopened a slept agent whose tab is gone in a fresh tab; this record is spent. */ diff --git a/src/main/runtime/workspaces/workspace-sleep-own-worktree.test.ts b/src/main/runtime/workspaces/workspace-sleep-own-worktree.test.ts index 22bda27e4ac6..98a9b79d093b 100644 --- a/src/main/runtime/workspaces/workspace-sleep-own-worktree.test.ts +++ b/src/main/runtime/workspaces/workspace-sleep-own-worktree.test.ts @@ -80,3 +80,35 @@ describe("a phone's or the CLI's sleep", () => { expect(failedNotices(notices)).toEqual([]) }) }) + +it.each([true, false])( + 'an automatic=%s retry preserves Sleep/VM suspension intent', + async (automatic) => { + let finishStop: (result: RuntimeWorktreeTerminalSleepResult) => void = () => {} + const stopped = new Promise((resolve) => { + finishStop = resolve + }) + const suspendVm = vi.fn(async () => {}) + const ensureRestoredPaneStarted = vi.fn(async () => null) + const stop = vi.fn(() => stopped) + const { sleep } = coordinator({ + workspaceLifecycle: null, + sleepTerminalsForWorktree: stop, + ensureRestoredPaneStarted, + workspaceSleepPlatform: { + callEnvironment: async () => { + throw new Error('unused') + }, + suspendVm + } + }) + const sleeping = sleep.sleepOwnWorktree(WORKTREE, {}) + await vi.waitFor(() => expect(stop).toHaveBeenCalled()) + const pane = { worktreeId: WORKTREE, tabId: 'tab', leafId: 'leaf' } + await sleep.resumePane(pane, automatic) + finishStop(verified) + await sleeping + expect(ensureRestoredPaneStarted).toHaveBeenCalledWith(pane, { automatic }) + expect(suspendVm).toHaveBeenCalledTimes(automatic ? 1 : 0) + } +) diff --git a/src/main/runtime/workspaces/workspace-sleep-runtime.ts b/src/main/runtime/workspaces/workspace-sleep-runtime.ts index c1a3ecf63463..e3c6f5c1f845 100644 --- a/src/main/runtime/workspaces/workspace-sleep-runtime.ts +++ b/src/main/runtime/workspaces/workspace-sleep-runtime.ts @@ -43,7 +43,10 @@ export type WorkspaceSleepRuntime = { notifyWorkspaceSleep: (notice: WorkspaceSleepNotice) => void wakeRecordsForWorktree: (worktreeId: string) => SleepingAgentSessionRecord[] resumeSleptWorkspaceAgents: (worktreeId: string) => Promise - ensureRestoredPaneStarted: (pane: RestoredPane) => Promise + ensureRestoredPaneStarted: ( + pane: RestoredPane, + trigger?: { automatic?: boolean } + ) => Promise /** The window's wake of its own completed-agent hibernation, which main does not hold. */ wakeWindowHibernatedAgents: (worktreeId: string) => void } @@ -133,11 +136,13 @@ export class WorkspaceSleepCoordinator { } /** A slept pane was opened: main resumes it, queued like any wake, and the opener attaches. */ - resumePane(pane: RestoredPane): Promise { - this.noteReopened(pane.worktreeId) + resumePane(pane: RestoredPane, automatic = false): Promise { + if (!automatic) { + this.noteReopened(pane.worktreeId) + } return queueTerminalWorkspaceCommand(this.runtime, `id:${pane.worktreeId}`, { kind: 'wake', - run: async () => (await this.runtime.ensureRestoredPaneStarted(pane)) !== null + run: async () => (await this.runtime.ensureRestoredPaneStarted(pane, { automatic })) !== null }) } diff --git a/src/preload/api/worktree-api.ts b/src/preload/api/worktree-api.ts index 6ca23b4f0b3d..2aac77686536 100644 --- a/src/preload/api/worktree-api.ts +++ b/src/preload/api/worktree-api.ts @@ -88,7 +88,10 @@ export type WorktreeApi = { sleep: (request: WorkspaceSleepRequest) => Promise sleepReopened: (worktreeId: string) => Promise /** True once running, so the renderer's subsequent spawn reattaches. */ - resumeSleptPane: (pane: { worktreeId: string; tabId: string; leafId: string }) => Promise + resumeSleptPane: ( + pane: { worktreeId: string; tabId: string; leafId: string }, + automatic?: boolean + ) => Promise /** Drops main's workspace-sleep record only while no tab holds its pane. */ retireStrandedSleepRecord: (args: { worktreeId: string; paneKey: string }) => Promise remove: (args: { diff --git a/src/preload/api/worktrees-bridge.ts b/src/preload/api/worktrees-bridge.ts index 44692d18209f..feb3f4a668aa 100644 --- a/src/preload/api/worktrees-bridge.ts +++ b/src/preload/api/worktrees-bridge.ts @@ -44,7 +44,8 @@ export const worktreesApi = { sleep: (request) => ipcRenderer.invoke('worktrees:sleep', request), sleepReopened: (worktreeId) => ipcRenderer.invoke('worktrees:sleepReopened', worktreeId), - resumeSleptPane: (pane) => ipcRenderer.invoke('worktrees:resumeSleptPane', pane), + resumeSleptPane: (pane, automatic) => + ipcRenderer.invoke('worktrees:resumeSleptPane', pane, automatic), retireStrandedSleepRecord: (args) => ipcRenderer.invoke('worktrees:retireStrandedSleepRecord', args), diff --git a/src/renderer/src/components/terminal-pane/pty-connection-hidden-sleeping-resume.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection-hidden-sleeping-resume.spec.ts index a0346d86995c..8d939d727a2e 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-hidden-sleeping-resume.spec.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-hidden-sleeping-resume.spec.ts @@ -229,6 +229,20 @@ export function registerPtyConnectionHiddenSleepingResumeTests(): void { expect(resumeCommands(transport)[0]).toContain("'resume' 'codex-session-1'") }) + it('keeps an initial hidden workspace-sleep wake explicit', async () => { + seedSleepingPane(null, { origin: 'worktree-sleep' }) + const resumeSleptPane = vi.fn(async () => true) + window.api.worktrees = { ...window.api.worktrees, resumeSleptPane } + const { requestSleepingAgentWakeOnMount } = await import('@/lib/sleeping-agent-wake-requests') + requestSleepingAgentWakeOnMount('wt-1', ['tab-1']) + connectHiddenPane(null) + await flushAsyncTicks(20) + expect(resumeSleptPane).toHaveBeenCalledWith( + { worktreeId: 'wt-1', tabId: 'tab-1', leafId: LEAF_2 }, + undefined + ) + }) + it('resumes a held hidden pane immediately on a phone wake', async () => { seedSleepingPane(DEAD_SESSION_ID) setHostLiveness(false) diff --git a/src/renderer/src/components/terminal-pane/pty-connection-spawn-deferred-sleep.test.ts b/src/renderer/src/components/terminal-pane/pty-connection-spawn-deferred-sleep.test.ts index 135cb543f555..2f9e539b4323 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-spawn-deferred-sleep.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-spawn-deferred-sleep.test.ts @@ -1,3 +1,4 @@ +import type { ConnectPanePtySession } from './pty-connection/connect-pane-pty-session' import type * as React from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { makePaneKey } from '../../../../shared/stable-pane-id' @@ -227,6 +228,220 @@ describe('connectPanePty: a restore the host kept asleep', () => { await restoreTerminalTestGlobals() }) + it('retains the main owner through wrapped refusal, hidden retries and explicit attachment', async () => { + const { connectPanePty } = await import('./pty-connection') + const { getPaneSpawnDeferral } = await import('@/lib/pane-spawn-deferral-registry') + const pane = createPane(1) + const paneKey = makePaneKey('tab-1', pane.leafId) + const record = { + paneKey, + tabId: 'tab-1', + worktreeId: 'wt-1', + agent: 'claude', + providerSession: RESUME, + prompt: '', + state: 'working', + capturedAt: 1, + updatedAt: 1, + origin: 'worktree-sleep' + } + mockStoreState.sleepingAgentSessionsByPaneKey[paneKey] = record + mockStoreState.agentStatusByPaneKey = {} + mockStoreState.tabsByWorktree['wt-1'] = [{ id: 'tab-1', ptyId: null }] + mockStoreState.terminalLayoutsByTabId['tab-1'] = { + root: { type: 'leaf', leafId: pane.leafId }, + activeLeafId: pane.leafId, + expandedLeafId: null, + ptyIdsByLeafId: {} + } + const mainResume = vi.fn(async (_pane: unknown, _automatic?: boolean): Promise => { + throw new Error( + "Error invoking remote method 'worktrees:resumeSleptPane': Error: terminal_spawn_deferred:live_cap" + ) + }) + window.api.worktrees = { ...window.api.worktrees, resumeSleptPane: mainResume } + const transport = createMockTransport() + transport.connect.mockResolvedValue('main-pty') + transportFactoryQueue.push(transport) + const onDeferredCwdSpawnFailed = vi.fn() + const deps = createDeps({ onDeferredCwdSpawnFailed }) + const binding = connectPanePty(...mockPanePtyArgs(pane, createManager(1), deps)) + await flushAsyncTicks(30) + const owner = { worktreeId: 'wt-1', tabId: 'tab-1', leafId: pane.leafId } + expect(mainResume).toHaveBeenLastCalledWith(owner, undefined) + expect(transport.connect).not.toHaveBeenCalled() + expect(getPaneSpawnDeferral(paneKey)?.reason).toBe('live_cap') + expect(onDeferredCwdSpawnFailed).toHaveBeenCalledOnce() + expect(deps.onShowSessionRestoredBanner).not.toHaveBeenCalled() + + deps.isVisibleRef.current = false + await expect(drain.queued.get(paneKey)?.()).resolves.toBe(false) + expect(mainResume).toHaveBeenLastCalledWith(owner, true) + expect(getPaneSpawnDeferral(paneKey)?.reason).toBe('live_cap') + expect(mockStoreState.sleepingAgentSessionsByPaneKey[paneKey]).toBe(record) + expect(transport.connect).not.toHaveBeenCalled() + + mainResume.mockResolvedValue(true) + deps.isVisibleRef.current = true + getPaneSpawnDeferral(paneKey)?.resume() + await flushAsyncTicks(30) + expect(mainResume).toHaveBeenLastCalledWith(owner, false) + expect(transport.connect).toHaveBeenCalledOnce() + expect(transport.connect).toHaveBeenCalledWith( + expect.not.objectContaining({ command: expect.anything() }) + ) + expect(deps.onShowSessionRestoredBanner).toHaveBeenCalledOnce() + expect(mockStoreState.clearSleepingAgentSession).toHaveBeenCalledWith(paneKey) + expect(getPaneSpawnDeferral(paneKey)).toBeUndefined() + expect(drain.queued.has(paneKey)).toBe(false) + binding.dispose() + }) + + it('fences late main outcomes and preserves only explicit legacy fallback', async () => { + const { attachToMainResumedSleepPane } = + await import('./pty-connection/main-resumed-sleep-pane') + const { mainResumedSleepPane } = await import('./pty-connection/main-resumed-sleep-pane') + for (const outcome of [ + 'false', + 'generic', + 'automatic-false', + 'sleeping', + 'cancel', + 'dispose', + 'superseded', + 'cancel-refused', + 'dispose-refused', + 'teardown-refused', + 'attach-failed' + ]) { + mockStoreState.deleteStateByWorktreeId = {} + const pane = createPane(1) + const paneKey = makePaneKey('tab-1', pane.leafId) + const source = { cancelled: false } + const startup = { + command: "claude '--resume' 'provider-session-1'", + agent: 'claude' as const, + resumeProviderSession: RESUME, + resumeOrigin: 'saved' as const, + launchToken: 'token', + launchConfig: { agentArgs: '', agentEnv: {} }, + useLiveEntry: false, + hasSleepingRecord: true, + resumeSource: source, + sleepingRecordEntry: { + paneKey, + record: { + paneKey, + tabId: 'tab-1', + worktreeId: 'wt-1', + agent: 'claude' as const, + providerSession: RESUME, + prompt: '', + state: 'working' as const, + capturedAt: 1, + updatedAt: 1, + origin: 'worktree-sleep' as const + } + } + } + let land: (value: boolean) => void = () => {} + let refuse: (error: Error) => void = () => {} + const pending = new Promise((resolve, reject) => { + land = resolve + refuse = reject + }) + const mainResume = vi.fn(() => pending) + window.api.worktrees = { ...window.api.worktrees, resumeSleptPane: mainResume } + const fixture = { + disposed: false, + transportStreamGeneration: 1, + tabGeneration: 0, + cacheKey: paneKey, + deps: createDeps(), + transport: { getPtyId: () => null, abandonPreconnectInput: vi.fn() }, + startFreshSpawn: vi.fn(async () => (outcome === 'attach-failed' ? null : 'pty')), + settlePaneAttachAttempt: vi.fn(), + enterSpawnDeferredSleep: vi.fn(), + showSessionRestoredBanner: vi.fn() + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: fixture supplies every field the main resume helper and owner selector read. + const session = fixture as unknown as ConnectPanePtySession + const owner = { worktreeId: 'wt-1', tabId: 'tab-1', leafId: pane.leafId } + expect(mainResumedSleepPane(session, startup)).toEqual(owner) + expect( + mainResumedSleepPane({ ...session, runtimeEnvironmentId: 'paired' }, startup) + ).toBeNull() + expect(mainResumedSleepPane(session, { ...startup, useLiveEntry: true })).toBeNull() + expect( + mainResumedSleepPane(session, { + ...startup, + sleepingRecordEntry: { + paneKey, + record: { ...startup.sleepingRecordEntry.record, origin: 'quit' } + } + }) + ).toBeNull() + expect( + mainResumedSleepPane(session, { + ...startup, + sleepingRecordEntry: { + paneKey, + record: { ...startup.sleepingRecordEntry.record, tabId: 'web-terminal-remote' } + } + }) + ).toBeNull() + if (outcome === 'false') { + const { installSpawnDeferredSleep } = await import('./pty-connection/spawn-deferred-sleep') + installSpawnDeferredSleep(session) + const { launchConfig: _launchConfig, ...withoutConfig } = startup + session.deferredSpawn = { reason: 'live_cap', startupOverride: withoutConfig, options: {} } + session.spawnColdRestoreAgentResume = vi.fn(async () => null) + await session.resumeDeferredSpawn() + expect(session.spawnColdRestoreAgentResume).toHaveBeenCalledWith(withoutConfig, {}, false) + session.disposeSpawnDeferral() + session.enterSpawnDeferredSleep = vi.fn() + } + const running = attachToMainResumedSleepPane( + session, + owner, + startup, + {}, + outcome === 'sleeping' || outcome === 'automatic-false' + ) + if (outcome.startsWith('cancel')) { + source.cancelled = true + } + if (outcome.startsWith('dispose')) { + fixture.disposed = true + } + if (outcome === 'teardown-refused') { + mockStoreState.deleteStateByWorktreeId = { + 'wt-1': { isDeleting: true, error: null, canForceDelete: false, forceDeleteReason: null } + } + } + if (outcome === 'superseded') { + fixture.transportStreamGeneration += 1 + } + // A real Electron rejection is delivered through the same pending operation. + if (outcome === 'generic' || outcome === 'sleeping' || outcome.endsWith('-refused')) { + refuse( + new Error( + `Error invoking remote method 'worktrees:resumeSleptPane': Error: ${outcome === 'sleeping' ? 'worktree_terminals_sleeping' : outcome.endsWith('-refused') ? 'terminal_spawn_deferred:live_cap' : 'terminal_not_started'}` + ) + ) + } else { + land(outcome !== 'false' && outcome !== 'automatic-false') + } + await running + expect(fixture.startFreshSpawn).toHaveBeenCalledTimes( + ['false', 'generic', 'attach-failed'].includes(outcome) ? 1 : 0 + ) + expect(fixture.showSessionRestoredBanner).not.toHaveBeenCalled() + expect(fixture.enterSpawnDeferredSleep).not.toHaveBeenCalled() + expect(mockStoreState.clearSleepingAgentSession).not.toHaveBeenCalled() + } + }) + it('keeps the pane sleeping with its resume handle and resumes it when opened', async () => { const { connectPanePty } = await import('./pty-connection') const { getPaneSpawnDeferral } = await import('@/lib/pane-spawn-deferral-registry') diff --git a/src/renderer/src/components/terminal-pane/pty-connection/deferred-cold-restore-and-snapshot.ts b/src/renderer/src/components/terminal-pane/pty-connection/deferred-cold-restore-and-snapshot.ts index 593f10738d68..e35657a5dbbd 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/deferred-cold-restore-and-snapshot.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/deferred-cold-restore-and-snapshot.ts @@ -85,19 +85,15 @@ export function bindDeferredColdRestoreAndSnapshot(session: ConnectPanePtySessio // Why ungated: a reveal, a restart replacement on show, or a phone wake already chose to run now. session.spawnColdRestoreAgentResume = ( startup: ColdRestoreAgentResumeStartup | null = session.buildColdRestoreAgentResumeStartup(), - options: FreshSpawnOptions = {} + options: FreshSpawnOptions = {}, + automatic?: boolean ): Promise => { if (startup?.resumeSource?.cancelled) { return Promise.resolve(null) } const mainPane = mainResumedSleepPane(session, startup) if (mainPane && startup?.sleepingRecordEntry) { - return attachToMainResumedSleepPane( - session, - mainPane, - startup.sleepingRecordEntry.paneKey, - options - ) + return attachToMainResumedSleepPane(session, mainPane, startup, options, automatic) } return startPaneThroughMainThenAttach(session, () => { session.applyColdRestoreAgentResumeStartup(startup) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts b/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts index 2abd01112ee4..8dcb9d9c6c1b 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts @@ -22,35 +22,34 @@ import type { import type { ConnectPanePtySession } from './connect-pane-pty-session' import { findTerminalTabForPane } from './terminal-tab-id' +export function releaseDeferredCwdFence(session: ConnectPanePtySession): void { + if (!session.transport.getPtyId()) { + session.transport.abandonPreconnectInput?.() + try { + session.deps.onDeferredCwdSpawnFailed?.() + } catch { + // Cleanup must not turn a settled spawn into an unhandled rejection. + } + } +} + export function bindStartFreshSpawn(session: ConnectPanePtySession): void { session.startFreshSpawn = ( startupOverride?: PendingStartupCommand | null, options: FreshSpawnOptions = {} ): Promise => { - const releaseDeferredCwdFence = (): void => { - if (!session.transport.getPtyId()) { - // Abandoned spawns never connect; discard buffered input and settle its write promises here. - session.transport.abandonPreconnectInput?.() - try { - session.deps.onDeferredCwdSpawnFailed?.() - } catch { - // A cleanup callback must not turn a settled spawn into an unhandled rejection. - } - } - } - if ( hasWorktreeTeardownStarted( useAppStore.getState().deleteStateByWorktreeId?.[session.deps.worktreeId] ) ) { // Worktree deletion already killed its PTYs; skip respawn into the directory being removed instead of racing main’s fence. - releaseDeferredCwdFence() + releaseDeferredCwdFence(session) return Promise.resolve(null) } const effectiveStartup = startupOverride === undefined ? session.paneStartup : startupOverride if (effectiveStartup?.resumeSource?.cancelled) { - releaseDeferredCwdFence() + releaseDeferredCwdFence(session) return Promise.resolve(null) } session.authoritativeReattachGeneration += 1 @@ -145,7 +144,6 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { session.pendingSpawnDeferral = null if (deferral) { // Why before the launch-config cleanup below: a deferred launch is postponed, not dead. - releaseDeferredCwdFence() clearPreSignaledSerializer() session.finishReattachLiveDataDeferral(false, outputCallbacks.generation) session.enterSpawnDeferredSleep(deferral, startupOverride, options, visibleAtSpawn) @@ -181,7 +179,7 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { } if (!accepted) { // A rejected reattach ends this spawn; nothing later clears the fence. - releaseDeferredCwdFence() + releaseDeferredCwdFence(session) } return accepted ? resolvedPtyId : null } @@ -246,7 +244,7 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { session.reconcilePtySizeAfterSpawn(resolvedPtyId, session.cols, session.rows) } if (!resolvedPtyId) { - releaseDeferredCwdFence() + releaseDeferredCwdFence(session) clearPreSignaledSerializer() session.finishReattachLiveDataDeferral(false, outputCallbacks.generation) return null @@ -269,7 +267,7 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { if (!ownerRefused && isPaneOwnerRefusal(message)) { outputCallbacks.callbacks.onError(message) } - releaseDeferredCwdFence() + releaseDeferredCwdFence(session) session.finishReattachLiveDataDeferral(false, outputCallbacks.generation) if ( session.paneStartup?.launchConfig || @@ -310,7 +308,6 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { } if (session.deferredSpawn) { // Why no remount: the host would defer the remount's restore again, in a loop. - session.settlePaneAttachAttempt?.('failed') return } settleSpawnThatLeftPaneUnbound(session) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/main-resumed-sleep-pane.ts b/src/renderer/src/components/terminal-pane/pty-connection/main-resumed-sleep-pane.ts index 3aea67d5b1df..c51df2a9e976 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/main-resumed-sleep-pane.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/main-resumed-sleep-pane.ts @@ -1,6 +1,10 @@ // A slept workspace's pane: main resumes its agent, and this window only attaches to that terminal. import { useAppStore } from '@/store' +import { hasWorktreeTeardownStarted } from '@/store/slices/worktree-delete-state-types' +import { readTerminalSpawnDeferral } from '../../../../../shared/host-spawn-admission' +import { releaseDeferredCwdFence } from './fresh-spawn-start' +import { findTerminalTabForPane } from './terminal-tab-id' import { isHostMirroredSleepingRecord } from '@/lib/host-mirrored-pane-liveness' import { parsePaneKey } from '../../../../../shared/stable-pane-id' import { isWorkspaceSleepRecord } from '../../../../../shared/workspace-sleep' @@ -31,18 +35,52 @@ export function mainResumedSleepPane( export async function attachToMainResumedSleepPane( session: ConnectPanePtySession, pane: { worktreeId: string; tabId: string; leafId: string }, - paneKey: string, - options: FreshSpawnOptions + startup: ColdRestoreAgentResumeStartup, + options: FreshSpawnOptions, + automatic?: boolean ): Promise { - const resumed = await window.api.worktrees.resumeSleptPane(pane).catch(() => false) - if (session.disposed) { + const generation = session.transportStreamGeneration + const isCurrent = (): boolean => + !session.disposed && + !hasWorktreeTeardownStarted( + useAppStore.getState().deleteStateByWorktreeId?.[pane.worktreeId] + ) && + !startup.resumeSource?.cancelled && + (startup.isCurrent?.() ?? true) && + (findTerminalTabForPane(useAppStore.getState(), pane.worktreeId, pane.tabId)?.generation ?? + 0) === session.tabGeneration + if (!isCurrent()) { + return null + } + const visibleAtSpawn = session.deps.isVisibleRef.current === true + let resumed = false + try { + resumed = await window.api.worktrees.resumeSleptPane(pane, automatic) + } catch (error: unknown) { + if (!isCurrent() || generation !== session.transportStreamGeneration) { + return null + } + const deferral = readTerminalSpawnDeferral(error) + if (deferral) { + session.enterSpawnDeferredSleep(deferral, startup, options, visibleAtSpawn) + return null + } + } + if (!isCurrent() || generation !== session.transportStreamGeneration) { + return null + } + if (automatic && !resumed) { + releaseDeferredCwdFence(session) + session.settlePaneAttachAttempt?.('failed') return null } const ptyId = await session.startFreshSpawn(null, options) - if (resumed && ptyId) { + if (isCurrent() && resumed && ptyId) { session.showSessionRestoredBanner() // Main keeps its record; the window's mirror of it is spent. - useAppStore.getState().clearSleepingAgentSession(paneKey) + if (startup.sleepingRecordEntry) { + useAppStore.getState().clearSleepingAgentSession(startup.sleepingRecordEntry.paneKey) + } } return ptyId } diff --git a/src/renderer/src/components/terminal-pane/pty-connection/spawn-deferred-sleep.ts b/src/renderer/src/components/terminal-pane/pty-connection/spawn-deferred-sleep.ts index 0f3232297d41..d481af74d855 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/spawn-deferred-sleep.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/spawn-deferred-sleep.ts @@ -1,3 +1,5 @@ +import { releaseDeferredCwdFence } from './fresh-spawn-start' +import { mainResumedSleepPane } from './main-resumed-sleep-pane' import { useAppStore } from '@/store' import { writeTerminalOutput } from '@/lib/pane-manager/pane-terminal-output-scheduler' import type { SpawnDeferralReason } from '../../../../../shared/host-spawn-admission' @@ -43,7 +45,13 @@ type DeferredSpawn = { function isColdRestoreStartup( startup: PendingStartupCommand | null | undefined ): startup is ColdRestoreAgentResumeStartup { - return Boolean(startup && 'launchConfig' in startup && 'resumeProviderSession' in startup) + return Boolean( + startup && + 'agent' in startup && + 'resumeProviderSession' in startup && + 'useLiveEntry' in startup && + 'sleepingRecordEntry' in startup + ) } /** The record a deferred restore leaves behind, so the session stays listed and resumable even if @@ -168,6 +176,7 @@ export function installSpawnDeferredSleep(session: ConnectPanePtySession): void options: FreshSpawnOptions, visibleAtSpawn: boolean ): void => { + releaseDeferredCwdFence(session) session.keepUnrunResumeHandle(startupOverride) session.deferredSpawn = { reason, startupOverride, options } const deferral = { reason, resume: () => void session.resumeDeferredSpawn() } @@ -182,6 +191,7 @@ export function installSpawnDeferredSleep(session: ConnectPanePtySession): void async () => (await session.resumeDeferredSpawn().catch(() => null)) !== null ) } + session.settlePaneAttachAttempt?.('failed') if (!visibleAtSpawn) { // Why: a pane opened while its hidden restore was in flight resumes as the user's own. queueMicrotask(() => session.resumeDeferredSpawnOnReveal()) @@ -216,9 +226,18 @@ export function installSpawnDeferredSleep(session: ConnectPanePtySession): void clearPaneSpawnDeferral(session.cacheKey) } } - return startPaneThroughMainThenAttach(session, () => - session.startFreshSpawn(deferred.startupOverride, deferred.options) - ).then( + const startup = deferred.startupOverride + const spawned: Promise = + isColdRestoreStartup(startup) && mainResumedSleepPane(session, startup) + ? session.spawnColdRestoreAgentResume( + startup, + deferred.options, + session.deps.isVisibleRef.current !== true + ) + : startPaneThroughMainThenAttach(session, () => + session.startFreshSpawn(startup, deferred.options) + ) + return spawned.then( (ptyId: string | null) => { settle() return ptyId From 83a54c43a96024448f1ba7677141fed76d9672d3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:00:23 -0700 Subject: [PATCH 06/15] Fix terminal limit CI quality checks --- src/main/daemon/daemon-pty-adapter.ts | 6 ++---- src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts | 9 +++++---- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/main/daemon/daemon-pty-adapter.ts b/src/main/daemon/daemon-pty-adapter.ts index b1ff4e54db3e..532cc165ac1f 100644 --- a/src/main/daemon/daemon-pty-adapter.ts +++ b/src/main/daemon/daemon-pty-adapter.ts @@ -237,10 +237,8 @@ export class DaemonPtyAdapter extends DaemonPtyDaemonRecovery implements IPtyPro throw new Error('Terminal host changed. Refresh the setting and try again.') } try { - const status = await this.client.request( - update ? 'setTerminalLimit' : 'terminalLimitStatus', - update - ) + const type = update ? 'setTerminalLimit' : 'terminalLimitStatus' + const status = await this.client.request(type, update) if ( !identity || this.getDaemonIdentity()?.launchNonce !== identity.launchNonce || diff --git a/src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts b/src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts index d43c49af336e..f71022dc152e 100644 --- a/src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts +++ b/src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts @@ -1,4 +1,5 @@ import { beforeEach, expect, it, vi } from 'vitest' +import { ipcRenderer } from 'electron' import type { WorktreeIpcContext } from '../worktree-ipc-context' const { handlers } = vi.hoisted(() => ({ @@ -37,12 +38,12 @@ it('validates the bundled bridge argument before the runtime receives any trigge {}, { automatic: true, targetsHost: true, targetGroupId: 'g' } ]) { - await expect( - Reflect.apply(worktreesApi.resumeSleptPane, null, [pane, invalid]) - ).rejects.toThrow('invalid_automatic') + await expect(ipcRenderer.invoke('worktrees:resumeSleptPane', pane, invalid)).rejects.toThrow( + 'invalid_automatic' + ) } await expect( - Reflect.apply(worktreesApi.resumeSleptPane, null, [{ tabId: 'tab' }, true]) + ipcRenderer.invoke('worktrees:resumeSleptPane', { tabId: 'tab' }, true) ).rejects.toThrow('invalid_pane') expect(resumeSleptPane).not.toHaveBeenCalled() }) From dd6485e7b8e38b46f905c2690e625662c7b4a29a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:10:02 -0700 Subject: [PATCH 07/15] Correct slept terminal resume test types --- src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts | 6 ++++-- .../mobile-session-tabs-windowless-sleep-resume.spec.ts | 3 ++- .../pty-connection-spawn-deferred-sleep.test.ts | 3 ++- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts b/src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts index f71022dc152e..58369aa41d18 100644 --- a/src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts +++ b/src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts @@ -1,6 +1,7 @@ import { beforeEach, expect, it, vi } from 'vitest' import { ipcRenderer } from 'electron' import type { WorktreeIpcContext } from '../worktree-ipc-context' +import type { WorktreeApi } from '../../../../preload/api/worktree-api' const { handlers } = vi.hoisted(() => ({ handlers: new Map unknown>() @@ -23,9 +24,10 @@ it('validates the bundled bridge argument before the runtime receives any trigge // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: registration reads only runtime; this test invokes only resumeSleptPane. registerWorktreeSleepHandlers({ runtime: { resumeSleptPane } } as unknown as WorktreeIpcContext) const pane = { worktreeId: 'wt', tabId: 'tab', leafId: 'leaf' } - await expect(worktreesApi.resumeSleptPane(pane)).resolves.toBe(true) + const bridge: WorktreeApi = worktreesApi + await expect(bridge.resumeSleptPane(pane)).resolves.toBe(true) for (const automatic of [undefined, false, true]) { - await expect(worktreesApi.resumeSleptPane(pane, automatic)).resolves.toBe(true) + await expect(bridge.resumeSleptPane(pane, automatic)).resolves.toBe(true) expect(resumeSleptPane).toHaveBeenLastCalledWith(pane, automatic) } resumeSleptPane.mockClear() diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-windowless-sleep-resume.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-windowless-sleep-resume.spec.ts index b186de35afe0..3d9b3fcb39ab 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-windowless-sleep-resume.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-windowless-sleep-resume.spec.ts @@ -1,4 +1,5 @@ import { spawnWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' +import type { SpawnRequestFacts } from '../../../shared/host-spawn-admission' import { createSpawnAdmissionState, DEFAULT_SPAWN_ADMISSION_LIMITS, @@ -324,7 +325,7 @@ describe('opening a workspace-slept running agent on a host with no window', () hasAgentSessionClaim: false, hasHistorySeed: false, deadlineAt: 1000 - } + } satisfies SpawnRequestFacts const decision = decideSpawnAdmission({ state, facts, diff --git a/src/renderer/src/components/terminal-pane/pty-connection-spawn-deferred-sleep.test.ts b/src/renderer/src/components/terminal-pane/pty-connection-spawn-deferred-sleep.test.ts index 2f9e539b4323..dcf8386dd15c 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-spawn-deferred-sleep.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-spawn-deferred-sleep.test.ts @@ -248,6 +248,7 @@ describe('connectPanePty: a restore the host kept asleep', () => { mockStoreState.sleepingAgentSessionsByPaneKey[paneKey] = record mockStoreState.agentStatusByPaneKey = {} mockStoreState.tabsByWorktree['wt-1'] = [{ id: 'tab-1', ptyId: null }] + mockStoreState.terminalLayoutsByTabId ??= {} mockStoreState.terminalLayoutsByTabId['tab-1'] = { root: { type: 'leaf', leafId: pane.leafId }, activeLeafId: pane.leafId, @@ -416,7 +417,7 @@ describe('connectPanePty: a restore the host kept asleep', () => { } if (outcome === 'teardown-refused') { mockStoreState.deleteStateByWorktreeId = { - 'wt-1': { isDeleting: true, error: null, canForceDelete: false, forceDeleteReason: null } + 'wt-1': { isDeleting: true } } } if (outcome === 'superseded') { From 7236570a39fcb79cda88376bfc812fff073e18fc Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:01:35 -0700 Subject: [PATCH 08/15] Move the slept terminal Resume fix to its own pull request The Resume correction fixes a bug that already exists at the default limit, so it now lives in #35401 and this change only adds the terminal limit setting. --- .../sleep/register-worktree-sleep-handlers.ts | 7 +- .../worktrees/sleep/resume-slept-pane.test.ts | 51 ----- ...ssion-tabs-windowless-sleep-resume.spec.ts | 90 -------- .../managed-workspace-operations.ts | 4 +- .../workspace-sleep-own-worktree.test.ts | 32 --- .../workspaces/workspace-sleep-runtime.ts | 13 +- src/preload/api/worktree-api.ts | 5 +- src/preload/api/worktrees-bridge.ts | 3 +- ...-connection-hidden-sleeping-resume.spec.ts | 14 -- ...ty-connection-spawn-deferred-sleep.test.ts | 216 ------------------ .../deferred-cold-restore-and-snapshot.ts | 10 +- .../pty-connection/fresh-spawn-start.ts | 35 +-- .../pty-connection/main-resumed-sleep-pane.ts | 50 +--- .../pty-connection/spawn-deferred-sleep.ts | 27 +-- 14 files changed, 46 insertions(+), 511 deletions(-) delete mode 100644 src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts diff --git a/src/main/ipc/worktrees/sleep/register-worktree-sleep-handlers.ts b/src/main/ipc/worktrees/sleep/register-worktree-sleep-handlers.ts index fea90d1d36c6..98c4425414dc 100644 --- a/src/main/ipc/worktrees/sleep/register-worktree-sleep-handlers.ts +++ b/src/main/ipc/worktrees/sleep/register-worktree-sleep-handlers.ts @@ -28,14 +28,11 @@ export function registerWorktreeSleepHandlers(context: WorktreeIpcContext): void context.runtime.noteWorkspaceReopened(worktreeId) ) // Main resumes the session before the renderer attaches its spawn. - ipcMain.handle('worktrees:resumeSleptPane', (_event, pane: unknown, automatic: unknown) => { + ipcMain.handle('worktrees:resumeSleptPane', (_event, pane: unknown) => { if (!isRestoredPane(pane)) { throw new Error('invalid_pane') } - if (automatic !== undefined && typeof automatic !== 'boolean') { - throw new Error('invalid_automatic') - } - return context.runtime.resumeSleptPane(pane, automatic) + return context.runtime.resumeSleptPane(pane) }) ipcMain.handle( 'worktrees:retireStrandedSleepRecord', diff --git a/src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts b/src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts deleted file mode 100644 index 58369aa41d18..000000000000 --- a/src/main/ipc/worktrees/sleep/resume-slept-pane.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { beforeEach, expect, it, vi } from 'vitest' -import { ipcRenderer } from 'electron' -import type { WorktreeIpcContext } from '../worktree-ipc-context' -import type { WorktreeApi } from '../../../../preload/api/worktree-api' - -const { handlers } = vi.hoisted(() => ({ - handlers: new Map unknown>() -})) -vi.mock('electron', () => ({ - ipcMain: { - handle: (name: string, handler: (...args: unknown[]) => unknown) => handlers.set(name, handler) - }, - ipcRenderer: { - invoke: async (name: string, ...args: unknown[]) => handlers.get(name)?.({}, ...args) - } -})) -import { registerWorktreeSleepHandlers } from './register-worktree-sleep-handlers' -import { worktreesApi } from '../../../../preload/api/worktrees-bridge' - -beforeEach(() => handlers.clear()) - -it('validates the bundled bridge argument before the runtime receives any trigger authority', async () => { - const resumeSleptPane = vi.fn(async () => true) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: registration reads only runtime; this test invokes only resumeSleptPane. - registerWorktreeSleepHandlers({ runtime: { resumeSleptPane } } as unknown as WorktreeIpcContext) - const pane = { worktreeId: 'wt', tabId: 'tab', leafId: 'leaf' } - const bridge: WorktreeApi = worktreesApi - await expect(bridge.resumeSleptPane(pane)).resolves.toBe(true) - for (const automatic of [undefined, false, true]) { - await expect(bridge.resumeSleptPane(pane, automatic)).resolves.toBe(true) - expect(resumeSleptPane).toHaveBeenLastCalledWith(pane, automatic) - } - resumeSleptPane.mockClear() - for (const invalid of [ - null, - 0, - 1, - 'true', - [], - {}, - { automatic: true, targetsHost: true, targetGroupId: 'g' } - ]) { - await expect(ipcRenderer.invoke('worktrees:resumeSleptPane', pane, invalid)).rejects.toThrow( - 'invalid_automatic' - ) - } - await expect( - ipcRenderer.invoke('worktrees:resumeSleptPane', { tabId: 'tab' }, true) - ).rejects.toThrow('invalid_pane') - expect(resumeSleptPane).not.toHaveBeenCalled() -}) diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-windowless-sleep-resume.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-windowless-sleep-resume.spec.ts index 3d9b3fcb39ab..5f106b187a36 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-windowless-sleep-resume.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-windowless-sleep-resume.spec.ts @@ -1,11 +1,3 @@ -import { spawnWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' -import type { SpawnRequestFacts } from '../../../shared/host-spawn-admission' -import { - createSpawnAdmissionState, - DEFAULT_SPAWN_ADMISSION_LIMITS, - decideSpawnAdmission, - resolveSpawnCharge -} from '../../../shared/host-spawn-admission' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' import { describe, expect, it, vi } from 'vitest' import { OrcaRuntimeService, electronMocks } from '../orca-runtime-test-mocks.spec' @@ -292,88 +284,6 @@ describe('opening a workspace-slept running agent on a host with no window', () describe("the window's open of a slept pane (worktrees:resumeSleptPane)", () => { const pane = { worktreeId: TEST_WORKTREE_ID, tabId: 'host-tab', leafId: HEADLESS_LEAF_ID } - it('keeps the original provider and current retry intent through a refused main start', async () => { - const fixture = makeWorkingSleepStore() - const { runtime, spawn, opened } = openPane(fixture.runtimeStore, 'openable', { - withWindow: true, - tap: false - }) - await opened - const limits = DEFAULT_SPAWN_ADMISSION_LIMITS - const state = createSpawnAdmissionState(limits, 0) - state.liveAutomatic = limits.maxLiveAutomatic - spawn.mockImplementation(async (...args: unknown[]) => { - const request = args[0] - if (typeof request !== 'object' || request === null || !('spawnIntent' in request)) { - throw new Error('missing intent') - } - const declaredIntent = request.spawnIntent - if (declaredIntent !== 'user-resume' && declaredIntent !== 'automatic-restore') { - throw new Error('wrong intent') - } - const release = await runtime.acquireWorktreeTerminalSpawn( - spawnWorktreeTarget(TEST_WORKTREE_ID, null), - { - refuseSleptWorktree: - 'refuseSleptWorktree' in request && request.refuseSleptWorktree === true - } - ) - try { - const facts = { - clientId: 'resume-test', - declaredIntent, - hasAgentSessionClaim: false, - hasHistorySeed: false, - deadlineAt: 1000 - } satisfies SpawnRequestFacts - const decision = decideSpawnAdmission({ - state, - facts, - charge: resolveSpawnCharge(state, facts, limits, 0), - pressure: 'ok', - mode: { kind: 'normal' }, - limits, - now: 0 - }) - if (spawn.mock.calls.length === 1 || decision.kind === 'defer') { - throw new Error('terminal_spawn_deferred:live_cap') - } - return { id: 'persisted-pty' } - } finally { - release() - } - }) - await runtime.sleepTerminalsForWorktree(`id:${TEST_WORKTREE_ID}`) - await expect(runtime.resumeSleptPane(pane)).rejects.toThrow( - 'terminal_spawn_deferred:live_cap' - ) - expect(spawn).toHaveBeenLastCalledWith( - expect.objectContaining({ spawnIntent: 'user-resume' }) - ) - await expect(runtime.resumeSleptPane(pane, true)).rejects.toThrow( - 'terminal_spawn_deferred:live_cap' - ) - expect(spawn).toHaveBeenLastCalledWith( - expect.objectContaining({ - spawnIntent: 'automatic-restore', - refuseSleptWorktree: true - }) - ) - await runtime.sleepTerminalsForWorktree(`id:${TEST_WORKTREE_ID}`) - await expect(runtime.resumeSleptPane(pane, true)).rejects.toThrow( - 'worktree_terminals_sleeping' - ) - expect(spawn).toHaveBeenCalledTimes(3) - await expect(runtime.resumeSleptPane(pane, false)).resolves.toBe(true) - for (let call = 0; call < 4; call += 1) { - expect(spawnedCommand(spawn, call)).toContain('provider-session-1') - expect(spawnedCommand(spawn, call)).not.toContain('--dangerously-skip-permissions') - } - expect(spawn).toHaveBeenLastCalledWith( - expect.objectContaining({ spawnIntent: 'user-resume' }) - ) - }) - it('resumes once; a second open after it finished attaches to the same terminal', async () => { const fixture = makeWorkingSleepStore() const { runtime, spawn, opened } = openPane(fixture.runtimeStore, 'openable', { diff --git a/src/main/runtime/workspaces/managed-workspace-operations.ts b/src/main/runtime/workspaces/managed-workspace-operations.ts index 42f72e52516c..73355ae15898 100644 --- a/src/main/runtime/workspaces/managed-workspace-operations.ts +++ b/src/main/runtime/workspaces/managed-workspace-operations.ts @@ -262,8 +262,8 @@ export abstract class OrcaRuntimeWithListManagedWorktrees extends OrcaRuntimeWit } /** The window opened a slept pane; main resumes it and the window attaches. */ - resumeSleptPane(pane: RestoredPane, automatic?: boolean): Promise { - return this.workspaceSleep.resumePane(pane, automatic) + resumeSleptPane(pane: RestoredPane): Promise { + return this.workspaceSleep.resumePane(pane) } /** The window reopened a slept agent whose tab is gone in a fresh tab; this record is spent. */ diff --git a/src/main/runtime/workspaces/workspace-sleep-own-worktree.test.ts b/src/main/runtime/workspaces/workspace-sleep-own-worktree.test.ts index 98a9b79d093b..22bda27e4ac6 100644 --- a/src/main/runtime/workspaces/workspace-sleep-own-worktree.test.ts +++ b/src/main/runtime/workspaces/workspace-sleep-own-worktree.test.ts @@ -80,35 +80,3 @@ describe("a phone's or the CLI's sleep", () => { expect(failedNotices(notices)).toEqual([]) }) }) - -it.each([true, false])( - 'an automatic=%s retry preserves Sleep/VM suspension intent', - async (automatic) => { - let finishStop: (result: RuntimeWorktreeTerminalSleepResult) => void = () => {} - const stopped = new Promise((resolve) => { - finishStop = resolve - }) - const suspendVm = vi.fn(async () => {}) - const ensureRestoredPaneStarted = vi.fn(async () => null) - const stop = vi.fn(() => stopped) - const { sleep } = coordinator({ - workspaceLifecycle: null, - sleepTerminalsForWorktree: stop, - ensureRestoredPaneStarted, - workspaceSleepPlatform: { - callEnvironment: async () => { - throw new Error('unused') - }, - suspendVm - } - }) - const sleeping = sleep.sleepOwnWorktree(WORKTREE, {}) - await vi.waitFor(() => expect(stop).toHaveBeenCalled()) - const pane = { worktreeId: WORKTREE, tabId: 'tab', leafId: 'leaf' } - await sleep.resumePane(pane, automatic) - finishStop(verified) - await sleeping - expect(ensureRestoredPaneStarted).toHaveBeenCalledWith(pane, { automatic }) - expect(suspendVm).toHaveBeenCalledTimes(automatic ? 1 : 0) - } -) diff --git a/src/main/runtime/workspaces/workspace-sleep-runtime.ts b/src/main/runtime/workspaces/workspace-sleep-runtime.ts index e3c6f5c1f845..c1a3ecf63463 100644 --- a/src/main/runtime/workspaces/workspace-sleep-runtime.ts +++ b/src/main/runtime/workspaces/workspace-sleep-runtime.ts @@ -43,10 +43,7 @@ export type WorkspaceSleepRuntime = { notifyWorkspaceSleep: (notice: WorkspaceSleepNotice) => void wakeRecordsForWorktree: (worktreeId: string) => SleepingAgentSessionRecord[] resumeSleptWorkspaceAgents: (worktreeId: string) => Promise - ensureRestoredPaneStarted: ( - pane: RestoredPane, - trigger?: { automatic?: boolean } - ) => Promise + ensureRestoredPaneStarted: (pane: RestoredPane) => Promise /** The window's wake of its own completed-agent hibernation, which main does not hold. */ wakeWindowHibernatedAgents: (worktreeId: string) => void } @@ -136,13 +133,11 @@ export class WorkspaceSleepCoordinator { } /** A slept pane was opened: main resumes it, queued like any wake, and the opener attaches. */ - resumePane(pane: RestoredPane, automatic = false): Promise { - if (!automatic) { - this.noteReopened(pane.worktreeId) - } + resumePane(pane: RestoredPane): Promise { + this.noteReopened(pane.worktreeId) return queueTerminalWorkspaceCommand(this.runtime, `id:${pane.worktreeId}`, { kind: 'wake', - run: async () => (await this.runtime.ensureRestoredPaneStarted(pane, { automatic })) !== null + run: async () => (await this.runtime.ensureRestoredPaneStarted(pane)) !== null }) } diff --git a/src/preload/api/worktree-api.ts b/src/preload/api/worktree-api.ts index 2aac77686536..6ca23b4f0b3d 100644 --- a/src/preload/api/worktree-api.ts +++ b/src/preload/api/worktree-api.ts @@ -88,10 +88,7 @@ export type WorktreeApi = { sleep: (request: WorkspaceSleepRequest) => Promise sleepReopened: (worktreeId: string) => Promise /** True once running, so the renderer's subsequent spawn reattaches. */ - resumeSleptPane: ( - pane: { worktreeId: string; tabId: string; leafId: string }, - automatic?: boolean - ) => Promise + resumeSleptPane: (pane: { worktreeId: string; tabId: string; leafId: string }) => Promise /** Drops main's workspace-sleep record only while no tab holds its pane. */ retireStrandedSleepRecord: (args: { worktreeId: string; paneKey: string }) => Promise remove: (args: { diff --git a/src/preload/api/worktrees-bridge.ts b/src/preload/api/worktrees-bridge.ts index feb3f4a668aa..44692d18209f 100644 --- a/src/preload/api/worktrees-bridge.ts +++ b/src/preload/api/worktrees-bridge.ts @@ -44,8 +44,7 @@ export const worktreesApi = { sleep: (request) => ipcRenderer.invoke('worktrees:sleep', request), sleepReopened: (worktreeId) => ipcRenderer.invoke('worktrees:sleepReopened', worktreeId), - resumeSleptPane: (pane, automatic) => - ipcRenderer.invoke('worktrees:resumeSleptPane', pane, automatic), + resumeSleptPane: (pane) => ipcRenderer.invoke('worktrees:resumeSleptPane', pane), retireStrandedSleepRecord: (args) => ipcRenderer.invoke('worktrees:retireStrandedSleepRecord', args), diff --git a/src/renderer/src/components/terminal-pane/pty-connection-hidden-sleeping-resume.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection-hidden-sleeping-resume.spec.ts index 8d939d727a2e..a0346d86995c 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-hidden-sleeping-resume.spec.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-hidden-sleeping-resume.spec.ts @@ -229,20 +229,6 @@ export function registerPtyConnectionHiddenSleepingResumeTests(): void { expect(resumeCommands(transport)[0]).toContain("'resume' 'codex-session-1'") }) - it('keeps an initial hidden workspace-sleep wake explicit', async () => { - seedSleepingPane(null, { origin: 'worktree-sleep' }) - const resumeSleptPane = vi.fn(async () => true) - window.api.worktrees = { ...window.api.worktrees, resumeSleptPane } - const { requestSleepingAgentWakeOnMount } = await import('@/lib/sleeping-agent-wake-requests') - requestSleepingAgentWakeOnMount('wt-1', ['tab-1']) - connectHiddenPane(null) - await flushAsyncTicks(20) - expect(resumeSleptPane).toHaveBeenCalledWith( - { worktreeId: 'wt-1', tabId: 'tab-1', leafId: LEAF_2 }, - undefined - ) - }) - it('resumes a held hidden pane immediately on a phone wake', async () => { seedSleepingPane(DEAD_SESSION_ID) setHostLiveness(false) diff --git a/src/renderer/src/components/terminal-pane/pty-connection-spawn-deferred-sleep.test.ts b/src/renderer/src/components/terminal-pane/pty-connection-spawn-deferred-sleep.test.ts index dcf8386dd15c..135cb543f555 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-spawn-deferred-sleep.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-spawn-deferred-sleep.test.ts @@ -1,4 +1,3 @@ -import type { ConnectPanePtySession } from './pty-connection/connect-pane-pty-session' import type * as React from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { makePaneKey } from '../../../../shared/stable-pane-id' @@ -228,221 +227,6 @@ describe('connectPanePty: a restore the host kept asleep', () => { await restoreTerminalTestGlobals() }) - it('retains the main owner through wrapped refusal, hidden retries and explicit attachment', async () => { - const { connectPanePty } = await import('./pty-connection') - const { getPaneSpawnDeferral } = await import('@/lib/pane-spawn-deferral-registry') - const pane = createPane(1) - const paneKey = makePaneKey('tab-1', pane.leafId) - const record = { - paneKey, - tabId: 'tab-1', - worktreeId: 'wt-1', - agent: 'claude', - providerSession: RESUME, - prompt: '', - state: 'working', - capturedAt: 1, - updatedAt: 1, - origin: 'worktree-sleep' - } - mockStoreState.sleepingAgentSessionsByPaneKey[paneKey] = record - mockStoreState.agentStatusByPaneKey = {} - mockStoreState.tabsByWorktree['wt-1'] = [{ id: 'tab-1', ptyId: null }] - mockStoreState.terminalLayoutsByTabId ??= {} - mockStoreState.terminalLayoutsByTabId['tab-1'] = { - root: { type: 'leaf', leafId: pane.leafId }, - activeLeafId: pane.leafId, - expandedLeafId: null, - ptyIdsByLeafId: {} - } - const mainResume = vi.fn(async (_pane: unknown, _automatic?: boolean): Promise => { - throw new Error( - "Error invoking remote method 'worktrees:resumeSleptPane': Error: terminal_spawn_deferred:live_cap" - ) - }) - window.api.worktrees = { ...window.api.worktrees, resumeSleptPane: mainResume } - const transport = createMockTransport() - transport.connect.mockResolvedValue('main-pty') - transportFactoryQueue.push(transport) - const onDeferredCwdSpawnFailed = vi.fn() - const deps = createDeps({ onDeferredCwdSpawnFailed }) - const binding = connectPanePty(...mockPanePtyArgs(pane, createManager(1), deps)) - await flushAsyncTicks(30) - const owner = { worktreeId: 'wt-1', tabId: 'tab-1', leafId: pane.leafId } - expect(mainResume).toHaveBeenLastCalledWith(owner, undefined) - expect(transport.connect).not.toHaveBeenCalled() - expect(getPaneSpawnDeferral(paneKey)?.reason).toBe('live_cap') - expect(onDeferredCwdSpawnFailed).toHaveBeenCalledOnce() - expect(deps.onShowSessionRestoredBanner).not.toHaveBeenCalled() - - deps.isVisibleRef.current = false - await expect(drain.queued.get(paneKey)?.()).resolves.toBe(false) - expect(mainResume).toHaveBeenLastCalledWith(owner, true) - expect(getPaneSpawnDeferral(paneKey)?.reason).toBe('live_cap') - expect(mockStoreState.sleepingAgentSessionsByPaneKey[paneKey]).toBe(record) - expect(transport.connect).not.toHaveBeenCalled() - - mainResume.mockResolvedValue(true) - deps.isVisibleRef.current = true - getPaneSpawnDeferral(paneKey)?.resume() - await flushAsyncTicks(30) - expect(mainResume).toHaveBeenLastCalledWith(owner, false) - expect(transport.connect).toHaveBeenCalledOnce() - expect(transport.connect).toHaveBeenCalledWith( - expect.not.objectContaining({ command: expect.anything() }) - ) - expect(deps.onShowSessionRestoredBanner).toHaveBeenCalledOnce() - expect(mockStoreState.clearSleepingAgentSession).toHaveBeenCalledWith(paneKey) - expect(getPaneSpawnDeferral(paneKey)).toBeUndefined() - expect(drain.queued.has(paneKey)).toBe(false) - binding.dispose() - }) - - it('fences late main outcomes and preserves only explicit legacy fallback', async () => { - const { attachToMainResumedSleepPane } = - await import('./pty-connection/main-resumed-sleep-pane') - const { mainResumedSleepPane } = await import('./pty-connection/main-resumed-sleep-pane') - for (const outcome of [ - 'false', - 'generic', - 'automatic-false', - 'sleeping', - 'cancel', - 'dispose', - 'superseded', - 'cancel-refused', - 'dispose-refused', - 'teardown-refused', - 'attach-failed' - ]) { - mockStoreState.deleteStateByWorktreeId = {} - const pane = createPane(1) - const paneKey = makePaneKey('tab-1', pane.leafId) - const source = { cancelled: false } - const startup = { - command: "claude '--resume' 'provider-session-1'", - agent: 'claude' as const, - resumeProviderSession: RESUME, - resumeOrigin: 'saved' as const, - launchToken: 'token', - launchConfig: { agentArgs: '', agentEnv: {} }, - useLiveEntry: false, - hasSleepingRecord: true, - resumeSource: source, - sleepingRecordEntry: { - paneKey, - record: { - paneKey, - tabId: 'tab-1', - worktreeId: 'wt-1', - agent: 'claude' as const, - providerSession: RESUME, - prompt: '', - state: 'working' as const, - capturedAt: 1, - updatedAt: 1, - origin: 'worktree-sleep' as const - } - } - } - let land: (value: boolean) => void = () => {} - let refuse: (error: Error) => void = () => {} - const pending = new Promise((resolve, reject) => { - land = resolve - refuse = reject - }) - const mainResume = vi.fn(() => pending) - window.api.worktrees = { ...window.api.worktrees, resumeSleptPane: mainResume } - const fixture = { - disposed: false, - transportStreamGeneration: 1, - tabGeneration: 0, - cacheKey: paneKey, - deps: createDeps(), - transport: { getPtyId: () => null, abandonPreconnectInput: vi.fn() }, - startFreshSpawn: vi.fn(async () => (outcome === 'attach-failed' ? null : 'pty')), - settlePaneAttachAttempt: vi.fn(), - enterSpawnDeferredSleep: vi.fn(), - showSessionRestoredBanner: vi.fn() - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: fixture supplies every field the main resume helper and owner selector read. - const session = fixture as unknown as ConnectPanePtySession - const owner = { worktreeId: 'wt-1', tabId: 'tab-1', leafId: pane.leafId } - expect(mainResumedSleepPane(session, startup)).toEqual(owner) - expect( - mainResumedSleepPane({ ...session, runtimeEnvironmentId: 'paired' }, startup) - ).toBeNull() - expect(mainResumedSleepPane(session, { ...startup, useLiveEntry: true })).toBeNull() - expect( - mainResumedSleepPane(session, { - ...startup, - sleepingRecordEntry: { - paneKey, - record: { ...startup.sleepingRecordEntry.record, origin: 'quit' } - } - }) - ).toBeNull() - expect( - mainResumedSleepPane(session, { - ...startup, - sleepingRecordEntry: { - paneKey, - record: { ...startup.sleepingRecordEntry.record, tabId: 'web-terminal-remote' } - } - }) - ).toBeNull() - if (outcome === 'false') { - const { installSpawnDeferredSleep } = await import('./pty-connection/spawn-deferred-sleep') - installSpawnDeferredSleep(session) - const { launchConfig: _launchConfig, ...withoutConfig } = startup - session.deferredSpawn = { reason: 'live_cap', startupOverride: withoutConfig, options: {} } - session.spawnColdRestoreAgentResume = vi.fn(async () => null) - await session.resumeDeferredSpawn() - expect(session.spawnColdRestoreAgentResume).toHaveBeenCalledWith(withoutConfig, {}, false) - session.disposeSpawnDeferral() - session.enterSpawnDeferredSleep = vi.fn() - } - const running = attachToMainResumedSleepPane( - session, - owner, - startup, - {}, - outcome === 'sleeping' || outcome === 'automatic-false' - ) - if (outcome.startsWith('cancel')) { - source.cancelled = true - } - if (outcome.startsWith('dispose')) { - fixture.disposed = true - } - if (outcome === 'teardown-refused') { - mockStoreState.deleteStateByWorktreeId = { - 'wt-1': { isDeleting: true } - } - } - if (outcome === 'superseded') { - fixture.transportStreamGeneration += 1 - } - // A real Electron rejection is delivered through the same pending operation. - if (outcome === 'generic' || outcome === 'sleeping' || outcome.endsWith('-refused')) { - refuse( - new Error( - `Error invoking remote method 'worktrees:resumeSleptPane': Error: ${outcome === 'sleeping' ? 'worktree_terminals_sleeping' : outcome.endsWith('-refused') ? 'terminal_spawn_deferred:live_cap' : 'terminal_not_started'}` - ) - ) - } else { - land(outcome !== 'false' && outcome !== 'automatic-false') - } - await running - expect(fixture.startFreshSpawn).toHaveBeenCalledTimes( - ['false', 'generic', 'attach-failed'].includes(outcome) ? 1 : 0 - ) - expect(fixture.showSessionRestoredBanner).not.toHaveBeenCalled() - expect(fixture.enterSpawnDeferredSleep).not.toHaveBeenCalled() - expect(mockStoreState.clearSleepingAgentSession).not.toHaveBeenCalled() - } - }) - it('keeps the pane sleeping with its resume handle and resumes it when opened', async () => { const { connectPanePty } = await import('./pty-connection') const { getPaneSpawnDeferral } = await import('@/lib/pane-spawn-deferral-registry') diff --git a/src/renderer/src/components/terminal-pane/pty-connection/deferred-cold-restore-and-snapshot.ts b/src/renderer/src/components/terminal-pane/pty-connection/deferred-cold-restore-and-snapshot.ts index e35657a5dbbd..593f10738d68 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/deferred-cold-restore-and-snapshot.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/deferred-cold-restore-and-snapshot.ts @@ -85,15 +85,19 @@ export function bindDeferredColdRestoreAndSnapshot(session: ConnectPanePtySessio // Why ungated: a reveal, a restart replacement on show, or a phone wake already chose to run now. session.spawnColdRestoreAgentResume = ( startup: ColdRestoreAgentResumeStartup | null = session.buildColdRestoreAgentResumeStartup(), - options: FreshSpawnOptions = {}, - automatic?: boolean + options: FreshSpawnOptions = {} ): Promise => { if (startup?.resumeSource?.cancelled) { return Promise.resolve(null) } const mainPane = mainResumedSleepPane(session, startup) if (mainPane && startup?.sleepingRecordEntry) { - return attachToMainResumedSleepPane(session, mainPane, startup, options, automatic) + return attachToMainResumedSleepPane( + session, + mainPane, + startup.sleepingRecordEntry.paneKey, + options + ) } return startPaneThroughMainThenAttach(session, () => { session.applyColdRestoreAgentResumeStartup(startup) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts b/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts index 8dcb9d9c6c1b..2abd01112ee4 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts @@ -22,34 +22,35 @@ import type { import type { ConnectPanePtySession } from './connect-pane-pty-session' import { findTerminalTabForPane } from './terminal-tab-id' -export function releaseDeferredCwdFence(session: ConnectPanePtySession): void { - if (!session.transport.getPtyId()) { - session.transport.abandonPreconnectInput?.() - try { - session.deps.onDeferredCwdSpawnFailed?.() - } catch { - // Cleanup must not turn a settled spawn into an unhandled rejection. - } - } -} - export function bindStartFreshSpawn(session: ConnectPanePtySession): void { session.startFreshSpawn = ( startupOverride?: PendingStartupCommand | null, options: FreshSpawnOptions = {} ): Promise => { + const releaseDeferredCwdFence = (): void => { + if (!session.transport.getPtyId()) { + // Abandoned spawns never connect; discard buffered input and settle its write promises here. + session.transport.abandonPreconnectInput?.() + try { + session.deps.onDeferredCwdSpawnFailed?.() + } catch { + // A cleanup callback must not turn a settled spawn into an unhandled rejection. + } + } + } + if ( hasWorktreeTeardownStarted( useAppStore.getState().deleteStateByWorktreeId?.[session.deps.worktreeId] ) ) { // Worktree deletion already killed its PTYs; skip respawn into the directory being removed instead of racing main’s fence. - releaseDeferredCwdFence(session) + releaseDeferredCwdFence() return Promise.resolve(null) } const effectiveStartup = startupOverride === undefined ? session.paneStartup : startupOverride if (effectiveStartup?.resumeSource?.cancelled) { - releaseDeferredCwdFence(session) + releaseDeferredCwdFence() return Promise.resolve(null) } session.authoritativeReattachGeneration += 1 @@ -144,6 +145,7 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { session.pendingSpawnDeferral = null if (deferral) { // Why before the launch-config cleanup below: a deferred launch is postponed, not dead. + releaseDeferredCwdFence() clearPreSignaledSerializer() session.finishReattachLiveDataDeferral(false, outputCallbacks.generation) session.enterSpawnDeferredSleep(deferral, startupOverride, options, visibleAtSpawn) @@ -179,7 +181,7 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { } if (!accepted) { // A rejected reattach ends this spawn; nothing later clears the fence. - releaseDeferredCwdFence(session) + releaseDeferredCwdFence() } return accepted ? resolvedPtyId : null } @@ -244,7 +246,7 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { session.reconcilePtySizeAfterSpawn(resolvedPtyId, session.cols, session.rows) } if (!resolvedPtyId) { - releaseDeferredCwdFence(session) + releaseDeferredCwdFence() clearPreSignaledSerializer() session.finishReattachLiveDataDeferral(false, outputCallbacks.generation) return null @@ -267,7 +269,7 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { if (!ownerRefused && isPaneOwnerRefusal(message)) { outputCallbacks.callbacks.onError(message) } - releaseDeferredCwdFence(session) + releaseDeferredCwdFence() session.finishReattachLiveDataDeferral(false, outputCallbacks.generation) if ( session.paneStartup?.launchConfig || @@ -308,6 +310,7 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { } if (session.deferredSpawn) { // Why no remount: the host would defer the remount's restore again, in a loop. + session.settlePaneAttachAttempt?.('failed') return } settleSpawnThatLeftPaneUnbound(session) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/main-resumed-sleep-pane.ts b/src/renderer/src/components/terminal-pane/pty-connection/main-resumed-sleep-pane.ts index c51df2a9e976..3aea67d5b1df 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/main-resumed-sleep-pane.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/main-resumed-sleep-pane.ts @@ -1,10 +1,6 @@ // A slept workspace's pane: main resumes its agent, and this window only attaches to that terminal. import { useAppStore } from '@/store' -import { hasWorktreeTeardownStarted } from '@/store/slices/worktree-delete-state-types' -import { readTerminalSpawnDeferral } from '../../../../../shared/host-spawn-admission' -import { releaseDeferredCwdFence } from './fresh-spawn-start' -import { findTerminalTabForPane } from './terminal-tab-id' import { isHostMirroredSleepingRecord } from '@/lib/host-mirrored-pane-liveness' import { parsePaneKey } from '../../../../../shared/stable-pane-id' import { isWorkspaceSleepRecord } from '../../../../../shared/workspace-sleep' @@ -35,52 +31,18 @@ export function mainResumedSleepPane( export async function attachToMainResumedSleepPane( session: ConnectPanePtySession, pane: { worktreeId: string; tabId: string; leafId: string }, - startup: ColdRestoreAgentResumeStartup, - options: FreshSpawnOptions, - automatic?: boolean + paneKey: string, + options: FreshSpawnOptions ): Promise { - const generation = session.transportStreamGeneration - const isCurrent = (): boolean => - !session.disposed && - !hasWorktreeTeardownStarted( - useAppStore.getState().deleteStateByWorktreeId?.[pane.worktreeId] - ) && - !startup.resumeSource?.cancelled && - (startup.isCurrent?.() ?? true) && - (findTerminalTabForPane(useAppStore.getState(), pane.worktreeId, pane.tabId)?.generation ?? - 0) === session.tabGeneration - if (!isCurrent()) { - return null - } - const visibleAtSpawn = session.deps.isVisibleRef.current === true - let resumed = false - try { - resumed = await window.api.worktrees.resumeSleptPane(pane, automatic) - } catch (error: unknown) { - if (!isCurrent() || generation !== session.transportStreamGeneration) { - return null - } - const deferral = readTerminalSpawnDeferral(error) - if (deferral) { - session.enterSpawnDeferredSleep(deferral, startup, options, visibleAtSpawn) - return null - } - } - if (!isCurrent() || generation !== session.transportStreamGeneration) { - return null - } - if (automatic && !resumed) { - releaseDeferredCwdFence(session) - session.settlePaneAttachAttempt?.('failed') + const resumed = await window.api.worktrees.resumeSleptPane(pane).catch(() => false) + if (session.disposed) { return null } const ptyId = await session.startFreshSpawn(null, options) - if (isCurrent() && resumed && ptyId) { + if (resumed && ptyId) { session.showSessionRestoredBanner() // Main keeps its record; the window's mirror of it is spent. - if (startup.sleepingRecordEntry) { - useAppStore.getState().clearSleepingAgentSession(startup.sleepingRecordEntry.paneKey) - } + useAppStore.getState().clearSleepingAgentSession(paneKey) } return ptyId } diff --git a/src/renderer/src/components/terminal-pane/pty-connection/spawn-deferred-sleep.ts b/src/renderer/src/components/terminal-pane/pty-connection/spawn-deferred-sleep.ts index d481af74d855..0f3232297d41 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/spawn-deferred-sleep.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/spawn-deferred-sleep.ts @@ -1,5 +1,3 @@ -import { releaseDeferredCwdFence } from './fresh-spawn-start' -import { mainResumedSleepPane } from './main-resumed-sleep-pane' import { useAppStore } from '@/store' import { writeTerminalOutput } from '@/lib/pane-manager/pane-terminal-output-scheduler' import type { SpawnDeferralReason } from '../../../../../shared/host-spawn-admission' @@ -45,13 +43,7 @@ type DeferredSpawn = { function isColdRestoreStartup( startup: PendingStartupCommand | null | undefined ): startup is ColdRestoreAgentResumeStartup { - return Boolean( - startup && - 'agent' in startup && - 'resumeProviderSession' in startup && - 'useLiveEntry' in startup && - 'sleepingRecordEntry' in startup - ) + return Boolean(startup && 'launchConfig' in startup && 'resumeProviderSession' in startup) } /** The record a deferred restore leaves behind, so the session stays listed and resumable even if @@ -176,7 +168,6 @@ export function installSpawnDeferredSleep(session: ConnectPanePtySession): void options: FreshSpawnOptions, visibleAtSpawn: boolean ): void => { - releaseDeferredCwdFence(session) session.keepUnrunResumeHandle(startupOverride) session.deferredSpawn = { reason, startupOverride, options } const deferral = { reason, resume: () => void session.resumeDeferredSpawn() } @@ -191,7 +182,6 @@ export function installSpawnDeferredSleep(session: ConnectPanePtySession): void async () => (await session.resumeDeferredSpawn().catch(() => null)) !== null ) } - session.settlePaneAttachAttempt?.('failed') if (!visibleAtSpawn) { // Why: a pane opened while its hidden restore was in flight resumes as the user's own. queueMicrotask(() => session.resumeDeferredSpawnOnReveal()) @@ -226,18 +216,9 @@ export function installSpawnDeferredSleep(session: ConnectPanePtySession): void clearPaneSpawnDeferral(session.cacheKey) } } - const startup = deferred.startupOverride - const spawned: Promise = - isColdRestoreStartup(startup) && mainResumedSleepPane(session, startup) - ? session.spawnColdRestoreAgentResume( - startup, - deferred.options, - session.deps.isVisibleRef.current !== true - ) - : startPaneThroughMainThenAttach(session, () => - session.startFreshSpawn(startup, deferred.options) - ) - return spawned.then( + return startPaneThroughMainThenAttach(session, () => + session.startFreshSpawn(deferred.startupOverride, deferred.options) + ).then( (ptyId: string | null) => { settle() return ptyId From 17c7d51ce5c3254062b2fb340c074c54b8b16598 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:43:19 -0700 Subject: [PATCH 09/15] Keep terminal limits effective when saved settings cannot be read --- src/main/daemon/daemon-server.ts | 42 ++-- src/main/daemon/daemon-terminal-limit.test.ts | 11 +- src/main/daemon/host-terminal-policy.test.ts | 203 ++++++++++++++---- src/main/daemon/host-terminal-policy.ts | 127 ++++++++--- src/main/daemon/terminal-spawn-gate.ts | 21 +- .../normalize-loaded-global-settings.test.ts | 10 + .../settings/TerminalLimitSetting.test.tsx | 38 +++- .../settings/TerminalLimitSetting.tsx | 18 +- src/renderer/src/i18n/locales/en.json | 1 + src/renderer/src/i18n/locales/es.json | 1 + src/renderer/src/i18n/locales/fr.json | 1 + src/renderer/src/i18n/locales/ja.json | 1 + src/renderer/src/i18n/locales/ko.json | 1 + src/renderer/src/i18n/locales/pt.json | 1 + src/renderer/src/i18n/locales/zh.json | 1 + src/shared/terminal-limit-policy.ts | 1 + 16 files changed, 360 insertions(+), 118 deletions(-) diff --git a/src/main/daemon/daemon-server.ts b/src/main/daemon/daemon-server.ts index e24ec3540480..5d22a888720c 100644 --- a/src/main/daemon/daemon-server.ts +++ b/src/main/daemon/daemon-server.ts @@ -113,14 +113,10 @@ export class DaemonServer { ) const protocolVersion = options.protocolVersion ?? PROTOCOL_VERSION - const launchNonce = - options.launchNonce ?? - (protocolVersion >= CLEAN_DISCONNECT_PROTOCOL_VERSION ? randomUUID() : null) + const hasIdentity = protocolVersion >= CLEAN_DISCONNECT_PROTOCOL_VERSION + const launchNonce = options.launchNonce ?? (hasIdentity ? randomUUID() : null) const startedAtMs = - options.startedAtMs ?? - (protocolVersion >= CLEAN_DISCONNECT_PROTOCOL_VERSION - ? Date.now() - process.uptime() * 1000 - : null) + options.startedAtMs ?? (hasIdentity ? Date.now() - process.uptime() * 1000 : null) this.terminalPolicyNonce = launchNonce ?? randomUUID() const token = randomUUID() @@ -182,11 +178,7 @@ export class DaemonServer { onOwnershipLost: () => this.lifecycle.onEndpointOwnershipLost() }) const lifecycleClock = options.initialAdoptionTestConfig?.clock ?? { - setTimeout: (callback: () => void, delayMs: number) => { - const timer = setTimeout(callback, delayMs) - timer.unref() - return timer - }, + setTimeout: (callback: () => void, delayMs: number) => setTimeout(callback, delayMs).unref(), clearTimeout: (handle: unknown) => clearTimeout(handle as ReturnType), now: () => Date.now() } @@ -246,7 +238,16 @@ export class DaemonServer { } async start(): Promise { - await this.lifecycle.start((socket) => this.connections.accept(socket)) + await this.terminalPolicy.start((event, details) => this.log.log(event, details)) + if (!this.lifecycle.isAcceptingWork()) { + return + } + try { + await this.lifecycle.start((socket) => this.connections.accept(socket)) + } catch (error) { + this.terminalPolicy.dispose() + throw error + } // Only the endpoint winner may inspect or rewrite the automatic-work marker. this.automaticWork.start() } @@ -266,6 +267,7 @@ export class DaemonServer { } private async disposeResources(): Promise { + this.terminalPolicy.dispose() this.endpoint.stopOwnershipWatch() this.stopStreamBacklogProbe() this.transientFactRelay.dispose() @@ -294,19 +296,15 @@ export class DaemonServer { return answerDaemonControlRequest( socket, request, - async () => { - const limitRequest = answerTerminalLimitRequest( + async () => + answerTerminalLimitRequest( request, this.terminalPolicy, this.terminalPolicyNonce, () => this.lifecycle.isAcceptingWork() && !this.endpoint.hasLostOwnership() - ) - return ( - limitRequest ?? - answerAutomaticWorkRequest(request, this.automaticWork, this.endpoint) ?? - this.requestRouter.route(clientId, request) - ) - }, + ) ?? + answerAutomaticWorkRequest(request, this.automaticWork, this.endpoint) ?? + this.requestRouter.route(clientId, request), () => this.lifecycle.startPendingShutdownReply(clientId, request.id) ) } diff --git a/src/main/daemon/daemon-terminal-limit.test.ts b/src/main/daemon/daemon-terminal-limit.test.ts index 2c6b48409cd7..cb1b36203961 100644 --- a/src/main/daemon/daemon-terminal-limit.test.ts +++ b/src/main/daemon/daemon-terminal-limit.test.ts @@ -36,6 +36,8 @@ afterEach(async () => { it('reads and saves on the attached daemon socket, refusing stale identity and lost endpoint writes', async () => { directory = mkdtempSync(join(tmpdir(), 'terminal-limit-rpc-')) const path = join(directory, 'policy', 'terminals.json') + await fs.mkdir(join(directory, 'policy'), { mode: 0o700 }) + await fs.writeFile(path, 'invalid JSON') server = new DaemonServer({ socketPath: getDaemonSocketPath(directory), tokenPath: join(directory, 'token'), @@ -53,8 +55,15 @@ it('reads and saves on the attached daemon socket, refusing stale identity and l maxTerminals: 256, systemPtyLimit: 511, source: 'default', - editable: true + editable: true, + savedUnreadable: true }) + const repaired = await client.request('setTerminalLimit', { + daemonNonce: before.daemonNonce, + maxTerminals: 256 + }) + expect(repaired.maxTerminals).toBe(256) + expect(repaired.savedUnreadable).toBeUndefined() const update = { daemonNonce: before.daemonNonce, maxTerminals: 384 } await expect(client.request('setTerminalLimit', update)).resolves.toMatchObject({ maxTerminals: 384, diff --git a/src/main/daemon/host-terminal-policy.test.ts b/src/main/daemon/host-terminal-policy.test.ts index 575f2ea3368e..b27beebce3d1 100644 --- a/src/main/daemon/host-terminal-policy.test.ts +++ b/src/main/daemon/host-terminal-policy.test.ts @@ -1,13 +1,17 @@ import type * as FileSystem from 'node:fs/promises' -import { mkdtemp, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises' +import { mkdtemp, readdir, rename, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { HostTerminalPolicy, hostTerminalPolicyPath } from './host-terminal-policy' import { SystemPtyLimit, parseLinuxPtyLimit } from './system-pty-limit' +import * as deadlines from './daemon-request-deadline' import { HostTerminalLedger } from './host-terminal-ledger' import { TerminalSpawnGate } from './terminal-spawn-gate' -import type { SpawnRequestFacts } from '../../shared/host-spawn-admission' +import { + DEFAULT_SPAWN_ADMISSION_LIMITS, + type SpawnRequestFacts +} from '../../shared/host-spawn-admission' vi.mock('node:fs/promises', async (original) => { const fs = await original() @@ -32,8 +36,17 @@ const facts: SpawnRequestFacts = { deadlineAt: Number.POSITIVE_INFINITY } const system = () => new SystemPtyLimit(async () => 511) +const policies: HostTerminalPolicy[] = [] +function createPolicy( + ...args: ConstructorParameters +): HostTerminalPolicy { + const value = new HostTerminalPolicy(...args) + policies.push(value) + return value +} const directories: string[] = [] afterEach(async () => { + policies.splice(0).forEach((value) => value.dispose()) vi.useRealTimers() await Promise.all( directories.splice(0).map((path) => fs.rm(path, { recursive: true, force: true })) @@ -51,8 +64,9 @@ describe('host terminal policy', () => { it('shares live raises and decreases across daemons and retains the policy after reconstruction', async () => { const root = await home() const path = hostTerminalPolicyPath(root, 'machine-a') - const first = new HostTerminalPolicy(path, {}, system()) - const second = new HostTerminalPolicy(path, {}, system()) + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }) + const first = createPolicy(path, {}, system()) + const second = createPolicy(path, {}, system()) const gate = (policy: HostTerminalPolicy, pid: number) => new TerminalSpawnGate({ log: vi.fn(), @@ -65,23 +79,35 @@ describe('host terminal policy', () => { log: vi.fn() }) }) + const log = vi.fn() + await Promise.all([first.start(log), second.start()]) + expect(log).not.toHaveBeenCalled() const desktop = gate(first, 100) const server = gate(second, 200) await first.save(1, () => true) const running = await desktop.admit(facts) running.commit('existing-shell', true) - await expect(server.admit(facts)).rejects.toThrow() + await vi.advanceTimersByTimeAsync(3_000) + await vi.waitFor(() => expect(second.admissionMaximum()).toBe(first.admissionMaximum())) + expect(() => server.admit(facts)).toThrow() await first.save(2, () => true) + expect(first.admissionMaximum()).toBe(2) + expect(second.admissionMaximum()).toBe(1) + await vi.advanceTimersByTimeAsync(3_000) + await vi.waitFor(() => expect(second.admissionMaximum()).toBe(2)) const setup = await server.admit(facts) setup.commit('setup-script', true) await first.save(1, () => true) - await expect(server.admit(facts)).rejects.toThrow() + await vi.advanceTimersByTimeAsync(3_000) + await vi.waitFor(() => expect(second.admissionMaximum()).toBe(first.admissionMaximum())) + expect(() => server.admit(facts)).toThrow() expect(desktop.snapshot().terminals).toBe(1) expect(server.snapshot().terminals).toBe(1) - const restarted = new HostTerminalPolicy(path, {}, system()) - expect(await restarted.admissionMaximum()).toBe(1) + const restarted = createPolicy(path, {}, system()) + await restarted.start() + expect(restarted.admissionMaximum()).toBe(1) desktop.onSessionExit('existing-shell') - await expect(server.admit(facts)).rejects.toThrow() + expect(() => server.admit(facts)).toThrow() server.onSessionExit('setup-script') const next = await server.admit(facts) next.abandon() @@ -94,7 +120,7 @@ describe('host terminal policy', () => { const path = hostTerminalPolicyPath(root, 'machine-a') expect(path).not.toBe(hostTerminalPolicyPath(root, 'machine-b')) expect(hostTerminalPolicyPath(root, null)).toBeNull() - const policy = new HostTerminalPolicy(path, {}, system()) + const policy = createPolicy(path, {}, system()) await expect(policy.save(512, () => true)).rejects.toThrow('capacity') await policy.save(384, () => true) expect(await policy.status('nonce')).toMatchObject({ @@ -102,60 +128,141 @@ describe('host terminal policy', () => { source: 'saved', systemPtyLimit: 511 }) - const override = new HostTerminalPolicy( - path, - { ORCA_DAEMON_MAX_HOST_TERMINALS: '600' }, - system() - ) + const read = vi.fn() + const override = createPolicy(path, { ORCA_DAEMON_MAX_HOST_TERMINALS: '600' }, system(), read) + await override.start() + expect(read).not.toHaveBeenCalled() expect(await override.status('nonce')).toMatchObject({ maxTerminals: 600, source: 'environment', editable: false }) await expect(override.save(20, () => true)).rejects.toThrow('unavailable') - const unidentified = new HostTerminalPolicy(null, {}, system()) + const unidentified = createPolicy(null, {}, system()) expect(await unidentified.status('nonce')).toMatchObject({ maxTerminals: 256, editable: false }) await expect(unidentified.save(10, () => true)).rejects.toThrow() - const reduced = new HostTerminalPolicy(path, {}, new SystemPtyLimit(async () => 128)) + const reduced = createPolicy(path, {}, new SystemPtyLimit(async () => 128)) + await reduced.start() expect(await reduced.status('nonce')).toMatchObject({ maxTerminals: 384, systemPtyLimit: 128 }) - const defaults = new HostTerminalPolicy(null, {}, new SystemPtyLimit(async () => 128)) + const defaults = createPolicy(null, {}, new SystemPtyLimit(async () => 128)) expect(await defaults.status('nonce')).toMatchObject({ maxTerminals: 256, systemPtyLimit: 128 }) }) - it('bounds admission wait while retaining one stalled underlying read', async () => { - vi.useFakeTimers() - const read = vi.fn(() => new Promise(() => {})) - const policy = new HostTerminalPolicy('/unreachable/terminal-policy', {}, system(), read) - const attempts = Promise.all([policy.admissionMaximum(), policy.admissionMaximum()]) - await vi.advanceTimersByTimeAsync(251) - expect(await attempts).toEqual([256, 256]) - const retry = policy.admissionMaximum() - await vi.advanceTimersByTimeAsync(251) - expect(await retry).toBe(256) - expect(read).toHaveBeenCalledOnce() - }) - - it('drains a held admission snapshot after replacement before confirming the saved value', async () => { + it('bounds shared startup and retains one raw read/observer across ticks, admissions and saves', async () => { const path = join(await home(), 'policy.json') + vi.useFakeTimers() const old = deferred() const read = vi .fn() .mockImplementationOnce(() => old.promise) - .mockImplementation(async () => JSON.parse(await readFile(path, 'utf8')).maxTerminals) - const policy = new HostTerminalPolicy(path, {}, system(), read) - const admission = policy.admissionMaximum() - const replaced = deferred() - vi.mocked(rename).mockImplementationOnce(async (...args) => { - await fs.rename(...args) - replaced.resolve() + .mockResolvedValue(384) + const value = createPolicy(path, {}, system(), read) + const observed = vi.spyOn(deadlines, 'awaitDaemonValueWithinCallerDeadline') + const startup = value.start() + expect(value.start()).toBe(startup) + await vi.advanceTimersByTimeAsync(251) + await startup + expect(await value.status('nonce')).toMatchObject({ maxTerminals: 256, savedUnreadable: true }) + expect(await value.save(384, () => true)).toMatchObject({ maxTerminals: 384 }) + const observers = observed.mock.calls.length + const maximum = vi.fn(() => value.admissionMaximum()) + const gate = new TerminalSpawnGate({ + log: vi.fn(), + mode: 'enforce', + limits: { ...DEFAULT_SPAWN_ADMISSION_LIMITS, automaticConcurrency: 1 }, + resolveMaximum: maximum + }) + for (const n of [30, 300]) { + for (let i = 0; i < n; i++) { + const lease = gate.admit(facts) + if (lease instanceof Promise) { + throw new Error('Admission must be synchronous') + } + lease.commit(`${n}-${i}`, true) + } + await vi.advanceTimersByTimeAsync(30_000) + expect(read).toHaveBeenCalledOnce() + expect(observed).toHaveBeenCalledTimes(observers) + } + expect(gate.snapshot().terminals).toBe(330) + const automatic = { ...facts, declaredIntent: 'automatic-restore' as const } + const first = await gate.admit(automatic) + const waiting = gate.admit(automatic) + expect(waiting).toBeInstanceOf(Promise) + expect(gate.snapshot().waiting).toBe(1) + const beforeWake = maximum.mock.calls.length + first.commit('first', true) + const next = await waiting + next.commit('next', true) + gate.onSessionExit('first') + gate.onSessionExit('next') + expect(maximum).toHaveBeenCalledTimes(beforeWake + 1) + expect(maximum.mock.results.at(-1)?.value).toBe(384) + expect(read).toHaveBeenCalledOnce() + expect(gate.snapshot()).toMatchObject({ + terminals: 330, + waiting: 0, + inFlight: { automatic: 0 } }) - const save = policy.save(3, () => true, 'nonce') - await replaced.promise - await new Promise(setImmediate) old.resolve(2) - expect(await admission).toBe(2) - expect(await save).toMatchObject({ maxTerminals: 3, source: 'saved', daemonNonce: 'nonce' }) + await vi.advanceTimersByTimeAsync(0) + expect(value.admissionMaximum()).toBe(384) expect(read).toHaveBeenCalledTimes(2) + value.dispose() + await vi.advanceTimersByTimeAsync(30_000) + expect(read).toHaveBeenCalledTimes(2) + }) + + it('retains last good through failures, fences stale reads against save and disposal, and recovers', async () => { + const path = join(await home(), 'policy.json') + vi.useFakeTimers() + const held = deferred() + const read = vi.fn<() => Promise>().mockResolvedValue(384) + const value = createPolicy(path, {}, system(), read) + const log = vi.fn() + await value.start(log) + read.mockRejectedValue(new SyntaxError('Invalid JSON')) + await vi.advanceTimersByTimeAsync(6_000) + read.mockRejectedValue(Object.assign(new Error('denied'), { code: 'EACCES' })) + await vi.advanceTimersByTimeAsync(3_000) + read.mockResolvedValue(null) + await vi.advanceTimersByTimeAsync(3_000) + read.mockReturnValue(held.promise) + await vi.advanceTimersByTimeAsync(3_251) + expect(value.admissionMaximum()).toBe(384) + expect(await value.status('nonce')).toMatchObject({ + maxTerminals: 384, + source: 'saved', + savedUnreadable: true, + editable: true + }) + expect(log).toHaveBeenCalledTimes(1) + held.resolve(2) + read.mockResolvedValue(400) + await vi.advanceTimersByTimeAsync(3_000) + const recovered = await value.status('nonce') + expect(recovered.maxTerminals).toBe(400) + expect(recovered.savedUnreadable).toBeUndefined() + expect(log.mock.calls.map(([event]) => event)).toEqual([ + 'terminal-policy-read-failed', + 'terminal-policy-read-recovered' + ]) + const stale = deferred() + read.mockReturnValueOnce(stale.promise).mockResolvedValue(384) + await vi.advanceTimersToNextTimerAsync() + expect(await value.save(384, () => true)).toMatchObject({ maxTerminals: 384 }) + stale.resolve(2) + await vi.advanceTimersByTimeAsync(0) + expect(value.admissionMaximum()).toBe(384) + const late = deferred() + read.mockReturnValue(late.promise) + await vi.advanceTimersToNextTimerAsync() + value.dispose() + const count = read.mock.calls.length + late.resolve(2) + await vi.advanceTimersByTimeAsync(30_000) + expect(read).toHaveBeenCalledTimes(count) + expect(value.admissionMaximum()).toBe(384) }) it('expires staging without a late rename or orphan, and permits retry while cleanup stalls', async () => { @@ -183,7 +290,7 @@ describe('host terminal policy', () => { } }) vi.useFakeTimers() - const policy = new HostTerminalPolicy(path, {}, system()) + const policy = createPolicy(path, {}, system()) const save = policy.save(10, () => true) const failed = expect(save).rejects.toThrow('confirm') await started.promise @@ -226,7 +333,7 @@ describe('host terminal policy', () => { cleaned.resolve() } }) - const policy = new HostTerminalPolicy(path, {}, system()) + const policy = createPolicy(path, {}, system()) vi.useFakeTimers() const save = policy.save(10, () => true) const failed = expect(save).rejects.toThrow('confirm') @@ -243,7 +350,9 @@ describe('host terminal policy', () => { } finally { Object.defineProperty(process, 'platform', { configurable: true, value: platform }) } - expect(await policy.admissionMaximum()).toBe(outcome === 'completed' ? 10 : 20) + await vi.waitFor(() => + expect(policy.admissionMaximum()).toBe(outcome === 'completed' ? 10 : 20) + ) expect(rename).toHaveBeenCalledTimes(2) } ) diff --git a/src/main/daemon/host-terminal-policy.ts b/src/main/daemon/host-terminal-policy.ts index 60e21f36a4bf..19ee4e0ba25d 100644 --- a/src/main/daemon/host-terminal-policy.ts +++ b/src/main/daemon/host-terminal-policy.ts @@ -2,7 +2,6 @@ import { createHash, randomUUID } from 'node:crypto' import { lstat, mkdir, rm, writeFile } from 'node:fs/promises' import { homedir } from 'node:os' import { dirname, join } from 'node:path' -import { InFlightPromiseDedupe } from '../../shared/in-flight-promise-dedupe' import { readNodeFileWithinLimit } from '../../shared/node-bounded-file-reader' import { renameFileWithWindowsRetryAsync } from '../../shared/windows-retry-file-operations' import { @@ -92,7 +91,14 @@ async function withPolicyOperation( } export class HostTerminalPolicy { - private readonly reads = new InFlightPromiseDedupe(0, 1) + private savedMaximum: number | null = null + private savedUnreadable = false + private revision = 0 + private disposed = false + private reading = false + private initialization?: Promise + private timer?: ReturnType + private log: (event: string, details: Record) => void = () => {} private readonly environment: number | null constructor( @@ -111,32 +117,83 @@ export class HostTerminalPolicy { : null } - private saved(): Promise { + start(log = this.log): Promise { + this.log = log + return (this.initialization ??= this.refresh().then(() => { + if (!this.disposed && this.path && this.environment === null) { + this.timer = setInterval(() => void this.refresh(), 3_000) + this.timer.unref?.() + } + })) + } + + dispose(): void { + this.disposed = true + this.revision += 1 + clearInterval(this.timer) + } + + private async refresh(): Promise { + if (this.disposed || this.reading || !this.path || this.environment !== null) { + return + } const path = this.path - return path ? this.reads.run('policy', () => this.readSaved(path)) : Promise.resolve(null) + const revision = this.revision + this.reading = true + const raw = Promise.resolve().then(() => this.readSaved(path)) + void raw + .finally(() => { + this.reading = false + if (revision !== this.revision) { + void this.refresh() + } + }) + .catch(() => undefined) + try { + const read = await awaitDaemonValueWithinCallerDeadline(raw, Date.now() + 250) + if (this.disposed || revision !== this.revision) { + return + } + if (!read.completed || (read.value === null && this.savedMaximum !== null)) { + throw new Error('Saved terminal limit unavailable') + } + this.savedMaximum = read.value + this.setReadHealth(false) + } catch { + if (!this.disposed && revision === this.revision) { + this.setReadHealth(true) + } + } } - async admissionMaximum(): Promise { - if (this.environment !== null) { - return this.environment + private setReadHealth(failed: boolean): void { + if (failed === this.savedUnreadable) { + return } + this.savedUnreadable = failed try { - const read = await awaitDaemonValueWithinCallerDeadline(this.saved(), Date.now() + 250) - return (read.completed ? read.value : null) ?? DEFAULT_MAX_HOST_TERMINALS + this.log(failed ? 'terminal-policy-read-failed' : 'terminal-policy-read-recovered', { + maxTerminals: this.admissionMaximum() + }) } catch { - // Settings storage cannot prevent a user from starting a terminal. - return DEFAULT_MAX_HOST_TERMINALS + // Diagnostics cannot change the applied limit. } } - private observedStatus( - saved: number | null, - systemPtyLimit: number | null, - daemonNonce: string - ): TerminalLimitStatus { + admissionMaximum(): number { + return this.environment ?? this.savedMaximum ?? DEFAULT_MAX_HOST_TERMINALS + } + + private observedStatus(systemPtyLimit: number | null, daemonNonce: string): TerminalLimitStatus { return { - maxTerminals: this.environment ?? saved ?? DEFAULT_MAX_HOST_TERMINALS, - source: this.environment !== null ? 'environment' : saved !== null ? 'saved' : 'default', + maxTerminals: this.admissionMaximum(), + source: + this.environment !== null + ? 'environment' + : this.savedMaximum !== null + ? 'saved' + : 'default', + ...(this.savedUnreadable ? { savedUnreadable: true } : {}), systemPtyLimit, editable: this.environment === null && this.path !== null, daemonNonce @@ -149,13 +206,8 @@ export class HostTerminalPolicy { deadline = Date.now() + 2_000 ): Promise { return withPolicyOperation(isCurrent, deadline, async (operation) => { - const [saved, systemPtyLimit] = await operation.wait(() => - Promise.all([ - this.environment === null ? this.saved() : Promise.resolve(null), - this.system.read() - ]) - ) - return this.observedStatus(saved, systemPtyLimit, daemonNonce) + const systemPtyLimit = await operation.wait(() => this.system.read()) + return this.observedStatus(systemPtyLimit, daemonNonce) }) } @@ -165,7 +217,9 @@ export class HostTerminalPolicy { daemonNonce = '', deadline = Date.now() + 2_000 ): Promise { - return withPolicyOperation(isCurrent, deadline, async (operation) => { + this.revision += 1 + const current = (): boolean => !this.disposed && isCurrent() + return withPolicyOperation(current, deadline, async (operation) => { const path = this.path if (!path || this.environment !== null) { throw new Error('Terminal setting unavailable') @@ -198,16 +252,25 @@ export class HostTerminalPolicy { }) const replaced = await operation.wait(() => { const rename = renameFileWithWindowsRetryAsync(temporary, path, operation.isCurrent) - staging = rename - return rename + const committed = rename.then((replaced) => { + if (replaced && !this.disposed) { + this.revision += 1 + if (operation.isCurrent()) { + this.savedMaximum = maximum + this.setReadHealth(false) + } else { + void this.refresh() + } + } + return replaced + }) + staging = committed + return committed }) if (!replaced) { throw new Error('Terminal host changed') } - // Drain pre-replacement observations without evicting their raw I/O. - await operation.wait(() => this.saved().catch(() => null)) - const saved = await operation.wait(() => this.saved()) - return this.observedStatus(saved, systemPtyLimit, daemonNonce) + return this.observedStatus(systemPtyLimit, daemonNonce) } finally { // A late staging write must settle before removal can consume its temporary file. void staging diff --git a/src/main/daemon/terminal-spawn-gate.ts b/src/main/daemon/terminal-spawn-gate.ts index 3cb81dd796b2..769205808988 100644 --- a/src/main/daemon/terminal-spawn-gate.ts +++ b/src/main/daemon/terminal-spawn-gate.ts @@ -68,7 +68,7 @@ type TerminalSpawnGateOptions = { /** Runs synchronously before the first automatic fork is admitted. */ armAutomaticWork?: () => void /** The execution host's terminal cap; defaults to capping this daemon alone. */ - resolveMaximum?: () => Promise + resolveMaximum?: () => number hostTerminals?: HostTerminalLedger /** Retain refused restores for clients that already discarded their own resume records. */ legacyRestores?: LegacyRestoreRecords @@ -109,7 +109,7 @@ export class TerminalSpawnGate { ) } - /** A maximum resolver or paced wait adds an async boundary; callers recheck shutdown after await. */ + /** Only pacing adds an async boundary; callers recheck shutdown after await. */ admit( facts: SpawnRequestFacts, cancel?: { signal: AbortSignal; error: () => Error }, @@ -117,13 +117,11 @@ export class TerminalSpawnGate { ): TerminalSpawnLease | Promise { return admitRecordingLegacyRestore( () => { - const admit = (maximum?: number): TerminalSpawnLease | Promise => { - const attempt = this.attempt(facts, cancel, false, maximum) - return attempt.kind === 'lease' - ? attempt.lease - : this.admitAfterWait(facts, cancel, attempt) - } - return this.options.resolveMaximum ? this.options.resolveMaximum().then(admit) : admit() + const maximum = this.options.resolveMaximum?.() ?? this.host.maxTerminals + const attempt = this.attempt(facts, cancel, false, maximum) + return attempt.kind === 'lease' + ? attempt.lease + : this.admitAfterWait(facts, cancel, attempt) }, this.options.legacyRestores, facts, @@ -139,7 +137,8 @@ export class TerminalSpawnGate { let attempt: ReturnType = first while (attempt.kind === 'wait') { await this.waiters.waitForChange(attempt.untilMs, cancel?.signal) - attempt = this.attempt(facts, cancel, true, await this.options.resolveMaximum?.()) + const maximum = this.options.resolveMaximum?.() ?? this.host.maxTerminals + attempt = this.attempt(facts, cancel, true, maximum) } return attempt.lease } @@ -148,7 +147,7 @@ export class TerminalSpawnGate { facts: SpawnRequestFacts, cancel: { signal: AbortSignal; error: () => Error } | undefined, alreadyWaited: boolean, - maximum = this.host.maxTerminals + maximum: number ): { kind: 'lease'; lease: TerminalSpawnLease } | { kind: 'wait'; untilMs: number } { if (cancel?.signal.aborted) { throw cancel.error() diff --git a/src/main/persistence/loading-store/normalize-loaded-global-settings.test.ts b/src/main/persistence/loading-store/normalize-loaded-global-settings.test.ts index 402eb9f4a638..6fae9ae35248 100644 --- a/src/main/persistence/loading-store/normalize-loaded-global-settings.test.ts +++ b/src/main/persistence/loading-store/normalize-loaded-global-settings.test.ts @@ -310,3 +310,13 @@ describe('terminal default shell', () => { expect(normalizeLegacyProfile({ terminalDefaultShell: ' ' }).terminalDefaultShell).toBe('') }) }) + +it('loads an existing profile without a terminal policy mirror and preserves its saved preferences', () => { + const loaded = normalizeLegacyProfile({ + terminalFocusFollowsMouse: true, + machineName: 'Build server' + }) + expect(loaded.terminalFocusFollowsMouse).toBe(true) + expect(loaded.machineName).toBe('Build server') + expect(loaded).not.toHaveProperty('maxTerminals') +}) diff --git a/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx b/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx index fe0bbe3d074f..ba7d1c68e379 100644 --- a/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx +++ b/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx @@ -4,6 +4,7 @@ import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { TerminalLimitSetting } from './TerminalLimitSetting' import { readTerminalLimit, saveTerminalLimit } from './terminal-limit-transport' +import type * as TerminalLimitTransport from './terminal-limit-transport' import type { SettingsHostScope } from './settings-host-scope' import type { TerminalLimitStatus } from '../../../../shared/terminal-limit-policy' import { useAppStore } from '@/store' @@ -11,8 +12,10 @@ import { i18n } from '@/i18n/i18n' import { getTerminalAdvancedSearchEntries } from './terminal-advanced-platform-search' import { matchesSettingsSearch } from './settings-search' import type { RuntimeStatus } from '../../../../shared/runtime-types' +import { callHostRoute } from '@/runtime/host-route-call' import { advanceRuntimeEnvironmentConnectionGeneration } from '@/store/slices/runtime-status-connection-generation' +vi.mock('@/runtime/host-route-call', () => ({ callHostRoute: vi.fn() })) vi.mock('./terminal-limit-transport', () => ({ readTerminalLimit: vi.fn(), saveTerminalLimit: vi.fn() @@ -94,7 +97,7 @@ it('clamps in the input, confirms Enter and blur saves once, and omits the capti expect(input().value).toBe('256') expect(input().max).toBe('511') expect(container.textContent).toContain('System PTY limit: 511') - expect(container.textContent).not.toMatch(/Reset|Default:|1–511/) + expect(container.textContent).not.toMatch(/Reset|Default:|1–511|Couldn’t read/) await type('9999') expect(input().value).toBe('511') await enter() @@ -240,3 +243,36 @@ it('finds localized capacity in both the catalog and the rendered row filter', a await render() expect(container.querySelector('input')).toBeNull() }) + +it.each([256, 384])( + 'repairs an unreadable saved limit by committing %s, including the effective value', + async (maximum) => { + vi.mocked(readTerminalLimit).mockResolvedValue({ ...base, savedUnreadable: true }) + await render() + expect(input().disabled).toBe(false) + expect(container.textContent).toContain('Using 256') + await type(String(maximum)) + await enter() + expect(saveTerminalLimit).toHaveBeenCalledWith( + expect.anything(), + { maxTerminals: maximum, daemonNonce: 'daemon-a' }, + expect.any(AbortSignal) + ) + expect(input().value).toBe(String(maximum)) + expect(container.textContent).not.toContain('Couldn’t read') + } +) + +it('uses the selected-host transport and refuses unsupported capability without issuing a policy RPC', async () => { + const transport = await vi.importActual( + './terminal-limit-transport' + ) + const route = { + target: { kind: 'environment' as const, environmentId: 'old-server' }, + at: 'local' as const + } + const signal = new AbortController().signal + vi.mocked(callHostRoute).mockResolvedValue({ capabilities: [] }) + await expect(transport.readTerminalLimit(route, signal)).resolves.toBeNull() + expect(callHostRoute).toHaveBeenCalledExactlyOnceWith(route, 'status.get', undefined, { signal }) +}) diff --git a/src/renderer/src/components/settings/TerminalLimitSetting.tsx b/src/renderer/src/components/settings/TerminalLimitSetting.tsx index acf8db1330fd..0300c2a8e671 100644 --- a/src/renderer/src/components/settings/TerminalLimitSetting.tsx +++ b/src/renderer/src/components/settings/TerminalLimitSetting.tsx @@ -85,7 +85,7 @@ function TerminalLimitField({ scope }: { scope: SettingsHostScope }): React.JSX. const request = controller.current if ( !status?.editable || - draft === null || + (draft === null && !status.savedUnreadable) || saving.current || !request || request.signal.aborted @@ -96,12 +96,13 @@ function TerminalLimitField({ scope }: { scope: SettingsHostScope }): React.JSX. setFailed(true) return } - if (draft === '' || !Number.isFinite(Number(draft))) { + const text = draft ?? String(status.maxTerminals) + if (text === '' || !Number.isFinite(Number(text))) { setDraft(null) return } - const value = Math.max(1, Math.min(maximum, Math.trunc(Number(draft)))) - if (value === status.maxTerminals) { + const value = Math.max(1, Math.min(maximum, Math.trunc(Number(text)))) + if (value === status.maxTerminals && !status.savedUnreadable) { setDraft(null) return } @@ -198,6 +199,15 @@ function TerminalLimitField({ scope }: { scope: SettingsHostScope }): React.JSX. )} {unavailable ? {unavailable} : null} + {status?.savedUnreadable && !failed ? ( + + {translate( + 'settings.terminal.limit.savedUnreadable', + 'Couldn’t read this host’s saved terminal limit. Using {{value}}. Enter a value and press Enter to replace it.', + { value: status.maxTerminals.toLocaleString() } + )} + + ) : null} {failed ? ( {translate( diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 4ed78c0ad30b..c09106e4d3c9 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -338,6 +338,7 @@ "disconnected": "This host is disconnected. Reconnect to view or change its terminal limit.", "unsupported": "This host’s terminal service does not support changing this limit yet.", "environment": "This Orca instance has a terminal limit set by its environment. Remove the override on this host to edit it here.", + "savedUnreadable": "Couldn’t read this host’s saved terminal limit. Using {{value}}. Enter a value and press Enter to replace it.", "failed": "Couldn’t confirm the terminal limit. Try again.", "retry": "Retry", "unit": "terminals", diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 22eb5080fc50..afbb57b7d5ce 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -110,6 +110,7 @@ "disconnected": "Este equipo está desconectado. Vuelve a conectarlo para ver o cambiar su límite de terminales.", "unsupported": "El servicio de terminal de este equipo aún no permite cambiar este límite.", "environment": "El entorno establece el límite de terminales de esta instancia de Orca. Elimina esa configuración en este equipo para editarlo aquí.", + "savedUnreadable": "No se pudo leer el límite de terminales guardado de este host. Se usa {{value}}. Introduce un valor y pulsa Intro para reemplazarlo.", "failed": "No se pudo confirmar el límite de terminales. Inténtalo de nuevo.", "retry": "Reintentar", "unit": "terminales", diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 051ed3ed8c7f..37c243cccf85 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -250,6 +250,7 @@ "disconnected": "Cet hôte est déconnecté. Reconnectez-le pour consulter ou modifier sa limite de terminaux.", "unsupported": "Le service de terminal de cet hôte ne permet pas encore de modifier cette limite.", "environment": "L’environnement définit la limite de terminaux de cette instance d’Orca. Supprimez cette configuration sur cet hôte pour la modifier ici.", + "savedUnreadable": "Impossible de lire la limite de terminaux enregistrée sur cet hôte. Valeur utilisée : {{value}}. Saisissez une valeur et appuyez sur Entrée pour la remplacer.", "failed": "Impossible de confirmer la limite de terminaux. Réessayez.", "retry": "Réessayer", "unit": "terminaux", diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 27e76a6e371f..70f998675b51 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -110,6 +110,7 @@ "disconnected": "このホストは切断されています。再接続してターミナルの上限を確認または変更してください。", "unsupported": "このホストのターミナルサービスは、まだ上限の変更に対応していません。", "environment": "このOrcaインスタンスのターミナル上限は環境変数で設定されています。ここで編集するには、このホストの環境変数による設定を削除してください。", + "savedUnreadable": "このホストに保存されたターミナル上限を読み取れませんでした。{{value}} を使用しています。値を入力し、Enter キーを押して置き換えてください。", "failed": "ターミナルの上限を確認できませんでした。もう一度お試しください。", "retry": "再試行", "unit": "ターミナル", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 03b4538fa6be..2603e9be15a4 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -110,6 +110,7 @@ "disconnected": "이 호스트의 연결이 끊겼습니다. 터미널 한도를 확인하거나 변경하려면 다시 연결하세요.", "unsupported": "이 호스트의 터미널 서비스는 아직 한도 변경을 지원하지 않습니다.", "environment": "이 Orca 인스턴스의 터미널 한도는 환경 변수로 설정되어 있습니다. 여기서 편집하려면 이 호스트에서 해당 설정을 제거하세요.", + "savedUnreadable": "이 호스트에 저장된 터미널 제한을 읽지 못했습니다. {{value}}을(를) 사용합니다. 값을 입력하고 Enter 키를 눌러 교체하세요.", "failed": "터미널 한도를 확인하지 못했습니다. 다시 시도하세요.", "retry": "다시 시도", "unit": "터미널", diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 394be9b0e3b2..7c07213a50b8 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -15733,6 +15733,7 @@ "pane": { "id": { "copy": { + "savedUnreadable": "Não foi possível ler o limite de terminais salvo neste host. Usando {{value}}. Digite um valor e pressione Enter para substituí-lo.", "failed": "Não foi possível copiar o ID do painel" } } diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 0b93015d1a91..ee14c1402e12 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -110,6 +110,7 @@ "disconnected": "此主机已断开连接。请重新连接以查看或更改终端上限。", "unsupported": "此主机的终端服务尚不支持更改此上限。", "environment": "此 Orca 实例的终端上限由环境变量设置。要在此编辑,请先移除此主机上的相应环境设置。", + "savedUnreadable": "无法读取此主机已保存的终端上限。当前使用 {{value}}。输入数值并按 Enter 键即可替换。", "failed": "无法确认终端上限。请重试。", "retry": "重试", "unit": "个终端", diff --git a/src/shared/terminal-limit-policy.ts b/src/shared/terminal-limit-policy.ts index 800429839430..91c9faed8fae 100644 --- a/src/shared/terminal-limit-policy.ts +++ b/src/shared/terminal-limit-policy.ts @@ -5,6 +5,7 @@ export type TerminalLimitStatus = { maxTerminals: number systemPtyLimit: number | null source: 'environment' | 'saved' | 'default' + savedUnreadable?: boolean editable: boolean daemonNonce: string } From 8dff54b4d3c19b328a51b6cf770dde8509989ebe Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:19:10 -0700 Subject: [PATCH 10/15] Require a numeric edit before repairing terminal limits --- .../settings/TerminalLimitSetting.test.tsx | 47 +++++++++++++++++-- .../settings/TerminalLimitSetting.tsx | 7 ++- src/renderer/src/i18n/locales/pt.json | 4 +- 3 files changed, 49 insertions(+), 9 deletions(-) diff --git a/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx b/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx index ba7d1c68e379..473694f86b41 100644 --- a/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx +++ b/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx @@ -9,6 +9,7 @@ import type { SettingsHostScope } from './settings-host-scope' import type { TerminalLimitStatus } from '../../../../shared/terminal-limit-policy' import { useAppStore } from '@/store' import { i18n } from '@/i18n/i18n' +import ptCatalog from '@/i18n/locales/pt.json' import { getTerminalAdvancedSearchEntries } from './terminal-advanced-platform-search' import { matchesSettingsSearch } from './settings-search' import type { RuntimeStatus } from '../../../../shared/runtime-types' @@ -242,17 +243,25 @@ it('finds localized capacity in both the catalog and the rendered row filter', a search.query = 'aucun-résultat' await render() expect(container.querySelector('input')).toBeNull() + expect(ptCatalog.settings.terminal.limit.savedUnreadable).toContain('Não foi possível ler') }) -it.each([256, 384])( - 'repairs an unreadable saved limit by committing %s, including the effective value', - async (maximum) => { +it.each([ + ['Enter', 256], + ['blur', 256], + ['Enter', 384] +] as const)( + 'repairs an unreadable saved limit with %s at %s, including the edited effective value', + async (event, maximum) => { vi.mocked(readTerminalLimit).mockResolvedValue({ ...base, savedUnreadable: true }) await render() expect(input().disabled).toBe(false) expect(container.textContent).toContain('Using 256') + await type('') await type(String(maximum)) - await enter() + await (event === 'Enter' + ? enter() + : act(async () => input().dispatchEvent(new FocusEvent('focusout', { bubbles: true })))) expect(saveTerminalLimit).toHaveBeenCalledWith( expect.anything(), { maxTerminals: maximum, daemonNonce: 'daemon-a' }, @@ -276,3 +285,33 @@ it('uses the selected-host transport and refuses unsupported capability without await expect(transport.readTerminalLimit(route, signal)).resolves.toBeNull() expect(callHostRoute).toHaveBeenCalledExactlyOnceWith(route, 'status.get', undefined, { signal }) }) + +it('preserves unhealthy above-bound readback on untouched and canceled commits', async () => { + vi.mocked(readTerminalLimit).mockResolvedValue({ + ...base, + maxTerminals: 384, + systemPtyLimit: 128, + source: 'saved', + savedUnreadable: true + }) + await render() + const blur = async () => + act(async () => input().dispatchEvent(new FocusEvent('focusout', { bubbles: true }))) + await enter() + await blur() + expect(input().value).toBe('384') + expect(saveTerminalLimit).not.toHaveBeenCalled() + await type('64') + await act(async () => + input().dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })) + ) + await blur() + await enter() + expect(input().value).toBe('384') + expect(saveTerminalLimit).not.toHaveBeenCalled() + await type('64') + await blur() + await enter() + expect(input().value).toBe('64') + expect(saveTerminalLimit).toHaveBeenCalledTimes(1) +}) diff --git a/src/renderer/src/components/settings/TerminalLimitSetting.tsx b/src/renderer/src/components/settings/TerminalLimitSetting.tsx index 0300c2a8e671..f6c5731260bb 100644 --- a/src/renderer/src/components/settings/TerminalLimitSetting.tsx +++ b/src/renderer/src/components/settings/TerminalLimitSetting.tsx @@ -85,7 +85,7 @@ function TerminalLimitField({ scope }: { scope: SettingsHostScope }): React.JSX. const request = controller.current if ( !status?.editable || - (draft === null && !status.savedUnreadable) || + draft === null || saving.current || !request || request.signal.aborted @@ -96,12 +96,11 @@ function TerminalLimitField({ scope }: { scope: SettingsHostScope }): React.JSX. setFailed(true) return } - const text = draft ?? String(status.maxTerminals) - if (text === '' || !Number.isFinite(Number(text))) { + if (draft === '' || !Number.isFinite(Number(draft))) { setDraft(null) return } - const value = Math.max(1, Math.min(maximum, Math.trunc(Number(text)))) + const value = Math.max(1, Math.min(maximum, Math.trunc(Number(draft)))) if (value === status.maxTerminals && !status.savedUnreadable) { setDraft(null) return diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 7c07213a50b8..f174a3fa05d3 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -856,6 +856,9 @@ "openManageSessions": "Abrir Gerenciar sessões", "administratorSearchDescription": "Veja as permissões do Orca no Windows ou reinicie com aprovação de administrador.", "administratorApproval": "O Windows pedirá aprovação. Use sua conta habitual." + }, + "limit": { + "savedUnreadable": "Não foi possível ler o limite de terminais salvo neste host. Usando {{value}}. Digite um valor e pressione Enter para substituí-lo." } }, "agents": { @@ -15733,7 +15736,6 @@ "pane": { "id": { "copy": { - "savedUnreadable": "Não foi possível ler o limite de terminais salvo neste host. Usando {{value}}. Digite um valor e pressione Enter para substituí-lo.", "failed": "Não foi possível copiar o ID do painel" } } From 0affbb5a93dceaa1a5815ec03b2443d351d85e2e Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:39:03 -0700 Subject: [PATCH 11/15] Derive terminal default from startup host capacity --- src/main/daemon/host-terminal-policy.test.ts | 35 ++++++++++++++++++-- src/main/daemon/host-terminal-policy.ts | 14 ++++++-- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/src/main/daemon/host-terminal-policy.test.ts b/src/main/daemon/host-terminal-policy.test.ts index b27beebce3d1..21261482b6e6 100644 --- a/src/main/daemon/host-terminal-policy.test.ts +++ b/src/main/daemon/host-terminal-policy.test.ts @@ -115,7 +115,7 @@ describe('host terminal policy', () => { server.stopHostTerminals() }) - it('validates the host ceiling, preserves environment priority and never shares a missing machine identity', async () => { + it('caches the capped startup default, validates host capacity and preserves saved/environment priority', async () => { const root = await home() const path = hostTerminalPolicyPath(root, 'machine-a') expect(path).not.toBe(hostTerminalPolicyPath(root, 'machine-b')) @@ -139,13 +139,32 @@ describe('host terminal policy', () => { }) await expect(override.save(20, () => true)).rejects.toThrow('unavailable') const unidentified = createPolicy(null, {}, system()) + await unidentified.start() expect(await unidentified.status('nonce')).toMatchObject({ maxTerminals: 256, editable: false }) await expect(unidentified.save(10, () => true)).rejects.toThrow() const reduced = createPolicy(path, {}, new SystemPtyLimit(async () => 128)) await reduced.start() expect(await reduced.status('nonce')).toMatchObject({ maxTerminals: 384, systemPtyLimit: 128 }) - const defaults = createPolicy(null, {}, new SystemPtyLimit(async () => 128)) - expect(await defaults.status('nonce')).toMatchObject({ maxTerminals: 256, systemPtyLimit: 128 }) + for (const [capacity, expected] of [ + [null, 256], + [511, 256], + [4096, 2048], + [16384, 4096] + ] as const) { + const probe = vi.fn<() => Promise>().mockResolvedValue(capacity) + const defaults = createPolicy(null, {}, new SystemPtyLimit(probe)) + await defaults.start() + expect(defaults.admissionMaximum()).toBe(expected) + expect(defaults.admissionMaximum()).toBe(expected) + expect(probe).toHaveBeenCalledOnce() + probe.mockResolvedValue(128) + expect(await defaults.status('nonce')).toMatchObject({ + maxTerminals: expected, + source: 'default', + systemPtyLimit: 128 + }) + expect(defaults.admissionMaximum()).toBe(expected) + } }) it('bounds shared startup and retains one raw read/observer across ticks, admissions and saves', async () => { @@ -211,6 +230,16 @@ describe('host terminal policy', () => { value.dispose() await vi.advanceTimersByTimeAsync(30_000) expect(read).toHaveBeenCalledTimes(2) + const systemProbe = deferred() + const cold = createPolicy(null, {}, new SystemPtyLimit(() => systemProbe.promise)) + const initializing = cold.start() + expect(cold.start()).toBe(initializing) + await vi.advanceTimersByTimeAsync(1_101) + await initializing + expect(cold.admissionMaximum()).toBe(256) + systemProbe.resolve(16384) + await vi.advanceTimersByTimeAsync(0) + expect(cold.admissionMaximum()).toBe(256) }) it('retains last good through failures, fences stale reads against save and disposal, and recovers', async () => { diff --git a/src/main/daemon/host-terminal-policy.ts b/src/main/daemon/host-terminal-policy.ts index 19ee4e0ba25d..f0aa8ca37281 100644 --- a/src/main/daemon/host-terminal-policy.ts +++ b/src/main/daemon/host-terminal-policy.ts @@ -6,6 +6,7 @@ import { readNodeFileWithinLimit } from '../../shared/node-bounded-file-reader' import { renameFileWithWindowsRetryAsync } from '../../shared/windows-retry-file-operations' import { isConfiguredTerminalLimit, + MAX_CONFIGURED_TERMINALS, terminalLimitInputMaximum, type TerminalLimitStatus } from '../../shared/terminal-limit-policy' @@ -91,6 +92,7 @@ async function withPolicyOperation( } export class HostTerminalPolicy { + private defaultMaximum = DEFAULT_MAX_HOST_TERMINALS private savedMaximum: number | null = null private savedUnreadable = false private revision = 0 @@ -119,7 +121,15 @@ export class HostTerminalPolicy { start(log = this.log): Promise { this.log = log - return (this.initialization ??= this.refresh().then(() => { + return (this.initialization ??= this.system.read().then(async (systemPtyLimit) => { + if (this.disposed) { + return + } + this.defaultMaximum = + systemPtyLimit === null + ? DEFAULT_MAX_HOST_TERMINALS + : Math.min(Math.ceil(systemPtyLimit / 2), MAX_CONFIGURED_TERMINALS) + await this.refresh() if (!this.disposed && this.path && this.environment === null) { this.timer = setInterval(() => void this.refresh(), 3_000) this.timer.unref?.() @@ -181,7 +191,7 @@ export class HostTerminalPolicy { } admissionMaximum(): number { - return this.environment ?? this.savedMaximum ?? DEFAULT_MAX_HOST_TERMINALS + return this.environment ?? this.savedMaximum ?? this.defaultMaximum } private observedStatus(systemPtyLimit: number | null, daemonNonce: string): TerminalLimitStatus { From cd1d7147c22f6e3caa82e037f16ea6bbbe498224 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 19:56:32 -0700 Subject: [PATCH 12/15] Apply terminal policy reads when validated results settle --- src/main/daemon/host-terminal-policy.test.ts | 145 +++++++++++++++++-- src/main/daemon/host-terminal-policy.ts | 22 ++- 2 files changed, 139 insertions(+), 28 deletions(-) diff --git a/src/main/daemon/host-terminal-policy.test.ts b/src/main/daemon/host-terminal-policy.test.ts index 21261482b6e6..fcbdd58ca479 100644 --- a/src/main/daemon/host-terminal-policy.test.ts +++ b/src/main/daemon/host-terminal-policy.test.ts @@ -8,6 +8,7 @@ import { SystemPtyLimit, parseLinuxPtyLimit } from './system-pty-limit' import * as deadlines from './daemon-request-deadline' import { HostTerminalLedger } from './host-terminal-ledger' import { TerminalSpawnGate } from './terminal-spawn-gate' +import { isConfiguredTerminalLimit } from '../../shared/terminal-limit-policy' import { DEFAULT_SPAWN_ADMISSION_LIMITS, type SpawnRequestFacts @@ -22,10 +23,12 @@ const fs = await vi.importActual('node:fs/promises') function deferred() { let resolve!: (value: T) => void - const promise = new Promise((done) => { + let reject!: (error: Error) => void + const promise = new Promise((done, fail) => { resolve = done + reject = fail }) - return { promise, resolve } + return { promise, resolve, reject } } const facts: SpawnRequestFacts = { @@ -167,7 +170,51 @@ describe('host terminal policy', () => { } }) - it('bounds shared startup and retains one raw read/observer across ticks, admissions and saves', async () => { + it('publishes slow startup, raises and decreases on settlement without background observers or transient health', async () => { + vi.useFakeTimers() + let saved = 384 + let latency = 300 + const read = vi.fn(() => { + const maximum = saved + return new Promise((resolve) => setTimeout(() => resolve(maximum), latency)) + }) + const value = createPolicy(join(await home(), 'policy.json'), {}, system(), read) + const log = vi.fn() + const observed = vi.spyOn(deadlines, 'awaitDaemonValueWithinCallerDeadline') + const startup = value.start(log) + expect(value.start()).toBe(startup) + await vi.advanceTimersByTimeAsync(251) + await startup + expect(await value.status('nonce')).toMatchObject({ maxTerminals: 256, source: 'default' }) + expect((await value.status('nonce')).savedUnreadable).toBeUndefined() + const observers = observed.mock.calls.length + await vi.advanceTimersByTimeAsync(49) + expect(value.admissionMaximum()).toBe(384) + for (const maximum of [400, 300]) { + saved = maximum + await vi.advanceTimersToNextTimerAsync() + await vi.advanceTimersByTimeAsync(300) + expect(value.admissionMaximum()).toBe(maximum) + } + latency = 3_100 + saved = 350 + await vi.advanceTimersToNextTimerAsync() + await vi.advanceTimersByTimeAsync(3_000) + expect(read).toHaveBeenCalledTimes(4) + expect(value.admissionMaximum()).toBe(300) + await vi.advanceTimersByTimeAsync(100) + expect(value.admissionMaximum()).toBe(350) + expect(observed).toHaveBeenCalledTimes(observers) + saved = 2 + await vi.advanceTimersToNextTimerAsync() + value.dispose() + await vi.advanceTimersByTimeAsync(30_000) + expect(read).toHaveBeenCalledTimes(5) + expect(value.admissionMaximum()).toBe(350) + expect(log).not.toHaveBeenCalled() + }) + + it('bounds shared startup and retains one raw read/observer across ticks, admissions and independent saves', async () => { const path = join(await home(), 'policy.json') vi.useFakeTimers() const old = deferred() @@ -177,11 +224,15 @@ describe('host terminal policy', () => { .mockResolvedValue(384) const value = createPolicy(path, {}, system(), read) const observed = vi.spyOn(deadlines, 'awaitDaemonValueWithinCallerDeadline') - const startup = value.start() + const log = vi.fn() + const startup = value.start(log) expect(value.start()).toBe(startup) await vi.advanceTimersByTimeAsync(251) await startup - expect(await value.status('nonce')).toMatchObject({ maxTerminals: 256, savedUnreadable: true }) + expect(await value.status('nonce')).toMatchObject({ maxTerminals: 256 }) + expect((await value.status('nonce')).savedUnreadable).toBeUndefined() + expect(await value.save(384, () => true)).toMatchObject({ maxTerminals: 384 }) + expect(await value.save(400, () => true)).toMatchObject({ maxTerminals: 400 }) expect(await value.save(384, () => true)).toMatchObject({ maxTerminals: 384 }) const observers = observed.mock.calls.length const maximum = vi.fn(() => value.admissionMaximum()) @@ -227,6 +278,8 @@ describe('host terminal policy', () => { await vi.advanceTimersByTimeAsync(0) expect(value.admissionMaximum()).toBe(384) expect(read).toHaveBeenCalledTimes(2) + expect(observed).toHaveBeenCalledTimes(observers) + expect(log).not.toHaveBeenCalled() value.dispose() await vi.advanceTimersByTimeAsync(30_000) expect(read).toHaveBeenCalledTimes(2) @@ -266,9 +319,12 @@ describe('host terminal policy', () => { editable: true }) expect(log).toHaveBeenCalledTimes(1) - held.resolve(2) + setTimeout(() => held.resolve(400), 300) read.mockResolvedValue(400) - await vi.advanceTimersByTimeAsync(3_000) + await vi.advanceTimersByTimeAsync(299) + expect(value.admissionMaximum()).toBe(384) + expect(log).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(1) const recovered = await value.status('nonce') expect(recovered.maxTerminals).toBe(400) expect(recovered.savedUnreadable).toBeUndefined() @@ -276,22 +332,58 @@ describe('host terminal policy', () => { 'terminal-policy-read-failed', 'terminal-policy-read-recovered' ]) + const rejected = deferred() + read.mockReturnValueOnce(rejected.promise) + await vi.advanceTimersToNextTimerAsync() + await expect(value.save(512, () => true)).rejects.toThrow('capacity') + rejected.reject(new Error('obsolete denied read')) + await vi.advanceTimersByTimeAsync(0) + expect(value.admissionMaximum()).toBe(400) + expect((await value.status('nonce')).savedUnreadable).toBeUndefined() + expect(log).toHaveBeenCalledTimes(2) + read.mockImplementationOnce(() => { + throw new Error('actual synchronous loader failure') + }) + await vi.advanceTimersToNextTimerAsync() + expect((await value.status('nonce')).savedUnreadable).toBe(true) + expect(log).toHaveBeenCalledTimes(3) const stale = deferred() - read.mockReturnValueOnce(stale.promise).mockResolvedValue(384) + const between = deferred() + read + .mockReturnValueOnce(stale.promise) + .mockReturnValueOnce(between.promise) + .mockResolvedValue(384) await vi.advanceTimersToNextTimerAsync() - expect(await value.save(384, () => true)).toMatchObject({ maxTerminals: 384 }) + const committing = deferred() + const release = deferred() + vi.mocked(rename).mockImplementationOnce(async (...args) => { + committing.resolve() + await release.promise + await fs.rename(...args) + }) + const save = value.save(384, () => true) + await committing.promise stale.resolve(2) await vi.advanceTimersByTimeAsync(0) + expect(await value.status('nonce')).toMatchObject({ maxTerminals: 400, savedUnreadable: true }) + expect(log).toHaveBeenCalledTimes(3) + release.resolve() + expect(await save).toMatchObject({ maxTerminals: 384 }) + between.reject(new Error('obsolete pre-commit denial')) + await vi.advanceTimersByTimeAsync(0) expect(value.admissionMaximum()).toBe(384) + expect((await value.status('nonce')).savedUnreadable).toBeUndefined() + expect(log).toHaveBeenCalledTimes(4) const late = deferred() read.mockReturnValue(late.promise) await vi.advanceTimersToNextTimerAsync() value.dispose() const count = read.mock.calls.length - late.resolve(2) + late.reject(new Error('disposed read failure')) await vi.advanceTimersByTimeAsync(30_000) expect(read).toHaveBeenCalledTimes(count) expect(value.admissionMaximum()).toBe(384) + expect(log).toHaveBeenCalledTimes(4) }) it('expires staging without a late rename or orphan, and permits retry while cleanup stalls', async () => { @@ -362,7 +454,22 @@ describe('host terminal policy', () => { cleaned.resolve() } }) - const policy = createPolicy(path, {}, system()) + const reconciling = deferred() + const read = vi.fn(async (file: string) => { + const saved: unknown = JSON.parse(await fs.readFile(file, 'utf8')) + if ( + !saved || + typeof saved !== 'object' || + !('maxTerminals' in saved) || + !isConfiguredTerminalLimit(saved.maxTerminals) + ) { + throw new Error('Invalid fixture') + } + reconciling.resolve() + await new Promise((resolve) => setTimeout(resolve, 300)) + return saved.maxTerminals + }) + const policy = createPolicy(path, {}, system(), read) vi.useFakeTimers() const save = policy.save(10, () => true) const failed = expect(save).rejects.toThrow('confirm') @@ -374,14 +481,22 @@ describe('host terminal policy', () => { try { Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) release.resolve() - await vi.advanceTimersByTimeAsync(100) + await vi.advanceTimersByTimeAsync(0) await cleaned.promise } finally { Object.defineProperty(process, 'platform', { configurable: true, value: platform }) } - await vi.waitFor(() => - expect(policy.admissionMaximum()).toBe(outcome === 'completed' ? 10 : 20) - ) + expect(policy.admissionMaximum()).toBe(20) + if (outcome === 'completed') { + await reconciling.promise + await vi.advanceTimersByTimeAsync(299) + expect(policy.admissionMaximum()).toBe(20) + await vi.advanceTimersByTimeAsync(1) + expect(policy.admissionMaximum()).toBe(10) + expect(read).toHaveBeenCalledOnce() + } else { + expect(read).not.toHaveBeenCalled() + } expect(rename).toHaveBeenCalledTimes(2) } ) diff --git a/src/main/daemon/host-terminal-policy.ts b/src/main/daemon/host-terminal-policy.ts index f0aa8ca37281..56e0c4ee7bf2 100644 --- a/src/main/daemon/host-terminal-policy.ts +++ b/src/main/daemon/host-terminal-policy.ts @@ -129,7 +129,7 @@ export class HostTerminalPolicy { systemPtyLimit === null ? DEFAULT_MAX_HOST_TERMINALS : Math.min(Math.ceil(systemPtyLimit / 2), MAX_CONFIGURED_TERMINALS) - await this.refresh() + await awaitDaemonValueWithinCallerDeadline(this.refresh(), Date.now() + 250) if (!this.disposed && this.path && this.environment === null) { this.timer = setInterval(() => void this.refresh(), 3_000) this.timer.unref?.() @@ -150,29 +150,25 @@ export class HostTerminalPolicy { const path = this.path const revision = this.revision this.reading = true - const raw = Promise.resolve().then(() => this.readSaved(path)) - void raw - .finally(() => { - this.reading = false - if (revision !== this.revision) { - void this.refresh() - } - }) - .catch(() => undefined) try { - const read = await awaitDaemonValueWithinCallerDeadline(raw, Date.now() + 250) + const maximum = await this.readSaved(path) if (this.disposed || revision !== this.revision) { return } - if (!read.completed || (read.value === null && this.savedMaximum !== null)) { + if (maximum === null && this.savedMaximum !== null) { throw new Error('Saved terminal limit unavailable') } - this.savedMaximum = read.value + this.savedMaximum = maximum this.setReadHealth(false) } catch { if (!this.disposed && revision === this.revision) { this.setReadHealth(true) } + } finally { + this.reading = false + if (!this.disposed && revision !== this.revision) { + void this.refresh() + } } } From 386f99556f0d0ae445003020629339a2f94a2a93 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:32:09 -0700 Subject: [PATCH 13/15] Align terminal limit tests with static analysis gates --- src/main/daemon/host-terminal-policy.test.ts | 2 ++ .../src/components/settings/TerminalLimitSetting.test.tsx | 4 +--- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/daemon/host-terminal-policy.test.ts b/src/main/daemon/host-terminal-policy.test.ts index fcbdd58ca479..ea2c5d18a763 100644 --- a/src/main/daemon/host-terminal-policy.test.ts +++ b/src/main/daemon/host-terminal-policy.test.ts @@ -176,6 +176,7 @@ describe('host terminal policy', () => { let latency = 300 const read = vi.fn(() => { const maximum = saved + // ast-grep-ignore: test-no-real-time-wait -- Fake timers model read latency across startup and refresh ticks. return new Promise((resolve) => setTimeout(() => resolve(maximum), latency)) }) const value = createPolicy(join(await home(), 'policy.json'), {}, system(), read) @@ -466,6 +467,7 @@ describe('host terminal policy', () => { throw new Error('Invalid fixture') } reconciling.resolve() + // ast-grep-ignore: test-no-real-time-wait -- Fake timers verify delayed actual-file reconciliation after an expired rename. await new Promise((resolve) => setTimeout(resolve, 300)) return saved.maxTerminals }) diff --git a/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx b/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx index 473694f86b41..c3e964489cfd 100644 --- a/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx +++ b/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx @@ -40,6 +40,7 @@ vi.mock('@/store/host-catalog-fencing', () => ({ captureHostIdentityFence: () => ({}), isHostIdentityFenceCurrent: () => true })) +const transport = await vi.importActual('./terminal-limit-transport') const local: SettingsHostScope = { target: { kind: 'local' }, available: true } const base: TerminalLimitStatus = { maxTerminals: 256, @@ -273,9 +274,6 @@ it.each([ ) it('uses the selected-host transport and refuses unsupported capability without issuing a policy RPC', async () => { - const transport = await vi.importActual( - './terminal-limit-transport' - ) const route = { target: { kind: 'environment' as const, environmentId: 'old-server' }, at: 'local' as const From 3ad31801c432b0e144e8f835d17318b3eaee7baf Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 23:51:29 -0700 Subject: [PATCH 14/15] Inject daemon startup errors at the publication boundary --- .../daemon-server-error-handling.test.ts | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/main/daemon/daemon-server-error-handling.test.ts b/src/main/daemon/daemon-server-error-handling.test.ts index b7834e8058e1..1281b3a2b28e 100644 --- a/src/main/daemon/daemon-server-error-handling.test.ts +++ b/src/main/daemon/daemon-server-error-handling.test.ts @@ -37,6 +37,7 @@ function createMockSubprocess(): SubprocessHandle { } type DaemonServerInternals = { endpoint: { + publish(bindPath: string): Promise hasLostOwnership(): boolean requestRetirementForLoss(): void checkOwnership(): void @@ -435,15 +436,23 @@ describe('daemon server error handling', () => { tokenPath, spawnSubprocess: () => createMockSubprocess() }) - const started = server.start() const daemon = server as unknown as DaemonServerInternals - await vi.waitFor(() => expect(daemon.lifecycle.server?.listening).toBe(true)) - daemon.lifecycle.server?.emit('error', new Error('injected accept failure')) + const publish = daemon.endpoint.publish.bind(daemon.endpoint) + const publication = vi + .spyOn(daemon.endpoint, 'publish') + .mockImplementationOnce((bindPath) => { + daemon.lifecycle.server?.emit('error', new Error('injected accept failure')) + return publish(bindPath) + }) - await expect(started).rejects.toThrow('injected accept failure') - // Startup rejects before publication settles; wait until the failed daemon actually stops serving. - await vi.waitFor(() => expect(daemon.lifecycle.server).toBeNull()) - await expect(waitForEndpointUnreachable(socketPath)).resolves.toBe(true) + try { + await expect(server.start()).rejects.toThrow('injected accept failure') + // Startup rejects before publication settles; wait until the failed daemon actually stops serving. + await vi.waitFor(() => expect(daemon.lifecycle.server).toBeNull()) + await expect(waitForEndpointUnreachable(socketPath)).resolves.toBe(true) + } finally { + publication.mockRestore() + } } ) }) From d2b3387a65e2ea9815cdd42c66e26c2be4bc6b80 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 29 Oct 2026 02:29:00 -0700 Subject: [PATCH 15/15] Format terminal capacity using the app language --- .../settings/TerminalLimitSetting.test.tsx | 29 ++++++++++++++----- .../settings/TerminalLimitSetting.tsx | 6 ++-- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx b/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx index c3e964489cfd..40821e17bd90 100644 --- a/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx +++ b/src/renderer/src/components/settings/TerminalLimitSetting.test.tsx @@ -233,18 +233,33 @@ it('disables on contact loss and reads again on a real same-runtime recovery pub expect(readTerminalLimit).toHaveBeenCalledTimes(2) }) -it('finds localized capacity in both the catalog and the rendered row filter', async () => { +it('finds and formats capacity in the UI language in the catalog and rendered row', async () => { await i18n.changeLanguage('fr') search.query = 'capacité' expect( getTerminalAdvancedSearchEntries().some((entry) => matchesSettingsSearch(search.query, entry)) ).toBe(true) - await render() - expect(input().value).toBe('256') - search.query = 'aucun-résultat' - await render() - expect(container.querySelector('input')).toBeNull() - expect(ptCatalog.settings.terminal.limit.savedUnreadable).toContain('Não foi possível ler') + vi.mocked(readTerminalLimit).mockResolvedValue({ + ...base, + maxTerminals: 2048, + systemPtyLimit: 4096, + savedUnreadable: true + }) + const format = vi.spyOn(Number.prototype, 'toLocaleString') + try { + await render() + expect(input().value).toBe('2048') + expect(container.textContent).toContain('4\u202f096') + expect(container.querySelector('[role="status"]')?.textContent).toContain('2\u202f048') + expect(format).toHaveBeenCalledWith('fr') + expect(format).not.toHaveBeenCalledWith() + search.query = 'aucun-résultat' + await render() + expect(container.querySelector('input')).toBeNull() + expect(ptCatalog.settings.terminal.limit.savedUnreadable).toContain('Não foi possível ler') + } finally { + format.mockRestore() + } }) it.each([ diff --git a/src/renderer/src/components/settings/TerminalLimitSetting.tsx b/src/renderer/src/components/settings/TerminalLimitSetting.tsx index f6c5731260bb..7351f702df9d 100644 --- a/src/renderer/src/components/settings/TerminalLimitSetting.tsx +++ b/src/renderer/src/components/settings/TerminalLimitSetting.tsx @@ -17,7 +17,7 @@ import { type HostIdentityFence } from '@/store/host-catalog-fencing' import type { HostRoute } from '@/runtime/runtime-client-target' -import { translate } from '@/i18n/i18n' +import { getIntlLocale, translate } from '@/i18n/i18n' import { runtimeHostContactForEntry } from '../../../../shared/runtime-host-contact' import { getTerminalLimitSearchKeywords } from './terminal-advanced-platform-search' @@ -187,7 +187,7 @@ function TerminalLimitField({ scope }: { scope: SettingsHostScope }): React.JSX. value: status === undefined && scope.available && !failed ? '…' - : (status?.systemPtyLimit?.toLocaleString() ?? + : (status?.systemPtyLimit?.toLocaleString(getIntlLocale()) ?? translate('settings.terminal.limit.unknown', 'Unavailable')) })} @@ -203,7 +203,7 @@ function TerminalLimitField({ scope }: { scope: SettingsHostScope }): React.JSX. {translate( 'settings.terminal.limit.savedUnreadable', 'Couldn’t read this host’s saved terminal limit. Using {{value}}. Enter a value and press Enter to replace it.', - { value: status.maxTerminals.toLocaleString() } + { value: status.maxTerminals.toLocaleString(getIntlLocale()) } )} ) : null}