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 saved apps when their inventory is unavailable

CloudTianTian1a5e50458d14
diff --git a/src/main/features/saved_apps.ts b/src/main/features/saved_apps.ts
index 704edf9f..b830e5c1 100644
--- a/src/main/features/saved_apps.ts
+++ b/src/main/features/saved_apps.ts
@@ -154,11 +154,12 @@ function failureCode(err: unknown, fallback: string): string {
return typeof message === 'string' && /^app_[a-z_]+$/.test(message) ? message : fallback;
}
-function isRealSavedAppDirectory(dir: string): boolean {
+function isRealSavedAppDirectory(dir: string, unavailable?: 'app_list_failed' | 'app_save_binding_unavailable'): boolean {
try {
const st = fs.lstatSync(dir);
return st.isDirectory() && !st.isSymbolicLink();
- } catch {
+ } catch (error) {
+ if (unavailable && (error as NodeJS.ErrnoException).code !== 'ENOENT') throw new Error(unavailable);
return false;
}
}
@@ -541,17 +542,18 @@ export async function getSaveTarget(uid: string, cid: string, source: {artifactI
// A deleted explicit destination must not fall back to an unrelated original.
if (id) {
const dir = savedAppDir(uid, safeAppId(id));
- if (!isRealSavedAppDirectory(dir)) return null;
+ if (!isRealSavedAppDirectory(dir, 'app_save_binding_unavailable')) return null;
const meta = readMeta(dir);
return { appId: id, title: sanitiseTitle(meta.title), appType: metadataAppType(meta.appType) ?? await resolveSavedAppType(uid, id) };
}
const edit = cid ? await getEditTarget(uid, cid) : null;
- if (edit) return isRealSavedAppDirectory(savedAppDir(uid, edit.appId)) ? edit : null;
+ if (edit) return isRealSavedAppDirectory(savedAppDir(uid, edit.appId), 'app_save_binding_unavailable') ? edit : null;
// Recover only unique historical provenance; duplicate copies are not a choice.
const sourceKeys=source.rootDir?[pathSourceKey(source.rootDir),legacyPathSourceKey(source.legacyRoot??source.rootDir)]:[];
const candidates = listSavedApps(uid).filter(app => {
let meta: Partial<SavedAppMeta>;
- try { meta = readMeta(savedAppDir(uid, app.id)); } catch { return false; }
+ try { meta = readMeta(savedAppDir(uid, app.id)); }
+ catch { throw new Error('app_save_binding_unavailable'); }
return source.artifactId ? meta.sourceCid === cid && meta.sourceArtifactId === source.artifactId
: sourceKeys.includes(meta.sourcePathKey!);
});
@@ -800,7 +802,10 @@ export function listSavedApps(userId: string): SavedAppListItem[] {
const root = userSavedAppsDir(userId);
let names: string[];
try { names = fs.readdirSync(root); }
- catch { return []; } // pool dir not created yet
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
+ throw new Error('app_list_failed');
+ }
sweepStagingDirs(root, names, retained);
const items: SavedAppListItem[] = [];
for (const name of names) {
@@ -808,7 +813,7 @@ export function listSavedApps(userId: string): SavedAppListItem[] {
let appId: string;
try { appId = safeAppId(name); } catch { continue; }
const dir = savedAppDir(userId, appId);
- if (!isRealSavedAppDirectory(dir)) continue;
+ if (!isRealSavedAppDirectory(dir, 'app_list_failed')) continue;
let meta: Partial<SavedAppMeta> = {};
try { meta = readMeta(dir); }
catch (err) {
diff --git a/test/e2e/saved_apps_e2e_lifecycle.spec.ts b/test/e2e/saved_apps_e2e_lifecycle.spec.ts
index 9a6a01f9..61a8cfe0 100644
--- a/test/e2e/saved_apps_e2e_lifecycle.spec.ts
+++ b/test/e2e/saved_apps_e2e_lifecycle.spec.ts
@@ -5,6 +5,46 @@ import { openSidebarEntry, expect, test } from './fixtures/orkas';
declare const currentCid: string;
+test('retains saved app cards when the local inventory is unreadable and recovers the same app', async ({orkas}, info) => {
+ const page=orkas.page!;
+ const source=orkas.createWorkspaceFile('inventory-recovery/index.html','<!doctype html><h1>Charging planner</h1>');
+ const saved=await orkas.invoke<any>('savedApps.saveFromPath',{path:source,title:'Charging planner'});
+ expect(saved.ok).toBe(true);
+ await openSidebarEntry(page,'#apps-btn');
+ const card=page.locator(`.app-card[data-app-id="${saved.id}"]`);
+ await expect(card).toBeVisible();
+ const root=path.join(orkas.workspaceRoot,'account-e2e/cloud/saved_apps');
+ await orkas.electronApp!.evaluate((_electron,root)=>{
+ const main=(process as any).mainModule,fs=main.require('node:fs'),modules=main.require('node:module');
+ const original=fs.readdirSync;
+ (globalThis as any).__restoreSavedInventory=()=>{fs.readdirSync=original;modules.syncBuiltinESMExports();};
+ fs.readdirSync=(target:any,...args:any[])=>{
+ if(String(target)===root)throw Object.assign(new Error('PRIVATE inventory unavailable'),{code:'EIO'});
+ return original(target,...args);
+ };
+ modules.syncBuiltinESMExports();
+ },root);
+ try {
+ await page.evaluate(()=>(window as any).loadSavedApps(true));
+ await expect(card).toBeVisible();
+ await expect(page.locator('#apps-empty')).toBeHidden();
+ await expect(page.locator('#apps-page-header-count')).toHaveText('1');
+ } finally {
+ await orkas.electronApp!.evaluate(()=>{
+ (globalThis as any).__restoreSavedInventory();delete (globalThis as any).__restoreSavedInventory;
+ });
+ }
+ await page.evaluate(()=>(window as any).loadSavedApps(true));
+ await expect(card).toBeVisible();
+ expect((await orkas.invoke<any>('savedApps.list')).apps.map((a:any)=>a.id)).toEqual([saved.id]);
+ expect(readFileSync(source,'utf8')).toContain('Charging planner');
+ const preview=await orkas.openPreview(()=>card.click());
+ await expect(preview.frameLocator('.saved-app-viewer-frame').locator('h1')).toHaveText('Charging planner');
+ await preview.screenshot({path:info.outputPath('recovered-planner.png')});
+ await orkas.closePreview(preview);
+ expect(orkas.modelRequests).toHaveLength(0);
+});
+
test('root-level Save as app explains the separate-folder requirement and saves only the recovered bundle', async ({ orkas }, testInfo) => {
const page=orkas.page!;
const source=orkas.createWorkspaceFile('小工具.html','<!doctype html><html lang="zh"><meta charset="utf-8"><title>小工具</title><body><h1>小工具</h1><p>一个待保存的应用</p></body></html>');
diff --git a/test/main/features/saved_apps.test.ts b/test/main/features/saved_apps.test.ts
index 2665b1d1..6d28536d 100644
--- a/test/main/features/saved_apps.test.ts
+++ b/test/main/features/saved_apps.test.ts
@@ -67,6 +67,34 @@ async function makeArtifact(title: string, extra: Array<{ path: string; content:
}
describe('saved_apps › saveFromArtifact', () => {
+ it.each(['artifact','workspace'] as const)('does not turn an unreadable %s save destination into a new app',async source=>{
+ const {savedApps}=await mods();
+ const artifactId=source==='artifact'?await makeArtifact('Original planner'):'';
+ const root=path.join(tmpDir,'workspace','planner');fs.mkdirSync(root,{recursive:true});
+ const sourceFile=path.join(root,'index.html');fs.writeFileSync(sourceFile,'<h1>Original planner</h1>');
+ const save=()=>source==='artifact'?savedApps.saveFromArtifact(UID,CID,artifactId,'auto')
+ :savedApps.saveFromPath(UID,sourceFile,{mode:'auto',fenceRoots:[tmpDir]});
+ const saved=await save();if(!saved.ok)throw new Error(saved.error);
+ const dir=path.join(APPS_ROOT(),saved.id),before=fs.readFileSync(path.join(dir,'index.html'));
+ const target=()=>savedApps.getSaveTarget(UID,CID,source==='artifact'?{artifactId}:{rootDir:root});
+ expect(await target()).toMatchObject({appId:saved.id});
+ const nodeFs=(await import('node:fs')).default,{syncBuiltinESMExports}=await import('node:module');
+ const lstat=nodeFs.lstatSync;
+ const fault=vi.spyOn(nodeFs,'lstatSync').mockImplementation(((file:any,...args:any[])=>{
+ if(String(file)===dir)throw Object.assign(new Error('PRIVATE target unavailable'),{code:'EIO'});
+ return (lstat as any)(file,...args);
+ }) as any);
+ syncBuiltinESMExports();
+ try {
+ await expect.soft(target()).rejects.toThrow('app_save_binding_unavailable');
+ expect.soft(await save()).toMatchObject({ok:false,error:'app_edit_target_missing'});
+ } finally {fault.mockRestore();syncBuiltinESMExports();}
+ expect.soft(fs.readdirSync(APPS_ROOT())).toEqual([saved.id]);
+ expect(fs.readFileSync(path.join(dir,'index.html'))).toEqual(before);
+ expect.soft(await target()).toMatchObject({appId:saved.id});
+ expect.soft(await save()).toMatchObject({ok:true,id:saved.id});
+ });
+
it('preserves the editing destination after a short context refresh write and recovers the next update', async () => {
const { savedApps, chatArtifacts } = await mods();
const saved = await savedApps.saveFromArtifact(UID, CID, await makeArtifact('Original'));
@@ -1246,6 +1274,82 @@ describe('saved_apps › rename / delete', () => {
});
describe('saved_apps › listSavedApps', () => {
+ it.each(['unreadable','missing','malformed'] as const)('refuses unknown historical provenance when saved metadata is %s',async failure=>{
+ const {savedApps,chatArtifacts}=await mods(),artifactId=await makeArtifact('Legacy planner');
+ const saved=await savedApps.saveFromArtifact(UID,CID,artifactId);if(!saved.ok)throw new Error(saved.error);
+ const artifact=chatArtifacts.resolveArtifactDir(UID,CID,artifactId);if(!artifact.ok)throw new Error(artifact.error);
+ const sourceMeta=path.join(artifact.dirPath,'__orkas-meta.json'),meta=JSON.parse(fs.readFileSync(sourceMeta,'utf8'));
+ delete meta.savedAppId;fs.writeFileSync(sourceMeta,JSON.stringify(meta));
+ const savedMeta=path.join(APPS_ROOT(),saved.id,'__orkas-meta.json'),before=fs.readFileSync(savedMeta);
+ expect(await savedApps.getSaveTarget(UID,CID,{artifactId})).toMatchObject({appId:saved.id});
+ const nodeFs=(await import('node:fs')).default,{syncBuiltinESMExports}=await import('node:module'),read=nodeFs.readFileSync;
+ const fault=vi.spyOn(nodeFs,'readFileSync').mockImplementation(((file:any,...args:any[])=>{
+ if(String(file)===savedMeta){
+ if(failure==='malformed')return 'PRIVATE malformed metadata';
+ throw Object.assign(new Error('PRIVATE metadata read unavailable'),{code:failure==='missing'?'ENOENT':'EIO'});
+ }
+ return (read as any)(file,...args);
+ }) as any);syncBuiltinESMExports();
+ try {
+ await expect.soft(savedApps.getSaveTarget(UID,CID,{artifactId})).rejects.toThrow('app_save_binding_unavailable');
+ expect.soft(await savedApps.saveFromArtifact(UID,CID,artifactId,'auto')).toMatchObject({ok:false,error:'app_edit_target_missing'});
+ }finally{fault.mockRestore();syncBuiltinESMExports();}
+ expect.soft(fs.readdirSync(APPS_ROOT())).toEqual([saved.id]);
+ expect(fs.readFileSync(savedMeta)).toEqual(before);
+ expect.soft(await savedApps.getSaveTarget(UID,CID,{artifactId})).toMatchObject({appId:saved.id});
+ });
+
+ it('rejects an unreadable app entry instead of returning an incomplete successful list', async () => {
+ const {savedApps}=await mods();
+ const saved=await savedApps.saveFromArtifact(UID,CID,await makeArtifact('Kept planner'));
+ if(!saved.ok)throw new Error(saved.error);
+ const before=savedApps.listSavedApps(UID),dir=path.join(APPS_ROOT(),saved.id);
+ const nodeFs=(await import('node:fs')).default,{syncBuiltinESMExports}=await import('node:module');
+ const lstat=nodeFs.lstatSync;
+ const fault=vi.spyOn(nodeFs,'lstatSync').mockImplementation(((target:any,...args:any[])=>{
+ if(String(target)===dir)throw Object.assign(new Error('PRIVATE entry unavailable'),{code:'EACCES'});
+ return (lstat as any)(target,...args);
+ }) as any);
+ syncBuiltinESMExports();
+ try {expect(()=>savedApps.listSavedApps(UID)).toThrow('app_list_failed');}
+ finally {fault.mockRestore();syncBuiltinESMExports();}
+ expect(savedApps.listSavedApps(UID)).toEqual(before);
+ expect(fs.readFileSync(path.join(dir,'index.html'),'utf8')).toContain('Kept planner');
+ });
+
+ it.each(['EACCES', 'EIO', 'ENOTDIR'])('rejects an unavailable %s inventory without erasing apps or historical save destinations', async code => {
+ const { savedApps, chatArtifacts } = await mods();
+ const artifactId = await makeArtifact('Retained planner');
+ const saved = await savedApps.saveFromArtifact(UID, CID, artifactId);
+ if (!saved.ok) throw new Error(saved.error);
+ // Legacy provenance has no explicit binding, so enumeration is necessary.
+ const artifactDir = chatArtifacts.resolveArtifactDir(UID, CID, artifactId);
+ if (!artifactDir.ok) throw new Error(artifactDir.error);
+ const artifactMeta = path.join(artifactDir.dirPath, '__orkas-meta.json');
+ const meta = JSON.parse(fs.readFileSync(artifactMeta, 'utf8')); delete meta.savedAppId;
+ fs.writeFileSync(artifactMeta, JSON.stringify(meta));
+ const before = savedApps.listSavedApps(UID);
+ expect(await savedApps.getSaveTarget(UID, CID, {artifactId})).toMatchObject({appId:saved.id});
+ const entry = path.join(APPS_ROOT(), saved.id, 'index.html');
+ const bytes = fs.readFileSync(entry);
+ const nodeFs = (await import('node:fs')).default;
+ const {syncBuiltinESMExports} = await import('node:module');
+ const readdir = nodeFs.readdirSync;
+ const fault = vi.spyOn(nodeFs, 'readdirSync').mockImplementation(((target:any, ...args:any[]) => {
+ if (String(target) === APPS_ROOT()) throw Object.assign(new Error('PRIVATE inventory path'), {code});
+ return (readdir as any)(target, ...args);
+ }) as any);
+ syncBuiltinESMExports();
+ try {
+ expect.soft(() => savedApps.listSavedApps(UID)).toThrow('app_list_failed');
+ await expect.soft(savedApps.listResolvedSavedApps(UID)).rejects.toThrow('app_list_failed');
+ await expect.soft(savedApps.getSaveTarget(UID, CID, {artifactId})).rejects.toThrow('app_list_failed');
+ expect(fs.readFileSync(entry)).toEqual(bytes);
+ } finally {fault.mockRestore();syncBuiltinESMExports();}
+ expect(savedApps.listSavedApps(UID)).toEqual(before);
+ expect(await savedApps.getSaveTarget(UID, CID, {artifactId})).toMatchObject({appId:saved.id});
+ });
+
it('keeps private malformed metadata excerpts out of diagnostics and retains the recoverable app', async () => {
const logging = await import('../../../src/main/logger');
const createLogger = logging.createLogger;