Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Harden isolated test cleanup and lifecycle evidence
wytbc703e2c03fb
diff --git a/test/e2e/fixtures/background-services.ts b/test/e2e/fixtures/background-services.tsindex f3f0ac88..5380d402 100644--- a/test/e2e/fixtures/background-services.ts+++ b/test/e2e/fixtures/background-services.ts@@ -25,6 +25,9 @@ export class BackgroundServices {body = JSON.parse(bytes.toString('utf8'));if (!body || Array.isArray(body) || typeof body !== 'object') throw new Error('invalid');} catch { return { status: 400, body: { code: 1, msg: 'invalid_payload' } }; }+ if (route === '/categories') return { status: 200, body: { code: 0, list: [+ { code: 'general', name_zh: '通用', name_en: 'General', sort_order: 10 },+ ] } };const allowed = ['/agents/list', '/skills/list', '/agents/detail', '/skills/bundle', '/defaults'];if (!allowed.includes(route)) return { status: 404, body: { code: 404, msg: 'e2e_stub_route_not_found' } };if (!this.catalog) {diff --git a/test/e2e/fixtures/orkas.ts b/test/e2e/fixtures/orkas.tsindex 0c3530f7..900698fe 100644--- a/test/e2e/fixtures/orkas.ts+++ b/test/e2e/fixtures/orkas.ts@@ -1,4 +1,4 @@-import { randomInt, randomUUID } from 'node:crypto';+import { createHash, randomInt, randomUUID } from 'node:crypto';import { createServer, type Server } from 'node:http';import {appendFileSync,@@ -14,6 +14,8 @@ import {import { tmpdir } from 'node:os';import path from 'node:path';import type { AddressInfo } from 'node:net';+import type { ChildProcess } from 'node:child_process';+import type { Duplex } from 'node:stream';import AdmZip from 'adm-zip';import { estimateTextTokens } from '../../../src/core-agent/src/agent/session';import { BackgroundServices } from './background-services';@@ -60,7 +62,7 @@ type OrkasOptions = {modelStub?: boolean;marketplaceStub?: boolean;cliStub?: boolean;- updateStub?: boolean;+ voiceStub?: boolean;metacognitionEnabled?: boolean;enableSystemProxy?: boolean;/** Language persisted before launch. `null` deliberately leaves the@@ -94,9 +96,15 @@ export type CliStubState = {modelListResponses: number;codexResumeHangs?: number;codexThreadRequests?: Array<{ method: string; pid: number }>;+ hermesFault?: 'version_unknown' | 'initialize_exit';+ hermesInitializations?: number;};type ModelStubMode = 'success' | 'refusal' | 'http-error' | 'auth-error' | 'model-not-open' | 'slow' | 'very-slow' | 'controlled-slow' | 'truncated';+type VoiceStubMode = 'success' | 'blocked-open';+const VOICE_API_KEY = 'orkas-e2e-voice-api-key-xxxxxxxx';+const VOICE_TICKET = 'E'.repeat(43);+type SystemIdleState = 'active' | 'idle' | 'locked' | 'unknown';type AgentFanoutTarget = {agentId: string;@@ -111,7 +119,7 @@ type ModelToolScenario =}| { kind: 'connector'; connectorId: string }| { kind: 'agent-authoring'; finalText: string }- | { kind: 'saved-tasks'; next: number; projectId: string; finalText: string }+ | { kind: 'saved-tasks'; next: number; finalText: string }| {kind: 'create-pdf';sourceType: 'markdown' | 'html';@@ -254,7 +262,7 @@ function writeJson(filePath: string, value: unknown): void {const TEST_NODE = process.env.ORKAS_TEST_NODE || process.execPath;-function writeNodeExecutable(directory: string, name: string, source: string): string {+function writeNodeExecutable(directory: string, name: string, source: string, versionInScript = false): string {mkdirSync(directory, { recursive: true });const scriptName = `${name}.js`;writeFileSync(path.join(directory, scriptName), source, 'utf8');@@ -279,9 +287,11 @@ function writeNodeExecutable(directory: string, name: string, source: string): sconst safeNode = TEST_NODE.replace(/'/g, `'\\''`);writeFileSync(launcher, ['#!/bin/sh',- 'case "$1" in',- " --version|version) printf '%s\\n' '99.0.0'; exit 0 ;;",- 'esac',+ ...(!versionInScript ? [+ 'case "$1" in',+ " --version|version) printf '%s\\n' '99.0.0'; exit 0 ;;",+ 'esac',+ ] : []),`exec '${safeNode}' "$(dirname "$0")/${scriptName}" "$@"`,'',].join('\n'), 'utf8');@@ -418,17 +428,22 @@ function fakeHermesSource(): string {const fs = require('node:fs');const readline = require('node:readline');const args = process.argv.slice(2);-if (args.includes('--version') || args[0] === 'version') {- process.stdout.write('Hermes Agent v99.0.0\n');- process.exit(0);-}-const statePath = process.env.ORKAS_E2E_CLI_STATE;const blank = () => ({ nextSession: 0, attempts: {}, toolExecutions: 0, invocations: [] });const readState = () => {try { return { ...blank(), ...JSON.parse(fs.readFileSync(statePath, 'utf8')) }; }catch { return blank(); }};+if (args.includes('--version') || args[0] === 'version') {+ process.stdout.write(readState().hermesFault === 'version_unknown'+ ? 'Hermes Agent (version unavailable)\n' : 'Hermes Agent v99.0.0\n');+ process.exit(0);+}+const writeState = state => {+ const tmp = statePath + '.' + String(process.pid) + '.tmp';+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2));+ fs.renameSync(tmp, statePath);+};const send = value => process.stdout.write(JSON.stringify(value) + '\n');let sessionId = '';const input = readline.createInterface({ input: process.stdin });@@ -436,13 +451,17 @@ input.on('line', line => {let message;try { message = JSON.parse(line); } catch { return; }if (message.id === 1) {+ const state = readState();+ state.hermesInitializations = (state.hermesInitializations || 0) + 1;+ writeState(state);+ if (state.hermesFault === 'initialize_exit') process.exit(1);send({ jsonrpc: '2.0', id: 1, result: { protocolVersion: 1 } });return;}if (message.id === 2) {const state = readState();sessionId = 'hermes-e2e-' + String(++state.nextSession);- fs.writeFileSync(statePath, JSON.stringify(state, null, 2));+ writeState(state);send({ jsonrpc: '2.0', id: 2, result: { sessionId } });return;}@@ -452,7 +471,7 @@ input.on('line', line => {state.invocations.push({cli: 'hermes', args, prompt, resumeSessionId: null, sessionId,});- fs.writeFileSync(statePath, JSON.stringify(state, null, 2));+ writeState(state);let text = 'E2E_HERMES_FIRST_OK';if (prompt.includes('E2E_HERMES_CONTINUE') && prompt.includes('E2E_HERMES_PRIOR_FACT')) {text = 'E2E_HERMES_HISTORY_BRIDGED';@@ -493,7 +512,11 @@ const readState = () => {try { return { ...blank(), ...JSON.parse(fs.readFileSync(statePath, 'utf8')) }; }catch { return blank(); }};-const writeState = state => fs.writeFileSync(statePath, JSON.stringify(state, null, 2));+const writeState = state => {+ const tmp = statePath + '.' + String(process.pid) + '.tmp';+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2));+ fs.renameSync(tmp, statePath);+};const send = value => process.stdout.write(JSON.stringify(value) + '\n');const argValue = name => {const index = args.indexOf(name);@@ -626,7 +649,11 @@ const readState = () => {try { return { ...blank(), ...JSON.parse(fs.readFileSync(statePath, 'utf8')) }; }catch { return blank(); }};-const writeState = state => fs.writeFileSync(statePath, JSON.stringify(state, null, 2));+const writeState = state => {+ const tmp = statePath + '.' + String(process.pid) + '.tmp';+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2));+ fs.renameSync(tmp, statePath);+};const send = value => process.stdout.write(JSON.stringify(value) + '\n');let threadId = '';let turnId = '';@@ -750,6 +777,13 @@ input.on('line', line => {send({ method: 'turn/started', params: {threadId, turn: { id: turnId, status: 'inProgress' },} });+ // A cancelled turn can appear in canonical recovery history. Only the+ // current synthetic task selects the post-Stop response; old hang/question+ // markers must not make this fresh request hang again.+ if (prompt.trimEnd().endsWith('E2E_CODEX_AFTER_STOP')) {+ finish('E2E_CODEX_DEFAULT_OK');+ return;+ }if (prompt.includes('E2E_CLI_NATIVE_QUESTION')) {send({ id: 'native-question', method: 'item/tool/requestUserInput', params: {threadId, turnId, itemId: 'native-question', isBlocking: true,@@ -763,6 +797,14 @@ input.on('line', line => {questions: [{ title: 'Which scope?', options: ['Current', 'All'] }],} } });}+ if (prompt.includes('E2E_CODEX_CRASH_PROCESS')) {+ const item = { id: 'crash-tool', type: 'commandExecution', command: 'fixture-check' };+ send({ method: 'item/started', params: { threadId, turnId, item } });+ send({ method: 'item/completed', params: { threadId, turnId, item: {+ ...item, status: 'completed', aggregatedOutput: 'DURABLE_CRASH_RECEIPT', exitCode: 0, durationMs: 25,+ } } });+ return;+ }if (!prompt.includes('E2E_CODEX_SEND_NOW_ACTIVE')) finish('E2E_CODEX_DEFAULT_OK');return;}@@ -857,7 +899,7 @@ export class OrkasTestApp {readonly modelStub: boolean;readonly marketplaceStub: boolean;readonly cliStub: boolean;- readonly updateStub: boolean;+ readonly voiceStub: boolean;readonly metacognitionEnabled: boolean;readonly enableSystemProxy: boolean;readonly appLocale: string;@@ -911,10 +953,9 @@ export class OrkasTestApp {private disposeApiServer: (() => Promise<void>) | null = null;private apiBaseUrl = 'http://127.0.0.1:9/api';private modelStubMode: ModelStubMode = 'success';- private clientConfigGeneration = 0;- private clientConfigImmediate: Record<string, unknown> = {- 'feature.e2e_published': 'generation-a',- };+ private voiceStubMode: VoiceStubMode = 'success';+ private readonly voiceSockets = new Set<Duplex>();+ readonly voiceSessionRequests: Array<{ method: string; path: string; authorized: boolean; body: string }> = [];private readonly modelTimers = new Set<ReturnType<typeof setTimeout>>();private controlledModelStream: {chunkReady: Promise<void>;@@ -931,6 +972,7 @@ export class OrkasTestApp {private traceNumber = 0;private readonly appClosePromises = new WeakMap<ElectronApplication, Promise<void>>();private readonly appTraceStops = new WeakMap<ElectronApplication, Promise<void>>();+ private readonly nativeShutdownProcesses = new WeakMap<ElectronApplication, ChildProcess>();private activeUserId: string;private readonly configuredModelSeededUsers = new Set<string>();private modelToolScenario: ModelToolScenario | null = null;@@ -956,7 +998,7 @@ export class OrkasTestApp {this.modelStub = options.modelStub === true;this.marketplaceStub = options.marketplaceStub === true;this.cliStub = options.cliStub === true;- this.updateStub = options.updateStub === true;+ this.voiceStub = options.voiceStub === true;this.metacognitionEnabled = options.metacognitionEnabled === true;this.enableSystemProxy = options.enableSystemProxy === true;this.appLocale = options.appLocale || '';@@ -975,7 +1017,7 @@ export class OrkasTestApp {? writeNodeExecutable(cliBinRoot, 'opencode-e2e', fakeOpenCodeSource()): null;this.fakeHermesPath = this.cliStub- ? writeNodeExecutable(cliBinRoot, 'hermes-e2e', fakeHermesSource())+ ? writeNodeExecutable(cliBinRoot, 'hermes-e2e', fakeHermesSource(), true): null;this.fakeCodexPath = this.cliStub? writeNodeExecutable(cliBinRoot, 'codex-e2e', fakeCodexSource())@@ -994,22 +1036,6 @@ export class OrkasTestApp {} satisfies CliStubState);}seedWorkspace(this.workspaceRoot, options.seedLanguage);- if (this.updateStub) {- writeJson(- path.join(this.workspaceRoot, this.activeUserId, 'local', 'config', 'remote-config.json'),- {- version: 1,- etag: `"sha256:e2e-client-config-generation"`,- config_hash: 'sha256:e2e-client-config-generation',- last_request_at_ms: Date.now(),- active: {- immediate: { 'feature.e2e_published': 'generation-a' },- restart: {},- },- fetched_at_ms: Date.now(),- },- );- }mkdirSync(this.userDataRoot, { recursive: true });mkdirSync(this.authRoot, { recursive: true });mkdirSync(this.userWorkspaceRoot, { recursive: true });@@ -1018,7 +1044,7 @@ export class OrkasTestApp {async launch(): Promise<void> {if (this.electronApp) throw new Error('Orkas Electron app is already running');this.lastLaunchReadyMs = null;- if (this.modelStub || this.marketplaceStub || this.updateStub) await this.ensureStubServer();+ if (this.modelStub || this.marketplaceStub || this.voiceStub) await this.ensureStubServer();const launchStartedAt = Date.now();const environment: NodeJS.ProcessEnv = {@@ -1181,6 +1207,51 @@ export class OrkasTestApp {return this.page;}+ /** Reopen only after a prepared native exit; never turn this into a quit. */+ async launchAfterNativeExit(expectedApp: ElectronApplication): Promise<Page> {+ if (this.electronApp !== expectedApp) throw new Error('Native exit application is no longer owned');+ const child = this.nativeShutdownProcesses.get(expectedApp);+ const traceStopped = this.appTraceStops.get(expectedApp);+ if (!child || !traceStopped) throw new Error('Native shutdown was not prepared');+ if (child.exitCode !== 0 || child.signalCode !== null) {+ throw new Error('Native application has not exited cleanly');+ }+ if (this.appClosePromises.has(expectedApp)) throw new Error('Application cleanup already started');+ await traceStopped;+ // A teardown/replacement may have won while the export was settling.+ if (this.electronApp !== expectedApp || this.appClosePromises.has(expectedApp)) {+ throw new Error('Native exit ownership changed during trace export');+ }+ this.appClosePromises.set(expectedApp, Promise.resolve());+ this.electronApp = null;+ this.page = null;+ await this.launch();+ if (!this.page) throw new Error('Orkas renderer did not open after native exit');+ return this.page;+ }++ /** A controlled crash is separate from the clean native-exit contract. */+ async launchAfterCrash(expectedApp: ElectronApplication): Promise<Page> {+ if (this.electronApp !== expectedApp) throw new Error('Crash application is no longer owned');+ const child = this.nativeShutdownProcesses.get(expectedApp);+ const traceStopped = this.appTraceStops.get(expectedApp);+ if (!child || !traceStopped) throw new Error('Native crash was not prepared');+ if (child.exitCode !== null || child.signalCode !== 'SIGKILL') {+ throw new Error('Native application has not exited with SIGKILL');+ }+ if (this.appClosePromises.has(expectedApp)) throw new Error('Application cleanup already started');+ await traceStopped;+ if (this.electronApp !== expectedApp || this.appClosePromises.has(expectedApp)) {+ throw new Error('Crash ownership changed during trace export');+ }+ this.appClosePromises.set(expectedApp, Promise.resolve());+ this.electronApp = null;+ this.page = null;+ await this.launch();+ if (!this.page) throw new Error('Orkas renderer did not open after native crash');+ return this.page;+ }+async switchLocalUser(userId: string,_profile: { nickname: string; email: string },@@ -1301,14 +1372,85 @@ export class OrkasTestApp {this.controlledModelStream.releaseFinish();}- setClientConfigImmediate(immediate: Record<string, unknown>): string {- if (!this.updateStub && !this.modelStub) throw new Error('The local client-config stub is not enabled for this fixture');- this.clientConfigGeneration += 1;- this.clientConfigImmediate = {- 'feature.e2e_published': 'generation-a',- ...immediate,- };- return `sha256:e2e-client-config-generation-${this.clientConfigGeneration}`;+ setVoiceMode(mode: VoiceStubMode): void {+ if (!this.voiceStub) throw new Error('The local voice stub is not enabled for this fixture');+ this.voiceStubMode = mode;+ }++ async installVoiceCaptureStub(): Promise<void> {+ if (!this.voiceStub || !this.electronApp || !this.page) {+ throw new Error('The local voice fixture is unavailable');+ }+ await this.electronApp.evaluate(({ systemPreferences }) => {+ const preferences = systemPreferences as any;+ preferences.getMediaAccessStatus = () => 'granted';+ preferences.askForMediaAccess = async () => true;+ });+ await this.invoke('orkasApi.save', { apiKey: VOICE_API_KEY });+ await this.electronApp.evaluate((_electron, input) => {+ const originalFetch = globalThis.fetch;+ const state = globalThis as typeof globalThis & { __e2eVoiceSessionUrls?: string[] };+ state.__e2eVoiceSessionUrls = [];+ globalThis.fetch = ((request: RequestInfo | URL, init?: RequestInit) => {+ const url = typeof request === 'string' ? request : request instanceof URL ? request.href : request.url;+ if (url !== 'https://orkas.ai/v1/audio/transcription_sessions') return originalFetch(request, init);+ state.__e2eVoiceSessionUrls!.push(url);+ return originalFetch(input.localOrigin + '/v1/audio/transcription_sessions', init);+ }) as typeof fetch;+ }, { localOrigin: this.apiBaseUrl.replace(/\/api$/, '') });+ await this.page.evaluate((input) => {+ const NativeWebSocket = window.WebSocket;+ (window as any).__e2eVoiceSocketUrls = [];+ class FixtureWebSocket extends NativeWebSocket {+ constructor(url: string | URL, protocols?: string | string[]) {+ const intended = new URL(String(url));+ if (intended.origin !== 'wss://orkas.ai' || intended.pathname !== '/api/voice/asr_ws'+ || intended.searchParams.get('ticket') !== input.ticket) {+ throw new Error('Unexpected public voice socket URL');+ }+ (window as any).__e2eVoiceSocketUrls.push(intended.toString());+ super(input.localSocketOrigin + intended.pathname + intended.search, protocols);+ }+ }+ Object.defineProperty(window, 'WebSocket', { configurable: true, value: FixtureWebSocket });+ const noopNode = () => ({+ connect() {},+ disconnect() {},+ onaudioprocess: null,+ });+ class FakeAudioContext {+ state = 'running';+ sampleRate = 16_000;+ destination = {};+ createMediaStreamSource() { return noopNode(); }+ createScriptProcessor() { return noopNode(); }+ createGain() {+ return {+ ...noopNode(),+ gain: { value: 1 },+ };+ }+ async resume() {}+ async close() {}+ }+ Object.defineProperty(window, 'AudioContext', {+ configurable: true,+ value: FakeAudioContext,+ });+ Object.defineProperty(navigator, 'mediaDevices', {+ configurable: true,+ value: {+ getUserMedia: async () => ({+ getTracks: () => [{+ stop() {+ (window as any).__e2eVoiceTrackStops =+ Number((window as any).__e2eVoiceTrackStops || 0) + 1;+ },+ }],+ }),+ },+ });+ }, { ticket: VOICE_TICKET, localSocketOrigin: this.apiBaseUrl.replace(/^http/, 'ws').replace(/\/api$/, '') });}setModelTextReplies(replies: string[]): void {@@ -1371,10 +1513,10 @@ export class OrkasTestApp {this.modelToolScenario = null;}- setSavedTasksScenario(projectId: string, finalText: string): void {+ setSavedTasksScenario(finalText: string): void {if (!this.modelStub) throw new Error('The local model stub is not enabled for this fixture');this.modelToolScenarioRequestStart = this.modelRequests.length;- this.modelToolScenario = { kind: 'saved-tasks', next: 0, projectId, finalText };+ this.modelToolScenario = { kind: 'saved-tasks', next: 0, finalText };}setBashDenyScenario(command: string): void {@@ -2024,8 +2166,16 @@ export class OrkasTestApp {/** Export while the browser context exists, before a case confirms native exit. */async prepareForNativeShutdown(): Promise<void> {- if (!this.electronApp) throw new Error('Electron is unavailable');- await this.stopAppTrace(this.electronApp);+ const app = this.electronApp;+ if (!app) throw new Error('Electron is unavailable');+ // Capture while the Playwright application is live. Its disposed channel+ // must not be queried to reconstruct process ownership after native exit.+ if (!this.nativeShutdownProcesses.has(app)) {+ const child = app.process();+ if (!child) throw new Error('Native Electron process is unavailable');+ this.nativeShutdownProcesses.set(app, child);+ }+ await this.stopAppTrace(app);}private stopAppTrace(app: ElectronApplication): Promise<void> {@@ -2084,7 +2234,7 @@ export class OrkasTestApp {});const isChat = requestUrl.pathname === '/api/v1/chat/completions';const isResponses = requestUrl.pathname === '/api/v1/responses';- const isClientConfig = requestUrl.pathname === '/api/config/client';+const isImageCreate = requestUrl.pathname === '/api/e2e-image/generations';const isImageTask = requestUrl.pathname === '/api/e2e-image/generations/e2e-image-task';const isImageOutput = requestUrl.pathname === '/generated/e2e-managed-image.png';@@ -2110,29 +2260,16 @@ export class OrkasTestApp {const marketplacePath = requestUrl.pathname.startsWith('/api/marketplace/')? requestUrl.pathname.slice('/api'.length): '';- if (request.method === 'GET' && isClientConfig) {- const configHash = this.clientConfigGeneration === 0- ? 'sha256:e2e-client-config-generation'- : `sha256:e2e-client-config-generation-${this.clientConfigGeneration}`;- const etag = `"${configHash}"`;- const ifNoneMatch = String(request.headers['if-none-match'] || '');- if (ifNoneMatch.split(',').map((item) => item.trim()).includes(etag)) {- response.writeHead(304, { ETag: etag });- response.end();- return;- }- response.writeHead(200, {- 'Content-Type': 'application/json',- ETag: etag,- 'Cache-Control': 'no-cache',+ if (this.voiceStub && request.method === 'POST' && requestUrl.pathname === '/v1/audio/transcription_sessions') {+ const chunks: Buffer[] = [];+ request.on('data', chunk => chunks.push(Buffer.from(chunk)));+ request.on('end', () => {+ const authorized = request.headers.authorization === `Bearer ${VOICE_API_KEY}`;+ this.voiceSessionRequests.push({ method: request.method!, path: requestUrl.pathname,+ authorized, body: Buffer.concat(chunks).toString('utf8') });+ response.writeHead(authorized ? 200 : 401, { 'Content-Type': 'application/json' });+ response.end(JSON.stringify(authorized ? { ticket: VOICE_TICKET } : { error: 'invalid_api_key' }));});- response.end(JSON.stringify({- code: 0,- schema: 1,- immediate: this.clientConfigImmediate,- restart: {},- config_hash: configHash,- }));return;}if (request.method === 'GET' && requestUrl.pathname === '/marketplace-e2e-skill.zip' && this.marketplaceStub) {@@ -2808,8 +2945,8 @@ export class OrkasTestApp {if (scenario?.kind === 'saved-tasks') {const calls = [- { name: 'auto_tasks', args: { action: 'create', project_id: scenario.projectId, title: 'Nightly review', content: 'Review changes', enabled: false, schedule: { type: 'daily', hour: 0, minute: 0 } } },- { name: 'todo_tasks', args: { action: 'create', project: scenario.projectId, content: 'Review release notes' } },+ { name: 'auto_tasks', args: { action: 'create', title: 'Nightly review', content: 'Review changes', enabled: false, schedule: { type: 'daily', hour: 0, minute: 0 } } },+ { name: 'todo_tasks', args: { action: 'create', content: 'Review release notes' } },{ name: 'auto_tasks', args: { action: 'create', title: 'Rejected automation', content: '' } },];const next = calls[scenario.next];@@ -3467,6 +3604,102 @@ export class OrkasTestApp {finishImmediately(events);});});+ if (this.voiceStub) {+ server.on('upgrade', (request, socket) => {+ const requestUrl = new URL(request.url || '/', 'http://127.0.0.1');+ if (requestUrl.pathname !== '/api/voice/asr_ws' || requestUrl.searchParams.get('ticket') !== VOICE_TICKET) {+ socket.destroy();+ return;+ }+ const key = String(request.headers['sec-websocket-key'] || '');+ if (!key) {+ socket.destroy();+ return;+ }+ this.voiceSockets.add(socket);+ socket.once('close', () => this.voiceSockets.delete(socket));++ const accept = createHash('sha1')+ .update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`)+ .digest('base64');+ const openSocket = () => {+ if (socket.destroyed) return;+ socket.write([+ 'HTTP/1.1 101 Switching Protocols',+ 'Upgrade: websocket',+ 'Connection: Upgrade',+ `Sec-WebSocket-Accept: ${accept}`,+ '',+ '',+ ].join('\r\n'));+ };+ // Keep the HTTP upgrade pending until the client cancels. This makes+ // the negotiation-cancellation contract deterministic under load;+ // a fixed delay can expire before Playwright gets its second click in.+ if (this.voiceStubMode !== 'blocked-open') {+ openSocket();+ }++ let buffered = Buffer.alloc(0);+ socket.on('data', (chunk) => {+ buffered = Buffer.concat([buffered, Buffer.from(chunk)]);+ while (buffered.length >= 2) {+ const opcode = buffered[0] & 0x0f;+ const masked = (buffered[1] & 0x80) !== 0;+ let payloadLength = buffered[1] & 0x7f;+ let offset = 2;+ if (payloadLength === 126) {+ if (buffered.length < 4) return;+ payloadLength = buffered.readUInt16BE(2);+ offset = 4;+ } else if (payloadLength === 127) {+ if (buffered.length < 10) return;+ const longLength = buffered.readBigUInt64BE(2);+ if (longLength > BigInt(Number.MAX_SAFE_INTEGER)) {+ socket.destroy();+ return;+ }+ payloadLength = Number(longLength);+ offset = 10;+ }+ const maskBytes = masked ? 4 : 0;+ if (buffered.length < offset + maskBytes + payloadLength) return;+ const mask = masked ? buffered.subarray(offset, offset + 4) : null;+ offset += maskBytes;+ const payload = Buffer.from(buffered.subarray(offset, offset + payloadLength));+ buffered = buffered.subarray(offset + payloadLength);+ if (mask) {+ for (let index = 0; index < payload.length; index += 1) {+ payload[index] ^= mask[index % 4];+ }+ }+ if (opcode === 0x8) {+ socket.end(Buffer.from([0x88, 0x00]));+ return;+ }+ if (opcode !== 0x1 || payload.toString('utf8') !== '__END__') continue;++ const result = Buffer.from(JSON.stringify({+ is_last_package: true,+ payload_msg: {+ result: {+ text: 'E2E dictated launch note',+ last: true,+ },+ },+ }), 'utf8');+ const header = result.length < 126+ ? Buffer.from([0x81, result.length])+ : Buffer.from([0x81, 126, (result.length >> 8) & 0xff, result.length & 0xff]);+ const timer = setTimeout(() => {+ this.modelTimers.delete(timer);+ if (!socket.destroyed) socket.write(Buffer.concat([header, result]));+ }, 20);+ this.modelTimers.add(timer);+ }+ });+ });+ }// Chromium rejects several legacy ports before a request reaches the// local server. On Windows, listen(0) can still select from the legacy// ephemeral range, so choose from the modern high-port range explicitly.@@ -3515,6 +3748,8 @@ export class OrkasTestApp {this.pendingCommentaryReply = null;for (const timer of this.modelTimers) clearTimeout(timer);this.modelTimers.clear();+ for (const socket of this.voiceSockets) socket.destroy();+ this.voiceSockets.clear();if ('closeAllConnections' in server && typeof server.closeAllConnections === 'function') {server.closeAllConnections();}@@ -3539,7 +3774,7 @@ type OrkasFixtures = {cliOrkas: OrkasTestApp;connectorOrkas: OrkasTestApp;cliModelOrkas: OrkasTestApp;- updateOrkas: OrkasTestApp;+ voiceOrkas: OrkasTestApp;metacognitionOrkas: OrkasTestApp;};@@ -3601,8 +3836,8 @@ export const test = base.extend<OrkasFixtures>({await app.dispose();}},- updateOrkas: async ({}, use, testInfo) => {- const app = new OrkasTestApp(testInfo, { updateStub: true });+ voiceOrkas: async ({}, use, testInfo) => {+ const app = new OrkasTestApp(testInfo, { voiceStub: true });try {await app.launch();await use(app);diff --git a/test/helpers/capture-main-log-workers.ts b/test/helpers/capture-main-log-workers.tsindex 84ac617c..fbb12fda 100644--- a/test/helpers/capture-main-log-workers.ts+++ b/test/helpers/capture-main-log-workers.ts@@ -27,10 +27,12 @@ export async function captureMainLogWorkers(): Promise<() => Promise<void>> {expect(delivery.stats()).toMatchObject({ dropped: 0, failed: false });}} finally {- await Promise.all(deliveries.map(delivery => delivery.close()));- vi.doUnmock('../../src/main/util/log-delivery');- if (previousDisable === undefined) delete process.env.ORKAS_TEST_DISABLE_LOG_DELIVERY;- else process.env.ORKAS_TEST_DISABLE_LOG_DELIVERY = previousDisable;+ try { await Promise.all(deliveries.map(delivery => delivery.close())); }+ finally {+ vi.doUnmock('../../src/main/util/log-delivery');+ if (previousDisable === undefined) delete process.env.ORKAS_TEST_DISABLE_LOG_DELIVERY;+ else process.env.ORKAS_TEST_DISABLE_LOG_DELIVERY = previousDisable;+ }}};}diff --git a/test/helpers/drain-main-runtime.ts b/test/helpers/drain-main-runtime.tsindex ed4848a6..8144263c 100644--- a/test/helpers/drain-main-runtime.ts+++ b/test/helpers/drain-main-runtime.ts@@ -6,9 +6,12 @@export async function drainMainRuntimeForTest(): Promise<void> {// `flushAll` settles deferred chat writes and releases the chat store's// SQLite handle, which Windows needs before the workspace can be removed.- const searchIndexer = await import('../../src/main/features/search/indexer');- await searchIndexer.flushAll();-- const kbVector = await import('../../src/main/features/kb_vector');- kbVector.closeAllKb();+ try {+ const searchIndexer = await import('../../src/main/features/search/indexer');+ await searchIndexer.flushAll();+ }+ finally {+ const kbVector = await import('../../src/main/features/kb_vector');+ kbVector.closeAllKb();+ }}diff --git a/test/helpers/frozen-file-metadata.ts b/test/helpers/frozen-file-metadata.tsnew file mode 100644index 00000000..75701041--- /dev/null+++ b/test/helpers/frozen-file-metadata.ts@@ -0,0 +1,40 @@+import fs from 'node:fs';+import path from 'node:path';+import { syncBuiltinESMExports } from 'node:module';+import { vi } from 'vitest';++/** Reproduce the observed Windows metadata collision without supplying file+ * contents or an expected revision. All reads still use the real changed file. */+export function freezeFileMetadata(files: string[], beforeClose?: (file: string) => Promise<void>): () => void {+ const snapshots = new Map(files.map(file => [path.resolve(file), {+ number: fs.lstatSync(file), bigint: fs.lstatSync(file, { bigint: true }),+ }]));+ const snapshot = (file: unknown, options: any) => typeof file === 'string'+ ? snapshots.get(path.resolve(file))?.[options?.bigint ? 'bigint' : 'number'] : undefined;+ const lstatSync = fs.lstatSync.bind(fs);+ const lstat = fs.promises.lstat.bind(fs.promises);+ const open = fs.promises.open.bind(fs.promises);+ const syncSpy = vi.spyOn(fs, 'lstatSync').mockImplementation(((file: any, options: any) =>+ snapshot(file, options) ?? lstatSync(file, options)) as any);+ const asyncSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation(((file: any, options: any) =>+ snapshot(file, options) ? Promise.resolve(snapshot(file, options)) : lstat(file, options)) as any);+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementation(async (...args) => {+ const handle = await open(...args);+ const stat = handle.stat.bind(handle);+ handle.stat = ((options: any) => snapshot(args[0], options)+ ? Promise.resolve(snapshot(args[0], options)) : stat(options)) as any;+ if (beforeClose) {+ const close = handle.close.bind(handle);+ handle.close = async () => {+ try { await beforeClose(String(args[0])); }+ finally { await close(); }+ };+ }+ return handle;+ });+ syncBuiltinESMExports();+ return () => {+ openSpy.mockRestore(); asyncSpy.mockRestore(); syncSpy.mockRestore();+ syncBuiltinESMExports();+ };+}diff --git a/test/helpers/npm-cli.ts b/test/helpers/npm-cli.tsnew file mode 100644index 00000000..72980860--- /dev/null+++ b/test/helpers/npm-cli.ts@@ -0,0 +1,22 @@+import fs from 'node:fs';+import path from 'node:path';++/** Resolve the installed real npm CLI before fixtures narrow PATH. Node and+ * npm may have separate installation prefixes (for example, Homebrew). */+export function findTestNpmCli(node: string): string | undefined {+ const bin = path.dirname(node);+ const candidates = [+ process.env.npm_execpath,+ path.join(bin, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),+ path.join(bin, 'node_modules', 'npm', 'bin', 'npm-cli.js'),+ ];+ for (const directory of String(process.env.PATH || '').split(path.delimiter)) {+ if (!directory) continue;+ try {+ const entry = fs.realpathSync(path.join(directory, 'npm'));+ if (path.basename(entry) === 'npm-cli.js') candidates.push(entry);+ } catch { /* A PATH entry need not contain npm. */ }+ candidates.push(path.join(directory, 'node_modules', 'npm', 'bin', 'npm-cli.js'));+ }+ return candidates.find((candidate): candidate is string => !!candidate && fs.existsSync(candidate));+}diff --git a/test/helpers/runtime-cleanup.test.ts b/test/helpers/runtime-cleanup.test.tsnew file mode 100644index 00000000..4d18bf4e--- /dev/null+++ b/test/helpers/runtime-cleanup.test.ts@@ -0,0 +1,106 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { EventEmitter } from 'node:events';+import vm from 'node:vm';+import { describe, expect, it, vi } from 'vitest';+import { parseJsonObjectAt } from './parse-json-object';+import { freezeFileMetadata } from './frozen-file-metadata';+import { captureMainLogWorkers } from './capture-main-log-workers';+import { drainMainRuntimeForTest } from './drain-main-runtime';+import { conversationCacheSource, conversationRemovalSource } from '../renderer/conversation-cache-test-source';++describe('reviewed test runtime boundaries', () => {+ it('loads the real conversation cache helpers without replacing newer task state or recounting removal', () => {+ const repaint = vi.fn(), clearRename = vi.fn();+ const context = vm.createContext({+ conversations: [{ conversation_id: 'existing', title: 'User title', title_manually_set: true,+ participants: ['retained'], updated_at: '2026-10-20T00:00:00Z' }],+ _conversationRemovalRevision: 0, _conversationProjectPages: new Map(),+ _unprojectedConversationPage: { total: 1, nextOffset: 1 },+ _clearConversationInlineRenameState: clearRename, renderConversationList: repaint,+ });+ vm.runInContext(conversationCacheSource + '\n' + conversationRemovalSource, context);+ context._cacheCreatedConversation({ conversation_id: 'existing', title: 'Old receipt', participants: [],+ updated_at: '2026-10-19T00:00:00Z' }, 'Optimistic title');+ expect(JSON.parse(JSON.stringify(context.conversations))).toEqual([{ conversation_id: 'existing', title: 'User title',+ title_manually_set: true, participants: ['retained'], updated_at: '2026-10-20T00:00:00Z' }]);+ context._removeConversationFromSidebar('existing'); context._removeConversationFromSidebar('existing');+ expect(context.conversations).toHaveLength(0);+ expect(context._unprojectedConversationPage).toEqual({ total: 0, nextOffset: 0 });+ expect(context._conversationRemovalRevision).toBe(2);+ expect(clearRename).toHaveBeenCalledOnce(); expect(repaint).toHaveBeenCalledOnce();+ });+ it('parses a complete nested JSON object with escaped strings and trailing diagnostics', () => {+ const text = 'prefix {"nested":[{"text":"brace } and \\\"quote\\\""}],"unicode":"雪"} trailing {noise}';+ const result = parseJsonObjectAt<any>(text, text.indexOf('{'));+ expect(result.value).toEqual({ nested: [{ text: 'brace } and "quote"' }], unicode: '雪' });+ expect(text.slice(result.end)).toBe(' trailing {noise}');+ for (const malformed of ['', '[]', '{', '{"text":"unfinished}', '{"bad":}']) {+ expect(() => parseJsonObjectAt(malformed, 0)).toThrow();+ }+ expect(() => parseJsonObjectAt('{}', -1)).toThrow();+ expect(() => parseJsonObjectAt('{}', 2)).toThrow();+ });++ it('closes a real file handle even when the pre-close fault hook rejects', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-metadata-close-'));+ const file = path.join(root, 'fixture.txt'); fs.writeFileSync(file, 'fixture');+ const failure = new Error('synthetic pre-close failure');+ let rejectClose = true;+ const restore = freezeFileMetadata([file], async () => { if (rejectClose) throw failure; });+ const handle = await fs.promises.open(file, 'r');+ try {+ await expect(handle.close()).rejects.toBe(failure);+ await expect(handle.read(Buffer.alloc(1), 0, 1, 0)).rejects.toMatchObject({ code: 'EBADF' });+ } finally {+ rejectClose = false;+ restore();+ // The original implementation leaks the descriptor; ensure RED cleanup+ // does not retain that leak in the test process.+ await handle.close().catch(() => {});+ fs.rmSync(root, { recursive: true, force: true });+ }+ });++ it.each(['load', 'flush'])('still closes KB state after search %s fails, preserving the original failure', async phase => {+ const failure = new Error('synthetic search drain failure'), closeAllKb = vi.fn();+ vi.doMock('../../src/main/features/search/indexer', () => {+ if (phase === 'load') throw failure;+ return { flushAll: async () => { throw failure; } };+ });+ vi.doMock('../../src/main/features/kb_vector', () => ({ closeAllKb }));+ try {+ const error = await drainMainRuntimeForTest().then(() => null, reason => reason);+ // Vitest wraps a module factory failure, retaining the original as cause.+ expect(phase === 'load' ? error?.cause : error).toBe(failure);+ expect(closeAllKb).toHaveBeenCalledOnce();+ } finally {+ vi.doUnmock('../../src/main/features/search/indexer');+ vi.doUnmock('../../src/main/features/kb_vector'); vi.resetModules();+ }+ });++ it('restores logging state and starts closing every captured worker even when termination rejects', async () => {+ const prior = process.env.ORKAS_TEST_DISABLE_LOG_DELIVERY;+ process.env.ORKAS_TEST_DISABLE_LOG_DELIVERY = 'caller-sentinel';+ const failure = new Error('synthetic worker termination failure');+ const worker = (fail: boolean) => Object.assign(new EventEmitter(), {+ unref: vi.fn(), postMessage: vi.fn(), terminate: vi.fn(async () => { if (fail) throw failure; return 0; }),+ });+ const first = worker(true), second = worker(false);+ const cleanup = await captureMainLogWorkers();+ try {+ (await import('../../src/main/util/log-delivery')).createLogDelivery({}, () => first as any);+ vi.resetModules();+ (await import('../../src/main/util/log-delivery')).createLogDelivery({}, () => second as any);+ await expect(cleanup()).rejects.toBe(failure);+ expect(first.terminate).toHaveBeenCalledOnce(); expect(second.terminate).toHaveBeenCalledOnce();+ expect(process.env.ORKAS_TEST_DISABLE_LOG_DELIVERY).toBe('caller-sentinel');+ } finally {+ vi.doUnmock('../../src/main/util/log-delivery'); vi.resetModules();+ if (prior === undefined) delete process.env.ORKAS_TEST_DISABLE_LOG_DELIVERY;+ else process.env.ORKAS_TEST_DISABLE_LOG_DELIVERY = prior;+ }+ });+});diff --git a/test/main/quality/e2e-background-services.test.ts b/test/main/quality/e2e-background-services.test.tsindex 5cbb4a68..2810a907 100644--- a/test/main/quality/e2e-background-services.test.ts+++ b/test/main/quality/e2e-background-services.test.ts@@ -25,6 +25,9 @@ describe('E2E background service contracts', () => {writeFileSync(file, 'local edit after catalog snapshot');expect(service.asset(new URL(detail.agent_json_url).pathname)?.toString()).toBe(original);expect(request('/defaults').body).toEqual({ code: 0, agents: [], skills: [] });+ expect(request('/categories')).toEqual({ status: 200, body: { code: 0, list: [+ { code: 'general', name_zh: '通用', name_en: 'General', sort_order: 10 },+ ] } });expect(request('/agents/detail', { id: 'missing' }).status).toBe(404);expect(request('/undeclared').status).toBe(404);expect(service.marketplace('/agents/list', Buffer.from('not-json'), '').status).toBe(400);diff --git a/test/main/quality/test-runner-checkpoint.test.ts b/test/main/quality/test-runner-checkpoint.test.tsindex e7da53e9..5f419eb5 100644--- a/test/main/quality/test-runner-checkpoint.test.ts+++ b/test/main/quality/test-runner-checkpoint.test.ts@@ -262,3 +262,39 @@ it.each(['electron-log-required', 'electron-logs'])(expect(fs.existsSync(path.join(root, 'output', 'checkpoint-electron-snapshot.log'))).toBe(true);},);++it('keeps a completed tool receipt without a terminal turn in the real interruption CLI fixture', () => {+ const file = ts.createSourceFile('orkas.ts', fs.readFileSync(+ path.join(pcRoot, 'test/e2e/fixtures/orkas.ts'), 'utf8'), ts.ScriptTarget.Latest, true);+ const factory = file.statements.find((statement): statement is ts.FunctionDeclaration =>+ ts.isFunctionDeclaration(statement) && statement.name?.text === 'fakeCodexSource');+ if (!factory) throw new Error('Missing Codex fixture producer');+ const code = ts.transpileModule(factory.getText(file), {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).outputText;+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-cli-interruption-producer-'));+ roots.push(root);+ const script = path.join(root, 'codex.cjs');+ fs.writeFileSync(script, new Function(code + '; return fakeCodexSource();')());+ const requests = [+ { id: 1, method: 'initialize' },+ { id: 2, method: 'thread/start' },+ { id: 3, method: 'turn/start', params: { input: [{ type: 'text', text: 'E2E_CODEX_CRASH_PROCESS' }] } },+ ];+ const result = spawnSync(node, [script], {+ cwd: root, encoding: 'utf8', timeout: 10_000,+ env: { ...process.env, ORKAS_E2E_CLI_STATE: path.join(root, 'state.json') },+ input: requests.map(request => JSON.stringify(request)).join('\n') + '\n',+ });+ expect(result.error).toBeUndefined();+ expect(result.status, result.stderr).toBe(0);+ expect(result.stderr).toBe('');+ const records = result.stdout.trim().split('\n').map(line => JSON.parse(line));+ expect(records.find(row => row.method === 'item/completed')?.params.item).toMatchObject({+ id: 'crash-tool', type: 'commandExecution', status: 'completed',+ aggregatedOutput: 'DURABLE_CRASH_RECEIPT', exitCode: 0,+ });+ expect(records.filter(row => row.method === 'turn/started')).toHaveLength(1);+ expect(records.filter(row => row.method === 'turn/completed')).toEqual([]);+ expect(records.filter(row => row.method === 'item/agentMessage/delta')).toEqual([]);+});diff --git a/test/main/util/run-tests.test.ts b/test/main/util/run-tests.test.tsindex 4995e43f..22186aab 100644--- a/test/main/util/run-tests.test.ts+++ b/test/main/util/run-tests.test.ts@@ -3,6 +3,7 @@ import fs from 'node:fs';import os from 'node:os';import path from 'node:path';import { spawn, spawnSync } from 'node:child_process';+import { findTestNpmCli } from '../../helpers/npm-cli';const pcRoot = path.resolve(__dirname, '../../..');const roots: string[] = [];@@ -46,28 +47,8 @@ function fixture() {return root;}-/** npm and direct Node launchers both use the installed npm CLI. Homebrew- * and other split layouts can put npm outside the outer Node's prefix. */-function npmCli(): string | undefined {- const bin = path.dirname(node);- const candidates = [- process.env.npm_execpath,- path.join(bin, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),- path.join(bin, 'node_modules', 'npm', 'bin', 'npm-cli.js'),- ];- for (const directory of String(process.env.PATH || '').split(path.delimiter)) {- if (!directory) continue;- try {- const entry = fs.realpathSync(path.join(directory, 'npm'));- if (path.basename(entry) === 'npm-cli.js') candidates.push(entry);- } catch { /* A PATH entry need not contain npm. */ }- candidates.push(path.join(directory, 'node_modules', 'npm', 'bin', 'npm-cli.js'));- }- return candidates.find((candidate): candidate is string => !!candidate && fs.existsSync(candidate));-}-function invoke(root: string, args: string[], env: Record<string, string> = {}) {- const npm = npmCli();+ const npm = findTestNpmCli(node);if (!npm) throw new Error('No npm CLI found on PATH or beside the test Node.');const result = spawnSync(node, [npm, ...args], {cwd: root, env: { ...process.env, ...env }, encoding: 'utf8', timeout: 15_000,diff --git a/test/web/electron-cleanup.test.ts b/test/web/electron-cleanup.test.tsindex a7c4decc..1d0f8807 100644--- a/test/web/electron-cleanup.test.ts+++ b/test/web/electron-cleanup.test.ts@@ -154,7 +154,7 @@ function createCleanupOwner(app: any) {ts.isClassDeclaration(node) && node.name?.text === 'OrkasTestApp');if (!owner) throw new Error('Missing fixture owner');const members = owner.members.filter(member =>- member.name && ['closeCurrentApp', 'appClosePromises', 'appTraceStops', 'stopAppTrace', 'prepareForNativeShutdown'].includes(member.name.getText(file)));+ member.name && ['closeCurrentApp', 'appClosePromises', 'appTraceStops', 'nativeShutdownProcesses', 'stopAppTrace', 'prepareForNativeShutdown', 'launchAfterNativeExit', 'launchAfterCrash'].includes(member.name.getText(file)));const code = ts.transpileModule(`class CleanupOwner { ${members.map(m => m.getText(file)).join('\n')} }`, {compilerOptions: { target: ts.ScriptTarget.ES2022 },}).outputText;@@ -239,3 +239,228 @@ it('leaves a replacement application and page owned after the old close finishesexpect(replacement.stop).not.toHaveBeenCalled();expect(replacement.app.evaluate).not.toHaveBeenCalled();});+++it('reopens through fixture ownership after prepared clean native exit without a fallback quit', async () => {+ const { app, stop, release } = controlledCleanupApp();+ const owner = createCleanupOwner(app);+ const child = app.process();+ app.process = vi.fn(() => child);+ release();+ await owner.prepareForNativeShutdown();+ app.process = vi.fn(() => { throw new Error('Disposed native application'); });+ app.context = vi.fn(() => { throw new Error('Disposed native browser context'); });+ const replacement = {};+ const replacementPage = {};+ owner.launch = vi.fn(async () => {+ expect(owner.electronApp).toBeNull();+ expect(owner.page).toBeNull();+ owner.electronApp = replacement;+ owner.page = replacementPage;+ });+ expect(await owner.launchAfterNativeExit(app)).toBe(replacementPage);+ expect(stop).toHaveBeenCalledTimes(1);+ expect(app.process).not.toHaveBeenCalled();+ expect(app.context).not.toHaveBeenCalled();+ expect(app.evaluate).not.toHaveBeenCalled();+ expect(app.close).not.toHaveBeenCalled();+ expect(owner.launch).toHaveBeenCalledTimes(1);+ expect(owner.electronApp).toBe(replacement);+ expect(owner.page).toBe(replacementPage);+});++it.each([+ { exitCode: null, signalCode: null },+ { exitCode: 2, signalCode: null },+ { exitCode: null, signalCode: 'SIGKILL' },+])('does not replace an unclean or still-running native owner: %j', async terminal => {+ const { app, release } = controlledCleanupApp();+ app.process = () => terminal;+ const owner = createCleanupOwner(app);+ const page = owner.page;+ owner.launch = vi.fn();+ release();+ await owner.prepareForNativeShutdown();+ await expect(owner.launchAfterNativeExit(app)).rejects.toThrow('has not exited cleanly');+ expect(owner.electronApp).toBe(app);+ expect(owner.page).toBe(page);+ expect(owner.launch).not.toHaveBeenCalled();+ expect(app.evaluate).not.toHaveBeenCalled();+ expect(app.close).not.toHaveBeenCalled();+});++it('requires native trace preparation and preserves its export failure', async () => {+ const { app } = controlledCleanupApp();+ const owner = createCleanupOwner(app);+ const page = owner.page;+ owner.launch = vi.fn();+ await expect(owner.launchAfterNativeExit(app)).rejects.toThrow('was not prepared');+ const failure = new Error('controlled trace export failure');+ app.context = () => ({ tracing: { stop: () => Promise.reject(failure) } });+ await expect(owner.prepareForNativeShutdown()).rejects.toBe(failure);+ await expect(owner.launchAfterNativeExit(app)).rejects.toBe(failure);+ expect(owner.electronApp).toBe(app);+ expect(owner.page).toBe(page);+ expect(owner.launch).not.toHaveBeenCalled();+ expect(app.evaluate).not.toHaveBeenCalled();+ expect(app.close).not.toHaveBeenCalled();+});++it('preserves a replacement owner when native trace export settles late', async () => {+ const { app, release } = controlledCleanupApp();+ const owner = createCleanupOwner(app);+ owner.launch = vi.fn();+ const exporting = owner.prepareForNativeShutdown();+ const reopening = owner.launchAfterNativeExit(app);+ const rejected = expect(reopening).rejects.toThrow('ownership changed');+ const replacement = {};+ const replacementPage = {};+ owner.electronApp = replacement;+ owner.page = replacementPage;+ release();+ await exporting;+ await rejected;+ expect(owner.electronApp).toBe(replacement);+ expect(owner.page).toBe(replacementPage);+ expect(owner.launch).not.toHaveBeenCalled();+ expect(app.evaluate).not.toHaveBeenCalled();+ expect(app.close).not.toHaveBeenCalled();+});++it('does not bypass cleanup already owned by teardown after native exit', async () => {+ const { app, release } = controlledCleanupApp();+ const owner = createCleanupOwner(app);+ owner.launch = vi.fn();+ release();+ await owner.prepareForNativeShutdown();+ owner.appClosePromises.set(app, Promise.resolve());+ await expect(owner.launchAfterNativeExit(app)).rejects.toThrow('cleanup already started');+ expect(owner.electronApp).toBe(app);+ expect(owner.launch).not.toHaveBeenCalled();+});++it('reopens only the prepared SIGKILL owner without querying its disposed channels or issuing quit', async () => {+ const { app, stop, release } = controlledCleanupApp();+ const child = { exitCode: null, signalCode: null as string | null };+ app.process = () => child;+ const owner = createCleanupOwner(app);+ release();+ await owner.prepareForNativeShutdown();+ child.signalCode = 'SIGKILL';+ app.process = vi.fn(() => { throw new Error('Disposed application process channel'); });+ app.context = vi.fn(() => { throw new Error('Disposed tracing channel'); });+ const replacement = {}, replacementPage = {};+ owner.launch = vi.fn(async () => {+ expect(owner.electronApp).toBeNull();+ expect(owner.page).toBeNull();+ owner.electronApp = replacement;+ owner.page = replacementPage;+ });+ expect(await owner.launchAfterCrash(app)).toBe(replacementPage);+ expect(stop).toHaveBeenCalledTimes(1);+ expect(owner.launch).toHaveBeenCalledTimes(1);+ expect(owner.electronApp).toBe(replacement);+ expect(owner.page).toBe(replacementPage);+ for (const operation of [app.process, app.context, app.evaluate, app.close]) expect(operation).not.toHaveBeenCalled();+});++it.each([+ { exitCode: null, signalCode: null },+ { exitCode: 0, signalCode: null },+ { exitCode: 2, signalCode: null },+ { exitCode: null, signalCode: 'SIGTERM' },+ { exitCode: 1, signalCode: 'SIGKILL' },+])('refuses crash reopen for any other native terminal state: %j', async terminal => {+ const { app, release } = controlledCleanupApp();+ app.process = () => terminal;+ const owner = createCleanupOwner(app);+ const page = owner.page;+ owner.launch = vi.fn();+ release();+ await owner.prepareForNativeShutdown();+ await expect(owner.launchAfterCrash(app)).rejects.toThrow('has not exited with SIGKILL');+ expect(owner.electronApp).toBe(app);+ expect(owner.page).toBe(page);+ expect(owner.launch).not.toHaveBeenCalled();+ expect(app.evaluate).not.toHaveBeenCalled();+ expect(app.close).not.toHaveBeenCalled();+});++it('requires captured crash ownership and retains trace export failures without clearing the app', async () => {+ const { app } = controlledCleanupApp();+ app.process = () => ({ exitCode: null, signalCode: 'SIGKILL' });+ const owner = createCleanupOwner(app);+ const page = owner.page;+ owner.launch = vi.fn();+ await expect(owner.launchAfterCrash({})).rejects.toThrow('no longer owned');+ await expect(owner.launchAfterCrash(app)).rejects.toThrow('was not prepared');+ const failure = new Error('controlled crash trace failure');+ app.context = () => ({ tracing: { stop: () => Promise.reject(failure) } });+ await expect(owner.prepareForNativeShutdown()).rejects.toBe(failure);+ await expect(owner.launchAfterCrash(app)).rejects.toBe(failure);+ expect(owner.electronApp).toBe(app);+ expect(owner.page).toBe(page);+ expect(owner.launch).not.toHaveBeenCalled();+ expect(app.evaluate).not.toHaveBeenCalled();+ expect(app.close).not.toHaveBeenCalled();+});++it('preserves a replacement owner while the crashed app trace export settles', async () => {+ const { app, release } = controlledCleanupApp();+ app.process = () => ({ exitCode: null, signalCode: 'SIGKILL' });+ const owner = createCleanupOwner(app);+ owner.launch = vi.fn();+ const exporting = owner.prepareForNativeShutdown();+ const reopening = owner.launchAfterCrash(app);+ const rejected = expect(reopening).rejects.toThrow('ownership changed');+ const replacement = {}, replacementPage = {};+ owner.electronApp = replacement;+ owner.page = replacementPage;+ release();+ await exporting;+ await rejected;+ expect(owner.electronApp).toBe(replacement);+ expect(owner.page).toBe(replacementPage);+ expect(owner.launch).not.toHaveBeenCalled();+ expect(app.evaluate).not.toHaveBeenCalled();+ expect(app.close).not.toHaveBeenCalled();+});++it.each(['before', 'during'])('preserves teardown ownership acquired %s crash trace completion', async when => {+ const { app, release } = controlledCleanupApp();+ app.process = () => ({ exitCode: null, signalCode: 'SIGKILL' });+ const owner = createCleanupOwner(app);+ owner.launch = vi.fn();+ const exporting = owner.prepareForNativeShutdown();+ if (when === 'before') owner.appClosePromises.set(app, Promise.resolve());+ const reopening = owner.launchAfterCrash(app);+ const rejected = expect(reopening).rejects.toThrow(when === 'before' ? 'cleanup already started' : 'ownership changed');+ if (when === 'during') owner.appClosePromises.set(app, Promise.resolve());+ release();+ await exporting;+ await rejected;+ expect(owner.electronApp).toBe(app);+ expect(owner.launch).not.toHaveBeenCalled();+ expect(app.evaluate).not.toHaveBeenCalled();+ expect(app.close).not.toHaveBeenCalled();+});++it('allows at most one concurrent crash reopen after the same trace export', async () => {+ const { app, release } = controlledCleanupApp();+ app.process = () => ({ exitCode: null, signalCode: 'SIGKILL' });+ const owner = createCleanupOwner(app);+ const exporting = owner.prepareForNativeShutdown();+ const replacement = {}, replacementPage = {};+ owner.launch = vi.fn(async () => { owner.electronApp = replacement; owner.page = replacementPage; });+ const outcomes = Promise.allSettled([owner.launchAfterCrash(app), owner.launchAfterCrash(app)]);+ release();+ await exporting;+ const results = await outcomes;+ expect(results.filter(result => result.status === 'fulfilled')).toEqual([{ status: 'fulfilled', value: replacementPage }]);+ expect(results.filter(result => result.status === 'rejected')).toHaveLength(1);+ expect(owner.launch).toHaveBeenCalledTimes(1);+ expect(owner.electronApp).toBe(replacement);+ expect(owner.page).toBe(replacementPage);+ expect(app.evaluate).not.toHaveBeenCalled();+ expect(app.close).not.toHaveBeenCalled();+});