Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Preserve category cache during concurrent refreshes

BlueSkyID6660c96d225e465
diff --git a/src/main/features/marketplace_biz.ts b/src/main/features/marketplace_biz.ts
index 32157288..425603a2 100644
--- a/src/main/features/marketplace_biz.ts
+++ b/src/main/features/marketplace_biz.ts
@@ -19,11 +19,12 @@ import * as fsp from 'node:fs/promises';
import * as path from 'node:path';
import { SUPPORTED_LANGS, type Lang } from '../i18n';
-import { marketplaceBizFile, userLocalBizDir } from '../paths';
+import { marketplaceBizFile } from '../paths';
import { getActiveUserId } from './users';
import { withCommonHeaders } from './api_common';
import { apiBase } from './marketplace';
import { createLogger } from '../logger';
+import { writeJson } from '../storage';
import { fetchWithRetry } from '../util/retry';
const log = createLogger('marketplace_biz');
@@ -146,10 +147,7 @@ async function _readPersisted(uid: string): Promise<PersistedBiz> {
}
async function _writePersisted(uid: string, data: PersistedBiz): Promise<void> {
- const dir = userLocalBizDir(uid);
- await fsp.mkdir(dir, { recursive: true });
- const file = marketplaceBizFile(uid);
- await fsp.writeFile(file, JSON.stringify(data, null, 2), 'utf8');
+ await writeJson(marketplaceBizFile(uid), data);
}
async function _fetchFromServer(): Promise<MarketplaceCategory[]> {
diff --git a/test/main/features/marketplace_biz.test.ts b/test/main/features/marketplace_biz.test.ts
index 34c92256..7651ddf4 100644
--- a/test/main/features/marketplace_biz.test.ts
+++ b/test/main/features/marketplace_biz.test.ts
@@ -1,4 +1,5 @@
import * as fs from 'node:fs';
+import * as fsp from 'node:fs/promises';
import * as os from 'node:os';
import * as path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -6,6 +7,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const runtime = vi.hoisted(() => ({
activeUid: 'marketplace-biz-a',
fetchWithRetry: vi.fn(),
+ warn: vi.fn(),
+ writeHook: null as null | ((file: string, data: string | Uint8Array, options: any) => Promise<void>),
+}));
+
+vi.mock('node:fs/promises', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('node:fs/promises')>();
+ return { ...actual, writeFile: (...args: Parameters<typeof actual.writeFile>) =>
+ runtime.writeHook
+ ? runtime.writeHook(String(args[0]), args[1] as string | Uint8Array, args[2])
+ : actual.writeFile(...args) };
+});
+vi.mock('../../../src/main/logger', () => ({
+ createLogger: () => ({ warn: runtime.warn }),
}));
vi.mock('../../../src/main/features/users', () => ({
@@ -44,10 +58,13 @@ beforeEach(() => {
process.env.ORKAS_WORKSPACE_ROOT = tempRoot;
runtime.activeUid = ACCOUNT_A;
runtime.fetchWithRetry.mockReset();
+ runtime.warn.mockReset();
+ runtime.writeHook = null;
vi.resetModules();
});
afterEach(() => {
+ runtime.writeHook = null;
if (priorWorkspaceRoot === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;
else process.env.ORKAS_WORKSPACE_ROOT = priorWorkspaceRoot;
fs.rmSync(tempRoot, { recursive: true, force: true });
@@ -195,6 +212,7 @@ describe('marketplace category cache', () => {
await expect(marketplaceBiz.getMarketplaceCategories({ forceRefresh: true }))
.resolves.toMatchObject([{ code: 'general' }]);
+ expect(runtime.warn.mock.calls).toEqual([['persisted categories write failed code=EEXIST']]);
});
it('keeps an in-flight account A refresh out of account B disk and memory caches', async () => {
@@ -235,4 +253,58 @@ describe('marketplace category cache', () => {
const listB = await marketplaceBiz.getMarketplaceCategories({ localOnly: true });
expect(listB).toMatchObject([{ code: 'education', name_en: 'Education B' }]);
});
+ it.each(['complete', 'fail'] as const)('keeps the previous offline registry readable while a refresh write will %s', async (outcome) => {
+ const { marketplaceBizFile } = await import('../../../src/main/paths');
+ const file = marketplaceBizFile(ACCOUNT_A);
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ const previous = { categories: { fetched_at: Date.now() - 90_000_000,
+ list: [{ code: 'custom', name_en: 'Saved category', name_zh: '缓存分类', sort_order: 1 }] } };
+ fs.writeFileSync(file, JSON.stringify(previous));
+ runtime.fetchWithRetry.mockResolvedValueOnce(response([
+ { code: 'updated', name_en: 'Updated category', name_zh: '新分类', sort_order: 2 },
+ ])).mockRejectedValueOnce(Object.assign(new Error('fixture offline'), { code: 'OFFLINE' }));
+ let entered!: () => void;
+ let release!: () => void;
+ const opened = new Promise<void>((resolve) => { entered = resolve; });
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ // Control only the filesystem scheduling/failure boundary. The production
+ // module and storage helper choose the destination and publication method.
+ runtime.writeHook = async (destination, data, options) => {
+ const handle = await fsp.open(destination, 'w', typeof options === 'object' ? options?.mode : undefined);
+ try {
+ entered();
+ await gate;
+ if (outcome === 'fail') throw Object.assign(new Error('fixture full disk'), { code: 'ENOSPC' });
+ await handle.writeFile(data, typeof options === 'string' ? options as BufferEncoding : undefined);
+ } finally { await handle.close(); }
+ };
+ const marketplaceBiz = await loadModule();
+ const refreshing = marketplaceBiz.getMarketplaceCategories({ forceRefresh: true });
+ try {
+ await opened;
+ // Force refresh exercises an independent reader instead of the fresh
+ // memory shortcut. Offline recovery must use the valid disk snapshot.
+ const concurrent = await marketplaceBiz.getMarketplaceCategories({ forceRefresh: true });
+ expect(concurrent).toMatchObject([{ code: 'custom', name_en: 'Saved category' }]);
+ expect(JSON.parse(fs.readFileSync(file, 'utf8'))).toEqual(previous);
+ expect(runtime.warn.mock.calls).toEqual([['fetch categories failed code=OFFLINE']]);
+ } finally {
+ release();
+ await refreshing;
+ runtime.writeHook = null;
+ }
+ await expect(refreshing).resolves.toMatchObject([{ code: 'updated' }]);
+ const saved = JSON.parse(fs.readFileSync(file, 'utf8'));
+ if (outcome === 'complete') {
+ expect(saved.categories.list).toMatchObject([{ code: 'updated', name_en: 'Updated category' }]);
+ expect(runtime.warn.mock.calls).toEqual([['fetch categories failed code=OFFLINE']]);
+ } else {
+ expect(saved).toEqual(previous);
+ expect(runtime.warn.mock.calls).toEqual([
+ ['fetch categories failed code=OFFLINE'], ['persisted categories write failed code=ENOSPC'],
+ ]);
+ }
+ expect(fs.readdirSync(path.dirname(file))).toEqual([path.basename(file)]);
+ });
+
});