mirror of
https://github.com/stablyai/orca.git
synced 2026-09-22 00:02:31 +00:00
* feat(ai-vault): isolate scanning in service processes * fix(ai-vault): retire idle service processes * fix(ai-vault): discard unverified cache processes * fix(ai-vault): clear relay sidecar cancel watchdog on acknowledgement A cancelled relay call is settled before its 2s cancel watchdog is armed, so the acknowledgement path bailed out of settle() before clearing the timer. The watchdog then faulted a healthy sidecar two seconds after every aborted scan, killing whatever request had since become active. * fix(ai-vault): clear the pending restart before scheduling another recordFault overwrote this.timer, stranding a restart that dispose() could no longer cancel. * refactor(ai-vault): drop the orphaned first-prompt IPC wrapper session-first-user-prompt-handler.ts now owns this entry point and routes through the service; the copy left in the read module had no callers. * fix(ai-vault): retry a faulted cold start before surfacing it A slow first start surfaced a raw 'did not become ready' error to the caller even though the supervisor was already respawning. Requeue an unsent call once onto the scheduled respawn instead. Also stop arming the cancellation watchdog for a call the child never received: no acknowledgement is coming, so it killed a healthy service and stalled the lane. Invalidation bookkeeping and ready-waiter construction move to the state module to stay under the max-lines cap. * fix(ai-vault): give relay title reads their own lane Before this branch the relay read title files directly, concurrently with scans. Routing both through one sidecar lane put title resolution behind a list scan that may run up to 130s, so SSH tab titles could lag minutes behind. Split cache and interactive lanes in both the relay client and the sidecar entry, mirroring the desktop service. Also: clear the ready deadline on fault, so a sidecar that dies before ready cannot fault its healthy replacement five seconds later; retry an unsent call once across a respawn; and skip the cancellation watchdog for a call the sidecar never received. Restart/circuit bookkeeping moves to its own module, mirroring the desktop policy, to stay under the max-lines cap. * fix(ai-vault): degrade relay title resolution on sidecar failure listSessions already returns a host issue when the sidecar is unavailable; titles propagated the raw RPC error instead. Return no titles so callers fall back to preview text, and keep cancellation propagating. * fix(ai-vault): scrub the service child environment The children are forked with a 384 MiB heap cap and no loader, but both spawn sites handed them the full parent environment, so an exported NODE_OPTIONS silently raised the cap or --require'd code into them. Allowlist both, following the plugin worker. The desktop child keeps the eleven agent-root overrides it resolves its own roots from; the relay sidecar takes remoteHome and hostPlatform from its init message and so needs none of them. Both children share one priority module while they share this one. * fix(ai-vault): soft-disable relay vault when the service is missing A missing service threw out of the constructor, so a Vault wiring bug would abort relay startup and take every PTY on the host with it. The unsupported-platform branch three lines above already treats a Vault failure as a soft disable; do the same here. Threading the service through the two handlers instead of a field also retires the definite-assignment assertion the throw was propping up. * fix(ai-vault): drain consumed cache invalidations invalidatedPaths was re-applied in every request's finally and never drained, so once N paths had been invalidated every later request paid N evictions for the life of the process; the 4096 cap only bounded how bad that got. The re-apply exists to cover a read that overlapped the invalidation, so drain once nothing is executing. Clearing unconditionally would drop the re-apply for a request still running on the other lane. * fix(ai-vault): keep a busy child through slow invalidation acks invalidate() reused the 5s ready budget as its acknowledgement deadline and killed the child on expiry, so a delete issued during a large scan could kill a healthy process mid-scan and burn a slot toward the restart circuit. Fault only when nothing is executing. Fork IPC ordering already puts the invalidation ahead of any later request, so a busy child owes no ack here, and the 130s/15s request deadlines still catch a wedged one. The start-retry predicate moves to the state module to stay under the line cap, matching the shape the relay client already uses. * fix(ai-vault): report a failed local scan as a host issue A local-scope scan let its error escape to the renderer, which paints it over the session list. Service supervision now produces those errors, so "AI Vault service restart circuit is open." replaced the list. Route local scope through the degradation the all-hosts leg and every SSH leg already use, so it lands as a retryable host issue row instead. Same result shape either way, so no IPC or wire contract changes. * test(ai-vault): cover the relay restart circuit transitions The relay policy shipped without tests. Pin both circuit edges, the aging-out case, the forced-refresh reopen the relay has and the desktop does not, and the backoff schedule. * fix(ai-vault): keep the OpenCode roots in the service child env The scrubbed allowlist dropped XDG_DATA_HOME and OPENCODE_DB, which the child reads to locate the OpenCode store and database. The pre-PR worker thread inherited them, so a user who sets either lost every OpenCode session. * test(ai-vault): anchor the service spawn env assertion
324 lines
13 KiB
TypeScript
324 lines
13 KiB
TypeScript
import { isBuiltin } from 'node:module'
|
|
import { resolve } from 'node:path'
|
|
import { defineConfig, type UserConfig } from 'electron-vite'
|
|
import react from '@vitejs/plugin-react'
|
|
import tailwindcss from '@tailwindcss/vite'
|
|
import { createBootstrapFatalExitBanner } from './config/build-plugins/bootstrap-fatal-exit-banner'
|
|
import { createPlainNodeEntryGuardPlugin } from './config/build-plugins/plain-node-entry-guard'
|
|
import packageJson from './package.json' with { type: 'json' }
|
|
|
|
const BUNDLED_MAIN_DEPENDENCIES = new Set([
|
|
'@xterm/headless',
|
|
'@xterm/addon-serialize',
|
|
'psl',
|
|
// Why: Windows NSIS deploys app.asar before external resources; bootstrap must
|
|
// not race the later resources/node_modules copy.
|
|
'zod'
|
|
])
|
|
const EXTERNAL_MAIN_DEPENDENCIES = Object.keys(packageJson.dependencies).filter(
|
|
(dependency) => !BUNDLED_MAIN_DEPENDENCIES.has(dependency)
|
|
)
|
|
|
|
function isExternalMainModule(source: string): boolean {
|
|
if (isBuiltin(source) || source === 'electron' || source.startsWith('electron/')) {
|
|
return true
|
|
}
|
|
return EXTERNAL_MAIN_DEPENDENCIES.some(
|
|
(dependency) => source === dependency || source.startsWith(`${dependency}/`)
|
|
)
|
|
}
|
|
|
|
// Why: the telemetry transport is gated by two compile-time constants that
|
|
// only the official CI release workflow sets. Contributor / `pnpm dev` /
|
|
// third-party rebuilds must substitute literal `null` at these sites so
|
|
// `IS_OFFICIAL_BUILD` in `src/main/telemetry/client.ts` evaluates `false`
|
|
// at module load and the track() wrapper short-circuits to console-mirror.
|
|
// The substitution happens at compile time — there is no runtime env-var
|
|
// fallback — so a curious contributor cannot spoof transmission with a
|
|
// shell export.
|
|
//
|
|
// CI injects real values via GitHub Actions secrets
|
|
// (ORCA_BUILD_IDENTITY='stable' | 'rc', ORCA_POSTHOG_WRITE_KEY=phc_...);
|
|
// every other build path resolves these env vars to undefined, which the
|
|
// JSON.stringify below folds to the literal `null`. Ambient declarations
|
|
// for the two constants live in `src/types/build-constants.d.ts`.
|
|
const orcaBuildIdentity = process.env.ORCA_BUILD_IDENTITY
|
|
const ORCA_BUILD_IDENTITY_LITERAL =
|
|
orcaBuildIdentity === 'stable' || orcaBuildIdentity === 'rc'
|
|
? JSON.stringify(orcaBuildIdentity)
|
|
: 'null'
|
|
const orcaPostHogWriteKey = process.env.ORCA_POSTHOG_WRITE_KEY
|
|
const ORCA_POSTHOG_WRITE_KEY_LITERAL =
|
|
typeof orcaPostHogWriteKey === 'string' && orcaPostHogWriteKey.length > 0
|
|
? JSON.stringify(orcaPostHogWriteKey)
|
|
: 'null'
|
|
const orcaDiagnosticsTokenUrl = process.env.ORCA_DIAGNOSTICS_TOKEN_URL
|
|
const ORCA_DIAGNOSTICS_TOKEN_URL_LITERAL =
|
|
typeof orcaDiagnosticsTokenUrl === 'string' && orcaDiagnosticsTokenUrl.length > 0
|
|
? JSON.stringify(orcaDiagnosticsTokenUrl)
|
|
: 'null'
|
|
|
|
function createStartupDiagnosticsBanner(chunkName: string): string {
|
|
return `
|
|
;(() => {
|
|
const env = typeof process !== 'undefined' ? process.env : undefined
|
|
const mode = env?.ORCA_STARTUP_DIAGNOSTICS
|
|
if (mode !== '1' && mode !== 'trace') {
|
|
return
|
|
}
|
|
const safeJson = (value) => {
|
|
try {
|
|
return JSON.stringify(value)
|
|
} catch {
|
|
return '"<unserializable>"'
|
|
}
|
|
}
|
|
let closeSync
|
|
let diagnosticFileDescriptor
|
|
let openSync
|
|
let writeSync
|
|
try {
|
|
const fs = require('node:fs')
|
|
closeSync = fs.closeSync
|
|
openSync = fs.openSync
|
|
writeSync = fs.writeSync
|
|
} catch {
|
|
closeSync = undefined
|
|
openSync = undefined
|
|
writeSync = undefined
|
|
}
|
|
const diagnosticFile = env?.ORCA_STARTUP_DIAGNOSTICS_FILE
|
|
if (typeof diagnosticFile === 'string' && diagnosticFile.length > 0 && typeof openSync === 'function') {
|
|
try {
|
|
diagnosticFileDescriptor = openSync(diagnosticFile, 'a', 0o600)
|
|
} catch {
|
|
diagnosticFileDescriptor = undefined
|
|
}
|
|
}
|
|
const writeLine = (message) => {
|
|
try {
|
|
const line = message.endsWith('\\n') ? message : message + '\\n'
|
|
if (typeof writeSync === 'function') {
|
|
writeSync(2, line)
|
|
if (typeof diagnosticFileDescriptor === 'number') {
|
|
writeSync(diagnosticFileDescriptor, line)
|
|
}
|
|
}
|
|
} catch {
|
|
// Diagnostics must never affect startup.
|
|
}
|
|
}
|
|
const chunkName = ${JSON.stringify(chunkName)}
|
|
writeLine('[bootstrap] bundle-enter chunk=' + safeJson(chunkName) + ' pid=' + process.pid + ' ppid=' + process.ppid + ' execPath=' + safeJson(process.execPath) + ' argv=' + safeJson(process.argv) + ' electronRunAsNode=' + safeJson(env?.ELECTRON_RUN_AS_NODE ?? null))
|
|
if (!globalThis.__ORCA_BOOTSTRAP_EXIT_LOG_INSTALLED__) {
|
|
globalThis.__ORCA_BOOTSTRAP_EXIT_LOG_INSTALLED__ = true
|
|
process.once('exit', (code) => {
|
|
writeLine('[bootstrap] process-exit code=' + code)
|
|
if (typeof closeSync === 'function' && typeof diagnosticFileDescriptor === 'number') {
|
|
try {
|
|
closeSync(diagnosticFileDescriptor)
|
|
} catch {
|
|
// Diagnostics must never affect shutdown.
|
|
}
|
|
}
|
|
})
|
|
process.on('uncaughtExceptionMonitor', (error, origin) => {
|
|
const message = error && typeof error === 'object' && 'stack' in error ? error.stack : error
|
|
writeLine('[bootstrap] uncaught-exception origin=' + safeJson(origin) + ' error=' + safeJson(String(message)))
|
|
})
|
|
process.on('unhandledRejection', (reason) => {
|
|
const message = reason && typeof reason === 'object' && 'stack' in reason ? reason.stack : reason
|
|
writeLine('[bootstrap] unhandled-rejection error=' + safeJson(String(message)))
|
|
})
|
|
}
|
|
if (mode === 'trace' && !globalThis.__ORCA_BOOTSTRAP_REQUIRE_TRACE_INSTALLED__) {
|
|
globalThis.__ORCA_BOOTSTRAP_REQUIRE_TRACE_INSTALLED__ = true
|
|
try {
|
|
const Module = require('node:module')
|
|
const originalLoad = Module._load
|
|
const parsedTraceLimit = Number(env?.ORCA_STARTUP_DIAGNOSTICS_TRACE_LIMIT ?? 20000)
|
|
const traceLimit = Number.isFinite(parsedTraceLimit) && parsedTraceLimit > 0 ? parsedTraceLimit : 20000
|
|
let traceLineCount = 0
|
|
let traceLimitReported = false
|
|
const writeTraceLine = (message) => {
|
|
if (traceLineCount >= traceLimit) {
|
|
if (!traceLimitReported) {
|
|
traceLimitReported = true
|
|
writeLine('[bootstrap] require-trace-limit-reached limit=' + safeJson(traceLimit))
|
|
}
|
|
return
|
|
}
|
|
traceLineCount += 1
|
|
writeLine(message)
|
|
}
|
|
Module._load = function (request, parent, isMain) {
|
|
const parentName = parent && parent.filename ? parent.filename : null
|
|
writeTraceLine('[bootstrap] require-start request=' + safeJson(request) + ' parent=' + safeJson(parentName) + ' isMain=' + safeJson(Boolean(isMain)))
|
|
try {
|
|
const result = Reflect.apply(originalLoad, this, arguments)
|
|
writeTraceLine('[bootstrap] require-ok request=' + safeJson(request))
|
|
return result
|
|
} catch (error) {
|
|
const message = error && typeof error === 'object' && 'stack' in error ? error.stack : error
|
|
writeTraceLine('[bootstrap] require-error request=' + safeJson(request) + ' error=' + safeJson(String(message)))
|
|
throw error
|
|
}
|
|
}
|
|
} catch (error) {
|
|
writeLine('[bootstrap] require-trace-install-error error=' + safeJson(String(error)))
|
|
}
|
|
}
|
|
})();
|
|
`
|
|
}
|
|
|
|
function createMainBootstrapPlugin() {
|
|
return {
|
|
name: 'orca-main-bootstrap',
|
|
generateBundle(_options, bundle) {
|
|
const mainChunk = bundle['index.js']
|
|
if (!mainChunk || mainChunk.type !== 'chunk') {
|
|
return
|
|
}
|
|
|
|
// Why: source guards and diagnostics run after Rollup's generated require
|
|
// prelude, too late to handle a missing bootstrap dependency.
|
|
mainChunk.code =
|
|
createBootstrapFatalExitBanner() +
|
|
createStartupDiagnosticsBanner(mainChunk.fileName) +
|
|
mainChunk.code
|
|
}
|
|
}
|
|
}
|
|
|
|
export const electronViteConfig: UserConfig = {
|
|
main: {
|
|
build: {
|
|
// Why: daemon-entry.js is asar-unpacked so child_process.fork() can
|
|
// execute it from disk. Node's module resolution from the unpacked
|
|
// directory cannot reach into app.asar; startup-critical pure JS must
|
|
// also survive a partially copied Windows resources tree.
|
|
externalizeDeps: {
|
|
exclude: [...BUNDLED_MAIN_DEPENDENCIES]
|
|
},
|
|
rollupOptions: {
|
|
// Why: native dependencies must resolve from packaged node_modules,
|
|
// while the unpacked daemon needs its pure-JS xterm graph bundled.
|
|
external: isExternalMainModule,
|
|
input: {
|
|
index: resolve('src/main/index.ts'),
|
|
// Why: sandboxed webview preloads cannot load Rollup helper chunks.
|
|
'browser-window-close-preload': resolve('src/preload/browser-window-close.ts'),
|
|
'daemon-entry': resolve('src/main/daemon/daemon-entry.ts'),
|
|
'plugin-host-entry': resolve('src/main/plugins/plugin-host-entry.ts'),
|
|
'computer-sidecar': resolve('src/main/computer/sidecar-entry.ts'),
|
|
'stt-worker': resolve('src/main/speech/stt-worker.ts'),
|
|
'warp-theme-parser-worker': resolve('src/main/warp-themes/warp-theme-parser-worker.ts'),
|
|
'session-scanner-opencode-sqlite-worker-entry': resolve(
|
|
'src/main/ai-vault/session-scanner-opencode-sqlite-worker-entry.ts'
|
|
),
|
|
'session-scanner-worker-entry': resolve(
|
|
'src/main/ai-vault/session-scanner-worker-entry.ts'
|
|
),
|
|
'session-scanner-service-entry': resolve(
|
|
'src/main/ai-vault/session-scanner-service-entry.ts'
|
|
),
|
|
// Why: libuv spawns processes inline on the calling loop, so the port
|
|
// scan's probe commands run on a worker thread instead of the UI one.
|
|
'port-scan-command-worker-entry': resolve(
|
|
'src/main/ports/port-scan-command-worker-entry.ts'
|
|
),
|
|
// Why: forked with ELECTRON_RUN_AS_NODE so @parcel/watcher faults
|
|
// can't take down the main process (issue #7547).
|
|
'parcel-watcher-process-entry': resolve('src/main/ipc/parcel-watcher-process-entry.ts'),
|
|
// Why: a worker thread survives the macOS 26 AppKit main-thread deadlock
|
|
// without paying for another Electron process.
|
|
'main-thread-hang-watchdog-entry': resolve(
|
|
'src/main/hang-watchdog/main-thread-hang-watchdog-entry.ts'
|
|
),
|
|
// Why: run under ELECTRON_RUN_AS_NODE while the caller blocks on
|
|
// spawnSync — codex app-server trust grants need a live event loop
|
|
// but must finish before a Codex pane launch proceeds.
|
|
'codex/codex-app-server-grant-entry': resolve(
|
|
'src/main/codex/codex-app-server-grant-entry.ts'
|
|
),
|
|
// Why: electron-vite cleans out/main in dev. The dev CLI imports
|
|
// this path for `orca agent hooks ...`, so it must survive rebuilds.
|
|
'agent-hooks/managed-agent-hook-controls': resolve(
|
|
'src/main/agent-hooks/managed-agent-hook-controls.ts'
|
|
),
|
|
// Why: account import mutates the user's macOS Keychain from the CLI.
|
|
'claude-accounts/keychain': resolve('src/main/claude-accounts/keychain.ts')
|
|
},
|
|
// Why: Rolldown's SSR default is ESM, but Electron and sidecar launchers
|
|
// consume these stable CommonJS paths.
|
|
output: {
|
|
format: 'cjs',
|
|
entryFileNames: '[name].js',
|
|
chunkFileNames: 'chunks/[name]-[hash].js'
|
|
},
|
|
plugins: [createMainBootstrapPlugin(), createPlainNodeEntryGuardPlugin()]
|
|
}
|
|
},
|
|
// Why: compile-time substitution for the telemetry gate. See the block
|
|
// above for the full rationale.
|
|
define: {
|
|
ORCA_BUILD_IDENTITY: ORCA_BUILD_IDENTITY_LITERAL,
|
|
ORCA_POSTHOG_WRITE_KEY: ORCA_POSTHOG_WRITE_KEY_LITERAL,
|
|
ORCA_DIAGNOSTICS_TOKEN_URL: ORCA_DIAGNOSTICS_TOKEN_URL_LITERAL
|
|
},
|
|
// Why: @xterm/headless declares "exports": null in package.json, which
|
|
// prevents Vite's default resolver from finding the CJS entry. Point
|
|
// directly at the published main file so the bundler can inline it.
|
|
resolve: {
|
|
alias: {
|
|
'@xterm/headless': resolve('node_modules/@xterm/headless/lib-headless/xterm-headless.js'),
|
|
'@xterm/addon-serialize': resolve(
|
|
'node_modules/@xterm/addon-serialize/lib/addon-serialize.js'
|
|
)
|
|
}
|
|
}
|
|
},
|
|
preload: {
|
|
build: {
|
|
externalizeDeps: {
|
|
exclude: ['@electron-toolkit/preload']
|
|
}
|
|
}
|
|
},
|
|
renderer: {
|
|
resolve: {
|
|
alias: {
|
|
'@renderer': resolve('src/renderer/src'),
|
|
'@': resolve('src/renderer/src')
|
|
}
|
|
},
|
|
plugins: [react(), tailwindcss()],
|
|
worker: {
|
|
format: 'es'
|
|
},
|
|
build: {
|
|
manifest: true,
|
|
modulePreload: { polyfill: true },
|
|
target: 'es2020',
|
|
// Why: the pop-out dashboard is a second top-level window with its own
|
|
// React root. It gets its own HTML entry so it can boot independently of
|
|
// the main window while reusing the same preload/window.api. `index` must
|
|
// stay listed — overriding input otherwise drops electron-vite's default
|
|
// renderer entry.
|
|
rollupOptions: {
|
|
// Why: shared chunks must never import an HTML entry whose module mounts
|
|
// a different React root.
|
|
preserveEntrySignatures: 'strict',
|
|
input: {
|
|
index: resolve('src/renderer/index.html'),
|
|
popout: resolve('src/renderer/popout.html'),
|
|
web: resolve('src/renderer/web-index.html')
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
export default defineConfig(electronViteConfig)
|