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.

Validate packaged dependencies and coalesce local shutdown

wyt6a366e046811
diff --git a/bin/native-package-gate.cjs b/bin/native-package-gate.cjs
index 55c312f0..630e87bd 100644
--- a/bin/native-package-gate.cjs
+++ b/bin/native-package-gate.cjs
@@ -125,18 +125,19 @@ function sharpPreparationFiles(platform, arch, version) {
};
}
-function nativePackageContract(nodeModules, platform, arch) {
+function nativePackageContract(nodeModules, platform, arch, onnxRuntime = null) {
const key = targetKey(platform, arch);
if (!TARGETS.has(key)) {
throw new Error(`[native-package-gate] unsupported packaged native target: ${key}`);
}
+ onnxRuntime ||= onnxRuntimePackage(nodeModules);
+
const mac = platform === 'darwin';
const esbuildPackage = mac ? `darwin-${arch}` : 'win32-x64';
const sqlitePackage = mac ? `sqlite-vec-darwin-${arch}` : 'sqlite-vec-windows-x64';
const canvasPackage = mac ? `canvas-darwin-${arch}` : 'canvas-win32-x64-msvc';
const tokenizersPackage = mac ? 'tokenizers-darwin-universal' : 'tokenizers-win32-x64-msvc';
- const onnxRuntime = onnxRuntimePackage(nodeModules);
const onnxBase = `${onnxRuntime.base}/bin/napi-v3/${platform}/${arch}`;
const onnxVersion = onnxRuntime.version;
diff --git a/bin/packaged-dependency-gate.cjs b/bin/packaged-dependency-gate.cjs
index 3418e88b..ada690bc 100644
--- a/bin/packaged-dependency-gate.cjs
+++ b/bin/packaged-dependency-gate.cjs
@@ -286,7 +286,7 @@ function verifyDirectDependencies(sourcePackage, lock, records) {
}
}
-function verifyResolvedGraph(sourcePackage, rootManifest, records) {
+function verifyResolvedGraph(sourcePackage, rootManifest, records, allowUnreachable = false) {
const overrides = sourcePackage.overrides || {};
const reachable = new Set();
const queue = [{ root: '', name: sourcePackage.name, version: sourcePackage.version, manifest: rootManifest }];
@@ -314,10 +314,52 @@ function verifyResolvedGraph(sourcePackage, rootManifest, records) {
.filter((record) => !reachable.has(record.root))
.map((record) => `${record.root} (${record.name}@${record.version})`)
.sort();
- if (unexpected.length > 0) {
+ if (!allowUnreachable && unexpected.length > 0) {
fail(`unreachable package(s) in app.asar: ${unexpected.join(', ')}`);
}
- return { edgeCount, overrideEdgeCount };
+ return { edgeCount, overrideEdgeCount, reachable: [...reachable] };
+}
+
+// Packaging-only source/cache checks reuse the final archive's resolution and
+// version rules. Unrelated dev and other-platform optional packages may exist
+// in the lock or build tree, but cannot satisfy a missing production edge.
+function verifySourceDependencyGraph(sourcePackage, lock, platform, arch) {
+ validateRootContract(sourcePackage, sourcePackage, lock);
+ if (!sameJson(lock.packages[''].devDependencies, sourcePackage.devDependencies)) {
+ fail('package-lock.json root devDependencies differs from source package.json');
+ }
+ const records = new Map();
+ for (const [root, manifest] of Object.entries(lock.packages)) {
+ if (!root || !listMatchesTarget(manifest.os, platform) || !listMatchesTarget(manifest.cpu, arch)) continue;
+ records.set(root, { root, name: manifest.name || packageNameFromLockPath(root), version: manifest.version, manifest });
+ }
+ verifyDirectDependencies(sourcePackage, lock, records);
+ return { ...verifyResolvedGraph(sourcePackage, sourcePackage, records, true), records };
+}
+
+function verifyInstalledProductionDependencies(pcRoot, platform, arch) {
+ const source = readJson('package.json', path.join(pcRoot, 'package.json'));
+ const lock = readJson('package-lock.json', path.join(pcRoot, 'package-lock.json'));
+ const locked = verifySourceDependencyGraph(source, lock, platform, arch);
+ const records = new Map();
+ // Follow the locked production closure, including nested packages. Never
+ // require() dependency code or load a target native binding on the build host.
+ for (const root of locked.reachable) {
+ const expected = locked.records.get(root);
+ const file = path.join(pcRoot, root, 'package.json');
+ // npm may legitimately omit optional packages. The resolved graph below
+ // still rejects every missing required edge, including nested fallbacks.
+ if (!fs.existsSync(file)) continue;
+ const manifest = readJson(`${root}/package.json`, file);
+ if (manifest.name !== expected.name || manifest.version !== expected.version) {
+ fail(`installed ${root} name/version does not match package-lock.json`);
+ }
+ for (const key of ['dependencies', 'optionalDependencies', 'peerDependencies', 'peerDependenciesMeta']) {
+ if (!sameJson(manifest[key] || {}, expected.manifest[key] || {})) fail(`installed ${root} ${key} differs from package-lock.json`);
+ }
+ records.set(root, { ...expected, manifest });
+ }
+ return verifyResolvedGraph(source, source, records, true);
}
function nodeRuntimeClosure(records, rootNames, includeOptional) {
@@ -475,4 +517,6 @@ module.exports = {
packageRootFromManifestPath,
verifyPackagedDependencyGraph,
verifyNodeRuntimeBuildConfig,
+ verifySourceDependencyGraph,
+ verifyInstalledProductionDependencies,
};
diff --git a/bin/runtime-gate.cjs b/bin/runtime-gate.cjs
index 5749ea36..4c1e7d53 100644
--- a/bin/runtime-gate.cjs
+++ b/bin/runtime-gate.cjs
@@ -389,13 +389,22 @@ function verifyRuntimeDir(kind, dir, key, spec, asset, targetPlatform, targetArc
requiredFile(`${kind} runtime executable`, executable);
for (const companion of runtimeCompanionFiles(kind, executable, targetPlatform, spec)) {
requiredFile(`${kind} runtime companion`, companion);
+ verifyExecutableMode(companion, targetPlatform, options);
}
+ verifyExecutableMode(executable, targetPlatform, options);
if (options.checkArch !== false && targetPlatform === 'darwin') {
assertDarwinExecutableArch(executable, targetArch);
}
return executable;
}
+function verifyExecutableMode(file, targetPlatform, options) {
+ // Opted in by packaging only; Windows commands have no POSIX execute bit.
+ if (options.requireExecutable && targetPlatform !== 'win32' && (fs.statSync(file).mode & 0o111) === 0) {
+ throw new Error(`[native-deps-gate] runtime file is not executable: ${file}`);
+ }
+}
+
function verifyFfmpegRuntimeDir(runtimeRoot, targetPlatform, targetArch, options = {}) {
const key = runtimeKey(targetPlatform, targetArch);
const allowedKeys = options.allowedKeys || [key];
@@ -422,6 +431,7 @@ function verifyFfmpegRuntimeDir(runtimeRoot, targetPlatform, targetArch, options
}
for (const [name, file] of Object.entries(binaries)) {
requiredFile(`${name} runtime executable`, file);
+ verifyExecutableMode(file, targetPlatform, options);
const expected = marker.binaries && marker.binaries[name];
const stat = fs.statSync(file);
const rawHashMatches = expected
@@ -480,6 +490,7 @@ function verifyWhisperRuntimeDir(runtimeRoot, targetPlatform, targetArch, option
throw new Error(`[native-deps-gate] whisper runtime hash/size mismatch: ${file}`);
}
if (expected.executable) {
+ verifyExecutableMode(file, targetPlatform, options);
assertExecutableArch(file, targetPlatform, targetArch, options);
}
}
@@ -808,6 +819,7 @@ function verifyPhonePasskeyRuntimeDir(runtimeRoot, targetPlatform, targetArch, o
}
}
const binary = path.join(dir, 'orkas-phone-passkey');
+ verifyExecutableMode(binary, targetPlatform, options);
assertExecutableArch(binary, targetPlatform, targetArch, options);
return binary;
}
diff --git a/run.cmd b/run.cmd
index 6b21d3f1..ffac7fdf 100644
--- a/run.cmd
+++ b/run.cmd
@@ -48,7 +48,8 @@ call node "%APP_DIR%\scripts\ensure-dev-dependencies.cjs"
if errorlevel 1 exit /b 1
pushd "%APP_DIR%"
-call npm run start:electron
+REM Dependencies were prepared above; avoid repeating npm prestart:electron.
+node "%APP_DIR%\node_modules\electron\cli.js" .
set "RC=%ERRORLEVEL%"
popd
exit /b %RC%
diff --git a/run.sh b/run.sh
index 3f7d2a34..2f7f35c1 100755
--- a/run.sh
+++ b/run.sh
@@ -101,4 +101,6 @@ fi
# This is ANGLE fallback noise when probing driver attributes and has no
# functional impact. Filter only that stderr line; pass through everything else.
# If `unbuffer` is unavailable, default line buffering is fine (macOS bash built-in).
-exec npm run start:electron 2> >(grep -v --line-buffered "EGL Driver message" >&2)
+# Dependencies are already prepared above; npm's prestart:electron would run
+# the entire preparation a second time before starting the same Electron CLI.
+exec node "$APP_DIR/node_modules/electron/cli.js" . 2> >(grep -v --line-buffered "EGL Driver message" >&2)
diff --git a/scripts/codesign-adhoc.cjs b/scripts/codesign-adhoc.cjs
index 8b630653..db2c5c27 100644
--- a/scripts/codesign-adhoc.cjs
+++ b/scripts/codesign-adhoc.cjs
@@ -520,6 +520,7 @@ function verifyPackedRuntimePayload(context, appPath, targetPlatform, targetArch
// verifyRuntimeRoot → verifyRuntimeDir → runtimeCompanionFiles (runtime-gate.cjs),
// which the remote extracted; it also keeps marker/pip-shim/arch/dir-allowlist checks.
const options = {
+ requireExecutable: true,
...(context.__orkasTestWhisperContract ? { whisperContract: context.__orkasTestWhisperContract } : {}),
...(context.__orkasTestWindowsVcContract ? { windowsVcContract: context.__orkasTestWindowsVcContract } : {}),
};
diff --git a/scripts/ensure-runtime-before-pack.cjs b/scripts/ensure-runtime-before-pack.cjs
index 58b6bda7..ce29ef01 100644
--- a/scripts/ensure-runtime-before-pack.cjs
+++ b/scripts/ensure-runtime-before-pack.cjs
@@ -206,7 +206,7 @@ module.exports = async function ensureRuntimeBeforePack(context) {
const verified = [];
for (const targetArch of arches) {
- verified.push(...verifyRuntimeRoot(runtimeRoot, platform, targetArch, { allowedKeys }));
+ verified.push(...verifyRuntimeRoot(runtimeRoot, platform, targetArch, { allowedKeys, requireExecutable: true }));
}
console.log(`[runtime-gate] pre-pack verified: ${verified.join(', ')}`);
};
diff --git a/src/main/index.ts b/src/main/index.ts
index 6b8d3b9e..ab2c32f4 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1,3 +1,4 @@
+import { createShutdownCoordinator } from './util/shutdown';
/**
* Orkas — Electron main entry.
*
@@ -1420,34 +1421,19 @@ if (!gotLock) {
app.quit();
} else {
- // Normal quit and explicit exit share the same local-resource drain.
- let shutdownFlushed = false;
- let shutdownFlushPromise: Promise<void> | null = null;
- const flushForShutdown = (): Promise<void> => {
- if (shutdownFlushPromise) return shutdownFlushPromise;
- shutdownFlushPromise = (async () => {
- const lifecycleFlush = openLifecycleTracking?.flushQuit();
- try { await searchFeature.flushAll(); }
- catch (err) { createLogger('search').warn('final flush failed', { error: (err as Error).message }); }
- try {
- const kb = await import('./features/kb_vector');
- kb.closeAllKb();
- } catch (err) { createLogger('kb_vector').warn('close failed', { error: (err as Error).message }); }
- try {
- const kbEmbed = await import('./features/kb_embed');
- kbEmbed.closeEmbedder();
- } catch (err) { createLogger('kb_embed').warn('close failed', { error: logErrorSummary(err) }); }
- try {
- const images = await import('./util/sharp-runtime');
- images.closeImageRuntime();
- } catch { createLogger('image-runtime').warn('image runtime shutdown failed'); }
- const webAssistSessions = await import('./features/web_assist_session');
- await webAssistSessions.flushWebAssistSessions();
- await sweepOfficeResidents('quit');
- await lifecycleFlush;
- })().finally(() => { shutdownFlushed = true; });
- return shutdownFlushPromise;
- };
+ const shutdown = createShutdownCoordinator({
+ localTasks: [
+ { name: 'open-lifecycle', run: async () => { await openLifecycleTracking?.flushQuit(); } },
+ { 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(); } },
+ ],
+ onFailure: name => createLogger(name).warn('shutdown preparation failed'),
+ });
+ const flushForShutdown = shutdown.prepare;
// Account login is stripped, but connector OAuth still returns through the OS protocol. Keep
// this connector-only receiver outside the removed account protocol module.
@@ -1756,7 +1742,7 @@ if (!gotLock) {
app.on('before-quit', async (e) => {
isQuitting = true;
- if (shutdownFlushed) return;
+ if (shutdown.complete) return;
e.preventDefault();
try { await flushForShutdown(); } finally { app.quit(); }
});
diff --git a/src/main/util/shutdown.ts b/src/main/util/shutdown.ts
new file mode 100644
index 00000000..7c6fb98c
--- /dev/null
+++ b/src/main/util/shutdown.ts
@@ -0,0 +1,30 @@
+interface ShutdownTask {
+ name: string;
+ run: () => void | Promise<void>;
+}
+
+/** Start and await each local durability task exactly once before exit. */
+export function createShutdownCoordinator({ localTasks, onFailure }: {
+ localTasks: readonly ShutdownTask[];
+ onFailure: (name: string) => void;
+}) {
+ let pending: Promise<void> | null = null;
+ let complete = false;
+ const run = async (task: ShutdownTask) => {
+ try { await task.run(); }
+ catch { onFailure(task.name); }
+ };
+ return {
+ get complete() { return complete; },
+ prepare(): Promise<void> {
+ if (pending) return pending;
+ // Publish the shared promise before any cleanup can synchronously emit
+ // another quit (for example while Electron loads a native module).
+ pending = Promise.resolve().then(async () => {
+ // Start every local save/close even if another one is slow or fails.
+ await Promise.all(localTasks.map(run));
+ }).finally(() => { complete = true; });
+ return pending;
+ },
+ };
+}
diff --git a/test/main/index-process.test.ts b/test/main/index-process.test.ts
index 73b9a8a4..bd66fbdf 100644
--- a/test/main/index-process.test.ts
+++ b/test/main/index-process.test.ts
@@ -42,7 +42,9 @@ describe('main process child-process ownership', () => {
expect(relaunchBlock).toContain('child.unref()');
expect(relaunchBlock).toContain('await prepareShutdown()');
expect(source).toContain('registerIpc(flushForShutdown)');
- expect(source).toContain('const lifecycleFlush = openLifecycleTracking?.flushQuit()');
+ // 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\(\); \}/);
const shellLauncher = fs.readFileSync(
path.resolve(process.cwd(), 'run.sh'),
diff --git a/test/main/util/packaged-dependency-gate.test.ts b/test/main/util/packaged-dependency-gate.test.ts
index 88acf01c..a9c80b85 100644
--- a/test/main/util/packaged-dependency-gate.test.ts
+++ b/test/main/util/packaged-dependency-gate.test.ts
@@ -11,6 +11,8 @@ const gate = require('../../../bin/packaged-dependency-gate.cjs') as {
comparePackagedDependencyInventories(left: any, right: any): string;
packageRootFromManifestPath(manifestPath: string): string | null;
verifyNodeRuntimeBuildConfig(sourcePackage: Manifest, lock: Manifest): string[];
+ verifySourceDependencyGraph(sourcePackage: Manifest, lock: Manifest, platform: string, arch: string): any;
+ verifyInstalledProductionDependencies(root: string, platform: string, arch: string): any;
verifyPackagedDependencyGraph(options: {
appAsar: string;
packageJsonFile: string;
@@ -134,6 +136,48 @@ async function verify(value: Fixture): Promise<any> {
}
describe('packaged-dependency-gate', () => {
+ function sourceGraphFixture(): Fixture {
+ const value = fixture();
+ for (const [root, manifest] of Object.entries(value.packages)) {
+ value.lock.packages[root] = { ...manifest };
+ }
+ value.sourcePackage.devDependencies = { 'build-only': '1.0.0' };
+ value.lock.packages[''].devDependencies = { 'build-only': '1.0.0' };
+ value.lock.packages['node_modules/build-only'] = { version: '1.0.0', dev: true };
+ return value;
+ }
+
+ it.each([['darwin', 'x64'], ['darwin', 'arm64'], ['win32', 'x64']])('validates the source graph for %s/%s without requiring other-platform optional packages', (platform, arch) => {
+ const value = sourceGraphFixture();
+ expect(() => gate.verifySourceDependencyGraph(value.sourcePackage, value.lock, platform, arch)).not.toThrow();
+ delete value.lock.packages['node_modules/consumer/node_modules/alpha'];
+ expect(() => gate.verifySourceDependencyGraph(value.sourcePackage, value.lock, platform, arch)).toThrow(/alpha/);
+ });
+
+ it('rejects root lock drift before packaging', () => {
+ const value = sourceGraphFixture();
+ value.lock.packages[''].dependencies = { alpha: '1.0.0' };
+ expect(() => gate.verifySourceDependencyGraph(value.sourcePackage, value.lock, 'win32', 'x64')).toThrow(/root dependencies/);
+ });
+
+ it('rechecks a cached production tree without executing dependencies or requiring dev packages', () => {
+ const value = sourceGraphFixture();
+ writeJson(path.join(tmpDir, 'package.json'), value.sourcePackage);
+ writeJson(path.join(tmpDir, 'package-lock.json'), value.lock);
+ for (const [root, manifest] of Object.entries(value.packages)) {
+ writeJson(path.join(tmpDir, root, 'package.json'), manifest);
+ fs.writeFileSync(path.join(tmpDir, root, 'index.js'), "throw new Error('must not execute during validation');");
+ }
+ expect(() => gate.verifyInstalledProductionDependencies(tmpDir, 'darwin', 'x64')).not.toThrow();
+ fs.rmSync(path.join(tmpDir, 'node_modules/platform-addon'), { recursive: true });
+ expect(() => gate.verifyInstalledProductionDependencies(tmpDir, 'darwin', 'x64')).not.toThrow();
+ const dependency = path.join(tmpDir, 'node_modules/consumer/node_modules/alpha/package.json');
+ writeJson(dependency, { name: 'alpha', version: '2.0.1' });
+ expect(() => gate.verifyInstalledProductionDependencies(tmpDir, 'darwin', 'x64')).toThrow(/version/);
+ fs.rmSync(path.dirname(dependency), { recursive: true });
+ expect(() => gate.verifyInstalledProductionDependencies(tmpDir, 'darwin', 'x64')).toThrow(/alpha/);
+ });
+
// A valid archive graph is insufficient for the stock Node image process:
// every dependency it resolves must also exist outside the archive.
function imageFixture(): Fixture {
diff --git a/test/main/util/runtime-gate.test.ts b/test/main/util/runtime-gate.test.ts
index 15f592f6..64f1630f 100644
--- a/test/main/util/runtime-gate.test.ts
+++ b/test/main/util/runtime-gate.test.ts
@@ -7,6 +7,7 @@ import * as path from 'node:path';
const require = createRequire(import.meta.url);
const {
+ verifyRuntimeDir,
verifyPhonePasskeyRuntimeDir,
requiredRuntimeVerificationEntries,
verifyFfmpegRuntimeDir,
@@ -14,6 +15,7 @@ const {
verifyWhisperRuntimeDir,
verifyWindowsVcImportClosure,
} = require('../../../bin/runtime-gate.cjs') as {
+ verifyRuntimeDir: (...args: any[]) => string;
verifyPhonePasskeyRuntimeDir: (root: string, platform: string, arch: string, options?: Record<string, unknown>) => string;
requiredRuntimeVerificationEntries: (platform: string, arch: string) => string[];
verifyFfmpegRuntimeDir: (root: string, platform: string, arch: string, options?: Record<string, unknown>) => string[];
@@ -36,6 +38,27 @@ afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
+describe('packaging executable mode check', () => {
+ it.skipIf(process.platform === 'win32')('rejects non-executable POSIX runtimes and companions only when packaging opts in', () => {
+ const dir = path.join(tmpDir, 'node');
+ fs.mkdirSync(path.join(dir, 'bin'), { recursive: true });
+ const asset = { executable: 'bin/node', name: 'node.tar.gz', sha256: 'fixture', size: 123 };
+ const spec = { version: '24.0.0' };
+ fs.writeFileSync(path.join(dir, '.orkas-runtime.json'), JSON.stringify({ kind: 'node', platformKey: 'darwin-arm64', version: spec.version, asset: asset.name, sha256: asset.sha256, size: asset.size }));
+ for (const name of ['node', 'npm', 'npx']) fs.writeFileSync(path.join(dir, 'bin', name), 'fixture', { mode: 0o755 });
+ const check = (packaging: boolean) => verifyRuntimeDir('node', dir, 'darwin-arm64', spec, asset, 'darwin', 'arm64', { checkArch: false, requireExecutable: packaging });
+ expect(check(true)).toBe(path.join(dir, 'bin/node'));
+ for (const name of ['node', 'npm', 'npx']) {
+ const file = path.join(dir, 'bin', name);
+ fs.chmodSync(file, 0o644);
+ expect(() => check(true)).toThrow(/executable/);
+ expect(() => check(false)).not.toThrow();
+ expect(fs.statSync(file).mode & 0o777).toBe(0o644);
+ fs.chmodSync(file, 0o755);
+ }
+ });
+});
+
const RUNTIME_SIZES: Record<'python' | 'uv' | 'node', number> = { python: 101, uv: 202, node: 303 };
function writeManifest(root: string, keys: string[]): void {
diff --git a/test/main/util/shutdown.test.ts b/test/main/util/shutdown.test.ts
new file mode 100644
index 00000000..7225f1e4
--- /dev/null
+++ b/test/main/util/shutdown.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createShutdownCoordinator } from '../../../src/main/util/shutdown';
+
+function gate() {
+ let release!: () => void;
+ const promise = new Promise<void>(resolve => { release = resolve; });
+ return { promise, release };
+}
+
+describe('application shutdown durability and latency', () => {
+ it('coalesces a quit emitted synchronously by local cleanup', async () => {
+ let reentered: Promise<void> | undefined;
+ let calls = 0;
+ const shutdown = createShutdownCoordinator({
+ localTasks: [{ name: 'local', run: () => {
+ if (++calls === 1) reentered = shutdown.prepare();
+ } }], onFailure: vi.fn(),
+ });
+ const pending = shutdown.prepare();
+ await pending;
+ expect(calls).toBe(1);
+ expect(reentered).toBe(pending);
+ });
+
+ it('finishes independent local saves together before normal exit', async () => {
+ const search = gate();
+ const browser = gate();
+ const started: string[] = [];
+ const shutdown = createShutdownCoordinator({
+ localTasks: [
+ { name: 'search', run: () => { started.push('search'); return search.promise; } },
+ { name: 'browser', run: () => { started.push('browser'); return browser.promise; } },
+ ], onFailure: vi.fn(),
+ });
+ const pending = shutdown.prepare();
+ await Promise.resolve();
+ expect(started).toEqual(['search', 'browser']);
+ search.release();
+ await Promise.resolve();
+ expect(shutdown.complete).toBe(false);
+ browser.release();
+ await pending;
+ expect(shutdown.complete).toBe(true);
+ });
+
+
+ it('drains remaining local saves and reports a failed cleanup once', async () => {
+ const saved = gate();
+ const onFailure = vi.fn();
+ const shutdown = createShutdownCoordinator({
+ localTasks: [
+ { name: 'broken', run: () => { throw new Error('controlled failure'); } },
+ { name: 'browser', run: () => saved.promise },
+ ], onFailure,
+ });
+ const pending = shutdown.prepare();
+ await Promise.resolve();
+ expect(shutdown.complete).toBe(false);
+ saved.release();
+ await pending;
+ expect(onFailure).toHaveBeenCalledExactlyOnceWith('broken');
+ expect(shutdown.complete).toBe(true);
+ });
+
+});