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.

Prune orphaned workspace-sourced file_cache entries on workspace switch

claw2e31a65eb694f
diff --git a/src/main/features/file_indexer.ts b/src/main/features/file_indexer.ts
index 8bacb86b..71f050f5 100644
--- a/src/main/features/file_indexer.ts
+++ b/src/main/features/file_indexer.ts
@@ -436,14 +436,26 @@ export function invalidateFileCache(userId: string, absPath: string): void {
}
/** Startup sweep: drop cache dirs whose source is gone, whose version is
- * obsolete, or whose meta is malformed. Cheap (stat per dir), no network. */
-export async function pruneOrphans(userId: string): Promise<{ deleted: number }> {
+ * obsolete, or whose meta is malformed. Cheap (stat per dir), no network.
+ *
+ * Optional `workspacePath`: when supplied, additionally drops
+ * `source==='workspace'` entries whose `absPath` is no longer inside the
+ * current workspace (e.g. user switched workspace dir, or moved the file
+ * out of it). Attachment-source entries are NOT subject to this check —
+ * they live in `<uid>/cloud/chat_attachments/`, separate from workspace.
+ * Without `workspacePath` the call behaves exactly as before. */
+export async function pruneOrphans(
+ userId: string,
+ opts?: { workspacePath?: string },
+): Promise<{ deleted: number }> {
const root = userFileCacheDir(userId);
let deleted = 0;
let items: fs.Dirent[];
try { items = fs.readdirSync(root, { withFileTypes: true }); }
catch { return { deleted: 0 }; }
+ const wsRoot = opts?.workspacePath ? path.resolve(opts.workspacePath) : '';
+
for (const e of items) {
if (!e.isDirectory()) continue;
const dir = path.join(root, e.name);
@@ -452,6 +464,7 @@ export async function pruneOrphans(userId: string): Promise<{ deleted: number }>
!meta ? 'no-meta' :
meta.cacheVersion !== EXTRACT_CACHE_VERSION ? 'version' :
!safeExistsSync(meta.absPath) ? 'orphan' :
+ (wsRoot && meta.source === 'workspace' && !_isUnder(meta.absPath, wsRoot)) ? 'out-of-workspace' :
null;
if (reason) {
removeDir(dir);
@@ -463,6 +476,13 @@ export async function pruneOrphans(userId: string): Promise<{ deleted: number }>
return { deleted };
}
+/** True iff `abs` is `root` itself or any descendant of it. Uses
+ * `path.relative` so it's robust against trailing slashes and `..`. */
+function _isUnder(abs: string, root: string): boolean {
+ const rel = path.relative(root, path.resolve(abs));
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+}
+
/** Drop all cache entries tagged with the given cid. Called from
* chat_attachments.purgeByCid when a conversation is deleted. */
export async function purgeFileCacheByCid(
diff --git a/src/main/features/user_workspace.ts b/src/main/features/user_workspace.ts
index 5b57e0f7..2e459f1f 100644
--- a/src/main/features/user_workspace.ts
+++ b/src/main/features/user_workspace.ts
@@ -19,6 +19,7 @@ import { dialog, BrowserWindow, shell } from 'electron';
import { DEFAULT_USER_WORKSPACE, userWorkspaceConfigFile } from '../paths';
import { createLogger } from '../logger';
import { t } from '../i18n';
+import { pruneOrphans } from './file_indexer';
const log = createLogger('user-workspace');
@@ -127,6 +128,7 @@ export function setWorkspacePath(
recentPaths: recents.slice(0, MAX_RECENT),
});
log.info('workspace path updated', { userId, path: resolved });
+ _sweepFileCacheForWorkspace(userId, resolved);
return { ok: true, path: resolved };
}
@@ -148,9 +150,25 @@ export function resetWorkspacePath(userId: string): { ok: true; path: string } {
recentPaths: recents.slice(0, MAX_RECENT),
});
log.info('workspace path reset to default', { userId });
+ _sweepFileCacheForWorkspace(userId, DEFAULT_USER_WORKSPACE);
return { ok: true, path: DEFAULT_USER_WORKSPACE };
}
+/** Workspace switched — drop file_cache entries whose source lives outside
+ * the new workspace. Fire-and-forget; cache pruning failure must not
+ * fail the user-visible "switch workspace" action. */
+function _sweepFileCacheForWorkspace(userId: string, workspacePath: string): void {
+ pruneOrphans(userId, { workspacePath })
+ .then((r) => {
+ if (r.deleted > 0) {
+ log.info(`file_cache sweep on workspace switch deleted=${r.deleted}`, { userId, workspacePath });
+ }
+ })
+ .catch((err) => {
+ log.warn(`file_cache sweep on workspace switch failed: ${(err as Error).message}`, { userId, workspacePath });
+ });
+}
+
/**
* Return full workspace info for rendering the dropdown:
* current effective path, default path, and recent paths (validated).
diff --git a/test/main/features/file_indexer.test.ts b/test/main/features/file_indexer.test.ts
index bb7992f4..c0483dc0 100644
--- a/test/main/features/file_indexer.test.ts
+++ b/test/main/features/file_indexer.test.ts
@@ -269,4 +269,44 @@ describe('file_indexer › invalidate + purge + prune', () => {
expect(r.deleted).toBe(1);
expect(fs.readdirSync(userFileCacheRoot()).length).toBe(0);
});
+
+ it('pruneOrphans with workspacePath drops workspace entries outside the new workspace', async () => {
+ const m = await loadMod();
+
+ // Two workspaces: ws-a and ws-b. Cache an entry sourced from ws-a,
+ // then switch to ws-b and assert ws-a's entry gets dropped while
+ // ws-b's entry stays.
+ const wsA = path.join(tmpDir, 'ws-a'); fs.mkdirSync(wsA, { recursive: true });
+ const wsB = path.join(tmpDir, 'ws-b'); fs.mkdirSync(wsB, { recursive: true });
+ const aFile = path.join(wsA, 'a.pdf');
+ const bFile = path.join(wsB, 'b.pdf');
+ fs.writeFileSync(aFile, makeMinimalPdf(['A']));
+ fs.writeFileSync(bFile, makeMinimalPdf(['B']));
+
+ await m.statFile(UID, aFile);
+ await m.statFile(UID, bFile);
+ expect(fs.readdirSync(userFileCacheRoot()).length).toBe(2);
+
+ const r = await m.pruneOrphans(UID, { workspacePath: wsB });
+ expect(r.deleted).toBe(1);
+ expect(fs.readdirSync(userFileCacheRoot()).length).toBe(1);
+ });
+
+ it('pruneOrphans with workspacePath spares attachment-source entries even when outside', async () => {
+ const m = await loadMod();
+ const cid = 'cattach';
+ const att = attachmentFile(cid, 'a.pdf', makeMinimalPdf(['X']));
+ // source/cid are auto-derived from the absPath being inside chat_attachments
+ await m.statFile(UID, att);
+ expect(fs.readdirSync(userFileCacheRoot()).length).toBe(1);
+
+ // Pick a workspacePath that doesn't contain the attachment dir;
+ // attachments live in <uid>/cloud/chat_attachments/, not in the
+ // workspace, but they must NOT be pruned by the workspace check.
+ const wsElsewhere = path.join(tmpDir, 'ws-elsewhere');
+ fs.mkdirSync(wsElsewhere, { recursive: true });
+ const r = await m.pruneOrphans(UID, { workspacePath: wsElsewhere });
+ expect(r.deleted).toBe(0);
+ expect(fs.readdirSync(userFileCacheRoot()).length).toBe(1);
+ });
});