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.

Prepare the selected model API during idle startup

wyt1846cd8b343b
diff --git a/src/main/features/auth.ts b/src/main/features/auth.ts
index c283210c..c7a35c8e 100644
--- a/src/main/features/auth.ts
+++ b/src/main/features/auth.ts
@@ -1670,6 +1670,36 @@ async function buildModelNameLookup(): Promise<(p: string, m: string) => string>
};
}
+/** Read only the first eligible transport's metadata for idle code preparation.
+ * Never refresh OAuth, resolve credentials, construct a client, or send a request. */
+export async function getChatPreloadApi(): Promise<string | null> {
+ if (!hasActiveUser()) return null;
+ const uid = getActiveUserId();
+ const store = loadProfiles();
+ const allowed = store.entries.filter(entry => isEntryAllowed(store, entry) && !isCooledDown(entry.profileId));
+ if (!allowed.length) return null;
+ const resolvable = await buildRuntimeModelResolver(allowed);
+ if (!isActiveAuthOwner(uid)) return null;
+ const entry = allowed.find(entry => resolvable(entry.provider, entry.model));
+ if (!entry) return null;
+ if (EXTERNAL_API_PROVIDERS.includes(entry.provider)) {
+ const models = await import('../model/core-agent/external-providers');
+ if (!isActiveAuthOwner(uid)) return null;
+ if (entry.provider === ORKAS_API_PROVIDER) return models.buildOrkasApiModel(entry.model).api;
+ if (entry.provider === 'moonshot') return models.buildMoonshotModel(entry.model).api;
+ if (entry.provider === 'deepseek') return models.buildDeepSeekModel(entry.model).api;
+ if (entry.provider === 'doubao') return models.buildDoubaoModel(entry.model).api;
+ const config = customRuntimeConfigFromProfile(store.profiles[entry.profileId]);
+ if (!config) return null;
+ return (config.protocol === 'anthropic'
+ ? models.buildCustomAnthropicModel(entry.model, config)
+ : models.buildCustomOpenAICompatibleModel(entry.model, config)).api;
+ }
+ const catalog = await ca();
+ if (!isActiveAuthOwner(uid)) return null;
+ return resolveConfiguredPiModel(catalog, entry.provider, entry.model)?.model.api ?? null;
+}
+
export async function listEntries(
opts: { includeUnavailable?: boolean } = {},
): Promise<{ entries: EntryView[] }> {
diff --git a/src/main/features/model-api-preload.ts b/src/main/features/model-api-preload.ts
new file mode 100644
index 00000000..53e7f0e4
--- /dev/null
+++ b/src/main/features/model-api-preload.ts
@@ -0,0 +1,35 @@
+import { getChatPreloadApi } from './auth';
+import { getActiveUserId } from './users';
+import { preloadModelApi } from '../model/core-agent/api-preload';
+import { createLogger } from '../logger';
+import { logErrorSummary } from '../util/log-redact';
+import { isBootAdmissionIdle, scheduleBootBackground } from '../util/boot_init';
+
+const log = createLogger('model-api-preload');
+const QUIET_MS = 3_000;
+
+/** One best-effort opportunity after the first document loads. Foreground sends
+ * never depend on this task; native ESM imports share their normal module cache.
+ * A late login or a changed selection retains ordinary lazy loading. */
+export function scheduleChatApiPreload(isRendererReady: () => Promise<boolean>) {
+ return scheduleBootBackground('model:preload-api', async (signal) => {
+ try {
+ if (signal?.aborted || !(await isRendererReady()) || !isBootAdmissionIdle(QUIET_MS)) return;
+ const uid = getActiveUserId();
+ const api = await getChatPreloadApi();
+ // Metadata discovery can yield. Recheck both ownership and user activity
+ // immediately before the non-interruptible module evaluation begins.
+ if (!api || signal?.aborted || uid !== getActiveUserId() || !isBootAdmissionIdle(QUIET_MS)) return;
+ const start = performance.now();
+ if (await preloadModelApi(api, () => !signal?.aborted && uid === getActiveUserId() && isBootAdmissionIdle(QUIET_MS))) {
+ log.info('model API preload finished', { api, duration_ms: Math.round(performance.now() - start) });
+ }
+ } catch (error) {
+ log.warn('model API preload unavailable', { error: logErrorSummary(error) });
+ }
+ }, 6_000, {
+ resourceClass: 'disk', preferIdle: true, recentActivityMs: QUIET_MS,
+ // This optional work must never override continuing user interaction.
+ maxUserDeferralMs: Number.POSITIVE_INFINITY,
+ });
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index 30105d65..4beea79c 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1,4 +1,5 @@
import { createShutdownCoordinator } from './util/shutdown';
+import { scheduleChatApiPreload } from './features/model-api-preload';
/**
* Orkas — Electron main entry.
*
@@ -283,6 +284,8 @@ function emitTaskTerminalToRenderer(event: TaskTerminalEvent): void {
taskTerminalUi.emit({ type: 'terminal', ...terminal }, ownerUserId);
}
+let modelApiPreloadScheduled = false;
+
function createWindow(): BrowserWindow {
const dev = !app.isPackaged;
const restored = windowState.restoreWindowState();
@@ -325,6 +328,15 @@ function createWindow(): BrowserWindow {
win.webContents.on('did-finish-load', () => {
mainRendererReady = true;
for (const channel of rendererChannels) channel.flush();
+ if (!modelApiPreloadScheduled) {
+ modelApiPreloadScheduled = true;
+ scheduleChatApiPreload(async () => {
+ if (win.isDestroyed() || win.webContents.isDestroyed() || win.webContents.isLoadingMainFrame()) return false;
+ return await win.webContents.executeJavaScript(
+ 'document.documentElement.dataset.orkasBootReady === "true"',
+ ) === true;
+ });
+ }
});
win.webContents.on('render-process-gone', () => {
mainRendererReady = false;
diff --git a/src/main/model/core-agent/api-preload.ts b/src/main/model/core-agent/api-preload.ts
new file mode 100644
index 00000000..1716a6b1
--- /dev/null
+++ b/src/main/model/core-agent/api-preload.ts
@@ -0,0 +1,30 @@
+/** Load code only. Keep the provider registry, clients and request path untouched.
+ * Other SDK families retain demand loading until their idle cost is verified. */
+export async function preloadModelApi(api: string, shouldContinue: () => boolean = () => true): Promise<boolean> {
+ // Public SDK entry points split linking into smaller batches. Each batch
+ // shares the ordinary ESM cache, and input/foreground work can stop the
+ // remaining preparation at the next event-loop turn.
+ const steps: Array<() => Promise<unknown>> = api === 'anthropic-messages' ? [
+ () => import('@anthropic-ai/sdk/resources'),
+ () => import('@anthropic-ai/sdk/client'),
+ ] : ['openai-completions', 'openai-responses', 'azure-openai-responses'].includes(api) ? [
+ () => import('openai/resources'),
+ () => import('openai/client'),
+ ] : [];
+ for (const load of steps) {
+ await new Promise<void>(resolve => setTimeout(resolve, 0));
+ if (!shouldContinue()) return false;
+ await load();
+ }
+ await new Promise<void>(resolve => setTimeout(resolve, 0));
+ if (!shouldContinue()) return false;
+ switch (api) {
+ case 'anthropic-messages': await import('@earendil-works/pi-ai/api/anthropic-messages'); break;
+ case 'openai-completions': await import('@earendil-works/pi-ai/api/openai-completions'); break;
+ case 'openai-responses': await import('@earendil-works/pi-ai/api/openai-responses'); break;
+ case 'openai-codex-responses': await import('@earendil-works/pi-ai/api/openai-codex-responses'); break;
+ case 'azure-openai-responses': await import('@earendil-works/pi-ai/api/azure-openai-responses'); break;
+ default: return false;
+ }
+ return true;
+}
diff --git a/src/main/util/boot_init.ts b/src/main/util/boot_init.ts
index bfc8038b..f7fcd63b 100644
--- a/src/main/util/boot_init.ts
+++ b/src/main/util/boot_init.ts
@@ -87,6 +87,8 @@ const _standaloneTimers = new Set<NodeJS.Timeout>();
const _resourceTails = new Map<BootResourceClass, Promise<void>>();
let _lastUserActivityAt = Date.now();
let _isRuntimeBusy: () => boolean = () => false;
+let _lifetime = new AbortController();
+const _standaloneCancels = new Set<() => void>();
export function configureBootAdmission(options: { isRuntimeBusy?: () => boolean } = {}): void {
_isRuntimeBusy = typeof options.isRuntimeBusy === 'function'
@@ -134,8 +136,21 @@ export function scheduleBootBackground(
const finish = (): void => {
if (settled) return;
settled = true;
+ _standaloneCancels.delete(cancel);
resolvePromise();
};
+ const cancel = (): void => {
+ if (cancelled || settled) return;
+ cancelled = true;
+ controller.abort(new Error(`background task cancelled: ${name}`));
+ if (timer) {
+ clearTimeout(timer);
+ _standaloneTimers.delete(timer);
+ timer = null;
+ }
+ finish();
+ };
+ _standaloneCancels.add(cancel);
timer = setTimeout(() => {
if (timer) _standaloneTimers.delete(timer);
timer = null;
@@ -146,17 +161,7 @@ export function scheduleBootBackground(
timer.unref?.();
_standaloneTimers.add(timer);
return {
- cancel() {
- if (cancelled || settled) return;
- cancelled = true;
- controller.abort(new Error(`background task cancelled: ${name}`));
- if (timer) {
- clearTimeout(timer);
- _standaloneTimers.delete(timer);
- timer = null;
- }
- finish();
- },
+ cancel,
promise,
};
}
@@ -216,7 +221,7 @@ export async function runBootPhases(deferMs: number = DEFAULT_DEFER_MS): Promise
_immediateRan = true;
log.info(`boot immediate phase: tasks=${_immediate.length}`);
await _runBatch(_immediate, 'immediate');
- if (!_deferredScheduled) {
+ if (!_deferredScheduled && !_lifetime.signal.aborted) {
_deferredScheduled = true;
_deferredBaseTimer = setTimeout(() => {
_deferredBaseTimer = null;
@@ -253,7 +258,9 @@ async function _runDeferredBatches(): Promise<void> {
async function _runBatch(tasks: Task[], phase: string): Promise<void> {
const inFlight: Promise<unknown>[] = [];
- for (const t of tasks) {
+ const lifetime = _lifetime.signal;
+ for (const task of tasks) {
+ const t = { ...task, signal: AbortSignal.any([lifetime, ...(task.signal ? [task.signal] : [])]) };
if (t.mode === 'serial') {
// Barrier: settle any pending parallel work before running this
// task, then await it.
@@ -270,6 +277,7 @@ async function _runBatch(tasks: Task[], phase: string): Promise<void> {
}
async function _runOne(t: Task, phase: string): Promise<void> {
+ t = { ...t, signal: AbortSignal.any([_lifetime.signal, ...(t.signal ? [t.signal] : [])]) };
const resource = t.options.resourceClass;
if (resource) {
const previous = _resourceTails.get(resource) || Promise.resolve();
@@ -343,14 +351,27 @@ async function _waitForAdmission(t: Task, phase: string): Promise<boolean> {
}
}
-/** Test-only — reset internal state so the suite can register & re-run. */
-export function _resetForTests(): void {
+/** No startup work may begin or recreate dependencies during application exit. */
+export function stopBootWork(): void {
+ _lifetime.abort(new Error('application is closing'));
+ for (const cancel of [..._standaloneCancels]) cancel();
if (_deferredBaseTimer) clearTimeout(_deferredBaseTimer);
_deferredBaseTimer = null;
for (const timer of _deferredOffsetTimers) clearTimeout(timer);
_deferredOffsetTimers.clear();
for (const timer of _standaloneTimers) clearTimeout(timer);
_standaloneTimers.clear();
+}
+
+/** A failed exit may accept new work, but never replay cancelled boot tasks. */
+export function resumeBootAdmission(): void {
+ if (_lifetime.signal.aborted) _lifetime = new AbortController();
+}
+
+/** Test-only — reset internal state so the suite can register & re-run. */
+export function _resetForTests(): void {
+ stopBootWork();
+ _lifetime = new AbortController();
_immediate.length = 0;
_deferred.length = 0;
_immediateRan = false;
diff --git a/test/e2e/startup_e2e_model_preload.spec.ts b/test/e2e/startup_e2e_model_preload.spec.ts
new file mode 100644
index 00000000..76faec91
--- /dev/null
+++ b/test/e2e/startup_e2e_model_preload.spec.ts
@@ -0,0 +1,49 @@
+import { expect, test } from '@playwright/test';
+import { OrkasTestApp } from './fixtures/orkas';
+import { checkLatencyBudget } from '../helpers/latency-budget';
+const { collectLogFiles } = require('./fixtures/electron-log-files.cjs');
+
+test('prepares the selected API after boot without requests and keeps Main responsive', async ({}, testInfo) => {
+ const app = new OrkasTestApp(testInfo, { modelStub: true });
+ try {
+ await app.launch();
+ const page = app.page!;
+ await expect(page.locator('html')).toHaveAttribute('data-orkas-boot-ready', 'true');
+ expect(app.modelRequests).toHaveLength(0);
+ expect(collectLogFiles(app.root)).not.toContain('model API preload finished');
+ await app.electronApp!.evaluate(({ app }) => {
+ const require = (process as any).mainModule.require.bind((process as any).mainModule);
+ const boot = require(`${app.getAppPath()}/src/main/util/boot_init`);
+ boot.noteBootUserActivity();
+ const pulse = { last: performance.now(), maxGapMs: 0, timer: null as any };
+ pulse.timer = setInterval(() => {
+ const now = performance.now();
+ pulse.maxGapMs = Math.max(pulse.maxGapMs, now - pulse.last - 10);
+ pulse.last = now;
+ }, 10);
+ (globalThis as any).__preloadPulse = pulse;
+ });
+ await expect.poll(() => collectLogFiles(app.root).includes('model API preload finished'), {
+ timeout: 30_000, intervals: [500],
+ }).toBe(true);
+ expect(app.modelRequests).toHaveLength(0);
+ const pulse = await app.electronApp!.evaluate(async () => {
+ await new Promise(resolve => setTimeout(resolve, 20));
+ const pulse = (globalThis as any).__preloadPulse;
+ clearInterval(pulse.timer);
+ delete (globalThis as any).__preloadPulse;
+ return { maxGapMs: pulse.maxGapMs };
+ });
+ checkLatencyBudget('main loop response during idle API preload', { elapsedMs: pulse.maxGapMs });
+ await page.locator('#new-chat-input').fill('Reply after idle preparation.');
+ await page.locator('#new-chat-send-btn').click();
+ await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]'))
+ .toContainText('Hello from the local E2E model.', { timeout: 30_000 });
+ expect(app.modelRequests).toHaveLength(1);
+ await expect(page.locator('#chat-input')).toBeEditable();
+ await testInfo.attach('preload-responsiveness', {
+ body: JSON.stringify({ boot_ready_ms: app.lastLaunchReadyMs, main_loop_gap_ms: pulse.maxGapMs }),
+ contentType: 'application/json',
+ });
+ } finally { await app.dispose(); }
+});
diff --git a/test/main/features/auth.test.ts b/test/main/features/auth.test.ts
index 86e93915..30ab6b11 100644
--- a/test/main/features/auth.test.ts
+++ b/test/main/features/auth.test.ts
@@ -2024,3 +2024,39 @@ describe('auth › chat picker operation ownership', () => {
} finally { release(); await pending; }
});
});
+
+describe('auth › idle API preload metadata', () => {
+ it('returns no target without configured credentials and makes no request', async () => {
+ const fetch = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('No preload network allowed'));
+ try {
+ const a = await import('../../../src/main/features/auth');
+ expect(await a.getChatPreloadApi()).toBeNull();
+ expect(fetch).not.toHaveBeenCalled();
+ } finally { fetch.mockRestore(); }
+ });
+ it.each([
+ ['openai', 'openai-completions'], ['anthropic', 'anthropic-messages'],
+ ])('uses the saved custom %s protocol without changing the selection', async (protocol, api) => {
+ const a = await import('../../../src/main/features/auth');
+ await a.addCustomModelEntry({ protocol, baseUrl: 'https://example.invalid/v1', model: 'fixture-model', apiKey: 'fixture-key' });
+ const before = await a.getConfig();
+ expect(await a.getChatPreloadApi()).toBe(api);
+ expect(await a.getConfig()).toEqual(before);
+ });
+ it('loads the current API metadata without refreshing an expired OAuth credential', async () => {
+ const refresh = vi.fn().mockRejectedValue(new Error('Preload must not refresh credentials'));
+ const provider = { id: 'anthropic', name: 'Controlled OAuth fixture', refreshToken: refresh, getApiKey: (c: any) => c.access };
+ vi.doMock('@earendil-works/pi-ai/oauth', () => ({ getOAuthProvider: () => provider, getOAuthProviders: () => [provider], registerOAuthProvider: vi.fn() }));
+ await writeExpiredOAuthEntry({ providerId: 'anthropic', model: 'claude-sonnet-5' });
+ const a = await import('../../../src/main/features/auth');
+ expect(await a.getChatPreloadApi()).toBe('anthropic-messages');
+ expect(refresh).not.toHaveBeenCalled();
+ });
+ it('reads the changed account instead of reusing a previous preload target', async () => {
+ const a = await import('../../../src/main/features/auth');
+ await a.addApiKeyEntry('anthropic', 'claude-sonnet-5', 'fixture-key');
+ expect(await a.getChatPreloadApi()).toBe('anthropic-messages');
+ (await import('../../../src/main/features/users')).activateUser('preload-other');
+ expect(await a.getChatPreloadApi()).toBeNull();
+ });
+});
diff --git a/test/main/features/model-api-preload.test.ts b/test/main/features/model-api-preload.test.ts
new file mode 100644
index 00000000..d077c6f6
--- /dev/null
+++ b/test/main/features/model-api-preload.test.ts
@@ -0,0 +1,92 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ api: vi.fn(), load: vi.fn(), warn: vi.fn(), uid: 'preload-user' }));
+vi.mock('../../../src/main/features/auth', () => ({ getChatPreloadApi: mocks.api }));
+vi.mock('../../../src/main/features/users', () => ({ getActiveUserId: () => mocks.uid }));
+vi.mock('../../../src/main/logger', () => ({ createLogger: () => ({ info: vi.fn(), warn: mocks.warn }) }));
+vi.mock('../../../src/main/model/core-agent/api-preload', () => ({ preloadModelApi: mocks.load }));
+
+import * as boot from '../../../src/main/util/boot_init';
+import { scheduleChatApiPreload } from '../../../src/main/features/model-api-preload';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ boot._resetForTests();
+ mocks.uid = 'preload-user';
+ mocks.api.mockReset().mockResolvedValue('anthropic-messages');
+ mocks.load.mockReset().mockResolvedValue(true);
+ mocks.warn.mockReset();
+});
+afterEach(() => { boot._resetForTests(); vi.useRealTimers(); });
+
+describe('post-startup model API preparation', () => {
+ it('returns immediately, waits until after startup, and loads only the selected API', async () => {
+ const ready = vi.fn(async () => true);
+ const task = scheduleChatApiPreload(ready);
+ expect(ready).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(5_999);
+ expect(mocks.load).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ await task.promise;
+ expect(mocks.load).toHaveBeenCalledExactlyOnceWith('anthropic-messages', expect.any(Function));
+ });
+ it('never forces loading through continuing user input or an active conversation', async () => {
+ let busy = true;
+ boot.configureBootAdmission({ isRuntimeBusy: () => busy });
+ const task = scheduleChatApiPreload(async () => true);
+ await vi.advanceTimersByTimeAsync(130_000);
+ expect(mocks.api).not.toHaveBeenCalled();
+ busy = false;
+ for (let i = 0; i < 130; i++) {
+ boot.noteBootUserActivity();
+ await vi.advanceTimersByTimeAsync(1_000);
+ }
+ expect(mocks.api).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(3_000);
+ await task.promise;
+ expect(mocks.load).toHaveBeenCalledOnce();
+ });
+ it.each(['not-ready', 'no-model', 'cancel', 'account-switch', 'new-input'])(
+ 'does no speculative loading for %s', async (state) => {
+ if (state === 'no-model') mocks.api.mockResolvedValue(null);
+ if (state === 'account-switch' || state === 'new-input') mocks.api.mockImplementation(async () => {
+ if (state === 'account-switch') mocks.uid = 'other-user';
+ else boot.noteBootUserActivity();
+ return 'anthropic-messages';
+ });
+ const task = scheduleChatApiPreload(async () => state !== 'not-ready');
+ if (state === 'cancel') task.cancel();
+ await vi.advanceTimersByTimeAsync(6_000);
+ await task.promise;
+ expect(mocks.load).not.toHaveBeenCalled();
+ },
+ );
+ it('contains a preload failure and leaves later independent work usable', async () => {
+ mocks.load.mockRejectedValueOnce(new Error('fixture import unavailable'));
+ const task = scheduleChatApiPreload(async () => true);
+ await vi.advanceTimersByTimeAsync(6_000);
+ await expect(task.promise).resolves.toBeUndefined();
+ expect(mocks.warn).toHaveBeenCalledOnce();
+ const later = scheduleChatApiPreload(async () => true);
+ await vi.advanceTimersByTimeAsync(6_000);
+ await later.promise;
+ expect(mocks.load).toHaveBeenCalledTimes(2);
+ });
+ it.each(['input', 'conversation', 'account', 'exit'])('stops subsequent batches when %s takes priority', async (reason) => {
+ let busy = false;
+ boot.configureBootAdmission({ isRuntimeBusy: () => busy });
+ mocks.load.mockImplementation(async (_api, shouldContinue) => {
+ expect(shouldContinue()).toBe(true);
+ if (reason === 'input') boot.noteBootUserActivity();
+ if (reason === 'conversation') busy = true;
+ if (reason === 'account') mocks.uid = 'other';
+ if (reason === 'exit') boot.stopBootWork();
+ expect(shouldContinue()).toBe(false);
+ return false;
+ });
+ const task = scheduleChatApiPreload(async () => true);
+ await vi.advanceTimersByTimeAsync(6_000);
+ await task.promise;
+ expect(mocks.load).toHaveBeenCalledOnce();
+ });
+});
diff --git a/test/main/model/core-agent/api-preload.test.ts b/test/main/model/core-agent/api-preload.test.ts
new file mode 100644
index 00000000..45c59905
--- /dev/null
+++ b/test/main/model/core-agent/api-preload.test.ts
@@ -0,0 +1,44 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mock = vi.hoisted(() => ({ loaded: vi.fn() }));
+beforeEach(() => {
+ vi.resetModules();
+ mock.loaded.mockReset();
+ // Reinstall factories so each scenario begins with a cold SDK graph.
+ vi.doMock('openai/resources', () => { mock.loaded('openai resources'); return {}; });
+ vi.doMock('openai/client', () => { mock.loaded('openai client'); return {}; });
+ vi.doMock('@anthropic-ai/sdk/resources', () => { mock.loaded('anthropic resources'); return {}; });
+ vi.doMock('@anthropic-ai/sdk/client', () => { mock.loaded('anthropic client'); return {}; });
+ vi.doMock('@earendil-works/pi-ai/api/openai-responses', () => { mock.loaded('openai API'); return {}; });
+ vi.doMock('@earendil-works/pi-ai/api/anthropic-messages', () => { mock.loaded('anthropic API'); return {}; });
+ vi.doMock('@earendil-works/pi-ai/api/openai-codex-responses', () => { mock.loaded('codex API'); return {}; });
+});
+
+describe('cooperative SDK preparation', () => {
+ it('does not load the OpenAI SDK for the native-fetch Codex transport', async () => {
+ const { preloadModelApi } = await import('../../../../src/main/model/core-agent/api-preload');
+ expect(await preloadModelApi('openai-codex-responses')).toBe(true);
+ expect(mock.loaded.mock.calls.flat()).toEqual(['codex API']);
+ });
+ it.each([['openai-responses', 'openai'], ['anthropic-messages', 'anthropic']])(
+ 'prepares %s in separate event-loop turns without loading another SDK', async (api, sdk) => {
+ const { preloadModelApi } = await import('../../../../src/main/model/core-agent/api-preload');
+ let foregroundTurns = 0;
+ mock.loaded.mockImplementation(() => { setTimeout(() => foregroundTurns++, 0); });
+ expect(await preloadModelApi(api)).toBe(true);
+ expect(mock.loaded.mock.calls.flat()).toEqual([`${sdk} resources`, `${sdk} client`, `${sdk} API`]);
+ expect(foregroundTurns).toBeGreaterThanOrEqual(2);
+ },
+ );
+ it.each([0, 1, 2])('does not start another import after foreground activity at batch %s', async (allowedBatches) => {
+ const { preloadModelApi } = await import('../../../../src/main/model/core-agent/api-preload');
+ expect(await preloadModelApi('openai-responses', () => mock.loaded.mock.calls.length < allowedBatches)).toBe(false);
+ expect(mock.loaded).toHaveBeenCalledTimes(allowedBatches);
+ expect(mock.loaded.mock.calls.flat()).not.toContain('openai API');
+ });
+ it.each(['unknown-api', 'google-generative-ai'])('leaves %s on the ordinary demand-loading path', async (api) => {
+ const { preloadModelApi } = await import('../../../../src/main/model/core-agent/api-preload');
+ expect(await preloadModelApi(api)).toBe(false);
+ expect(mock.loaded).not.toHaveBeenCalled();
+ });
+});
diff --git a/test/main/util/boot_init.test.ts b/test/main/util/boot_init.test.ts
index 9bcd02cc..c7d18361 100644
--- a/test/main/util/boot_init.test.ts
+++ b/test/main/util/boot_init.test.ts
@@ -12,6 +12,46 @@ afterEach(() => {
});
describe('util/boot_init', () => {
+ it('admits fresh work after a failed quit without reviving the cancelled batch', async () => {
+ vi.useFakeTimers();
+ const boot = await loadBootInit();
+ const old = vi.fn();
+ let release!: () => void;
+ boot.registerImmediate('held', () => new Promise<void>(resolve => { release = resolve; }), 'serial');
+ boot.registerImmediate('old', old);
+ const run = boot.runBootPhases();
+ await Promise.resolve();
+ boot.stopBootWork();
+ boot.resumeBootAdmission();
+ release();
+ await run;
+ const fresh = vi.fn();
+ const work = boot.scheduleBootBackground('fresh', fresh);
+ await vi.advanceTimersByTimeAsync(1);
+ await work.promise;
+ expect(old).not.toHaveBeenCalled();
+ expect(fresh).toHaveBeenCalledOnce();
+ });
+ it('stops deferred and standalone work and cancels an active cooperative task on quit', async () => {
+ vi.useFakeTimers();
+ const boot = await loadBootInit();
+ const later = vi.fn();
+ let activeSignal: AbortSignal | undefined;
+ boot.registerImmediate('active', signal => {
+ activeSignal = signal;
+ return new Promise<void>(resolve => signal!.addEventListener('abort', () => resolve(), { once: true }));
+ });
+ boot.registerDeferred('later', later);
+ const scheduled = boot.scheduleBootBackground('standalone', later, 10_000);
+ const run = boot.runBootPhases();
+ await Promise.resolve();
+ boot.stopBootWork();
+ await run;
+ await scheduled.promise;
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(activeSignal?.aborted).toBe(true);
+ expect(later).not.toHaveBeenCalled();
+ });
it('treats serial tasks as barriers after in-flight parallel work', async () => {
const boot = await loadBootInit();
const order: string[] = [];