Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix: poll for Cursor transcripts instead of watching the projects tree

Kelvinf9079962b875
diff --git a/cli/src/engines/cursor/discovery.spec.ts b/cli/src/engines/cursor/discovery.spec.ts
new file mode 100644
index 000000000..fbe8e026a
--- /dev/null
+++ b/cli/src/engines/cursor/discovery.spec.ts
@@ -0,0 +1,183 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+// The tree below a Cursor home is the wrong thing to watch: one macOS box had 6,849 folders under
+// ~/.cursor/projects for 10 transcripts, and a recursive watcher of that size stalls the daemon's
+// event loop (libuv rebuilds its single FSEvents stream on every add/remove). The discovery must
+// never reach for a directory watcher again, whichever library it would be.
+vi.mock('chokidar', () => ({
+ default: { watch: () => { throw new Error('cursor discovery must not watch the projects tree') } },
+}))
+
+const SESSION_A = 'aaaaaaaa-1111-4222-8333-444444444444'
+const SESSION_B = 'bbbbbbbb-1111-4222-8333-444444444444'
+// Fast enough that a test waiting on a sweep finishes in milliseconds, slow enough that a sweep
+// never overlaps the one before it on a loaded CI box.
+const POLL_MS = 20
+
+let cursorHome = ''
+
+function writeTranscript(project: string, sessionId: string): string {
+ const dir = join(cursorHome, 'projects', project, 'agent-transcripts', sessionId)
+ mkdirSync(dir, { recursive: true })
+ const path = join(dir, `${sessionId}.jsonl`)
+ writeFileSync(path, '{"role":"user"}\n')
+ return path
+}
+
+// `validTranscriptPath` checks candidates against the process-wide `env.CURSOR_HOME`, which the config
+// module resolves once at import time — so the module graph is reset and re-imported per test with
+// the throwaway home already in the environment (the same shape registry.spec.ts uses).
+async function loadDiscovery() {
+ vi.resetModules()
+ process.env.CURSOR_HOME = cursorHome
+ return import('./discovery.js')
+}
+
+async function settle(): Promise<void> {
+ await new Promise((resolve) => setTimeout(resolve, POLL_MS * 4))
+}
+
+describe('CursorTranscriptDiscovery', () => {
+ beforeEach(() => {
+ cursorHome = mkdtempSync(join(tmpdir(), 'cursor-discovery-'))
+ mkdirSync(join(cursorHome, 'projects'), { recursive: true })
+ })
+
+ afterEach(() => {
+ delete process.env.CURSOR_HOME
+ rmSync(cursorHome, { recursive: true, force: true })
+ })
+
+ it('reports a transcript that already exists without polling', async () => {
+ const { CursorTranscriptDiscovery } = await loadDiscovery()
+ const expected = writeTranscript('proj-1', SESSION_A)
+ const onFound = vi.fn()
+ const discovery = new CursorTranscriptDiscovery(cursorHome, onFound, POLL_MS)
+ await discovery.start()
+
+ await discovery.add(SESSION_A)
+
+ expect(onFound).toHaveBeenCalledTimes(1)
+ expect(onFound).toHaveBeenCalledWith(SESSION_A, expected)
+ expect(discovery.isPolling).toBe(false)
+ await discovery.stop()
+ })
+
+ it('polls only while a session is pending and reports the transcript once it appears', async () => {
+ const { CursorTranscriptDiscovery } = await loadDiscovery()
+ const onFound = vi.fn()
+ const discovery = new CursorTranscriptDiscovery(cursorHome, onFound, POLL_MS)
+ await discovery.start()
+
+ await discovery.add(SESSION_A)
+ expect(onFound).not.toHaveBeenCalled()
+ expect(discovery.isPolling).toBe(true)
+
+ const expected = writeTranscript('proj-late', SESSION_A)
+ await vi.waitFor(() => expect(onFound).toHaveBeenCalledWith(SESSION_A, expected))
+
+ // Found once, then the poll shuts itself off — nothing is left to look for.
+ await settle()
+ expect(onFound).toHaveBeenCalledTimes(1)
+ expect(discovery.isPolling).toBe(false)
+ await discovery.stop()
+ })
+
+ it('finds transcripts added before start() once polling begins', async () => {
+ const { CursorTranscriptDiscovery } = await loadDiscovery()
+ const onFound = vi.fn()
+ const discovery = new CursorTranscriptDiscovery(cursorHome, onFound, POLL_MS)
+
+ await discovery.add(SESSION_A)
+ expect(discovery.isPolling).toBe(false)
+ const expected = writeTranscript('proj-1', SESSION_A)
+
+ await discovery.start()
+ await vi.waitFor(() => expect(onFound).toHaveBeenCalledWith(SESSION_A, expected))
+ await discovery.stop()
+ })
+
+ it('stops looking for a session that was removed', async () => {
+ const { CursorTranscriptDiscovery } = await loadDiscovery()
+ const onFound = vi.fn()
+ const discovery = new CursorTranscriptDiscovery(cursorHome, onFound, POLL_MS)
+ await discovery.start()
+ await discovery.add(SESSION_A)
+ await discovery.add(SESSION_B)
+
+ discovery.remove(SESSION_A)
+ writeTranscript('proj-1', SESSION_A)
+ const expectedB = writeTranscript('proj-2', SESSION_B)
+
+ await vi.waitFor(() => expect(onFound).toHaveBeenCalledWith(SESSION_B, expectedB))
+ await settle()
+ expect(onFound).toHaveBeenCalledTimes(1)
+ expect(discovery.isPolling).toBe(false)
+ await discovery.stop()
+ })
+
+ it('reports nothing after stop()', async () => {
+ const { CursorTranscriptDiscovery } = await loadDiscovery()
+ const onFound = vi.fn()
+ const discovery = new CursorTranscriptDiscovery(cursorHome, onFound, POLL_MS)
+ await discovery.start()
+ await discovery.add(SESSION_A)
+
+ await discovery.stop()
+ expect(discovery.isPolling).toBe(false)
+ writeTranscript('proj-1', SESSION_A)
+
+ await settle()
+ expect(onFound).not.toHaveBeenCalled()
+ })
+
+ it('drops what an add() in flight finds once stop() has run', async () => {
+ const { CursorTranscriptDiscovery } = await loadDiscovery()
+ writeTranscript('proj-1', SESSION_A)
+ const onFound = vi.fn()
+ const discovery = new CursorTranscriptDiscovery(cursorHome, onFound, POLL_MS)
+ await discovery.start()
+
+ const adding = discovery.add(SESSION_A) // its lookup is now awaiting the disk
+ await discovery.stop()
+ await adding
+
+ expect(onFound).not.toHaveBeenCalled()
+ expect(discovery.isPolling).toBe(false)
+ })
+
+ it('ignores session ids that cannot name a transcript', async () => {
+ const { CursorTranscriptDiscovery } = await loadDiscovery()
+ const onFound = vi.fn()
+ const discovery = new CursorTranscriptDiscovery(cursorHome, onFound, POLL_MS)
+ await discovery.start()
+
+ await discovery.add('../../etc/passwd')
+ await discovery.add('short')
+
+ expect(discovery.isPolling).toBe(false)
+ expect(onFound).not.toHaveBeenCalled()
+ await discovery.stop()
+ })
+
+ it('never watches the projects tree, however large it is', async () => {
+ const { CursorTranscriptDiscovery } = await loadDiscovery()
+ // A thousand unrelated project folders — the shape of a Cursor home on a machine that has opened
+ // many repos. The old recursive watcher registered every one of these with the OS.
+ for (let i = 0; i < 1000; i++) mkdirSync(join(cursorHome, 'projects', `proj-${i}`, 'deep', 'er'), { recursive: true })
+ const onFound = vi.fn()
+ const discovery = new CursorTranscriptDiscovery(cursorHome, onFound, POLL_MS)
+
+ const started = Date.now()
+ await discovery.start()
+ await discovery.add(SESSION_A)
+ const expected = writeTranscript('proj-999', SESSION_A)
+ await vi.waitFor(() => expect(onFound).toHaveBeenCalledWith(SESSION_A, expected))
+ await discovery.stop()
+
+ expect(Date.now() - started).toBeLessThan(2000)
+ })
+})
diff --git a/cli/src/engines/cursor/discovery.ts b/cli/src/engines/cursor/discovery.ts
index d50734d55..c24ea0683 100644
--- a/cli/src/engines/cursor/discovery.ts
+++ b/cli/src/engines/cursor/discovery.ts
@@ -1,74 +1,138 @@
-import { mkdir, readdir } from 'node:fs/promises'
+import { access, readdir } from 'node:fs/promises'
import { join } from 'node:path'
-import chokidar, { type FSWatcher } from 'chokidar'
import { validTranscriptPath } from '../../lib/registry.js'
const SESSION_RE = /^[0-9a-f-]{16,}$/i
+/**
+ * How often a pending session is re-checked for a transcript that has since appeared. A Cursor
+ * session is pending only between its process turning up and its first transcript write, so this
+ * is a short-lived poll — and no poll runs at all while nothing is pending.
+ */
+export const CURSOR_TRANSCRIPT_POLL_MS = 1000
+
+/**
+ * Finds the transcript of a Cursor session whose process is already known but whose JSONL has not
+ * been written yet.
+ *
+ * This POLLS rather than watching `<CURSOR_HOME>/projects`. A recursive watcher over that tree was
+ * the daemon's single worst behaviour on macOS: one machine had 6,849 folders under it for 10
+ * transcripts, and libuv keeps every watched path in ONE FSEvents stream that it tears down and
+ * recreates on each add or remove — thousands of adds meant the event loop spent minutes inside
+ * FSEventStreamCreate, `FSEventStreamStart` began failing (surfaced by libuv as `EMFILE` to every
+ * handle at once, 2,700 errors a minute in the log), and the loopback API the desktop app relies on
+ * stopped answering: "This computer · Offline", `agent_create` timing out. A readdir of the project
+ * list plus one stat per pending session, once a second, finds the same file for no standing cost.
+ */
export class CursorTranscriptDiscovery {
- private watcher: FSWatcher | null = null
private readonly pending = new Set<string>()
+ private timer: NodeJS.Timeout | null = null
+ private started = false
+ private sweeping = false
+ /** Bumped by stop(); an add() that started before the bump discards what it finds. */
+ private epoch = 0
constructor(
private readonly cursorHome: string,
private readonly onFound: (sessionId: string, transcriptPath: string) => void,
+ private readonly pollMs: number = CURSOR_TRANSCRIPT_POLL_MS,
) {}
+ /** Whether a poll timer is live — true only while at least one session is pending. */
+ get isPolling(): boolean {
+ return this.timer !== null
+ }
+
async start(): Promise<void> {
- if (this.watcher) return
- const root = join(this.cursorHome, 'projects')
- await mkdir(root, { recursive: true })
- this.watcher = chokidar.watch(root, {
- ignoreInitial: false,
- depth: 5,
- // Cursor also places Unix sockets below project roots. Watching those can fail on macOS and
- // is unnecessary: discovery consumes only transcript JSONL files.
- ignored: (path, info) => Boolean(info && !info.isDirectory() && !path.endsWith('.jsonl')),
- })
- this.watcher
- .on('add', (path: string) => this.inspect(path))
- .on('change', (path: string) => this.inspect(path))
- .on('error', (err: unknown) => console.error('[cursor-discovery] watcher error:', err))
+ if (this.started) return
+ this.started = true
+ this.schedule()
}
async add(sessionId: string): Promise<void> {
if (!SESSION_RE.test(sessionId)) return
+ const epoch = this.epoch
const found = await findCursorTranscript(this.cursorHome, sessionId)
+ // Re-checked after the await: a stop() that ran while the lookup was in flight owns this session
+ // now — neither a callback nor a pending entry may outlive it.
+ if (epoch !== this.epoch) return
if (found) {
this.onFound(sessionId, found)
return
}
this.pending.add(sessionId)
+ this.schedule()
}
remove(sessionId: string): void {
this.pending.delete(sessionId)
+ if (this.pending.size === 0) this.clearTimer()
}
async stop(): Promise<void> {
+ this.epoch++
this.pending.clear()
- await this.watcher?.close()
- this.watcher = null
+ this.clearTimer()
+ this.started = false
}
- private inspect(path: string): void {
- const normalized = path.replace(/\\/g, '/')
- const match = /\/agent-transcripts\/([^/]+)\/\1\.jsonl$/.exec(normalized)
- const sessionId = match?.[1]
- if (!sessionId || !this.pending.has(sessionId) || !validTranscriptPath('cursor', path)) return
- this.pending.delete(sessionId)
- this.onFound(sessionId, path)
+ private schedule(): void {
+ if (!this.started || this.timer || this.pending.size === 0) return
+ this.timer = setInterval(() => { void this.sweep() }, this.pollMs)
+ // A pending session must never be what keeps the daemon alive through shutdown.
+ this.timer.unref()
+ }
+
+ private clearTimer(): void {
+ if (!this.timer) return
+ clearInterval(this.timer)
+ this.timer = null
+ }
+
+ private async sweep(): Promise<void> {
+ if (this.sweeping) return // a slow disk must not stack sweeps on top of each other
+ this.sweeping = true
+ try {
+ // One listing per sweep, shared by every pending session.
+ const projects = await listProjects(this.cursorHome)
+ for (const sessionId of [...this.pending]) {
+ const found = await transcriptAmong(this.cursorHome, projects, sessionId)
+ // Re-checked after the await: remove()/stop() may have run while the lookup was in flight.
+ if (!found || !this.pending.has(sessionId)) continue
+ this.pending.delete(sessionId)
+ this.onFound(sessionId, found)
+ }
+ } finally {
+ this.sweeping = false
+ if (this.pending.size === 0) this.clearTimer()
+ }
}
}
export async function findCursorTranscript(cursorHome: string, sessionId: string): Promise<string | null> {
if (!SESSION_RE.test(sessionId)) return null
+ return transcriptAmong(cursorHome, await listProjects(cursorHome), sessionId)
+}
+
+/** The project folders below `<cursorHome>/projects`; none when the tree does not exist yet. */
+async function listProjects(cursorHome: string): Promise<string[]> {
+ try { return await readdir(join(cursorHome, 'projects')) } catch { return [] }
+}
+
+async function transcriptAmong(cursorHome: string, projects: string[], sessionId: string): Promise<string | null> {
const root = join(cursorHome, 'projects')
- let projects: string[]
- try { projects = await readdir(root) } catch { return null }
for (const project of projects) {
const candidate = join(root, project, 'agent-transcripts', sessionId, `${sessionId}.jsonl`)
+ // Existence is probed asynchronously first. validTranscriptPath resolves two realpaths
+ // SYNCHRONOUSLY, and paying that for every project folder — hundreds on a machine that has
+ // opened many repos — once a second is a visible event-loop hitch. Only a candidate that is
+ // actually there pays for the validation.
+ if (!(await exists(candidate))) continue
if (validTranscriptPath('cursor', candidate)) return candidate
}
return null
}
+
+async function exists(path: string): Promise<boolean> {
+ try { await access(path); return true } catch { return false }
+}