Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
58ff3e6
feat: configure the running terminal limit for each host
brennanb2025 Oct 21, 2026
3c93d28
fix: bound terminal policy saves through fresh confirmation
brennanb2025 Oct 21, 2026
f09e44c
Merge origin/main and clarify terminal admission timing
brennanb2025 Oct 21, 2026
51c0a9d
Fix truncated zero-size system file reads
brennanb2025 Oct 21, 2026
5da3151
Merge main before final terminal limit QA
brennanb2025 Oct 22, 2026
ada51d4
Merge current main into terminal limit setting
brennanb2025 Oct 27, 2026
8710e48
Load actual filesystem fixtures once per test module
brennanb2025 Oct 27, 2026
42e4533
Preserve slept terminal ownership through capacity retries
brennanb2025 Oct 27, 2026
83a54c4
Fix terminal limit CI quality checks
brennanb2025 Oct 27, 2026
dd6485e
Correct slept terminal resume test types
brennanb2025 Oct 27, 2026
7236570
Move the slept terminal Resume fix to its own pull request
brennanb2025 Oct 28, 2026
17c7d51
Keep terminal limits effective when saved settings cannot be read
brennanb2025 Oct 28, 2026
8dff54b
Require a numeric edit before repairing terminal limits
brennanb2025 Oct 29, 2026
0affbb5
Derive terminal default from startup host capacity
brennanb2025 Oct 29, 2026
cd1d714
Apply terminal policy reads when validated results settle
brennanb2025 Oct 29, 2026
002998f
Merge origin/main into terminal limit settings
brennanb2025 Oct 29, 2026
386f995
Align terminal limit tests with static analysis gates
brennanb2025 Oct 29, 2026
3ad3180
Inject daemon startup errors at the publication boundary
brennanb2025 Oct 29, 2026
d2b3387
Format terminal capacity using the app language
brennanb2025 Oct 29, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/main/daemon/daemon-automatic-work-guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>) => void }
listSessions: () => readonly { sessionId: string; pid: number | null }[]
Expand Down Expand Up @@ -50,13 +52,15 @@ 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,
pressure: () => this.monitor.level,
automaticWorkMode: () => this.automaticWorkMode(),
armAutomaticWork: () => this.marker.arm(),
legacyRestores: this.legacyRestores,
resolveMaximum: policy ? () => policy.admissionMaximum() : undefined,
hostTerminals: new HostTerminalLedger({
dir: options.hostTerminalLedgerDir ?? null,
maxTerminals: resolveMaxHostTerminals(),
Expand Down
10 changes: 9 additions & 1 deletion src/main/daemon/daemon-automatic-work-resume.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { TerminalLimitStatus, TerminalLimitUpdate } from '../../shared/terminal-limit-policy'
import type {
AutomaticWorkResumeOutcome,
AutomaticWorkStatus
Expand All @@ -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: [] }
}
Expand Down Expand Up @@ -47,3 +48,10 @@ export async function resumeLocalAutomaticWork(
}
return current.value
}

export async function localTerminalLimit(
provider: IPtyProvider,
update?: TerminalLimitUpdate
): Promise<TerminalLimitStatus | null> {
return (await localDaemons(provider)?.current.terminalLimit(update)) ?? null
}
28 changes: 28 additions & 0 deletions src/main/daemon/daemon-control-request.ts
Original file line number Diff line number Diff line change
@@ -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<unknown>,
onReply: () => void
): Promise<void> {
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)
})
)
}
}
}
28 changes: 28 additions & 0 deletions src/main/daemon/daemon-pty-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -171,6 +172,33 @@ export class DaemonPtyAdapter extends DaemonPtyDaemonRecovery implements IPtyPro
})
}

async terminalLimit(update?: TerminalLimitUpdate): Promise<TerminalLimitStatus | null> {
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<TerminalLimitStatus>(
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<AutomaticWorkStatus | null> {
const status = await this.requestAutomaticWork<AutomaticWorkStatus>('automaticWorkStatus')
return status === AUTOMATIC_WORK_RESUME_UNSUPPORTED ? null : status
Expand Down
16 changes: 13 additions & 3 deletions src/main/daemon/daemon-request-deadline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,23 @@ export async function awaitDaemonWorkWithinCallerDeadline(
work: Promise<void>,
deadlineMs: number
): Promise<boolean> {
return (await awaitDaemonValueWithinCallerDeadline(work, deadlineMs)).completed
}

export async function awaitDaemonValueWithinCallerDeadline<T>(
work: Promise<T>,
deadlineMs: number
): Promise<{ completed: true; value: T } | { completed: false }> {
void work.catch(() => {})
let timer: ReturnType<typeof setTimeout> | undefined
try {
return await Promise.race([
work.then(() => true),
new Promise<boolean>((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?.()
})
])
Expand Down
2 changes: 2 additions & 0 deletions src/main/daemon/daemon-server-options.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down
53 changes: 26 additions & 27 deletions src/main/daemon/daemon-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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(),
Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -289,26 +291,23 @@ export class DaemonServer {
clientId: string,
request: DaemonRequest
): Promise<void> {
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)
)
}
}
48 changes: 48 additions & 0 deletions src/main/daemon/daemon-terminal-limit-protocol.ts
Original file line number Diff line number Diff line change
@@ -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<TerminalLimitStatus> | undefined {
if (request.type !== 'terminalLimitStatus' && request.type !== 'setTerminalLimit') {
return undefined
}
const work = async (): Promise<TerminalLimitStatus> => {
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
})
}
84 changes: 84 additions & 0 deletions src/main/daemon/daemon-terminal-limit.test.ts
Original file line number Diff line number Diff line change
@@ -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>('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()
}
})
Loading
Loading