Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

perf(desktop): cache Claude transcript lookups (#1150)

hushaowu-rh1a7ce7b355bc
diff --git a/apps/desktop/src/main/maker-orchestration/__tests__/claudeTranscriptAnchors.test.ts b/apps/desktop/src/main/maker-orchestration/__tests__/claudeTranscriptAnchors.test.ts
new file mode 100644
index 0000000000..395fbb3ef5
--- /dev/null
+++ b/apps/desktop/src/main/maker-orchestration/__tests__/claudeTranscriptAnchors.test.ts
@@ -0,0 +1,94 @@
+import { mkdtemp, mkdir, rm, writeFile, unlink, realpath } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+import {
+ findClaudeSessionJsonl,
+ __resetClaudeTranscriptPathCacheForTesting,
+} from '../claudeTranscriptAnchors';
+
+const roots: string[] = [];
+
+afterEach(async () => {
+ __resetClaudeTranscriptPathCacheForTesting();
+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
+});
+
+async function createRoot(): Promise<string> {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-transcript-anchor-'));
+ roots.push(root);
+ return root;
+}
+
+async function writeTranscript(root: string, project: string, sessionId: string): Promise<string> {
+ const dir = path.join(root, project);
+ await mkdir(dir, { recursive: true });
+ const file = path.join(dir, `${sessionId}.jsonl`);
+ await writeFile(file, '{"uuid":"u1","type":"assistant"}\n');
+ return file;
+}
+
+describe('Claude transcript path lookup cache', () => {
+ it('uses a negative cache and retries after the miss TTL', async () => {
+ const root = await createRoot();
+ let now = 1_000;
+
+ await expect(findClaudeSessionJsonl('s1', undefined, root, () => now)).resolves.toBeNull();
+ const file = await writeTranscript(root, 'project-a', 's1');
+ await expect(findClaudeSessionJsonl('s1', undefined, root, () => now)).resolves.toBeNull();
+
+ now += 5_001;
+ await expect(findClaudeSessionJsonl('s1', undefined, root, () => now)).resolves.toBe(file);
+ });
+
+ it('invalidates a cached hit when the file disappears', async () => {
+ const root = await createRoot();
+ const file = await writeTranscript(root, 'project-a', 's1');
+ let now = 1_000;
+
+ await expect(findClaudeSessionJsonl('s1', undefined, root, () => now)).resolves.toBe(file);
+ await unlink(file);
+ const replacement = await writeTranscript(root, 'nested/project-b', 's1');
+ now += 1;
+
+ await expect(findClaudeSessionJsonl('s1', undefined, root, () => now)).resolves.toBe(replacement);
+ });
+
+ it('keeps config roots isolated', async () => {
+ const firstRoot = await createRoot();
+ const secondRoot = await createRoot();
+ const first = await writeTranscript(firstRoot, 'project-a', 's1');
+ const second = await writeTranscript(secondRoot, 'project-b', 's1');
+
+ await expect(findClaudeSessionJsonl('s1', undefined, firstRoot)).resolves.toBe(first);
+ await expect(findClaudeSessionJsonl('s1', undefined, secondRoot)).resolves.toBe(second);
+ });
+
+ it('rechecks the direct path after a cached fallback is discovered', async () => {
+ const root = await createRoot();
+ const workingDir = path.join(root, 'workspace');
+ await mkdir(workingDir, { recursive: true });
+ const fallback = await writeTranscript(root, 'fallback', 's1');
+ let now = 1_000;
+
+ await expect(findClaudeSessionJsonl('s1', workingDir, root, () => now)).resolves.toBe(fallback);
+ const normalizedWorkingDir = (await realpath(workingDir)).normalize('NFC');
+ const directProject = normalizedWorkingDir.replace(/[^a-zA-Z0-9]/g, '-').slice(0, 200);
+ const direct = await writeTranscript(root, directProject, 's1');
+ now += 1;
+
+ await expect(findClaudeSessionJsonl('s1', workingDir, root, () => now)).resolves.toBe(direct);
+ });
+
+ it('evicts the oldest cache entries at the capacity limit', async () => {
+ const root = await createRoot();
+ let now = 1_000;
+
+ for (let index = 0; index <= 500; index += 1) {
+ await expect(findClaudeSessionJsonl(`s${index}`, undefined, root, () => now)).resolves.toBeNull();
+ }
+
+ const first = await writeTranscript(root, 'first-project', 's0');
+ await expect(findClaudeSessionJsonl('s0', undefined, root, () => now)).resolves.toBe(first);
+ });
+});
diff --git a/apps/desktop/src/main/maker-orchestration/claudeTranscriptAnchors.ts b/apps/desktop/src/main/maker-orchestration/claudeTranscriptAnchors.ts
index f3f07409d2..af62f4600e 100644
--- a/apps/desktop/src/main/maker-orchestration/claudeTranscriptAnchors.ts
+++ b/apps/desktop/src/main/maker-orchestration/claudeTranscriptAnchors.ts
@@ -5,6 +5,17 @@ import path from 'node:path';
const PROJECT_KEY_MAX_LENGTH = 200;
const SYNTHETIC_BLOCK_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-0{10}\d{2}$/i;
const MAX_SCAN_DEPTH = 4;
+const TRANSCRIPT_PATH_CACHE_TTL_MS = 60_000;
+const TRANSCRIPT_MISS_CACHE_TTL_MS = 5_000;
+const MAX_TRANSCRIPT_PATH_CACHE_ENTRIES = 500;
+
+interface TranscriptPathCacheEntry {
+ filePath: string | null;
+ checkedAt: number;
+}
+
+const transcriptPathCache = new Map<string, TranscriptPathCacheEntry>();
+const transcriptPathInFlight = new Map<string, Promise<string | null>>();
type JsonObject = Record<string, unknown>;
@@ -82,18 +93,55 @@ async function scanProjectDirsForSession(projectsRoot: string, filename: string)
return visit(projectsRoot, 0);
}
-async function findClaudeSessionJsonl(
+/**
+ * JSONL 路径发现按 config root + workingDir + sdkSessionId 单飞并短时缓存。直接路径仍优先;
+ * 命中缓存每次先复核文件仍存在,删除/移动后立即回退扫描,不把过期绝对路径返回给 fork/rewind。
+ */
+export async function findClaudeSessionJsonl(
sdkSessionId: string,
workingDir: string | null | undefined,
projectsRoot: string,
+ now = Date.now,
): Promise<string | null> {
- const filename = `${sdkSessionId}.jsonl`;
+ const key = `${projectsRoot}\0${workingDir ?? ''}\0${sdkSessionId}`;
+
+ // Direct paths are cheap to check and authoritative whenever they appear;
+ // never let a cached scan result mask a transcript restored into workingDir.
if (workingDir) {
const normalized = await normalizedExistingPath(workingDir);
- const directPath = path.join(projectsRoot, sanitizeClaudeProjectKey(normalized), filename);
+ const directPath = path.join(projectsRoot, sanitizeClaudeProjectKey(normalized), `${sdkSessionId}.jsonl`);
if (await fileExists(directPath)) return directPath;
}
- return scanProjectDirsForSession(projectsRoot, filename);
+
+ const current = transcriptPathCache.get(key);
+ const ttlMs = current?.filePath ? TRANSCRIPT_PATH_CACHE_TTL_MS : TRANSCRIPT_MISS_CACHE_TTL_MS;
+ if (current && now() - current.checkedAt < ttlMs) {
+ if (!current.filePath || await fileExists(current.filePath)) return current.filePath;
+ transcriptPathCache.delete(key);
+ }
+ const existing = transcriptPathInFlight.get(key);
+ if (existing) return existing;
+
+ const task = scanProjectDirsForSession(projectsRoot, `${sdkSessionId}.jsonl`)
+ .then((filePath) => {
+ transcriptPathCache.set(key, { filePath, checkedAt: now() });
+ while (transcriptPathCache.size > MAX_TRANSCRIPT_PATH_CACHE_ENTRIES) {
+ const oldestKey = transcriptPathCache.keys().next().value;
+ if (oldestKey === undefined) break;
+ transcriptPathCache.delete(oldestKey);
+ }
+ return filePath;
+ })
+ .finally(() => {
+ if (transcriptPathInFlight.get(key) === task) transcriptPathInFlight.delete(key);
+ });
+ transcriptPathInFlight.set(key, task);
+ return task;
+}
+
+export function __resetClaudeTranscriptPathCacheForTesting(): void {
+ transcriptPathCache.clear();
+ transcriptPathInFlight.clear();
}
function uniqueTruthy(values: Array<string | undefined>): string[] {