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
Improve marketplace catalog loading and reconciliation
BlueSkyID66681c79d5567d9
diff --git a/src/main/data/oss-projects.json b/src/main/data/oss-projects.jsonindex 84cc48ba..766ffc70 100644--- a/src/main/data/oss-projects.json+++ b/src/main/data/oss-projects.json@@ -12,7 +12,16 @@"name_ko": "애니메이션 / 동영상","name_de": "Animation / Video","name_ru": "Анимация / Видео",- "name_it": "Animazione / Video"+ "name_it": "Animazione / Video",+ "name_zh-tw": "動畫/影片",+ "name_pt-pt": "Animação / Vídeo",+ "name_es-419": "Animación / Video",+ "name_vi": "Hoạt hình / Video",+ "name_tr": "Animasyon / Video",+ "name_hi": "ऐनिमेशन / वीडियो",+ "name_id": "Animasi / video",+ "name_th": "แอนิเมชัน / วิดีโอ",+ "name_ar": "الرسوم المتحركة / الفيديو"},{"code": "browser",@@ -26,7 +35,16 @@"name_ko": "브라우저","name_de": "Browser","name_ru": "Браузер",- "name_it": "Browser"+ "name_it": "Browser",+ "name_zh-tw": "瀏覽器",+ "name_pt-pt": "Navegador",+ "name_es-419": "Navegador",+ "name_vi": "Trình duyệt",+ "name_tr": "Tarayıcı",+ "name_hi": "ब्राउज़र",+ "name_id": "Peramban",+ "name_th": "เบราว์เซอร์",+ "name_ar": "المتصفح"},{"code": "office",@@ -40,7 +58,16 @@"name_ko": "사무","name_de": "Büro","name_ru": "Офис",- "name_it": "Ufficio"+ "name_it": "Ufficio",+ "name_zh-tw": "辦公",+ "name_pt-pt": "Escritório",+ "name_es-419": "Oficina",+ "name_vi": "Văn phòng",+ "name_tr": "Ofis",+ "name_hi": "कार्यालय",+ "name_id": "Perkantoran",+ "name_th": "งานสำนักงาน",+ "name_ar": "الأعمال المكتبية"},{"code": "slides",@@ -54,7 +81,16 @@"name_ko": "슬라이드 / PPT","name_de": "Folien / PPT","name_ru": "Слайды / PPT",- "name_it": "Diapositive / PPT"+ "name_it": "Diapositive / PPT",+ "name_zh-tw": "簡報/PPT",+ "name_pt-pt": "Diapositivos / PPT",+ "name_es-419": "Diapositivas / PPT",+ "name_vi": "Trang trình chiếu / PPT",+ "name_tr": "Slaytlar / PPT",+ "name_hi": "स्लाइड / PPT",+ "name_id": "Slide / PPT",+ "name_th": "สไลด์ / PPT",+ "name_ar": "الشرائح / PPT"}],"projects": [diff --git a/src/main/features/builtin_marketplace.ts b/src/main/features/builtin_marketplace.tsindex 9154fc80..11f731c1 100644--- a/src/main/features/builtin_marketplace.ts+++ b/src/main/features/builtin_marketplace.ts@@ -43,6 +43,7 @@ import {type SkillInstall,} from './marketplace_installs';import { postJson } from './marketplace';+import { createMarketplaceCatalogReader, type MarketplaceCatalogReader, type MarketplaceCatalogRow } from './marketplace_catalog';import { migrateComponentEnabledId } from './component_enabled';const log = createLogger('builtin-marketplace');@@ -840,17 +841,7 @@ export async function seedBuiltinMarketplaceForUser(return result;}-type CatalogRow = {- id?: string;- name?: string;- version?: string;- published_at?: number;- updated_at?: number;- create_uid?: string;- default_install?: boolean | number;- status?: string;- state?: string;-};+type CatalogRow = MarketplaceCatalogRow;function _isResolvedOfficialRow(row: CatalogRow | undefined, name?: string): row is Required<Pick<CatalogRow, 'id'>> & CatalogRow {if (!row || !row.id || !safeId(row.id)) return false;@@ -859,33 +850,23 @@ function _isResolvedOfficialRow(row: CatalogRow | undefined, name?: string): rowreturn String(row.name || '').trim() === name.trim();}-async function _findCatalogRow(kind: 'agents' | 'skills', id: string, name: string): Promise<CatalogRow | null> {- if (safeId(id)) {- const byId = await postJson<{ list?: CatalogRow[] }>(- `/marketplace/${kind}/list`,- { page: 1, size: 100, ids: [id] },- );- const hit = (byId.list || []).find((row) => _isResolvedOfficialRow(row));- if (hit) return hit;+type AgentCatalogLookup = { id: string; name: string };++async function _resolveAgentInstall(+ row: AgentInstall,+ lookup: AgentCatalogLookup,+ rows: Map<string, MarketplaceCatalogRow>,+ readNames: () => Promise<Map<string, MarketplaceCatalogRow>>,+): Promise<AgentInstall | null> {+ let catalog = rows.get(lookup.id);+ if (!_isResolvedOfficialRow(catalog) && lookup.name) {+ catalog = (await readNames()).get(lookup.name.trim());+ if (!_isResolvedOfficialRow(catalog, lookup.name)) return null;}- if (!name) return null;- const byName = await postJson<{ list?: CatalogRow[] }>(- `/marketplace/${kind}/list`,- { page: 1, size: 100, q: name },- );- return (byName.list || []).find((row) => _isResolvedOfficialRow(row, name)) || null;-}--async function _resolveAgentInstall(uid: string, row: AgentInstall): Promise<AgentInstall | null> {- const dir = userMarketplaceAgentDir(uid, row.id);- const localJson = _readJsonObject(path.join(dir, 'agent.json')) || {};- const localName = _agentNameFromJson(localJson, row.id);- const declaredId = typeof localJson.agent_id === 'string' && safeId(localJson.agent_id)- ? localJson.agent_id- : row.id;- const catalog = await _findCatalogRow('agents', declaredId, localName);- if (!catalog?.id) return null;- const detail = await postJson<{+ if (!_isResolvedOfficialRow(catalog)) return null;+ // Legacy Servers omit the address from list responses. Only that compatibility+ // path needs detail; an explicit empty address is invalid, not a retry signal.+ const detail = catalog.agent_json_url !== undefined ? catalog : await postJson<{version?: string;published_at?: number;updated_at?: number;@@ -895,7 +876,10 @@ async function _resolveAgentInstall(uid: string, row: AgentInstall): Promise<Agedefault_install?: boolean;status?: string;state?: string;+ min_app_version?: string;+ minAppVersion?: string;}>('/marketplace/agents/detail', { id: catalog.id });+ if (!detail.agent_json_url) return null;return {id: catalog.id,version: normalizeInstallVersion(detail.version || catalog.version),@@ -907,6 +891,7 @@ async function _resolveAgentInstall(uid: string, row: AgentInstall): Promise<Age)),agent_json_url: detail.agent_json_url || '',agent_skills_bundle_url: detail.agent_skills_bundle_url || '',+ ...(minAppVersionFrom(detail, catalog) ? { min_app_version: minAppVersionFrom(detail, catalog) } : {}),installed_at: row.installed_at || Date.now(),create_uid: detail.create_uid || catalog.create_uid || BUILTIN_CREATE_UID,default_install: detail.default_install === true || catalog.default_install === true || catalog.default_install === 1,@@ -916,10 +901,10 @@ async function _resolveAgentInstall(uid: string, row: AgentInstall): Promise<Age};}-async function _resolveSkillInstall(uid: string, row: SkillInstall): Promise<SkillInstall | null> {- const catalog = await _findCatalogRow('skills', row.id, '');- if (!catalog?.id) return null;- const detail = await postJson<{+async function _resolveSkillInstall(row: SkillInstall, rows: Map<string, MarketplaceCatalogRow>): Promise<SkillInstall | null> {+ const catalog = rows.get(row.id);+ if (!_isResolvedOfficialRow(catalog)) return null;+ const detail = catalog.bundle_url !== undefined ? catalog : await postJson<{bundle_url?: string;version?: string;published_at?: number;@@ -928,7 +913,10 @@ async function _resolveSkillInstall(uid: string, row: SkillInstall): Promise<Skidefault_install?: boolean;status?: string;state?: string;+ min_app_version?: string;+ minAppVersion?: string;}>('/marketplace/skills/bundle', { id: catalog.id });+ if (!detail.bundle_url) return null;return {id: catalog.id,version: normalizeInstallVersion(detail.version || catalog.version),@@ -939,6 +927,7 @@ async function _resolveSkillInstall(uid: string, row: SkillInstall): Promise<Skitypeof catalog.updated_at === 'number' ? { updated_at: catalog.updated_at } : {})),bundle_url: detail.bundle_url || '',+ ...(minAppVersionFrom(detail, catalog) ? { min_app_version: minAppVersionFrom(detail, catalog) } : {}),installed_at: row.installed_at || Date.now(),create_uid: detail.create_uid || catalog.create_uid || BUILTIN_CREATE_UID,default_install: detail.default_install === true || catalog.default_install === true || catalog.default_install === 1,@@ -974,7 +963,7 @@ async function _rewriteAgentSeedId(dir: string, id: string): Promise<void> {export async function resolveBuiltinMarketplaceInstalls(uid: string,- opts: BuiltinMarketplaceSeedOptions = {},+ opts: BuiltinMarketplaceSeedOptions & { catalogReader?: MarketplaceCatalogReader } = {},): Promise<BuiltinMarketplaceResolveResult> {const result: BuiltinMarketplaceResolveResult = {resolved_agents: 0,@@ -987,13 +976,38 @@ export async function resolveBuiltinMarketplaceInstalls(const manifest = await readInstalls(uid);let changed = false;+ const reader = opts.catalogReader || createMarketplaceCatalogReader(() => _canContinue(opts));+ let agentsCatalog: Promise<Map<string, MarketplaceCatalogRow>> | undefined;+ let skillsCatalog: Promise<Map<string, MarketplaceCatalogRow>> | undefined;+ let agentNamesCatalog: Promise<Map<string, MarketplaceCatalogRow>> | undefined;+ const agentLookups = new Map<string, AgentCatalogLookup>();const enabledIdMigrations: Array<{ kind: 'agent' | 'skill'; fromId: string; toId: string }> = [];const snapshotRemovals = { agents: {} as Record<string, number>, skills: {} as Record<string, number> };for (const row of [...manifest.agents]) {if (!_canContinue(opts)) return result;if (row.seed_source !== 'builtin' || row.agent_json_url) continue;try {- const resolved = await _resolveAgentInstall(uid, row);+ if (!agentsCatalog) {+ const ids = manifest.agents.map(agent => agent.id);+ for (const agent of manifest.agents) {+ if (agent.seed_source !== 'builtin' || agent.agent_json_url) continue;+ const local = _readJsonObject(path.join(userMarketplaceAgentDir(uid, agent.id), 'agent.json')) || {};+ const declared = local.agent_id;+ const id = typeof declared === 'string' && safeId(declared) ? declared : agent.id;+ agentLookups.set(agent.id, { id, name: _agentNameFromJson(local, agent.id) });+ ids.push(id);+ }+ agentsCatalog = reader.read('agents', ids);+ }+ const rows = await agentsCatalog;+ if (!_canContinue(opts)) return result;+ const resolved = await _resolveAgentInstall(row, agentLookups.get(row.id)!, rows, () => {+ agentNamesCatalog ||= reader.readAgentNames([...agentLookups.values()]+ .filter(lookup => !_isResolvedOfficialRow(rows.get(lookup.id)))+ .map(lookup => lookup.name));+ return agentNamesCatalog;+ });+ if (!_canContinue(opts)) return result;if (!resolved) continue;const migrated = await _migrateDir('agent', uid, row.id, resolved.id);if (migrated === 'blocked') {@@ -1010,6 +1024,7 @@ export async function resolveBuiltinMarketplaceInstalls(result.resolved_agents++;changed = true;} catch (err) {+ if (!_canContinue(opts)) return result;result.failed.push(`agent:${row.id}`);log.warn(`resolve builtin agent ${row.id} failed`, { error: logErrorSummary(err) });}@@ -1018,23 +1033,18 @@ export async function resolveBuiltinMarketplaceInstalls(if (!_canContinue(opts)) return result;if (row.seed_source !== 'builtin' || row.bundle_url) continue;try {- const resolved = await _resolveSkillInstall(uid, row);+ skillsCatalog ||= reader.read('skills', manifest.skills.map(skill => skill.id));+ const rows = await skillsCatalog;+ if (!_canContinue(opts)) return result;+ const resolved = await _resolveSkillInstall(row, rows);+ if (!_canContinue(opts)) return result;if (!resolved) continue;- const migrated = await _migrateDir('skill', uid, row.id, resolved.id);- if (migrated === 'blocked') {- result.failed.push(`skill:${row.id}`);- continue;- }- if (migrated === 'moved') result.migrated_skills++;- manifest.skills = manifest.skills.filter((s) => s.id !== row.id && s.id !== resolved.id);+ manifest.skills = manifest.skills.filter((s) => s.id !== row.id);manifest.skills.push(resolved);- if (row.id !== resolved.id) {- enabledIdMigrations.push({ kind: 'skill', fromId: row.id, toId: resolved.id });- snapshotRemovals.skills[row.id] = row.installed_at;- }result.resolved_skills++;changed = true;} catch (err) {+ if (!_canContinue(opts)) return result;result.failed.push(`skill:${row.id}`);log.warn(`resolve builtin skill ${row.id} failed`, { error: logErrorSummary(err) });}diff --git a/src/main/features/marketplace.ts b/src/main/features/marketplace.tsindex 7b94939f..a4304066 100644--- a/src/main/features/marketplace.ts+++ b/src/main/features/marketplace.ts@@ -69,6 +69,7 @@ import {import { getActiveUserId, isAnonymousLocalId } from './users';import { withCommonHeaders } from './api_common';import { getLanguage } from './config';+import type { Lang } from '../i18n';import { invalidateSkills as invalidateCoreAgentSkills } from '../model/core-agent/skill-registry';import {getSkillCacheDir, isCacheFresh, readAgentCache, touchCacheEntry,@@ -137,7 +138,7 @@ export async function postJson<T>(p: string, body: unknown): Promise<T> {}// ── types ─────────────────────────────────────────────────────────────────-export interface MarketplaceCategory {+export interface MarketplaceCategory extends Partial<Record<`name_${Lang}`, string>> {code: string;name_zh: string;name_en: string;diff --git a/src/main/features/marketplace_biz.ts b/src/main/features/marketplace_biz.tsindex baddbf5c..32157288 100644--- a/src/main/features/marketplace_biz.ts+++ b/src/main/features/marketplace_biz.ts@@ -57,13 +57,13 @@ export function normalizeMarketplaceCategoryCode(* on a cold start. Mirrors the server category registry so the UI behaves identically when* the network blip clears. Keep in sync with `Server/biz/marketplace/marketplace_mgr.py`. */const FALLBACK_CATEGORIES: readonly MarketplaceCategory[] = [- { code: 'education', name_zh: '教育', name_en: 'Education', name_ja: '教育', name_pt: 'Educação', sort_order: 10, name_es: "Educación", name_fr: "Éducation", name_ko: "교육", name_de: "Bildung", name_ru: "Образование", name_it: "Istruzione" },- { code: 'ecommerce', name_zh: '电商', name_en: 'E-commerce', name_ja: 'EC', name_pt: 'E-commerce', sort_order: 20, name_es: "Comercio electrónico", name_fr: "Commerce en ligne", name_ko: "전자상거래", name_de: "E-Commerce", name_ru: "Электронная торговля", name_it: "E-commerce" },- { code: 'rnd', name_zh: '产研', name_en: 'R&D', name_ja: '研究開発', name_pt: 'P&D', sort_order: 30, name_es: "I+D", name_fr: "R&D", name_ko: "연구 개발", name_de: "Forschung und Entwicklung", name_ru: "Исследования и разработка", name_it: "Ricerca e sviluppo" },- { code: 'creation', name_zh: '创作', name_en: 'Creation', name_ja: '創作', name_pt: 'Criação', sort_order: 40, name_es: "Creación", name_fr: "Création", name_ko: "창작", name_de: "Kreation", name_ru: "Творчество", name_it: "Creazione" },- { code: 'data', name_zh: '数据', name_en: 'Data', name_ja: 'データ', name_pt: 'Dados', sort_order: 50, name_es: "Datos", name_fr: "Données", name_ko: "데이터", name_de: "Daten", name_ru: "Данные", name_it: "Dati" },- { code: 'office', name_zh: '办公', name_en: 'Office', name_ja: 'オフィス', name_pt: 'Escritório', sort_order: 60, name_es: "Oficina", name_fr: "Bureautique", name_ko: "사무", name_de: "Büro", name_ru: "Офис", name_it: "Ufficio" },- { code: 'general', name_zh: '通用', name_en: 'General', name_ja: '汎用', name_pt: 'Geral', sort_order: 70, name_es: "General", name_fr: "Général", name_ko: "일반", name_de: "Allgemein", name_ru: "Общее", name_it: "Generale" },+ { code: 'education', name_zh: '教育', name_en: 'Education', name_ja: '教育', name_pt: 'Educação', sort_order: 10, name_es: "Educación", name_fr: "Éducation", name_ko: "교육", name_de: "Bildung", name_ru: "Образование", name_it: "Istruzione", "name_zh-tw": "教育", "name_pt-pt": "Educação", "name_es-419": "Educación", "name_vi": "Giáo dục", "name_tr": "Eğitim", "name_id": "Pendidikan", "name_hi": "शिक्षा", "name_th": "การศึกษา", "name_ar": "التعليم" },+ { code: 'ecommerce', name_zh: '电商', name_en: 'E-commerce', name_ja: 'EC', name_pt: 'E-commerce', sort_order: 20, name_es: "Comercio electrónico", name_fr: "Commerce en ligne", name_ko: "전자상거래", name_de: "E-Commerce", name_ru: "Электронная торговля", name_it: "E-commerce", "name_zh-tw": "電子商務", "name_pt-pt": "Comércio eletrónico", "name_es-419": "Comercio electrónico", "name_vi": "Thương mại điện tử", "name_tr": "E-ticaret", "name_id": "E-commerce", "name_hi": "ई-कॉमर्स", "name_th": "อีคอมเมิร์ซ", "name_ar": "التجارة الإلكترونية" },+ { code: 'rnd', name_zh: '产研', name_en: 'R&D', name_ja: '研究開発', name_pt: 'P&D', sort_order: 30, name_es: "I+D", name_fr: "R&D", name_ko: "연구 개발", name_de: "Forschung und Entwicklung", name_ru: "Исследования и разработка", name_it: "Ricerca e sviluppo", "name_zh-tw": "研發", "name_pt-pt": "Investigação e desenvolvimento", "name_es-419": "Investigación y desarrollo", "name_vi": "Nghiên cứu và phát triển", "name_tr": "Araştırma ve geliştirme", "name_id": "Penelitian dan pengembangan", "name_hi": "अनुसंधान और विकास", "name_th": "การวิจัยและพัฒนา", "name_ar": "البحث والتطوير" },+ { code: 'creation', name_zh: '创作', name_en: 'Creation', name_ja: '創作', name_pt: 'Criação', sort_order: 40, name_es: "Creación", name_fr: "Création", name_ko: "창작", name_de: "Kreation", name_ru: "Творчество", name_it: "Creazione", "name_zh-tw": "創作", "name_pt-pt": "Criação", "name_es-419": "Creación", "name_vi": "Sáng tạo", "name_tr": "İçerik üretimi", "name_id": "Kreasi", "name_hi": "रचनात्मक कार्य", "name_th": "การสร้างสรรค์", "name_ar": "الإبداع" },+ { code: 'data', name_zh: '数据', name_en: 'Data', name_ja: 'データ', name_pt: 'Dados', sort_order: 50, name_es: "Datos", name_fr: "Données", name_ko: "데이터", name_de: "Daten", name_ru: "Данные", name_it: "Dati", "name_zh-tw": "資料", "name_pt-pt": "Dados", "name_es-419": "Datos", "name_vi": "Dữ liệu", "name_tr": "Veri", "name_id": "Data", "name_hi": "डेटा", "name_th": "ข้อมูล", "name_ar": "البيانات" },+ { code: 'office', name_zh: '办公', name_en: 'Office', name_ja: 'オフィス', name_pt: 'Escritório', sort_order: 60, name_es: "Oficina", name_fr: "Bureautique", name_ko: "사무", name_de: "Büro", name_ru: "Офис", name_it: "Ufficio", "name_zh-tw": "辦公", "name_pt-pt": "Escritório", "name_es-419": "Oficina", "name_vi": "Văn phòng", "name_tr": "Ofis", "name_id": "Perkantoran", "name_hi": "कार्यालय", "name_th": "งานสำนักงาน", "name_ar": "الأعمال المكتبية" },+ { code: 'general', name_zh: '通用', name_en: 'General', name_ja: '汎用', name_pt: 'Geral', sort_order: 70, name_es: "General", name_fr: "Général", name_ko: "일반", name_de: "Allgemein", name_ru: "Общее", name_it: "Generale", "name_zh-tw": "通用", "name_pt-pt": "Geral", "name_es-419": "General", "name_vi": "Tổng quát", "name_tr": "Genel", "name_id": "Umum", "name_hi": "सामान्य", "name_th": "ทั่วไป", "name_ar": "عام" },];interface PersistedBiz {diff --git a/src/main/features/marketplace_catalog.ts b/src/main/features/marketplace_catalog.tsnew file mode 100644index 00000000..9d9f13aa--- /dev/null+++ b/src/main/features/marketplace_catalog.ts@@ -0,0 +1,102 @@+import { postJson } from './marketplace';++export type MarketplaceCatalogKind = 'agents' | 'skills';+export interface MarketplaceCatalogRow {+ id: string;+ name?: string;+ version?: string;+ published_at?: number;+ updated_at?: number;+ create_uid?: string;+ default_install?: boolean | number;+ status?: string;+ state?: string;+ min_app_version?: string;+ minAppVersion?: string;+ agent_json_url?: string;+ agent_skills_bundle_url?: string;+ bundle_url?: string;+}++const PAGE_SIZE = 100;+const MAX_PAGES = 20;+const MAX_IDS = 2000;++export interface MarketplaceCatalogReader {+ read(kind: MarketplaceCatalogKind, ids: string[]): Promise<Map<string, MarketplaceCatalogRow>>;+ readAgentNames(names: string[]): Promise<Map<string, MarketplaceCatalogRow>>;+}++/** One startup/update pass owns this reader. Never share it across accounts or+ * runs: both positive and missing results are snapshots, not durable caches. */+export function createMarketplaceCatalogReader(shouldContinue: () => boolean = () => true): MarketplaceCatalogReader {+ const cache = {+ agents: new Map<string, Promise<Map<string, MarketplaceCatalogRow>>>(),+ skills: new Map<string, Promise<Map<string, MarketplaceCatalogRow>>>(),+ };+ const assertActive = (): void => {+ if (!shouldContinue()) throw new Error('marketplace catalog cancelled');+ };+ async function fetchBatch(kind: MarketplaceCatalogKind, ids: string[], byName = false): Promise<Map<string, MarketplaceCatalogRow>> {+ const wanted = new Set(ids);+ const rows = new Map<string, MarketplaceCatalogRow>();+ // Old Servers ignore ids. Keep bounded pagination and exact client-side+ // filtering; unrelated catalog rows must never resolve an installation.+ for (let page = 1; page <= MAX_PAGES; page++) {+ assertActive();+ const response = await postJson<{ list: MarketplaceCatalogRow[]; total?: number }>(+ `/marketplace/${kind}/list`, { page, size: PAGE_SIZE, ...(byName ? { names: ids } : { ids }) },+ );+ assertActive();+ if (!Array.isArray(response?.list)) throw new Error('invalid marketplace catalog response');+ for (const row of response.list) {+ if (!row) continue;+ const key = byName ? String(row.name || '').trim() : row.id;+ if (byName && (!row.id || (row.create_uid || '0') !== '0')) continue;+ if (wanted.has(key) && !rows.has(key)) rows.set(key, row);+ }+ if (rows.size === wanted.size || response.list.length < PAGE_SIZE+ || (typeof response.total === 'number' && page * PAGE_SIZE >= response.total)) return rows;+ }+ // A truncated catalog cannot establish absence (callers may prune missing+ // installs). Leave the manifest untouched and retry on a later pass.+ throw new Error('marketplace catalog pagination limit reached');+ }+ return {+ async readAgentNames(names) {+ assertActive();+ const wanted = [...new Set(names.map(name => name.trim()).filter(Boolean))];+ const rows = new Map<string, MarketplaceCatalogRow>();+ for (let offset = 0; offset < wanted.length; offset += MAX_IDS) {+ for (const [name, row] of await fetchBatch('agents', wanted.slice(offset, offset + MAX_IDS), true)) rows.set(name, row);+ }+ const byId = Promise.resolve(new Map([...rows.values()].map(row => [row.id, row])));+ for (const row of rows.values()) cache.agents.set(row.id, byId);+ return rows;+ },+ async read(kind, ids) {+ assertActive();+ const wanted = [...new Set(ids.filter(Boolean))];+ const missing = wanted.filter(id => !cache[kind].has(id));+ for (let offset = 0; offset < missing.length; offset += MAX_IDS) {+ const batch = missing.slice(offset, offset + MAX_IDS);+ const pending = fetchBatch(kind, batch);+ for (const id of batch) {+ // Share the batch promise so concurrent consumers see failures too.+ cache[kind].set(id, pending);+ }+ try { await pending; } catch (error) {+ for (const id of batch) cache[kind].delete(id);+ throw error;+ }+ }+ const rows = new Map<string, MarketplaceCatalogRow>();+ for (const id of wanted) {+ const row = (await cache[kind].get(id))?.get(id);+ if (row) rows.set(id, row);+ }+ assertActive();+ return rows;+ },+ };+}diff --git a/src/main/features/marketplace_reconcile.ts b/src/main/features/marketplace_reconcile.tsindex 74833a2f..0c58ed6c 100644--- a/src/main/features/marketplace_reconcile.ts+++ b/src/main/features/marketplace_reconcile.ts@@ -17,6 +17,7 @@ import * as fsp from 'node:fs/promises';import * as path from 'node:path';import { app } from 'electron';+import { Semaphore } from 'async-mutex';import {userMarketplaceAgentDir, userMarketplaceAgentSkillsDir, userMarketplaceSkillDir,@@ -41,6 +42,7 @@ import { withMarketplaceInstallLock } from './marketplace_locks';import { agentPrivateSkillIdsFromBundle } from './marketplace_private_skills';import { downloadMarketplaceBundle, parseMarketplaceBundle } from './marketplace_bundle';import { createLogger } from '../logger';+import { createMarketplaceCatalogReader, type MarketplaceCatalogReader, type MarketplaceCatalogRow } from './marketplace_catalog';import { fetchWithRetry } from '../util/retry';import { replaceDirectoryAtomically, sweepStaleReplacementArtifacts } from '../util/atomic-directory-replace';import {@@ -53,6 +55,10 @@ import {const log = createLogger('marketplace_reconcile');const MARKETPLACE_AGENT_JSON_DOWNLOAD_TIMEOUT_MS = 60_000;+const MAX_RECONCILE_JOBS = 4;+// Shared across overlapping startup/sync passes. Dependencies run inside the+// parent's slot; acquiring another slot there would deadlock four waiting agents.+const reconcileSlots = new Semaphore(MAX_RECONCILE_JOBS);function _currentAppVersion(): string {try { return app.getVersion(); } catch { return ''; }@@ -115,6 +121,7 @@ export interface ReconcileResult {}export interface MarketplaceReconcileOptions {+ catalogReader?: MarketplaceCatalogReader;shouldContinue?: () => boolean;/** Skip network-heavy server catalog checks when a recent startup attempt already ran. */minIntervalMs?: number;@@ -122,6 +129,12 @@ export interface MarketplaceReconcileOptions {force?: boolean;}+interface ReconcilePassOptions extends MarketplaceReconcileOptions {+ catalogReader: MarketplaceCatalogReader;+ skillPulls: Map<string, Promise<boolean>>;+ dependencies: Map<string, Promise<void>>;+}+interface ReconcileLocalState {server_check_attempted_at?: number;server_check_succeeded_at?: number;@@ -232,9 +245,10 @@ export async function checkServerUpdatesForInstalls(try {const agentIds = manifest.agents.map((a) => a.id).filter(Boolean);const skillIds = manifest.skills.map((s) => s.id).filter(Boolean);+ const reader = opts.catalogReader || createMarketplaceCatalogReader(() => !opts.shouldContinue || opts.shouldContinue());[agentMap, skillMap] = await Promise.all([- agentIds.length ? _fetchServerCatalogMap('agents', agentIds) : Promise.resolve(new Map()),- skillIds.length ? _fetchServerCatalogMap('skills', skillIds) : Promise.resolve(new Map()),+ agentIds.length ? _fetchServerCatalogMap('agents', agentIds, reader) : Promise.resolve(new Map()),+ skillIds.length ? _fetchServerCatalogMap('skills', skillIds, reader) : Promise.resolve(new Map()),]);} catch (err) {log.warn(`server-check fetch failed (offline?): ${(err as Error).message}`);@@ -280,7 +294,7 @@ export async function checkServerUpdatesForInstalls(...((contentUpgrade ? server.updated_at : a.updated_at) !== undefined? { updated_at: contentUpgrade ? server.updated_at : a.updated_at }: {}),- agent_json_url: a.agent_json_url,+ agent_json_url: contentUpgrade && server.agent_json_url ? server.agent_json_url : a.agent_json_url,...(contentUpgrade && typeof server.agent_skills_bundle_url === 'string'? { agent_skills_bundle_url: server.agent_skills_bundle_url }: (typeof a.agent_skills_bundle_url === 'string' ? { agent_skills_bundle_url: a.agent_skills_bundle_url } : {})),@@ -333,7 +347,7 @@ export async function checkServerUpdatesForInstalls(...((contentUpgrade ? server.updated_at : s.updated_at) !== undefined? { updated_at: contentUpgrade ? server.updated_at : s.updated_at }: {}),- bundle_url: s.bundle_url,+ bundle_url: contentUpgrade && server.bundle_url ? server.bundle_url : s.bundle_url,create_uid: s.create_uid,...(typeof server.default_install === 'boolean' ? { default_install: server.default_install } : {}),...(typeof server.status === 'string' ? { status: server.status } : {}),@@ -403,55 +417,48 @@ interface _CatalogRow {updated_at?: number;default_install?: boolean;status?: string;+ agent_json_url?: string;agent_skills_bundle_url?: string;+ bundle_url?: string;min_app_version?: string;}-/** Paginate the public `/marketplace/{kind}/list` endpoint and collapse to (id → version + ts).- * The optional `ids` filter is supported by newer Servers. Older Servers ignore the extra body- * field, so we still page defensively; the client-side id set prevents unrelated rows from- * entering the update map. Page-size 100 × 20 pages = 2000 row cap. */-async function _fetchServerCatalogMap(kind: 'agents' | 'skills', ids: string[]): Promise<Map<string, _CatalogRow>> {+/** Normalize one pass's shared catalog for strict-version update checks. */+async function _fetchServerCatalogMap(kind: 'agents' | 'skills', ids: string[], reader: MarketplaceCatalogReader): Promise<Map<string, _CatalogRow>> {const out = new Map<string, _CatalogRow>();- const PAGE_SIZE = 100;- const wanted = new Set(ids.filter(Boolean));- for (let page = 1; page <= 20; page++) {- const r = await postJson<{ list: Array<{ id?: string; version?: string; published_at?: number; updated_at?: number; default_install?: boolean | number; status?: string; state?: string; agent_skills_bundle_url?: string; min_app_version?: string; minAppVersion?: string }>; total?: number }>(- `/marketplace/${kind}/list`, { page, size: PAGE_SIZE, ids: [...wanted] },- );- const list = r.list || [];- for (const row of list) {- if (typeof row.id !== 'string' || !wanted.has(row.id)) continue;- if (typeof row.version === 'string' && typeof row.published_at === 'number'- && _isInstallRowVersionValid(row, kind === 'agents' ? 'agent' : 'skill')) {- out.set(row.id, {- version: row.version,- published_at: row.published_at,- ...(typeof row.updated_at === 'number' ? { updated_at: row.updated_at } : {}),- ...(typeof row.default_install === 'boolean' || typeof row.default_install === 'number'- ? { default_install: row.default_install === true || row.default_install === 1 }- : {}),- ...(typeof row.status === 'string' ? { status: row.status } : (- typeof row.state === 'string' ? { status: row.state } : {}- )),- ...(kind === 'agents' && typeof row.agent_skills_bundle_url === 'string'- ? { agent_skills_bundle_url: row.agent_skills_bundle_url }- : {}),- ...(_normalizeMinAppVersion(row) ? { min_app_version: _normalizeMinAppVersion(row) } : {}),- });- }- }- if (out.size >= wanted.size || list.length < PAGE_SIZE) break;+ for (const row of (await reader.read(kind, ids)).values()) {+ if (typeof row.version !== 'string' || typeof row.published_at !== 'number'+ || !_isInstallRowVersionValid(row, kind === 'agents' ? 'agent' : 'skill')) continue;+ out.set(row.id, {+ version: row.version,+ published_at: row.published_at,+ ...(typeof row.updated_at === 'number' ? { updated_at: row.updated_at } : {}),+ ...(typeof row.default_install === 'boolean' || typeof row.default_install === 'number'+ ? { default_install: row.default_install === true || row.default_install === 1 } : {}),+ ...(typeof row.status === 'string' ? { status: row.status } : (+ typeof row.state === 'string' ? { status: row.state } : {}+ )),+ ...(typeof row.agent_json_url === 'string' ? { agent_json_url: row.agent_json_url } : {}),+ ...(typeof row.agent_skills_bundle_url === 'string' ? { agent_skills_bundle_url: row.agent_skills_bundle_url } : {}),+ ...(typeof row.bundle_url === 'string' ? { bundle_url: row.bundle_url } : {}),+ ...(_normalizeMinAppVersion(row) ? { min_app_version: _normalizeMinAppVersion(row) } : {}),+ });}return out;}-/** Read manifest + reconcile every entry in parallel. Returns counts for logging. Emits status+/** Read manifest + reconcile entries with bounded concurrency. Returns counts for logging. Emits status* updates through the subscribe channel so the renderer can show a "syncing" banner. */export async function reconcileInstalls(uid: string,- opts: MarketplaceReconcileOptions = {},+ options: MarketplaceReconcileOptions = {},): Promise<ReconcileResult> {+ const opts: ReconcilePassOptions = {+ ...options,+ catalogReader: options.catalogReader ?? createMarketplaceCatalogReader(options.shouldContinue),+ skillPulls: new Map(),+ dependencies: new Map(),+ };try { _assertContinue(opts); } catch {return _emptyReconcileResult();}@@ -539,32 +546,34 @@ export async function reconcileInstalls(});};- const agentTasks = agentsNeedingPull.map(async (row) => {- try {- _assertContinue(opts);- await _pullAgent(uid, row, opts);- pulled_agents++;- bumpProgress();- } catch (err) {- if (err instanceof ReconcileCancelled) return;- log.warn(`agent ${row.id} pull failed: ${(err as Error).message}`);- failed.push(`agent:${row.id}`);- }- });- const skillTasks = skillsNeedingPull.map(async (row) => {- try {- _assertContinue(opts);- await _pullSkill(uid, row, opts);- pulled_skills++;- bumpProgress();- } catch (err) {- if (err instanceof ReconcileCancelled) return;- log.warn(`skill ${row.id} pull failed: ${(err as Error).message}`);- failed.push(`skill:${row.id}`);+ const jobs = [+ ...agentsNeedingPull.map(row => ({ kind: 'agent' as const, row })),+ ...skillsNeedingPull.map(row => ({ kind: 'skill' as const, row })),+ ];+ let nextJob = 0;+ await Promise.all(Array.from({ length: Math.min(MAX_RECONCILE_JOBS, total) }, async () => {+ while (nextJob < jobs.length) {+ if (opts.shouldContinue && !opts.shouldContinue()) return;+ const job = jobs[nextJob++];+ await reconcileSlots.runExclusive(async () => {+ try {+ _assertContinue(opts);+ const pulled = job.kind === 'agent'+ ? await _pullAgent(uid, job.row, opts)+ : await _pullSkill(uid, job.row, opts);+ if (pulled) {+ if (job.kind === 'agent') pulled_agents++;+ else pulled_skills++;+ bumpProgress();+ }+ } catch (err) {+ if (err instanceof ReconcileCancelled || (opts.shouldContinue && !opts.shouldContinue())) return;+ log.warn(`${job.kind} ${job.row.id} pull failed: ${(err as Error).message}`);+ failed.push(`${job.kind}:${job.row.id}`);+ }+ });}- });-- await Promise.all([...agentTasks, ...skillTasks]);+ }));if (pulled_skills > 0) {try { clearSkillListCache(); } catch { /* list cache may not be loaded yet */ }@@ -705,7 +714,7 @@ async function _reconcileLocalOnlyInstalls(version: meta.version,published_at: meta.published_at,...(typeof meta.updated_at === 'number' ? { updated_at: meta.updated_at } : {}),- bundle_url: meta.bundle_url!,+ bundle_url: meta.bundle_url,installed_at: meta.installed_at!,create_uid: meta.create_uid || '',...(typeof meta.default_install === 'boolean' ? { default_install: meta.default_install } : {}),@@ -896,60 +905,94 @@ async function _ensureAgentSkillDependencies(uid: string,agentId: string,agentJson: Record<string, unknown>,- privateSkillIds: ReadonlySet<string> = new Set(),- opts: MarketplaceReconcileOptions = {},+ privateSkillIds: ReadonlySet<string>,+ opts: ReconcilePassOptions,): Promise<void> {const skillList = _skillListFromAgentJson(agentJson)- .filter((skillId) => !privateSkillIds.has(skillId));+ .filter((id) => !privateSkillIds.has(id) && (opts.dependencies.has(id) || !_skillDependencySatisfied(uid, id)));if (skillList.length === 0) return;const manifest = await readInstalls(uid);const manifestSkills = new Map(manifest.skills.map((s) => [s.id, s]));+ const missingMetadata = skillList.filter(id => !opts.dependencies.has(id) && !manifestSkills.get(id)?.bundle_url);+ // Resolve this agent's missing public dependencies together. Other agents share+ // both the catalog snapshot and each dependency's install (including failures).+ let metadata: Promise<Map<string, MarketplaceCatalogRow>> | undefined;+ const readMetadata = () => metadata ??= opts.catalogReader.read('skills', missingMetadata);for (const skillId of skillList) {_assertContinue(opts);- if (_skillDependencySatisfied(uid, skillId)) continue;- let row = manifestSkills.get(skillId) || null;- if (row && _marketplaceStatus(row) && _marketplaceStatus(row) !== 'approved') {- throw new Error(`dependency skill ${skillId} is not approved (${_marketplaceStatus(row)})`);+ let pending = opts.dependencies.get(skillId);+ if (!pending) {+ pending = _installDependencySkill(uid, skillId, readMetadata, opts);+ opts.dependencies.set(skillId, pending);+ }+ await pending;+ _assertContinue(opts);+ }+ log.info(`dependencies-ready for agent ${agentId}`);+}++async function _installDependencySkill(+ uid: string,+ skillId: string,+ readMetadata: () => Promise<Map<string, MarketplaceCatalogRow>>,+ opts: ReconcilePassOptions,+): Promise<void> {+ // Re-read under the same lock used by install/uninstall. Concurrent agents or+ // passes must not reseed a dependency with a different installation clock.+ const row = await withMarketplaceInstallLock(uid, 'skill', skillId, async () => {+ _assertContinue(opts);+ if (_skillDependencySatisfied(uid, skillId)) return null;+ const manifest = await readInstalls(uid);+ let current = manifest.skills.find(s => s.id === skillId);+ if (current && _marketplaceStatus(current) && _marketplaceStatus(current) !== 'approved') {+ throw new Error(`dependency skill ${skillId} is not approved (${_marketplaceStatus(current)})`);}- if (!row || !row.bundle_url) {- const meta = await postJson<{- bundle_url: string;- version: string;- published_at: number;- updated_at?: number;- create_uid?: string;- default_install?: boolean;- status?: string;- state?: string;- min_app_version?: string;- minAppVersion?: string;- }>('/marketplace/skills/bundle', { id: skillId });+ if (!current?.bundle_url) {+ let meta = (await readMetadata()).get(skillId);+ _assertContinue(opts);+ if (!meta) throw new Error(`dependency skill ${skillId} not found in marketplace`);+ // Older servers do not return addresses in catalog rows. Explicitly empty+ // addresses on current servers are not a reason for per-item lookups.+ if (meta.bundle_url === undefined) {+ meta = await postJson<MarketplaceCatalogRow>('/marketplace/skills/bundle', { id: skillId });+ _assertContinue(opts);+ }+ if (meta.id && meta.id !== skillId) throw new Error(`dependency skill ${skillId} identity mismatch`);_assertApprovedDependencySkill(skillId, meta);const minAppVersion = _normalizeMinAppVersion(meta);if (!_isAppCompatible(minAppVersion)) {throw new Error(`dependency skill ${skillId} requires Orkas >= ${minAppVersion} (current ${_currentAppVersion() || 'unknown'})`);}- row = {+ if (!parseSemver(meta.version)) throw new Error(`dependency skill ${skillId} has invalid marketplace version`);+ if (!_hasDownloadUrl(meta.bundle_url)) throw new Error(`dependency skill ${skillId} missing bundle_url`);+ if (current) {+ _assertRefreshedVersion('skill', skillId, current.version, meta.version);+ await _assertInstallCurrent(uid, 'skills', current);+ }+ current = {id: skillId,- version: meta.version || '1.0.0',+ version: meta.version!,published_at: meta.published_at || 0,...(typeof meta.updated_at === 'number' ? { updated_at: meta.updated_at } : {}),- bundle_url: meta.bundle_url || '',- installed_at: Date.now(),+ bundle_url: meta.bundle_url,+ installed_at: current?.installed_at || Date.now(),create_uid: meta.create_uid || '',...(typeof meta.default_install === 'boolean' ? { default_install: meta.default_install } : {}),...((meta.status || meta.state) ? { status: meta.status || meta.state } : {}),...(minAppVersion ? { min_app_version: minAppVersion } : {}),};- if (!await addSkillInstall(uid, row, { mode: 'seed' })) throw new ReconcileCancelled();- manifestSkills.set(skillId, row);+ if (!await addSkillInstall(uid, current, { mode: 'seed' })) throw new ReconcileCancelled();}- if (!row.bundle_url) throw new Error(`dependency skill ${skillId} missing bundle_url`);- await _pullSkill(uid, row, opts);- try { clearSkillListCache(); } catch { /* list cache may not be loaded yet */ }- try { invalidateCoreAgentSkills(); } catch { /* runner may not be loaded yet */ }- log.info(`dependency-installed skill ${skillId} for agent ${agentId}`);+ return current;+ });+ if (!row) return;+ if (!_isInstallRowVersionValid(row, 'skill') || !_isInstallRowAppCompatible(row, 'skill')) {+ throw new Error(`dependency skill ${skillId} is not compatible`);}+ // Release the metadata lock before joining the transfer's install lock.+ await _pullSkill(uid, row, opts);+ try { clearSkillListCache(); } catch { /* list cache may not be loaded yet */ }+ try { invalidateCoreAgentSkills(); } catch { /* runner may not be loaded yet */ }}function _resourceSyncBlocksServerPull(dir: string): boolean {@@ -1132,12 +1175,17 @@ async function _assertInstallCurrent(uid: string, kind: 'agents' | 'skills', row/** 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> {- return withMarketplaceInstallLock(uid, 'agent', row.id, async () => _pullAgentLocked(uid, row, opts));+async function _pullAgent(uid: string, row: AgentInstall, opts: ReconcilePassOptions): Promise<boolean> {+ return withMarketplaceInstallLock(uid, 'agent', row.id, async () => {+ _assertContinue(opts);+ await _assertInstallCurrent(uid, 'agents', row);+ if (!_agentNeedsPull(uid, row)) return false;+ await _pullAgentLocked(uid, row, opts);+ return true;+ });}-async function _pullAgentLocked(uid: string, row: AgentInstall, opts: MarketplaceReconcileOptions = {}): Promise<void> {- await _assertInstallCurrent(uid, 'agents', row);+async function _pullAgentLocked(uid: string, row: AgentInstall, opts: ReconcilePassOptions): Promise<void> {let current = row;_assertContinue(opts);let res = _hasDownloadUrl(current.agent_json_url)@@ -1244,12 +1292,25 @@ async function _pullAgentLocked(uid: string, row: AgentInstall, opts: Marketplac/** Fetch the skill bundle zip from cloud URL + extract. Same wipe-and-replace semantics.* `extractBundleSafely` enforces entry count + uncompressed size caps (zip-bomb defense)* — shared with the marketplace install path. */-async function _pullSkill(uid: string, row: SkillInstall, opts: MarketplaceReconcileOptions = {}): Promise<void> {- return withMarketplaceInstallLock(uid, 'skill', row.id, async () => _pullSkillLocked(uid, row, opts));+async function _pullSkill(uid: string, row: SkillInstall, opts: ReconcilePassOptions): Promise<boolean> {+ const key = JSON.stringify([row.id, row.version, row.installed_at]);+ let pending = opts.skillPulls.get(key);+ if (!pending) {+ pending = withMarketplaceInstallLock(uid, 'skill', row.id, async () => {+ _assertContinue(opts);+ await _assertInstallCurrent(uid, 'skills', row);+ if (!_skillNeedsPull(uid, row)) return false;+ await _pullSkillLocked(uid, row, opts);+ return true;+ });+ // Keep rejected results for this pass too: four dependent agents must not+ // each exhaust the same failing download's retry budget.+ opts.skillPulls.set(key, pending);+ }+ return pending;}-async function _pullSkillLocked(uid: string, row: SkillInstall, opts: MarketplaceReconcileOptions = {}): Promise<void> {- await _assertInstallCurrent(uid, 'skills', row);+async function _pullSkillLocked(uid: string, row: SkillInstall, opts: MarketplaceReconcileOptions): Promise<void> {let current = row;_assertContinue(opts);let downloaded = _hasDownloadUrl(current.bundle_url)diff --git a/src/main/features/skills.ts b/src/main/features/skills.tsindex e3546416..60ad07de 100644--- a/src/main/features/skills.ts+++ b/src/main/features/skills.ts@@ -133,8 +133,8 @@ export interface SkillListing {source: SkillSource;description_zh: string;description_en: string;- /** Marketplace category code. Empty string when the SKILL.md frontmatter doesn't set one —- * UI treats that as "uncategorized". */+ /** Marketplace category code. `_meta.json` is authoritative; legacy+ * frontmatter remains a fallback. Empty values render as "uncategorized". */category: string;/** **Computed at load time, not persisted.** Filled by `listSkills` from* `features/component_enabled.ts`. Defaults to true unless the user hasdiff --git a/test/e2e/startup_e2e_bundled_content.spec.ts b/test/e2e/startup_e2e_bundled_content.spec.tsindex d8dfedac..67be787f 100644--- a/test/e2e/startup_e2e_bundled_content.spec.ts+++ b/test/e2e/startup_e2e_bundled_content.spec.ts@@ -30,9 +30,13 @@ test('publishes bundled resources before boot readiness across first use and restry {await app.launch();await expect(app.page!.locator('html')).toHaveAttribute('data-orkas-boot-ready', 'true');- const first = assertPublished('local');+ const registryFile = path.join(app.workspaceRoot, 'open-users.json');+ const uid = JSON.parse(readFileSync(registryFile, 'utf8')).open_current_user_id;+ expect(uid).toBe('account-e2e');+ const first = assertPublished(uid);await app.relaunch();- expect(assertPublished('local')).toBe(first);+ expect(JSON.parse(readFileSync(registryFile, 'utf8')).open_current_user_id).toBe(uid);+ expect(assertPublished(uid)).toBe(first);expect(app.modelRequests).toHaveLength(0);} finally {await app.dispose();diff --git a/test/integration/quick-start-catalog.test.ts b/test/integration/quick-start-catalog.test.tsindex 9d9c9da7..1ed3493e 100644--- a/test/integration/quick-start-catalog.test.ts+++ b/test/integration/quick-start-catalog.test.ts@@ -3,13 +3,15 @@ import path from "node:path";import { describe, expect, it } from "vitest";+import { SUPPORTED_LANGS } from "../../src/main/i18n";+import { DEFAULT_QUICK_START_CONFIG } from "../../src/main/features/client_config";const COMMANDER_QUICK_START_CASES = [{ key: "data", localeKey: "new_chat.quick.tmpl.data", agentId: "78900d8758bc", intent: "调研适合普通用户的 AI 桌面应用,比较主要用途、系统支持、安装与上手难度、模型能力、隐私、本地运行和价格,并根据不同需求给出选择建议。" },- { key: "office", localeKey: "new_chat.quick.tmpl.office", agentId: "a19101ba698a", intent: "为一家电商店铺制作可编辑的销售月报,使用示例数据,包含核心指标和趋势、渠道图表。" },+ { key: "ecommerce", localeKey: "new_chat.quick.tmpl.ecommerce", agentId: "5a1d43c2f28a", intent: "分析宠物饮水机在美国 Amazon 市场是否值得卖,给出选品和验证建议。" },{ key: "ppt", localeKey: "new_chat.quick.tmpl.ppt", agentId: "7e91cb9ec9e9", intent: "为一款 AI 办公助手制作一份 8 页可编辑产品介绍 PPT,面向企业客户,包含痛点、产品方案、核心能力、使用场景、价值和下一步行动。" },- { key: "creation", localeKey: "new_chat.quick.tmpl.creation", agentId: "173d4235a431", intent: "写一篇面向职场人的 AI 办公助手社媒文章。" },+ { key: "office", localeKey: "new_chat.quick.tmpl.office", agentId: "a19101ba698a", intent: "为一家电商店铺制作可编辑的销售月报,使用示例数据,包含核心指标和趋势、渠道图表。" },{ key: "image", localeKey: "new_chat.quick.tmpl.image", agentId: "814b61b027f0", intent: "设计一张城市夏日咖啡节海报:8 月 16 日 14:00–20:00,城市中央广场,包含手冲体验、咖啡市集和限定特调。" },{ key: "video", localeKey: "new_chat.quick.tmpl.video", agentId: "79df9cc89f5f", intent: "制作一条面向普通用户、时长约 45 秒的 AI 发展趋势科普视频。" },{ key: "ui_design", localeKey: "new_chat.quick.tmpl.ui_design", agentId: "bcfcb4921dce", intent: "设计一套响应式的个人记账应用登录、注册和找回密码 UI,覆盖校验、加载及成功失败状态。" },@@ -24,7 +26,7 @@ function locale(language: string): Record<string, string> {}describe("Commander quick-start cross-layer catalog", () => {- it("keeps the runtime order and owner ids aligned with the model regression catalog", () => {+ it("keeps the runtime order and owner ids aligned with the bundled product catalog", () => {expect(DEFAULT_QUICK_START_CONFIG).toEqual(COMMANDER_QUICK_START_CASES.map((item) => ({id: item.key,@@ -33,7 +35,7 @@ describe("Commander quick-start cross-layer catalog", () => {);});- it("keeps the Chinese product prompt identical to the model regression intent", () => {+ it("keeps the Chinese product prompt identical to the bundled product intent", () => {const zh = locale("zh");for (const item of COMMANDER_QUICK_START_CASES) {expect(zh[item.localeKey], item.key).toBe(item.intent);@@ -41,7 +43,7 @@ describe("Commander quick-start cross-layer catalog", () => {});it("ships a non-empty localized product prompt for every supported UI language", () => {- for (const language of ["en", "zh", "ja", "pt", "es", "fr", "ko", "de", "ru", "it"]) {+ for (const language of SUPPORTED_LANGS) {const messages = locale(language);for (const item of COMMANDER_QUICK_START_CASES) {expect(messages[item.localeKey]?.trim().length, `${language}/${item.key}`).toBeGreaterThan(10);diff --git a/test/main/avatar-catalogs.test.ts b/test/main/avatar-catalogs.test.tsindex 9a355e11..afa8ad8b 100644--- a/test/main/avatar-catalogs.test.ts+++ b/test/main/avatar-catalogs.test.ts@@ -200,12 +200,17 @@ describe('avatar catalogs', () => {['resources/builtin/marketplace/agents/5f890bd72ac4/agent.json', 'VoiceStudio', 'music', 'violet'],['resources/builtin/marketplace/agents/814b61b027f0/agent.json', 'ImageStudio', 'image', 'violet'],['resources/builtin/marketplace/agents/a19101ba698a/agent.json', 'OfficeWorker', 'briefcase', 'sky'],- ['resources/builtin/marketplace/agents/7e91cb9ec9e9/agent.json', 'PptMaker', 'presentation', 'violet'],['resources/builtin/marketplace/agents/78900d8758bc/agent.json', 'DeepResearcher', 'search', 'sky'],['resources/builtin/marketplace/agents/bcfcb4921dce/agent.json', 'UIDesigner', 'palette', 'violet'],['resources/builtin/marketplace/agents/e064dca9e1bd/agent.json', 'SeoGeoAgent', 'target', 'gold'],['resources/builtin/marketplace/agents/173d4235a431/agent.json', 'ContentWriter', 'document', 'lavender'],['resources/builtin/marketplace/agents/a316881746f9/agent.json', 'ProductDeveloper', 'code', 'sage'],+ ['resources/builtin/marketplace/agents/5a1d43c2f28a/agent.json', 'ECommerceResearcher', 'shopping-bag', 'lime'],+ ['resources/builtin/marketplace/agents/7e91cb9ec9e9/agent.json', 'PptMaker', 'presentation', 'violet'],+ ['resources/builtin/marketplace/agents/a4930d19ba6c/agent.json', 'ECommerceReviewer', 'shopping-bag', 'sky'],+ ['resources/builtin/marketplace/agents/bc7e2a904d18/agent.json', 'ECommerceAnalyzer', 'shopping-bag', 'sky'],+ ['resources/builtin/marketplace/agents/e0f3a98c624b/agent.json', 'ECommerceOperator', 'shopping-bag', 'lime'],+ ['resources/builtin/marketplace/agents/fa3e1f2f9e07/agent.json', 'ECommerceWriter', 'shopping-bag', 'peach'],] as const;const officialAgentFiles = [diff --git a/test/main/features/builtin_marketplace.test.ts b/test/main/features/builtin_marketplace.test.tsindex 430866e9..b76284f3 100644--- a/test/main/features/builtin_marketplace.test.ts+++ b/test/main/features/builtin_marketplace.test.ts@@ -1063,6 +1063,97 @@ describe('builtin marketplace seed', () => {});});+ it('resolves a packaged catalog and checks updates with two metadata requests and no detail downloads', async () => {+ const ids = Array.from({ length: 22 }, (_, i) => (i + 1).toString(16).padStart(12, '0'));+ for (const id of ids) {+ writeBuiltinAgent(id, { name: `Agent ${id}`, workflow: 'Write.' });+ writeBuiltinSkill(id);+ }+ const seed = await import('../../../src/main/features/builtin_marketplace');+ const installs = await import('../../../src/main/features/marketplace_installs');+ const { createMarketplaceCatalogReader } = await import('../../../src/main/features/marketplace_catalog');+ const reconcile = await import('../../../src/main/features/marketplace_reconcile');+ await seed.seedBuiltinMarketplaceForUser('u1');+ postJsonMock.mockImplementation(async (endpoint: string, body: any) => {+ if (!['/marketplace/agents/list', '/marketplace/skills/list'].includes(endpoint)) throw new Error('Unexpected detail download');+ return { list: body.ids.map((id: string) => ({+ id, name: `Agent ${id}`, version: '2.0.0', published_at: 100, updated_at: 200,+ create_uid: '0', default_install: true, status: 'approved', min_app_version: '1.0.0',+ ...(endpoint.includes('/agents/')+ ? { agent_json_url: `https://cdn.test/${id}.json`, agent_skills_bundle_url: '' }+ : { bundle_url: `https://cdn.test/${id}.zip` }),+ })), total: body.ids.length };+ });+ const catalogReader = createMarketplaceCatalogReader();+ expect(await seed.resolveBuiltinMarketplaceInstalls('u1', { catalogReader })).toMatchObject({+ resolved_agents: 22, resolved_skills: 22, failed: [],+ });+ expect(await reconcile.checkServerUpdatesForInstalls('u1', { catalogReader })).toMatchObject({+ updated_agents: 0, updated_skills: 0,+ });+ expect(postJsonMock).toHaveBeenCalledTimes(2);+ expect(postJsonMock.mock.calls.map(([, body]) => body.ids.length)).toEqual([22, 22]);+ const manifest = await installs.readInstalls('u1');+ for (const kind of ['agents', 'skills'] as const) {+ expect(manifest[kind]).toHaveLength(22);+ for (const row of manifest[kind]) {+ expect(row).toMatchObject({ version: '2.0.0', min_app_version: '1.0.0', create_uid: '0' });+ expect(row.seed_source).toBeUndefined();+ }+ }+ expect(await seed.resolveBuiltinMarketplaceInstalls('u1')).toMatchObject({ resolved_agents: 0, resolved_skills: 0, failed: [] });+ expect(postJsonMock).toHaveBeenCalledTimes(2);+ });++ it('batches absent Agent ids and their legacy name lookup instead of querying once per Agent', async () => {+ const ids = Array.from({ length: 22 }, (_, i) => (i + 1).toString(16).padStart(12, '0'));+ for (const id of ids) writeBuiltinAgent(id, { name: `Agent ${id}`, workflow: 'Write.' });+ const seed = await import('../../../src/main/features/builtin_marketplace');+ const installs = await import('../../../src/main/features/marketplace_installs');+ await seed.seedBuiltinMarketplaceForUser('u1');+ const before = await installs.readInstalls('u1');+ postJsonMock.mockResolvedValue({ list: [], total: 0 });+ expect(await seed.resolveBuiltinMarketplaceInstalls('u1')).toMatchObject({ resolved_agents: 0, failed: [] });+ expect(postJsonMock).toHaveBeenCalledTimes(2);+ expect(postJsonMock.mock.calls[0][1].ids).toEqual(ids);+ expect(postJsonMock.mock.calls[1][1].names).toEqual(ids.map(id => `Agent ${id}`));+ expect(await installs.readInstalls('u1')).toEqual(before);+ });++ it('does not publish stale catalog results or start another batch after an account switch', async () => {+ writeBuiltinAgent(TEST_AGENT_ID, { name: 'Writer', workflow: 'Write.' });+ writeBuiltinSkill('pending-skill');+ const seed = await import('../../../src/main/features/builtin_marketplace');+ const installs = await import('../../../src/main/features/marketplace_installs');+ await seed.seedBuiltinMarketplaceForUser('u1');+ const before = await installs.readInstalls('u1');+ let active = true;+ postJsonMock.mockImplementation(async () => {+ active = false;+ return { list: [{ id: TEST_AGENT_ID, version: '2.0.0', agent_json_url: 'https://cdn.test/agent.json' }], total: 1 };+ });+ expect(await seed.resolveBuiltinMarketplaceInstalls('u1', { shouldContinue: () => active })).toMatchObject({+ resolved_agents: 0, resolved_skills: 0, failed: [],+ });+ expect(postJsonMock).toHaveBeenCalledTimes(1);+ expect(await installs.readInstalls('u1')).toEqual(before);+ });++ it('keeps seeds intact when catalog installation addresses are explicitly unavailable', async () => {+ writeBuiltinAgent(TEST_AGENT_ID, { name: 'Writer', workflow: 'Write.' });+ writeBuiltinSkill('unavailable');+ const seed = await import('../../../src/main/features/builtin_marketplace');+ const installs = await import('../../../src/main/features/marketplace_installs');+ await seed.seedBuiltinMarketplaceForUser('u1');+ const before = await installs.readInstalls('u1');+ postJsonMock.mockImplementation(async (_endpoint: string, body: any) => ({+ list: body.ids.map((id: string) => ({ id, create_uid: '0', agent_json_url: '', bundle_url: '' })), total: body.ids.length,+ }));+ expect(await seed.resolveBuiltinMarketplaceInstalls('u1')).toMatchObject({ resolved_agents: 0, resolved_skills: 0 });+ expect(await installs.readInstalls('u1')).toEqual(before);+ expect(postJsonMock).toHaveBeenCalledTimes(2);+ });+it('resolves builtin skill seed rows to official marketplace rows by exact id', async () => {writeBuiltinSkill('seo-crawl', 'SEO Crawl');const seed = await import('../../../src/main/features/builtin_marketplace');@@ -1197,7 +1288,7 @@ describe('builtin marketplace seed', () => {if (p === '/marketplace/agents/list' && Array.isArray(body?.ids)) {return { list: [], total: 0 };}- if (p === '/marketplace/agents/list' && body?.q === 'Writer') {+ if (p === '/marketplace/agents/list' && body?.names?.includes('Writer')) {return {list: [{id: 'abc123def456',@@ -1248,7 +1339,7 @@ describe('builtin marketplace seed', () => {expect(enabled.readEnabledMap('u1').agents).toEqual({ abc123def456: false });});- it('moves a disabled preference when a builtin skill resolves to a replacement id', async () => {+ it('rejects unrelated catalog ids without moving a builtin skill or its disabled preference', async () => {writeBuiltinSkill('legacy-skill', 'Legacy Skill');const seed = await import('../../../src/main/features/builtin_marketplace');const paths = await import('../../../src/main/paths');@@ -1273,32 +1364,22 @@ describe('builtin marketplace seed', () => {total: 1,};}- if (p === '/marketplace/skills/bundle' && body?.id === 'abc123def456') {- return {- bundle_url: 'https://cdn.test/abc123def456.zip',- version: '2.0.0',- published_at: 100,- updated_at: 200,- create_uid: '0',- default_install: true,- status: 'approved',- };- }throw new Error(`unexpected ${p}`);});await expect(seed.resolveBuiltinMarketplaceInstalls('u1')).resolves.toMatchObject({- resolved_skills: 1,- migrated_skills: 1,+ resolved_skills: 0,+ migrated_skills: 0,failed: [],});- expect(fs.existsSync(path.join(paths.userMarketplaceSkillDir('u1', 'legacy-skill'), 'SKILL.md'))).toBe(false);- expect(fs.existsSync(path.join(paths.userMarketplaceSkillDir('u1', 'abc123def456'), 'SKILL.md'))).toBe(true);+ expect(fs.existsSync(path.join(paths.userMarketplaceSkillDir('u1', 'legacy-skill'), 'SKILL.md'))).toBe(true);+ expect(fs.existsSync(path.join(paths.userMarketplaceSkillDir('u1', 'abc123def456'), 'SKILL.md'))).toBe(false);expect((await installs.readInstalls('u1')).skills).toEqual([- expect.objectContaining({ id: 'abc123def456' }),+ expect.objectContaining({ id: 'legacy-skill', seed_source: 'builtin', bundle_url: '' }),]);- expect(enabled.readEnabledMap('u1').skills).toEqual({ abc123def456: false });+ expect(postJsonMock).toHaveBeenCalledTimes(1);+ expect(enabled.readEnabledMap('u1').skills).toEqual({ 'legacy-skill': false });});it('does not delete a builtin agent seed when id migration destination already exists', async () => {@@ -1326,7 +1407,7 @@ describe('builtin marketplace seed', () => {if (p === '/marketplace/agents/list' && Array.isArray(body?.ids)) {return { list: [], total: 0 };}- if (p === '/marketplace/agents/list' && body?.q === 'Writer') {+ if (p === '/marketplace/agents/list' && body?.names?.includes('Writer')) {return {list: [{id: officialId,@@ -1374,68 +1455,6 @@ describe('builtin marketplace seed', () => {]);});- it('does not delete a builtin skill seed when id migration destination already exists', async () => {- writeBuiltinSkill('legacy-skill', 'Legacy Skill');- const seed = await import('../../../src/main/features/builtin_marketplace');- const paths = await import('../../../src/main/paths');- const installs = await import('../../../src/main/features/marketplace_installs');- const enabled = await import('../../../src/main/features/component_enabled');- await seed.seedBuiltinMarketplaceForUser('u1');- enabled.setSkillEnabled('u1', 'legacy-skill', false);-- const officialDir = paths.userMarketplaceSkillDir('u1', 'official-skill');- fs.mkdirSync(officialDir, { recursive: true });- fs.writeFileSync(path.join(officialDir, 'SKILL.md'), '---\nname: existing\ndescription: keep\n---\n\nkeep\n', 'utf8');-- postJsonMock.mockImplementation(async (p: string, body: any) => {- if (p === '/marketplace/skills/list' && Array.isArray(body?.ids)) {- return {- list: [{- id: 'official-skill',- name: 'Legacy Skill',- version: '2.0.0',- published_at: 100,- updated_at: 200,- create_uid: '0',- default_install: true,- status: 'approved',- }],- total: 1,- };- }- if (p === '/marketplace/skills/bundle' && body?.id === 'official-skill') {- return {- bundle_url: 'https://cdn.test/official-skill.zip',- version: '2.0.0',- published_at: 100,- updated_at: 200,- create_uid: '0',- default_install: true,- status: 'approved',- };- }- throw new Error(`unexpected ${p}`);- });-- await expect(seed.resolveBuiltinMarketplaceInstalls('u1')).resolves.toMatchObject({- resolved_skills: 0,- migrated_skills: 0,- failed: ['skill:legacy-skill'],- });-- expect(fs.existsSync(path.join(paths.userMarketplaceSkillDir('u1', 'legacy-skill'), 'SKILL.md'))).toBe(true);- expect(fs.readFileSync(path.join(officialDir, 'SKILL.md'), 'utf8')).toContain('keep');- const manifest = await installs.readInstalls('u1');- expect(manifest.skills).toEqual([- expect.objectContaining({- id: 'legacy-skill',- bundle_url: '',- seed_source: 'builtin',- }),- ]);- expect(enabled.readEnabledMap('u1').skills).toEqual({ 'legacy-skill': false });- });-it('renders installed agent-private builtin skills only for the owning agent', async () => {writeBuiltinAgent(TEST_AGENT_ID, {name: 'Writer',diff --git a/test/main/features/bundled_content_startup.test.ts b/test/main/features/bundled_content_startup.test.tsindex 4bd8bc19..2d3f6559 100644--- a/test/main/features/bundled_content_startup.test.ts+++ b/test/main/features/bundled_content_startup.test.ts@@ -26,7 +26,7 @@ afterEach(() => {else process.env.ORKAS_WORKSPACE_ROOT = prevWs;if (prevBuiltin === undefined) delete process.env.ORKAS_BUILTIN_ROOT;else process.env.ORKAS_BUILTIN_ROOT = prevBuiltin;- fs.rmSync(tmpDir, { recursive: true, force: true });+ fs.rmSync(tmpDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });vi.restoreAllMocks();vi.resetModules();});diff --git a/test/main/features/marketplace_biz.test.ts b/test/main/features/marketplace_biz.test.tsindex 6f183788..34c92256 100644--- a/test/main/features/marketplace_biz.test.ts+++ b/test/main/features/marketplace_biz.test.ts@@ -63,6 +63,11 @@ describe('marketplace category cache', () => {expect(list.map((entry) => entry.sort_order)).toEqual([...list].map((entry) => entry.sort_order).sort((a, b) => a - b),);+ for (const entry of list) {+ for (const lang of ['ar', 'hi', 'th', 'tr', 'vi', 'zh-tw', 'pt-pt', 'es-419']) {+ expect(entry[`name_${lang}` as keyof typeof entry], `${entry.code}/${lang}`).toBeTruthy();+ }+ }expect(runtime.fetchWithRetry).not.toHaveBeenCalled();});@@ -139,6 +144,8 @@ describe('marketplace category cache', () => {name_en: 'Creation',name_es: 'Creación', name_fr: 'Création', name_ko: '창작',name_de: 'Kreation', name_ru: 'Творчество', name_it: 'Creazione',+ name_ar: 'إبداع', name_hi: 'रचना', name_th: 'การสร้างสรรค์', name_tr: 'Yaratıcılık',+ name_vi: 'Sáng tạo', 'name_zh-tw': '創作', 'name_pt-pt': 'Criação', 'name_es-419': 'Creación',sort_order: 40,},{@@ -167,6 +174,8 @@ describe('marketplace category cache', () => {expect(list.find(entry => entry.code === 'creation')).toMatchObject({name_es: 'Creación', name_fr: 'Création', name_ko: '창작',name_de: 'Kreation', name_ru: 'Творчество', name_it: 'Creazione',+ name_ar: 'إبداع', name_hi: 'रचना', name_th: 'การสร้างสรรค์', name_tr: 'Yaratıcılık',+ name_vi: 'Sáng tạo', 'name_zh-tw': '創作', 'name_pt-pt': 'Criação', 'name_es-419': 'Creación',});expect(await marketplaceBiz.getMarketplaceCategories({ localOnly: true })).toEqual(list);});diff --git a/test/main/features/marketplace_cache.test.ts b/test/main/features/marketplace_cache.test.tsindex d87d0b1f..5d4d5033 100644--- a/test/main/features/marketplace_cache.test.ts+++ b/test/main/features/marketplace_cache.test.ts@@ -20,7 +20,7 @@ beforeEach(async () => {afterEach(() => {if (previousWorkspaceRoot === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;else process.env.ORKAS_WORKSPACE_ROOT = previousWorkspaceRoot;- fs.rmSync(tempDir, { recursive: true, force: true });+ fs.rmSync(tempDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });});describe('marketplace content cache', () => {diff --git a/test/main/features/marketplace_catalog.test.ts b/test/main/features/marketplace_catalog.test.tsnew file mode 100644index 00000000..77f3002c--- /dev/null+++ b/test/main/features/marketplace_catalog.test.ts@@ -0,0 +1,87 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createMarketplaceCatalogReader } from '../../../src/main/features/marketplace_catalog';++const postJson = vi.hoisted(() => vi.fn());+vi.mock('../../../src/main/features/marketplace', () => ({ postJson }));+beforeEach(() => { postJson.mockReset(); });++describe('marketplace catalog batch reads', () => {+ it.each(['agents', 'skills'] as const)('bounds %s requests, reuses results and fetches only new ids', async (kind) => {+ const ids = Array.from({ length: 2005 }, (_, i) => `item-${i}`);+ postJson.mockImplementation(async (_path, body) => ({+ list: body.ids.slice((body.page - 1) * body.size, body.page * body.size)+ .map((id: string) => ({ id, version: '2.0.0' })), total: body.ids.length,+ }));+ const reader = createMarketplaceCatalogReader();+ const rows = await reader.read(kind, [...ids, ids[0]]);+ expect([...rows.keys()]).toEqual(ids);+ expect(postJson.mock.calls.map(([, body]) => body.ids.length)).toEqual([...Array(20).fill(2000), 5]);+ expect(postJson.mock.calls.every(([endpoint]) => endpoint === `/marketplace/${kind}/list`)).toBe(true);+ await reader.read(kind, ids.slice(50));+ expect(postJson).toHaveBeenCalledTimes(21);+ await reader.read(kind, [ids[0], 'new-install']);+ expect(postJson).toHaveBeenLastCalledWith(`/marketplace/${kind}/list`, { page: 1, size: 100, ids: ['new-install'] });+ });++ it('paginates an old Server that ignores ids and excludes unrelated rows', async () => {+ postJson.mockResolvedValueOnce({ list: Array.from({ length: 100 }, (_, i) => ({ id: `other-${i}` })), total: 102 })+ .mockResolvedValueOnce({ list: [{ id: 'wanted', version: '2.0.0' }, { id: 'other-last' }], total: 102 });+ const reader = createMarketplaceCatalogReader();+ expect([...(await reader.read('skills', ['wanted', 'missing'])).keys()]).toEqual(['wanted']);+ expect(postJson).toHaveBeenCalledTimes(2);+ expect(postJson.mock.calls[1][1].page).toBe(2);+ expect(await reader.read('skills', ['missing'])).toEqual(new Map());+ expect(postJson).toHaveBeenCalledTimes(2);+ });++ it('does not treat a malformed or truncated catalog as proof of missing installs', async () => {+ const reader = createMarketplaceCatalogReader();+ postJson.mockResolvedValueOnce({});+ await expect(reader.read('agents', ['wanted'])).rejects.toThrow('invalid marketplace catalog');+ postJson.mockResolvedValue({ list: Array.from({ length: 100 }, (_, i) => ({ id: `other-${i}` })), total: 3000 });+ await expect(reader.read('agents', ['wanted'])).rejects.toThrow('pagination limit');+ expect(postJson).toHaveBeenCalledTimes(21);+ postJson.mockResolvedValue({ list: [{ id: 'wanted' }], total: 1 });+ expect((await reader.read('agents', ['wanted'])).has('wanted')).toBe(true);+ });++ it('batches legacy Agent names, rejects community and near-name matches, and shares resolved ids', async () => {+ postJson.mockResolvedValue({ list: [+ { id: 'community', name: 'Writer', create_uid: 'another-user' },+ { id: 'near-match', name: 'Writer Plus', create_uid: '0' },+ { id: 'official', name: 'Writer', create_uid: '0' },+ { id: 'researcher', name: 'Researcher', create_uid: '0' },+ ], total: 4 });+ const reader = createMarketplaceCatalogReader();+ const rows = await reader.readAgentNames(['Writer', 'Researcher', 'Missing']);+ expect([...rows.values()].map(row => row.id)).toEqual(['official', 'researcher']);+ expect(postJson).toHaveBeenCalledExactlyOnceWith('/marketplace/agents/list', {+ page: 1, size: 100, names: ['Writer', 'Researcher', 'Missing'],+ });+ expect((await reader.read('agents', ['official', 'researcher'])).size).toBe(2);+ expect(postJson).toHaveBeenCalledTimes(1);+ });++ it('shares pending lookups without turning a failed request into a missing row', async () => {+ let reject!: (err: Error) => void;+ postJson.mockImplementationOnce(() => new Promise((_resolve, fail) => { reject = fail; }));+ const reader = createMarketplaceCatalogReader();+ const first = reader.read('skills', ['wanted']);+ const second = reader.read('skills', ['wanted']);+ const result = Promise.allSettled([first, second]);+ reject(new Error('fixture offline'));+ expect((await result).map(row => row.status)).toEqual(['rejected', 'rejected']);+ expect(postJson).toHaveBeenCalledTimes(1);+ postJson.mockResolvedValue({ list: [{ id: 'wanted' }], total: 1 });+ expect((await reader.read('skills', ['wanted'])).has('wanted')).toBe(true);+ });++ it('stops after account cancellation and does not reuse snapshots in the next pass', async () => {+ let active = true;+ postJson.mockImplementationOnce(async () => { active = false; return { list: [], total: 0 }; });+ await expect(createMarketplaceCatalogReader(() => active).read('agents', ['wanted'])).rejects.toThrow('cancelled');+ postJson.mockResolvedValue({ list: [{ id: 'wanted', version: '2.0.0' }], total: 1 });+ expect((await createMarketplaceCatalogReader().read('agents', ['wanted'])).get('wanted')?.version).toBe('2.0.0');+ expect(postJson).toHaveBeenCalledTimes(2);+ });+});diff --git a/test/main/features/marketplace_reconcile.test.ts b/test/main/features/marketplace_reconcile.test.tsindex 96ad5467..a0fb3346 100644--- a/test/main/features/marketplace_reconcile.test.ts+++ b/test/main/features/marketplace_reconcile.test.ts@@ -277,6 +277,7 @@ describe('marketplace reconcile', () => {version: '1.0.0',published_at: 100,updated_at: 999,+ agent_json_url: 'https://example.test/republished.json',agent_skills_bundle_url: 'https://example.test/private-v2.zip',}],total: 1,@@ -285,6 +286,7 @@ describe('marketplace reconcile', () => {if (p === '/marketplace/skills/list') {return {list: [{+ bundle_url: 'https://example.test/older.zip',id: 'skill-older',version: '0.9.0',published_at: 100,@@ -322,12 +324,14 @@ describe('marketplace reconcile', () => {const manifest = await installs.readInstalls('u1');expect(manifest.agents[0]).toMatchObject({id: 'agent-private',+ agent_json_url: 'https://example.test/agent.json',version: '1.0.0',updated_at: 100,agent_skills_bundle_url: 'https://example.test/private-v1.zip',});expect(manifest.skills[0]).toMatchObject({id: 'skill-older',+ bundle_url: 'https://example.test/skill.zip',version: '1.0.0',updated_at: 100,});@@ -1369,15 +1373,16 @@ describe('marketplace reconcile', () => {res.end('not found');});postJsonMock.mockImplementation(async (p: string, body: any) => {- if (p === '/marketplace/skills/bundle' && body?.id === 'dep-skill') {- return {+ if (p === '/marketplace/skills/list' && body?.ids?.includes('dep-skill')) {+ return { list: [{+ id: 'dep-skill',bundle_url: `${base}/dep-skill.zip`,version: '1.0.0',published_at: 100,updated_at: 110,create_uid: '0',status: 'approved',- };+ }], total: 1 };}throw new Error(`unexpected path ${p}`);});diff --git a/test/main/features/marketplace_reconcile_e2e_scheduler.test.ts b/test/main/features/marketplace_reconcile_e2e_scheduler.test.tsnew file mode 100644index 00000000..fb0ead8d--- /dev/null+++ b/test/main/features/marketplace_reconcile_e2e_scheduler.test.ts@@ -0,0 +1,274 @@+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: ${args[0]}`); } }),+}));+vi.mock('electron', () => ({ app: { getVersion: () => '1.7.0' } }));+vi.mock('../../../src/main/features/devtools', () => ({ isDevEnv: () => false }));+let root: string;+let previousRoot: string | undefined;+const delay = () => new Promise<void>(resolve => setTimeout(resolve, 15));+const url = (id: string) => `https://marketplace.example.test/${id}`;+const dir = (kind: 'agents' | 'skills', id: string) => path.join(root, 'u1', 'local', 'marketplace', kind, id);+const skillRow = (id: string) => ({ id, version: '2.0.0', published_at: 200, installed_at: 100, bundle_url: url(id), status: 'approved' });+const agentRow = (id: string) => ({ id, version: '2.0.0', published_at: 200, installed_at: 100, agent_json_url: url(id) });+function localAgent(id: string) {+ fs.mkdirSync(dir('agents', id), { recursive: true });+ fs.writeFileSync(path.join(dir('agents', id), 'agent.json'), JSON.stringify({ agent_id: id, name: 'Old agent' }));+ fs.writeFileSync(path.join(dir('agents', id), '_install.json'), JSON.stringify({ version: '1.0.0', installed_at: 100 }));+}+async function setup(agentIds: string[], skillIds: string[], dependencies: string[] = []) {+ const installs = await import('../../../src/main/features/marketplace_installs');+ const reconcile = await import('../../../src/main/features/marketplace_reconcile');+ await installs.writeInstalls('u1', { version: 1, agents: agentIds.map(agentRow), skills: skillIds.map(skillRow) });+ const calls: string[] = [];+ let active = 0;+ let peak = 0;+ let denied = '';+ const zip = new AdmZip();+ zip.addFile('SKILL.md', Buffer.from('---\nname: updated-skill\n---\nUpdated content\n'));+ const bytes = zip.toBuffer();+ const fetcher = vi.fn(async (input: unknown) => {+ const id = new URL(String(input)).pathname.slice(1);+ calls.push(id);+ peak = Math.max(peak, ++active);+ await delay();+ active--;+ if (id === denied) return new Response('denied', { status: 403 });+ if (agentIds.includes(id)) return Response.json({ agent_id: id, name: 'Updated agent', skill_list: dependencies });+ return new Response(new Uint8Array(bytes));+ });+ vi.stubGlobal('fetch', fetcher);+ postJson.mockImplementation(async (endpoint: string, body: { ids?: string[]; id?: string }) => {+ if (endpoint === '/marketplace/skills/list') return { list: body.ids!.map(skillRow), total: body.ids!.length };+ if (endpoint === '/marketplace/skills/bundle') return skillRow(body.id!);+ throw new Error(`Unexpected endpoint ${endpoint}`);+ });+ return { installs, reconcile, calls, fetcher, peak: () => peak, deny: (id: string) => { denied = id; } };+}+function expectInstalled(kind: 'agents' | 'skills', ids: string[]) {+ for (const id of ids) {+ expect(JSON.parse(fs.readFileSync(path.join(dir(kind, id), '_install.json'), 'utf8')).version).toBe('2.0.0');+ expect(fs.readFileSync(path.join(dir(kind, id), kind === 'agents' ? 'agent.json' : 'SKILL.md'), 'utf8')).toContain('Updated');+ }+}+beforeEach(() => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-marketplace-scheduler-'));+ 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('marketplace update scheduling end to end', () => {+ it('bounds mixed update downloads and installs every selected resource', async () => {+ const agents = Array.from({ length: 12 }, (_, i) => `agent-${i}`);+ const skills = Array.from({ length: 32 }, (_, i) => `skill-${i}`);+ const ctx = await setup(agents, skills);+ expect(await ctx.reconcile.reconcileInstalls('u1')).toMatchObject({ pulled_agents: 12, pulled_skills: 32, failed: [] });+ expectInstalled('agents', agents);+ expectInstalled('skills', skills);+ expect(ctx.peak()).toBeLessThanOrEqual(4);+ expect(ctx.calls).toHaveLength(44);+ expect(warnings).not.toHaveBeenCalled();+ });+ it('lets four agents share a selected dependency without queue deadlock or duplicate transfer', async () => {+ const agents = ['agent-1', 'agent-2', 'agent-3', 'agent-4'];+ const ctx = await setup(agents, ['shared'], ['shared']);+ expect(await ctx.reconcile.reconcileInstalls('u1')).toMatchObject({ pulled_agents: 4, pulled_skills: 1, failed: [] });+ expectInstalled('agents', agents);+ expectInstalled('skills', ['shared']);+ expect(ctx.calls.filter(id => id === 'shared')).toHaveLength(1);+ expect(postJson).not.toHaveBeenCalled();+ expect(warnings).not.toHaveBeenCalled();+ });+ it('batches missing dependency metadata and shares installs across agents', async () => {+ const agents = ['agent-1', 'agent-2', 'agent-3', 'agent-4'];+ const dependencies = ['dep-1', 'dep-2', 'dep-3'];+ const ctx = await setup(agents, [], dependencies);+ expect(await ctx.reconcile.reconcileInstalls('u1')).toMatchObject({ pulled_agents: 4, failed: [] });+ expectInstalled('agents', agents);+ expectInstalled('skills', dependencies);+ expect(postJson).toHaveBeenCalledExactlyOnceWith('/marketplace/skills/list', { ids: dependencies, page: 1, size: 100 });+ for (const id of dependencies) expect(ctx.calls.filter(call => call === id)).toHaveLength(1);+ expect(warnings).not.toHaveBeenCalled();+ });+ it('retains old agents after a shared dependency failure and retries only unfinished installs', async () => {+ const agents = ['agent-1', 'agent-2', 'agent-3', 'agent-4'];+ const ctx = await setup(agents, ['shared', 'independent'], ['shared']);+ agents.forEach(localAgent);+ ctx.deny('shared');+ const failed = await ctx.reconcile.reconcileInstalls('u1');+ expect(failed.failed.sort()).toEqual([...agents.map(id => `agent:${id}`), 'skill:shared'].sort());+ expect(failed.pulled_skills).toBe(1);+ expectInstalled('skills', ['independent']);+ for (const id of agents) expect(fs.readFileSync(path.join(dir('agents', id), 'agent.json'), 'utf8')).toContain('Old agent');+ expect(ctx.calls.filter(id => id === 'shared')).toHaveLength(1);+ expect(warnings).toHaveBeenCalledTimes(5);+ warnings.mockClear();+ ctx.deny('');+ expect(await ctx.reconcile.reconcileInstalls('u1')).toMatchObject({ pulled_agents: 4, pulled_skills: 1, failed: [] });+ expectInstalled('agents', agents);+ expectInstalled('skills', ['shared']);+ expect(ctx.calls.filter(id => id === 'independent')).toHaveLength(1);+ expect(ctx.calls.filter(id => id === 'shared')).toHaveLength(2);+ expect(warnings).not.toHaveBeenCalled();+ });+ it('shares the global limit across overlapping passes and skips installs completed while waiting', async () => {+ const skills = Array.from({ length: 12 }, (_, i) => `skill-${i}`);+ const ctx = await setup([], skills);+ const results = await Promise.all([ctx.reconcile.reconcileInstalls('u1'), ctx.reconcile.reconcileInstalls('u1')]);+ expect(results.every(result => result.failed.length === 0)).toBe(true);+ expectInstalled('skills', skills);+ expect(ctx.peak()).toBeLessThanOrEqual(4);+ for (const id of skills) expect(ctx.calls.filter(call => call === id)).toHaveLength(1);+ expect(warnings).not.toHaveBeenCalled();+ });+ it('cancels queued updates when the account becomes inactive', async () => {+ const skills = Array.from({ length: 12 }, (_, i) => `skill-${i}`);+ const ctx = await setup([], skills);+ let active = true;+ const fetcher = ctx.fetcher.getMockImplementation()!;+ ctx.fetcher.mockImplementation(async input => {+ const response = await fetcher(input);+ active = false;+ return response;+ });+ expect(await ctx.reconcile.reconcileInstalls('u1', { shouldContinue: () => active })).toMatchObject({ pulled_skills: 0, failed: [] });+ expect(ctx.calls.length).toBeLessThanOrEqual(4);+ for (const id of skills) expect(fs.existsSync(path.join(dir('skills', id), 'SKILL.md'))).toBe(false);+ expect(warnings).not.toHaveBeenCalled();+ });+ it('keeps agent-private bundles private while batching public dependencies', async () => {+ const ctx = await setup(['agent-1'], [], ['private-skill', 'dep-1', 'dep-2']);+ await ctx.installs.writeInstalls('u1', { version: 1, agents: [{ ...agentRow('agent-1'), agent_skills_bundle_url: url('private-bundle') }], skills: [] });+ const zip = new AdmZip();+ zip.addFile('private-skill/SKILL.md', Buffer.from('---\nname: private-skill\n---\nPrivate content'));+ const fetcher = ctx.fetcher.getMockImplementation()!;+ ctx.fetcher.mockImplementation(async input => String(input) === url('private-bundle')+ ? new Response(new Uint8Array(zip.toBuffer())) : fetcher(input));+ expect(await ctx.reconcile.reconcileInstalls('u1')).toMatchObject({ pulled_agents: 1, failed: [] });+ expectInstalled('skills', ['dep-1', 'dep-2']);+ expect(fs.readFileSync(path.join(dir('agents', 'agent-1'), 'skills', 'private-skill', 'SKILL.md'), 'utf8')).toContain('Private content');+ expect((await ctx.installs.readInstalls('u1')).skills.map(row => row.id).sort()).toEqual(['dep-1', 'dep-2']);+ expect(postJson).toHaveBeenCalledExactlyOnceWith('/marketplace/skills/list', { ids: ['dep-1', 'dep-2'], page: 1, size: 100 });+ expect(warnings).not.toHaveBeenCalled();+ });++ it('uses one legacy detail lookup per missing dependency when catalog addresses are absent', async () => {+ const ctx = await setup(['agent-1', 'agent-2'], [], ['shared']);+ postJson.mockImplementation(async (endpoint: string) => {+ if (endpoint === '/marketplace/skills/list') return { list: [{ id: 'shared', version: '2.0.0', status: 'approved' }], total: 1 };+ if (endpoint === '/marketplace/skills/bundle') return skillRow('shared');+ throw new Error('Unexpected endpoint');+ });+ expect(await ctx.reconcile.reconcileInstalls('u1')).toMatchObject({ pulled_agents: 2, failed: [] });+ expectInstalled('agents', ['agent-1', 'agent-2']);+ expectInstalled('skills', ['shared']);+ expect(postJson.mock.calls.map(call => call[0])).toEqual(['/marketplace/skills/list', '/marketplace/skills/bundle']);+ expect(ctx.calls.filter(id => id === 'shared')).toHaveLength(1);+ expect(warnings).not.toHaveBeenCalled();+ });++ it.each(['missing', 'empty address', 'unapproved', 'incompatible', 'invalid version'])(+ 'rejects a %s dependency without installing the agent or falling back to per-item lookup', async failure => {+ const ctx = await setup(['agent-1'], [], ['shared']);+ localAgent('agent-1');+ const row = { ...skillRow('shared'),+ ...(failure === 'empty address' ? { bundle_url: '' } : {}),+ ...(failure === 'unapproved' ? { status: 'pending' } : {}),+ ...(failure === 'incompatible' ? { min_app_version: '99.0.0' } : {}),+ ...(failure === 'invalid version' ? { version: 'invalid' } : {}),+ };+ postJson.mockResolvedValue({ list: failure === 'missing' ? [] : [row], total: failure === 'missing' ? 0 : 1 });+ expect(await ctx.reconcile.reconcileInstalls('u1')).toMatchObject({ pulled_agents: 0, failed: ['agent:agent-1'] });+ expect(fs.readFileSync(path.join(dir('agents', 'agent-1'), 'agent.json'), 'utf8')).toContain('Old agent');+ expect((await ctx.installs.readInstalls('u1')).skills).toEqual([]);+ expect(ctx.calls).toEqual(['agent-1']);+ expect(postJson).toHaveBeenCalledTimes(1);+ expect(warnings).toHaveBeenCalledTimes(1);+ expect(warnings.mock.calls[0][0]).toContain('agent agent-1 pull failed:');+ },+ );++ it('does not resurrect a dependency removed while its catalog request was pending', async () => {+ const ctx = await setup(['agent-1', 'agent-2'], [], ['shared']);+ postJson.mockImplementation(async () => {+ await ctx.installs.removeSkillInstall('u1', 'shared');+ return { list: [skillRow('shared')], total: 1 };+ });+ expect(await ctx.reconcile.reconcileInstalls('u1')).toMatchObject({ pulled_agents: 0, failed: [] });+ expect(ctx.calls.sort()).toEqual(['agent-1', 'agent-2']);+ expect((await ctx.installs.readInstalls('u1')).skills).toEqual([]);+ expect(fs.existsSync(dir('skills', 'shared'))).toBe(false);+ expect(warnings).not.toHaveBeenCalled();+ });++ it('leaves queued resources uninstalled after an uninstall and continues unrelated work', async () => {+ const skills = Array.from({ length: 12 }, (_, i) => `skill-${i}`);+ const ctx = await setup([], skills);+ const fetcher = ctx.fetcher.getMockImplementation()!;+ ctx.fetcher.mockImplementation(async input => {+ if (String(input) === url('skill-0')) await ctx.installs.removeSkillInstall('u1', 'skill-11');+ return fetcher(input);+ });+ expect(await ctx.reconcile.reconcileInstalls('u1')).toMatchObject({ pulled_skills: 11, failed: [] });+ expectInstalled('skills', skills.slice(0, 11));+ expect(ctx.calls).not.toContain('skill-11');+ expect(fs.existsSync(dir('skills', 'skill-11'))).toBe(false);+ expect(warnings).not.toHaveBeenCalled();+ });++ it('does not seed dependencies after cancellation during metadata resolution', async () => {+ const ctx = await setup(['agent-1'], [], ['shared']);+ let active = true;+ postJson.mockImplementation(async () => {+ active = false;+ return { list: [skillRow('shared')], total: 1 };+ });+ expect(await ctx.reconcile.reconcileInstalls('u1', { shouldContinue: () => active })).toMatchObject({ pulled_agents: 0, failed: [] });+ expect((await ctx.installs.readInstalls('u1')).skills).toEqual([]);+ expect(ctx.calls).toEqual(['agent-1']);+ expect(warnings).not.toHaveBeenCalled();+ });++ it('keeps a newer manifest dependency when an older catalog supplies its missing address', async () => {+ const ctx = await setup(['agent-1'], ['shared'], ['shared']);+ await ctx.installs.writeInstalls('u1', { version: 1, agents: [agentRow('agent-1')], skills: [{ ...skillRow('shared'), version: '3.0.0', bundle_url: '' }] });+ const result = await ctx.reconcile.reconcileInstalls('u1');+ expect(result).toMatchObject({ pulled_agents: 0, pulled_skills: 0 });+ expect(result.failed.sort()).toEqual(['agent:agent-1', 'skill:shared']);+ expect((await ctx.installs.readInstalls('u1')).skills[0]).toMatchObject({ version: '3.0.0', bundle_url: '' });+ expect(ctx.calls).toEqual(['agent-1']);+ expect(warnings).toHaveBeenCalledTimes(2);+ });++ it('rejects a legacy detail response for a different dependency identity', async () => {+ const ctx = await setup(['agent-1'], [], ['shared']);+ postJson.mockImplementation(async (endpoint: string) => endpoint === '/marketplace/skills/list'+ ? { list: [{ id: 'shared', version: '2.0.0', status: 'approved' }], total: 1 }+ : skillRow('other-skill'));+ expect(await ctx.reconcile.reconcileInstalls('u1')).toMatchObject({ pulled_agents: 0, failed: ['agent:agent-1'] });+ expect((await ctx.installs.readInstalls('u1')).skills).toEqual([]);+ expect(ctx.calls).toEqual(['agent-1']);+ expect(warnings).toHaveBeenCalledTimes(1);+ expect(warnings.mock.calls[0][0]).toContain('identity mismatch');+ });++});diff --git a/test/main/features/marketplace_reconcile_urls.test.ts b/test/main/features/marketplace_reconcile_urls.test.tsindex 832cb7a1..9d69e1c2 100644--- a/test/main/features/marketplace_reconcile_urls.test.ts+++ b/test/main/features/marketplace_reconcile_urls.test.ts@@ -41,7 +41,7 @@ describe.each(['agent', 'skill'] as const)('marketplace %s download address recoconst oldUrl = `https://marketplace.example.test/${id}/old`;const detailPath = `/marketplace/${plural}/${kind === 'agent' ? 'detail' : 'bundle'}`;- async function setup(url: string, localVersion = '1.0.0') {+ async function setup(url: string, localVersion = '1.0.0', catalogAddress?: string) {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);@@ -68,7 +68,7 @@ describe.each(['agent', 'skill'] as const)('marketplace %s download address reco})();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 === `/marketplace/${plural}/list`) return { list: [{ id, version: '2.0.0', published_at: 200, ...(catalogAddress === undefined ? {} : { [urlKey]: catalogAddress }) }], total: 1 };if (endpoint === detailPath) return fresh;throw new Error('Unexpected marketplace endpoint');});@@ -93,6 +93,14 @@ describe.each(['agent', 'skill'] as const)('marketplace %s download address recoexpect(fs.readFileSync(path.join(ctx.dir, file), 'utf8')).toContain(kind === 'agent' ? 'Updated version' : 'updated-version');}+ it('uses the batched upgrade address without a per-item detail request', async () => {+ const ctx = await setup('', '1.0.0', freshUrl);+ await expectUpdated(ctx);+ expect(postJson).not.toHaveBeenCalled();+ expect(ctx.download).toHaveBeenCalledTimes(1);+ expect(warnings).not.toHaveBeenCalled();+ });+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);diff --git a/test/main/features/system_skills.test.ts b/test/main/features/system_skills.test.tsindex 871723b3..9e843af8 100644--- a/test/main/features/system_skills.test.ts+++ b/test/main/features/system_skills.test.ts@@ -12,6 +12,7 @@ const UID = 'system-skills-user';let tmpDir: string;let prevWs: string | undefined;+let prevDisableDelivery: string | undefined;let logDeliveries: ReturnType<typeof import('../../../src/main/util/log-delivery').createLogDelivery>[];beforeEach(async () => {@@ -19,7 +20,9 @@ beforeEach(async () => {vi.doUnmock('../../../src/main/paths');tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-system-skills-'));prevWs = process.env.ORKAS_WORKSPACE_ROOT;+ prevDisableDelivery = process.env.ORKAS_TEST_DISABLE_LOG_DELIVERY;process.env.ORKAS_WORKSPACE_ROOT = tmpDir;+ process.env.ORKAS_TEST_DISABLE_LOG_DELIVERY = '0';vi.resetModules();logDeliveries = [];const delivery = await import('../../../src/main/util/log-delivery');@@ -39,6 +42,8 @@ afterEach(async () => {} finally { await Promise.all(logDeliveries.map(delivery => delivery.close())); }if (prevWs === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;else process.env.ORKAS_WORKSPACE_ROOT = prevWs;+ if (prevDisableDelivery === undefined) delete process.env.ORKAS_TEST_DISABLE_LOG_DELIVERY;+ else process.env.ORKAS_TEST_DISABLE_LOG_DELIVERY = prevDisableDelivery;fs.rmSync(tmpDir, { recursive: true, force: true });vi.restoreAllMocks();vi.resetModules();diff --git a/test/main/model/skill-registry.test.ts b/test/main/model/skill-registry.test.tsindex 212e4863..2e6e267c 100644--- a/test/main/model/skill-registry.test.ts+++ b/test/main/model/skill-registry.test.ts@@ -118,6 +118,8 @@ describe('Agent authoring Skill candidates', () => {}}expect(specs.length).toBeGreaterThan(0);+ const packagedIds = specs.map((spec) => spec.id).sort();+ expect(new Set(packagedIds).size).toBe(packagedIds.length);const registry = await loadRegistry();const bindings = new Map<string, import('../../../src/main/model/core-agent/skill-registry').SkillRuntimeBinding>();const system = await registry.getSystemSkillsPromptBlock(TEST_UID, bindings);diff --git a/test/main/quality/skill-inline-budget.test.ts b/test/main/quality/skill-inline-budget.test.tsindex 18839901..c6b06556 100644--- a/test/main/quality/skill-inline-budget.test.ts+++ b/test/main/quality/skill-inline-budget.test.ts@@ -646,8 +646,10 @@ describe('builtin skill inline budget', () => {it('keeps shared and System discovery descriptions compact without changing user-content limits', () => {const resident = groups.filter(group => group.kind !== 'agent').flatMap(group => group.specs);// A shipped-source growth alarm, not a runtime truncation or quality gate.+ // 2026-09-22: six requester-approved ecommerce Skills moved into the+ // resident shared roster without changing their descriptions (5,192 chars).const chars = resident.reduce((sum, spec) => sum + pickDescription(spec, 'en').length, 0);- expect(chars).toBeLessThanOrEqual(4_500);+ expect(chars).toBeLessThanOrEqual(5_250);const creator = resident.find(spec => spec.name === 'agent-creator')!;const skillCreator = resident.find(spec => spec.name === 'skill-creator')!;expect(creator.description_en).not.toMatch(/inline.*container/i);diff --git a/test/renderer/marketplace-install-error.test.ts b/test/renderer/marketplace-install-error.test.tsindex fec73083..50a8069e 100644--- a/test/renderer/marketplace-install-error.test.ts+++ b/test/renderer/marketplace-install-error.test.ts@@ -289,22 +289,18 @@ describe('marketplace install error display', () => {const installStart = marketplaceSource.indexOf('async function _mpInstall(');const uninstallStart = marketplaceSource.indexOf('async function _mpUninstall(');const normalInstall = marketplaceSource.indexOf('const installed = await invokeInstall(false);', installStart);- const normalSuccess = marketplaceSource.indexOf("trackResult('success');", normalInstall);const normalState = marketplaceSource.indexOf('_mpApplyInstalledState(kind, item, installed);', normalInstall);const normalRefresh = marketplaceSource.indexOf('await _mpRefreshAfterAction(kind);', normalInstall);const uninstallInvoke = marketplaceSource.indexOf("window.orkas.invoke(channel, { id })", uninstallStart);- const uninstallSuccess = marketplaceSource.indexOf("trackResult('success');", uninstallInvoke);const uninstallState = marketplaceSource.indexOf('_mpApplyUninstalledState(kind, id);', uninstallInvoke);const uninstallRefresh = marketplaceSource.indexOf('await _mpRefreshAfterAction(kind);', uninstallInvoke);expect(normalInstall).toBeGreaterThan(installStart);- expect(normalInstall).toBeLessThan(normalSuccess);- expect(normalSuccess).toBeLessThan(normalState);- expect(normalSuccess).toBeLessThan(normalRefresh);+ expect(normalInstall).toBeLessThan(normalState);+ expect(normalState).toBeLessThan(normalRefresh);expect(uninstallInvoke).toBeGreaterThan(uninstallStart);- expect(uninstallInvoke).toBeLessThan(uninstallSuccess);- expect(uninstallSuccess).toBeLessThan(uninstallState);- expect(uninstallSuccess).toBeLessThan(uninstallRefresh);+ expect(uninstallInvoke).toBeLessThan(uninstallState);+ expect(uninstallState).toBeLessThan(uninstallRefresh);});});diff --git a/test/renderer/skills-frontmatter.test.ts b/test/renderer/skills-frontmatter.test.tsindex dfbb6666..68c1055b 100644--- a/test/renderer/skills-frontmatter.test.ts+++ b/test/renderer/skills-frontmatter.test.ts@@ -132,7 +132,7 @@ describe('skills renderer frontmatter parsing', () => {expect(msgEl.textContent).toBe('skills.saving');});- it('tracks URL skill creation success', async () => {+ it('opens the created URL skill after persistence', async () => {const context = loadSkillRendererHelpers();const monitorCalls: any[] = [];const calls: string[] = [];@@ -140,11 +140,6 @@ describe('skills renderer frontmatter parsing', () => {const msgEl = { textContent: '', className: '' };context.__calls = calls;context.performance = { now: () => { now += 25; return now; } };- context.window.Monitor = {- click: (action: string, payload: any) => monitorCalls.push(['click', action, payload]),- event: (action: string, payload: any) => monitorCalls.push(['event', action, payload]),- error: (action: string, payload: any) => monitorCalls.push(['error', action, payload]),- };context.apiFetch = async (url: string, opts: any) => {calls.push(`api:${url}:${opts?.method || 'GET'}`);return {@@ -164,16 +159,6 @@ describe('skills renderer frontmatter parsing', () => {`, context);await context._saveSkillFromUrl({ msgEl });-- expect(monitorCalls).toEqual([- ['click', 'skill_create_submit', { creation_method: 'url' }],- ['event', 'skill_create_result', {- creation_method: 'url',- result: 'success',- duration_ms: 25,- skill_count: 1,- }],- ]);expect(calls).toEqual(['busy:true','paint',@@ -183,16 +168,11 @@ describe('skills renderer frontmatter parsing', () => {]);});- it('tracks manual, URL, and directory client validation as blocked terminals', async () => {+ it('shows recoverable validation errors without creating invalid skills', async () => {const context = loadSkillRendererHelpers();const monitorCalls: any[] = [];let now = 100;context.performance = { now: () => { now += 25; return now; } };- context.window.Monitor = {- click: (action: string, payload: any) => monitorCalls.push(['click', action, payload]),- event: (action: string, payload: any) => monitorCalls.push(['event', action, payload]),- error: (action: string, payload: any) => monitorCalls.push(['error', action, payload]),- };vm.runInContext(`document = {getElementById: () => ({ value: '', textContent: '', className: '', focus() {} }),@@ -200,70 +180,23 @@ describe('skills renderer frontmatter parsing', () => {`, context);const msgEl = { textContent: '', className: '' };+ context.apiFetch = () => { throw new Error('Invalid input must not create a skill'); };await context._saveSkillManual({ editId: '', msgEl });+ expect(msgEl.textContent).toBe('skills.input_name_needed');await context._saveSkillFromUrl({ msgEl });+ expect(msgEl.textContent).toBe('skill_modal.err_url_invalid');await context._saveSkillFromDir({ msgEl });-- expect(monitorCalls).toEqual([- ['click', 'skill_create_submit', { creation_method: 'manual' }],- ['event', 'skill_create_result', {- creation_method: 'manual', result: 'blocked', duration_ms: 25, error_code: 'no_name',- }],- ['click', 'skill_create_submit', { creation_method: 'url' }],- ['event', 'skill_create_result', {- creation_method: 'url', result: 'blocked', duration_ms: 25, error_code: 'url_invalid',- }],- ['click', 'skill_create_submit', { creation_method: 'dir' }],- ['event', 'skill_create_result', {- creation_method: 'dir', result: 'blocked', duration_ms: 25, error_code: 'dir_missing',- }],- ]);- });-- it('keeps Skill create success authoritative and omits raw refresh errors', async () => {- const context = loadSkillRendererHelpers();- const monitorCalls: any[] = [];- let now = 100;- context.performance = { now: () => { now += 25; return now; } };- context.window.Monitor = {- click: (action: string, payload: any) => monitorCalls.push(['click', action, payload]),- event: (action: string, payload: any) => monitorCalls.push(['event', action, payload]),- error: (action: string, payload: any) => monitorCalls.push(['error', action, payload]),- };- context.apiFetch = async () => ({- json: async () => ({ ok: true, skill: { id: 'created', name: 'Private name' } }),- });- vm.runInContext(`- document = { getElementById: () => ({ value: 'https://example.com/private', focus() {} }) };- _setSkillModalBusy = () => {};- _waitForSkillModalBusyPaint = async () => {};- _afterSkillCreated = async () => { throw new Error('private refresh detail'); };- `, context);-- await context._saveSkillFromUrl({ msgEl: { textContent: '', className: '' } });-- expect(monitorCalls).toEqual([- ['click', 'skill_create_submit', { creation_method: 'url' }],- ['event', 'skill_create_result', {- creation_method: 'url', result: 'success', duration_ms: 25, skill_count: 1,- }],- ]);- expect(JSON.stringify(monitorCalls)).not.toContain('Private name');- expect(JSON.stringify(monitorCalls)).not.toContain('private refresh detail');+ expect(msgEl.textContent).toBe('skill_modal.err_dir_missing');+ expect(msgEl.className).toBe('form-msg err');});- it('reports Skill create failures with a stable result code only', async () => {+ it('shows a failed import and releases the busy state', async () => {const context = loadSkillRendererHelpers();const monitorCalls: any[] = [];let now = 100;context.performance = { now: () => { now += 25; return now; } };- context.window.Monitor = {- click: (action: string, payload: any) => monitorCalls.push(['click', action, payload]),- event: (action: string, payload: any) => monitorCalls.push(['event', action, payload]),- error: (action: string, payload: any) => monitorCalls.push(['error', action, payload]),- };context.apiFetch = async () => ({- json: async () => ({ ok: false, error: 'failed to import private-user/private-skill' }),+ json: async () => ({ ok: false, error: 'Import failed' }),});vm.runInContext(`document = { getElementById: () => ({ value: 'https://example.com/private', focus() {} }) };@@ -271,25 +204,18 @@ describe('skills renderer frontmatter parsing', () => {_waitForSkillModalBusyPaint = async () => {};`, context);- await context._saveSkillFromUrl({ msgEl: { textContent: '', className: '' } });-- expect(monitorCalls).toEqual([- ['click', 'skill_create_submit', { creation_method: 'url' }],- ['event', 'skill_create_result', {- creation_method: 'url', result: 'failure', duration_ms: 25, error_code: 'import_failed',- }],- ]);- expect(JSON.stringify(monitorCalls)).not.toContain('private-user');+ const msgEl = { textContent: '', className: '' };+ const busy: boolean[] = [];+ context._setSkillModalBusy = (value: boolean) => busy.push(value);+ await context._saveSkillFromUrl({ msgEl });+ expect(msgEl.className).toBe('form-msg err');+ expect(msgEl.textContent).toBe('Import failed');+ expect(busy[busy.length - 1]).toBe(false);});it('keeps Skill toggle and package mutation success authoritative across refresh failures', async () => {const context = loadSkillRendererHelpers();const monitorCalls: any[] = [];- context.window.Monitor = {- click: (action: string, payload: any) => monitorCalls.push(['click', action, payload]),- event: (action: string, payload: any) => monitorCalls.push(['event', action, payload]),- error: (action: string, payload: any) => monitorCalls.push(['error', action, payload]),- };context.Monitor = context.window.Monitor;context.window.orkas = { invoke: async () => ({ ok: true }) };context.uiAlert = async () => {};@@ -310,16 +236,11 @@ describe('skills renderer frontmatter parsing', () => {);expect(skillResults).toHaveLength(0);expect(packageResults).toHaveLength(0);- expect(monitorCalls.some(([kind]) => kind === 'error')).toBe(false);});it('keeps a successful Skill delete authoritative when refresh fails', async () => {const context = loadSkillRendererHelpers();const monitorCalls: any[] = [];- context.window.Monitor = {- event: (action: string, payload: any) => monitorCalls.push(['event', action, payload]),- error: (action: string, payload: any) => monitorCalls.push(['error', action, payload]),- };context.Monitor = context.window.Monitor;context.uiConfirm = async () => true;context.uiAlert = async () => {};@@ -337,7 +258,6 @@ describe('skills renderer frontmatter parsing', () => {);expect(results).toHaveLength(0);expect(vm.runInContext('_selectedSkill', context)).toBeNull();- expect(JSON.stringify(monitorCalls)).not.toContain('Private Skill');});it('sends forced import auto-seed even when edit chat history is not empty', async () => {