Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
fix: resolve builtin marketplace download URLs before updates
CloudTianTian47e2b715cecf
diff --git a/src/main/features/marketplace_reconcile.ts b/src/main/features/marketplace_reconcile.tsindex dfb9198e..a0bf88a5 100644--- a/src/main/features/marketplace_reconcile.ts+++ b/src/main/features/marketplace_reconcile.ts@@ -1093,6 +1093,17 @@ async function _patchInstallMeta(dir: string, patch: Partial<InstallMeta>): Promawait _writeInstallMeta(dir, next);}+/** Builtin installs have no remote URL until their first online resolution. */+function _hasDownloadUrl(value: unknown): value is string {+ if (typeof value !== 'string' || !value.trim()) return false;+ try {+ const url = new URL(value);+ return url.protocol === 'https:' || url.protocol === 'http:';+ } catch {+ return false;+ }+}+/** Fetch agent.json from the cloud URL recorded in the manifest, write to the per-machine* install target. Wipe-and-replace so a previous version doesn't leave stale fields. */async function _pullAgent(uid: string, row: AgentInstall, opts: MarketplaceReconcileOptions = {}): Promise<void> {@@ -1102,11 +1113,12 @@ async function _pullAgent(uid: string, row: AgentInstall, opts: MarketplaceReconasync function _pullAgentLocked(uid: string, row: AgentInstall, opts: MarketplaceReconcileOptions = {}): Promise<void> {let current = row;_assertContinue(opts);- let res = await fetchWithRetry(`marketplace:pull-agent:${row.id}`, current.agent_json_url, undefined, {- timeoutMs: MARKETPLACE_AGENT_JSON_DOWNLOAD_TIMEOUT_MS,- });- const needsDetailRefresh = !res.ok && res.status === 404;- if (needsDetailRefresh) {+ let res = _hasDownloadUrl(current.agent_json_url)+ ? await fetchWithRetry(`marketplace:pull-agent:${row.id}`, current.agent_json_url, undefined, {+ timeoutMs: MARKETPLACE_AGENT_JSON_DOWNLOAD_TIMEOUT_MS,+ })+ : null;+ if (!res || res.status === 404) {_assertContinue(opts);const fresh = await postJson<{agent_json: Record<string, unknown>;@@ -1122,7 +1134,9 @@ async function _pullAgentLocked(uid: string, row: AgentInstall, opts: Marketplacmin_app_version?: string;minAppVersion?: string;}>('/marketplace/agents/detail', { id: row.id });+ _assertContinue(opts);_assertRefreshedVersion('agent', row.id, row.version, fresh.version);+ if (!_hasDownloadUrl(fresh.agent_json_url)) throw new Error('agent detail missing a valid download URL');const minAppVersion = _normalizeMinAppVersion(fresh, fresh.agent_json);current = {...row,@@ -1209,11 +1223,12 @@ async function _pullSkill(uid: string, row: SkillInstall, opts: MarketplaceReconasync function _pullSkillLocked(uid: string, row: SkillInstall, opts: MarketplaceReconcileOptions = {}): Promise<void> {let current = row;_assertContinue(opts);- let downloaded = await downloadMarketplaceBundle(`marketplace:pull-skill:${row.id}`, current.bundle_url, {- assertContinue: () => _assertContinue(opts),- });- let res = downloaded.response;- if (!res.ok && res.status === 404) {+ let downloaded = _hasDownloadUrl(current.bundle_url)+ ? await downloadMarketplaceBundle(`marketplace:pull-skill:${row.id}`, current.bundle_url, {+ assertContinue: () => _assertContinue(opts),+ })+ : null;+ if (!downloaded || downloaded.response.status === 404) {_assertContinue(opts);const fresh = await postJson<{bundle_url: string;@@ -1227,7 +1242,9 @@ async function _pullSkillLocked(uid: string, row: SkillInstall, opts: Marketplacmin_app_version?: string;minAppVersion?: string;}>('/marketplace/skills/bundle', { id: row.id });+ _assertContinue(opts);_assertRefreshedVersion('skill', row.id, row.version, fresh.version);+ if (!_hasDownloadUrl(fresh.bundle_url)) throw new Error('skill detail missing a valid download URL');const minAppVersion = _normalizeMinAppVersion(fresh);current = {...row,@@ -1243,8 +1260,8 @@ async function _pullSkillLocked(uid: string, row: SkillInstall, opts: Marketplacdownloaded = await downloadMarketplaceBundle(`marketplace:pull-skill:${row.id}:fresh`, current.bundle_url, {assertContinue: () => _assertContinue(opts),});- res = downloaded.response;}+ const res = downloaded.response;if (!res.ok) throw new Error(`HTTP ${res.status}`);if (!downloaded.buffer) throw new Error('skill bundle response body missing');_assertContinue(opts);diff --git a/src/main/index.ts b/src/main/index.tsindex 4236ce4e..98e896f2 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -762,6 +762,15 @@ async function runMarketplaceInstallReconcile(reason: string): Promise<void> {return;}+ const builtinMarketplace = await import('./features/builtin_marketplace');+ await builtinMarketplace.resolveBuiltinMarketplaceInstalls(uid, { shouldContinue }).catch((err) => {+ marketplaceBootLog.warn('builtin marketplace resolve failed', { error: logErrorSummary(err) });+ });+ if (!shouldContinue()) {+ clearDefaultSeedStatus();+ return;+ }+const forceMarketplaceNetwork = reason === 'marketplace-defaults-retry';const seeded = await mp.ensureDefaultInstalls(uid, {shouldContinue,diff --git a/test/main/features/marketplace_reconcile_urls.test.ts b/test/main/features/marketplace_reconcile_urls.test.tsnew file mode 100644index 00000000..832cb7a1--- /dev/null+++ b/test/main/features/marketplace_reconcile_urls.test.ts@@ -0,0 +1,166 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import AdmZip from 'adm-zip';++const postJson = vi.hoisted(() => vi.fn());+const warnings = vi.hoisted(() => vi.fn());+vi.mock('../../../src/main/features/marketplace', async () => ({+ postJson,+ extractBundleSafely: (await import('../../../src/main/features/marketplace_bundle')).extractBundleSafely,+}));+vi.mock('../../../src/main/logger', () => ({+ createLogger: () => ({ info: vi.fn(), warn: warnings, error: (...args: unknown[]) => { throw new Error(`Unexpected error log: ${args[0]}`); } }),+}));+vi.mock('electron', () => ({ app: { getVersion: () => '1.7.0' } }));++let root: string;+let previousRoot: string | undefined;+beforeEach(() => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-marketplace-urls-'));+ previousRoot = process.env.ORKAS_WORKSPACE_ROOT;+ process.env.ORKAS_WORKSPACE_ROOT = root;+ vi.resetModules();+ postJson.mockReset();+ warnings.mockReset();+});+afterEach(() => {+ vi.unstubAllGlobals();+ if (previousRoot === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;+ else process.env.ORKAS_WORKSPACE_ROOT = previousRoot;+ fs.rmSync(root, { recursive: true, force: true });+});++describe.each(['agent', 'skill'] as const)('marketplace %s download address recovery', (kind) => {+ const plural = kind === 'agent' ? 'agents' : 'skills';+ const urlKey = kind === 'agent' ? 'agent_json_url' : 'bundle_url';+ const file = kind === 'agent' ? 'agent.json' : 'SKILL.md';+ const id = 'ab1234567890';+ const freshUrl = `https://marketplace.example.test/${id}/content`;+ const oldUrl = `https://marketplace.example.test/${id}/old`;+ const detailPath = `/marketplace/${plural}/${kind === 'agent' ? 'detail' : 'bundle'}`;++ async function setup(url: string, localVersion = '1.0.0') {+ const installs = await import('../../../src/main/features/marketplace_installs');+ const reconcile = await import('../../../src/main/features/marketplace_reconcile');+ const dir = path.join(root, 'u1', 'local', 'marketplace', plural, id);+ fs.mkdirSync(dir, { recursive: true });+ const localContent = kind === 'agent'+ ? JSON.stringify({ agent_id: id, name: 'Installed version' })+ : '---\nname: installed-version\n---\n';+ fs.writeFileSync(path.join(dir, file), localContent);+ fs.writeFileSync(path.join(dir, '_install.json'), JSON.stringify({+ version: localVersion, published_at: 100, installed_at: 100,+ seed_source: 'builtin', [urlKey]: url,+ }));+ const row = {+ id, version: '1.0.0', published_at: 100, installed_at: 100,+ seed_source: 'builtin', [urlKey]: url,+ };+ await installs.writeInstalls('u1', { version: 1, agents: [], skills: [], [plural]: [row] } as any);+ const content = kind === 'agent'+ ? Buffer.from(JSON.stringify({ agent_id: id, name: 'Updated version' }))+ : (() => {+ const zip = new AdmZip();+ zip.addFile('SKILL.md', Buffer.from('---\nname: updated-version\n---\n'));+ return zip.toBuffer();+ })();+ const fresh = { version: '2.0.0', published_at: 200, [urlKey]: freshUrl, create_uid: '0' };+ postJson.mockImplementation(async (endpoint: string) => {+ if (endpoint === `/marketplace/${plural}/list`) return { list: [{ id, version: '2.0.0', published_at: 200 }], total: 1 };+ if (endpoint === detailPath) return fresh;+ throw new Error('Unexpected marketplace endpoint');+ });+ const download = vi.fn(async (url: unknown) => {+ if (url === oldUrl) return new Response('not found', { status: 404 });+ if (url !== freshUrl) throw new TypeError('Invalid fixture download URL');+ return new Response(new Uint8Array(content));+ });+ vi.stubGlobal('fetch', download);+ await reconcile.checkServerUpdatesForInstalls('u1');+ postJson.mockClear();+ const beforeManifest = await installs.readInstalls('u1');+ const beforeMeta = fs.readFileSync(path.join(dir, '_install.json'), 'utf8');+ return { installs, reconcile, dir, localContent, beforeManifest, beforeMeta, fresh, download };+ }++ async function expectUpdated(ctx: Awaited<ReturnType<typeof setup>>) {+ expect(await ctx.reconcile.reconcileInstalls('u1')).toMatchObject({ [`pulled_${plural}`]: 1, failed: [] });+ const rows = (await ctx.installs.readInstalls('u1'))[plural];+ expect(rows[0]).toMatchObject({ version: '2.0.0', [urlKey]: freshUrl });+ expect(JSON.parse(fs.readFileSync(path.join(ctx.dir, '_install.json'), 'utf8'))).toMatchObject({ version: '2.0.0', [urlKey]: freshUrl });+ expect(fs.readFileSync(path.join(ctx.dir, file), 'utf8')).toContain(kind === 'agent' ? 'Updated version' : 'updated-version');+ }++ it.each(['', 'not-a-url', 'file:///fixture'])('upgrades a builtin with unresolved address %j through detail lookup', async (url) => {+ const ctx = await setup(url);+ await expectUpdated(ctx);+ expect(postJson).toHaveBeenCalledExactlyOnceWith(detailPath, { id });+ expect(ctx.download).toHaveBeenCalledTimes(1);+ expect(ctx.download.mock.calls[0][0]).toBe(freshUrl);+ expect(warnings).not.toHaveBeenCalled();+ });++ it('keeps a valid direct download free of additional detail requests', async () => {+ const ctx = await setup(freshUrl);+ await expectUpdated(ctx);+ expect(postJson).not.toHaveBeenCalled();+ expect(ctx.download).toHaveBeenCalledTimes(1);+ expect(warnings).not.toHaveBeenCalled();+ });++ it('still refreshes a stale 404 address once', async () => {+ const ctx = await setup(oldUrl);+ await expectUpdated(ctx);+ expect(postJson).toHaveBeenCalledExactlyOnceWith(detailPath, { id });+ expect(ctx.download.mock.calls.map(call => call[0])).toEqual([oldUrl, freshUrl]);+ expect(warnings).not.toHaveBeenCalled();+ });++ it.each(['detail failure', 'invalid address', 'older version', 'incompatible version', 'download failure', 'corrupt content'] as const)(+ 'preserves the old install on %s and completes a later retry', async (failure) => {+ const ctx = await setup('');+ if (failure === 'detail failure') postJson.mockRejectedValueOnce(new Error('Fixture detail unavailable'));+ if (failure === 'invalid address') postJson.mockResolvedValueOnce({ ...ctx.fresh, [urlKey]: '' });+ if (failure === 'older version') postJson.mockResolvedValueOnce({ ...ctx.fresh, version: '1.5.0' });+ if (failure === 'incompatible version') postJson.mockResolvedValueOnce({ ...ctx.fresh, min_app_version: '99.0.0' });+ if (failure === 'download failure') ctx.download.mockResolvedValueOnce(new Response('denied', { status: 403 }));+ if (failure === 'corrupt content') ctx.download.mockResolvedValueOnce(new Response('invalid content'));++ expect(await ctx.reconcile.reconcileInstalls('u1')).toMatchObject({ [`pulled_${plural}`]: 0, failed: [`${kind}:${id}`] });+ expect(await ctx.installs.readInstalls('u1')).toEqual(ctx.beforeManifest);+ expect(fs.readFileSync(path.join(ctx.dir, '_install.json'), 'utf8')).toBe(ctx.beforeMeta);+ expect(fs.readFileSync(path.join(ctx.dir, file), 'utf8')).toBe(ctx.localContent);+ expect(postJson).toHaveBeenCalledExactlyOnceWith(detailPath, { id });+ expect(warnings).toHaveBeenCalledTimes(1);+ expect(warnings.mock.calls[0][0]).toContain(`${kind} ${id} pull failed:`);+ if (['detail failure', 'invalid address', 'older version'].includes(failure)) expect(ctx.download).not.toHaveBeenCalled();+ warnings.mockClear();+ await expectUpdated(ctx);+ expect(warnings).not.toHaveBeenCalled();+ },+ );++ it('does not download or change installation state if the account changes during detail lookup', async () => {+ const ctx = await setup('');+ let active = true;+ postJson.mockImplementationOnce(async () => { active = false; return ctx.fresh; });+ expect(await ctx.reconcile.reconcileInstalls('u1', { shouldContinue: () => active })).toMatchObject({ [`pulled_${plural}`]: 0, failed: [] });+ expect(ctx.download).not.toHaveBeenCalled();+ expect(await ctx.installs.readInstalls('u1')).toEqual(ctx.beforeManifest);+ expect(fs.readFileSync(path.join(ctx.dir, '_install.json'), 'utf8')).toBe(ctx.beforeMeta);+ expect(fs.readFileSync(path.join(ctx.dir, file), 'utf8')).toBe(ctx.localContent);+ expect(warnings).not.toHaveBeenCalled();+ });++ it('keeps a newer packaged builtin without resolving or downloading older content', async () => {+ const ctx = await setup('', '3.0.0');+ expect(await ctx.reconcile.reconcileInstalls('u1')).toMatchObject({ [`pulled_${plural}`]: 0, failed: [] });+ expect(postJson).not.toHaveBeenCalled();+ expect(ctx.download).not.toHaveBeenCalled();+ expect(fs.readFileSync(path.join(ctx.dir, file), 'utf8')).toBe(ctx.localContent);+ expect(fs.readFileSync(path.join(ctx.dir, '_install.json'), 'utf8')).toBe(ctx.beforeMeta);+ expect(warnings).not.toHaveBeenCalled();+ });+});diff --git a/test/main/features/marketplace_startup_resolution.test.ts b/test/main/features/marketplace_startup_resolution.test.tsnew file mode 100644index 00000000..e1a067b0--- /dev/null+++ b/test/main/features/marketplace_startup_resolution.test.ts@@ -0,0 +1,92 @@+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';+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 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;`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },+}).outputText;++function harness() {+ const events: string[] = [];+ let active = true;+ const warn = vi.fn();+ const status = vi.fn();+ const resolve = vi.fn(async (_uid: string, opts: { shouldContinue: () => boolean }) => {+ expect(opts.shouldContinue()).toBe(true);+ events.push('resolve');+ });+ 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 {}; },+ },+ };+ const context = {+ exports: {} as { run: (reason: string) => Promise<void> },+ require: (name: string) => {+ if (!(name in modules)) throw new Error('Unexpected startup dependency');+ return modules[name];+ },+ 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(),+ 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; } };+}++describe('open-source startup marketplace resolution', () => {+ it('resolves seeded local installs before checking versions and downloading updates', async () => {+ const h = harness();+ await h.run('startup');+ expect(h.events).toEqual(['seed', 'resolve', 'defaults', 'catalog', 'download']);+ expect(h.resolve).toHaveBeenCalledExactlyOnceWith('fixture-user', expect.objectContaining({ shouldContinue: expect.any(Function) }));+ expect(h.warn).not.toHaveBeenCalled();+ });++ it('allows reconcile to recover unresolved URLs if the startup resolution is unavailable', async () => {+ const h = harness();+ h.resolve.mockRejectedValueOnce(new Error('Fixture lookup failure'));+ await h.run('startup');+ expect(h.events).toEqual(['seed', 'defaults', 'catalog', 'download']);+ 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']);+ expect(h.warn).not.toHaveBeenCalled();+ });++ it('stops further startup work and clears progress after an account change during resolution', async () => {+ const h = harness();+ h.resolve.mockImplementationOnce(async () => { h.events.push('resolve'); h.deactivate(); });+ await 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();+ });+});