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.

fix(resources): restore cancellable reconciliation and catalog refresh

wytcca369ab2558
diff --git a/src/main/index.ts b/src/main/index.ts
index c1e85402..dfaace8b 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -139,6 +139,7 @@ protocol.registerSchemesAsPrivileged([
import * as paths from './paths';
import { serveFileRange as serveFileRangeCore } from './util/http-range';
import {
+ type BootResourceClass,
configureBootAdmission,
noteBootUserActivity,
registerDeferred,
@@ -217,6 +218,7 @@ import * as systemSkills from './features/system_skills';
import * as bundledContentStartup from './features/bundled_content_startup';
import * as builtinMarketplaceStartup from './features/builtin_marketplace_startup';
import type { BuiltinMarketplaceSeedResult } from './features/builtin_marketplace';
+import { createMarketplaceCatalogReader } from './features/marketplace_catalog';
import * as chatAttachments from './features/chat_attachments';
import * as chatArtifacts from './features/chat_artifacts';
import * as savedApps from './features/saved_apps';
@@ -817,7 +819,7 @@ async function runBootMaintenanceSweeps(): Promise<void> {
let marketplaceReconcileStatusSubscribed = false;
let marketplaceReconcileInFlight: Promise<void> | null = null;
let marketplaceReconcileInFlightKey = '';
-const marketplaceDefaultsRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();
+const marketplaceDefaultsRetryTasks = new Map<string, ReturnType<typeof scheduleBootBackground>>();
const marketplaceDefaultsRetryAttempts = new Map<string, number>();
function subscribeMarketplaceReconcileStatus(m: typeof import('./features/marketplace_reconcile')): void {
@@ -854,6 +856,7 @@ function broadcastBuiltinMarketplaceSeedChanged(result: BuiltinMarketplaceSeedRe
pulled,
updated_at: Date.now(),
});
+ ipc.broadcastToRenderer('marketplace:content-changed', {});
}
async function seedBuiltinMarketplaceForCurrentUser(
@@ -874,14 +877,13 @@ function marketplaceBootContextStillActive(uid: string): boolean {
}
function clearMarketplaceDefaultsRetry(runKey: string): void {
- const timer = marketplaceDefaultsRetryTimers.get(runKey);
- if (timer) clearTimeout(timer);
- marketplaceDefaultsRetryTimers.delete(runKey);
+ marketplaceDefaultsRetryTasks.get(runKey)?.cancel();
+ marketplaceDefaultsRetryTasks.delete(runKey);
marketplaceDefaultsRetryAttempts.delete(runKey);
}
function scheduleMarketplaceDefaultsRetry(runKey: string, uid: string, error: string): void {
- if (marketplaceDefaultsRetryTimers.has(runKey)) return;
+ if (marketplaceDefaultsRetryTasks.has(runKey)) return;
const attempt = marketplaceDefaultsRetryAttempts.get(runKey) || 0;
const delayMs = MARKETPLACE_DEFAULTS_RETRY_DELAYS_MS[attempt];
if (delayMs === undefined) {
@@ -890,122 +892,159 @@ function scheduleMarketplaceDefaultsRetry(runKey: string, uid: string, error: st
return;
}
marketplaceDefaultsRetryAttempts.set(runKey, attempt + 1);
- const timer = setTimeout(() => {
- marketplaceDefaultsRetryTimers.delete(runKey);
- if (!marketplaceBootContextStillActive(uid)) {
+ const task = scheduleBootBackground(`marketplace-defaults-retry:${runKey}`, async (signal) => {
+ marketplaceDefaultsRetryTasks.delete(runKey);
+ // A retry can become eligible while the earlier network phases drain.
+ // Start a fresh pass afterward instead of joining and losing this retry.
+ if (marketplaceReconcileInFlightKey === runKey) {
+ await marketplaceReconcileInFlight?.catch(() => undefined);
+ }
+ if (signal?.aborted || !marketplaceBootContextStillActive(uid)) {
marketplaceDefaultsRetryAttempts.delete(runKey);
return;
}
- runMarketplaceInstallReconcile('marketplace-defaults-retry').catch((err) => {
- marketplaceBootLog.warn('marketplace default installs retry failed', {
- error: (err as Error).message,
- });
+ await runMarketplaceInstallReconcile('marketplace-defaults-retry', signal).catch((err) => {
+ marketplaceBootLog.warn('marketplace default installs retry failed', { error: (err as Error).message });
});
- }, delayMs);
- timer.unref?.();
- marketplaceDefaultsRetryTimers.set(runKey, timer);
+ }, delayMs, { preferIdle: true, maxUserDeferralMs: 30_000, maxSliceMs: 60_000 });
+ marketplaceDefaultsRetryTasks.set(runKey, task);
marketplaceBootLog.info('scheduled marketplace default installs retry', {
- attempt: attempt + 1,
- delay_ms: delayMs,
- error,
+ attempt: attempt + 1, delay_ms: delayMs, error,
});
}
-async function runMarketplaceInstallReconcile(reason: string): Promise<void> {
+async function runMarketplaceInstallReconcile(reason: string, signal?: AbortSignal): Promise<void> {
const uid = users.getActiveUserId();
- if (!marketplaceBootContextStillActive(uid)) {
+ if (signal?.aborted || !marketplaceBootContextStillActive(uid)) {
marketplaceBootLog.info('skip marketplace reconcile: local user unavailable', { reason });
return;
}
-
const runKey = uid;
if (marketplaceReconcileInFlight && marketplaceReconcileInFlightKey === runKey) {
await marketplaceReconcileInFlight;
return;
}
-
- const shouldContinue = (): boolean => marketplaceBootContextStillActive(uid);
+ const shouldContinue = (): boolean => !signal?.aborted && marketplaceBootContextStillActive(uid);
+ // Network waits must not reserve the disk queue. Cancellation stops queued
+ // phases; active work drains before returning, guarding publication itself.
+ const runStep = async (name: string, resourceClass: BootResourceClass, fn: () => Promise<void>): Promise<void> => {
+ if (!shouldContinue()) return;
+ let operation: Promise<void> | undefined;
+ const scheduled = scheduleBootBackground(`marketplace:${name}`, () => {
+ if (shouldContinue()) return operation = fn();
+ }, 0, { resourceClass, preferIdle: true, maxUserDeferralMs: 30_000 });
+ const cancel = (): void => scheduled.cancel();
+ signal?.addEventListener('abort', cancel, { once: true });
+ if (signal?.aborted) cancel();
+ try {
+ await scheduled.promise;
+ await operation;
+ } finally {
+ signal?.removeEventListener('abort', cancel);
+ }
+ };
marketplaceReconcileInFlightKey = runKey;
marketplaceReconcileInFlight = (async () => {
let defaultSeedStatusActive = false;
let marketplaceReconcileModule: typeof import('./features/marketplace_reconcile') | null = null;
+ let marketplaceModule: typeof import('./features/marketplace') | null = null;
const clearDefaultSeedStatus = (): void => {
if (marketplaceReconcileModule && defaultSeedStatusActive) {
marketplaceReconcileModule.setDefaultInstallSeedStatus(false);
defaultSeedStatusActive = false;
}
};
-
try {
- const [mp, m] = await Promise.all([
- import('./features/marketplace'),
- import('./features/marketplace_reconcile'),
- ]);
- marketplaceReconcileModule = m;
- subscribeMarketplaceReconcileStatus(m);
-
- await seedBuiltinMarketplaceForCurrentUser(reason, shouldContinue);
-
- if (await mp.hasKnownDefaultInstallWork(uid)) {
- m.setDefaultInstallSeedStatus(true);
- defaultSeedStatusActive = true;
- }
-
- if (!shouldContinue()) {
- clearDefaultSeedStatus();
- return;
- }
-
- const builtinMarketplace = await import('./features/builtin_marketplace');
- await builtinMarketplace.resolveBuiltinMarketplaceInstalls(uid, { shouldContinue }).catch((err) => {
- marketplaceBootLog.warn('builtin marketplace resolve failed', { error: logErrorSummary(err) });
+ await runStep('local-content', 'disk', async () => {
+ await seedBuiltinMarketplaceForCurrentUser(reason, shouldContinue);
+ if (!shouldContinue()) return;
+ const [mp, m] = await Promise.all([
+ import('./features/marketplace'), import('./features/marketplace_reconcile'),
+ ]);
+ if (!shouldContinue()) return;
+ marketplaceModule = mp;
+ marketplaceReconcileModule = m;
+ subscribeMarketplaceReconcileStatus(m);
+ if (await mp.hasKnownDefaultInstallWork(uid)) {
+ if (!shouldContinue()) return;
+ m.setDefaultInstallSeedStatus(true);
+ defaultSeedStatusActive = true;
+ }
});
- if (!shouldContinue()) {
- clearDefaultSeedStatus();
- return;
- }
-
- const forceMarketplaceNetwork = reason === 'marketplace-defaults-retry';
- const seeded = await mp.ensureDefaultInstalls(uid, {
- shouldContinue,
- minIntervalMs: forceMarketplaceNetwork ? 0 : MARKETPLACE_DEFAULTS_REFRESH_INTERVAL_MS,
- force: forceMarketplaceNetwork,
+ await runStep('network', 'network', async () => {
+ const catalogReader = createMarketplaceCatalogReader(shouldContinue);
+ const builtinMarketplace = await import('./features/builtin_marketplace');
+ if (!shouldContinue()) return;
+ await builtinMarketplace.resolveBuiltinMarketplaceInstalls(uid, { shouldContinue, catalogReader }).catch((err) => {
+ marketplaceBootLog.warn('builtin marketplace resolve failed', { error: logErrorSummary(err) });
+ });
+ if (!shouldContinue()) return;
+ try {
+ const mp = marketplaceModule || await import('./features/marketplace');
+ const forceMarketplaceNetwork = reason === 'marketplace-defaults-retry';
+ const seeded = await mp.ensureDefaultInstalls(uid, {
+ shouldContinue,
+ minIntervalMs: forceMarketplaceNetwork ? 0 : MARKETPLACE_DEFAULTS_REFRESH_INTERVAL_MS,
+ force: forceMarketplaceNetwork,
+ });
+ if (!shouldContinue()) return;
+ if (seeded.failed) {
+ clearDefaultSeedStatus();
+ scheduleMarketplaceDefaultsRetry(runKey, uid, seeded.error || 'unknown error');
+ } else {
+ clearMarketplaceDefaultsRetry(runKey);
+ }
+ if ((seeded.seeded_agents || seeded.seeded_skills) && marketplaceReconcileModule && !defaultSeedStatusActive) {
+ marketplaceReconcileModule.setDefaultInstallSeedStatus(true);
+ defaultSeedStatusActive = true;
+ }
+ } catch (err) {
+ clearDefaultSeedStatus();
+ marketplaceBootLog.warn('default installs seed failed', { error: (err as Error).message });
+ if (shouldContinue()) scheduleMarketplaceDefaultsRetry(runKey, uid, (err as Error).message);
+ }
+ if (!shouldContinue()) return;
+ try {
+ const m = marketplaceReconcileModule || await import('./features/marketplace_reconcile');
+ await m.checkServerUpdatesForInstalls(uid, {
+ shouldContinue, minIntervalMs: MARKETPLACE_SERVER_CHECK_INTERVAL_MS, catalogReader,
+ });
+ } catch (err) {
+ clearDefaultSeedStatus();
+ marketplaceBootLog.warn('marketplace update check failed', { reason, error: logErrorSummary(err) });
+ }
});
- if (seeded.failed) {
- clearDefaultSeedStatus();
- scheduleMarketplaceDefaultsRetry(runKey, uid, seeded.error || 'unknown error');
- } else {
- clearMarketplaceDefaultsRetry(runKey);
- }
- if ((seeded.seeded_agents || seeded.seeded_skills) && !defaultSeedStatusActive) {
- m.setDefaultInstallSeedStatus(true);
- defaultSeedStatusActive = true;
- }
-
- if (!shouldContinue()) {
- clearDefaultSeedStatus();
- return;
- }
-
- await m.checkServerUpdatesForInstalls(uid, {
- shouldContinue,
- minIntervalMs: MARKETPLACE_SERVER_CHECK_INTERVAL_MS,
+ await runStep('reconcile', 'network', async () => {
+ try {
+ const m = marketplaceReconcileModule || await import('./features/marketplace_reconcile');
+ const result = await m.reconcileInstalls(uid, { shouldContinue });
+ if (!shouldContinue()) return;
+ if (
+ result.pulled_agents || result.pulled_skills
+ || result.pruned_agents || result.pruned_skills
+ || result.restored_agents || result.restored_skills
+ || result.patched_agents || result.patched_skills
+ ) {
+ ipc.broadcastToRenderer('marketplace:content-changed', {});
+ marketplaceBootLog.info('marketplace install reconcile completed', { reason, ...result });
+ }
+ } catch (err) {
+ clearDefaultSeedStatus();
+ marketplaceBootLog.warn('marketplace reconcile failed', { reason, error: (err as Error).message });
+ }
+ });
+ await runStep('local-repair', 'disk', async () => {
+ try {
+ const skills = await import('./features/skills');
+ if (shouldContinue()) await skills.repairLegacySkillEnabledIdsForActiveUser();
+ } catch (err) {
+ marketplaceBootLog.warn('legacy skill enabled-state repair failed', { error: logErrorSummary(err) });
+ }
});
- const result = await m.reconcileInstalls(uid, { shouldContinue });
- if (
- result.pulled_agents || result.pulled_skills
- || result.pruned_agents || result.pruned_skills
- || result.restored_agents || result.restored_skills
- || result.patched_agents || result.patched_skills
- ) {
- marketplaceBootLog.info('marketplace install reconcile completed', { reason, ...result });
- }
} catch (err) {
+ marketplaceBootLog.warn('marketplace install reconcile failed', { reason, error: (err as Error).message });
+ } finally {
clearDefaultSeedStatus();
- marketplaceBootLog.warn('marketplace install reconcile failed', {
- reason,
- error: (err as Error).message,
- });
}
})().finally(() => {
if (marketplaceReconcileInFlightKey === runKey) {
@@ -1777,7 +1816,7 @@ if (!gotLock) {
}));
projectDriverRunner.startDriverScheduler();
});
- registerDeferred('marketplace:reconcile', () => runMarketplaceInstallReconcile('startup'));
+ registerDeferred('marketplace:reconcile', (signal) => runMarketplaceInstallReconcile('startup', signal));
registerDeferred('boot:maintenance-sweeps', () => runBootMaintenanceSweeps(), 'serial', BOOT_HEAVY_DISK_DELAY_MS, idleDisk);
registerDeferred('browser:http-cache', async (signal) => {
diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.js
index 9cfc8a6e..af3adefe 100644
--- a/src/renderer/modules/agents.js
+++ b/src/renderer/modules/agents.js
@@ -1084,6 +1084,33 @@ async function refreshAgentsAfterMarketplaceReconcile() {
}
}
+// Marketplace convergence can finish before its lazy browse UI is loaded.
+// This eager owner also covers the full catalog cached by the composer picker.
+async function _refreshMarketplaceCatalogsAfterChange() {
+ const jobs = [];
+ if (_agentsCache || _agentsLoadInFlight) {
+ jobs.push(['agents', () => refreshAgentsAfterMarketplaceReconcile()]);
+ }
+ if (typeof refreshSkillsAfterMarketplaceReconcile === 'function'
+ && ((typeof _skillsCache !== 'undefined' && _skillsCache)
+ || (typeof _skillsLoadInFlight !== 'undefined' && _skillsLoadInFlight))) {
+ jobs.push(['skills', () => refreshSkillsAfterMarketplaceReconcile()]);
+ }
+ if (typeof refreshMarketplaceAfterContentChange === 'function') {
+ jobs.push(['marketplace', () => refreshMarketplaceAfterContentChange()]);
+ }
+ await Promise.all(jobs.map(async ([kind, refresh]) => {
+ try { await refresh(); }
+ catch (_) { _agentsLog.warn('marketplace content refresh failed', { resource_kind: kind }); }
+ }));
+}
+
+if (typeof window.orkas?.onPushEvent === 'function') {
+ window.orkas.onPushEvent('marketplace:content-changed', () => {
+ _refreshMarketplaceCatalogsAfterChange();
+ });
+}
+
/** Render the per-row "⋯" menu items based on the target agent's source +
* enabled state. Called fresh on each open so the toggle label is right
* and builtin agents see only the enable/disable item. */
@@ -2908,7 +2935,6 @@ function _switchAgentTab(tab) {
// CLI discovery is process-heavy and belongs only to the External flow.
// Start it when that panel actually becomes visible, not whenever the
// default in-process create modal opens.
- if (tab === 'external')
if (tab === 'external' && typeof mountExternalCliSelect === 'function') {
mountExternalCliSelect((cli) => _applyExternalCliDefaults(cli)).catch(() => {});
}
@@ -3081,8 +3107,6 @@ function closeAgentModal(options = {}) {
window.closeAgentModal = closeAgentModal;
function cancelAgentModal() {
- const activeTab = document.querySelector('#agent-modal-tabs .is-active')?.dataset.agentTab || 'create';
- if (activeTab === 'external')
closeAgentModal({ restoreFocus: true });
}
window.cancelAgentModal = cancelAgentModal;
diff --git a/src/renderer/modules/marketplace.js b/src/renderer/modules/marketplace.js
index fc1b6cb3..1df5800b 100644
--- a/src/renderer/modules/marketplace.js
+++ b/src/renderer/modules/marketplace.js
@@ -558,7 +558,6 @@ async function _mpInitReconcileWatch() {
function _mpApplyReconcileStatus(status) {
if (!status) return;
- const prevState = _mpReconcileLastState;
_mpReconcileStatus = status;
_mpReconcileLastState = status.state;
// Auto-hide a finished banner after 3s so a successful reconcile doesn't linger.
@@ -571,33 +570,12 @@ function _mpApplyReconcileStatus(status) {
}, 3000);
}
_mpUpdateReconcileBanner();
- // Reconcile just pulled new content into install dirs. Refresh the agents / skills /
- // marketplace-installed-state caches so the new items appear without the user having to
- // switch tabs. Force re-fetch (loadAgents(true) / loadSkills(true)) bypasses the renderer
- // module-level lists cache; the marketplace listed-state hydrates from those.
- if (status.state === 'done' && prevState === 'running' && status.pulled > 0) {
- Promise.resolve().then(async () => {
- try {
- if (typeof refreshAgentsAfterMarketplaceReconcile === 'function') {
- await refreshAgentsAfterMarketplaceReconcile();
- } else if (typeof loadAgents === 'function') {
- await loadAgents(true);
- }
- } catch { /* ignore */ }
- try {
- if (typeof refreshSkillsAfterMarketplaceReconcile === 'function') {
- await refreshSkillsAfterMarketplaceReconcile();
- } else if (typeof loadSkills === 'function') {
- await loadSkills(true);
- }
- } catch { /* ignore */ }
- // If marketplace panel is open right now, also re-run the install-state hydration
- // so card buttons flip from Install to Installed without a tab switch.
- if (isMarketplaceOpen()) {
- try { await _mpLoadAll(); } catch { /* ignore */ }
- }
- }).catch(() => { /* ignore */ });
- }
+}
+
+// The eager catalog owner calls this only when this feature is loaded. Keep
+// installed buttons and an open detail in sync with the changed local catalog.
+async function refreshMarketplaceAfterContentChange() {
+ if (isMarketplaceOpen() && _mpState) await _mpLoadAll();
}
function _mpScheduleReconcileWatchInit(attempt = 0) {
diff --git a/test/main/features/marketplace_startup_resolution.test.ts b/test/main/features/marketplace_startup_resolution.test.ts
index e1a067b0..0c8a3b4f 100644
--- a/test/main/features/marketplace_startup_resolution.test.ts
+++ b/test/main/features/marketplace_startup_resolution.test.ts
@@ -1,92 +1,278 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as vm from 'node:vm';
import * as ts from 'typescript';
-// Execute the actual startup function with isolated feature boundaries; importing
-// the Electron entry module would launch windows and unrelated startup services.
+const wire = vi.hoisted(() => ({ postJson: vi.fn(), bootWarn: vi.fn() }));
+vi.mock('../../../src/main/features/marketplace', () => ({ postJson: wire.postJson }));
+vi.mock('../../../src/main/logger', () => ({ createLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: wire.bootWarn, error: vi.fn() }) }));
+import * as boot from '../../../src/main/util/boot_init';
+import { createMarketplaceCatalogReader } from '../../../src/main/features/marketplace_catalog';
+
+// Execute the actual entry functions and actual boot admission queue, without
+// importing the Electron entry module (which would open unrelated services).
const source = fs.readFileSync(path.resolve(__dirname, '../../../src/main/index.ts'), 'utf8');
const parsed = ts.createSourceFile('index.ts', source, ts.ScriptTarget.Latest, true);
-const startup = parsed.statements.find((node): node is ts.FunctionDeclaration =>
- ts.isFunctionDeclaration(node) && node.name?.text === 'runMarketplaceInstallReconcile');
-if (!startup) throw new Error('Marketplace startup entry is missing');
-const compiled = ts.transpileModule(`${startup.getText(parsed)}\nexports.run = runMarketplaceInstallReconcile;`, {
+const names = new Set(['clearMarketplaceDefaultsRetry', 'scheduleMarketplaceDefaultsRetry', 'runMarketplaceInstallReconcile', 'broadcastBuiltinMarketplaceSeedChanged']);
+const declarations = parsed.statements.flatMap(node => {
+ if (ts.isFunctionDeclaration(node) && names.has(node.name?.text || '')) return [node.getText(parsed)];
+ if (ts.isVariableStatement(node)) {
+ const selected = node.declarationList.declarations.filter(declaration => ts.isIdentifier(declaration.name)
+ && /^marketplace(?:ReconcileInFlight|DefaultsRetry)/.test(declaration.name.text));
+ return selected.map(declaration => `let ${declaration.getText(parsed)};`);
+ }
+ return [];
+});
+let registration = '';
+function findRegistration(node: ts.Node): void {
+ if (ts.isCallExpression(node) && node.expression.getText(parsed) === 'registerDeferred'
+ && node.arguments[0]?.getText(parsed) === "'marketplace:reconcile'") registration = node.getText(parsed);
+ ts.forEachChild(node, findRegistration);
+}
+findRegistration(parsed);
+if (!registration || declarations.length < 6) throw new Error('Marketplace startup entries are missing');
+const compiled = ts.transpileModule(`${declarations.join('\n')}\nexports.run = runMarketplaceInstallReconcile;\nexports.retry = scheduleMarketplaceDefaultsRetry;\nexports.registerStartup = () => { ${registration}; };\nexports.publishBuiltin = broadcastBuiltinMarketplaceSeedChanged;`, {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
}).outputText;
-function harness() {
+type Options = { shouldContinue: () => boolean; catalogReader?: ReturnType<typeof createMarketplaceCatalogReader> };
+function harness(catalog = false, retryDelayMs = 3_000) {
const events: string[] = [];
+ const readers: unknown[] = [];
let active = true;
+ const controller = new AbortController();
const warn = vi.fn();
+ const broadcast = vi.fn();
const status = vi.fn();
- const resolve = vi.fn(async (_uid: string, opts: { shouldContinue: () => boolean }) => {
+ const seed = vi.fn(async () => { events.push('seed'); });
+ const resolve = vi.fn(async (_uid: string, opts: Options) => {
expect(opts.shouldContinue()).toBe(true);
events.push('resolve');
+ if (catalog) {
+ const reader = opts.catalogReader || createMarketplaceCatalogReader(opts.shouldContinue);
+ readers.push(reader);
+ await reader.read('agents', ['installed-agent']);
+ }
});
+ const defaults = vi.fn(async (): Promise<{ failed?: boolean; error?: string }> => { events.push('defaults'); return {}; });
+ const check = vi.fn(async (_uid: string, opts: Options) => {
+ events.push('catalog');
+ if (catalog) {
+ const reader = opts.catalogReader || createMarketplaceCatalogReader(opts.shouldContinue);
+ readers.push(reader);
+ await reader.read('agents', ['installed-agent']);
+ }
+ });
+ const download = vi.fn(async () => { events.push('download'); return {}; });
+ const repair = vi.fn(async () => { events.push('repair'); return 0; });
+ const schedule = vi.fn(boot.scheduleBootBackground);
const modules: Record<string, unknown> = {
'./features/builtin_marketplace': { resolveBuiltinMarketplaceInstalls: resolve },
- './features/marketplace': {
- hasKnownDefaultInstallWork: async () => true,
- ensureDefaultInstalls: async () => { events.push('defaults'); return {}; },
- },
- './features/marketplace_reconcile': {
- setDefaultInstallSeedStatus: status,
- checkServerUpdatesForInstalls: async () => { events.push('catalog'); },
- reconcileInstalls: async () => { events.push('download'); return {}; },
- },
+ './features/marketplace': { hasKnownDefaultInstallWork: async () => true, ensureDefaultInstalls: defaults },
+ './features/marketplace_reconcile': { setDefaultInstallSeedStatus: status, checkServerUpdatesForInstalls: check, reconcileInstalls: download },
+ './features/skills': { repairLegacySkillEnabledIdsForActiveUser: repair },
};
const context = {
- exports: {} as { run: (reason: string) => Promise<void> },
+ exports: {} as { run: (reason: string, signal?: AbortSignal) => Promise<void>; retry: (key: string, uid: string, error: string) => void; registerStartup: () => void; publishBuiltin: (result: Record<string, number>) => void },
require: (name: string) => {
- if (!(name in modules)) throw new Error('Unexpected startup dependency');
+ if (!(name in modules)) throw new Error(`Unexpected startup dependency: ${name}`);
return modules[name];
},
+ setTimeout, clearTimeout, Date,
+ ipc: { broadcastToRenderer: broadcast },
users: { getActiveUserId: () => 'fixture-user' },
marketplaceBootContextStillActive: () => active,
marketplaceBootLog: { info: vi.fn(), warn },
logErrorSummary: () => ({ name: 'Error' }),
- marketplaceReconcileInFlight: null,
- marketplaceReconcileInFlightKey: '',
subscribeMarketplaceReconcileStatus: vi.fn(),
- seedBuiltinMarketplaceForCurrentUser: async () => { events.push('seed'); },
- clearMarketplaceDefaultsRetry: vi.fn(),
- scheduleMarketplaceDefaultsRetry: vi.fn(),
+ seedBuiltinMarketplaceForCurrentUser: seed,
+ scheduleBootBackground: schedule,
+ registerDeferred: boot.registerDeferred,
+ createMarketplaceCatalogReader,
+ MARKETPLACE_DEFAULTS_RETRY_DELAYS_MS: [retryDelayMs, retryDelayMs, retryDelayMs],
MARKETPLACE_DEFAULTS_REFRESH_INTERVAL_MS: 60_000,
MARKETPLACE_SERVER_CHECK_INTERVAL_MS: 60_000,
};
vm.runInNewContext(compiled, context);
- return { run: context.exports.run, events, resolve, warn, status, deactivate: () => { active = false; } };
+ return { ...context.exports, events, readers, seed, resolve, defaults, check, download, repair, schedule, controller, warn, status, broadcast, deactivate: () => { active = false; } };
}
+async function settle(work: Promise<void>): Promise<void> { await vi.runAllTimersAsync(); await work; }
+beforeEach(async () => {
+ vi.useFakeTimers();
+ boot._resetForTests();
+ wire.bootWarn.mockClear();
+ wire.postJson.mockReset().mockResolvedValue({ list: [{ id: 'installed-agent', version: '1' }] });
+ await vi.advanceTimersByTimeAsync(2_000);
+});
+afterEach(() => { boot._resetForTests(); vi.useRealTimers(); expect(wire.bootWarn).not.toHaveBeenCalled(); });
describe('open-source startup marketplace resolution', () => {
- it('resolves seeded local installs before checking versions and downloading updates', async () => {
+ it('resolves seeded installs before versions, downloads and local enabled-state repair', async () => {
const h = harness();
- await h.run('startup');
- expect(h.events).toEqual(['seed', 'resolve', 'defaults', 'catalog', 'download']);
+ await settle(h.run('startup'));
+ expect(h.events).toEqual(['seed', 'resolve', 'defaults', 'catalog', 'download', 'repair']);
expect(h.resolve).toHaveBeenCalledExactlyOnceWith('fixture-user', expect.objectContaining({ shouldContinue: expect.any(Function) }));
+ expect(h.status.mock.calls.map(call => call[0])).toEqual([true, false]);
expect(h.warn).not.toHaveBeenCalled();
+ expect(wire.bootWarn).not.toHaveBeenCalled();
});
-
- it('allows reconcile to recover unresolved URLs if the startup resolution is unavailable', async () => {
+ it('allows reconcile to recover unresolved URLs when lookup fails', async () => {
const h = harness();
h.resolve.mockRejectedValueOnce(new Error('Fixture lookup failure'));
- await h.run('startup');
- expect(h.events).toEqual(['seed', 'defaults', 'catalog', 'download']);
+ await settle(h.run('startup'));
+ expect(h.events).toEqual(['seed', 'defaults', 'catalog', 'download', 'repair']);
expect(h.warn).toHaveBeenCalledExactlyOnceWith('builtin marketplace resolve failed', { error: { name: 'Error' } });
- h.warn.mockClear();
- h.events.length = 0;
- await h.run('marketplace-defaults-retry');
- expect(h.events).toEqual(['seed', 'resolve', 'defaults', 'catalog', 'download']);
+ h.warn.mockClear(); h.events.length = 0;
+ await settle(h.run('marketplace-defaults-retry'));
+ expect(h.events).toEqual(['seed', 'resolve', 'defaults', 'catalog', 'download', 'repair']);
expect(h.warn).not.toHaveBeenCalled();
});
-
- it('stops further startup work and clears progress after an account change during resolution', async () => {
+ it('clears progress after the active local user changes during resolution', async () => {
const h = harness();
h.resolve.mockImplementationOnce(async () => { h.events.push('resolve'); h.deactivate(); });
- await h.run('startup');
+ await settle(h.run('startup'));
+ expect(h.events).toEqual(['seed', 'resolve']);
+ expect(h.status.mock.calls.map(call => call[0])).toEqual([true, false]);
+ expect(h.warn).not.toHaveBeenCalled();
+ });
+ it('shares one real catalog snapshot per pass and refreshes it on the next pass', async () => {
+ const h = harness(true);
+ await settle(h.run('startup'));
+ expect(wire.postJson).toHaveBeenCalledTimes(1);
+ expect(h.readers[0]).toBe(h.readers[1]);
+ await settle(h.run('manual-refresh'));
+ expect(wire.postJson).toHaveBeenCalledTimes(2);
+ expect(h.readers[2]).toBe(h.readers[3]);
+ expect(h.readers[0]).not.toBe(h.readers[2]);
+ });
+ it('does not start a queued retry after boot shutdown', async () => {
+ const h = harness();
+ h.retry('fixture-user', 'fixture-user', 'Fixture unavailable');
+ boot.stopBootWork();
+ await vi.advanceTimersByTimeAsync(4_000);
+ expect(h.events).toEqual([]);
+ expect(h.warn).not.toHaveBeenCalled();
+ });
+ it.each(['seed', 'resolve', 'defaults', 'catalog'] as const)('stops after cancellation during %s without retry or later writes', async phase => {
+ const h = harness();
+ const abort = async () => { h.events.push(phase); h.controller.abort(); };
+ if (phase === 'seed') h.seed.mockImplementationOnce(abort);
+ if (phase === 'resolve') h.resolve.mockImplementationOnce(abort);
+ if (phase === 'defaults') h.defaults.mockImplementationOnce(async () => { await abort(); return { failed: true, error: 'Fixture cancelled' }; });
+ if (phase === 'catalog') h.check.mockImplementationOnce(abort);
+ await settle(h.run('startup', h.controller.signal));
+ const ordered = ['seed', 'resolve', 'defaults', 'catalog'];
+ expect(h.events).toEqual(ordered.slice(0, ordered.indexOf(phase) + 1));
+ expect(h.download).not.toHaveBeenCalled();
+ expect(h.repair).not.toHaveBeenCalled();
+ expect(h.warn).not.toHaveBeenCalled();
+ });
+ it('passes the actual deferred registration lifetime through to active lookup', async () => {
+ const h = harness();
+ h.resolve.mockImplementationOnce(async () => { h.events.push('resolve'); boot.stopBootWork(); });
+ h.registerStartup();
+ await boot.runBootPhases(0);
+ await vi.runAllTimersAsync();
+ expect(h.events).toEqual(['seed', 'resolve']);
+ expect(h.status.mock.calls.map(call => call[0])).toEqual([true, false]);
+ });
+ it('drains active lookup before settling cancellation and releases disk during network wait', async () => {
+ const h = harness();
+ let release!: () => void;
+ const held = new Promise<void>(resolve => { release = resolve; });
+ h.resolve.mockImplementationOnce(async () => { h.events.push('resolve'); await held; });
+ let ended = false;
+ const work = h.run('startup', h.controller.signal).then(() => { ended = true; });
+ try {
+ await vi.advanceTimersByTimeAsync(10);
+ expect(h.events).toEqual(['seed', 'resolve']);
+ let diskFinished = false;
+ const disk = boot.scheduleBootBackground('fixture-local-work', () => { diskFinished = true; }, 0, { resourceClass: 'disk' });
+ await vi.advanceTimersByTimeAsync(10);
+ expect(diskFinished).toBe(true);
+ await disk.promise;
+ expect(h.schedule.mock.calls.map(call => call[3]?.resourceClass)).toEqual(['disk', 'network']);
+ h.controller.abort();
+ await vi.advanceTimersByTimeAsync(10);
+ expect(ended).toBe(false);
+ } finally { release(); await settle(work); }
expect(h.events).toEqual(['seed', 'resolve']);
+ expect(h.warn).not.toHaveBeenCalled();
+ });
+ it('drains an overlapping pass before executing a fresh defaults retry', async () => {
+ const h = harness(false, 30);
+ let release!: () => void;
+ const held = new Promise<void>(resolve => { release = resolve; });
+ h.defaults.mockResolvedValueOnce({ failed: true, error: 'Fixture unavailable' });
+ h.check.mockImplementationOnce(async () => { h.events.push('catalog'); await held; });
+ const work = h.run('startup');
+ try {
+ await vi.advanceTimersByTimeAsync(50);
+ expect(h.defaults).toHaveBeenCalledTimes(1);
+ } finally { release(); await settle(work); }
+ expect(h.defaults).toHaveBeenCalledTimes(2);
+ expect(h.download).toHaveBeenCalledTimes(2);
+ expect(h.repair).toHaveBeenCalledTimes(2);
+ expect(h.warn).not.toHaveBeenCalled();
+ });
+ it('does not seed or open a catalog when its startup lifetime is already cancelled', async () => {
+ const h = harness();
+ h.controller.abort();
+ await settle(h.run('startup', h.controller.signal));
+ expect(h.events).toEqual([]);
+ expect(h.status).not.toHaveBeenCalled();
+ });
+ it('keeps local repair reachable after a catalog update failure', async () => {
+ const h = harness();
+ h.check.mockRejectedValueOnce(new Error('Fixture update failure'));
+ await settle(h.run('startup'));
+ expect(h.events).toEqual(['seed', 'resolve', 'defaults', 'download', 'repair']);
+ expect(h.warn).toHaveBeenCalledExactlyOnceWith('marketplace update check failed', { reason: 'startup', error: { name: 'Error' } });
+ expect(h.status.mock.calls.map(call => call[0])).toEqual([true, false]);
+ });
+ it('isolates local repair failures and retries the repair on a later pass', async () => {
+ const h = harness();
+ h.repair.mockRejectedValueOnce(new Error('Fixture read failure'));
+ await settle(h.run('startup'));
+ expect(h.warn).toHaveBeenCalledExactlyOnceWith('legacy skill enabled-state repair failed', { error: { name: 'Error' } });
expect(h.status.mock.calls.map(call => call[0])).toEqual([true, false]);
+ h.warn.mockClear();
+ await settle(h.run('manual-refresh'));
+ expect(h.repair).toHaveBeenCalledTimes(2);
expect(h.warn).not.toHaveBeenCalled();
});
+ it.each(['pruned_agents', 'pruned_skills', 'restored_agents', 'restored_skills', 'patched_agents', 'patched_skills'])('publishes local content changes for %s without a download', async field => {
+ const h = harness();
+ h.download.mockResolvedValueOnce({ [field]: 1 });
+ await settle(h.run('startup'));
+ expect(h.broadcast).toHaveBeenCalledExactlyOnceWith('marketplace:content-changed', {});
+ });
+ it('publishes one content change for a download and none for a no-op', async () => {
+ const h = harness();
+ await settle(h.run('startup'));
+ expect(h.broadcast).not.toHaveBeenCalled();
+ h.download.mockResolvedValueOnce({ pulled_agents: 1, patched_skills: 1 });
+ await settle(h.run('manual-refresh'));
+ expect(h.broadcast).toHaveBeenCalledExactlyOnceWith('marketplace:content-changed', {});
+ });
+ it('does not publish a late local result after cancellation', async () => {
+ const h = harness();
+ h.download.mockImplementationOnce(async () => { h.controller.abort(); return { pruned_agents: 1 }; });
+ await settle(h.run('startup', h.controller.signal));
+ expect(h.broadcast).not.toHaveBeenCalled();
+ });
+
+ it('publishes built-in changes separately from truthful seed progress', () => {
+ const h = harness();
+ h.publishBuiltin({ seeded_agents: 0, seeded_skills: 0, manifest_agents: 0, manifest_skills: 0 });
+ expect(h.broadcast).not.toHaveBeenCalled();
+ h.publishBuiltin({ seeded_agents: 1, seeded_skills: 0, manifest_agents: 0, manifest_skills: 0 });
+ expect(h.broadcast.mock.calls.filter(call => call[0] === 'marketplace:content-changed')).toEqual([['marketplace:content-changed', {}]]);
+ expect(h.broadcast.mock.calls.filter(call => call[0] === 'marketplace:reconcile-status').map(call => call[1])).toMatchObject([
+ { state: 'running', phase: 'default_seed', pulled: 0, total: 1 },
+ { state: 'done', phase: 'default_seed', pulled: 1, total: 1 },
+ ]);
+ });
+
});
diff --git a/test/main/telemetry-delivery-ownership.test.ts b/test/main/telemetry-delivery-ownership.test.ts
index f4b5714e..da39f433 100644
--- a/test/main/telemetry-delivery-ownership.test.ts
+++ b/test/main/telemetry-delivery-ownership.test.ts
@@ -103,6 +103,9 @@ describe('Main task-terminal UI delivery', () => {
const win = Object.assign(new EventEmitter(), { webContents });
const context = vm.createContext({
createRendererChannel,
+ // Preloading is scheduled independently of terminal delivery. Keep its
+ // callback deferred, as the real scheduler does until the app is ready.
+ scheduleChatApiPreload: () => {},
users: { hasActiveUser: () => true, getActiveUserId: () => 'owner-a' },
ipc: { broadcastToRenderer: (channel: string, payload: unknown) => { delivered.push({ channel, payload }); return true; } },
win,
@@ -111,8 +114,11 @@ describe('Main task-terminal UI delivery', () => {
const lifecycleEnd = mainSource.indexOf('\n // Block HTML', lifecycleStart);
expect(lifecycleStart).toBeGreaterThan(0);
expect(lifecycleEnd).toBeGreaterThan(lifecycleStart);
+ const preloadState = mainSource.match(/^let modelApiPreloadScheduled = false;$/m)?.[0];
+ expect(preloadState).toBeDefined();
const source = [
'let mainRendererReady = false;',
+ preloadState!,
mainSource.slice(mainSource.indexOf('const rendererChannels:'), mainSource.indexOf('function emitTaskTerminalToRenderer(')),
mainSource.slice(lifecycleStart, lifecycleEnd),
].join('\n');
diff --git a/test/renderer/agent-skill-resource-telemetry.test.ts b/test/renderer/agent-skill-resource-telemetry.test.ts
new file mode 100644
index 00000000..c801217d
--- /dev/null
+++ b/test/renderer/agent-skill-resource-telemetry.test.ts
@@ -0,0 +1,465 @@
+import { composerAccessorSource } from './composer-test-source';
+import { describe, expect, it, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as vm from 'node:vm';
+
+class FakeElement {
+ value = '';
+ textContent = '';
+ className = '';
+ focused = false;
+ hidden = false;
+ disabled = false;
+ dataset: Record<string, string> = {};
+ style: Record<string, string> = {};
+ removedClasses: string[] = [];
+ classList = {
+ add() {},
+ remove: (name: string) => { this.removedClasses.push(name); },
+ contains() { return false; },
+ };
+ contains(_target?: unknown) { return false; }
+ focus() { this.focused = true; }
+ addEventListener() {}
+ querySelector() { return null; }
+ querySelectorAll() { return []; }
+}
+
+function loadAgentRenderer() {
+ const elements = new Map<string, FakeElement>();
+ const element = (id: string) => {
+ if (!elements.has(id)) elements.set(id, new FakeElement());
+ return elements.get(id)!;
+ };
+ let now = 100;
+ const context: any = {
+ console,
+ clearTimeout,
+ setTimeout: (fn: () => void) => { fn(); return 1; },
+ performance: { now: () => { now += 25; return now; } },
+ createLogger: () => ({ warn() {}, error() {}, info() {} }),
+ document: {
+ getElementById: (id: string) => element(id),
+ querySelector: () => null,
+ querySelectorAll: () => [],
+ addEventListener() {},
+ createElement: () => new FakeElement(),
+ body: { appendChild() {} },
+ },
+ window: {
+ addEventListener() {},
+ innerWidth: 1024,
+ innerHeight: 768,
+ orkas: { invoke: async () => ({ ok: true }) },
+ },
+ t: (key: string, vars?: Record<string, string>) => {
+ if (key === 'chat.recipient_commander') return 'Commander';
+ if (key === 'agents.seed_workflow_model') return `${vars?.name || ''}:${vars?.description || ''}`;
+ return key;
+ },
+ getLang: () => 'en',
+ normalizeDisplayText: (value: unknown) => String(value || '').trim(),
+ normalizeCatalogSource: (source: string) => source || '',
+ isMarketplaceCatalogSource: (source: string) => source === 'marketplace',
+ escapeHtml: (value: unknown) => String(value || ''),
+ pickDesc: () => '',
+ pickLocalizedField: (item: any, field: string) => item?.[field] || '',
+ renderAvatarHtml: () => '',
+ isDevMode: () => false,
+ _toggleComposerRecipient: vi.fn(),
+ uiAlert: async () => {},
+ };
+ context.global = context;
+ context.globalThis = context;
+ vm.createContext(context);
+ vm.runInContext(composerAccessorSource, context);
+ const source = fs.readFileSync(path.join(__dirname, '../../src/renderer/modules/agents.js'), 'utf8');
+ vm.runInContext(source, context, { filename: 'agents.js' });
+ return { context, element };
+}
+
+
+function clickCancel(context: any) {
+ const html = fs.readFileSync(path.join(__dirname, '../../src/renderer/index.html'), 'utf8');
+ const modal = html.slice(html.indexOf('id="agent-modal"'), html.indexOf('<!-- Create/Edit Skill Modal -->'));
+ const handler = modal.match(/<button\b[^>]*onclick="([^"]+)"[^>]*data-i18n="common.cancel"/)?.[1];
+ expect(handler).toBeTruthy();
+ vm.runInContext(handler!, context);
+}
+
+describe('public agent creation and resource workflows', () => {
+ it('closes the default create modal and restores the originating composer on Cancel', () => {
+ const { context, element } = loadAgentRenderer();
+ context.openAgentModal({ returnFocusId: 'new-chat-input' });
+ clickCancel(context);
+ expect(element('agent-modal').removedClasses).toContain('open');
+ expect(element('new-chat-input').focused).toBe(true);
+ });
+
+ it('wires the shared modal Cancel button through the tab-aware handler', () => {
+ const html = fs.readFileSync(path.join(__dirname, '../../src/renderer/index.html'), 'utf8');
+ const modal = html.slice(
+ html.indexOf('id="agent-modal"'),
+ html.indexOf('<!-- Create/Edit Skill Modal -->'),
+ );
+
+ expect(modal).toContain('onclick="cancelAgentModal()"');
+ expect(modal).not.toContain('onclick="closeAgentModal()"');
+ });
+
+ it('restores focus to the new-chat composer when its external-agent modal is cancelled', () => {
+ const { context, element } = loadAgentRenderer();
+ context.document.querySelector = (selector: string) => (
+ selector === '#agent-modal-tabs .is-active'
+ ? { dataset: { agentTab: 'external' } }
+ : null
+ );
+
+ context.openAgentModal({
+ initialTab: 'external',
+ externalOnly: true,
+ returnFocusId: 'new-chat-input',
+ });
+ clickCancel(context);
+
+ expect(element('agent-modal').removedClasses).toContain('open');
+ expect(element('agent-modal-tabs').hidden).toBe(true);
+ expect(element('new-chat-input').focused).toBe(true);
+ });
+
+ it('restores the create and external tabs for the regular Agents-page flow', () => {
+ const { context, element } = loadAgentRenderer();
+ const styles = fs.readFileSync(path.join(__dirname, '../../src/renderer/style.css'), 'utf8');
+
+ context.openAgentModal({ initialTab: 'external', externalOnly: true });
+ expect(element('agent-modal-tabs').hidden).toBe(true);
+ expect(styles).toContain('.skill-modal-tabs[hidden] {\n display: none !important;\n}');
+ // Binding an existing CLI is not authoring a new agent, and the title has
+ // to follow the entry — including across a later language change, which
+ // re-reads the key, not the rendered string.
+ expect(element('agent-modal-title').dataset.i18n).toBe('agent_modal.title_connect');
+ expect(element('agent-modal-title').textContent).toBe('agent_modal.title_connect');
+
+ context.openAgentModal();
+ expect(element('agent-modal-tabs').hidden).toBe(false);
+ expect(element('agent-modal-title').dataset.i18n).toBe('agent_modal.title');
+ });
+
+ it('disables save only when the External flow has no available CLI', () => {
+ const { context, element } = loadAgentRenderer();
+
+ context.openAgentModal({ initialTab: 'external' });
+ expect(element('agent-save-btn').disabled).toBe(true);
+
+ context.setExternalAgentCreateAvailability(true);
+ expect(element('agent-save-btn').disabled).toBe(false);
+
+ context.setExternalAgentCreateAvailability(false);
+ expect(element('agent-save-btn').disabled).toBe(true);
+
+ context._switchAgentTab('create');
+ expect(element('agent-save-btn').disabled).toBe(false);
+ });
+
+ it('does not let deferred modal focus steal input from the summary field', () => {
+ const { context, element } = loadAgentRenderer();
+ const timers: Array<() => void> = [];
+ context.setTimeout = (fn: () => void) => {
+ timers.push(fn);
+ return timers.length;
+ };
+ const modal = element('agent-modal');
+ const summary = element('agent-desc-input');
+ modal.contains = (target: unknown) => target === summary;
+
+ context.openAgentModal();
+ context.document.activeElement = summary;
+ timers.forEach((fn) => fn());
+
+ expect(timers).toHaveLength(1);
+ expect(element('agent-name-input').focused).toBe(false);
+ });
+
+ it('keeps a successful Agent toggle authoritative when list refresh fails', async () => {
+ const { context } = loadAgentRenderer();
+ context.window.orkas.invoke = async () => ({ ok: true });
+ vm.runInContext(`
+ _agentsCache = [];
+ _selectedAgent = null;
+ loadAgents = async () => { throw new Error('refresh failed'); };
+ `, context);
+
+ await expect(context._flipAgentEnabled('agent-one', false)).resolves.toBe(true);
+
+ });
+
+ it('keeps a successful Agent delete authoritative when refresh fails', async () => {
+ const { context } = loadAgentRenderer();
+ context.uiConfirm = async () => true;
+ const request = vi.fn(async () => ({ json: async () => ({ ok: true }) }));
+ context.apiFetch = request;
+ vm.runInContext(`
+ _selectedAgent = { id: 'agent-one', name: 'Private Agent', source: 'custom' };
+ loadAgents = async () => { throw new Error('refresh failed'); };
+ loadConversations = async () => {};
+ `, context);
+
+ await context.deleteSelectedAgent();
+ expect(request).toHaveBeenCalledExactlyOnceWith('/api/agents/agent-one', { method: 'DELETE' });
+ expect(vm.runInContext('_selectedAgent', context)).toBeNull();
+
+ });
+
+ it('blocks external-agent creation when the selected CLI has a compatibility warning', async () => {
+ const { context, element } = loadAgentRenderer();
+ element('agent-ext-name-input').value = 'Codex';
+ element('agent-ext-desc-input').value = 'Runs local coding tasks';
+ context.getExternalCliValue = () => 'codex';
+ context.getExternalCliSelectionWarning = () => 'Version 0.139.0 is too old. Update the CLI.';
+ let createRequests = 0;
+ context.apiFetch = async () => {
+ createRequests += 1;
+ return { json: async () => ({ ok: true }) };
+ };
+
+ await context._saveExternalAgent({ msgEl: element('agent-form-msg') });
+
+ expect(element('agent-form-msg').textContent).toBe(
+ 'Version 0.139.0 is too old. Update the CLI.',
+ );
+ expect(element('agent-form-msg').className).toBe('form-msg err');
+ expect(createRequests).toBe(0);
+ });
+
+ it.each([
+ {
+ reason: 'no_cli',
+ cli: null,
+ name: '',
+ desc: '',
+ errorCode: 'no_cli',
+ },
+ {
+ reason: 'no_name',
+ cli: 'codex',
+ name: '',
+ desc: 'Runs local coding tasks',
+ errorCode: 'no_name',
+ },
+ {
+ reason: 'invalid name',
+ cli: 'codex',
+ name: 'Claude.Code',
+ desc: 'Runs local coding tasks',
+ errorCode: 'name_invalid',
+ },
+ {
+ reason: 'reserved name',
+ cli: 'codex',
+ name: 'Commander',
+ desc: 'Runs local coding tasks',
+ errorCode: 'name_reserved',
+ },
+ {
+ reason: 'no description',
+ cli: 'codex',
+ name: 'Codex',
+ desc: '',
+ errorCode: 'no_desc',
+ },
+ ])('rejects invalid external creation without a write: $reason', async ({ cli, name, desc, errorCode }) => {
+ const { context, element } = loadAgentRenderer();
+ element('agent-ext-name-input').value = name;
+ element('agent-ext-desc-input').value = desc;
+ context.getExternalCliValue = () => cli;
+ context.getExternalCliSelectionWarning = () => '';
+
+ const write = vi.fn();
+ context.apiFetch = write;
+ await context._saveExternalAgent({ msgEl: element('agent-form-msg') });
+
+ expect(write).not.toHaveBeenCalled();
+ expect(element('agent-form-msg').className).toBe('form-msg err');
+ expect(element('agent-form-msg').textContent).toBe(({ no_cli: 'agents.ext_cli_needed', no_name: 'agents.input_name_needed', name_invalid: 'agents.name_invalid', name_reserved: 'agents.name_reserved', no_desc: 'agents.input_desc_needed' } as Record<string, string>)[errorCode]);
+ });
+
+ it('removes whitespace from an external-agent name before saving', async () => {
+ const { context, element } = loadAgentRenderer();
+ const requests: any[] = [];
+ element('agent-ext-name-input').value = 'Claude Code';
+ element('agent-ext-desc-input').value = 'Runs local coding tasks';
+ context.getExternalCliValue = () => 'codex';
+ context.getExternalCliSelectionWarning = () => '';
+ context.apiFetch = async (_url: string, init: { body: string }) => {
+ const body = JSON.parse(init.body);
+ requests.push(body);
+ return {
+ json: async () => ({
+ ok: true,
+ agent: { agent_id: 'agent-created', name: body.name },
+ }),
+ };
+ };
+ context.closeAgentModal = () => {};
+ context.setView = () => {};
+ context.loadAgents = async () => {};
+ context._showAgentsDetailView = async () => {};
+
+ await context._saveExternalAgent({ msgEl: element('agent-form-msg') });
+
+ expect(element('agent-ext-name-input').value).toBe('ClaudeCode');
+ expect(requests[0].name).toBe('ClaudeCode');
+ });
+
+ it.each(['claude', 'codex', 'openclaw', 'opencode', 'hermes'].flatMap(cli => (
+ ['en', 'zh', 'ja', 'pt'].map(lang => ({ cli, lang }))
+ )))('fills and saves the real $cli default in a $lang UI after an empty description', async ({ cli, lang }) => {
+ const { context, element } = loadAgentRenderer();
+ for (const module of ['utils.js', 'local-agents.js']) {
+ vm.runInContext(fs.readFileSync(path.join(__dirname, '../../src/renderer/modules', module), 'utf8'), context);
+ }
+ const requests: any[] = [];
+ context.getLang = () => lang;
+ context.getExternalCliValue = () => cli;
+ context.getExternalCliSelectionWarning = () => '';
+ const seed = context.getCliDefaults(cli);
+ const expected = lang === 'zh' ? seed.description_zh : seed.description_en;
+ expect(expected.trim()).not.toBe('');
+ context._applyExternalCliDefaults(cli);
+ expect(element('agent-ext-name-input').value).toBe(seed.name);
+ expect(element('agent-ext-desc-input').value).toBe(expected);
+ element('agent-ext-desc-input').value = ' ';
+ context.apiFetch = async (_url: string, init: { body: string }) => {
+ const body = JSON.parse(init.body);
+ requests.push(body);
+ return {
+ json: async () => ({
+ ok: true,
+ agent: { agent_id: 'agent-created', name: body.name },
+ }),
+ };
+ };
+ context.closeAgentModal = () => {};
+ context.setView = () => {};
+ context.loadAgents = async () => {};
+ context._showAgentsDetailView = async () => {};
+
+ await context._saveExternalAgent({ msgEl: element('agent-form-msg') });
+
+ expect(element('agent-ext-desc-input').value).toBe(expected);
+ expect(requests).toHaveLength(1);
+ expect(requests[0]).toMatchObject({
+ name: seed.name, description: expected, runtime: { kind: 'cli', cli },
+ });
+ });
+
+ it.each(['en', 'zh'])('refreshes untouched CLI defaults but preserves user text in a %s UI', (lang) => {
+ const { context, element } = loadAgentRenderer();
+ for (const module of ['utils.js', 'local-agents.js']) {
+ vm.runInContext(fs.readFileSync(path.join(__dirname, '../../src/renderer/modules', module), 'utf8'), context);
+ }
+ context.getLang = () => lang;
+ context._applyExternalCliDefaults('claude');
+ element('agent-ext-name-input').value = 'MyAgent';
+ context._applyExternalCliDefaults('codex');
+ expect(element('agent-ext-name-input').value).toBe('MyAgent');
+ expect(element('agent-ext-desc-input').value).toBe(context.getCliDefaults('codex')[`description_${lang}`]);
+
+ const custom = lang === 'zh' ? '仅处理团队的发布任务。' : 'Only handle release work for my team.';
+ element('agent-ext-desc-input').value = custom;
+ context._applyExternalCliDefaults('hermes');
+ expect(element('agent-ext-desc-input').value).toBe(custom);
+ context._applyExternalCliDefaults(null);
+ expect(element('agent-ext-desc-input').value).toBe(custom);
+ expect(element('agent-ext-name-input').value).toBe('MyAgent');
+ });
+
+ it('adds a suffix when an untouched default external-agent name is taken', async () => {
+ const { context, element } = loadAgentRenderer();
+ const names: string[] = [];
+ element('agent-ext-name-input').value = 'Codex';
+ element('agent-ext-desc-input').value = 'Runs local coding tasks';
+ context.getExternalCliValue = () => 'codex';
+ context.getExternalCliSelectionWarning = () => '';
+ context.getCliDefaults = () => ({ name: 'Codex' });
+ context.apiFetch = async (_url: string, init: { body: string }) => {
+ const body = JSON.parse(init.body);
+ names.push(body.name);
+ return {
+ json: async () => names.length === 1
+ ? { ok: false, code: 'E_AGENT_NAME_TAKEN' }
+ : {
+ ok: true,
+ agent: { agent_id: 'agent-created', name: body.name },
+ },
+ };
+ };
+ context.closeAgentModal = () => {};
+ context.setView = () => {};
+ context.loadAgents = async () => {};
+ context._showAgentsDetailView = async () => {};
+
+ await context._saveExternalAgent({ msgEl: element('agent-form-msg') });
+
+ expect(names).toEqual(['Codex', 'Codex-2']);
+ expect(element('agent-ext-name-input').value).toBe('Codex-2');
+ });
+
+ it('does not silently rename a custom external-agent name when it is taken', async () => {
+ const { context, element } = loadAgentRenderer();
+ const names: string[] = [];
+ element('agent-ext-name-input').value = 'MyCodingAgent';
+ element('agent-ext-desc-input').value = 'Runs local coding tasks';
+ context.getExternalCliValue = () => 'codex';
+ context.getExternalCliSelectionWarning = () => '';
+ context.getCliDefaults = () => ({ name: 'Codex' });
+ context.apiFetch = async (_url: string, init: { body: string }) => {
+ const body = JSON.parse(init.body);
+ names.push(body.name);
+ return {
+ json: async () => ({
+ ok: false,
+ code: 'E_AGENT_NAME_TAKEN',
+ error: 'name taken',
+ }),
+ };
+ };
+
+ await context._saveExternalAgent({ msgEl: element('agent-form-msg') });
+
+ expect(names).toEqual(['MyCodingAgent']);
+ expect(element('agent-ext-name-input').value).toBe('MyCodingAgent');
+ expect(element('agent-form-msg').className).toBe('form-msg err');
+ expect(element('agent-form-msg').textContent).toBeTruthy();
+ });
+
+ it('keeps resource-card skill use selected in the new-chat composer', async () => {
+ const { context } = loadAgentRenderer();
+ const useSelections: Array<[string, Record<string, unknown> | null]> = [];
+ context.apiFetch = async () => ({
+ json: async () => ({ ok: true, agent: { agent_id: 'agent-card', name: 'Card Agent' } }),
+ });
+ context.setView = () => {};
+ context.setChatRecipient = () => {};
+ // Picker selections toggle the recipient marker in the composer text
+ // (conversation.js); the agent module only forwards the pick.
+ context._toggleComposerRecipient = (target: string, recipient: Record<string, unknown>) => context.setChatRecipient(target, recipient);
+ context.setChatUseSelection = (target: string, selection: Record<string, unknown> | null) => {
+ useSelections.push([target, selection]);
+ };
+ context.setChatSkill = () => {};
+
+ await context.useAgent('agent-card');
+ await context.useSkill('skill-card', 'Card Skill', 'global');
+ await context._triggerPickerItem('agent', 'agent-chat', 'Chat Agent', 'new-chat-recipient-chip', {});
+ await context._triggerPickerItem('skill', 'skill-chat', 'Chat Skill', 'new-chat-recipient-chip', {});
+ await context._triggerPickerItem('agent', 'agent-auto', 'Auto Agent', 'auto-recipient-chip', {});
+ await context._triggerPickerItem('skill', 'skill-auto', 'Auto Skill', 'auto-recipient-chip', {});
+
+ expect(useSelections).toContainEqual(['new-chat', {
+ kind: 'skill', id: 'skill-card', name: 'Card Skill', source: 'global',
+ }]);
+ });
+
+});
diff --git a/test/renderer/marketplace-install-error.test.ts b/test/renderer/marketplace-install-error.test.ts
index 50a8069e..dab33767 100644
--- a/test/renderer/marketplace-install-error.test.ts
+++ b/test/renderer/marketplace-install-error.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as vm from 'node:vm';
@@ -8,7 +8,7 @@ const marketplaceSource = fs.readFileSync(
'utf8',
);
-function loadMarketplaceRenderer(): any {
+function loadMarketplaceRenderer(loadMarketplace = true): any {
const userErrorCode = fs.readFileSync(
path.join(__dirname, '../../src/renderer/modules/user-error.js'),
'utf8',
@@ -65,10 +65,42 @@ function loadMarketplaceRenderer(): any {
vm.createContext(context);
vm.runInContext(semverCode, context, { filename: 'semver.js' });
vm.runInContext(userErrorCode, context, { filename: 'user-error.js' });
- vm.runInContext(marketplaceSource, context, { filename: 'marketplace.js' });
+ if (loadMarketplace) vm.runInContext(marketplaceSource, context, { filename: 'marketplace.js' });
return context;
}
+// Use the real isolated preload bridge: this notification must cross its
+// allow-list and IPC payload projection, not a renderer-only fake subscriber.
+function preloadPushBridge(invoke: (channel: string) => unknown) {
+ const listeners = new Map<string, (event: unknown, payload: unknown) => void>();
+ let api: any;
+ vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../../src/main/preload.js'), 'utf8'), {
+ require: () => ({
+ contextBridge: { exposeInMainWorld: (key: string, value: unknown) => { if (key === 'orkas') api = value; } },
+ ipcRenderer: {
+ sendSync: () => null,
+ invoke: async (_channel: string, envelope: { channel: string }) => invoke(envelope.channel),
+ on: (channel: string, handler: (event: unknown, payload: unknown) => void) => listeners.set(channel, handler),
+ removeListener: (channel: string) => listeners.delete(channel),
+ },
+ }),
+ process: { argv: [] }, window: { addEventListener: () => {} }, document: { readyState: 'complete' },
+ console, Date, Error, Promise, Object, setTimeout, clearTimeout,
+ }, { filename: 'preload.js' });
+ return { api, emit: (channel: string, payload: unknown) => listeners.get(channel)?.({}, payload), listeners };
+}
+
+function loadEagerAgents(ctx: any) {
+ const warnings = vi.fn();
+ const errors = vi.fn();
+ ctx.createLogger = () => ({ info: vi.fn(), debug: vi.fn(), warn: warnings, error: errors });
+ ctx.URLSearchParams = URLSearchParams;
+ ctx.pinyinSortKey = (value: string) => value;
+ vm.runInContext(fs.readFileSync(path.join(__dirname, '../../src/renderer/modules/agents.js'), 'utf8'), ctx, { filename: 'agents.js' });
+ vm.runInContext('_refreshCommanderAgentState = async () => {}; renderAgentsList = rows => { presentedAgents = rows; };', ctx);
+ return { warnings, errors };
+}
+
describe('marketplace install error display', () => {
it('keeps the origin tab selected and returns directly to New Task for nested marketplace entry', () => {
const ctx = loadMarketplaceRenderer();
@@ -303,4 +335,125 @@ describe('marketplace install error display', () => {
expect(uninstallState).toBeLessThan(uninstallRefresh);
});
+ it.each(['prune', 'restore', 'patch'] as const)('refreshes real installed-card state after local %s without pulled progress', async change => {
+ const ctx = loadMarketplaceRenderer();
+ const item = { id: 'content-writer', name: 'Writer', version: '1.0.2' };
+ let agents = change === 'restore' ? [] : [{ agent_id: item.id, source: 'marketplace', version: '1.0.1' }];
+ let skills: Array<{ id: string; source: string; version: string }> = [];
+ const bridge = preloadPushBridge(channel => {
+ if (channel === 'agents.list') return { agents };
+ if (channel === 'skills.list') return { skills };
+ return { state: 'idle', list: [] };
+ });
+ ctx.window.orkas = bridge.api;
+ loadEagerAgents(ctx);
+ vm.runInContext('_agentsCache = [];', ctx);
+ ctx._skillsCache = [];
+ ctx.refreshAgentsAfterMarketplaceReconcile = vi.fn(async () => {});
+ ctx.refreshSkillsAfterMarketplaceReconcile = vi.fn(async () => {});
+ ctx.escapeHtml = (value: unknown) => String(value ?? '');
+ ctx.pickDesc = () => '';
+ ctx.renderAvatarHtml = () => '';
+ ctx.document.getElementById = (id: string) => id === 'panel-marketplace'
+ ? { classList: { contains: (name: string) => name === 'active' } } : null;
+ ctx.testState = {
+ tab: 'agent', appVersion: '1.9.5', installing: new Set(),
+ installedAgentIds: new Set(), installedAgentMeta: new Map(),
+ installedSkillIds: new Set(), installedSkillMeta: new Map(),
+ };
+ vm.runInContext('_mpState = testState; _mpRender = () => {};', ctx);
+ await ctx._mpRefreshInstalledState();
+ const before = ctx._mpCardHtml(item, 'en');
+ expect(before).toContain(change === 'restore' ? '>Install</button>' : '>Update</button>');
+ await ctx._mpInitReconcileWatch();
+ agents = change === 'prune' ? [] : [{ agent_id: item.id, source: 'marketplace', version: '1.0.2' }];
+ skills = [{ id: 'restored-skill', source: 'marketplace', version: '2.0.0' }];
+ bridge.emit('marketplace:content-changed', {});
+ await vi.waitFor(() => {
+ expect(vm.runInContext('_mpState.installedAgentIds.has("content-writer")', ctx)).toBe(change !== 'prune');
+ expect(vm.runInContext('_mpState.installedSkillIds.has("restored-skill")', ctx)).toBe(true);
+ if (change !== 'prune') expect(vm.runInContext('_mpState.installedAgentMeta.get("content-writer").version', ctx)).toBe('1.0.2');
+ });
+ expect(ctx._mpCardHtml(item, 'en')).toContain(change === 'prune' ? '>Install</button>' : '>Installed</button>');
+ expect(ctx.refreshAgentsAfterMarketplaceReconcile).toHaveBeenCalledOnce();
+ expect(ctx.refreshSkillsAfterMarketplaceReconcile).toHaveBeenCalledOnce();
+ expect(vm.runInContext('_mpReconcileStatus.state', ctx)).toBe('idle');
+ });
+
+ it('refreshes a downloaded catalog once without using progress as another invalidation', async () => {
+ const ctx = loadMarketplaceRenderer();
+ const bridge = preloadPushBridge(() => ({ state: 'idle', list: [] }));
+ ctx.window.orkas = bridge.api;
+ loadEagerAgents(ctx);
+ vm.runInContext('_agentsCache = [];', ctx);
+ ctx._skillsCache = [];
+ ctx.refreshAgentsAfterMarketplaceReconcile = vi.fn(async () => {});
+ ctx.refreshSkillsAfterMarketplaceReconcile = vi.fn(async () => {});
+ await ctx._mpInitReconcileWatch();
+ bridge.emit('marketplace:reconcile-status', { state: 'running', pulled: 0 });
+ bridge.emit('marketplace:reconcile-status', { state: 'done', pulled: 1 });
+ bridge.emit('marketplace:content-changed', {});
+ await vi.waitFor(() => expect(ctx.refreshSkillsAfterMarketplaceReconcile).toHaveBeenCalledOnce());
+ expect(ctx.refreshAgentsAfterMarketplaceReconcile).toHaveBeenCalledOnce();
+ expect(vm.runInContext('_mpReconcileStatus.pulled', ctx)).toBe(1);
+ });
+
+ it.each(['prune', 'restore', 'patch'] as const)('updates the picker full cache on %s before any lazy marketplace load', async change => {
+ const ctx = loadMarketplaceRenderer(false);
+ let agents = change === 'restore' ? [] : [{ agent_id: 'writer', name: 'Writer', source: 'marketplace', version: '1.0.1' }];
+ const bridge = preloadPushBridge(() => ({}));
+ ctx.window.orkas = bridge.api;
+ const logs = loadEagerAgents(ctx);
+ ctx.loadRendererFeature = vi.fn();
+ ctx.apiFetch = vi.fn(async () => ({ json: async () => ({ ok: true, agents }) }));
+ await ctx._ensureAgentPickerTabData('agents', 0);
+ expect(vm.runInContext('_agentsCacheIsSummary', ctx)).toBe(false);
+ expect(vm.runInContext('_agentsCache.map(row => row.version)', ctx)).toEqual(change === 'restore' ? [] : ['1.0.1']);
+ expect(vm.runInContext('typeof _mpState', ctx)).toBe('undefined');
+ agents = change === 'prune' ? [] : [{ agent_id: 'writer', name: 'Writer', source: 'marketplace', version: '1.0.2' }];
+ bridge.emit('marketplace:content-changed', {});
+ await vi.waitFor(() => expect(vm.runInContext('_agentsCache.map(row => row.version)', ctx)).toEqual(change === 'prune' ? [] : ['1.0.2']));
+ expect(ctx.apiFetch).toHaveBeenCalledWith('/api/agents/list?force=1');
+ const reads = ctx.apiFetch.mock.calls.length;
+ await ctx.loadAgents(false);
+ expect(ctx.apiFetch).toHaveBeenCalledTimes(reads);
+ expect(ctx.presentedAgents.map((row: any) => row.version)).toEqual(change === 'prune' ? [] : ['1.0.2']);
+ expect(ctx.loadRendererFeature).not.toHaveBeenCalled();
+ expect(vm.runInContext('typeof _mpState', ctx)).toBe('undefined');
+ expect(logs.warnings).not.toHaveBeenCalled();
+ expect(logs.errors).not.toHaveBeenCalled();
+ });
+
+ it('does not populate unused catalogs or load lazy features for an early content event', async () => {
+ const ctx = loadMarketplaceRenderer(false);
+ const bridge = preloadPushBridge(() => ({}));
+ ctx.window.orkas = bridge.api;
+ const logs = loadEagerAgents(ctx);
+ ctx.loadRendererFeature = vi.fn();
+ ctx.apiFetch = vi.fn();
+ bridge.emit('marketplace:content-changed', {});
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(ctx.apiFetch).not.toHaveBeenCalled();
+ expect(ctx.loadRendererFeature).not.toHaveBeenCalled();
+ expect(vm.runInContext('_agentsCache', ctx)).toBeNull();
+ expect(vm.runInContext('typeof _mpState', ctx)).toBe('undefined');
+ expect(logs.warnings).not.toHaveBeenCalled();
+ });
+ it('diagnoses a failed Agent presentation refresh while keeping other loaded catalogs current', async () => {
+ const ctx = loadMarketplaceRenderer();
+ const bridge = preloadPushBridge(channel => channel === 'skills.list' ? { skills: [] } : { agents: [] });
+ ctx.window.orkas = bridge.api;
+ const logs = loadEagerAgents(ctx);
+ vm.runInContext('_agentsCache = [];', ctx);
+ ctx._skillsCache = [];
+ ctx.refreshAgentsAfterMarketplaceReconcile = vi.fn(async () => { throw new Error('CONFIDENTIAL'); });
+ ctx.refreshSkillsAfterMarketplaceReconcile = vi.fn(async () => {});
+ bridge.emit('marketplace:content-changed', {});
+ await vi.waitFor(() => expect(logs.warnings).toHaveBeenCalledExactlyOnceWith('marketplace content refresh failed', { resource_kind: 'agents' }));
+ expect(ctx.refreshSkillsAfterMarketplaceReconcile).toHaveBeenCalledOnce();
+ expect(JSON.stringify(logs.warnings.mock.calls)).not.toContain('CONFIDENTIAL');
+ expect(logs.errors).not.toHaveBeenCalled();
+ });
+
});