Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
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
395 changes: 381 additions & 14 deletions config/patches/node-pty@1.1.0.patch

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion config/process-host-direct-import-baseline.txt
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ src/main/plugins/catalog/plugin-private-marketplace-ssh-shim.cjs
src/main/ports/port-scan-command-execution.ts
src/main/providers/macos-login-session-pty-probe.ts
src/main/providers/process-cwd.ts
src/main/pty-descendant-termination.ts
src/main/pty-descendant-fresh-table.ts
src/main/pty/windows-environment-path.ts
src/main/rate-limits/gemini-cli-oauth-extractor.ts
src/main/runtime/windows-default-route-interfaces.ts
Expand Down
6 changes: 3 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions src/main/daemon/daemon-process-inspection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { execFile } from 'node:child_process'
import { readFile } from 'node:fs/promises'
import { promisify } from 'node:util'
import { psLocaleEnvironment } from '../../shared/ps-locale-environment'
import { readPsStdoutInProcess } from '../../shared/libproc-process-table'
import { parseLinuxBootTimeSeconds, parseLinuxProcStartTicks } from './daemon-process-start-time'
import type {
LinuxStatEvidence,
Expand Down Expand Up @@ -202,6 +203,13 @@ async function runInspectionCommand(
args: string[],
timeoutMs: number
): Promise<string> {
const inProcess =
file === 'ps'
? await readPsStdoutInProcess(args, { env: psLocaleEnvironment(), timeoutMs })
: null
if (inProcess !== null) {
return inProcess
}
const { stdout } = await execFileAsync(file, args, {
encoding: 'utf8',
env: psLocaleEnvironment(),
Expand Down
6 changes: 4 additions & 2 deletions src/main/daemon/daemon-protocol-version.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Why: daemons survive app updates, so wire behavior must be version-gated.
// v54 reads the macOS process table in process instead of forking setuid ps on every poll (#31783).
// v53 rolls the daemon-side terminal fixes since v1.4.241 (foreground confirmation for chat continuation, ConPTY reflow, WSL malloc tunables) into a fresh daemon.
// v52 rolls the daemon-side terminal fixes since v1.4.240 (ConPTY, teardown, spawn pane keys) into a fresh daemon.
// v51 checks terminal identity, ownership and attachments before reserving teardown.
Expand All @@ -11,7 +12,7 @@
// v43 dropped it with the revert); v41 stages long startup commands as sourced scripts; v40 rolled
// the #25130/#24636 shell-wrapper changes and the wider agent list into a fresh daemon; older owners
// stay attachable.
export const PROTOCOL_VERSION = 53
export const PROTOCOL_VERSION = 54
export const FENCED_TERMINATION_PROTOCOL_VERSION = 51
export const CLAUDE_ACCOUNT_FUNCTION_DAEMON_PROTOCOL_VERSION = 42
export const CLAUDE_ACCOUNT_FUNCTION_REVERTED_DAEMON_PROTOCOL_VERSION = 43
Expand Down Expand Up @@ -46,7 +47,8 @@ export const CLEAN_DISCONNECT_PROTOCOL_VERSION = 24
export const MODE_2031_UNSUBSCRIBE_FACT_PROTOCOL_VERSION = 29
export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52
28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53
] as const

export function supportsColorQueryReplyColors(protocolVersion: number): boolean {
Expand Down
66 changes: 66 additions & 0 deletions src/main/daemon/terminal-descendant-shutdown-libproc.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

type ExecFileCallback = (error: Error | null, stdout?: string) => void
const { execFile } = vi.hoisted(() => ({
execFile:
vi.fn<
(
file: string,
args: string[],
options: { timeout: number },
callback: ExecFileCallback
) => void
>()
}))
vi.mock('node:child_process', () => ({ execFile }))

import { setLibprocAddonForTests } from '../../shared/libproc-addon'
import { resetNativeReadsForTests } from '../../shared/libproc-native-reads'
import { collectDescendantRows, parseProcessTable } from '../pty-descendant-termination'
import { terminateShutdownDescendants } from './terminal-descendant-shutdown'

const STARTED = 'Mon Jul 13 12:54:47 2026'
const PS_OUTPUT = ` 100 1 100 0 ${STARTED}\n 200 100 100 0 ${STARTED}\n`

beforeEach(() => {
vi.useFakeTimers()
resetNativeReadsForTests()
// A stalled libuv pool: native reads never finish.
setLibprocAddonForTests({
readProcessTable: () => new Promise<never>(() => {}),
processCwd: () => null,
processPath: () => null
})
// A 200ms ps, killed at its timeout like execFile.
execFile.mockImplementation((_file, _args, { timeout }, callback) => {
const done = setTimeout(() => {
clearTimeout(killed)
callback(null, PS_OUTPUT)
}, 200)
const killed = setTimeout(() => {
clearTimeout(done)
callback(new Error('ps timed out'))
}, timeout)
})
})
afterEach(() => {
execFile.mockReset()
setLibprocAddonForTests(undefined)
vi.restoreAllMocks()
vi.useRealTimers()
})

describe('terminal shutdown descendant sweep over a stalled native reader', () => {
it('still terminates then kills a surviving descendant through a 200ms ps', async () => {
const kill = vi.spyOn(process, 'kill').mockReturnValue(true)
const snapshot = collectDescendantRows(100, parseProcessTable(PS_OUTPUT), Date.now())

const verdict = terminateShutdownDescendants(snapshot)
await vi.advanceTimersByTimeAsync(4_000)
await verdict

const signals = kill.mock.calls.filter(([pid]) => pid === 200).map(([, signal]) => signal)
expect(signals[0]).toBe('SIGTERM')
expect(signals).toContain('SIGKILL')
})
})
3 changes: 3 additions & 0 deletions src/main/daemon/terminal-descendant-shutdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ const readShutdownProcessTable: ProcessTableReader = (timeoutMs) => {
}, clear)
return promise
}
// Wrapping the production reader keeps its in-process allowance, so a stalled native read still leaves ps the whole window.
readShutdownProcessTable.deadlineAllowanceMs = (timeoutMs) =>
descendantTermination.readProcessTable.deadlineAllowanceMs?.(timeoutMs) ?? 0

export function terminateShutdownDescendants(
snapshot: DescendantSnapshot
Expand Down
25 changes: 17 additions & 8 deletions src/main/provider-process/provider-process-row-read.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { readFile } from 'node:fs/promises'
import { runProcess } from '@orca/process-host'
import { runPsInProcess } from '../../shared/libproc-process-table'
import { parseProcessTable, type ProcessTableRow } from '../pty-process-table-parser'

const PROCESS_ROW_TIMEOUT_MS = 2_000
Expand Down Expand Up @@ -43,14 +44,22 @@ async function readLinuxProcStatRow(pid: number): Promise<ProcessRowRead> {

async function readPsProcessRow(pid: number): Promise<ProcessRowRead> {
try {
const result = await runProcess({
program: 'ps',
args: ['-o', 'pid=,ppid=,pgid=,lstart=', '-p', String(pid)],
// Stable locale makes repeated start markers comparable.
env: { ...process.env, LANG: 'C', LC_ALL: 'C' },
timeoutMs: PROCESS_ROW_TIMEOUT_MS,
maxOutputBytes: 4096
})
const args = ['-o', 'pid=,ppid=,pgid=,lstart=', '-p', String(pid)]
// Stable locale makes repeated start markers comparable.
const env = { ...process.env, LANG: 'C', LC_ALL: 'C' }
const result =
(await runPsInProcess(args, {
env,
timeoutMs: PROCESS_ROW_TIMEOUT_MS,
maxOutputBytes: 4096
})) ??
(await runProcess({
program: 'ps',
args,
env,
timeoutMs: PROCESS_ROW_TIMEOUT_MS,
maxOutputBytes: 4096
}))
const row = parseProcessTable(result.stdout).find((entry) => entry.pid === pid)
if (row) {
return { ...row, startResolution: 'second' }
Expand Down
6 changes: 6 additions & 0 deletions src/main/providers/process-cwd.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { execFile as execFileCb } from 'node:child_process'
import { readlink } from 'node:fs/promises'
import { LSOF_NONBLOCKING_ARGS } from '../../shared/lsof-nonblocking-args'
import { readLibprocProcessCwd } from '../../shared/libproc-addon'

// Coalesce/cache per-PID cwd reads briefly so rapid pane actions cannot accumulate lsof subprocesses.
const CACHE_TTL_MS = 1500
Expand Down Expand Up @@ -61,6 +62,11 @@ async function doResolve(pid: number): Promise<string> {
/* fall through */
}

const inProcess = readLibprocProcessCwd(pid)
if (inProcess !== undefined) {
return inProcess ?? ''
}

try {
// lsof needs -a to AND PID/cwd filters; OR would return unrelated process cwd records.
const stdout = await readCwdWithLsof(pid)
Expand Down
52 changes: 52 additions & 0 deletions src/main/pty-descendant-fresh-table.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { execFile } from 'node:child_process'
import {
inProcessDeadlineAllowanceMs,
inProcessSliceMs,
runPsInProcess
} from '../shared/libproc-process-table'
import { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser'

export const DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000
// Busy hosts can exceed execFile’s 1MB default; truncated output would omit descendants.
const PS_MAX_BUFFER_BYTES = 32 * 1024 * 1024

export type ProcessTableCapture = {
rows: ProcessTableRow[]
/** Start boundary of the scan that produced rows, never a later consumer's time. */
capturedAtMs: number
}

export type ProcessTableReader = {
(timeoutMs?: number): Promise<ProcessTableCapture>
/** Time the reader may spend in process before giving ps its whole timeout; outer deadlines add it. Absent: none. */
deadlineAllowanceMs?: (timeoutMs: number) => number
}

const DESCENDANT_PS_ARGS = ['-axo', 'pid=,ppid=,pgid=,tpgid=,lstart=']

export const readFreshProcessTable: ProcessTableReader = Object.assign(readFreshProcessTableOnce, {
deadlineAllowanceMs: inProcessDeadlineAllowanceMs
})

async function readFreshProcessTableOnce(
timeoutMs = DESCENDANT_SNAPSHOT_TIMEOUT_MS
): Promise<ProcessTableCapture> {
// Stamp before ps starts so a capture-second PID cannot appear older after a clock rollover.
const capturedAtMs = Date.now()
// Pin lstart’s locale so delayed identity checks parse it consistently.
const env = { ...process.env, LANG: 'C', LC_ALL: 'C' }
// Registered now, so no native read submitted before this request serves it; a stalled one leaves ps its full timeout.
const inProcess = await runPsInProcess(DESCENDANT_PS_ARGS, {
env,
timeoutMs: inProcessSliceMs(timeoutMs)
})
if (inProcess && !inProcess.timedOut) {
return { rows: parseProcessTable(inProcess.stdout), capturedAtMs }
}
const options = { maxBuffer: PS_MAX_BUFFER_BYTES, timeout: timeoutMs, env }
return new Promise((resolve, reject) => {
execFile('ps', DESCENDANT_PS_ARGS, { ...options, killSignal: 'SIGKILL' }, (error, stdout) =>
error ? reject(error) : resolve({ rows: parseProcessTable(stdout), capturedAtMs })
)
})
}
Loading
Loading