Files
orca/src/main/runtime/runtime-socket-sweep.test.ts
T
Jinwoo HongandOrca 827b84d27a fix(runtime): add single-instance lock + owned-metadata clear (#1312) (#1326)
* fix(runtime): add single-instance lock + owned-metadata clear to prevent orca-runtime.json corruption

Closes #1312.

Every AppImage/.app relaunch was booting a fresh Electron main that clobbered
`<userData>/orca-runtime.json` and `agent-hooks/endpoint.env`. When the newest
instance quit, metadata pointed at a dead pid and `orca status` reported
`stale_bootstrap` even though the original Orca was still running. SIGKILL'd
predecessors also left orphaned `o-<pid>-*.sock` files in userData.

Three surgical changes:

1. `app.requestSingleInstanceLock()` in a new
   `src/main/startup/single-instance-lock.ts` helper, wired into
   `src/main/index.ts` after `configureDevUserDataPath(is.dev)` so dev and
   packaged runs lock in separate namespaces. Losing instances focus the
   primary's window via `second-instance` and quit without touching userData.

2. `clearRuntimeMetadataIfOwned(userData, pid, runtimeId)` in
   `runtime-metadata.ts` — compares both pid AND runtimeId against the
   current file before clearing, so the auto-updater handoff window never
   erases the replacement process's fresh bootstrap. Called from a rewritten
   `will-quit` handler that folds `runtimeRpc.stop()` + owned-clear into the
   same `Promise.allSettled([disconnectDaemon, …]).then(app.quit)` chain
   (inside the `!daemonDisconnectDone` guard so the second-pass re-entry
   can't re-invoke stop+clear).

3. `sweepOrphanedRuntimeSockets()` in `runtime-rpc.ts` runs at the top of
   `start()` on POSIX, using `process.kill(pid, 0)` to probe liveness and
   remove `o-<dead-pid>-*.sock` orphans left by SIGKILL/OOM-kill.

Tests (37 new/updated):
- `single-instance-lock.test.ts` (3): lock-failed does not register listener;
  lock-acquired registers exactly one; callback dispatches correctly.
- `runtime-metadata.test.ts` (+4): clearRuntimeMetadataIfOwned matched /
  pid-mismatch / runtimeId-mismatch / no-file branches.
- `runtime-socket-sweep.test.ts` (4): own-pid-skip / alive-retain /
  dead-sweep / regex-miss separated via synthetic ownPid=1; two
  regex-invariant tests assert the sweep regex matches the real
  `createRuntimeTransportMetadata` output (including the 'rt' fallback).

Design doc: `docs/fix-missing-single-instance-lock.md`.

Co-authored-by: Orca <help@stably.ai>

* fix(runtime): focus hidden windows on second-instance event

focus() alone is a silent no-op when the primary window is hidden
(close-to-tray on macOS via Cmd+W, or on a different macOS Space) or
behind other apps on Windows. Call show() before focus() so a second
launch attempt reliably surfaces the existing window regardless of
state.

Co-authored-by: Orca <help@stably.ai>

---------

Co-authored-by: Orca <help@stably.ai>
2026-05-02 23:05:14 -07:00

84 lines
3.6 KiB
TypeScript

import { existsSync, mkdtempSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { describe, expect, it } from 'vitest'
import {
createRuntimeTransportMetadata,
RUNTIME_SOCKET_NAME_REGEX,
sweepOrphanedRuntimeSockets
} from './runtime-rpc'
describe('sweepOrphanedRuntimeSockets', () => {
// Why: a pid we know is always alive and is never the test runner's own
// pid — init on POSIX, so process.kill(1, 0) resolves without ESRCH. Using
// this synthetic pid for ownPid cleanly separates three retention branches
// (own-pid-skipped / alive-non-own-retained / dead-swept) into distinct
// observations.
const SYNTHETIC_OWN_PID = 1
const KNOWN_DEAD_PID = 99999999
it.runIf(process.platform !== 'win32')(
'sweeps dead-pid sockets while retaining own, alive, and non-matching entries',
() => {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-sweep-'))
const ownPidSocket = join(userDataPath, `o-${SYNTHETIC_OWN_PID}-aaaa.sock`)
const aliveSocket = join(userDataPath, `o-${process.pid}-bbbb.sock`)
const deadSocket = join(userDataPath, `o-${KNOWN_DEAD_PID}-cccc.sock`)
const unrelatedFile = join(userDataPath, 'foo.sock')
writeFileSync(ownPidSocket, '')
writeFileSync(aliveSocket, '')
writeFileSync(deadSocket, '')
writeFileSync(unrelatedFile, '')
sweepOrphanedRuntimeSockets(userDataPath, SYNTHETIC_OWN_PID)
// Why: own pid (1) is skipped by the ownPid === pid early-exit.
expect(existsSync(ownPidSocket)).toBe(true)
// Why: alive non-own pid — process.kill(pid, 0) succeeds without
// throwing, so the sweep leaves it alone.
expect(existsSync(aliveSocket)).toBe(true)
// Why: dead pid — process.kill throws ESRCH, sweep removes it.
expect(existsSync(deadSocket)).toBe(false)
// Why: regex miss — not `o-<digits>-<suffix>.sock` shape, so the
// sweep never touches it.
expect(existsSync(unrelatedFile)).toBe(true)
}
)
it('tolerates a non-existent userData directory', () => {
const userDataPath = join(tmpdir(), `orca-sweep-missing-${Date.now()}`)
expect(() => sweepOrphanedRuntimeSockets(userDataPath, SYNTHETIC_OWN_PID)).not.toThrow()
})
it('regex invariant: matches sockets produced by createRuntimeTransportMetadata', () => {
// Why: if the socket-name factory ever changes shape (e.g. adds a new
// separator or allows different characters), the sweep will silently
// stop matching real sockets. Assert the two stay in lockstep.
const userDataPath = '/tmp'
const transport = createRuntimeTransportMetadata(userDataPath, 12345, 'linux', 'rt_abcdef')
expect(transport.kind).toBe('unix')
if (transport.kind !== 'unix') {
throw new Error('expected unix transport')
}
const basename = transport.endpoint.slice(transport.endpoint.lastIndexOf('/') + 1)
expect(RUNTIME_SOCKET_NAME_REGEX.test(basename)).toBe(true)
})
it('regex invariant: also matches the fallback runtimeId suffix ("rt")', () => {
// Why: createRuntimeTransportMetadata falls back to the literal 'rt'
// suffix when the runtimeId contains no allowed characters; the sweep
// regex must still match that shape.
const userDataPath = '/tmp'
const transport = createRuntimeTransportMetadata(userDataPath, 99, 'darwin', '!!!!')
if (transport.kind !== 'unix') {
throw new Error('expected unix transport')
}
const basename = transport.endpoint.slice(transport.endpoint.lastIndexOf('/') + 1)
expect(RUNTIME_SOCKET_NAME_REGEX.test(basename)).toBe(true)
expect(basename).toBe('o-99-rt.sock')
})
})