fix(terminal): scope macOS daemons to login sessions
This commit is contained in:
@@ -5483,6 +5483,96 @@
|
||||
"Windows native runtime watches bypass this child path; WSL reservation/release is deterministic-contract tested but not live fault-injected, and SSH registration ownership is not live-relay fault-injected."
|
||||
],
|
||||
"demotionRule": "Demote or quarantine if the fault harness flakes without a product or harness bug, if healthy operation exceeds one runtime watcher child, if total physical operation exceeds eight children including retiring generations, if quarantine children outlive their roots or repeat after fusing, if event delivery becomes unbounded, or if metadata/stat work returns to the serve process."
|
||||
},
|
||||
{
|
||||
"id": "terminal-session.macos-login-scope",
|
||||
"title": "macOS daemon PTYs stay inside their owning login session",
|
||||
"maturity": "experimental",
|
||||
"protection": "partial",
|
||||
"owner": "terminal-provider",
|
||||
"layer": "daemon-lifecycle-contract",
|
||||
"surfaces": [
|
||||
"daemon startup",
|
||||
"terminal restore",
|
||||
"macOS logout",
|
||||
"WindowServer recovery",
|
||||
"fast user switching"
|
||||
],
|
||||
"platforms": ["macos"],
|
||||
"providers": ["daemon"],
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["daemon"],
|
||||
"coverageNotes": "Real-socket deterministic tests inject macOS audit-session scopes and cover logout/login rejection, same-session recovery, daemon loss, two-user fast switching, and concurrent clients. A built-daemon fixture covers scoped and unscoped handshakes with a real disposable PTY. Destructive live logout and WindowServer qualification remain uncollected.",
|
||||
"motivatingLinks": ["https://github.com/stablyai/orca/issues/7936"],
|
||||
"invariant": "A client may attach only to a daemon and PTYs in the same valid runtime/login-session scope; a later macOS login or machine boot must not inherit prior-scope PTYs or recovery bytes, while same-session relaunches and independently scoped user accounts retain their sessions.",
|
||||
"oracle": "Create a PTY through an authenticated real-socket client in one injected audit-session scope, disconnect the GUI owner while the daemon survives, and require a later-login scope to fail hello before inventory or createOrAttach. Require same-scope WindowServer/app recovery to return isNew=false with the original PTY PID, daemon loss to return isNew=true, and separate user endpoints to remain independently attachable across switching.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/daemon-login-session-history.test.ts src/main/daemon/macos-gui-session-scope.test.ts src/main/daemon/macos-login-session-lifecycle.test.ts src/main/daemon/daemon-health.test.ts src/main/daemon/daemon-init.test.ts"
|
||||
],
|
||||
"testFiles": [
|
||||
"src/main/daemon/daemon-login-session-history.test.ts",
|
||||
"src/main/daemon/macos-gui-session-scope.test.ts",
|
||||
"src/main/daemon/macos-login-session-lifecycle.test.ts",
|
||||
"src/main/daemon/daemon-health.test.ts",
|
||||
"src/main/daemon/daemon-init.test.ts"
|
||||
],
|
||||
"assertionRefs": [
|
||||
{
|
||||
"file": "src/main/daemon/macos-login-session-lifecycle.test.ts",
|
||||
"assertions": [
|
||||
"a later login is rejected before warm attachment",
|
||||
"WindowServer restart, app crash, and normal reopen preserve the PTY only inside one scope",
|
||||
"reboot creates a fresh PTY",
|
||||
"fast-switched user endpoints remain isolated and independently usable",
|
||||
"concurrent same-scope clients share one PTY"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/main/daemon/daemon-init.test.ts",
|
||||
"assertions": [
|
||||
"scope rejection enters exact-PID bounded daemon replacement",
|
||||
"pre-scope daemons are adopted only when verified process audit identity matches"
|
||||
]
|
||||
}
|
||||
],
|
||||
"evidenceRuns": [
|
||||
{
|
||||
"date": "2026-07-20",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/daemon-login-session-history.test.ts src/main/daemon/macos-gui-session-scope.test.ts src/main/daemon/macos-login-session-lifecycle.test.ts src/main/daemon/daemon-health.test.ts src/main/daemon/daemon-init.test.ts",
|
||||
"result": "passed",
|
||||
"durationSeconds": 0.46,
|
||||
"summary": "Five deterministic scope-resolution, lifecycle, recovery-history, health, and startup-replacement files passed with 103 tests, including independent fast-switched users and repeated audit ids across reboot."
|
||||
}
|
||||
],
|
||||
"runtimeBudget": {
|
||||
"p95Seconds": 5,
|
||||
"scope": "focused daemon lifecycle contract tests"
|
||||
},
|
||||
"flakeHistory": {
|
||||
"status": "unknown",
|
||||
"evidence": "The deterministic local suite and isolated built-daemon smoke passed; CI and soak history are not yet available."
|
||||
},
|
||||
"redGreenEvidence": {
|
||||
"status": "partial",
|
||||
"evidence": "Before the production fence, the deterministic logout fixture warm-attached the prior PTY with isNew=false and PID 7936. The fixed fixture rejects the later scope during hello. Saved CI red artifacts remain uncollected."
|
||||
},
|
||||
"performanceBudget": {
|
||||
"required": true,
|
||||
"evidence": "Desktop startup adds one bounded launchctl process-domain read plus one bounded boot-session sysctl read, with no polling, timers, inventories, or hot-path work. Legacy checks run only for discovered daemon endpoints and reuse the already-resolved boot scope. Login-scoped recovery reuses one tagged directory, preventing per-login directory growth; same-scope restarts retain files while a repeated audit id after reboot cannot."
|
||||
},
|
||||
"promotionCriteria": [
|
||||
"Collect stable CI history for the deterministic macOS gate.",
|
||||
"Run optional destructive qualification in a disposable macOS account or VM for full logout and WindowServer recovery.",
|
||||
"Attach saved intentional-break evidence for scope validation and history isolation."
|
||||
],
|
||||
"knownGaps": [
|
||||
"No real logout, WindowServer termination, or reboot was performed on the developer account.",
|
||||
"The built-daemon smoke is an explicit post-build validation step rather than a source-only test file.",
|
||||
"Linux, Windows, WSL, SSH, and headless paths are contractually unscoped and were checked by existing focused suites rather than live cross-platform hosts."
|
||||
],
|
||||
"demotionRule": "Keep experimental or demote if the gate flakes without a product or harness bug, if a scope mismatch reaches session inventory or PTY attachment, or if same-scope recovery changes daemon or PTY identity."
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# Issue 7936: macOS Login-Session Daemon Lifecycle
|
||||
|
||||
## Automated reproduction
|
||||
|
||||
`src/main/daemon/macos-login-session-lifecycle.test.ts` uses a real daemon server, authenticated clients, Unix socket, and live PTY registry with injected macOS audit-session scopes. Before the fix, the later-login client warm-attached the original PTY and returned `isNew: false`. The fixed contract rejects that client during hello, before session inventory or `createOrAttach`.
|
||||
|
||||
Run:
|
||||
|
||||
```sh
|
||||
pnpm exec vitest run --config config/vitest.config.ts \
|
||||
src/main/daemon/daemon-login-session-history.test.ts \
|
||||
src/main/daemon/macos-gui-session-scope.test.ts \
|
||||
src/main/daemon/macos-login-session-lifecycle.test.ts
|
||||
```
|
||||
|
||||
The suite separately covers:
|
||||
|
||||
- full logout/login: a changed audit-session scope cannot attach;
|
||||
- WindowServer crash/restart: an unchanged scope warm-attaches;
|
||||
- app crash/relaunch: an unchanged scope warm-attaches;
|
||||
- normal quit/reopen: an unchanged scope warm-attaches;
|
||||
- reboot: a changed boot UUID plus daemon loss creates a fresh PTY and discards prior-boot recovery bytes;
|
||||
- fast user switching: a foreign scope is rejected without invalidating the original scoped daemon, and switching back can reattach;
|
||||
- concurrent clients: clients in one scope share one PTY.
|
||||
|
||||
Fast user switching uses independent runtime directories for the two user accounts and proves each daemon/PTY remains independently attachable after the other account becomes active. A separate adversarial same-endpoint case proves a foreign scope cannot inspect or attach the switched-away account's daemon.
|
||||
|
||||
`daemon-init.test.ts` additionally proves a scope-rejected current daemon enters the existing exact-PID bounded replacement path, while a pre-scope daemon is adopted only after its verified process audit session matches.
|
||||
|
||||
## Safe macOS validation
|
||||
|
||||
These checks do not log out the user, kill WindowServer, or access the installed Orca daemon:
|
||||
|
||||
1. Run the focused suites above. The macOS-only resolver test reads the current test process with `/bin/launchctl print pid/<pid>` and asserts a valid UID/audit-session identity.
|
||||
2. Run the daemon client/server, health, init, adapter, and idle-retirement suites. They use temporary directories and isolated socket/token files.
|
||||
3. Build the main process and launch only the built daemon entry against a temporary runtime directory. Pass an injected old scope, create a disposable PTY, then connect with a different scope and verify hello rejection. Terminate only that recorded child PID and verify its socket/token disappear within the shutdown bound.
|
||||
4. Repeat with the same scope and verify the daemon PID and PTY PID remain unchanged across client disconnect/reconnect.
|
||||
5. Repeat with no scope to exercise the headless contract. This must retain existing unscoped behavior.
|
||||
|
||||
An optional manual qualification run may be performed only with explicit permission on a disposable macOS account or VM:
|
||||
|
||||
- normal quit/reopen and forced app-main crash must preserve terminals;
|
||||
- fast-switch to a different account and back must preserve each account independently;
|
||||
- a WindowServer-only restart should preserve terminals when the audit session survives;
|
||||
- full logout/login must replace the old daemon and cold-resume rather than attach its PTYs;
|
||||
- reboot must not claim a warm PTY survived.
|
||||
|
||||
Record the app PID, daemon PID, PTY PID, audit-session scope, and `isNew` result at each boundary. Never use `pkill -f orca`; target only fixture PIDs or the disposable qualification account.
|
||||
|
||||
## Reliability contract
|
||||
|
||||
- Invariant (`terminal-session.macos-login-scope`): a client can attach only to a daemon and PTYs in the same valid runtime/login-session scope.
|
||||
- Failure source: issue 7936, including full logout and WindowServer-recovery reports.
|
||||
- Oracle: a real-socket later-login client is rejected during hello, while same-scope recovery returns `isNew: false` with the original PTY PID.
|
||||
- Gate: experimental entry `terminal-session.macos-login-scope` in `config/reliability-gates.jsonc`.
|
||||
- Performance budget: one bounded `launchctl print pid/<pid>` and one bounded `sysctl kern.bootsessionuuid` at desktop startup, with no polling or hot-path inventory; one scope-tagged recovery slot avoids per-login disk growth.
|
||||
- Diagnostics: daemon logs record accepted/rejected hello outcomes and the rejection reason without terminal output.
|
||||
|
||||
Provider/platform coverage:
|
||||
|
||||
| Area | Coverage |
|
||||
| --- | --- |
|
||||
| Local and daemon PTY | Real-socket lifecycle and built-daemon smoke cover attach identity and exact fixture cleanup. |
|
||||
| SSH/headless | Unaffected: macOS `--serve` and non-GUI runtimes remain unscoped; unscoped built-daemon smoke passes. |
|
||||
| WSL/Linux/Windows | Unaffected by runtime checks; focused daemon suites and Node typecheck pass. |
|
||||
| Mobile/relay | Unaffected: clients continue through the owning desktop/headless runtime provider. |
|
||||
| macOS GUI | Deterministic audit-scope resolver, lifecycle, history-isolation, and startup-replacement coverage passes. |
|
||||
|
||||
Residual gaps: destructive logout, WindowServer termination, reboot, and live multi-account switching were not run on the developer account. They remain optional qualification steps for a disposable account or VM.
|
||||
@@ -8,7 +8,8 @@ import {
|
||||
CLEAN_DISCONNECT_PROTOCOL_VERSION,
|
||||
PROTOCOL_VERSION,
|
||||
NOTIFY_PREFIX,
|
||||
DaemonProtocolError
|
||||
DaemonProtocolError,
|
||||
supportsRuntimeScope
|
||||
} from './types'
|
||||
import type {
|
||||
DaemonEndpointIdentity,
|
||||
@@ -27,6 +28,7 @@ export type DaemonClientOptions = {
|
||||
socketPath: string
|
||||
tokenPath: string
|
||||
protocolVersion?: number
|
||||
runtimeScope?: string
|
||||
}
|
||||
|
||||
type PendingRequest = {
|
||||
@@ -39,6 +41,7 @@ export class DaemonClient {
|
||||
private socketPath: string
|
||||
private tokenPath: string
|
||||
private protocolVersion: number
|
||||
private runtimeScope: string | undefined
|
||||
private clientId = randomUUID()
|
||||
|
||||
private controlSocket: Socket | null = null
|
||||
@@ -68,6 +71,7 @@ export class DaemonClient {
|
||||
this.socketPath = opts.socketPath
|
||||
this.tokenPath = opts.tokenPath
|
||||
this.protocolVersion = opts.protocolVersion ?? PROTOCOL_VERSION
|
||||
this.runtimeScope = opts.runtimeScope
|
||||
}
|
||||
|
||||
isConnected(): boolean {
|
||||
@@ -330,7 +334,8 @@ export class DaemonClient {
|
||||
version: this.protocolVersion,
|
||||
token,
|
||||
clientId: this.clientId,
|
||||
role
|
||||
role,
|
||||
...(this.runtimeScope ? { runtimeScope: this.runtimeScope } : {})
|
||||
}
|
||||
|
||||
let buffer = ''
|
||||
@@ -371,6 +376,13 @@ export class DaemonClient {
|
||||
try {
|
||||
const response = JSON.parse(line) as HelloResponse
|
||||
if (response.ok) {
|
||||
if (
|
||||
supportsRuntimeScope(this.protocolVersion) &&
|
||||
response.runtimeScope !== this.runtimeScope
|
||||
) {
|
||||
finish(new DaemonProtocolError('Runtime scope mismatch'))
|
||||
return
|
||||
}
|
||||
const identity = parseDaemonEndpointIdentity(response.daemonIdentity)
|
||||
if (
|
||||
(this.protocolVersion >= CLEAN_DISCONNECT_PROTOCOL_VERSION && identity === null) ||
|
||||
|
||||
@@ -71,6 +71,23 @@ describe('daemon-entry parseArgs', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('parses the internal macOS runtime scope', () => {
|
||||
expect(
|
||||
parseArgs([
|
||||
'--socket',
|
||||
'/tmp/t.sock',
|
||||
'--token',
|
||||
'/tmp/t.token',
|
||||
'--runtime-scope',
|
||||
'macos-gui:501:100101:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
])
|
||||
).toEqual({
|
||||
socketPath: '/tmp/t.sock',
|
||||
tokenPath: '/tmp/t.token',
|
||||
runtimeScope: 'macos-gui:501:100101:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects either PID-record ownership argument without its pair', () => {
|
||||
expect(() =>
|
||||
parseArgs([
|
||||
|
||||
@@ -19,6 +19,7 @@ export type ParsedDaemonArgs = {
|
||||
tokenPath: string
|
||||
pidPath?: string
|
||||
launchNonce?: string
|
||||
runtimeScope?: string
|
||||
/** Optional — absent for adopted old daemons and tests, which log nothing. */
|
||||
logFilePath?: string
|
||||
}
|
||||
@@ -29,6 +30,7 @@ export function parseArgs(argv: string[]): ParsedDaemonArgs {
|
||||
let logFilePath = ''
|
||||
let pidPath = ''
|
||||
let launchNonce = ''
|
||||
let runtimeScope = ''
|
||||
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
if (argv[i] === '--socket' && argv[i + 1]) {
|
||||
@@ -46,6 +48,9 @@ export function parseArgs(argv: string[]): ParsedDaemonArgs {
|
||||
} else if (argv[i] === '--launch-nonce' && argv[i + 1]) {
|
||||
launchNonce = argv[i + 1]
|
||||
i++
|
||||
} else if (argv[i] === '--runtime-scope' && argv[i + 1]) {
|
||||
runtimeScope = argv[i + 1]
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +66,7 @@ export function parseArgs(argv: string[]): ParsedDaemonArgs {
|
||||
socketPath,
|
||||
tokenPath,
|
||||
...(pidPath ? { pidPath, launchNonce } : {}),
|
||||
...(runtimeScope ? { runtimeScope } : {}),
|
||||
...(logFilePath ? { logFilePath } : {})
|
||||
}
|
||||
}
|
||||
@@ -73,7 +79,7 @@ async function main(): Promise<void> {
|
||||
// an otherwise healthy detached daemon. Swallow it: stderr is diagnostic only.
|
||||
process.stderr.on('error', () => {})
|
||||
|
||||
const { socketPath, tokenPath, pidPath, launchNonce, logFilePath } = parseArgs(
|
||||
const { socketPath, tokenPath, pidPath, launchNonce, runtimeScope, logFilePath } = parseArgs(
|
||||
process.argv.slice(2)
|
||||
)
|
||||
const startedAtMs = Date.now() - process.uptime() * 1000
|
||||
@@ -162,6 +168,7 @@ async function main(): Promise<void> {
|
||||
tokenPath,
|
||||
...(pidPath ? { pidPath } : {}),
|
||||
...(launchNonce ? { launchNonce } : {}),
|
||||
...(runtimeScope ? { runtimeScope } : {}),
|
||||
...(pidPath ? { startedAtMs } : {}),
|
||||
log: daemonLog,
|
||||
preparePtySpawn: runMacosLoginPreflight,
|
||||
|
||||
@@ -147,6 +147,35 @@ describe('daemon health', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects health adoption from a different runtime scope', async () => {
|
||||
const server = new DaemonServer({
|
||||
socketPath,
|
||||
tokenPath,
|
||||
runtimeScope: 'macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900',
|
||||
spawnSubprocess: () => createMockSubprocess()
|
||||
})
|
||||
await server.start()
|
||||
|
||||
try {
|
||||
await expect(
|
||||
checkDaemonHealth(
|
||||
socketPath,
|
||||
tokenPath,
|
||||
'macos-gui:501:2002:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
)
|
||||
).resolves.toBe('rejected')
|
||||
await expect(
|
||||
checkDaemonHealth(
|
||||
socketPath,
|
||||
tokenPath,
|
||||
'macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
)
|
||||
).resolves.toBe('healthy')
|
||||
} finally {
|
||||
await server.shutdown()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not unlink a live socket when the pid file does not match this daemon', async () => {
|
||||
if (process.platform === 'win32') {
|
||||
return
|
||||
|
||||
@@ -80,7 +80,11 @@ function canConnectSocket(socketPath: string): Promise<boolean> {
|
||||
})
|
||||
}
|
||||
|
||||
export function checkDaemonHealth(socketPath: string, tokenPath: string): Promise<DaemonHealth> {
|
||||
export function checkDaemonHealth(
|
||||
socketPath: string,
|
||||
tokenPath: string,
|
||||
runtimeScope?: string
|
||||
): Promise<DaemonHealth> {
|
||||
return new Promise((resolve) => {
|
||||
if (process.platform !== 'win32' && !existsSync(socketPath)) {
|
||||
resolve('unreachable')
|
||||
@@ -119,7 +123,8 @@ export function checkDaemonHealth(socketPath: string, tokenPath: string): Promis
|
||||
version: PROTOCOL_VERSION,
|
||||
token,
|
||||
clientId: 'health-check',
|
||||
role: 'control'
|
||||
role: 'control',
|
||||
...(runtimeScope ? { runtimeScope } : {})
|
||||
}
|
||||
sock?.write(encodeNdjson(hello))
|
||||
}
|
||||
@@ -176,8 +181,12 @@ export function checkDaemonHealth(socketPath: string, tokenPath: string): Promis
|
||||
})
|
||||
}
|
||||
|
||||
export async function healthCheckDaemon(socketPath: string, tokenPath: string): Promise<boolean> {
|
||||
return (await checkDaemonHealth(socketPath, tokenPath)) === 'healthy'
|
||||
export async function healthCheckDaemon(
|
||||
socketPath: string,
|
||||
tokenPath: string,
|
||||
runtimeScope?: string
|
||||
): Promise<boolean> {
|
||||
return (await checkDaemonHealth(socketPath, tokenPath, runtimeScope)) === 'healthy'
|
||||
}
|
||||
|
||||
function isSystemResolverHealth(value: unknown): value is SystemResolverHealth {
|
||||
@@ -187,7 +196,8 @@ function isSystemResolverHealth(value: unknown): value is SystemResolverHealth {
|
||||
export function getMacDaemonSystemResolverHealth(
|
||||
socketPath: string,
|
||||
tokenPath: string,
|
||||
protocolVersion = PROTOCOL_VERSION
|
||||
protocolVersion = PROTOCOL_VERSION,
|
||||
runtimeScope?: string
|
||||
): Promise<SystemResolverHealth> {
|
||||
if (process.platform !== 'darwin') {
|
||||
return Promise.resolve('unknown')
|
||||
@@ -231,7 +241,8 @@ export function getMacDaemonSystemResolverHealth(
|
||||
version: protocolVersion,
|
||||
token,
|
||||
clientId: 'resolver-health-check',
|
||||
role: 'control'
|
||||
role: 'control',
|
||||
...(runtimeScope ? { runtimeScope } : {})
|
||||
}
|
||||
sock?.write(encodeNdjson(hello))
|
||||
}
|
||||
@@ -607,6 +618,17 @@ async function readVerifiedDaemonPid(
|
||||
return parsedPid
|
||||
}
|
||||
|
||||
export async function getVerifiedDaemonPid(
|
||||
runtimeDir: string,
|
||||
socketPath: string,
|
||||
tokenPath: string,
|
||||
protocolVersion = PROTOCOL_VERSION
|
||||
): Promise<number | null> {
|
||||
return (
|
||||
(await readVerifiedDaemonPid(runtimeDir, socketPath, tokenPath, protocolVersion))?.pid ?? null
|
||||
)
|
||||
}
|
||||
|
||||
export async function isDaemonStaleForCurrentBundle(
|
||||
runtimeDir: string,
|
||||
socketPath: string,
|
||||
|
||||
@@ -4,6 +4,7 @@ export type HelloMessage = {
|
||||
token: string
|
||||
clientId: string
|
||||
role: 'control' | 'stream'
|
||||
runtimeScope?: string
|
||||
}
|
||||
|
||||
export type DaemonEndpointIdentity = {
|
||||
@@ -17,4 +18,5 @@ export type HelloResponse = {
|
||||
ok: boolean
|
||||
error?: string
|
||||
daemonIdentity?: DaemonEndpointIdentity
|
||||
runtimeScope?: string
|
||||
}
|
||||
|
||||
@@ -25,10 +25,13 @@ const {
|
||||
healthCheckDaemonMock,
|
||||
getMacDaemonSystemResolverHealthMock,
|
||||
getDaemonLaunchIdentityMock,
|
||||
getVerifiedDaemonPidMock,
|
||||
isDaemonStaleForCurrentBundleMock,
|
||||
killStaleDaemonMock,
|
||||
getProcessStartedAtMsMock,
|
||||
parseDaemonPidFileMock,
|
||||
parseMacosGuiSessionScopeMock,
|
||||
readMacosProcessSessionIdentityMock,
|
||||
unlinkOwnedDaemonPidFileMock,
|
||||
daemonClientMock,
|
||||
spawnerInstances,
|
||||
@@ -82,6 +85,7 @@ const {
|
||||
const healthCheckDaemonMock = vi.fn(async () => true)
|
||||
const getMacDaemonSystemResolverHealthMock = vi.fn(() => 'healthy')
|
||||
const getDaemonLaunchIdentityMock = vi.fn(() => 'match')
|
||||
const getVerifiedDaemonPidMock = vi.fn(async () => 12345)
|
||||
const isDaemonStaleForCurrentBundleMock = vi.fn(() => false)
|
||||
const killStaleDaemonMock = vi.fn(async () => true)
|
||||
const getProcessStartedAtMsMock = vi.fn((): number | null => 1_000_000)
|
||||
@@ -89,6 +93,16 @@ const {
|
||||
(): { pid: number; startedAtMs: number | null } | null => null
|
||||
)
|
||||
const unlinkOwnedDaemonPidFileMock = vi.fn(() => true)
|
||||
const parseMacosGuiSessionScopeMock = vi.fn((scope: string | undefined) => {
|
||||
const parts = scope?.split(':')
|
||||
return parts?.length === 4
|
||||
? { uid: Number(parts[1]), auditSessionId: Number(parts[2]), bootSessionId: parts[3] }
|
||||
: null
|
||||
})
|
||||
const readMacosProcessSessionIdentityMock = vi.fn(async () => ({
|
||||
uid: 501,
|
||||
auditSessionId: 1001
|
||||
}))
|
||||
|
||||
const daemonClientMock = vi.fn().mockImplementation(function MockDaemonClient() {
|
||||
return {
|
||||
@@ -162,10 +176,13 @@ const {
|
||||
healthCheckDaemonMock,
|
||||
getMacDaemonSystemResolverHealthMock,
|
||||
getDaemonLaunchIdentityMock,
|
||||
getVerifiedDaemonPidMock,
|
||||
isDaemonStaleForCurrentBundleMock,
|
||||
killStaleDaemonMock,
|
||||
getProcessStartedAtMsMock,
|
||||
parseDaemonPidFileMock,
|
||||
parseMacosGuiSessionScopeMock,
|
||||
readMacosProcessSessionIdentityMock,
|
||||
unlinkOwnedDaemonPidFileMock,
|
||||
daemonClientMock,
|
||||
spawnerInstances,
|
||||
@@ -201,6 +218,7 @@ type MockAdapter = {
|
||||
historyPath?: string
|
||||
respawn?: () => Promise<void>
|
||||
protocolVersion?: number
|
||||
runtimeScope?: string
|
||||
}
|
||||
getActiveSessionIds: ReturnType<typeof vi.fn>
|
||||
fanoutSyntheticExits: ReturnType<typeof vi.fn>
|
||||
@@ -242,6 +260,7 @@ vi.mock('net', () => ({ connect: netConnectMock }))
|
||||
vi.mock('./daemon-health', () => ({
|
||||
checkDaemonHealth: checkDaemonHealthMock,
|
||||
getDaemonLaunchIdentity: getDaemonLaunchIdentityMock,
|
||||
getVerifiedDaemonPid: getVerifiedDaemonPidMock,
|
||||
getMacDaemonSystemResolverHealth: getMacDaemonSystemResolverHealthMock,
|
||||
healthCheckDaemon: healthCheckDaemonMock,
|
||||
isDaemonStaleForCurrentBundle: isDaemonStaleForCurrentBundleMock,
|
||||
@@ -250,6 +269,11 @@ vi.mock('./daemon-health', () => ({
|
||||
parseDaemonPidFile: parseDaemonPidFileMock
|
||||
}))
|
||||
|
||||
vi.mock('./macos-gui-session-scope', () => ({
|
||||
parseMacosGuiSessionScope: parseMacosGuiSessionScopeMock,
|
||||
readMacosProcessSessionIdentity: readMacosProcessSessionIdentityMock
|
||||
}))
|
||||
|
||||
vi.mock('./client', () => ({ DaemonClient: daemonClientMock }))
|
||||
|
||||
vi.mock('./daemon-spawner', () => ({
|
||||
@@ -398,6 +422,11 @@ async function importFresh() {
|
||||
getMacDaemonSystemResolverHealthMock.mockReset()
|
||||
getMacDaemonSystemResolverHealthMock.mockReturnValue('healthy')
|
||||
getDaemonLaunchIdentityMock.mockClear()
|
||||
getVerifiedDaemonPidMock.mockReset()
|
||||
getVerifiedDaemonPidMock.mockResolvedValue(12345)
|
||||
parseMacosGuiSessionScopeMock.mockClear()
|
||||
readMacosProcessSessionIdentityMock.mockReset()
|
||||
readMacosProcessSessionIdentityMock.mockResolvedValue({ uid: 501, auditSessionId: 1001 })
|
||||
isDaemonStaleForCurrentBundleMock.mockReset()
|
||||
isDaemonStaleForCurrentBundleMock.mockReturnValue(false)
|
||||
killStaleDaemonMock.mockClear()
|
||||
@@ -906,6 +935,76 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => {
|
||||
expect(adapterInstances.some((instance) => instance.protocolVersion === 9)).toBe(true)
|
||||
})
|
||||
|
||||
it('adopts a pre-scope daemon only when its verified process belongs to this login', async () => {
|
||||
const mod = await importFresh()
|
||||
probeSocketExistsMock.mockImplementation((p?: string) => p?.endsWith('daemon-v9.sock') ?? false)
|
||||
netConnectMock.mockImplementation(() => {
|
||||
const handlers: Record<string, (() => void)[]> = { connect: [], error: [] }
|
||||
return {
|
||||
on(event: string, cb: () => void) {
|
||||
handlers[event]?.push(cb)
|
||||
if (event === 'connect') {
|
||||
queueMicrotask(() => cb())
|
||||
}
|
||||
return this
|
||||
},
|
||||
removeListener(event: string, cb: () => void) {
|
||||
handlers[event] = handlers[event]?.filter((handler) => handler !== cb) ?? []
|
||||
return this
|
||||
},
|
||||
destroy() {}
|
||||
}
|
||||
})
|
||||
|
||||
await mod.initDaemonPtyProvider(undefined, {
|
||||
runtimeScope: 'macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
})
|
||||
|
||||
const legacy = adapterInstances.find((instance) => instance.protocolVersion === 9)
|
||||
expect(legacy?.options.runtimeScope).toBe(
|
||||
'macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
)
|
||||
const current = adapterInstances.find(
|
||||
(instance) => instance.protocolVersion === PROTOCOL_VERSION
|
||||
)
|
||||
expect(current?.options.historyPath).toBe(
|
||||
join(FAKE_USER_DATA_PATH, 'terminal-history', 'daemon-login-session')
|
||||
)
|
||||
expect(legacy?.options.historyPath).toBe(join(FAKE_USER_DATA_PATH, 'terminal-history'))
|
||||
expect(getVerifiedDaemonPidMock).toHaveBeenCalled()
|
||||
expect(readMacosProcessSessionIdentityMock).toHaveBeenCalledWith(12345)
|
||||
})
|
||||
|
||||
it('retires a pre-scope daemon from an earlier login instead of discovering its PTYs', async () => {
|
||||
const mod = await importFresh()
|
||||
probeSocketExistsMock.mockImplementation((p?: string) => p?.endsWith('daemon-v9.sock') ?? false)
|
||||
readMacosProcessSessionIdentityMock.mockResolvedValue({ uid: 501, auditSessionId: 2002 })
|
||||
netConnectMock.mockImplementation(() => {
|
||||
const handlers: Record<string, (() => void)[]> = { connect: [], error: [] }
|
||||
return {
|
||||
on(event: string, cb: () => void) {
|
||||
handlers[event]?.push(cb)
|
||||
if (event === 'connect') {
|
||||
queueMicrotask(() => cb())
|
||||
}
|
||||
return this
|
||||
},
|
||||
removeListener(event: string, cb: () => void) {
|
||||
handlers[event] = handlers[event]?.filter((handler) => handler !== cb) ?? []
|
||||
return this
|
||||
},
|
||||
destroy() {}
|
||||
}
|
||||
})
|
||||
|
||||
await mod.initDaemonPtyProvider(undefined, {
|
||||
runtimeScope: 'macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
})
|
||||
|
||||
expect(adapterInstances.some((instance) => instance.protocolVersion === 9)).toBe(false)
|
||||
expect(daemonClientMock).toHaveBeenCalledWith(expect.objectContaining({ protocolVersion: 9 }))
|
||||
})
|
||||
|
||||
it('restart path with no legacy adapters yields a bare DaemonPtyAdapter (not wrapped in a router)', async () => {
|
||||
const mod = await importFresh()
|
||||
await mod.initDaemonPtyProvider()
|
||||
@@ -2558,6 +2657,53 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('replaces a daemon that rejects the new macOS login scope before adoption', async () => {
|
||||
const mod = await importFresh()
|
||||
await mod.initDaemonPtyProvider(undefined, {
|
||||
runtimeScope: 'macos-gui:501:2002:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
})
|
||||
const launcher = spawnerInstances[0].launcher as (
|
||||
socketPath: string,
|
||||
tokenPath: string
|
||||
) => Promise<{ shutdown(): Promise<void> }>
|
||||
checkDaemonHealthMock.mockResolvedValueOnce('rejected')
|
||||
forkMock.mockImplementationOnce(() => ({
|
||||
pid: 12345,
|
||||
on(event: string, cb: (arg?: unknown) => void) {
|
||||
if (event === 'message') {
|
||||
queueMicrotask(() => cb({ type: 'ready', startedAtMs: 1_000_000 }))
|
||||
}
|
||||
return this
|
||||
},
|
||||
off() {
|
||||
return this
|
||||
},
|
||||
disconnect: vi.fn(),
|
||||
unref: vi.fn()
|
||||
}))
|
||||
|
||||
await launcher('/fake/socket', '/fake/token')
|
||||
|
||||
expect(checkDaemonHealthMock).toHaveBeenCalledWith(
|
||||
'/fake/socket',
|
||||
'/fake/token',
|
||||
'macos-gui:501:2002:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
)
|
||||
expect(killStaleDaemonMock).toHaveBeenCalledWith(
|
||||
FAKE_RUNTIME_DIR,
|
||||
'/fake/socket',
|
||||
'/fake/token'
|
||||
)
|
||||
expect(forkMock).toHaveBeenCalledWith(
|
||||
FAKE_DAEMON_ENTRY_PATH,
|
||||
expect.arrayContaining([
|
||||
'--runtime-scope',
|
||||
'macos-gui:501:2002:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
]),
|
||||
expect.objectContaining({ detached: true })
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves a packaged healthy daemon when its app bundle is current', async () => {
|
||||
const mod = await importFresh()
|
||||
await mod.initDaemonPtyProvider()
|
||||
|
||||
+143
-33
@@ -28,11 +28,17 @@ import {
|
||||
import {
|
||||
getMacDaemonSystemResolverHealth,
|
||||
getDaemonLaunchIdentity,
|
||||
getVerifiedDaemonPid,
|
||||
checkDaemonHealth,
|
||||
isDaemonStaleForCurrentBundle,
|
||||
killStaleDaemon,
|
||||
parseDaemonPidFile
|
||||
} from './daemon-health'
|
||||
import {
|
||||
parseMacosGuiSessionScope,
|
||||
readMacosProcessSessionIdentity
|
||||
} from './macos-gui-session-scope'
|
||||
import { prepareDaemonLoginSessionHistoryDir } from './daemon-login-session-history'
|
||||
import {
|
||||
collectPinnedDaemonVersions,
|
||||
materializeRelocatedDaemonHost,
|
||||
@@ -71,6 +77,7 @@ type DaemonProvider = DaemonPtyRouter | DaemonPtyAdapter | DegradedDaemonPtyProv
|
||||
let adapter: DaemonProvider | null = null
|
||||
// Why: coalesce concurrent restartDaemon() calls so two entries can't race the 7-step sequence against a half-spawned replacement.
|
||||
let restartInFlight: Promise<RestartDaemonResult> | null = null
|
||||
let daemonRuntimeScope: string | undefined
|
||||
|
||||
function getRuntimeDir(): string {
|
||||
const dir = join(app.getPath('userData'), 'daemon')
|
||||
@@ -78,10 +85,8 @@ function getRuntimeDir(): string {
|
||||
return dir
|
||||
}
|
||||
|
||||
function getHistoryDir(): string {
|
||||
const dir = join(app.getPath('userData'), 'terminal-history')
|
||||
mkdirSync(dir, { recursive: true })
|
||||
return dir
|
||||
function getHistoryDir(runtimeScope?: string): string {
|
||||
return prepareDaemonLoginSessionHistoryDir(app.getPath('userData'), runtimeScope)
|
||||
}
|
||||
|
||||
function getDaemonEntryPath(): string {
|
||||
@@ -147,9 +152,15 @@ function probeSocket(socketPath: string): Promise<boolean> {
|
||||
async function getAliveDaemonSessionCount(
|
||||
socketPath: string,
|
||||
tokenPath: string,
|
||||
protocolVersion = PROTOCOL_VERSION
|
||||
protocolVersion = PROTOCOL_VERSION,
|
||||
runtimeScope?: string
|
||||
): Promise<number | null> {
|
||||
const client = new DaemonClient({ socketPath, tokenPath, protocolVersion })
|
||||
const client = new DaemonClient({
|
||||
socketPath,
|
||||
tokenPath,
|
||||
protocolVersion,
|
||||
...(runtimeScope ? { runtimeScope } : {})
|
||||
})
|
||||
try {
|
||||
await client.ensureConnected()
|
||||
const result = await client.request<ListSessionsResult>('listSessions', undefined)
|
||||
@@ -164,11 +175,12 @@ async function getAliveDaemonSessionCount(
|
||||
function createPreservedDaemonHandle(
|
||||
runtimeDir: string,
|
||||
protocolVersion = PROTOCOL_VERSION,
|
||||
mode?: 'degraded-new-pty-fallback'
|
||||
mode?: 'degraded-new-pty-fallback',
|
||||
runtimeScope?: string
|
||||
): DaemonProcessHandle {
|
||||
const handle: DaemonProcessHandle = {
|
||||
shutdown: async () => {
|
||||
await cleanupDaemonForProtocol(runtimeDir, protocolVersion)
|
||||
await cleanupDaemonForProtocol(runtimeDir, protocolVersion, runtimeScope)
|
||||
}
|
||||
}
|
||||
if (mode) {
|
||||
@@ -181,9 +193,16 @@ async function holdDaemonAdoptionLease(
|
||||
handle: DaemonProcessHandle,
|
||||
socketPath: string,
|
||||
tokenPath: string,
|
||||
runtimeScope?: string,
|
||||
connectedClient?: DaemonClient
|
||||
): Promise<DaemonProcessHandle> {
|
||||
const client = connectedClient ?? new DaemonClient({ socketPath, tokenPath })
|
||||
const client =
|
||||
connectedClient ??
|
||||
new DaemonClient({
|
||||
socketPath,
|
||||
tokenPath,
|
||||
...(runtimeScope ? { runtimeScope } : {})
|
||||
})
|
||||
try {
|
||||
await client.ensureConnected()
|
||||
} catch (error) {
|
||||
@@ -307,9 +326,15 @@ function isNoSuchProcessError(error: unknown): boolean {
|
||||
async function shouldPreserveDaemonWithLiveSessions(
|
||||
socketPath: string,
|
||||
tokenPath: string,
|
||||
replacementLabel: string
|
||||
replacementLabel: string,
|
||||
runtimeScope?: string
|
||||
): Promise<boolean> {
|
||||
const liveSessionCount = await getAliveDaemonSessionCount(socketPath, tokenPath)
|
||||
const liveSessionCount = await getAliveDaemonSessionCount(
|
||||
socketPath,
|
||||
tokenPath,
|
||||
PROTOCOL_VERSION,
|
||||
runtimeScope
|
||||
)
|
||||
if (liveSessionCount === 0) {
|
||||
return false
|
||||
}
|
||||
@@ -321,12 +346,16 @@ async function shouldPreserveDaemonWithLiveSessions(
|
||||
return true
|
||||
}
|
||||
|
||||
function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher {
|
||||
function createOutOfProcessLauncher(runtimeDir: string, runtimeScope?: string): DaemonLauncher {
|
||||
return async (socketPath, tokenPath, suppliedPidPath, suppliedLaunchNonce) => {
|
||||
const entryPath = getDaemonEntryPath()
|
||||
const pidPath = suppliedPidPath ?? getDaemonPidPath(runtimeDir)
|
||||
const launchNonce = suppliedLaunchNonce ?? randomUUID()
|
||||
let adoptionClient: DaemonClient | null = new DaemonClient({ socketPath, tokenPath })
|
||||
let adoptionClient: DaemonClient | null = new DaemonClient({
|
||||
socketPath,
|
||||
tokenPath,
|
||||
...(runtimeScope ? { runtimeScope } : {})
|
||||
})
|
||||
try {
|
||||
// Why: acquire the full pair before control-only probes so an expired inherited deadline can't fire in the probe-to-adoption gap.
|
||||
await adoptionClient.ensureConnected()
|
||||
@@ -340,18 +369,31 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher {
|
||||
const connectedClient = adoptionClient ?? undefined
|
||||
adoptionClient = null
|
||||
return holdDaemonAdoptionLease(
|
||||
createPreservedDaemonHandle(runtimeDir, PROTOCOL_VERSION, mode),
|
||||
createPreservedDaemonHandle(runtimeDir, PROTOCOL_VERSION, mode, runtimeScope),
|
||||
socketPath,
|
||||
tokenPath,
|
||||
runtimeScope,
|
||||
connectedClient
|
||||
)
|
||||
}
|
||||
try {
|
||||
const health = await checkDaemonHealth(socketPath, tokenPath)
|
||||
const health = await checkDaemonHealth(socketPath, tokenPath, runtimeScope)
|
||||
if (health === 'healthy') {
|
||||
const resolverHealth = await getMacDaemonSystemResolverHealth(socketPath, tokenPath)
|
||||
const resolverHealth = runtimeScope
|
||||
? await getMacDaemonSystemResolverHealth(
|
||||
socketPath,
|
||||
tokenPath,
|
||||
PROTOCOL_VERSION,
|
||||
runtimeScope
|
||||
)
|
||||
: await getMacDaemonSystemResolverHealth(socketPath, tokenPath)
|
||||
if (resolverHealth === 'unhealthy') {
|
||||
const liveSessionCount = await getAliveDaemonSessionCount(socketPath, tokenPath)
|
||||
const liveSessionCount = await getAliveDaemonSessionCount(
|
||||
socketPath,
|
||||
tokenPath,
|
||||
PROTOCOL_VERSION,
|
||||
runtimeScope
|
||||
)
|
||||
if (liveSessionCount !== 0) {
|
||||
console.warn(
|
||||
liveSessionCount === null
|
||||
@@ -361,7 +403,7 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher {
|
||||
return preserveDaemon()
|
||||
}
|
||||
console.warn('[daemon] Replacing daemon with unavailable macOS system resolver')
|
||||
await cleanupDaemonForProtocol(runtimeDir, PROTOCOL_VERSION)
|
||||
await cleanupDaemonForProtocol(runtimeDir, PROTOCOL_VERSION, runtimeScope)
|
||||
} else {
|
||||
// Why: a protocol-healthy daemon can outlive its launching app bundle (dev worktree rebuild, or packaged update replacing the app path).
|
||||
const identity = await getDaemonLaunchIdentity(
|
||||
@@ -384,7 +426,12 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher {
|
||||
? 'launched before the current app bundle was installed'
|
||||
: 'launched from a different app path'
|
||||
if (
|
||||
await shouldPreserveDaemonWithLiveSessions(socketPath, tokenPath, replacementLabel)
|
||||
await shouldPreserveDaemonWithLiveSessions(
|
||||
socketPath,
|
||||
tokenPath,
|
||||
replacementLabel,
|
||||
runtimeScope
|
||||
)
|
||||
) {
|
||||
return preserveDaemon()
|
||||
}
|
||||
@@ -393,7 +440,7 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher {
|
||||
? '[daemon] Replacing daemon launched before the current app bundle was installed'
|
||||
: '[daemon] Replacing daemon launched from a different app path'
|
||||
)
|
||||
await cleanupDaemonForProtocol(runtimeDir, PROTOCOL_VERSION)
|
||||
await cleanupDaemonForProtocol(runtimeDir, PROTOCOL_VERSION, runtimeScope)
|
||||
} else {
|
||||
// Why: healthy daemon from a previous session answered a protocol ping — safe to reuse.
|
||||
return preserveDaemon()
|
||||
@@ -401,7 +448,12 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher {
|
||||
}
|
||||
} else {
|
||||
// Why: a busy machine can time out the health check on a live daemon; re-verify with a session list before killing its sessions.
|
||||
let liveSessionCount = await getAliveDaemonSessionCount(socketPath, tokenPath)
|
||||
let liveSessionCount = await getAliveDaemonSessionCount(
|
||||
socketPath,
|
||||
tokenPath,
|
||||
PROTOCOL_VERSION,
|
||||
runtimeScope
|
||||
)
|
||||
// Why: a wedged-but-connectable daemon (Windows update relaunch) may still own live sessions, so grace-retry before replacing; a permanent wedge (#8689) exhausts the grace, and 'rejected' skips it (handshake refused = never adoptable).
|
||||
let graceRetry = 0
|
||||
while (
|
||||
@@ -410,7 +462,12 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher {
|
||||
graceRetry < WEDGED_DAEMON_GRACE_RETRIES &&
|
||||
(await probeSocket(socketPath))
|
||||
) {
|
||||
liveSessionCount = await getAliveDaemonSessionCount(socketPath, tokenPath)
|
||||
liveSessionCount = await getAliveDaemonSessionCount(
|
||||
socketPath,
|
||||
tokenPath,
|
||||
PROTOCOL_VERSION,
|
||||
runtimeScope
|
||||
)
|
||||
graceRetry++
|
||||
}
|
||||
if (liveSessionCount !== null && liveSessionCount > 0) {
|
||||
@@ -448,6 +505,7 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher {
|
||||
pidPath,
|
||||
'--launch-nonce',
|
||||
launchNonce,
|
||||
...(runtimeScope ? ['--runtime-scope', runtimeScope] : []),
|
||||
...daemonLogArgs()
|
||||
],
|
||||
{
|
||||
@@ -596,7 +654,8 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher {
|
||||
shutdown: () => terminateLaunchedDaemonChild(child)
|
||||
},
|
||||
socketPath,
|
||||
tokenPath
|
||||
tokenPath,
|
||||
runtimeScope
|
||||
)
|
||||
} catch (error) {
|
||||
// Why: another client may have adopted this live process; keep its pid record until exit, but remove one published after an early exit.
|
||||
@@ -625,7 +684,10 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher {
|
||||
}
|
||||
}
|
||||
|
||||
export async function initDaemonPtyProvider(signal?: AbortSignal): Promise<void> {
|
||||
export async function initDaemonPtyProvider(
|
||||
signal?: AbortSignal,
|
||||
options: { runtimeScope?: string } = {}
|
||||
): Promise<void> {
|
||||
logDaemonMilestone('daemon-init-start')
|
||||
// Why: e2e coverage for the startup PTY gate (#5232) needs a daemon init that deterministically outlasts the first-window timeout.
|
||||
const e2eInitDelayMs = Number(process.env.ORCA_E2E_DAEMON_INIT_DELAY_MS)
|
||||
@@ -636,7 +698,7 @@ export async function initDaemonPtyProvider(signal?: AbortSignal): Promise<void>
|
||||
|
||||
const newSpawner = new DaemonSpawner({
|
||||
runtimeDir,
|
||||
launcher: createOutOfProcessLauncher(runtimeDir)
|
||||
launcher: createOutOfProcessLauncher(runtimeDir, options.runtimeScope)
|
||||
})
|
||||
|
||||
// Why: assign the module-level spawner/adapter only after both succeed, so a failed ensureRunning() leaves no stale spawner.
|
||||
@@ -649,7 +711,8 @@ export async function initDaemonPtyProvider(signal?: AbortSignal): Promise<void>
|
||||
// Why: fail-open may already have spawned fallback PTYs; don't install late, but retire an empty daemon (live sessions reject it and survive).
|
||||
const abortedStartupAdapter = new DaemonPtyAdapter({
|
||||
socketPath: info.socketPath,
|
||||
tokenPath: info.tokenPath
|
||||
tokenPath: info.tokenPath,
|
||||
...(options.runtimeScope ? { runtimeScope: options.runtimeScope } : {})
|
||||
})
|
||||
releaseDaemonAdoptionLease(newSpawner.getHandle())
|
||||
await abortedStartupAdapter.disconnectOnly()
|
||||
@@ -659,7 +722,8 @@ export async function initDaemonPtyProvider(signal?: AbortSignal): Promise<void>
|
||||
const newAdapter = new DaemonPtyAdapter({
|
||||
socketPath: info.socketPath,
|
||||
tokenPath: info.tokenPath,
|
||||
historyPath: getHistoryDir(),
|
||||
...(options.runtimeScope ? { runtimeScope: options.runtimeScope } : {}),
|
||||
historyPath: getHistoryDir(options.runtimeScope),
|
||||
// Why: on daemon death, ensureConnected() detects the dead socket and calls this to fork a replacement before retrying.
|
||||
respawn: async () => {
|
||||
console.warn('[daemon] Daemon process died — respawning')
|
||||
@@ -675,7 +739,7 @@ export async function initDaemonPtyProvider(signal?: AbortSignal): Promise<void>
|
||||
await newAdapter.establishLifecycleLease()
|
||||
releaseDaemonAdoptionLease(newSpawner.getHandle())
|
||||
|
||||
legacyAdapters = await createLegacyDaemonAdapters(runtimeDir)
|
||||
legacyAdapters = await createLegacyDaemonAdapters(runtimeDir, options.runtimeScope)
|
||||
routedAdapter =
|
||||
launchMode === 'degraded-new-pty-fallback'
|
||||
? new DegradedDaemonPtyProvider({
|
||||
@@ -709,6 +773,7 @@ export async function initDaemonPtyProvider(signal?: AbortSignal): Promise<void>
|
||||
throw error
|
||||
}
|
||||
spawner = newSpawner
|
||||
daemonRuntimeScope = options.runtimeScope
|
||||
adapter = routedAdapter
|
||||
setLocalPtyProvider(routedAdapter)
|
||||
// Why: the first window may register PTY listeners before daemon init finishes; rebind so daemon PTYs still fan out events.
|
||||
@@ -827,7 +892,7 @@ async function runRestartDaemon(): Promise<RestartDaemonResult> {
|
||||
// Step 3: kill the current-protocol daemon process; legacy adapters untouched.
|
||||
let info: Awaited<ReturnType<DaemonSpawner['ensureRunning']>>
|
||||
try {
|
||||
await cleanupDaemonForProtocol(runtimeDir, PROTOCOL_VERSION)
|
||||
await cleanupDaemonForProtocol(runtimeDir, PROTOCOL_VERSION, daemonRuntimeScope)
|
||||
|
||||
// Step 4: reuse the existing spawner so the respawn closure baked into long-lived adapters stays valid (do NOT new one).
|
||||
currentSpawner.resetHandle()
|
||||
@@ -842,7 +907,8 @@ async function runRestartDaemon(): Promise<RestartDaemonResult> {
|
||||
const newCurrent = new DaemonPtyAdapter({
|
||||
socketPath: info.socketPath,
|
||||
tokenPath: info.tokenPath,
|
||||
historyPath: getHistoryDir(),
|
||||
...(daemonRuntimeScope ? { runtimeScope: daemonRuntimeScope } : {}),
|
||||
historyPath: getHistoryDir(daemonRuntimeScope),
|
||||
respawn: async () => {
|
||||
console.warn('[daemon] Daemon process died — respawning')
|
||||
currentSpawner.resetHandle()
|
||||
@@ -918,7 +984,8 @@ export type OrphanedDaemonCleanupResult = {
|
||||
|
||||
export async function cleanupDaemonForProtocol(
|
||||
runtimeDir: string,
|
||||
protocolVersion: number
|
||||
protocolVersion: number,
|
||||
runtimeScope?: string
|
||||
): Promise<OrphanedDaemonCleanupResult> {
|
||||
const socketPath = getDaemonSocketPath(runtimeDir, protocolVersion)
|
||||
const tokenPath = getDaemonTokenPath(runtimeDir, protocolVersion)
|
||||
@@ -946,7 +1013,12 @@ export async function cleanupDaemonForProtocol(
|
||||
return { cleaned: false, killedCount: 0 }
|
||||
}
|
||||
|
||||
const client = new DaemonClient({ socketPath, tokenPath, protocolVersion })
|
||||
const client = new DaemonClient({
|
||||
socketPath,
|
||||
tokenPath,
|
||||
protocolVersion,
|
||||
...(runtimeScope ? { runtimeScope } : {})
|
||||
})
|
||||
let killedCount = 0
|
||||
let didRequestShutdown = false
|
||||
let didKillStaleDaemon = false
|
||||
@@ -1020,7 +1092,31 @@ function legacyDaemonProcessMayBeAlive(runtimeDir: string, protocolVersion: numb
|
||||
}
|
||||
}
|
||||
|
||||
async function createLegacyDaemonAdapters(runtimeDir: string): Promise<DaemonPtyAdapter[]> {
|
||||
async function legacyDaemonMatchesRuntimeScope(
|
||||
runtimeDir: string,
|
||||
socketPath: string,
|
||||
tokenPath: string,
|
||||
protocolVersion: number,
|
||||
runtimeScope: string | undefined
|
||||
): Promise<boolean> {
|
||||
if (!runtimeScope) {
|
||||
return true
|
||||
}
|
||||
const expectedIdentity = parseMacosGuiSessionScope(runtimeScope)
|
||||
const pid = await getVerifiedDaemonPid(runtimeDir, socketPath, tokenPath, protocolVersion)
|
||||
const processIdentity = pid === null ? null : await readMacosProcessSessionIdentity(pid)
|
||||
return (
|
||||
expectedIdentity !== null &&
|
||||
processIdentity !== null &&
|
||||
processIdentity.uid === expectedIdentity.uid &&
|
||||
processIdentity.auditSessionId === expectedIdentity.auditSessionId
|
||||
)
|
||||
}
|
||||
|
||||
async function createLegacyDaemonAdapters(
|
||||
runtimeDir: string,
|
||||
runtimeScope?: string
|
||||
): Promise<DaemonPtyAdapter[]> {
|
||||
const adapters: DaemonPtyAdapter[] = []
|
||||
for (const protocolVersion of PREVIOUS_DAEMON_PROTOCOL_VERSIONS) {
|
||||
const socketPath = getDaemonSocketPath(runtimeDir, protocolVersion)
|
||||
@@ -1048,6 +1144,19 @@ async function createLegacyDaemonAdapters(runtimeDir: string): Promise<DaemonPty
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (
|
||||
!(await legacyDaemonMatchesRuntimeScope(
|
||||
runtimeDir,
|
||||
socketPath,
|
||||
tokenPath,
|
||||
protocolVersion,
|
||||
runtimeScope
|
||||
))
|
||||
) {
|
||||
// Why: pre-scope daemons ignore hello metadata, so process audit identity is the only safe upgrade-time attach fence.
|
||||
await cleanupDaemonForProtocol(runtimeDir, protocolVersion)
|
||||
continue
|
||||
}
|
||||
// Keep old-protocol PTYs routed to their original daemon during upgrade; legacy adapters never respawn (new code would recreate stale env semantics).
|
||||
// historyPath is still needed for cleanup — without it a later v4 session reusing the same ID could false-restore stale scrollback.bin.
|
||||
adapters.push(
|
||||
@@ -1055,6 +1164,7 @@ async function createLegacyDaemonAdapters(runtimeDir: string): Promise<DaemonPty
|
||||
socketPath,
|
||||
tokenPath,
|
||||
protocolVersion,
|
||||
...(runtimeScope ? { runtimeScope } : {}),
|
||||
historyPath: getHistoryDir()
|
||||
})
|
||||
)
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { prepareDaemonLoginSessionHistoryDir } from './daemon-login-session-history'
|
||||
|
||||
const tempDirs: string[] = []
|
||||
|
||||
function createUserDataDir(): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'orca-login-history-'))
|
||||
tempDirs.push(dir)
|
||||
return dir
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
describe('daemon login-session history', () => {
|
||||
it('keeps the existing unscoped path for headless and non-macOS runtimes', () => {
|
||||
const userDataPath = createUserDataDir()
|
||||
expect(prepareDaemonLoginSessionHistoryDir(userDataPath)).toBe(
|
||||
join(userDataPath, 'terminal-history')
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves recovery data for the same login scope', () => {
|
||||
const userDataPath = createUserDataDir()
|
||||
const scope = 'macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
const historyDir = prepareDaemonLoginSessionHistoryDir(userDataPath, scope)
|
||||
const sentinel = join(historyDir, 'same-session-checkpoint')
|
||||
writeFileSync(sentinel, 'keep')
|
||||
|
||||
expect(prepareDaemonLoginSessionHistoryDir(userDataPath, scope)).toBe(historyDir)
|
||||
expect(readFileSync(sentinel, 'utf8')).toBe('keep')
|
||||
})
|
||||
|
||||
it('clears recovery data before reusing the slot for a later login scope', () => {
|
||||
const userDataPath = createUserDataDir()
|
||||
const historyDir = prepareDaemonLoginSessionHistoryDir(
|
||||
userDataPath,
|
||||
'macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
)
|
||||
const sentinel = join(historyDir, 'prior-session-checkpoint')
|
||||
writeFileSync(sentinel, 'discard')
|
||||
|
||||
expect(
|
||||
prepareDaemonLoginSessionHistoryDir(
|
||||
userDataPath,
|
||||
'macos-gui:501:2002:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
)
|
||||
).toBe(historyDir)
|
||||
expect(existsSync(sentinel)).toBe(false)
|
||||
expect(
|
||||
readFileSync(join(userDataPath, 'terminal-history', 'daemon-login-session.scope'), 'utf8')
|
||||
).toBe('macos-gui:501:2002:31622fb2-6a38-4323-9678-f0533e61d900')
|
||||
})
|
||||
|
||||
it('clears recovery data when a reboot reuses the same audit session id', () => {
|
||||
const userDataPath = createUserDataDir()
|
||||
const beforeReboot = 'macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
const afterReboot = 'macos-gui:501:1001:a7af08e0-f85c-4aa1-8b57-b087d254dc85'
|
||||
const historyDir = prepareDaemonLoginSessionHistoryDir(userDataPath, beforeReboot)
|
||||
const sentinel = join(historyDir, 'prior-boot-checkpoint')
|
||||
writeFileSync(sentinel, 'discard')
|
||||
|
||||
prepareDaemonLoginSessionHistoryDir(userDataPath, afterReboot)
|
||||
|
||||
expect(existsSync(sentinel)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const LOGIN_SESSION_HISTORY_DIR = 'daemon-login-session'
|
||||
const LOGIN_SESSION_SCOPE_FILE = 'daemon-login-session.scope'
|
||||
|
||||
export function prepareDaemonLoginSessionHistoryDir(
|
||||
userDataPath: string,
|
||||
runtimeScope?: string
|
||||
): string {
|
||||
const baseDir = join(userDataPath, 'terminal-history')
|
||||
if (!runtimeScope) {
|
||||
mkdirSync(baseDir, { recursive: true })
|
||||
return baseDir
|
||||
}
|
||||
|
||||
const historyDir = join(baseDir, LOGIN_SESSION_HISTORY_DIR)
|
||||
const scopePath = join(baseDir, LOGIN_SESSION_SCOPE_FILE)
|
||||
let savedScope: string | null = null
|
||||
try {
|
||||
savedScope = readFileSync(scopePath, 'utf8')
|
||||
} catch {
|
||||
// First scoped launch or an interrupted prior cleanup.
|
||||
}
|
||||
|
||||
if (savedScope !== runtimeScope && existsSync(historyDir)) {
|
||||
// Why: recovery bytes from an invalid login session must never be restored into the new scope.
|
||||
rmSync(historyDir, { recursive: true, force: true })
|
||||
}
|
||||
mkdirSync(historyDir, { recursive: true })
|
||||
if (savedScope !== runtimeScope) {
|
||||
writeFileSync(scopePath, runtimeScope, { mode: 0o600 })
|
||||
}
|
||||
return historyDir
|
||||
}
|
||||
@@ -9,6 +9,7 @@ export type DaemonStartOptions = {
|
||||
startedAtMs?: number
|
||||
/** Direct-construction seam for versioned protocol fixtures; never CLI/env configured. */
|
||||
protocolVersion?: number
|
||||
runtimeScope?: string
|
||||
spawnSubprocess: DaemonServerOptions['spawnSubprocess']
|
||||
preparePtySpawn?: DaemonServerOptions['preparePtySpawn']
|
||||
log?: DaemonFileLog
|
||||
@@ -28,6 +29,7 @@ export async function startDaemon(opts: DaemonStartOptions): Promise<DaemonHandl
|
||||
...(opts.launchNonce ? { launchNonce: opts.launchNonce } : {}),
|
||||
...(opts.startedAtMs ? { startedAtMs: opts.startedAtMs } : {}),
|
||||
...(opts.protocolVersion !== undefined ? { protocolVersion: opts.protocolVersion } : {}),
|
||||
...(opts.runtimeScope ? { runtimeScope: opts.runtimeScope } : {}),
|
||||
spawnSubprocess: opts.spawnSubprocess,
|
||||
...(opts.preparePtySpawn ? { preparePtySpawn: opts.preparePtySpawn } : {}),
|
||||
...(opts.log ? { log: opts.log } : {}),
|
||||
|
||||
@@ -3,6 +3,7 @@ export const PROTOCOL_VERSION = 25
|
||||
export const PTY_STARTUP_INGRESS_PROTOCOL_VERSION = 25
|
||||
export const GIT_CREDENTIAL_GUARD_HOST_PROTOCOL_VERSION = 22
|
||||
export const CLEAN_DISCONNECT_PROTOCOL_VERSION = 24
|
||||
export const RUNTIME_SCOPE_PROTOCOL_VERSION = 25
|
||||
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
|
||||
] as const
|
||||
@@ -10,3 +11,7 @@ export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [
|
||||
export function supportsPtyStartupIngress(protocolVersion: number): boolean {
|
||||
return protocolVersion >= PTY_STARTUP_INGRESS_PROTOCOL_VERSION
|
||||
}
|
||||
|
||||
export function supportsRuntimeScope(protocolVersion: number): boolean {
|
||||
return protocolVersion >= RUNTIME_SCOPE_PROTOCOL_VERSION
|
||||
}
|
||||
|
||||
@@ -66,6 +66,7 @@ export type DaemonPtyAdapterOptions = {
|
||||
socketPath: string
|
||||
tokenPath: string
|
||||
protocolVersion?: number
|
||||
runtimeScope?: string
|
||||
/** Directory for disk-based terminal history; when set, raw PTY output is written to disk for cold restore on daemon crash. */
|
||||
historyPath?: string
|
||||
/** Called when the daemon socket is unreachable; forks a fresh daemon so the next connect can succeed. */
|
||||
@@ -93,6 +94,7 @@ export class DaemonPtyAdapter implements IPtyProvider {
|
||||
readonly protocolVersion: number
|
||||
private socketPath: string
|
||||
private tokenPath: string
|
||||
private runtimeScope: string | undefined
|
||||
private client: DaemonClient
|
||||
private historyManager: HistoryManager | null
|
||||
private historyReader: HistoryReader | null
|
||||
@@ -154,10 +156,12 @@ export class DaemonPtyAdapter implements IPtyProvider {
|
||||
this.protocolVersion = opts.protocolVersion ?? PROTOCOL_VERSION
|
||||
this.socketPath = opts.socketPath
|
||||
this.tokenPath = opts.tokenPath
|
||||
this.runtimeScope = opts.runtimeScope
|
||||
this.client = new DaemonClient({
|
||||
socketPath: opts.socketPath,
|
||||
tokenPath: opts.tokenPath,
|
||||
protocolVersion: opts.protocolVersion
|
||||
protocolVersion: opts.protocolVersion,
|
||||
...(opts.runtimeScope ? { runtimeScope: opts.runtimeScope } : {})
|
||||
})
|
||||
this.historyManager = opts.historyPath ? new HistoryManager(opts.historyPath) : null
|
||||
this.historyReader = opts.historyPath ? new HistoryReader(opts.historyPath) : null
|
||||
@@ -1227,11 +1231,18 @@ export class DaemonPtyAdapter implements IPtyProvider {
|
||||
return
|
||||
}
|
||||
|
||||
const health = await getMacDaemonSystemResolverHealth(
|
||||
this.socketPath,
|
||||
this.tokenPath,
|
||||
this.protocolVersion
|
||||
)
|
||||
const health = this.runtimeScope
|
||||
? await getMacDaemonSystemResolverHealth(
|
||||
this.socketPath,
|
||||
this.tokenPath,
|
||||
this.protocolVersion,
|
||||
this.runtimeScope
|
||||
)
|
||||
: await getMacDaemonSystemResolverHealth(
|
||||
this.socketPath,
|
||||
this.tokenPath,
|
||||
this.protocolVersion
|
||||
)
|
||||
if (health !== 'unhealthy') {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { DaemonEvent, CreateOrAttachResult } from './types'
|
||||
export type DaemonPtyProviderOptions = {
|
||||
socketPath: string
|
||||
tokenPath: string
|
||||
runtimeScope?: string
|
||||
}
|
||||
|
||||
export type DaemonSpawnOptions = {
|
||||
@@ -31,7 +32,8 @@ export class DaemonPtyProvider {
|
||||
constructor(opts: DaemonPtyProviderOptions) {
|
||||
this.client = new DaemonClient({
|
||||
socketPath: opts.socketPath,
|
||||
tokenPath: opts.tokenPath
|
||||
tokenPath: opts.tokenPath,
|
||||
...(opts.runtimeScope ? { runtimeScope: opts.runtimeScope } : {})
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -41,6 +41,7 @@ export type DaemonServerOptions = {
|
||||
startedAtMs?: number
|
||||
/** Direct-construction seam for protocol fixture tests; production never overrides it. */
|
||||
protocolVersion?: number
|
||||
runtimeScope?: string
|
||||
onIdleShutdown?: () => void
|
||||
/** Direct-construction-only controls; production uses the compiled initial-adoption timeout. */
|
||||
initialAdoptionTestConfig?: {
|
||||
@@ -96,6 +97,7 @@ export class DaemonServer {
|
||||
private launchNonce: string | null
|
||||
private startedAtMs: number | null
|
||||
private protocolVersion: number
|
||||
private runtimeScope: string | undefined
|
||||
private onIdleShutdown: () => void
|
||||
private ptySpawnHealthCheck: () => Promise<void>
|
||||
private preparePtySpawn: () => Promise<void>
|
||||
@@ -155,6 +157,7 @@ export class DaemonServer {
|
||||
this.tokenPath = opts.tokenPath
|
||||
this.pidPath = opts.pidPath ?? null
|
||||
this.protocolVersion = opts.protocolVersion ?? PROTOCOL_VERSION
|
||||
this.runtimeScope = opts.runtimeScope
|
||||
this.launchNonce =
|
||||
opts.launchNonce ??
|
||||
(this.protocolVersion >= CLEAN_DISCONNECT_PROTOCOL_VERSION ? randomUUID() : null)
|
||||
@@ -433,6 +436,13 @@ export class DaemonServer {
|
||||
return
|
||||
}
|
||||
|
||||
if (hello.runtimeScope !== this.runtimeScope) {
|
||||
this.log.log('client-hello-rejected', { reason: 'runtime-scope-mismatch', role: hello.role })
|
||||
socket.write(encodeNdjson({ type: 'hello', ok: false, error: 'Runtime scope mismatch' }))
|
||||
socket.destroy()
|
||||
return
|
||||
}
|
||||
|
||||
this.log.log('client-hello-accepted', { role: hello.role, clientId: hello.clientId })
|
||||
socket.write(
|
||||
encodeNdjson({
|
||||
@@ -446,7 +456,8 @@ export class DaemonServer {
|
||||
launchNonce: this.launchNonce
|
||||
}
|
||||
}
|
||||
: {})
|
||||
: {}),
|
||||
...(this.runtimeScope ? { runtimeScope: this.runtimeScope } : {})
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
parseMacosGuiSessionScope,
|
||||
parseMacosProcessSessionIdentity,
|
||||
resolveMacosGuiSessionScope
|
||||
} from './macos-gui-session-scope'
|
||||
|
||||
const BOOT_SESSION_ID = '31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
const PROCESS_DOMAIN = `pid/123 = {
|
||||
type = pid
|
||||
security context = {
|
||||
uid = 501
|
||||
asid = 100101
|
||||
}
|
||||
}`
|
||||
|
||||
describe('macOS GUI session scope', () => {
|
||||
it('parses the audit session and boot identity', () => {
|
||||
expect(parseMacosProcessSessionIdentity(PROCESS_DOMAIN)).toEqual({
|
||||
uid: 501,
|
||||
auditSessionId: 100101
|
||||
})
|
||||
expect(parseMacosGuiSessionScope(`macos-gui:501:100101:${BOOT_SESSION_ID}`)).toEqual({
|
||||
uid: 501,
|
||||
auditSessionId: 100101,
|
||||
bootSessionId: BOOT_SESSION_ID
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects missing, default, zero, and malformed security contexts', () => {
|
||||
expect(parseMacosProcessSessionIdentity('security context = { uid = 501 asid = 0 }')).toBeNull()
|
||||
expect(
|
||||
parseMacosProcessSessionIdentity('security context = { uid = 501 asid = 4294967295 }')
|
||||
).toBeNull()
|
||||
expect(parseMacosProcessSessionIdentity('type = pid')).toBeNull()
|
||||
expect(parseMacosGuiSessionScope(`macos-gui:501:not-a-number:${BOOT_SESSION_ID}`)).toBeNull()
|
||||
expect(parseMacosGuiSessionScope(`macos-gui:501:4294967295:${BOOT_SESSION_ID}`)).toBeNull()
|
||||
expect(parseMacosGuiSessionScope('macos-gui:501:100101:not-a-boot-uuid')).toBeNull()
|
||||
})
|
||||
|
||||
it('resolves a desktop runtime from its audit and boot sessions', async () => {
|
||||
const readProcessDomain = vi.fn(async () => PROCESS_DOMAIN)
|
||||
const readBootSessionId = vi.fn(async () => BOOT_SESSION_ID.toUpperCase())
|
||||
await expect(
|
||||
resolveMacosGuiSessionScope({
|
||||
isGuiRuntime: true,
|
||||
platform: 'darwin',
|
||||
pid: 123,
|
||||
uid: 501,
|
||||
readProcessDomain,
|
||||
readBootSessionId
|
||||
})
|
||||
).resolves.toBe(`macos-gui:501:100101:${BOOT_SESSION_ID}`)
|
||||
expect(readProcessDomain).toHaveBeenCalledWith(123)
|
||||
expect(readBootSessionId).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('fails closed when a desktop runtime cannot prove its user and sessions', async () => {
|
||||
await expect(
|
||||
resolveMacosGuiSessionScope({
|
||||
isGuiRuntime: true,
|
||||
platform: 'darwin',
|
||||
uid: 502,
|
||||
readProcessDomain: async () => PROCESS_DOMAIN,
|
||||
readBootSessionId: async () => BOOT_SESSION_ID
|
||||
})
|
||||
).rejects.toThrow('Cannot determine')
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ platform: 'linux' as const, isGuiRuntime: true },
|
||||
{ platform: 'darwin' as const, isGuiRuntime: false }
|
||||
])('does not scope $platform headless=$isGuiRuntime', async ({ platform, isGuiRuntime }) => {
|
||||
const readProcessDomain = vi.fn(async () => PROCESS_DOMAIN)
|
||||
const readBootSessionId = vi.fn(async () => BOOT_SESSION_ID)
|
||||
await expect(
|
||||
resolveMacosGuiSessionScope({
|
||||
platform,
|
||||
isGuiRuntime,
|
||||
readProcessDomain,
|
||||
readBootSessionId
|
||||
})
|
||||
).resolves.toBeUndefined()
|
||||
expect(readProcessDomain).not.toHaveBeenCalled()
|
||||
expect(readBootSessionId).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.runIf(process.platform === 'darwin')(
|
||||
'reads the current macOS process audit and boot sessions without touching login state',
|
||||
async () => {
|
||||
const scope = await resolveMacosGuiSessionScope({ isGuiRuntime: true })
|
||||
expect(parseMacosGuiSessionScope(scope)).toMatchObject({ uid: process.getuid?.() })
|
||||
}
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,128 @@
|
||||
const MACOS_GUI_SCOPE_PATTERN =
|
||||
/^macos-gui:(\d+):(\d+):([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})$/i
|
||||
// Why: macOS exposes the no-audit-session sentinel (-1) as an unsigned 32-bit value.
|
||||
const MACOS_NO_AUDIT_SESSION_ID = 0xffff_ffff
|
||||
const MACOS_BOOT_SESSION_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i
|
||||
|
||||
export type MacosGuiSessionScope = `macos-gui:${number}:${number}:${string}`
|
||||
export type MacosProcessSessionIdentity = { uid: number; auditSessionId: number }
|
||||
|
||||
type ResolveMacosGuiSessionScopeOptions = {
|
||||
isGuiRuntime: boolean
|
||||
platform?: NodeJS.Platform
|
||||
pid?: number
|
||||
uid?: number
|
||||
readProcessDomain?: (pid: number) => Promise<string>
|
||||
readBootSessionId?: () => Promise<string>
|
||||
}
|
||||
|
||||
function isValidAuditSessionId(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value > 0 && value !== MACOS_NO_AUDIT_SESSION_ID
|
||||
}
|
||||
|
||||
export function parseMacosProcessSessionIdentity(
|
||||
output: string
|
||||
): MacosProcessSessionIdentity | null {
|
||||
const context = /security context\s*=\s*\{([^}]*)\}/s.exec(output)?.[1]
|
||||
if (!context) {
|
||||
return null
|
||||
}
|
||||
const uid = Number(/\buid\s*=\s*(\d+)/.exec(context)?.[1])
|
||||
const auditSessionId = Number(/\basid\s*=\s*(\d+)/.exec(context)?.[1])
|
||||
if (!Number.isSafeInteger(uid) || uid < 0 || !isValidAuditSessionId(auditSessionId)) {
|
||||
return null
|
||||
}
|
||||
return { uid, auditSessionId }
|
||||
}
|
||||
|
||||
export function parseMacosGuiSessionScope(scope: string | undefined):
|
||||
| (MacosProcessSessionIdentity & {
|
||||
bootSessionId: string
|
||||
})
|
||||
| null {
|
||||
const match = scope ? MACOS_GUI_SCOPE_PATTERN.exec(scope) : null
|
||||
if (!match) {
|
||||
return null
|
||||
}
|
||||
const uid = Number(match[1])
|
||||
const auditSessionId = Number(match[2])
|
||||
return Number.isSafeInteger(uid) && isValidAuditSessionId(auditSessionId)
|
||||
? { uid, auditSessionId, bootSessionId: match[3].toLowerCase() }
|
||||
: null
|
||||
}
|
||||
|
||||
async function readLaunchctlProcessDomain(pid: number): Promise<string> {
|
||||
const { execFile } = await import('node:child_process')
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(
|
||||
'/bin/launchctl',
|
||||
['print', `pid/${pid}`],
|
||||
{ encoding: 'utf8', timeout: 1_000, maxBuffer: 64 * 1024 },
|
||||
(error, stdout) => {
|
||||
if (error) {
|
||||
reject(error)
|
||||
} else {
|
||||
resolve(stdout)
|
||||
}
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
async function readMacosBootSessionId(): Promise<string> {
|
||||
// Why: audit session IDs can repeat after reboot; the boot UUID keeps cold recovery fenced too.
|
||||
const { execFile } = await import('node:child_process')
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(
|
||||
'/usr/sbin/sysctl',
|
||||
['-n', 'kern.bootsessionuuid'],
|
||||
{ encoding: 'utf8', timeout: 1_000, maxBuffer: 1024 },
|
||||
(error, stdout) => {
|
||||
if (error) {
|
||||
reject(error)
|
||||
} else {
|
||||
resolve(stdout.trim())
|
||||
}
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
export async function readMacosProcessSessionIdentity(
|
||||
pid: number,
|
||||
readProcessDomain: (pid: number) => Promise<string> = readLaunchctlProcessDomain
|
||||
): Promise<MacosProcessSessionIdentity | null> {
|
||||
if (process.platform !== 'darwin') {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
return parseMacosProcessSessionIdentity(await readProcessDomain(pid))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveMacosGuiSessionScope({
|
||||
isGuiRuntime,
|
||||
platform = process.platform,
|
||||
pid = process.pid,
|
||||
uid = process.getuid?.(),
|
||||
readProcessDomain = readLaunchctlProcessDomain,
|
||||
readBootSessionId = readMacosBootSessionId
|
||||
}: ResolveMacosGuiSessionScopeOptions): Promise<MacosGuiSessionScope | undefined> {
|
||||
if (platform !== 'darwin' || !isGuiRuntime) {
|
||||
return undefined
|
||||
}
|
||||
if (!Number.isSafeInteger(uid) || (uid as number) < 0) {
|
||||
throw new Error('Cannot determine the macOS GUI login-session owner')
|
||||
}
|
||||
const [identity, rawBootSessionId] = await Promise.all([
|
||||
readProcessDomain(pid).then(parseMacosProcessSessionIdentity),
|
||||
readBootSessionId()
|
||||
])
|
||||
const bootSessionId = rawBootSessionId.trim().toLowerCase()
|
||||
if (!identity || identity.uid !== uid || !MACOS_BOOT_SESSION_PATTERN.test(bootSessionId)) {
|
||||
throw new Error('Cannot determine the macOS GUI login-session owner')
|
||||
}
|
||||
return `macos-gui:${identity.uid}:${identity.auditSessionId}:${bootSessionId}`
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { DaemonClient, type DaemonClientOptions } from './client'
|
||||
import { DaemonServer, type DaemonServerOptions } from './daemon-server'
|
||||
import { getDaemonSocketPath } from './daemon-spawner'
|
||||
import type { SubprocessHandle } from './session'
|
||||
|
||||
type SessionScopedClientOptions = DaemonClientOptions & {
|
||||
runtimeScope: string
|
||||
}
|
||||
|
||||
type SessionScopedServerOptions = DaemonServerOptions & {
|
||||
runtimeScope: string
|
||||
}
|
||||
|
||||
function createLiveSubprocess(): SubprocessHandle {
|
||||
let onExit: ((code: number) => void) | null = null
|
||||
return {
|
||||
pid: 7936,
|
||||
getForegroundProcess: () => null,
|
||||
write: vi.fn(),
|
||||
resize: vi.fn(),
|
||||
kill: vi.fn(() => queueMicrotask(() => onExit?.(0))),
|
||||
forceKill: vi.fn(() => queueMicrotask(() => onExit?.(137))),
|
||||
signal: vi.fn(),
|
||||
onData: vi.fn(),
|
||||
onExit: vi.fn((callback) => {
|
||||
onExit = callback
|
||||
}),
|
||||
dispose: vi.fn()
|
||||
}
|
||||
}
|
||||
|
||||
describe('macOS GUI login-session daemon lifecycle', () => {
|
||||
let runtimeDir: string
|
||||
let socketPath: string
|
||||
let tokenPath: string
|
||||
let server: DaemonServer | null
|
||||
const clients: DaemonClient[] = []
|
||||
|
||||
beforeEach(() => {
|
||||
runtimeDir = mkdtempSync(join(tmpdir(), 'orca-macos-login-session-'))
|
||||
socketPath = getDaemonSocketPath(runtimeDir)
|
||||
tokenPath = join(runtimeDir, 'daemon.token')
|
||||
server = null
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
for (const client of clients.splice(0)) {
|
||||
client.disconnect()
|
||||
}
|
||||
await server?.shutdown().catch(() => {})
|
||||
rmSync(runtimeDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function createClient(runtimeScope: string): DaemonClient {
|
||||
const options: SessionScopedClientOptions = { socketPath, tokenPath, runtimeScope }
|
||||
const client = new DaemonClient(options)
|
||||
clients.push(client)
|
||||
return client
|
||||
}
|
||||
|
||||
async function startScopedServer(
|
||||
runtimeScope = 'macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
): Promise<void> {
|
||||
const daemonOptions: SessionScopedServerOptions = {
|
||||
socketPath,
|
||||
tokenPath,
|
||||
runtimeScope,
|
||||
spawnSubprocess: () => createLiveSubprocess()
|
||||
}
|
||||
server = new DaemonServer(daemonOptions)
|
||||
await server.start()
|
||||
}
|
||||
|
||||
async function createTerminal(client: DaemonClient): Promise<{ isNew: boolean; pid: number }> {
|
||||
await client.ensureConnected()
|
||||
return client.request('createOrAttach', {
|
||||
sessionId: 'restored-terminal',
|
||||
cols: 80,
|
||||
rows: 24
|
||||
})
|
||||
}
|
||||
|
||||
it('rejects a later login before it can warm-attach a surviving PTY', async () => {
|
||||
await startScopedServer()
|
||||
|
||||
const originalLogin = createClient('macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900')
|
||||
await expect(createTerminal(originalLogin)).resolves.toMatchObject({ isNew: true })
|
||||
|
||||
// Model logout's observed failure mode: the GUI client exits but its detached daemon survives.
|
||||
originalLogin.disconnect()
|
||||
|
||||
const laterLogin = createClient('macos-gui:501:2002:31622fb2-6a38-4323-9678-f0533e61d900')
|
||||
await expect(createTerminal(laterLogin)).rejects.toThrow('Runtime scope mismatch')
|
||||
})
|
||||
|
||||
it.each(['WindowServer crash/restart', 'app crash/relaunch', 'normal app quit/reopen'])(
|
||||
'preserves the PTY across %s inside the same login session',
|
||||
async () => {
|
||||
await startScopedServer()
|
||||
const originalClient = createClient('macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900')
|
||||
await expect(createTerminal(originalClient)).resolves.toMatchObject({ isNew: true })
|
||||
originalClient.disconnect()
|
||||
|
||||
const replacementClient = createClient(
|
||||
'macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
)
|
||||
await expect(createTerminal(replacementClient)).resolves.toMatchObject({
|
||||
isNew: false,
|
||||
pid: 7936
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
it('models reboot as daemon loss rather than warm PTY inheritance', async () => {
|
||||
await startScopedServer()
|
||||
const beforeReboot = createClient('macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900')
|
||||
await expect(createTerminal(beforeReboot)).resolves.toMatchObject({ isNew: true })
|
||||
beforeReboot.disconnect()
|
||||
await server?.shutdown()
|
||||
|
||||
const rebootedScope = 'macos-gui:501:1001:a7af08e0-f85c-4aa1-8b57-b087d254dc85'
|
||||
await startScopedServer(rebootedScope)
|
||||
const afterReboot = createClient(rebootedScope)
|
||||
await expect(createTerminal(afterReboot)).resolves.toMatchObject({ isNew: true })
|
||||
})
|
||||
|
||||
it('keeps a switched-away login usable after rejecting another login scope', async () => {
|
||||
await startScopedServer()
|
||||
const originalLogin = createClient('macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900')
|
||||
await expect(createTerminal(originalLogin)).resolves.toMatchObject({ isNew: true })
|
||||
originalLogin.disconnect()
|
||||
|
||||
const otherLogin = createClient('macos-gui:502:3003:31622fb2-6a38-4323-9678-f0533e61d900')
|
||||
await expect(createTerminal(otherLogin)).rejects.toThrow('Runtime scope mismatch')
|
||||
|
||||
const switchedBack = createClient('macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900')
|
||||
await expect(createTerminal(switchedBack)).resolves.toMatchObject({
|
||||
isNew: false,
|
||||
pid: 7936
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps fast-switched user accounts isolated on independent daemon endpoints', async () => {
|
||||
const firstUserDir = mkdtempSync(join(tmpdir(), 'orca-macos-fast-switch-user-a-'))
|
||||
const secondUserDir = mkdtempSync(join(tmpdir(), 'orca-macos-fast-switch-user-b-'))
|
||||
const firstServer = new DaemonServer({
|
||||
socketPath: getDaemonSocketPath(firstUserDir),
|
||||
tokenPath: join(firstUserDir, 'daemon.token'),
|
||||
runtimeScope: 'macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900',
|
||||
spawnSubprocess: () => createLiveSubprocess()
|
||||
})
|
||||
const secondServer = new DaemonServer({
|
||||
socketPath: getDaemonSocketPath(secondUserDir),
|
||||
tokenPath: join(secondUserDir, 'daemon.token'),
|
||||
runtimeScope: 'macos-gui:502:2002:31622fb2-6a38-4323-9678-f0533e61d900',
|
||||
spawnSubprocess: () => createLiveSubprocess()
|
||||
})
|
||||
const firstUser = new DaemonClient({
|
||||
socketPath: getDaemonSocketPath(firstUserDir),
|
||||
tokenPath: join(firstUserDir, 'daemon.token'),
|
||||
runtimeScope: 'macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
})
|
||||
const secondUser = new DaemonClient({
|
||||
socketPath: getDaemonSocketPath(secondUserDir),
|
||||
tokenPath: join(secondUserDir, 'daemon.token'),
|
||||
runtimeScope: 'macos-gui:502:2002:31622fb2-6a38-4323-9678-f0533e61d900'
|
||||
})
|
||||
|
||||
try {
|
||||
await Promise.all([firstServer.start(), secondServer.start()])
|
||||
await expect(createTerminal(firstUser)).resolves.toMatchObject({ isNew: true })
|
||||
await expect(createTerminal(secondUser)).resolves.toMatchObject({ isNew: true })
|
||||
firstUser.disconnect()
|
||||
await expect(createTerminal(secondUser)).resolves.toMatchObject({ isNew: false })
|
||||
await expect(createTerminal(firstUser)).resolves.toMatchObject({ isNew: false })
|
||||
} finally {
|
||||
firstUser.disconnect()
|
||||
secondUser.disconnect()
|
||||
await Promise.all([firstServer.shutdown(), secondServer.shutdown()])
|
||||
rmSync(firstUserDir, { recursive: true, force: true })
|
||||
rmSync(secondUserDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('lets concurrent clients in one login session share one PTY', async () => {
|
||||
await startScopedServer()
|
||||
const first = createClient('macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900')
|
||||
const second = createClient('macos-gui:501:1001:31622fb2-6a38-4323-9678-f0533e61d900')
|
||||
|
||||
const results = await Promise.all([createTerminal(first), createTerminal(second)])
|
||||
expect(results.filter((result) => result.isNew)).toHaveLength(1)
|
||||
expect(results.every((result) => result.pid === 7936)).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -21,7 +21,9 @@ export {
|
||||
PREVIOUS_DAEMON_PROTOCOL_VERSIONS,
|
||||
PROTOCOL_VERSION,
|
||||
PTY_STARTUP_INGRESS_PROTOCOL_VERSION,
|
||||
supportsPtyStartupIngress
|
||||
RUNTIME_SCOPE_PROTOCOL_VERSION,
|
||||
supportsPtyStartupIngress,
|
||||
supportsRuntimeScope
|
||||
} from './daemon-protocol-version'
|
||||
|
||||
// ─── Session State Machine ──────────────────────────────────────────
|
||||
|
||||
+3
-1
@@ -23,6 +23,7 @@ import { CodexUsageStore, initCodexUsagePath } from './codex-usage/store'
|
||||
import { OpenCodeUsageStore, initOpenCodeUsagePath } from './opencode-usage/store'
|
||||
import { killAllPty } from './ipc/pty'
|
||||
import { initDaemonPtyProvider, disconnectDaemon, shutdownDaemon } from './daemon/daemon-init'
|
||||
import { resolveMacosGuiSessionScope } from './daemon/macos-gui-session-scope'
|
||||
import { closeAllWatchers } from './ipc/filesystem-watcher'
|
||||
import { disposeWorktreeBaseDirectoryWatchers } from './ipc/worktree-base-directory-watcher'
|
||||
import { registerCoreHandlers } from './ipc/register-core-handlers'
|
||||
@@ -659,7 +660,8 @@ function startTerminalRuntimeStartupServices(): Promise<void> {
|
||||
// Why: both desktop and headless serve must adopt the same persistent provider before creating terminals or a renderer.
|
||||
startDaemonPtyProvider: async (signal) => {
|
||||
logStartupMilestone('startup-service-start', { service: 'daemon-pty-provider' })
|
||||
await initDaemonPtyProvider(signal)
|
||||
const runtimeScope = await resolveMacosGuiSessionScope({ isGuiRuntime: !isServeMode })
|
||||
await initDaemonPtyProvider(signal, runtimeScope ? { runtimeScope } : {})
|
||||
logStartupMilestone('startup-service-done', { service: 'daemon-pty-provider' })
|
||||
},
|
||||
// Why: PTY spawn env reads ORCA_AGENT_HOOK_* from live server state, so the renderer awaits this before restored terminals reconnect.
|
||||
|
||||
Reference in New Issue
Block a user