diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index b120f9feb5e5a..5d6c8b7304a0b 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -5325,6 +5325,8 @@ interface ClaudeLiveQueryContext { // Per process, not per session: a relative temp dir follows the cwd this CLI // was launched in, and a later turn's cwd can differ. readonly taskOutputRoot: string | undefined; + readonly taskOutputCwd: string | null; + readonly taskOutputProjectBySession: Map; } interface ActiveClaudeToolCall { @@ -11609,6 +11611,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( root: liveQuery.taskOutputRoot, sessionId: message.session_id, taskId: message.task_id, + cwd: liveQuery.taskOutputCwd, + projectCache: liveQuery.taskOutputProjectBySession, stop, onChunk: (chunk) => emitProviderEvent({ @@ -13372,6 +13376,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( resolvedTurnCwd, hostPlatform, ), + taskOutputCwd: resolvedTurnCwd, + taskOutputProjectBySession: new Map(), }; // One step, so the replaced process cannot exit between the install and the handoff. yield* Ref.update(queryContext, (replaced) => { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts index 51c9a7848f100..5a69ad378dcbf 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts @@ -127,6 +127,215 @@ describe("tailClaudeTaskOutput", () => { assert.deepEqual(chunks, ["one\n", "two\n"]); }).pipe(Effect.provide(NodeServices.layer)), ); + + it.live("checks the cwd project slug before scanning root and reuses cached project dirs", () => + Effect.gen(function* () { + const baseFs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* baseFs.makeTempDirectoryScoped({ prefix: "claude-task-output-" }); + for (let i = 0; i < 20; i += 1) { + yield* baseFs.makeDirectory(path.join(root, `unrelated-dir-${i}`), { recursive: true }); + yield* baseFs.writeFileString(path.join(root, `unrelated-file-${i}.log`), "x"); + } + const cwd = path.resolve("/private/tmp/project"); + const slug = cwd.replace(/[^a-zA-Z0-9]/g, "-"); + const tasks = path.join(root, slug, SESSION_ID, "tasks"); + const file = path.join(tasks, `${TASK_ID}.output`); + yield* baseFs.makeDirectory(tasks, { recursive: true }); + yield* baseFs.writeFileString(file, "from-cwd\n"); + + const lateTaskId = "blatetask"; + const lateFile = path.join(tasks, `${lateTaskId}.output`); + // The late file appears right after the first probe misses it, so the next poll must find it. + let createLateFileOnProbe = false; + let readDirCount = 0; + let existsCount = 0; + const countingFs: FileSystem.FileSystem = { + ...baseFs, + readDirectory: (target, options) => { + if (target === root) readDirCount += 1; + return baseFs.readDirectory(target, options); + }, + exists: (target) => { + existsCount += 1; + if (createLateFileOnProbe && target === lateFile) { + createLateFileOnProbe = false; + return baseFs.writeFileString(lateFile, "late\n").pipe(Effect.as(false)); + } + return baseFs.exists(target); + }, + }; + + const cache = new Map(); + const chunks: Array = []; + const stop = yield* Deferred.make(); + const first = yield* Deferred.make(); + const fiber = yield* tailClaudeTaskOutput({ + root, + sessionId: SESSION_ID, + taskId: TASK_ID, + cwd, + projectCache: cache, + stop, + onChunk: (chunk) => + Effect.sync(() => chunks.push(chunk)).pipe( + Effect.andThen(Deferred.succeed(first, undefined)), + ), + }).pipe(Effect.provideService(FileSystem.FileSystem, countingFs), Effect.forkScoped); + yield* Deferred.await(first); + yield* Deferred.succeed(stop, undefined); + yield* Fiber.join(fiber); + + assert.deepEqual(chunks, ["from-cwd\n"]); + assert.equal(readDirCount, 0); + assert.equal(existsCount, 1); + assert.equal(cache.get(SESSION_ID), slug); + + // Missing output file when session dir already exists under cwd slug should not scan root. + readDirCount = 0; + existsCount = 0; + createLateFileOnProbe = true; + const lateChunks: Array = []; + const lateStop = yield* Deferred.make(); + const lateFirst = yield* Deferred.make(); + const lateFiber = yield* tailClaudeTaskOutput({ + root, + sessionId: SESSION_ID, + taskId: lateTaskId, + cwd, + projectCache: cache, + stop: lateStop, + onChunk: (chunk) => + Effect.sync(() => lateChunks.push(chunk)).pipe( + Effect.andThen(Deferred.succeed(lateFirst, undefined)), + ), + }).pipe(Effect.provideService(FileSystem.FileSystem, countingFs), Effect.forkScoped); + yield* Deferred.await(lateFirst); + yield* Deferred.succeed(lateStop, undefined); + yield* Fiber.join(lateFiber); + assert.deepEqual(lateChunks, ["late\n"]); + assert.equal(readDirCount, 0); + + // Fallback scan for a non-matching project dir caches it for subsequent tasks in the session. + const otherSession = "1d92cc39-9e89-4889-bd22-3de9880233d4"; + const otherTasks = path.join(root, "custom-slug", otherSession, "tasks"); + yield* baseFs.makeDirectory(otherTasks, { recursive: true }); + yield* baseFs.writeFileString(path.join(otherTasks, "btask1.output"), "one\n"); + yield* baseFs.writeFileString(path.join(otherTasks, "btask2.output"), "two\n"); + + const firstFallbackChunks: Array = []; + const stop1 = yield* Deferred.make(); + const got1 = yield* Deferred.make(); + const fiber1 = yield* tailClaudeTaskOutput({ + root, + sessionId: otherSession, + taskId: "btask1", + projectCache: cache, + stop: stop1, + onChunk: (chunk) => + Effect.sync(() => firstFallbackChunks.push(chunk)).pipe( + Effect.andThen(Deferred.succeed(got1, undefined)), + ), + }).pipe(Effect.provideService(FileSystem.FileSystem, countingFs), Effect.forkScoped); + yield* Deferred.await(got1); + yield* Deferred.succeed(stop1, undefined); + yield* Fiber.join(fiber1); + assert.deepEqual(firstFallbackChunks, ["one\n"]); + assert.equal(cache.get(otherSession), "custom-slug"); + + readDirCount = 0; + existsCount = 0; + const secondFallbackChunks: Array = []; + const stop2 = yield* Deferred.make(); + const got2 = yield* Deferred.make(); + const fiber2 = yield* tailClaudeTaskOutput({ + root, + sessionId: otherSession, + taskId: "btask2", + projectCache: cache, + stop: stop2, + onChunk: (chunk) => + Effect.sync(() => secondFallbackChunks.push(chunk)).pipe( + Effect.andThen(Deferred.succeed(got2, undefined)), + ), + }).pipe(Effect.provideService(FileSystem.FileSystem, countingFs), Effect.forkScoped); + yield* Deferred.await(got2); + yield* Deferred.succeed(stop2, undefined); + yield* Fiber.join(fiber2); + assert.deepEqual(secondFallbackChunks, ["two\n"]); + assert.equal(readDirCount, 0); + assert.equal(existsCount, 1); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("aborts root directory scan immediately when stop completes during locate", () => + Effect.gen(function* () { + const baseFs = yield* FileSystem.FileSystem; + const root = yield* baseFs.makeTempDirectoryScoped({ prefix: "claude-task-output-" }); + const stop = yield* Deferred.make(); + let existsCount = 0; + const fakeFs: FileSystem.FileSystem = { + ...baseFs, + readDirectory: (target, options) => + target === root + ? Effect.succeed(Array.from({ length: 20 }, (_, index) => `project-${index}`)) + : baseFs.readDirectory(target, options), + exists: () => + Effect.suspend(() => { + existsCount += 1; + if (existsCount === 2) { + return Deferred.succeed(stop, undefined).pipe(Effect.as(false)); + } + return Effect.succeed(false); + }), + }; + + yield* tailClaudeTaskOutput({ + root, + sessionId: SESSION_ID, + taskId: TASK_ID, + stop, + onChunk: () => Effect.void, + }).pipe(Effect.provideService(FileSystem.FileSystem, fakeFs)); + + assert.equal(existsCount, 2); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect( + "skips the task-file probe when stop completes during the session-directory check", + () => + Effect.gen(function* () { + const baseFs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* baseFs.makeTempDirectoryScoped({ prefix: "claude-task-output-" }); + const stop = yield* Deferred.make(); + const probes: Array = []; + const fakeFs: FileSystem.FileSystem = { + ...baseFs, + readDirectory: (target, options) => + target === root ? Effect.succeed(["project-0"]) : baseFs.readDirectory(target, options), + exists: (target) => + Effect.suspend(() => { + probes.push(target); + // The session directory exists; stop lands while that check is in flight. + return target === path.join(root, "project-0", SESSION_ID) + ? Deferred.succeed(stop, undefined).pipe(Effect.as(true)) + : Effect.succeed(false); + }), + }; + + yield* tailClaudeTaskOutput({ + root, + sessionId: SESSION_ID, + taskId: TASK_ID, + stop, + onChunk: () => Effect.void, + }).pipe(Effect.provideService(FileSystem.FileSystem, fakeFs)); + + assert.deepEqual(probes, [path.join(root, "project-0", SESSION_ID)]); + }).pipe(Effect.provide(NodeServices.layer)), + ); }); describe("claudeTaskOutputRoot", () => { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.ts index 7eac250d7afde..ce9e3b994e3e5 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.ts @@ -34,23 +34,106 @@ export function claudeTaskOutputRoot( return path.resolve(cwd ?? ".", base, `claude-${uid}`); } +const claudeProjectSlug = (cwd: string, path: Path.Path): string => + path.resolve(cwd).replace(/[^a-zA-Z0-9]/g, "-"); + +const taskOutputFile = ( + path: Path.Path, + root: string, + project: string, + sessionId: string, + taskId: string, +): string => path.join(root, project, sessionId, "tasks", `${taskId}.output`); + const locate = Effect.fn("ClaudeTaskOutputTail.locate")(function* (input: { readonly root: string; readonly sessionId: string; readonly taskId: string; + readonly stop: Deferred.Deferred; + readonly abortOnStop: boolean; + readonly cwd: string | undefined; + readonly projectCache: Map; + readonly realSlugRef: { resolved: boolean; value: string | undefined }; }) { + const shouldAbort = () => + input.abortOnStop ? Deferred.isDone(input.stop) : Effect.succeed(false); + if (yield* shouldAbort()) return Option.none(); const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const exists = (target: string) => + fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false)); + const probed = new Set(); + + // Runs inside the ClaudeTaskOutputTail.locate span. + const probeKnownProject = Effect.fnUntraced(function* ( + project: string, + rememberSessionDir: boolean, + ) { + probed.add(project); + const candidate = taskOutputFile(path, input.root, project, input.sessionId, input.taskId); + if (yield* exists(candidate)) { + input.projectCache.set(input.sessionId, project); + return { kind: "found" as const, file: candidate }; + } + if (yield* shouldAbort()) return { kind: "aborted" as const }; + if (yield* exists(path.join(input.root, project, input.sessionId))) { + if (rememberSessionDir) input.projectCache.set(input.sessionId, project); + return { kind: "session_exists" as const }; + } + return { kind: "missing" as const }; + }); + + // 1. Check the cached project directory for this session first. + const cachedProject = input.projectCache.get(input.sessionId); + if (cachedProject !== undefined) { + const result = yield* probeKnownProject(cachedProject, false); + if (result.kind === "found") return Option.some(result.file); + if (result.kind === "session_exists" || result.kind === "aborted") return Option.none(); + input.projectCache.delete(input.sessionId); + } + + // 2. Check Claude Code's deterministic cwd slug before scanning root. + if (input.cwd !== undefined) { + const directSlug = claudeProjectSlug(input.cwd, path); + if (!probed.has(directSlug)) { + if (yield* shouldAbort()) return Option.none(); + const result = yield* probeKnownProject(directSlug, true); + if (result.kind === "found") return Option.some(result.file); + if (result.kind === "session_exists" || result.kind === "aborted") + return Option.none(); + } + if (!input.realSlugRef.resolved) { + input.realSlugRef.resolved = true; + const realCwd = yield* fileSystem + .realPath(input.cwd) + .pipe(Effect.orElseSucceed(() => undefined)); + if (realCwd !== undefined) { + const slug = claudeProjectSlug(realCwd, path); + if (slug !== directSlug) input.realSlugRef.value = slug; + } + } + const realSlug = input.realSlugRef.value; + if (realSlug !== undefined && !probed.has(realSlug)) { + if (yield* shouldAbort()) return Option.none(); + const result = yield* probeKnownProject(realSlug, true); + if (result.kind === "found") return Option.some(result.file); + if (result.kind === "session_exists" || result.kind === "aborted") + return Option.none(); + } + } + + // 3. Fall back to scanning root when cwd is absent or does not match Claude's directory slug. + if (yield* shouldAbort()) return Option.none(); const projects = yield* fileSystem.readDirectory(input.root).pipe(Effect.orElseSucceed(() => [])); for (const project of projects) { - const candidate = path.join( - input.root, - project, - input.sessionId, - "tasks", - `${input.taskId}.output`, - ); - if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) { + if (probed.has(project)) continue; + if (yield* shouldAbort()) return Option.none(); + // Unrelated project dirs and regular files fail in one stat before probing tasks/.output. + if (!(yield* exists(path.join(input.root, project, input.sessionId)))) continue; + if (yield* shouldAbort()) return Option.none(); + const candidate = taskOutputFile(path, input.root, project, input.sessionId, input.taskId); + if (yield* exists(candidate)) { + input.projectCache.set(input.sessionId, project); return Option.some(candidate); } } @@ -64,6 +147,8 @@ export const tailClaudeTaskOutput = Effect.fn("ClaudeTaskOutputTail.tail")(funct readonly taskId: string; readonly stop: Deferred.Deferred; readonly onChunk: (chunk: string) => Effect.Effect; + readonly cwd?: string | null | undefined; + readonly projectCache?: Map | undefined; }) { const fileSystem = yield* FileSystem.FileSystem; const pause = Deferred.await(input.stop).pipe( @@ -73,9 +158,24 @@ export const tailClaudeTaskOutput = Effect.fn("ClaudeTaskOutputTail.tail")(funct orElse: () => Effect.succeed(false), }), ); + const projectCache = input.projectCache ?? new Map(); + const trimmedCwd = input.cwd?.trim(); + const cwd = trimmedCwd && trimmedCwd.length > 0 ? trimmedCwd : undefined; + const realSlugRef = { resolved: false, value: undefined as string | undefined }; let file = Option.none(); for (let attempt = 0; Option.isNone(file); attempt += 1) { - file = yield* locate(input); + const stoppedBeforeLocate = yield* Deferred.isDone(input.stop); + if (attempt > 0 && stoppedBeforeLocate) return; + file = yield* locate({ + root: input.root, + sessionId: input.sessionId, + taskId: input.taskId, + stop: input.stop, + abortOnStop: !stoppedBeforeLocate, + cwd, + projectCache, + realSlugRef, + }); if (Option.isSome(file)) break; if (attempt + 1 >= MAX_LOCATE_ATTEMPTS || (yield* pause)) return; }