Skip to content

armgit / Orkas

Public Imported from GitHub
0

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.

Archive active work before shutdown and preserve restart recovery

wyta99a4642e352
diff --git a/src/main/index.ts b/src/main/index.ts
index 4beea79c..c1e85402 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -43,6 +43,7 @@ import { installWindowPresentationEvents } from './util/window-presentation';
import './install-data-root.cjs';
import { resolveCliCommand } from './features/local_agents/spawn-command';
import { createOptionalTray } from './util/app-tray';
+import { captureWindowsShutdownProcesses } from './util/windows-shutdown-processes';
import { desktopPlatform, osVersion, preferredSystemLanguage } from './system_info';
import {
hardenedWebPreferences,
@@ -190,7 +191,7 @@ void installEnvProxyDispatcher();
import { installFetchDiag } from './model/core-agent/fetch-diag';
installFetchDiag();
-import { hasActiveWork, subscribeTaskTerminals, type TaskTerminalEvent } from './features/group_chat/bus';
+import { hasActiveWork, prepareForShutdown, subscribeTaskTerminals, type TaskTerminalEvent } from './features/group_chat/bus';
import { setFetchImplementation } from './util/retry';
setFetchImplementation((input, init) => net.fetch(input as Parameters<typeof net.fetch>[0], init));
@@ -440,7 +441,10 @@ function openConversationFromTaskNotification(
/** `prepareShutdown` is the work a normal quit runs in `before-quit`; exits
* that bypass it (`app.exit`) run it themselves. */
-function registerIpc(prepareShutdown: () => Promise<void>): void {
+function registerIpc(
+ prepareShutdown: (mode?: 'quit' | 'relaunch') => Promise<void>,
+ isShutdownQuiescent: () => boolean,
+): void {
ipc.register();
// Subscribe before opening the renderer. The deferred driver scheduler must
// not determine whether foreground or early background writes are visible.
@@ -577,6 +581,11 @@ function registerIpc(prepareShutdown: () => Promise<void>): void {
ipcMain.handle('orkas.relaunch', async () => {
const isWindows = process.platform === 'win32';
const script = path.join(paths.PC_ROOT, isWindows ? 'run.cmd' : 'run.sh');
+ try {
+ if (!fs.statSync(script).isFile()) throw new Error('Invalid launcher');
+ } catch {
+ throw Object.assign(new Error('Relaunch could not start'), { code: 'E_RELAUNCH_START_FAILED' });
+ }
const resolved = isWindows
? resolveCliCommand(script, [], process.platform, process.env)
: { command: 'bash', args: [script], windowsVerbatimArguments: undefined };
@@ -587,17 +596,44 @@ function registerIpc(prepareShutdown: () => Promise<void>): void {
delete childEnv.ORKAS_WORKSPACE_ROOT;
delete childEnv.CORE_AGENT_AUTH_DIR;
childEnv.ORKAS_RELAUNCH_OWNER_PID = String(process.pid);
- const child = spawn(resolved.command, resolved.args, {
- cwd: paths.PC_ROOT,
- detached: true,
- stdio: 'ignore',
- windowsHide: true,
- windowsVerbatimArguments: resolved.windowsVerbatimArguments,
- env: childEnv,
+ const child = await new Promise<ReturnType<typeof spawn>>((resolve, reject) => {
+ const launcher = spawn(resolved.command, resolved.args, {
+ cwd: paths.PC_ROOT,
+ detached: true,
+ stdio: 'ignore',
+ windowsHide: true,
+ windowsVerbatimArguments: resolved.windowsVerbatimArguments,
+ env: childEnv,
+ });
+ launcher.once('error', reject);
+ launcher.once('spawn', () => { launcher.unref(); resolve(launcher); });
+ }).catch(() => {
+ throw Object.assign(new Error('Relaunch could not start'), { code: 'E_RELAUNCH_START_FAILED' });
});
- child.unref();
log.info('relaunch via shell script');
- await prepareShutdown();
+ let timer: NodeJS.Timeout | undefined;
+ try {
+ await Promise.race([
+ prepareShutdown('relaunch'),
+ new Promise<void>((resolve, reject) => {
+ // run.sh/run.cmd give this owner 15 seconds to leave. Only bound
+ // local cleanup once critical active-task archival has settled.
+ timer = setTimeout(() => {
+ let quiescent = false;
+ try { quiescent = isShutdownQuiescent(); } catch { /* unknown phase retains the app */ }
+ if (quiescent) resolve();
+ else reject(Object.assign(new Error('Active task archival failed'), {
+ code: 'E_SHUTDOWN_ARCHIVE_FAILED',
+ }));
+ }, 10_000);
+ }),
+ ]);
+ } catch (error) {
+ if (child.exitCode === null && child.signalCode === null) {
+ try { child.kill(); } catch { /* retain the original archival failure */ }
+ }
+ throw error;
+ } finally { if (timer) clearTimeout(timer); }
app.exit(0);
return { ok: true };
});
@@ -1437,16 +1473,58 @@ if (!gotLock) {
} else {
const shutdown = createShutdownCoordinator({
+ captureProcesses: () => captureWindowsShutdownProcesses(),
+ quiesce: async () => {
+ await Promise.all([
+ prepareForShutdown(),
+ import('./features/local_agents/runner.js').then(runner => runner.stopBackgroundRuns('the app is quitting')),
+ ]);
+ const boot = await import('./util/boot_init');
+ boot.stopBootWork();
+ const library = await import('./features/library_corpus');
+ library.closeAllLibraryCorpora();
+ },
localTasks: [
{ name: 'open-lifecycle', run: async () => { await openLifecycleTracking?.flushQuit(); } },
+ { name: 'connectors', run: () => connectorsFeature.shutdown() },
{ name: 'search', run: () => searchFeature.flushAll() },
- { name: 'kb_vector', run: async () => { (await import('./features/kb_vector')).closeAllKb(); } },
- { name: 'kb_embed', run: async () => { (await import('./features/kb_embed')).closeEmbedder(); } },
- { name: 'image-runtime', run: async () => { (await import('./util/sharp-runtime')).closeImageRuntime(); } },
- { name: 'office-engine', run: () => sweepOfficeResidents('quit') },
- { name: 'web-assist-session', run: async () => { await (await import('./features/web_assist_session')).flushWebAssistSessions(); } },
+ { name: 'kb_vector', run: async () => {
+ const kb = await import('./features/kb_vector');
+ kb.closeAllKb();
+ } },
+ { name: 'kb_embed', run: async () => {
+ // Kill the isolated embedder worker so it releases its model promptly.
+ const kbEmbed = await import('./features/kb_embed');
+ kbEmbed.closeEmbedder();
+ } },
+ { name: 'image-runtime', run: async () => {
+ const images = await import('./util/sharp-runtime');
+ images.closeImageRuntime();
+ } },
+ { name: 'office-engine', run: async () => {
+ const extraction = await import('./util/office-extract');
+ await extraction.closeOfficeExtraction();
+ const oe = await import('./features/office/office_engine');
+ oe.closeAllOfficeResidents();
+ } },
+ { name: 'web-assist-session', run: async () => {
+ const webAssistSessions = await import('./features/web_assist_session');
+ await webAssistSessions.flushWebAssistSessions();
+ } },
+ { name: 'web-app-data', run: async () => {
+ // Checkpoint local app databases before closing the application.
+ const apps = await import('./features/web_apps/host');
+ apps.runtime.closeUser(users.getActiveUserId());
+ await apps.runtime.drainData();
+ } },
],
onFailure: name => createLogger(name).warn('shutdown preparation failed'),
+ onIncomplete: async () => {
+ const library = await import('./features/library_corpus');
+ await library.resumeLibraryAdmission();
+ const boot = await import('./util/boot_init');
+ boot.resumeBootAdmission();
+ },
});
const flushForShutdown = shutdown.prepare;
@@ -1514,7 +1592,7 @@ if (!gotLock) {
}
callback(permission === 'clipboard-read' || permission === 'clipboard-sanitized-write');
});
- registerIpc(flushForShutdown);
+ registerIpc(flushForShutdown, () => shutdown.quiescent);
const stopTaskNotifications = taskNotifications.startTaskNotifications({
getActiveUserId: () => users.getActiveUserId(),
isEnabled: () => appConfig.getTaskNotificationsEnabled(),
@@ -1563,16 +1641,6 @@ if (!gotLock) {
openConversation: openConversationFromTaskNotification,
});
app.once('before-quit', stopTaskNotifications);
- // A CLI agent's process is our child but its own process-group leader, so
- // quitting without ending it leaves it running with nothing to report to.
- // Fire-and-forget: Electron does not await this hook, and the deadline
- // inside only decides whether the CLI gets to write a clean session state
- // before the app goes.
- app.once('before-quit', () => {
- void import('./features/local_agents/runner.js')
- .then(runner => runner.stopBackgroundRuns('the app is quitting'))
- .catch(() => { /* nothing was running, or the module never loaded */ });
- });
const stopTaskTerminalUi = subscribeTaskTerminals(emitTaskTerminalToRenderer);
app.once('before-quit', stopTaskTerminalUi);
// Running Agent work keeps the machine out of idle sleep; an idle app holds nothing.
@@ -1580,6 +1648,11 @@ if (!gotLock) {
app.once('before-quit', idleSleepGuard.stop);
clientConfigFeature.clientConfig.subscribeAll((keys) => {
ipc.broadcastToRenderer('client-config:changed', { keys });
+ if (keys.includes('connectors.catalog') || keys.includes('connectors.dcr_catalog')) {
+ connectorsFeature.refreshStaleToolCaches(users.getActiveUserId(), 'client_config_changed').catch((err) => {
+ log.warn('connector stale tool-cache refresh after client config change failed', { error: logErrorSummary(err) });
+ });
+ }
});
const BOOT_BACKGROUND_DEFER_MS = 6_000;
const bootDevice = getBootDeviceProfile();
@@ -1598,12 +1671,9 @@ if (!gotLock) {
startupDelayMs: CLIENT_CONFIG_STARTUP_DELAY_MS,
forceStartupRefresh: false,
});
- const connectorsTimer = setTimeout(() => {
- connectorsFeature.bootstrap(users.getActiveUserId()).catch(() => {
- /* errors logged inside the feature; never block app startup */
- });
- }, CONNECTORS_BOOTSTRAP_DELAY_MS);
- connectorsTimer.unref?.();
+ scheduleBootBackground('connectors:bootstrap', async () => {
+ await connectorsFeature.bootstrap(users.getActiveUserId());
+ }, CONNECTORS_BOOTSTRAP_DELAY_MS, { resourceClass: 'process', preferIdle: true, maxSliceMs: 30_000 });
createWindow();
openLifecycleTracking = startOpenLifecycleTracking({
app,
@@ -1773,6 +1843,12 @@ if (!gotLock) {
isQuitting = true;
if (shutdown.complete) return;
e.preventDefault();
- try { await flushForShutdown(); } finally { app.quit(); }
+ try {
+ await flushForShutdown();
+ app.quit();
+ } catch (error) {
+ isQuitting = false;
+ log.error('quit preparation failed', { error: logErrorSummary(error) });
+ }
});
}
diff --git a/test/e2e/chat_e2e_cli_interruption.spec.ts b/test/e2e/chat_e2e_cli_interruption.spec.ts
new file mode 100644
index 00000000..5c35308b
--- /dev/null
+++ b/test/e2e/chat_e2e_cli_interruption.spec.ts
@@ -0,0 +1,81 @@
+import { readFileSync, readdirSync } from 'node:fs';
+import path from 'node:path';
+import { killProcessTree } from '../../src/core-agent/src/sandbox/executor';
+import { expect, test } from './fixtures/orkas';
+
+test('recovers a running CLI process and elapsed time after a real application kill without replaying the task', async ({ cliOrkas }, info) => {
+ test.setTimeout(120_000);
+ const name = 'CodexCrashRecovery';
+ const { agent } = await cliOrkas.invoke<{ agent: { agent_id: string } }>('agents.create', {
+ name, description: 'Deterministic crash recovery', category: 'general', runtime: { kind: 'cli', cli: 'codex' },
+ });
+ const page = cliOrkas.page!;
+ await page.locator('#new-chat-btn').click();
+ await page.locator('#new-chat-input').fill(`@${name} E2E_CODEX_CRASH_PROCESS`);
+ await page.locator('#new-chat-send-btn').click();
+ await expect.poll(() => cliOrkas.readCliState().invocations.length, { timeout: 30_000 }).toBe(1);
+ const cid = await page.evaluate<string>('currentCid');
+ const account = path.join(cliOrkas.workspaceRoot, 'account-e2e');
+ const historyFile = path.join(account, 'cloud', 'chats', `${cid}.jsonl`);
+ const stateFile = path.join(account, 'cloud', 'chats', cid, 'state.json');
+ const runs = path.join(account, 'local', 'file_cache', 'local-agent-runs');
+ let run = '';
+ await expect.poll(() => {
+ for (const entry of readdirSync(runs)) {
+ const directory = path.join(runs, entry);
+ const meta = JSON.parse(readFileSync(path.join(directory, 'meta.json'), 'utf8'));
+ if (meta.cid === cid && meta.agentId === agent.agent_id) {
+ run = directory;
+ return readFileSync(path.join(directory, 'events.jsonl'), 'utf8').includes('DURABLE_CRASH_RECEIPT');
+ }
+ }
+ return false;
+ }).toBe(true);
+ const durable = JSON.parse(readFileSync(stateFile, 'utf8'));
+ expect(durable.in_flight).toContain(agent.agent_id);
+ expect(durable.in_flight_turns[agent.agent_id]).toMatchObject({ turn_id: expect.any(String), source_message_id: expect.any(String) });
+ const meta = JSON.parse(readFileSync(path.join(run, 'meta.json'), 'utf8'));
+ expect(meta.endedAt).toBeUndefined();
+ const crashedApp = cliOrkas.electronApp!;
+ await cliOrkas.prepareForNativeShutdown();
+ const child = crashedApp.process();
+ const exited = new Promise<void>(resolve => child.once('exit', () => resolve()));
+ const killedAt = Date.now();
+ killProcessTree(child, 'SIGKILL');
+ await exited;
+ expect(child.exitCode).toBeNull();
+ expect(child.signalCode).toBe('SIGKILL');
+
+ for (let reopen = 0; reopen < 2; reopen++) {
+ const reopened = reopen === 0
+ ? await cliOrkas.launchAfterCrash(crashedApp)
+ : await cliOrkas.relaunch();
+ await reopened.locator(`#conversation-list .conv-item[data-cid="${cid}"]`).click();
+ const notice = reopened.locator('#chat-history .chat-message.assistant[data-system-kind="reply_interrupted"]');
+ await expect(notice).toHaveCount(1);
+ const rail = notice.locator('.stream-process');
+ await expect(rail.locator('.stream-process-runtime')).toBeVisible();
+ await expect(rail.locator('.stream-process-runtime')).toHaveText(/^≈ /);
+ await rail.locator('.stream-process-summary').click();
+ await rail.locator('.stream-process-compact-summary').click();
+ const tool = rail.locator('[data-process-call-id="cli:crash-tool"]');
+ await expect(tool).toHaveCount(1);
+ await tool.click();
+ await expect(rail).toContainText('DURABLE_CRASH_RECEIPT');
+ const { history } = await cliOrkas.invoke<{ history: any[] }>('conversations.history', { cid, limit: 20 });
+ const receipt = history.find(row => row.system_kind === 'reply_interrupted');
+ expect(receipt).toMatchObject({ from: agent.agent_id, ...durable.in_flight_turns[agent.agent_id] });
+ const clock = receipt.process.find(item => item.event?.stream === 'runtime').event.data;
+ expect(clock.phase).toBe('interrupted');
+ expect(clock.duration_estimated).toBe(true);
+ expect(clock.duration_ms).toBeGreaterThan(0);
+ expect(clock.duration_ms).toBeLessThanOrEqual(killedAt - Date.parse(meta.startedAt));
+ expect(history.filter(row => row.system_kind === 'reply_interrupted')).toHaveLength(1);
+ expect(cliOrkas.readCliState().invocations).toHaveLength(1);
+ expect(JSON.parse(readFileSync(stateFile, 'utf8')).status).toBe('idle');
+ await expect(reopened.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
+ if (!reopen) await reopened.screenshot({ path: info.outputPath('cli-crash-recovered.png') });
+ }
+ const canonical = readFileSync(historyFile, 'utf8').trim().split('\n').map(line => JSON.parse(line));
+ expect(canonical.filter(row => row.system_kind === 'reply_interrupted')).toHaveLength(1);
+});
diff --git a/test/e2e/chat_e2e_shutdown.spec.ts b/test/e2e/chat_e2e_shutdown.spec.ts
index e85ebfd8..a3d7b842 100644
--- a/test/e2e/chat_e2e_shutdown.spec.ts
+++ b/test/e2e/chat_e2e_shutdown.spec.ts
@@ -168,6 +168,16 @@ for (const [boundary, continuation] of [
expect(after.filter(row => row.system_kind === 'reply_interrupted')).toHaveLength(1);
const archived = after.find(row => row.system_kind === 'reply_interrupted');
expect(archived.source_message_id).toBe(after.find(row => row.from === 'user').id);
+ const clocks = (archived.process || []).filter(item => item.event?.stream === 'runtime'
+ && ['end', 'interrupted'].includes(item.event.data?.phase));
+ expect(clocks, 'shutdown must retain the clock together with the public process').toHaveLength(1);
+ expect(clocks[0].event.data.duration_ms).toBeGreaterThan(0);
+ const reopenedPage = modelOrkas.page!;
+ await reopenedPage.locator(`#conversation-list .conv-item[data-cid="${cid}"]`).click();
+ const interruption = reopenedPage.locator('#chat-history .chat-message.assistant[data-system-kind="reply_interrupted"]');
+ await expect(interruption).toHaveCount(1);
+ await expect(interruption.locator('.stream-process-runtime')).toBeVisible();
+ await expect(interruption.locator('.stream-process-runtime')).not.toHaveText('');
modelOrkas.clearModelToolScenario();
modelOrkas.setModelTextReplies(['The saved evidence is available.']);
const retried = await modelOrkas.invoke<any>('groupChat.send', {
diff --git a/test/main/index-process.test.ts b/test/main/index-process.test.ts
index bd66fbdf..7af97e71 100644
--- a/test/main/index-process.test.ts
+++ b/test/main/index-process.test.ts
@@ -1,6 +1,40 @@
import fs from 'node:fs';
import path from 'node:path';
-import { describe, expect, it } from 'vitest';
+import vm from 'node:vm';
+import { EventEmitter } from 'node:events';
+import * as ts from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+
+function relaunchSource(): string {
+ const source = fs.readFileSync(path.resolve('src/main/index.ts'), 'utf8');
+ const start = source.indexOf("ipcMain.handle('orkas.relaunch'");
+ const end = source.indexOf('\n });', start);
+ if (start < 0 || end < 0) throw new Error('Main relaunch handler is missing');
+ return source.slice(start, end + '\n });'.length);
+}
+
+function relaunchHarness(prepareShutdown: () => Promise<void>, isShutdownQuiescent: () => boolean, platform = 'linux') {
+ const child = Object.assign(new EventEmitter(), {
+ exitCode: null, signalCode: null as string | null,
+ unref: vi.fn(), kill: vi.fn(() => { child.signalCode = 'SIGTERM'; return true; }),
+ });
+ const spawn = vi.fn((_command: string, _args: string[], _options: any) => child);
+ const exit = vi.fn();
+ const statSync = vi.fn(() => ({ isFile: () => true }));
+ const resolveCliCommand = vi.fn(() => ({ command: 'cmd.exe', args: ['/d', '/s', '/c', 'synthetic quoted launcher'], windowsVerbatimArguments: true }));
+ let invoke!: () => Promise<unknown>;
+ vm.runInNewContext(ts.transpileModule(relaunchSource(), {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
+ }).outputText, {
+ ipcMain: { handle: (_channel: string, handler: typeof invoke) => { invoke = handler; } },
+ path: platform === 'win32' ? path.win32 : path.posix,
+ paths: { PC_ROOT: platform === 'win32' ? 'C:\\public repo & fixture' : '/public repo & fixture' },
+ process: { platform, pid: 12345, env: { ORKAS_WORKSPACE_ROOT: '/old workspace', CORE_AGENT_AUTH_DIR: '/old auth', SYNTHETIC_KEEP: 'kept' } },
+ fs: { statSync }, resolveCliCommand, spawn, app: { exit }, prepareShutdown, isShutdownQuiescent,
+ log: { info() {} }, setTimeout, clearTimeout,
+ });
+ return { child, spawn, exit, invoke, resolveCliCommand, statSync };
+}
describe('main process child-process ownership', () => {
it('keeps unpackaged E2E launches isolated and hidden by default', () => {
@@ -24,9 +58,7 @@ describe('main process child-process ownership', () => {
path.resolve(process.cwd(), 'src/main/index.ts'),
'utf8',
);
- const relaunchStart = source.indexOf("ipcMain.handle('orkas.relaunch'");
- expect(relaunchStart).toBeGreaterThan(-1);
- const relaunchBlock = source.slice(relaunchStart, relaunchStart + 1_800);
+ const relaunchBlock = relaunchSource();
expect(relaunchBlock).toContain('resolveCliCommand');
expect(relaunchBlock).toContain('delete childEnv.ORKAS_WORKSPACE_ROOT');
@@ -39,9 +71,8 @@ describe('main process child-process ownership', () => {
expect(relaunchBlock).toContain('windowsHide: true');
expect(relaunchBlock).toContain('windowsVerbatimArguments: resolved.windowsVerbatimArguments');
expect(relaunchBlock).toContain('env: childEnv');
- expect(relaunchBlock).toContain('child.unref()');
- expect(relaunchBlock).toContain('await prepareShutdown()');
- expect(source).toContain('registerIpc(flushForShutdown)');
+ expect(relaunchBlock).toContain('launcher.unref()');
+ expect(relaunchBlock).toContain("prepareShutdown('relaunch')");
// The shared coordinator owns the awaitable local drain, including the
// public lifecycle receipt. Its behavior is covered by shutdown/lifecycle cases.
expect(source).toMatch(/name: 'open-lifecycle',\s*run: async \(\) => \{ await openLifecycleTracking\?\.flushQuit\(\); \}/);
@@ -62,3 +93,103 @@ describe('main process child-process ownership', () => {
expect(windowsLauncher).not.toMatch(/taskkill[^\n]+electron\.exe/i);
});
});
+
+describe('Main relaunch lifecycle outcomes', () => {
+ it.each(['linux', 'win32'].flatMap(platform => ['missing', 'directory'].map(kind => ({ platform, kind }))))(
+ 'retains the current app when the $platform launcher is $kind', async ({ platform, kind }) => {
+ const prepare = vi.fn(async () => {});
+ const fixture = relaunchHarness(prepare, () => true, platform);
+ if (kind === 'missing') fixture.statSync.mockImplementation(() => { throw Object.assign(new Error('synthetic missing launcher'), { code: 'ENOENT' }); });
+ else fixture.statSync.mockReturnValue({ isFile: () => false });
+ const pending = fixture.invoke().then(() => 'exited', error => error);
+ // A shell can launch successfully even when its script is absent.
+ fixture.child.emit('spawn');
+ expect(await pending).toMatchObject({ code: 'E_RELAUNCH_START_FAILED', message: 'Relaunch could not start' });
+ expect(fixture.spawn).not.toHaveBeenCalled();
+ expect(prepare).not.toHaveBeenCalled();
+ expect(fixture.exit).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['synchronous', 'asynchronous'])('retains the app and reports a bounded error on a %s native replacement failure', async failure => {
+ const prepare = vi.fn(async () => {});
+ const fixture = relaunchHarness(prepare, () => true);
+ if (failure === 'synchronous') fixture.spawn.mockImplementationOnce(() => { throw new Error('synthetic private launcher path'); });
+ const pending = fixture.invoke().then(() => 'exited', error => error);
+ if (failure === 'asynchronous') fixture.child.emit('error', new Error('synthetic private launcher path'));
+ const result = await pending;
+ expect(result).toMatchObject({ code: 'E_RELAUNCH_START_FAILED', message: 'Relaunch could not start' });
+ expect(prepare).not.toHaveBeenCalled();
+ expect(fixture.child.unref).not.toHaveBeenCalled();
+ expect(fixture.exit).not.toHaveBeenCalled();
+ });
+
+ it('cancels the replacement launcher and retains the app when active-task archival fails', async () => {
+ const failure = Object.assign(new Error('synthetic archival failure'), { code: 'E_SHUTDOWN_ARCHIVE_FAILED' });
+ const fixture = relaunchHarness(vi.fn(async () => { throw failure; }), () => false);
+ const pending = fixture.invoke().then(() => 'exited', error => error);
+ fixture.child.emit('spawn');
+ expect(await pending).toBe(failure);
+ expect(fixture.child.kill).toHaveBeenCalledOnce();
+ expect(fixture.exit).not.toHaveBeenCalled();
+ });
+
+ it.each([false, true])('bounds slow cleanup only after archival has quiesced=%s', async quiescent => {
+ vi.useFakeTimers();
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const fixture = relaunchHarness(() => gate, () => quiescent);
+ let result: any = 'pending';
+ const pending = fixture.invoke().then(value => { result = value; }, error => { result = error; });
+ try {
+ fixture.child.emit('spawn');
+ await vi.advanceTimersByTimeAsync(10_001);
+ if (quiescent) {
+ expect(fixture.exit).toHaveBeenCalledWith(0);
+ expect(fixture.child.kill).not.toHaveBeenCalled();
+ } else {
+ expect(result).toMatchObject({ code: 'E_SHUTDOWN_ARCHIVE_FAILED' });
+ expect(fixture.child.kill).toHaveBeenCalledOnce();
+ expect(fixture.exit).not.toHaveBeenCalled();
+ }
+ } finally { release(); await pending; vi.useRealTimers(); }
+ });
+
+ it('retains the app when the archival phase is unavailable at the shutdown deadline', async () => {
+ vi.useFakeTimers();
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const fixture = relaunchHarness(() => gate, () => { throw new Error('synthetic unknown phase'); });
+ const pending = fixture.invoke().then(() => 'exited', error => error);
+ try {
+ fixture.child.emit('spawn');
+ await vi.advanceTimersByTimeAsync(10_001);
+ expect(await pending).toMatchObject({ code: 'E_SHUTDOWN_ARCHIVE_FAILED' });
+ expect(fixture.child.kill).toHaveBeenCalledOnce();
+ expect(fixture.exit).not.toHaveBeenCalled();
+ } finally { release(); await pending; vi.useRealTimers(); }
+ });
+
+ it.each(['linux', 'win32'])('preserves the public %s launcher contract and clears the successful cleanup deadline', async platform => {
+ vi.useFakeTimers();
+ const prepare = vi.fn(async () => {});
+ const fixture = relaunchHarness(prepare, () => true, platform);
+ try {
+ const pending = fixture.invoke();
+ expect(prepare).not.toHaveBeenCalled();
+ fixture.child.emit('spawn');
+ await pending;
+ expect(prepare).toHaveBeenCalledWith('relaunch');
+ expect(fixture.child.unref).toHaveBeenCalledOnce();
+ expect(fixture.exit).toHaveBeenCalledOnce();
+ expect(fixture.spawn.mock.calls[0][2]).toMatchObject({ detached: true, stdio: 'ignore', windowsHide: true,
+ env: { ORKAS_RELAUNCH_OWNER_PID: '12345', SYNTHETIC_KEEP: 'kept' } });
+ expect(fixture.spawn.mock.calls[0][2].env).not.toHaveProperty('ORKAS_WORKSPACE_ROOT');
+ expect(fixture.spawn.mock.calls[0][2].env).not.toHaveProperty('CORE_AGENT_AUTH_DIR');
+ if (platform === 'win32') expect(fixture.resolveCliCommand).toHaveBeenCalledWith('C:\\public repo & fixture\\run.cmd', [], 'win32', expect.any(Object));
+ else expect(fixture.spawn.mock.calls[0].slice(0, 2)).toEqual(['bash', ['/public repo & fixture/run.sh']]);
+ await vi.advanceTimersByTimeAsync(15_001);
+ expect(fixture.child.kill).not.toHaveBeenCalled();
+ } finally { vi.useRealTimers(); }
+ });
+});