diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index f83382d7531e3..0ff0271f44fb2 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -937,13 +937,14 @@ const ThreadWorkLogRow = function ThreadWorkLogRow( const warning = failureItem.failure.class === "usage_limit"; const timestamp = new Date(row.createdAt); const resetAt = failureItem.failure.resetAt; + // The reset time is the viewer's local time; naming the zone keeps it unambiguous. const resetTime = resetAt - ? new Date(resetAt).toLocaleString(undefined, { + ? `${new Date(resetAt).toLocaleString(undefined, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit", - }) + })} (${new Intl.DateTimeFormat().resolvedOptions().timeZone})` : null; const label = warning ? `Usage limit reached.${resetTime ? ` Retry after ${resetTime}.` : ""}` diff --git a/apps/server/src/cloud/CloudLink.lifecycle.test.ts b/apps/server/src/cloud/CloudLink.lifecycle.test.ts index 115ac732c5169..39971c81d8511 100644 --- a/apps/server/src/cloud/CloudLink.lifecycle.test.ts +++ b/apps/server/src/cloud/CloudLink.lifecycle.test.ts @@ -140,6 +140,7 @@ describe("releaseManagedTunnelOnShutdown", () => { readonly address?: HttpServer.HttpServer["Service"]["address"]; readonly respondEffect?: Effect.Effect; readonly getExisting?: CliTokenManager.CloudCliTokenManager["Service"]["getExisting"]; + readonly latestReachability?: ConnectReachability.ConnectReachability["Service"]["latest"]; } const writeLauncherState = (update: ServiceUpdateRecord) => @@ -165,7 +166,7 @@ describe("releaseManagedTunnelOnShutdown", () => { ConnectReachability.ConnectReachability, ConnectReachability.ConnectReachability.of({ check: Effect.die("unused"), - latest: Effect.succeedNone, + latest: harness.latestReachability ?? Effect.succeedNone, }), ), Effect.provideService(HttpServer.HttpServer, { @@ -1050,4 +1051,57 @@ describe("releaseManagedTunnelOnShutdown", () => { expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false); }).pipe(provideReleaseHarness({ store: failingStore, applyConfigCalls, requests })); }); + + it.effect("does not report a not-linked check once the managed tunnel config is stored", () => { + const { store } = makeMemorySecretStore(managedLinkSecrets); + const notLinked = ConnectReachability.classifyReachability( + { + managedTunnelConfigured: false, + connector: null, + endpoint: null, + edgeReachable: null, + exitNode: null, + }, + "2026-10-29T00:00:00.000Z", + ); + + return Effect.gen(function* () { + const state = yield* (yield* CloudLink.CloudLink).linkState(); + + expect(state.managedTunnelActive).toBe(true); + expect(state.reachability?.status === "unreachable" && state.reachability.cause).not.toBe( + "not_linked", + ); + }).pipe( + provideReleaseHarness({ + store, + applyConfigCalls: [], + requests: [], + latestReachability: Effect.succeedSome(notLinked), + }), + ); + }); + + it.effect("reports a check that ran after the managed tunnel config was stored", () => { + const { store } = makeMemorySecretStore(managedLinkSecrets); + const reachable = { + status: "reachable" as const, + checkedAt: "2026-10-29T00:00:00.000Z", + readyConnections: 4, + protocol: "quic", + }; + + return Effect.gen(function* () { + const state = yield* (yield* CloudLink.CloudLink).linkState(); + + expect(state.reachability).toEqual(reachable); + }).pipe( + provideReleaseHarness({ + store, + applyConfigCalls: [], + requests: [], + latestReachability: Effect.succeedSome(reachable), + }), + ); + }); }); diff --git a/apps/server/src/cloud/CloudLink.ts b/apps/server/src/cloud/CloudLink.ts index 322a4b7503bcb..3d8d9650b22a6 100644 --- a/apps/server/src/cloud/CloudLink.ts +++ b/apps/server/src/cloud/CloudLink.ts @@ -1290,6 +1290,13 @@ const make = Effect.gen(function* () { ], { concurrency: 8 }, ); + // A not-linked check predates the stored tunnel config; the next check replaces it. + const currentReachability = Option.filter( + latestReachability, + (result) => + Option.isNone(endpointRuntimeConfig) || + !(result.status === "unreachable" && result.cause === "not_linked"), + ); return { linked: Option.isSome(cloudUserId), linkRevoked: Option.isSome(cloudUserId) && Option.isSome(revoked), @@ -1302,7 +1309,7 @@ const make = Effect.gen(function* () { : false, holdWebhooksWhileOffline: Option.isSome(holdWebhooks) && bytesToString(holdWebhooks.value) === "true", - ...(Option.isSome(latestReachability) ? { reachability: latestReachability.value } : {}), + ...(Option.isSome(currentReachability) ? { reachability: currentReachability.value } : {}), } satisfies EnvironmentCloudLinkStateResult; }); diff --git a/apps/server/src/cloud/ConnectReachability.test.ts b/apps/server/src/cloud/ConnectReachability.test.ts index 28735b87378f7..b6a73ab5dcd27 100644 --- a/apps/server/src/cloud/ConnectReachability.test.ts +++ b/apps/server/src/cloud/ConnectReachability.test.ts @@ -65,6 +65,13 @@ describe("classifyReachability", () => { classifyReachability(facts({ connector: notConnected, edgeReachable: true }), checkedAt), ).toMatchObject({ cause: "connector_not_ready" }); }); + + it("does not point an unlinked server at a background service it may not have", () => { + // Desktop and `t3 serve` run the server without a background service. + const result = classifyReachability(facts({ managedTunnelConfigured: false }), checkedAt); + expect(result).toMatchObject({ cause: "not_linked" }); + expect(result.status === "unreachable" && result.fix).not.toContain("t3 service"); + }); }); describe("T3 Connect troubleshooting links", () => { diff --git a/apps/server/src/cloud/ConnectReachability.ts b/apps/server/src/cloud/ConnectReachability.ts index 17e78f4be1783..acb581778d958 100644 --- a/apps/server/src/cloud/ConnectReachability.ts +++ b/apps/server/src/cloud/ConnectReachability.ts @@ -68,10 +68,11 @@ export function classifyReachability( const restart = "Restart T3 Code. If it stays, run `t3 connect` again."; if (!facts.managedTunnelConfigured) { + // A running server reads the link `t3 connect` stores only at startup. return fail( "not_linked", "The server has not set up a T3 Connect tunnel.", - "Run `t3 connect`, then restart the server (`t3 service restart`) so it applies the link.", + "Run `t3 connect`, then restart T3 Code so it applies the link.", ); } if (connector === null) { diff --git a/apps/server/src/mcp/PreviewAutomationBroker.test.ts b/apps/server/src/mcp/PreviewAutomationBroker.test.ts index 0fb3b610e5d59..1c193096db273 100644 --- a/apps/server/src/mcp/PreviewAutomationBroker.test.ts +++ b/apps/server/src/mcp/PreviewAutomationBroker.test.ts @@ -335,6 +335,43 @@ it.effect.each([ ), ); +it.effect("names the click target that matched nothing when the server browser times out", () => + Effect.scoped( + Effect.gen(function* () { + const broker = yield* makeBroker; + const clientId = SERVER_BROWSER_AUTOMATION_CLIENT_ID; + const requests = requestsFrom(yield* broker.connect(makeHost({ clientId }))); + yield* Stream.runForEach(requests, (request) => + broker.respond({ + clientId, + connectionId: request.connectionId, + requestId: request.requestId, + ok: false, + error: { + _tag: "PreviewAutomationTimeoutError", + message: "No element matches the target.", + detail: { reason: 'No element matches ".definitely-no-such-t3-target".' }, + }, + }), + ).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + + const error = yield* broker + .invoke({ + scope, + operation: "click", + input: { selector: ".definitely-no-such-t3-target", timeoutMs: 15_000 }, + }) + .pipe(Effect.flip); + + expect(error._tag).toBe("PreviewAutomationTimeoutError"); + expect(error.message).toBe( + 'Preview automation click timed out after 15000ms. No element matches ".definitely-no-such-t3-target".', + ); + }), + ), +); + it.effect("distinguishes malformed remote failures", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/mcp/PreviewAutomationBroker.ts b/apps/server/src/mcp/PreviewAutomationBroker.ts index cc34ebbce69f3..85646d387160d 100644 --- a/apps/server/src/mcp/PreviewAutomationBroker.ts +++ b/apps/server/src/mcp/PreviewAutomationBroker.ts @@ -205,6 +205,14 @@ const readRemoteTimeoutMs = (detail: unknown): number | undefined => { : undefined; }; +const readRemoteReason = (detail: unknown): string | undefined => + typeof detail === "object" && + detail !== null && + "reason" in detail && + typeof detail.reason === "string" + ? detail.reason + : undefined; + const MAX_REASON_CHARS = 500; const classifyResponseError = ( @@ -255,9 +263,13 @@ const classifyResponseError = ( }); case "PreviewAutomationTimeoutError": { const remoteTimeoutMs = readRemoteTimeoutMs(error.detail); + const remoteReason = readRemoteReason(error.detail); return new PreviewAutomationTimeoutError({ ...context, ...remoteDiagnostics, + ...(context.clientId === SERVER_BROWSER_AUTOMATION_CLIENT_ID && remoteReason !== undefined + ? { reason: remoteReason.slice(0, MAX_REASON_CHARS) } + : {}), ...(remoteTimeoutMs === undefined ? {} : { timeoutMs: Math.min(context.timeoutMs, remoteTimeoutMs) }), diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index ec9372f80fb7b..f406bd7447514 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -2744,22 +2744,40 @@ describe("ClaudeAdapterV2 MCP credential channel", () => { }); describe("ClaudeAdapterV2 native session identity", () => { - const openTurnWithOrdinal = (providerTurnOrdinal: number, nativeThreadHasTurns?: boolean) => + const openTurnWithOrdinal = ( + providerTurnOrdinal: number, + nativeThreadHasTurns?: boolean, + importedNativeThreadId?: string, + ) => Effect.scoped( Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocator.IdAllocatorV2; + const path = yield* Path.Path; const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-v2-session-identity-", }); + if (importedNativeThreadId !== undefined) { + // An unreadable copy in another project must not hide the readable one. + yield* fileSystem.makeDirectory( + path.join(attachmentsDir, "projects", "-other", `${importedNativeThreadId}.jsonl`), + { recursive: true }, + ); + const projectDir = path.join(attachmentsDir, "projects", "-workspace"); + yield* fileSystem.makeDirectory(projectDir, { recursive: true }); + yield* fileSystem.writeFileString( + path.join(projectDir, `${importedNativeThreadId}.jsonl`), + `{"type":"user","message":{"role":"user","content":"hello"},"sessionId":"${importedNativeThreadId}"}\n`, + ); + } const openedQueries: Array = []; const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, settings: DEFAULT_CLAUDE_SETTINGS, - environment: {}, + environment: { CLAUDE_CONFIG_DIR: attachmentsDir }, attachmentsDir, fileSystem, - path: yield* Path.Path, + path, random: yield* SecureRandom.SecureRandom, idAllocator, queryRunner: { @@ -2792,12 +2810,49 @@ describe("ClaudeAdapterV2 native session identity", () => { modelSelection: CLAUDE_TEST_MODEL_SELECTION, runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); const now = yield* DateTime.now; + // Mirrors the provider thread a session import records: a strong native + // ref with no conversation head and no provider turns. + const providerThread = + importedNativeThreadId === undefined + ? yield* runtime.ensureThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }) + : yield* runtime.resumeThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + providerThread: { + id: idAllocator.derive.providerThread({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + providerInstanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + nativeThreadId: importedNativeThreadId, + }), + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + providerInstanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + providerSessionId: null, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeId: importedNativeThreadId, + strength: "strong", + }, + nativeConversationHeadRef: null, + status: "not_loaded", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + contextUsage: null, + nativeMetadata: null, + goal: null, + createdAt: now, + updatedAt: now, + }, + }); yield* runtime.startTurn( makeClaudeTestTurnInput({ threadId, @@ -2843,6 +2898,15 @@ describe("ClaudeAdapterV2 native session identity", () => { assert.equal(openedQueries[0]?.options.title, "Claude attachment test"); }), ); + + it.effect("resumes an imported native session on its first T3 turn", () => + Effect.gen(function* () { + const openedQueries = yield* openTurnWithOrdinal(1, false, "imported-native-session"); + assert.equal(openedQueries.length, 1); + assert.equal(openedQueries[0]?.options.resume, "imported-native-session"); + assert.equal(openedQueries[0]?.options.sessionId, undefined); + }), + ); }); const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); @@ -11283,6 +11347,88 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect( + "dates a buffered wake gateway limit from its arrival, not the continuation replay", + () => + Effect.scoped( + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-gateway-1"), + text: "Run the build in the background.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* Queue.take(harness.terminalReceipts); + + yield* Queue.offer(harness.sdkMessages, wakeNotification); + yield* harness.offerAndWait( + makeAssistantErrorFrame({ + uuid: "00000000-0000-4000-8000-000000000634", + error: "server_error", + }), + ); + assert.lengthOf(harness.continuationRequests, 1); + const arrivedAt = yield* DateTime.now; + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000635", + result: + 'API Error: 503 [cpa/claude-opus-5-5] [429]: {"type":"error","error":{"type":"rate_limit_error","message":"All credentials are cooling down"}} (reset after 2h54m21s)', + isError: true, + apiErrorStatus: 503, + terminalReason: "api_error", + origin: { kind: "task-notification" }, + }), + ); + + yield* TestClock.adjust("1 hour"); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-wake-gateway-2"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "failed"); + if (terminal.status !== "failed") return; + assert.equal(terminal.failure.class, "usage_limit"); + assert.equal( + terminal.failure.resetAt, + DateTime.formatIso( + DateTime.makeUnsafe( + DateTime.toEpochMillis(arrivedAt) + (2 * 3_600 + 54 * 60 + 21) * 1_000, + ), + ), + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + it.effect("leaves buffered wake messages for the continuation queued behind a user turn", () => Effect.scoped( Effect.gen(function* () { @@ -11379,6 +11525,86 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("settles a continuation whose wake turn a user turn absorbed", () => + Effect.scoped( + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-1"), + text: "Run the build in the background.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer(harness.sdkMessages, wakeNotification); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* harness.awaitTerminal(1); + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.awaitContinuation(1); + + // Claude folds this prompt into the wake turn it already opened, so one result ends both. + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-2"), + text: "Any update on the pull request?", + attachments: [], + providerTurnOrdinal: 2, + }), + ); + yield* harness.until(() => harness.offeredMessages.length === 2); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000140", + result: "Checks passed and the pull request is up to date.", + }), + ); + yield* harness.awaitTerminal(2); + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-3"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 3, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.awaitTerminal(3); + assert.equal(harness.terminalEvents()[2]?.status, "completed"); + assert.isTrue( + harness.events.some( + (event) => + event.type === "message.updated" && event.message.text === WAKE_ASSISTANT_TEXT, + ), + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + it.effect("ignores a zero-turn task-notification origin result during a normal user turn", () => Effect.scoped( Effect.gen(function* () { @@ -12600,6 +12826,198 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("keeps an idle-launched nested subagent completed through a sibling's wake", () => + Effect.scoped( + Effect.gen(function* () { + const OUTER_TASK_ID = "task-16355-outer"; + const OUTER_TOOL_USE_ID = "toolu-16355-outer"; + const NESTED_TASK_ID = "task-16355-nested"; + const NESTED_TOOL_USE_ID = "toolu-16355-nested"; + const SIBLING_TASK_ID = "task-16355-sibling"; + const SIBLING_TOOL_USE_ID = "toolu-16355-sibling"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const nestedStatuses = () => + harness.events.flatMap((event) => + event.type === "subagent.updated" && + event.subagent.nativeTaskRef?.nativeId === NESTED_TASK_ID + ? [event.subagent.status] + : [], + ); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-16355-1"), + text: "Run two audits in the background.", + attachments: [], + }), + ); + for (const frame of [ + makeSubagentTaskStartedFrame({ + taskId: OUTER_TASK_ID, + toolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000016301", + }), + makeSubagentTaskStartedFrame({ + taskId: SIBLING_TASK_ID, + toolUseId: SIBLING_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000016302", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000016303", + result: "Both audits run in the background.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(1); + + // The background subagent launches a foreground nested one while the root is idle. + for (const frame of [ + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_16355_nested_launch", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: NESTED_TOOL_USE_ID, + name: "Agent", + input: { description: "Nested check", prompt: "Sleep, then reply NESTED_OK" }, + }, + ], + }, + parent_tool_use_id: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000016304", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: NESTED_TASK_ID, + tool_use_id: NESTED_TOOL_USE_ID, + description: "Nested check", + subagent_type: "general-purpose", + is_backgrounded: false, + spawn_depth: 2, + task_type: "local_agent", + prompt: "Sleep, then reply NESTED_OK", + uuid: "00000000-0000-4000-8000-000000016305", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_progress", + task_id: NESTED_TASK_ID, + description: "Sleeping", + uuid: "00000000-0000-4000-8000-000000016306", + session_id: WAKE_NATIVE_SESSION, + }), + ]) { + yield* harness.offerAndWait(frame); + } + + // A user turn runs while the nested and then the outer subagent finish. + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-16355-2"), + text: "Sleep for a while.", + attachments: [], + providerTurnOrdinal: 2, + }), + ); + yield* harness.until(() => harness.offeredMessages.length === 2); + for (const frame of [ + makeSubagentNotificationFrame({ + taskId: NESTED_TASK_ID, + toolUseId: NESTED_TOOL_USE_ID, + summary: "NESTED_OK", + uuid: "00000000-0000-4000-8000-000000016307", + }), + makeSubagentToolResultFrame({ + parentToolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000016308", + toolUseId: NESTED_TOOL_USE_ID, + }), + ...makeSubagentAssistantFrames({ + parentToolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000016309", + text: "OUTER_DONE", + }), + makeSubagentNotificationFrame({ + taskId: OUTER_TASK_ID, + toolUseId: OUTER_TOOL_USE_ID, + summary: "OUTER_DONE", + uuid: "00000000-0000-4000-8000-000000016310", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000016311", + result: "Slept.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(2); + + // The sibling's completion wakes a continuation while the root is idle. + for (const frame of [ + makeSubagentNotificationFrame({ + taskId: SIBLING_TASK_ID, + toolUseId: SIBLING_TOOL_USE_ID, + summary: "SIBLING_DONE", + uuid: "00000000-0000-4000-8000-000000016312", + }), + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000016313", + text: "Both audits finished.", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000016314", + result: "Both audits finished.", + origin: { kind: "task-notification" }, + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitContinuation(1); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-16355-3"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 3, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.awaitTerminal(3); + + assert.equal(nestedStatuses().at(-1), "completed"); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + it.effect.each(["exit", "Stop"] as const)( "settles a plain background subagent and its open call on %s after the root turn completes", (reason) => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 9c7f8d9b690ee..6d551cb3df868 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -123,6 +123,7 @@ import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Equal from "effect/Equal"; import * as Exit from "effect/Exit"; @@ -339,6 +340,13 @@ const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500; const BACKGROUND_MOVE_TIMEOUT_MS = 5_000; // How long a Stop waits for the CLI to exit before the user is offered Force stop. const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000; +// Matches the stderr tail the SDK keeps for a CLI it spawns itself. +const CLAUDE_STDERR_TAIL_LENGTH = 2_048; +// The process group is killed on exit, so its stderr closes promptly. +const CLAUDE_STDERR_DRAIN_TIMEOUT = Duration.seconds(1); +// Claude Code's refusal of bypassPermissions as root, which it explains only on stderr. +const CLAUDE_ROOT_REFUSAL = + "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons"; const CLAUDE_GROUP_WATCH_SCRIPT = [ "{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } /dev/null 2>&1 &", @@ -353,6 +361,8 @@ const CLAUDE_GROUP_WATCH_SCRIPT = [ export function spawnClaudeProcessGroup( options: ClaudeSpawnOptions, onExit?: () => void, + onStderr: (text: string) => void = () => {}, + onStderrClose: () => void = () => {}, ): ClaudeSpawnedProcess { const child = NodeChildProcess.spawn( "/bin/sh", @@ -361,10 +371,12 @@ export function spawnClaudeProcessGroup( cwd: options.cwd, env: options.env, signal: options.signal, - stdio: ["pipe", "pipe", "ignore", "pipe"], + stdio: ["pipe", "pipe", "pipe", "pipe"], detached: true, }, ); + // Always drained, so a chatty CLI never blocks on a full stderr pipe. + child.stderr?.setEncoding("utf8").on("data", onStderr).once("close", onStderrClose); child.once("exit", () => { try { signalProcessGroup(child.pid ?? 0, "SIGKILL"); @@ -559,6 +571,17 @@ export class ClaudeAgentSdkQueryRunnerError extends Schema.TaggedError()( + "ClaudeCodeRootRefusalError", + { + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Claude Code exited before it started: ${CLAUDE_ROOT_REFUSAL}`; + } +} + class ClaudeMcpRegistrationTimeoutError extends Schema.TaggedError()( "ClaudeMcpRegistrationTimeoutError", {}, @@ -1010,10 +1033,25 @@ export const layerQueryRunner: Layer.Layer< const unit = launch?.unit; const stopScope = unit === undefined ? undefined : () => void runFork(agentScope.stop(unit)); + // Only a CLI that fails before its first message explains itself on + // stderr. The known root refusal becomes a curated failure; any other + // stderr can hold private text, so it stays out of turn failures. + let stderrTail = ""; + let stderrClosed: Promise = Promise.resolve(); + let answered = false; + const appendStderr = (text: string) => { + if (answered) return; + stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH); + }; const spawnProcess = options.spawnClaudeCodeProcess ?? ((spawnOptions: ClaudeSpawnOptions) => { - if (platform !== "win32") return spawnClaudeProcessGroup(spawnOptions, stopScope); + if (platform !== "win32") { + // Node can report "exit" before it has read the stderr the CLI wrote. + let stderrDone = () => {}; + stderrClosed = new Promise((resolve) => (stderrDone = resolve)); + return spawnClaudeProcessGroup(spawnOptions, stopScope, appendStderr, stderrDone); + } const child = NodeChildProcess.spawn(spawnOptions.command, spawnOptions.args, { cwd: spawnOptions.cwd, env: spawnOptions.env, @@ -1133,9 +1171,31 @@ export const layerQueryRunner: Layer.Layer< ); return { - messages: Stream.fromAsyncIterable(claudeQueryMessages(queryRuntime), (cause) => - queryRunnerError(cause, "fromAsyncIterable"), + messages: Stream.fromAsyncIterable( + claudeQueryMessages(queryRuntime), + (cause) => cause, ).pipe( + Stream.catch((cause) => + Stream.fromEffect( + Effect.gen(function* () { + if (!answered) { + yield* Effect.promise(() => stderrClosed).pipe( + Effect.timeoutOption(CLAUDE_STDERR_DRAIN_TIMEOUT), + ); + } + const refusedRoot = !answered && stderrTail.includes(CLAUDE_ROOT_REFUSAL); + return yield* queryRunnerError( + refusedRoot ? new ClaudeCodeRootRefusalError({ cause }) : cause, + "fromAsyncIterable", + ); + }), + ), + ), + Stream.tap(() => + Effect.sync(() => { + answered = true; + }), + ), Stream.tap((message) => logProtocolEvent({ direction: "incoming", @@ -3809,7 +3869,7 @@ function gatewayCooldownResetAt( function providerFailureFromResult( message: SDKResultMessage, - completedAt: DateTime.Utc, + receivedAt: DateTime.Utc, failureHint?: string, usageLimited = false, ): OrchestrationV2ProviderFailure | null { @@ -3823,7 +3883,7 @@ function providerFailureFromResult( /^API Error: 503 \[[^\]\r\n]+\] \[429\]: \{"type":"error","error":\{"type":"rate_limit_error",[^\r\n]*\} \(reset after (?:(\d+)h ?)?(?:(\d+)m ?)?(?:(\d+)s)?\)/.exec( message.result, ), - completedAt, + receivedAt, ) : undefined; if (gatewayResetAt !== undefined) { @@ -3867,7 +3927,7 @@ function providerFailureFromResult( apiErrorStatus === 429 && message.result.startsWith("API Error:") ? gatewayCooldownResetAt( /\(reset after (?:(\d+)h ?)?(?:(\d+)m ?)?(?:(\d+)s)?\)/.exec(message.result), - completedAt, + receivedAt, ) : undefined; return makeProviderFailure({ @@ -4895,6 +4955,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const pendingSubagentFramesByToolUseId = yield* Ref.make( new Map>(), ); + // A gateway's relative reset counts from the result's arrival, not its replay. + const bufferedResultArrivals = new WeakMap(); const wakeBuffers = yield* Ref.make( new Map< string, @@ -5042,6 +5104,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } }); const requestedContinuations = yield* Ref.make(new Set()); + const absorbedWakes = yield* Ref.make(new Set()); const heldProposedPlansByToolUseId = new Map(); const runtimeContext = yield* Effect.context(); const runPromise = Effect.runPromiseWith(runtimeContext); @@ -5477,6 +5540,14 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* endClaudeMonitorTasks((_taskId, task) => task.nativeThreadId === nativeThreadId); }); + const forgetAbsorbedWake = (nativeThreadId: string) => + Ref.update(absorbedWakes, (current) => { + if (!current.has(nativeThreadId)) return current; + const updated = new Set(current); + updated.delete(nativeThreadId); + return updated; + }); + const clearWakeStateForNativeThread = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (nativeThreadId: string) { @@ -5497,8 +5568,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( updated.delete(nativeThreadId); return updated; }); + yield* forgetAbsorbedWake(nativeThreadId); }); + // Claude runs one root turn at a time, so a user turn's result also ends a wake turn it + // folded in. The continuation replays that wake's buffered frames but gets no result of its own. + const markAbsorbedWake = Effect.fnUntraced(function* (nativeThreadId: string) { + const messages = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? []; + const lastResult = messages.findLastIndex((entry) => entry.type === "result"); + if (!messages.slice(lastResult + 1).some(isClaudeRootTurnFrame)) return; + yield* Ref.update(absorbedWakes, (current) => new Set(current).add(nativeThreadId)); + }); + // The SDK emits no initial roster; reset roster and wake eligibility when opening a live query. const resetBackgroundTaskStateForNativeThreadProcess = Effect.fnUntraced(function* ( nativeThreadId: string, @@ -8158,6 +8239,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( childThreadId: registered?.childThreadId, }); } + if (message.type === "result") { + bufferedResultArrivals.set(message, yield* DateTime.now); + } + if (isClaudeRootTurnFrame(message)) { + yield* forgetAbsorbedWake(wakeInput.nativeThreadId); + } yield* Ref.update(wakeBuffers, (current) => { const existing = current.get(wakeInput.nativeThreadId); const updated = new Map(current); @@ -9211,10 +9298,32 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } if (message.type === "system" && message.subtype === "task_notification") { - if ( - !appliedSubagentOutcomes.has(message) && - (yield* Ref.get(sessionSubagentsByTaskId)).has(message.task_id) - ) { + const isRegistered = (yield* Ref.get(sessionSubagentsByTaskId)).has(message.task_id); + // A task whose start is still held for the next wake drain has no + // node to finish yet; hold its outcome behind that start, or the + // drain replays the start alone and the task stays running. + if (!isRegistered) { + yield* Ref.update(wakeBuffers, (current) => { + const entry = current.get(liveQuery.nativeThreadId); + if ( + entry === undefined || + entry.messages.includes(message) || + !entry.messages.some( + (buffered) => + buffered.type === "system" && + buffered.subtype === "task_started" && + buffered.task_id === message.task_id, + ) + ) { + return current; + } + return new Map(current).set(liveQuery.nativeThreadId, { + ...entry, + messages: [...entry.messages, message], + }); + }); + } + if (!appliedSubagentOutcomes.has(message) && isRegistered) { yield* discardBufferedSubagentStarts( liveQuery.nativeThreadId, message.task_id, @@ -9588,6 +9697,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( next.delete(context.providerTurnId); return next; }); + if (!isClaudeProviderContinuationTurn(context.input)) { + yield* markAbsorbedWake(liveQuery.nativeThreadId); + } const usageLimited = context.authenticationFailureMessage === undefined && (context.rejectedRateLimitTypes.size > 0 || @@ -9632,7 +9744,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( message: limitedCompaction.message ?? failureHint, code: "compaction_failed", }) - : providerFailureFromResult(message, completedAt, failureHint, usageLimited); + : providerFailureFromResult( + message, + bufferedResultArrivals.get(message) ?? completedAt, + failureHint, + usageLimited, + ); const terminalFailure = resultFailure?.class === "usage_limit" ? { ...resultFailure, resetAt: resetAt ?? resultFailure.resetAt ?? null } @@ -10889,6 +11006,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( updated.delete(nativeThreadId); return updated; }); + const wakeAbsorbed = (yield* Ref.get(absorbedWakes)).has(nativeThreadId); + yield* forgetAbsorbedWake(nativeThreadId); if (drained.length === 0) { const completedAt = yield* DateTime.now; yield* finalizeActiveTurn({ context, status: "completed", completedAt }); @@ -10957,7 +11076,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* handleSdkMessage({ query: querySession.query, message: lastResult }); return; } - if (hasOpaqueTaskNotification && !context.nativeWakeStarted) { + if (wakeAbsorbed || (hasOpaqueTaskNotification && !context.nativeWakeStarted)) { const completedAt = yield* DateTime.now; yield* finalizeActiveTurn({ context, status: "completed", completedAt }); } else if (!context.nativeWakeStarted) { @@ -11288,41 +11407,47 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* Effect.addFinalizer(() => closeSession()); // Metadata-only transcripts cannot be resumed or recreated; fail resumeThread to trigger a fresh session and handoff. - const hasEmptyClaudeTranscript = Effect.fn("ClaudeAdapterV2.hasEmptyClaudeTranscript")( - function* (nativeThreadId: string) { - const configuredDir = adapterOptions.environment.CLAUDE_CONFIG_DIR?.trim() ?? ""; - const projectsDir = path.join( - configuredDir.length > 0 - ? path.resolve(session.cwd, configuredDir) - : path.join(yield* HostProcess.HomeDirectory, ".claude"), - "projects", - ); - // Any message in any transcript copy means Claude may still resume it. - let found = false; - for (const project of yield* fileSystem.readDirectory(projectsDir)) { - const transcriptPath = path.join(projectsDir, project, `${nativeThreadId}.jsonl`); - // Stray files beside the project dirs fail with ENOTDIR. - if ( - !(yield* fileSystem.exists(transcriptPath).pipe(Effect.orElseSucceed(() => false))) - ) { - continue; - } - const conversationLine = yield* fileSystem - .stream(transcriptPath) - .pipe( - Stream.decodeText, - Stream.splitLines, - Stream.filter(isClaudeConversationLine), - Stream.runHead, - ); - if (Option.isSome(conversationLine)) { - return false; - } - found = true; + const claudeTranscriptState = Effect.fn("ClaudeAdapterV2.claudeTranscriptState")(function* ( + nativeThreadId: string, + ) { + const configuredDir = adapterOptions.environment.CLAUDE_CONFIG_DIR?.trim() ?? ""; + const projectsDir = path.join( + configuredDir.length > 0 + ? path.resolve(session.cwd, configuredDir) + : path.join(yield* HostProcess.HomeDirectory, ".claude"), + "projects", + ); + // Any message in any transcript copy means Claude may still resume it. + let found = false; + let unreadable = false; + for (const project of yield* fileSystem.readDirectory(projectsDir)) { + const transcriptPath = path.join(projectsDir, project, `${nativeThreadId}.jsonl`); + // Stray files beside the project dirs fail with ENOTDIR. + if ( + !(yield* fileSystem.exists(transcriptPath).pipe(Effect.orElseSucceed(() => false))) + ) { + continue; } - return found; - }, - ); + const conversationLine = yield* fileSystem + .stream(transcriptPath) + .pipe( + Stream.decodeText, + Stream.splitLines, + Stream.filter(isClaudeConversationLine), + Stream.runHead, + Effect.option, + ); + if (Option.isNone(conversationLine)) { + unreadable = true; + continue; + } + if (Option.isSome(conversationLine.value)) { + return "conversation" as const; + } + found = true; + } + return found && !unreadable ? ("empty" as const) : ("missing" as const); + }); const runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime = { instanceId: adapterOptions.instanceId, @@ -11414,16 +11539,25 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeThreadId !== undefined && nativeThreadId !== null && // A live process holds the conversation even before saving it. - (yield* Ref.get(queryContext))?.nativeThreadId !== nativeThreadId && - // An unreadable transcript leaves the resume to the CLI. - (yield* hasEmptyClaudeTranscript(nativeThreadId).pipe( - Effect.orElseSucceed(() => false), - )) + (yield* Ref.get(queryContext))?.nativeThreadId !== nativeThreadId ) { - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ - driver: CLAUDE_PROVIDER, - detail: `Claude session ${nativeThreadId} has no conversation to resume.`, - }); + // An unreadable transcript leaves the resume to the CLI. + const transcript = yield* claudeTranscriptState(nativeThreadId).pipe( + Effect.orElseSucceed(() => "missing" as const), + ); + if (transcript === "empty") { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CLAUDE_PROVIDER, + detail: `Claude session ${nativeThreadId} has no conversation to resume.`, + }); + } + // A session imported from the terminal has history but no T3 + // provider turns; opening it with sessionId fails "already in use". + if (transcript === "conversation") { + yield* Ref.update(openedNativeThreads, (current) => + current.has(nativeThreadId) ? current : new Set(current).add(nativeThreadId), + ); + } } const updatedAt = yield* DateTime.now; return { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index 340de961471d7..5898996e486ee 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -17,6 +17,7 @@ import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import { vi } from "vite-plus/test"; @@ -546,6 +547,47 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro }), ); + const rootRefusal = + "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons"; + + const startupFailureMessage = (stderr: string) => + Effect.gen(function* () { + const cli = fakeClaudeCli(`printf '%s\\n' '${stderr}' >&2\nexit 1`); + yield* Effect.addFinalizer(() => + Effect.sync(() => NodeFS.rmSync(NodePath.dirname(cli), { recursive: true, force: true })), + ); + const session = yield* openFakeCli(cli); + const exit = yield* Stream.runDrain(session.messages).pipe(Effect.exit); + assert.isTrue(Exit.isFailure(exit)); + return Exit.isFailure(exit) + ? makeProviderFailure({ cause: exit.cause, class: "transport_error" }).message + : ""; + }); + + // Claude Code refuses bypassPermissions as root and explains why only on + // stderr, so the turn failure has to carry that line. + it.effect("reports the CLI's root refusal when it exits before answering", () => + Effect.gen(function* () { + assert.include(yield* startupFailureMessage(rootRefusal), rootRefusal); + }).pipe(Effect.provide(realQueryRunner)), + ); + + // Startup stderr can carry paths, tokens, or settings, so only the known + // refusal reaches the failure the client shows. + it.effect("keeps other startup stderr out of the turn failure", () => + Effect.gen(function* () { + const surrounded = yield* startupFailureMessage( + `token=sk-private-123\n${rootRefusal}\nat /home/private/settings.json`, + ); + assert.include(surrounded, rootRefusal); + assert.notInclude(surrounded, "sk-private-123"); + assert.notInclude(surrounded, "/home/private"); + + const unknown = yield* startupFailureMessage("token=sk-private-123"); + assert.notInclude(unknown, "sk-private-123"); + }).pipe(Effect.provide(realQueryRunner)), + ); + // The CLI keeps running its turn after its pipes close, so a server that // crashed would leave it working next to the session it resumes. it.effect("stops the CLI when the server that started it goes away", () => diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 5a73f1ac512c4..c7a4da67c11b4 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -5923,6 +5923,95 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + // regression: #28032 an unlisted codexErrorInfo dropped the failed turn/completed + it.effect("fails the turn when Codex reports an error info the schema does not list", () => + Effect.scoped( + Effect.gen(function* () { + const nativeThreadId = "native-unlisted-error-info"; + const nativeTurnId = "turn-unlisted-error-info"; + const message = + "The 'gpt-5-codex' model is not supported when using Codex with a ChatGPT account."; + const error = { message, codexErrorInfo: "modelNotFound", additionalDetails: null }; + const usage = { + totalTokens: 1, + inputTokens: 1, + cachedInputTokens: 0, + outputTokens: 0, + reasoningOutputTokens: 0, + }; + const transcript = makeCodexReplayTranscript({ + scenario: "codex-unlisted-error-info", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "say hi" }), + { + type: "emit_inbound", + label: "error", + frame: { + method: "error", + params: { threadId: nativeThreadId, turnId: nativeTurnId, willRetry: false, error }, + }, + }, + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: { ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }), error }, + }, + }, + }, + // Notifications dispatch in order, so this marks turn/completed as handled. + { + type: "emit_inbound", + label: "usage", + frame: { + method: "thread/tokenUsage/updated", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + tokenUsage: { total: usage, last: usage, modelContextWindow: 200_000 }, + }, + }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + text: "say hi", + attemptId: RunAttemptId.make("attempt-unlisted-error-info"), + }), + ); + yield* harness.until( + () => + harness.terminalEvents().length > 0 || + harness.events.some( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.tokenUsage != null, + ), + ); + const terminal = harness.terminalEvents()[0]; + assert.equal(terminal?.status, "failed"); + if (terminal?.status !== "failed") return; + assert.equal(terminal.failure.message, message); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + const FAILED_SCENARIO = "codex-failed-mid-command"; const FAILED_NATIVE_THREAD = "native-codex-failed-thread"; const FAILED_NATIVE_TURN = "native-codex-failed-turn"; diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 327841d16277b..c334af4fad113 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -72,11 +72,18 @@ const event = ( type: string, data: Record, label?: string, + version = 1, ): ProviderReplayEntry => ({ type: "emit_inbound", frame: { type: "sdk.event", - event: { id: `evt_${type.replaceAll(".", "")}0000`, created: 1, type, data, ...durable }, + event: { + id: `evt_${type.replaceAll(".", "")}0000`, + created: 1, + type, + data, + durable: { ...durable.durable, version }, + }, }, ...(label === undefined ? {} : { label }), }); @@ -943,47 +950,85 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); - it.effect("keeps a finished background subagent's queued report as pending work", () => - Effect.gen(function* () { - const { runtime, thread } = yield* resumed([ - ...backgroundLaunch(CHILD), - event("session.execution.succeeded", { sessionID: SESSION }), - event("session.execution.succeeded", { sessionID: CHILD }), - event("session.inbox.enqueued", { - inboxID: "msg_report", - sessionID: SESSION, - item: { - type: "synthetic", - payload: { - text: `\nCHILD_OK\n`, - description: "Sleep", - metadata: { - source: "subagent", - childID: CHILD, - agent: "General", - state: "completed", - }, - }, - delivery: "steer", - }, - }), - event("session.usage.updated", { sessionID: SESSION }), - ]); - const reported = yield* Deferred.make(); - yield* runtime.events.pipe( - Stream.tap((event) => - event.type === "subagent.updated" && event.subagent.status === "completed" - ? Deferred.succeed(reported, undefined) - : Effect.void, - ), - Stream.runDrain, - Effect.forkScoped, - ); - yield* runtime.startTurn(withLineage(thread)); - yield* Deferred.await(reported); - assert.isTrue(yield* runtime.hasPendingBackgroundWork!); - assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread)); - }).pipe(Effect.scoped), + it.effect( + "keeps a finished background subagent's queued report pending until its native continuation ends", + () => + Effect.gen(function* () { + const gate = makeProviderReplayGate(["continue"]); + const { runtime, thread } = yield* resumed( + [ + ...nestedLaunch, + event("session.execution.succeeded", { sessionID: DEEP }), + deepReport("completed"), + event("session.model.selected", { + sessionID: SESSION, + model: { providerID: "opencode", id: "big-pickle", variant: "thinking" }, + }), + event("session.execution.started", { sessionID: MIDDLE }, "continue"), + event("session.inbox.delivered", { sessionID: MIDDLE, inboxID: "msg_deep_report" }), + event("session.text.ended", { + sessionID: MIDDLE, + assistantMessageID: "msg_native_continuation", + ordinal: 0, + text: "GRANDCHILD_OK", + }), + event("session.execution.succeeded", { sessionID: MIDDLE }), + event("session.model.selected", { + sessionID: SESSION, + model: { providerID: "opencode", id: "big-pickle", variant: "none" }, + }), + ], + { replayGate: gate }, + ); + const queued = yield* Deferred.make(); + const drained = yield* Deferred.make(); + const timeline: Array = []; + yield* runtime.events.pipe( + Stream.runForEach((event) => + Effect.gen(function* () { + if (event.type === "provider_thread.updated") { + if ( + event.providerThread.nativeThreadRef?.nativeId === MIDDLE && + event.pendingBackgroundWork !== undefined + ) { + timeline.push(event.pendingBackgroundWork); + } + if (event.providerThread.id === thread.id) { + const variant = + event.providerThread.nativeMetadata?.modelSelection?.options?.[0]?.value; + if (variant === "thinking") yield* Deferred.succeed(queued, undefined); + if (variant === "none") yield* Deferred.succeed(drained, undefined); + } + } + if ( + event.type === "provider_turn.updated" && + event.providerTurn.nativeTurnRef?.nativeId === `${MIDDLE}:turn:2` + ) { + timeline.push(event.providerTurn.status); + } + if (event.type === "message.updated" && event.message.text === "GRANDCHILD_OK") { + timeline.push(event.message.text); + } + }), + ), + Effect.forkScoped, + ); + yield* runtime.startTurn(withLineage(thread)); + yield* Deferred.await(queued); + assert.isTrue(yield* runtime.hasPendingBackgroundWork!); + assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread)); + assert.strictEqual(timeline.at(-1), true); + timeline.length = 0; + gate.release("continue"); + yield* Deferred.await(drained); + assert.deepEqual( + timeline.filter((entry) => typeof entry === "string"), + ["running", "GRANDCHILD_OK", "completed"], + ); + assert.isAbove(timeline.indexOf(false), timeline.indexOf("completed")); + assert.strictEqual(timeline.at(-1), false); + assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread)); + }).pipe(Effect.scoped), ); const returnedRunning = (id: string): ProviderReplayEntry => ({ @@ -1283,6 +1328,9 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { Effect.gen(function* () { const deep: Array = []; const middleTurns = new Map(); + const pendingSnapshots = new Map(); + const variants = new Map(); + let rootVariant: unknown; const terminals: Array = []; const changed = yield* Deferred.make(); let wake = changed; @@ -1290,6 +1338,16 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { Stream.tap((event) => Effect.gen(function* () { if (event.type === "turn.terminal") terminals.push(event.status); + if (event.type === "provider_thread.updated") { + const nativeId = event.providerThread.nativeThreadRef?.nativeId; + if (nativeId != null && event.pendingBackgroundWork !== undefined) { + pendingSnapshots.set(nativeId, event.pendingBackgroundWork); + } + const variant = + event.providerThread.nativeMetadata?.modelSelection?.options?.[0]?.value; + if (nativeId != null) variants.set(nativeId, variant); + if (nativeId === SESSION) rootVariant = variant; + } if (event.type === "subagent.updated" && event.subagent.title === "Deep") { deep.push(event.subagent.status); } @@ -1314,9 +1372,164 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { yield* until(check); }); }); - return { deep, middleTurns, terminals, until }; + return { + deep, + middleTurns, + terminals, + pendingSnapshots, + variants, + get rootVariant() { + return rootVariant; + }, + until, + }; }); + it.effect("clears a nested report cancelled during a held wake", () => + Effect.gen(function* () { + const offers: Array = []; + const gate = makeProviderReplayGate(["drained"]); + const { runtime, thread } = yield* resumed( + [ + ...backgroundLaunch(CHILD), + event("session.execution.succeeded", { sessionID: SESSION }), + event("session.execution.succeeded", { sessionID: CHILD }), + childReport("msg_report", "CHILD_OK"), + event("session.execution.started", { sessionID: SESSION }), + ...nestedLaunch.slice(3, -2), + event( + "session.tool.success", + { + ...toolOf(SESSION, "call-middle"), + content: [{ type: "text", text: "MIDDLE_OK" }], + metadata: { sessionID: MIDDLE, status: "completed", truncated: false }, + executed: false, + }, + undefined, + 2, + ), + event("session.execution.succeeded", { sessionID: DEEP }), + deepReport("completed"), + event("session.inbox.cancelled", { sessionID: MIDDLE, inboxID: "msg_deep_report" }), + event("session.execution.succeeded", { sessionID: SESSION }), + event("session.model.selected", { + sessionID: SESSION, + model: { providerID: "opencode", id: "big-pickle", variant: "thinking" }, + }), + event( + "session.model.selected", + { + sessionID: SESSION, + model: { providerID: "opencode", id: "big-pickle", variant: "none" }, + }, + "drained", + ), + ], + { replayGate: gate }, + ).pipe( + Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, { + offer: (request) => + Effect.sync(() => { + offers.push(request); + }), + take: Effect.never, + }), + ); + const watch = yield* watchNested(runtime); + yield* runtime.startTurn(withLineage(thread)); + assert.isTrue(yield* Effect.promise(() => gate.waitForReached("drained"))); + yield* watch.until(() => watch.rootVariant === "thinking"); + assert.lengthOf(offers, 1); + yield* runtime.startTurn(continuationTurn(thread, offers[0]!)); + gate.release("drained"); + yield* watch.until(() => watch.rootVariant === "none"); + assert.isFalse(yield* runtime.hasPendingBackgroundWork!); + assert.strictEqual(watch.pendingSnapshots.get(MIDDLE), false); + }).pipe(Effect.scoped), + ); + + it.effect("clears the caller's pending work when a called session's held wake runs", () => + Effect.gen(function* () { + const OTHER = "ses_other00000000000000000000"; + const offers: Array = []; + const gate = makeProviderReplayGate(["drained"]); + const { runtime, thread } = yield* resumed( + [ + out("session.get", { sessionID: OTHER }), + replyData("session.get", sessionInfo({ id: OTHER })), + out("permission.list", { sessionID: OTHER }), + replyData("permission.list", []), + out("session.form.list", { sessionID: OTHER }), + replyData("session.form.list", []), + event("session.execution.started", { sessionID: OTHER }), + event("session.execution.succeeded", { sessionID: OTHER }), + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.started", { sessionID: SESSION }), + event("session.tool.input.started", { + ...toolOf(SESSION, "call-other"), + name: "subagent", + }), + event("session.tool.called", { + ...toolOf(SESSION, "call-other"), + name: "subagent", + input: { description: "Other", prompt: "again" }, + executed: false, + }), + event("session.tool.progress", { + ...toolOf(SESSION, "call-other"), + metadata: { sessionID: OTHER, status: "running" }, + }), + event("session.tool.success", { + ...toolOf(SESSION, "call-other"), + content: [{ type: "text", text: "OTHER_OK" }], + metadata: { sessionID: OTHER, status: "completed", truncated: false }, + executed: false, + }), + event("session.execution.succeeded", { sessionID: SESSION }), + event( + "session.model.selected", + { + sessionID: OTHER, + model: { providerID: "opencode", id: "big-pickle", variant: "none" }, + }, + "drained", + ), + ], + { replayGate: gate }, + ).pipe( + Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, { + offer: (request) => + Effect.sync(() => { + offers.push(request); + }), + take: Effect.never, + }), + ); + const other = yield* runtime.resumeThread({ + providerThread: { + ...thread, + id: ProviderThreadId.make("provider-thread:opencode2-adapter:other"), + nativeThreadRef: { driver: OPENCODE_PROVIDER, nativeId: OTHER, strength: "strong" }, + }, + threadId, + modelSelection: bigPickle, + runtimePolicy: policy(), + }); + const watch = yield* watchNested(runtime); + yield* watch.until(() => offers.length === 1); + yield* runtime.startTurn(withLineage(thread)); + assert.isTrue(yield* Effect.promise(() => gate.waitForReached("drained"))); + // The called session's held wake is its caller's pending work too. + yield* watch.until(() => watch.pendingSnapshots.get(SESSION) === true); + yield* runtime.startTurn(continuationTurn(other, offers[0]!)); + gate.release("drained"); + yield* watch.until(() => watch.variants.get(OTHER) === "none"); + assert.isFalse(watch.pendingSnapshots.get(OTHER)); + assert.isFalse(watch.pendingSnapshots.get(SESSION)); + }).pipe(Effect.scoped), + ); + it.effect("stops a foreground subagent's background subagent after the turn ended", () => Effect.gen(function* () { const offered = yield* Deferred.make(); @@ -2298,6 +2511,76 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); + it.effect("sends a $skill that appears once OpenCode finishes scanning the directory", () => + Effect.gen(function* () { + const prompts: Array = []; + const greet = { + id: "greet", + name: "greet", + path: `${WORK}/.opencode/skills/greet/SKILL.md`, + content: "Say hello.", + }; + const { runtime, thread } = yield* resumed( + [ + out("skill.list", { "location[directory]": WORK }), + reply("skill.list", { location: { directory: WORK }, data: [] }), + // OpenCode answers the model list only once the directory scan has ended. + ...directoryModels(WORK), + out("skill.list", { "location[directory]": WORK }), + reply("skill.list", { location: { directory: WORK }, data: [greet] }), + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.succeeded", { sessionID: SESSION }), + ], + { onPrompt: (input) => prompts.push(input) }, + ); + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + const started = yield* runtime + .startTurn({ + ...turnInput(thread), + message: { ...turnInput(thread).message, text: "$greet again please" }, + }) + .pipe(Effect.exit); + assert.deepInclude(prompts[0], { skills: [{ id: "greet" }] }); + assert.isTrue(Exit.isSuccess(started)); + assert.equal((yield* Fiber.join(terminal))?.status, "completed"); + }).pipe(Effect.scoped), + ); + + it.effect( + "keeps a $skill found on the first read when the reread after the scan comes back empty", + () => + Effect.gen(function* () { + const prompts: Array = []; + const greet = { + id: "greet", + name: "greet", + path: `${WORK}/.opencode/skills/greet/SKILL.md`, + content: "Say hello.", + }; + const { runtime, thread } = yield* resumed( + [ + out("skill.list", { "location[directory]": WORK }), + reply("skill.list", { location: { directory: WORK }, data: [greet] }), + ...directoryModels(WORK), + out("skill.list", { "location[directory]": WORK }), + reply("skill.list", { location: { directory: WORK }, data: [] }), + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.succeeded", { sessionID: SESSION }), + ], + { onPrompt: (input) => prompts.push(input) }, + ); + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + yield* runtime.startTurn({ + ...turnInput(thread), + message: { ...turnInput(thread).message, text: "$greet then echo $HOME" }, + }); + assert.equal((yield* Fiber.join(terminal))?.status, "completed"); + assert.deepInclude(prompts[0], { skills: [{ id: "greet" }] }); + }).pipe(Effect.scoped), + ); + it.effect("keeps a turn still running after a reconnect open for its next events", () => Effect.gen(function* () { const { runtime, thread } = yield* resumed([ @@ -3347,6 +3630,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { status: "completed", reason: "auto", summary: "First turn summary", + recent: 42, }, { id: "msg_dropped", time: { created: 3 }, text: "second", type: "user" }, ], diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 422225904e29a..9731de8813d95 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -6286,24 +6286,69 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio activeProviderThread.providerInstanceId !== modelSelection.instanceId; // Account overlays share native history. Selection commands may already // have updated the app thread, so classify against the native thread's owner. + const providerSwitchPlan = isProviderSwitch + ? yield* providerSwitchService + .plan({ + projection: { + ...projection, + thread: { + ...projection.thread, + modelSelection: { + ...projection.thread.modelSelection, + instanceId: activeProviderThread.providerInstanceId, + }, + }, + }, + targetModelSelection: modelSelection, + }) + .pipe(mapDispatchError(command)) + : null; const canResumeAcrossInstances = isProviderSwitch && activeProviderThread.nativeThreadRef !== null && - (yield* providerSwitchService - .plan({ - projection: { - ...projection, - thread: { - ...projection.thread, - modelSelection: { - ...projection.thread.modelSelection, - instanceId: activeProviderThread.providerInstanceId, - }, - }, - }, - targetModelSelection: modelSelection, - }) - .pipe(mapDispatchError(command))).transition.type === "restart_and_resume"; + providerSwitchPlan?.transition.type === "restart_and_resume"; + const sessionsToDetach = projection.providerSessions.filter( + (session) => + providerSwitchPlan?.releaseProviderSessionIds.includes(session.id) && + session.status !== "stopped" && + session.status !== "error", + ); + // Detaching kills background work running inside the provider process. + // Probe even with an empty roster: Claude's native subagents never reach + // pendingBackgroundTasks. Sessions shared across threads probe per thread. + for (const detaching of sessionsToDetach) { + const session = yield* providerSessions + .get(detaching.id) + .pipe(Effect.orElseSucceed(() => Option.none())); + if (Option.isNone(session)) { + continue; + } + const runtime = session.value; + const probes = + !detaching.capabilities.sessions.supportsMultipleProviderThreadsPerSession && + runtime.hasPendingBackgroundWork !== undefined + ? [runtime.hasPendingBackgroundWork] + : projection.providerThreads.flatMap((providerThread) => + providerThread.providerSessionId === detaching.id && + runtime.hasPendingBackgroundWorkForThread !== undefined + ? [runtime.hasPendingBackgroundWorkForThread(providerThread)] + : [], + ); + for (const probe of probes) { + const stillRunning = yield* probe.pipe( + // A failed probe cannot confirm that the work ended. + Effect.catchCause(() => Effect.succeed(true)), + ); + if (stillRunning) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: + "The previous provider is still running background agents or commands, and switching would end them. Wait for them to finish, or press Stop, then send the message again.", + }); + } + } + } if ( pendingForkTransfer === undefined && @@ -7610,30 +7655,32 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } - if (canResumeAcrossInstances && activeProviderThread.providerSessionId !== null) { - const previousProviderSessionId = activeProviderThread.providerSessionId; + const detachDetail = canResumeAcrossInstances + ? "Provider account changed; continuing the native thread." + : "Provider or model selection changed."; + for (const session of sessionsToDetach) { yield* emitEvent({ type: "provider-session.detached", threadId: command.threadId, - driver: activeProviderThread.driver, - providerInstanceId: activeProviderThread.providerInstanceId, + driver: session.driver, + providerInstanceId: session.providerInstanceId, occurredAt: now, payload: { - providerSessionId: previousProviderSessionId, + providerSessionId: session.id, detachedAt: now, - reason: "Provider account changed; continuing the native thread.", + reason: detachDetail, }, }); yield* Ref.update(effects, (existing) => [ ...existing, { - id: `effect:${command.commandId}:provider-session.detach:${previousProviderSessionId}`, + id: `effect:${command.commandId}:provider-session.detach:${session.id}`, commandId: command.commandId, threadId: command.threadId, request: { type: "provider-session.detach", - providerSessionId: previousProviderSessionId, - detail: "Provider account changed; continuing the native thread.", + providerSessionId: session.id, + detail: detachDetail, }, } satisfies PendingOrchestrationEffectV2, ]); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index b43d74b2f8236..dd8eb62abc06f 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -318,6 +318,102 @@ function makeProviderThread(input: { }; } +// A Codex native subagent's provider thread is owned by its child app thread +// but reachable from the parent's projection through the subagent record. +const makeNativeChildFixture = Effect.fnUntraced(function* () { + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const eventSink = yield* EventSink.EventSinkV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const now = yield* DateTime.now; + const parentThreadId = ThreadId.make("native-parent"); + const childThreadId = ThreadId.make("native-child"); + const providerSessionId = idAllocator.derive.providerSession({ + providerInstanceId: modelSelection.instanceId, + }); + const childThreadEvent = yield* makeThreadCreatedEvent({ + idAllocator, + threadId: childThreadId, + now, + }); + const childProviderThread = makeProviderThread({ + idAllocator, + threadId: childThreadId, + providerSessionId, + nativeThreadId: "native-child-thread", + now, + }); + const parentRunId = idAllocator.derive.run({ threadId: parentThreadId, ordinal: 1 }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId: parentThreadId, now }), + { + ...childThreadEvent, + payload: { + ...childThreadEvent.payload, + createdBy: "agent", + creationSource: "provider", + activeProviderThreadId: null, + lineage: { + parentThreadId, + relationshipToParent: "subagent", + rootThreadId: parentThreadId, + }, + }, + }, + { + id: yield* idAllocator.allocate.event({ threadId: childThreadId }), + type: "provider-thread.updated", + threadId: childThreadId, + occurredAt: now, + payload: childProviderThread, + }, + { + id: yield* idAllocator.allocate.event({ threadId: parentThreadId }), + type: "subagent.updated", + threadId: parentThreadId, + occurredAt: now, + payload: { + id: idAllocator.derive.nodeFromProviderItem({ + driver: CODEX_DRIVER, + nativeItemId: "native-child-task", + }), + threadId: parentThreadId, + runId: parentRunId, + parentNodeId: idAllocator.derive.rootNode({ runId: parentRunId }), + origin: "provider_native", + createdBy: "agent", + driver: CODEX_DRIVER, + providerInstanceId: modelSelection.instanceId, + providerThreadId: childProviderThread.id, + childThreadId, + nativeTaskRef: { + driver: CODEX_DRIVER, + nativeId: "native-child-task", + strength: "strong", + }, + prompt: "Reply READY", + title: "Native child", + model: null, + status: "completed", + result: "READY", + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }, + ], + }); + const parent = { threadId: parentThreadId, providerSessionId }; + const runtime = yield* manager.open({ ...parent, modelSelection, runtimePolicy }); + const resumeChild = runtime.resumeThread({ + providerThread: childProviderThread, + threadId: childThreadId, + modelSelection, + runtimePolicy, + }); + return { manager, parent, resumeChild }; +}); + function unimplemented(detail: string) { return Effect.fail( new ProviderAdapter.ProviderAdapterProtocolError({ @@ -4320,6 +4416,40 @@ it.effect( }), ); +it.effect( + "ProviderSessionManagerV2 keeps an attached native child loaded when its parent detaches", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + yield* Effect.gen(function* () { + const { manager, parent, resumeChild } = yield* makeNativeChildFixture(); + yield* resumeChild; + yield* manager.detach(parent); + + assert.deepEqual((yield* Ref.get(state)).unloadedNativeThreadIds, []); + // The child's next turn trusts the manager's loaded cache, so the + // native thread must still be loaded for that turn to be heard. + yield* resumeChild; + assert.equal((yield* Ref.get(state)).resumeCount, 1); + assert.isTrue(yield* manager.isLive(parent.providerSessionId)); + }).pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 1000 })), Effect.scoped); + }), +); + +it.effect( + "ProviderSessionManagerV2 unloads an unattached native child when its parent detaches", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + yield* Effect.gen(function* () { + const { manager, parent } = yield* makeNativeChildFixture(); + yield* manager.detach(parent); + + assert.deepEqual((yield* Ref.get(state)).unloadedNativeThreadIds, ["native-child-thread"]); + }).pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 1000 })), Effect.scoped); + }), +); + it.effect( "ProviderSessionManagerV2 re-attaching a thread waits for its in-flight unload, then reloads it", () => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index ffafbbef7fb32..252c6e4f190b2 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2587,38 +2587,38 @@ export const layerWithOptions = ( } const unloadThread = detached.value.exposedRuntime.unloadThread; if (detached.value.supportsMultipleProviderThreads && unloadThread !== undefined) { - // Serialize unload with attachment so attached threads stay loaded and later attaches resume after unload. - yield* threadAttachment.withLock( - threadAttachmentKey(input), - Effect.gen(function* () { - const entry = (yield* Ref.get(sessions)).get(key); - if ( - entry?.runtime !== detached.value.runtime || - entry.attachedThreadIds.has(input.threadId) - ) { - return; - } - yield* Effect.forEach( - detachedProviderThreads.filter((thread) => thread.nativeThreadRef !== null), - (providerThread) => - unloadThread({ providerThread }).pipe( - Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS), - Effect.catchCause((cause) => - Effect.logWarning( - "orchestration-v2.driver-session.detach-unload-failed", - { - providerSessionId: input.providerSessionId, - threadId: input.threadId, - providerThreadId: providerThread.id, - cause, - }, - ), - ), + // The projection includes native children owned by other app threads; + // lock each owner so an attached child stays loaded and later attaches wait. + for (const providerThread of detachedProviderThreads) { + if (providerThread.nativeThreadRef === null) continue; + const ownerThreadId = providerThread.appThreadId ?? input.threadId; + yield* threadAttachment.withLock( + threadAttachmentKey({ + providerSessionId: input.providerSessionId, + threadId: ownerThreadId, + }), + Effect.gen(function* () { + const entry = (yield* Ref.get(sessions)).get(key); + if ( + entry?.runtime !== detached.value.runtime || + entry.attachedThreadIds.has(ownerThreadId) + ) { + return; + } + yield* unloadThread({ providerThread }).pipe( + Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS), + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.driver-session.detach-unload-failed", { + providerSessionId: input.providerSessionId, + threadId: ownerThreadId, + providerThreadId: providerThread.id, + cause, + }), ), - { concurrency: 1, discard: true }, - ); - }), - ); + ); + }), + ); + } } yield* scheduleIdleRelease(input.providerSessionId); }, diff --git a/apps/server/src/orchestration-v2/RunFinalizationService.test.ts b/apps/server/src/orchestration-v2/RunFinalizationService.test.ts index 38a18192531a5..b51ec8fb80de0 100644 --- a/apps/server/src/orchestration-v2/RunFinalizationService.test.ts +++ b/apps/server/src/orchestration-v2/RunFinalizationService.test.ts @@ -5,8 +5,12 @@ import { ThreadId, type OrchestrationV2ThreadShell, } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as TestClock from "effect/testing/TestClock"; import * as PullRequestService from "../pullRequest/PullRequestService.ts"; import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts"; @@ -93,6 +97,7 @@ it.effect.each( ).map((scenario) => [scenario.label, scenario] as const), )("%s", ([, scenario]) => { const refreshed: string[] = []; + const lookedUp = Deferred.makeUnsafe(); const threadId = ThreadId.make("thread-pr-refresh"); const runId = RunId.make("completed-run"); const layer = RunFinalization.layerObserver.pipe( @@ -114,11 +119,11 @@ it.effect.each( }), refreshStatus: () => Effect.die("turn completion must preserve known PRs and lookup backoff"), - refreshPullRequestStatus: (cwd) => - Effect.sync(() => { - refreshed.push(cwd); - return null; - }), + // Requested synchronously by refresh; the lookup itself runs in the background. + refreshPullRequestStatus: (cwd) => { + refreshed.push(cwd); + return Deferred.succeed(lookedUp, undefined).pipe(Effect.as(null)); + }, }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ getThreadShell: () => @@ -134,6 +139,105 @@ it.effect.each( return Effect.gen(function* () { const observer = yield* RunFinalization.RunFinalizationObserver; yield* observer.refresh({ cwd: "/repo", threadId, runId }); + if (scenario.expected.length > 0) yield* Deferred.await(lookedUp); assert.deepEqual(refreshed, [...scenario.expected]); }).pipe(Effect.provide(layer)); }); + +it.effect("returns from the post-turn refresh without waiting for the PR lookup", () => { + const threadId = ThreadId.make("thread-slow-forge"); + const runId = RunId.make("completed-run"); + const layer = RunFinalization.layerObserver.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(WorkspaceEntries.WorkspaceEntries)({ refresh: () => Effect.void }), + Layer.mock(PullRequestService.PullRequestService)({ + refreshAfterTurn: () => Effect.void, + }), + Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({ + refreshLocalStatus: () => + Effect.succeed({ + isRepo: true, + hasPrimaryRemote: true, + isDefaultRef: false, + refName: "feature", + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + }), + refreshPullRequestStatus: () => Effect.never, + }), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadShell: () => + Effect.succeed({ + id: threadId, + branch: "feature", + activeRunId: null, + } as OrchestrationV2ThreadShell), + }), + ), + ), + ); + return Effect.gen(function* () { + const observer = yield* RunFinalization.RunFinalizationObserver; + const refresh = yield* observer + .refresh({ cwd: "/repo", threadId, runId }) + .pipe(Effect.timeoutOption("1 minute"), Effect.forkChild({ startImmediately: true })); + yield* TestClock.adjust("1 minute"); + const result = yield* Fiber.join(refresh); + assert.isTrue( + Option.isSome(result), + "turn finalization waited on the forge PR lookup, blocking the thread's next turn", + ); + }).pipe(Effect.provide(layer)); +}); + +it.effect("replaces a still-running PR lookup when a newer turn finishes", () => { + const threadId = ThreadId.make("thread-back-to-back"); + const runId = RunId.make("completed-run"); + const firstInterrupted = Deferred.makeUnsafe(); + const secondLookedUp = Deferred.makeUnsafe(); + let lookups = 0; + const layer = RunFinalization.layerObserver.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(WorkspaceEntries.WorkspaceEntries)({ refresh: () => Effect.void }), + Layer.mock(PullRequestService.PullRequestService)({ + refreshAfterTurn: () => Effect.void, + }), + Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({ + refreshLocalStatus: () => + Effect.succeed({ + isRepo: true, + hasPrimaryRemote: true, + isDefaultRef: false, + refName: "feature", + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + }), + refreshPullRequestStatus: () => + ++lookups === 1 + ? Effect.never.pipe( + Effect.onInterrupt(() => Deferred.succeed(firstInterrupted, undefined)), + ) + : Deferred.succeed(secondLookedUp, undefined).pipe(Effect.as(null)), + }), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadShell: () => + Effect.succeed({ + id: threadId, + branch: "feature", + activeRunId: null, + } as OrchestrationV2ThreadShell), + }), + ), + ), + ); + return Effect.gen(function* () { + const observer = yield* RunFinalization.RunFinalizationObserver; + yield* observer.refresh({ cwd: "/repo", threadId, runId }); + yield* observer.refresh({ cwd: "/repo", threadId, runId }); + yield* Deferred.await(firstInterrupted); + yield* Deferred.await(secondLookedUp); + assert.strictEqual(lookups, 2); + }).pipe(Effect.provide(layer)); +}); diff --git a/apps/server/src/orchestration-v2/RunFinalizationService.ts b/apps/server/src/orchestration-v2/RunFinalizationService.ts index 40882033ba527..3775e63f0e733 100644 --- a/apps/server/src/orchestration-v2/RunFinalizationService.ts +++ b/apps/server/src/orchestration-v2/RunFinalizationService.ts @@ -1,6 +1,7 @@ import { CheckpointScopeId, ProjectId, RunId, ThreadId } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as FiberMap from "effect/FiberMap"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; @@ -96,6 +97,7 @@ export const layerObserver = Layer.effect( const vcsStatus = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; const projections = yield* ProjectionStore.ProjectionStoreV2; const pullRequests = yield* PullRequestService.PullRequestService; + const pullRequestLookups = yield* FiberMap.make(); return { refreshAfterTurn: pullRequests.refreshAfterTurn, refresh: Effect.fn("RunFinalizationService.refresh")( @@ -108,6 +110,8 @@ export const layerObserver = Layer.effect( const thread = yield* projections.getThreadShell(threadId); if (!thread || thread.branch !== local.refName) return; if (thread.activeRunId !== null && thread.activeRunId !== runId) return; + // The forge CLI can take minutes, so the next turn must not wait for it. A newer + // turn's lookup replaces a running one instead of queueing behind the cwd's lock. yield* vcsStatus.refreshPullRequestStatus(cwd).pipe( Effect.catch((error) => Effect.logWarning("failed to refresh pull request status after run completion", { @@ -116,6 +120,7 @@ export const layerObserver = Layer.effect( detail: error.message, }), ), + FiberMap.run(pullRequestLookups, cwd), ); }, (effect, { cwd }) => diff --git a/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts index 043f789e9598e..9c2ff9ef18f7a 100644 --- a/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts @@ -16,6 +16,8 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; @@ -152,6 +154,7 @@ describe("ThreadPullRequestServiceV2 reads", () => { SecureRandom.make((size) => new Uint8Array(size).fill(1)), ), FileSystem.layerNoop({}), + Path.layer, ); yield* Effect.gen(function* () { const service = yield* ThreadPullRequestService.make; @@ -176,6 +179,127 @@ describe("ThreadPullRequestServiceV2 reads", () => { ), ); + it.effect.each([ + { + worktree: "a linked worktree", + existingPaths: ["/workspace/worktree", "/workspace/worktree/.git"], + unreadablePaths: [], + cwd: "/workspace/worktree", + }, + // A folder that outlived its .git makes git fail with not_a_repository. + { + worktree: "a folder without .git", + existingPaths: ["/workspace/worktree"], + unreadablePaths: [], + cwd: "/workspace/project", + }, + { + worktree: "a folder whose .git cannot be checked", + existingPaths: ["/workspace/worktree"], + unreadablePaths: ["/workspace/worktree/.git"], + cwd: "/workspace/worktree", + }, + { + worktree: "a missing folder", + existingPaths: [], + unreadablePaths: [], + cwd: "/workspace/project", + }, + ] as const)( + "looks up a branch whose worktree is $worktree in $cwd", + ({ existingPaths, unreadablePaths, cwd }) => + Effect.scoped( + Effect.gen(function* () { + const thread = { + ...threadShell("worktree-thread"), + branch: "feature/worktree", + worktreePath: "/workspace/worktree", + }; + const project: OrchestrationProjectShell = { + id: thread.projectId, + title: "Project", + workspaceRoot: "/workspace/project", + defaultModelSelection: null, + scripts: [], + createdAt: "2026-08-01T00:00:00.000Z", + updatedAt: "2026-08-01T00:00:00.000Z", + }; + const activation = yield* Deferred.make(); + const sweepStarted = yield* Deferred.make(); + const lookupCwds: Array = []; + const dependencies = Layer.mergeAll( + Layer.mock(Orchestrator.OrchestratorV2)({ + streamDomainEvents: Stream.never, + getShellSnapshot: () => + Deferred.succeed(sweepStarted, undefined).pipe( + Effect.as({ + schemaVersion: 2, + snapshotSequence: 1, + threads: [thread], + archivedThreads: [], + }), + ), + }), + Layer.mock(ProjectStore.ProjectStoreV2)({ + listShells: () => Effect.succeed([project]), + getShell: () => Effect.succeedSome(project), + }), + Layer.mock(GitManager.GitManager)({ + branchPullRequest: (input) => + Effect.sync(() => { + lookupCwds.push(input.cwd); + return null; + }), + }), + Layer.mock(PullRequestService.PullRequestService)({}), + Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({ + resolve: () => + Effect.succeed({ + canonicalKey: "github.com/acme/project", + locator: { + source: "git-remote" as const, + remoteName: "origin", + remoteUrl: "git@github.com:acme/project.git", + }, + provider: SourceControlProviderKind.make("github"), + owner: "acme", + name: "project", + }), + }), + Layer.mock(BackgroundPolicy.BackgroundPolicy)({}), + Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)), + Layer.succeed( + SecureRandom.SecureRandom, + SecureRandom.make((size) => new Uint8Array(size).fill(1)), + ), + FileSystem.layerNoop({ + exists: (path) => + unreadablePaths.some((entry) => entry === path) + ? Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "exists", + pathOrDescriptor: path, + }), + ) + : Effect.succeed(existingPaths.some((entry) => entry === path)), + }), + Path.layer, + ); + yield* Effect.gen(function* () { + const service = yield* ThreadPullRequestService.make; + yield* service.start(); + yield* Deferred.succeed(activation, undefined); + yield* Deferred.await(sweepStarted); + yield* service.drain; + }).pipe(Effect.provide(dependencies)); + + expect(lookupCwds).toEqual([cwd]); + }), + ), + ); + it.effect("leaves delegated child threads to their own refresh instead of the sweep", () => Effect.scoped( Effect.gen(function* () { @@ -264,6 +388,7 @@ describe("ThreadPullRequestServiceV2 reads", () => { SecureRandom.make((size) => new Uint8Array(size).fill(1)), ), FileSystem.layerNoop({}), + Path.layer, ); yield* Effect.gen(function* () { const service = yield* ThreadPullRequestService.make; @@ -387,6 +512,7 @@ describe("ThreadPullRequestServiceV2 reads", () => { SecureRandom.make((size) => new Uint8Array(size).fill(1)), ), FileSystem.layerNoop({}), + Path.layer, ); yield* Effect.gen(function* () { const service = yield* ThreadPullRequestService.make; diff --git a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.ts index 689d9ca99ce98..e221388a5b8c0 100644 --- a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts +++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.ts @@ -14,6 +14,7 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Schedule from "effect/Schedule"; import type * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; @@ -102,6 +103,7 @@ export const make = Effect.gen(function* () { const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; const random = yield* SecureRandom.SecureRandom; const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; const pendingBackfill = new Map(); @@ -188,10 +190,13 @@ export const make = Effect.gen(function* () { refresh: request.refresh, }); if (first.branch !== null && repository === null) return finishBackfill(group); - const worktreeExists = - first.worktreePath !== null && (yield* fileSystem.exists(first.worktreePath)); + // A worktree folder can outlive its .git, and git there fails with not_a_repository. + // An unreadable .git keeps the worktree rather than failing the whole group. const cwd = - worktreeExists && first.worktreePath !== null + first.worktreePath !== null && + (yield* fileSystem + .exists(path.join(first.worktreePath, ".git")) + .pipe(Effect.orElseSucceed(() => true))) ? first.worktreePath : project.workspaceRoot; const detected = diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index f118cd13a62dc..1d8e514942719 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -25,6 +25,8 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; import * as PubSub from "effect/PubSub"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; @@ -553,6 +555,7 @@ interface HarnessOptions { readonly branchPullRequest?: GitManager.GitManager["Service"]["branchPullRequest"]; readonly pullRequestSummary?: PullRequestService.PullRequestService["Service"]["summary"]; readonly existingWorktreePaths?: ReadonlyArray; + readonly unreadablePaths?: ReadonlyArray; readonly onDispatch?: (command: AutoSettleCommand) => Effect.Effect; readonly onScriptRun?: ( input: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput, @@ -702,8 +705,19 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)), Layer.succeed(SecureRandom.SecureRandom, testCrypto), FileSystem.layerNoop({ - exists: (path) => Effect.succeed(options.existingWorktreePaths?.includes(path) ?? false), + exists: (path) => + options.unreadablePaths?.includes(path) + ? Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "exists", + pathOrDescriptor: path, + }), + ) + : Effect.succeed(options.existingWorktreePaths?.includes(path) ?? false), }), + Path.layer, ); return { @@ -897,6 +911,117 @@ describe("ThreadSettlementServiceV2 worker", () => { ), ); + it.effect("looks up a branch in its worktree only while the worktree has .git", () => + Effect.scoped( + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([ + makeThread("linked-worktree", { + branch: "linked", + worktreePath: "/worktrees/linked", + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + }), + // A folder that outlived its .git makes git fail with not_a_repository. + makeThread("emptied-worktree", { + branch: "emptied", + worktreePath: "/worktrees/emptied", + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + }), + ]), + existingWorktreePaths: [ + "/worktrees/linked", + "/worktrees/linked/.git", + "/worktrees/emptied", + ], + }); + + yield* Effect.gen(function* () { + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads); + const cwdByBranch = Object.fromEntries( + (yield* Ref.get(fixture.branchCalls)).map((call) => [call.branch, call.cwd]), + ); + expect(cwdByBranch).toEqual({ + linked: "/worktrees/linked", + emptied: "/workspace/project", + }); + }).pipe(Effect.provide(fixture.layer)); + }), + ), + ); + + it.effect("does not settle a thread whose worktree cannot be checked", () => + Effect.scoped( + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot( + [ + makeThread("unreadable-worktree", { + branch: "unreadable", + worktreePath: "/worktrees/unreadable", + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + }), + // A merged linked pull request still needs the branch recheck before settling. + makeThread("unreadable-linked-worktree", { + branch: "feature", + worktreePath: "/worktrees/unreadable-linked", + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + linkedPullRequest: { + projectId: PROJECT_ID, + repository: "owner/repository", + number: 41, + url: "https://example.test/owner/repository/pull/41", + }, + }), + makeThread("readable-worktree", { + branch: "readable", + worktreePath: "/worktrees/readable", + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + }), + ], + [ + { + ...makeProject(), + repositoryIdentity: { + canonicalKey: "example.test/owner/repository", + locator: { + source: "git-remote", + remoteName: "origin", + remoteUrl: "https://example.test/owner/repository.git", + }, + provider: SourceControlProviderKind.make("github"), + owner: "owner", + name: "repository", + }, + }, + ], + ), + existingWorktreePaths: ["/worktrees/readable", "/worktrees/readable/.git"], + unreadablePaths: ["/worktrees/unreadable/.git", "/worktrees/unreadable-linked/.git"], + pullRequestSummary: (input) => + Effect.succeed({ + ...makePullRequestSummary({ ...input, state: "merged" }), + mergedAt: NOW, + }), + branchPullRequest: (input) => + input.cwd.startsWith("/worktrees/unreadable") + ? Effect.die(new Error("git: permission denied")) + : Effect.succeed(makeBranchPullRequest("merged")), + }); + + yield* Effect.gen(function* () { + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads); + expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([ + ThreadId.make("readable-worktree"), + ]); + }).pipe(Effect.provide(fixture.layer)); + }), + ), + ); + it.effect("reevaluates immediately after a pull request merge", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 99fcb077aa718..8c2dcfe8868cc 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -19,6 +19,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as FiberSet from "effect/FiberSet"; import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; import * as Schedule from "effect/Schedule"; import * as Semaphore from "effect/Semaphore"; import type * as Scope from "effect/Scope"; @@ -297,6 +298,7 @@ export const make = Effect.gen(function* () { const pullRequests = yield* PullRequestService.PullRequestService; const random = yield* SecureRandom.SecureRandom; const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; // A shell merge or close sends no event, and the branch lookup caches an open pull request for // a minute, so these threads' next lookup reads the host fresh. const shellClosedThreads = new Set(); @@ -394,12 +396,14 @@ export const make = Effect.gen(function* () { Effect.gen(function* () { const project = projects.get(thread.projectId); if (project === undefined || thread.branch === null) return; - const worktreeExists = - thread.worktreePath !== null && - (yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false))); + // A worktree folder can outlive its .git, and git there fails with not_a_repository. + // An unreadable .git keeps the worktree, so git fails there and the thread is skipped. lookupCwdByThreadId.set( thread.id, - worktreeExists && thread.worktreePath !== null + thread.worktreePath !== null && + (yield* fileSystem + .exists(path.join(thread.worktreePath, ".git")) + .pipe(Effect.orElseSucceed(() => true))) ? thread.worktreePath : project.workspaceRoot, ); diff --git a/apps/server/src/orchestration-v2/testkit/OpenCode2PendingSnapshots.evidence.test.ts b/apps/server/src/orchestration-v2/testkit/OpenCode2PendingSnapshots.evidence.test.ts new file mode 100644 index 0000000000000..c22913a23f5a6 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/OpenCode2PendingSnapshots.evidence.test.ts @@ -0,0 +1,159 @@ +import { assert, describe, it } from "@effect/vitest"; +import type { ProviderInstanceId } from "@t3tools/contracts"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Config from "effect/Config"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; + +import { OpenCode2OrchestratorReplayHarness } from "../Adapters/OpenCode2AdapterV2.testkit.ts"; +import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts"; +import { findReplayFixture, runReplayFixture } from "./ProviderReplayFixtures.ts"; + +// Evidence driver: replays recorded OpenCode 2 fixtures through +// OrchestratorV2 and records the adapter's own event stream, because the +// `pendingBackgroundWork` flag is dropped before it reaches domain events. +// Set EV_TRANSCRIPT to a file path to append the transcript there. + +type Row = { + readonly id: string; + readonly fixture: string; + /** True when every native thread must end on a `pendingBackgroundWork: false` snapshot. */ + readonly requireSettledSnapshots: boolean; +}; + +const ROWS: ReadonlyArray = [ + { id: "R1", fixture: "opencode2_nested_background", requireSettledSnapshots: true }, + { id: "R1-compat", fixture: "opencode2_background", requireSettledSnapshots: true }, + { id: "R2c-compat", fixture: "opencode2_resume_after_restart", requireSettledSnapshots: false }, + { id: "R2c-compat", fixture: "opencode2_interrupt", requireSettledSnapshots: false }, + { id: "R3", fixture: "opencode2_simple", requireSettledSnapshots: false }, + { id: "R3", fixture: "opencode2_tool_call", requireSettledSnapshots: false }, +]; + +const tasksOf = (tasks: ReadonlyArray<{ readonly taskId: string }> | undefined) => + `[${(tasks ?? []).map((task) => task.taskId).join(",")}]`; + +const describeEvent = (event: ProviderAdapter.ProviderAdapterV2Event): string | undefined => { + switch (event.type) { + case "provider_thread.updated": + return `provider_thread.updated native=${event.providerThread.nativeThreadRef?.nativeId ?? "?"} pendingBackgroundWork=${String(event.pendingBackgroundWork)} pendingBackgroundTasks=${tasksOf(event.providerThread.pendingBackgroundTasks)}`; + case "provider_turn.updated": + return `provider_turn.updated native=${event.providerTurn.nativeTurnRef?.nativeId ?? "?"} status=${event.providerTurn.status}`; + case "subagent.updated": + return `subagent.updated title=${event.subagent.title ?? "?"} status=${event.subagent.status}`; + case "turn.terminal": + return `turn.terminal status=${event.status}`; + default: + return undefined; + } +}; + +const tappedHarness = ( + record: (event: ProviderAdapter.ProviderAdapterV2Event) => void, +): typeof OpenCode2OrchestratorReplayHarness => ({ + ...OpenCode2OrchestratorReplayHarness, + makeProviderAdapterRegistryLayer: ( + ...args: Parameters + ) => + Layer.effect( + ProviderAdapterRegistry.ProviderAdapterRegistryV2, + Effect.gen(function* () { + const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2; + return ProviderAdapterRegistry.ProviderAdapterRegistryV2.of({ + ...registry, + get: (instanceId: ProviderInstanceId) => + registry.get(instanceId).pipe( + Effect.map((adapter) => + ProviderAdapter.ProviderAdapterV2.of({ + ...adapter, + openSession: (input) => + adapter.openSession(input).pipe( + Effect.map((runtime) => ({ + ...runtime, + events: runtime.events.pipe( + Stream.tap((event) => Effect.sync(() => record(event))), + ), + })), + ), + }), + ), + ), + }); + }), + ).pipe( + Layer.provide(OpenCode2OrchestratorReplayHarness.makeProviderAdapterRegistryLayer(...args)), + ), +}); + +const runRow = (row: Row) => + Effect.gen(function* () { + const fixture = findReplayFixture(row.fixture); + const driver = fixture?.providers.find((provider) => provider.driver === "opencode"); + assert.isDefined(fixture); + assert.isDefined(driver); + const events: Array = []; + const lines: Array = []; + const emit = (line: string) => lines.push(line); + emit(`== ${row.id} ${row.fixture} (recorded fixture) ==`); + const exit = yield* runReplayFixture({ + fixtureName: row.fixture, + buildInput: fixture.buildInput, + driver, + harness: tappedHarness((event) => events.push(event)), + }).pipe(Effect.exit); + let index = 0; + for (const event of events) { + const line = describeEvent(event); + if (line !== undefined) emit(` adapter[${index}] ${line}`); + index += 1; + } + const lastSnapshot = new Map(); + let everPending = false; + for (const event of events) { + if (event.type !== "provider_thread.updated") continue; + const nativeId = event.providerThread.nativeThreadRef?.nativeId ?? "?"; + lastSnapshot.set(nativeId, event.pendingBackgroundWork); + if (event.pendingBackgroundWork === true) everPending = true; + } + const finals = [...lastSnapshot].map(([id, flag]) => `${id}=${String(flag)}`).join(" "); + emit(` final snapshot per native thread: ${finals}`); + if (exit._tag === "Success") { + for (const domain of exit.value.domainEvents) { + if (domain.type !== "provider-thread.updated") continue; + emit( + ` domain provider-thread.updated native=${domain.payload.nativeThreadRef?.nativeId ?? "?"} pendingBackgroundTasks=${tasksOf(domain.payload.pendingBackgroundTasks)}`, + ); + } + } + const failures: Array = []; + if (exit._tag === "Failure") failures.push("fixture output assertions failed"); + if (row.requireSettledSnapshots) { + if (!everPending) failures.push("no pendingBackgroundWork=true snapshot was published"); + for (const [id, flag] of lastSnapshot) { + if (flag !== false) failures.push(`${id} ended on pendingBackgroundWork=${String(flag)}`); + } + } else if ([...lastSnapshot.values()].includes(true)) { + failures.push("a native thread ended with pending work"); + } + emit( + ` ${row.id} ${row.fixture}: ${failures.length === 0 ? "PASS" : `FAIL (${failures.join("; ")})`}`, + ); + const transcript = yield* Config.String("EV_TRANSCRIPT").pipe(Config.withDefault("")); + if (transcript !== "") { + const fs = yield* FileSystem.FileSystem; + yield* fs.writeFileString(transcript, `${lines.join("\n")}\n`, { flag: "a" }); + } + return failures; + }).pipe(Effect.provide(NodeServices.layer)); + +describe("OpenCode 2 pending-work snapshots (#19228 evidence)", () => { + it.effect.each(ROWS.map((row) => [`${row.id} ${row.fixture}`, row] as const))("%s", ([, row]) => + runRow(row).pipe( + Effect.map((failures) => assert.deepEqual(failures, [])), + Effect.scoped, + ), + ); +}); diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index bb21d8ca9929a..f36e463079f99 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -119,6 +119,8 @@ function makeTestAdapter(input: { readonly subagentOnlyBackgroundWork?: boolean; readonly holdFirstTurn?: Deferred.Deferred; readonly releaseFirstTurn?: Deferred.Deferred; + readonly backgroundWork?: Ref.Ref; + readonly closedSessions?: Ref.Ref>; }): ProviderAdapter.ProviderAdapterV2["Service"] { return { instanceId: input.instanceId, @@ -128,6 +130,12 @@ function makeTestAdapter(input: { openSession: (sessionInput) => Effect.gen(function* () { const events = yield* PubSub.unbounded(); + if (input.closedSessions !== undefined) { + const closedSessions = input.closedSessions; + yield* Effect.addFinalizer(() => + Ref.update(closedSessions, (ids) => [...ids, sessionInput.providerSessionId]), + ); + } const now = yield* DateTime.now; const providerSession: OrchestrationV2ProviderSession = { id: sessionInput.providerSessionId, @@ -162,6 +170,14 @@ function makeTestAdapter(input: { ...(input.canReuseContextUsage === undefined ? {} : { canReuseContextUsage: input.canReuseContextUsage }), + ...(input.backgroundWork === undefined + ? {} + : { + // Like Claude: native subagents are visible only to the session-wide + // probe, never to the per-thread roster probe. + hasPendingBackgroundWork: Ref.get(input.backgroundWork), + hasPendingBackgroundWorkForThread: () => Effect.succeed(false), + }), ensureThread: (threadInput) => Effect.gen(function* () { const createdAt = yield* DateTime.now; @@ -748,16 +764,7 @@ describe("orchestration v2 provider switching", () => { yield* wait(3); } if (replaceNative) { - const target = (yield* orchestrator.getThreadProjection(threadId)).providerThreads.find( - (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId, - )!; - yield* orchestrator.dispatch({ - type: "provider-session.detach", - commandId: CommandId.make("detach-for-native-replacement"), - threadId, - providerSessionId: target.providerSessionId!, - }); - yield* worker.drain(); + // Switching back to Codex already released Claude's session. yield* Ref.set(failResumeOnce, true); } if (scenario.includes("retry")) yield* Ref.set(failStartOnce, true); @@ -2520,6 +2527,141 @@ describe("orchestration v2 provider switching", () => { ), ); + // regression: #20343 sending to an instance with separate history must release the old session + it.live.each([ + ["detaches the previous instance's session when a send hands off to another instance", false], + ["refuses the hand-off while the previous instance still runs background work", true], + ] as const)("%s", ([, backgroundRunning]) => + Effect.scoped( + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("handoff-releases-session"); + const capturedTurns = yield* Ref.make>([]); + const backgroundWork = yield* Ref.make(backgroundRunning); + const closedSessions = yield* Ref.make>([]); + const secondSelection: ModelSelection = { + ...CLAUDE_MODEL_SELECTION, + instanceId: ProviderInstanceId.make("claude-second-account"), + }; + // No shared continuation key: each Claude instance owns its own native history. + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ + makeTestAdapter({ + instanceId: CLAUDE_MODEL_SELECTION.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: CLAUDE_MODEL_SELECTION, + responseByRunOrdinal: { 1: "First account complete" }, + capturedTurns, + backgroundWork, + closedSessions, + }), + makeTestAdapter({ + instanceId: secondSelection.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: secondSelection, + responseByRunOrdinal: { 2: "Second account complete" }, + capturedTurns, + }), + ]); + const handoffThreadId = ThreadId.make("thread:handoff-releases-session"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const send = (ordinal: number, modelSelection: ModelSelection, attempt = "") => + orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:handoff-releases-session:${ordinal}${attempt}`), + threadId: handoffThreadId, + messageId: MessageId.make(`message:handoff-releases-session:${ordinal}${attempt}`), + text: `Prompt ${ordinal}`, + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:handoff-releases-session:create"), + threadId: handoffThreadId, + projectId: ProjectId.make("project:handoff-releases-session"), + title: "Handoff releases session", + modelSelection: CLAUDE_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + yield* send(1, CLAUDE_MODEL_SELECTION); + yield* worker.drain(); + const afterFirst = yield* waitForIdle(handoffThreadId); + const firstSession = afterFirst.providerSessions.find( + (session) => session.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId, + ); + assert.equal(firstSession?.status, "ready"); + + if (backgroundRunning) { + // Native subagents live only in the adapter's roster, so the projection's + // pendingBackgroundTasks stays empty while the probe still reports work. + assert.deepEqual(afterFirst.providerThreads[0]?.pendingBackgroundTasks ?? [], []); + const refused = yield* send(2, secondSelection, ":refused").pipe(Effect.flip); + assert.include(String(refused.cause), "still running background agents or commands"); + const unchanged = yield* orchestrator.getThreadProjection(handoffThreadId); + assert.lengthOf(unchanged.runs, 1); + assert.deepEqual(yield* Ref.get(closedSessions), []); + assert.equal(unchanged.thread.providerInstanceId, CLAUDE_MODEL_SELECTION.instanceId); + assert.deepEqual( + unchanged.providerSessions.map((session) => [session.id, session.status]), + [[firstSession!.id, "ready"]], + ); + yield* Ref.set(backgroundWork, false); + } + + yield* send(2, secondSelection); + yield* worker.drain(); + const afterSecond = yield* waitForIdle(handoffThreadId); + yield* worker.drain(); + const projection = yield* orchestrator.getThreadProjection(handoffThreadId); + + assert.deepEqual( + projection.runs.map((run) => [run.providerInstanceId, run.status]), + [ + [CLAUDE_MODEL_SELECTION.instanceId, "completed"], + [secondSelection.instanceId, "completed"], + ], + ); + assert.lengthOf(afterSecond.contextHandoffs, 1); + assert.deepEqual( + projection.providerSessions.map((session) => session.providerInstanceId), + [secondSelection.instanceId], + ); + // The detached event alone hides the session; the runtime must also close. + assert.deepEqual(yield* Ref.get(closedSessions), [firstSession!.id]); + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { + name: "handoff-releases-session", + runtimePolicyOverride: { + cwd, + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }, + layerRegistry, + ), + ), + ); + }), + ), + ); + // regression: #21314 a queued PR update must follow the provider that took over the thread it.live.each([ ["automatic", "Claude"], diff --git a/apps/server/src/persistence/Migrations.test.ts b/apps/server/src/persistence/Migrations.test.ts index 54e4a711aa8a1..bf4b9676e2a5d 100644 --- a/apps/server/src/persistence/Migrations.test.ts +++ b/apps/server/src/persistence/Migrations.test.ts @@ -78,6 +78,44 @@ describe("runMigrations", () => { }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); + it.effect("drops the unused correlation index and keeps correlation values", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 54 }); + yield* sql` + INSERT INTO orchestration_events ( + event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, + command_id, causation_event_id, correlation_id, actor_kind, payload_json, metadata_json + ) + VALUES ( + 'event-1', 'thread', 'thread-1', 0, 'thread.created', '2026-01-01T00:00:00.000Z', + 'command-1', NULL, 'correlation-1', 'client', '{}', '{}' + ) + `; + + yield* runMigrations(); + + const indexes = yield* sql<{ readonly name: string }>` + SELECT name FROM sqlite_master + WHERE type = 'index' AND tbl_name = 'orchestration_events' AND sql IS NOT NULL + `; + const indexNames = indexes.map((row) => row.name); + assert.notInclude(indexNames, "idx_orch_events_correlation_id"); + for (const kept of [ + "idx_orch_events_stream_version", + "idx_orch_events_stream_sequence", + "idx_orch_events_command_id", + "idx_orchestration_events_agent_stream_sequence", + ]) { + assert.include(indexNames, kept); + } + const events = yield* sql<{ readonly correlation_id: string | null }>` + SELECT correlation_id FROM orchestration_events WHERE event_id = 'event-1' + `; + assert.deepStrictEqual(events, [{ correlation_id: "correlation-1" }]); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), + ); + it.effect.each([30, 54])("still starts with a site-local migration at id %s", (id) => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index feab4ef823f00..3ee83e5fe01bf 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -80,6 +80,7 @@ import Migration0074 from "./Migrations/074_ExcludeAttachmentPlaceholdersFromSea import Migration0075 from "./Migrations/075_SubagentDeliveryState.ts"; import Migration0076 from "./Migrations/076_ProjectionProjectsPinArchive.ts"; import Migration0077 from "./Migrations/077_RepairBooleanSettledOverride.ts"; +import Migration0078 from "./Migrations/078_DropOrchestrationEventCorrelationIndex.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -160,6 +161,7 @@ const migrationEntries = [ [75, "SubagentDeliveryState", Migration0075], [76, "ProjectionProjectsPinArchive", Migration0076], [77, "RepairBooleanSettledOverride", Migration0077], + [78, "DropOrchestrationEventCorrelationIndex", Migration0078], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/078_DropOrchestrationEventCorrelationIndex.ts b/apps/server/src/persistence/Migrations/078_DropOrchestrationEventCorrelationIndex.ts new file mode 100644 index 0000000000000..bf00778eff5d9 --- /dev/null +++ b/apps/server/src/persistence/Migrations/078_DropOrchestrationEventCorrelationIndex.ts @@ -0,0 +1,10 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // No query filters events by correlation_id, so this index only adds write + // and storage cost. The column and its values stay. + yield* sql`DROP INDEX IF EXISTS idx_orch_events_correlation_id`; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 4083978758ce0..d062961b3af57 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -57,6 +57,7 @@ describe("V2 preview upgrade", () => { [75, "SubagentDeliveryState"], [76, "ProjectionProjectsPinArchive"], [77, "RepairBooleanSettledOverride"], + [78, "DropOrchestrationEventCorrelationIndex"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -157,6 +158,7 @@ describe("V2 preview upgrade", () => { [75, "SubagentDeliveryState"], [76, "ProjectionProjectsPinArchive"], [77, "RepairBooleanSettledOverride"], + [78, "DropOrchestrationEventCorrelationIndex"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index de2ed0a875509..7111b17eb5b28 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -1083,6 +1083,26 @@ it.effect.each([ { type: "mouseReleased", x: 119 }, ], }, + { + name: "wheel burst before a click", + inputs: [ + ...Array.from({ length: 120 }, () => ({ + type: "wheel", + x: 100, + y: 200, + deltaX: 0, + deltaY: 12, + })), + { type: "mouse", action: "down", x: 100, buttons: 1, button: "left" }, + { type: "mouse", action: "up", x: 100, buttons: 0, button: "left" }, + ], + expected: [ + { type: "mouseMoved", x: -1 }, + { type: "mouseWheel", x: 100, y: 200, deltaX: 0, deltaY: 1440 }, + { type: "mousePressed", x: 100 }, + { type: "mouseReleased", x: 100 }, + ], + }, { name: "modifier changes and drag points", inputs: [ @@ -1117,13 +1137,30 @@ it.effect.each([ expected: [ { type: "mouseMoved", x: -1 }, { type: "mouseMoved", x: 1 }, - { type: "mouseWheel", deltaY: 20 }, - { type: "mouseWheel", deltaY: 30 }, + { type: "mouseWheel", deltaY: 50 }, { type: "mouseMoved", x: 2 }, { type: "keyDown", key: "a" }, { type: "mouseMoved", x: 3 }, ], }, + { + name: "wheel position, modifier and direction boundaries", + inputs: [ + { type: "wheel", x: 1, deltaX: 5, deltaY: 10 }, + { type: "wheel", x: 1, deltaX: 5, deltaY: 10 }, + { type: "wheel", x: 2, deltaY: 10 }, + { type: "wheel", x: 2, deltaY: 10, modifiers: 2 }, + { type: "wheel", x: 2, deltaY: -10, modifiers: 2 }, + { type: "wheel", x: 2, deltaY: -10, modifiers: 2 }, + ], + expected: [ + { type: "mouseMoved", x: -1 }, + { type: "mouseWheel", x: 1, deltaX: 10, deltaY: 20, modifiers: 0 }, + { type: "mouseWheel", x: 2, deltaX: 0, deltaY: 10, modifiers: 0 }, + { type: "mouseWheel", x: 2, deltaY: 10, modifiers: 2 }, + { type: "mouseWheel", x: 2, deltaY: -20, modifiers: 2 }, + ], + }, { name: "text, navigation and resize boundaries", inputs: [ diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 6257a686764f1..7444b84f906e3 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -2639,16 +2639,35 @@ const make = Effect.gen(function* () { : {}), }); } else { - const dispatch = () => dispatchViewerInput(tab, session, viewer, message); + const dispatch = (input: Record) => + dispatchViewerInput(tab, session, viewer, input); if ( message.type === "mouse" && message.action === "move" && message.button === "none" && message.buttons === 0 ) { - await tab.control.humanLatest(viewer.id, `hover:${modifiersOf(message)}`, dispatch); + await tab.control.humanLatest( + viewer.id, + `hover:${modifiersOf(message)}`, + message, + dispatch, + ); + } else if (message.type === "wheel") { + // A reversal stays separate so scrolling clamped at an edge behaves as if unmerged. + await tab.control.humanLatest( + viewer.id, + `wheel:${num(message.x)}:${num(message.y)}:${modifiersOf(message)}:${Math.sign(num(message.deltaX))}:${Math.sign(num(message.deltaY))}`, + message, + dispatch, + (waiting, next) => ({ + ...next, + deltaX: num(waiting.deltaX) + num(next.deltaX), + deltaY: num(waiting.deltaY) + num(next.deltaY), + }), + ); } else { - await tab.control.human(viewer.id, dispatch); + await tab.control.human(viewer.id, () => dispatch(message)); } } } catch { diff --git a/apps/server/src/preview/ServerBrowserPage.test.ts b/apps/server/src/preview/ServerBrowserPage.test.ts index d58fe63047bd5..2c6d3a01bcf74 100644 --- a/apps/server/src/preview/ServerBrowserPage.test.ts +++ b/apps/server/src/preview/ServerBrowserPage.test.ts @@ -98,6 +98,27 @@ describe("server browser element refs", () => { expect(await page.locator("li").count()).toBe(5); }); + it("tells a click target that matches nothing from one that never becomes clickable", async () => { + await page.setContent(``); + const failure = (selector: string) => + ServerBrowserPage.click(page, { selector, timeoutMs: 500 }).then( + () => expect.unreachable(), + ServerBrowserPage.toOperationError, + ); + + const absent = await failure(".definitely-no-such-t3-target"); + expect(absent.tag).toBe("PreviewAutomationTimeoutError"); + expect(absent.message).toBe( + 'The click may have happened and removed its target or navigated; check the page before retrying. No element matches ".definitely-no-such-t3-target" after the timeout; take a fresh snapshot and use its locator.', + ); + expect(absent.cause).toMatchObject({ name: "TimeoutError" }); + const hidden = await failure("button"); + expect(hidden.tag).toBe("PreviewAutomationTimeoutError"); + expect(hidden.message).toBe( + 'The click may have happened; check the page before retrying. "button" still matches an element after the timeout.', + ); + }); + it("does not retarget a removed ref to a replacement node", async () => { await page.setContent(""); const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "original"); diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index d573cd6387c8b..f128bf445e603 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -33,8 +33,8 @@ export class ServerBrowserOperationError extends Error { readonly tag: string; readonly detail: unknown; - constructor(tag: string, message: string, detail?: unknown) { - super(message); + constructor(tag: string, message: string, detail?: unknown, options?: ErrorOptions) { + super(message, options); this.tag = tag; this.detail = detail; } @@ -72,6 +72,8 @@ export const toOperationError = ( }; const DEFAULT_TIMEOUT_MS = 15_000; +const TARGET_COUNT_MS = 250; +const MAX_TARGET_CHARS = 200; const pageRefs = new WeakMap }>(); // A compact runtime namespace prevents old refs from aliasing after a server restart. @@ -634,6 +636,58 @@ export const click = async ( ): Promise<{ readonly x: number; readonly y: number }> => { const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; const locator = targetLocator(page, input); + try { + return await clickTarget(page, locator, input, timeout, pointer); + } catch (cause) { + throw locator === null ? cause : await namedTargetTimeout(locator, input, cause); + } +}; + +/** + * Playwright's timeout names neither the target nor why it waited. Counting only after the + * wait failed keeps auto-wait intact, but the count describes the page after the timeout, not + * what the click did: Playwright can dispatch the click and then time out waiting for the + * navigation it started. + */ +const namedTargetTimeout = async ( + locator: Locator, + input: { readonly locator?: string | undefined; readonly selector?: string | undefined }, + cause: unknown, +) => { + if (!(cause instanceof Error && cause.name === "TimeoutError")) return cause; + const selector = JSON.stringify(input.locator ?? input.selector); + // The warning leads and the target is capped, so a reply cut short still carries the warning. + const target = + selector.length > MAX_TARGET_CHARS ? `${selector.slice(0, MAX_TARGET_CHARS)}...` : selector; + // The host's reply must still beat the broker's short grace after the operation timeout. + let timer: ReturnType | undefined; + const matches = await Promise.race([ + locator.count().catch(() => undefined), + new Promise((resolve) => { + timer = setTimeout(() => resolve(undefined), TARGET_COUNT_MS); + }), + ]).finally(() => clearTimeout(timer)); + const reason = + matches === undefined + ? `The click may have happened; check the page before retrying. Whether ${target} still matches an element is unknown.` + : matches === 0 + ? `The click may have happened and removed its target or navigated; check the page before retrying. No element matches ${target} after the timeout; take a fresh snapshot and use its locator.` + : `The click may have happened; check the page before retrying. ${target} still matches an element after the timeout.`; + return new ServerBrowserOperationError( + "PreviewAutomationTimeoutError", + reason, + { reason }, + { cause }, + ); +}; + +const clickTarget = async ( + page: Page, + locator: Locator | null, + input: PreviewAutomationClickInput, + timeout: number, + pointer: PointerReporter, +) => { const point = await targetPoint(page, locator, input, timeout); await pointer(point, "click"); const options = { button: input.button ?? "left", clickCount: input.clickCount ?? 1 } as const; diff --git a/apps/server/src/preview/SessionControl.test.ts b/apps/server/src/preview/SessionControl.test.ts index e086ad854b3fb..f47be6319cb81 100644 --- a/apps/server/src/preview/SessionControl.test.ts +++ b/apps/server/src/preview/SessionControl.test.ts @@ -9,14 +9,14 @@ describe("SessionControl", () => { const started = Promise.withResolvers(); const finish = Promise.withResolvers(); const events: Array = []; - const running = control.humanLatest("viewer", "hover:0", async () => { + const running = control.humanLatest("viewer", "hover:0", undefined, async () => { events.push("running"); started.resolve(); await finish.promise; }); await started.promise; const moves = Array.from({ length: 120 }, (_, position) => - control.humanLatest("viewer", "hover:0", async () => { + control.humanLatest("viewer", "hover:0", undefined, async () => { events.push(position); }), ); @@ -36,7 +36,7 @@ describe("SessionControl", () => { const finish = Promise.withResolvers(); const events: string[] = []; const running = control.human("viewer", () => finish.promise); - const before = control.humanLatest("viewer", "hover:0", async () => { + const before = control.humanLatest("viewer", "hover:0", undefined, async () => { events.push("before"); }); const recordBarrier = async () => { @@ -44,11 +44,11 @@ describe("SessionControl", () => { }; const between = barrier === "modifiers" - ? control.humanLatest("viewer", "hover:2", recordBarrier) + ? control.humanLatest("viewer", "hover:2", undefined, recordBarrier) : barrier === "system" ? control.system(recordBarrier) : control.human("viewer", recordBarrier); - const after = control.humanLatest("viewer", "hover:0", async () => { + const after = control.humanLatest("viewer", "hover:0", undefined, async () => { events.push("after"); }); finish.resolve(); @@ -63,15 +63,15 @@ describe("SessionControl", () => { const finish = Promise.withResolvers(); const events: string[] = []; const running = control.human("viewer", () => finish.promise); - const stale = control.humanLatest("viewer", "hover", async () => { + const stale = control.humanLatest("viewer", "hover", undefined, async () => { events.push("stale"); }); await expect( - control.humanLatest("other", "hover", async () => { + control.humanLatest("other", "hover", undefined, async () => { events.push("other"); }), ).rejects.toThrow(BrowserControlInterrupted); - const latest = control.humanLatest("viewer", "hover", async () => { + const latest = control.humanLatest("viewer", "hover", undefined, async () => { events.push("latest"); }); finish.resolve(); @@ -93,16 +93,16 @@ describe("SessionControl", () => { }); await started.promise; const stale = expect( - control.humanLatest("viewer", "hover", async () => { + control.humanLatest("viewer", "hover", undefined, async () => { events.push("stale"); }), ).rejects.toThrow(BrowserControlInterrupted); const released = control[handoff]("viewer"); const retaken = control.take("viewer"); - const fresh = control.humanLatest("viewer", "hover", async () => { + const fresh = control.humanLatest("viewer", "hover", undefined, async () => { events.push("fresh"); }); - const latest = control.humanLatest("viewer", "hover", async () => { + const latest = control.humanLatest("viewer", "hover", undefined, async () => { events.push("latest"); }); finish.resolve(); @@ -124,14 +124,14 @@ describe("SessionControl", () => { await started.promise; const waiting = [1, 2].map((position) => expect( - control.humanLatest("viewer", "hover", async () => { + control.humanLatest("viewer", "hover", undefined, async () => { events.push(`hover ${position}`); }), ).rejects.toThrow("closed"), ); const closed = control.close(); await expect( - control.humanLatest("viewer", "hover", async () => { + control.humanLatest("viewer", "hover", undefined, async () => { events.push("after close"); }), ).rejects.toThrow("closed"); @@ -147,18 +147,18 @@ describe("SessionControl", () => { const events: string[] = []; const running = control.human("viewer", () => finish.promise); const first = expect( - control.humanLatest("viewer", "hover", async () => { + control.humanLatest("viewer", "hover", undefined, async () => { events.push("superseded"); }), ).rejects.toThrow("dispatch failed"); const last = expect( - control.humanLatest("viewer", "hover", async () => { + control.humanLatest("viewer", "hover", undefined, async () => { throw new Error("dispatch failed"); }), ).rejects.toThrow("dispatch failed"); finish.resolve(); await Promise.all([running, first, last]); - await control.humanLatest("viewer", "hover", async () => { + await control.humanLatest("viewer", "hover", undefined, async () => { events.push("recovered"); }); expect(events).toEqual(["recovered"]); @@ -177,10 +177,10 @@ describe("SessionControl", () => { ); return "started"; }); - const first = control.humanLatest("viewer", "hover", async () => { + const first = control.humanLatest("viewer", "hover", undefined, async () => { events.push("superseded"); }); - const latest = control.humanLatest("viewer", "hover", async () => { + const latest = control.humanLatest("viewer", "hover", undefined, async () => { events.push("latest"); }); await expect(navigation).resolves.toBe("started"); diff --git a/apps/server/src/preview/SessionControl.ts b/apps/server/src/preview/SessionControl.ts index cff65d3379a02..57644e3be7135 100644 --- a/apps/server/src/preview/SessionControl.ts +++ b/apps/server/src/preview/SessionControl.ts @@ -23,7 +23,7 @@ export class SessionControl { private readonly onGenerationChange: () => void; private tail: Promise = Promise.resolve(); private latestHuman: { - entry: { viewerId: string; key: string; run: () => Promise }; + entry: { viewerId: string; key: string; input: unknown; run: (input: never) => Promise }; result: Promise; } | null = null; private pending: Promise = Promise.resolve(); @@ -134,18 +134,28 @@ export class SessionControl { return this.action(() => this.owner === viewerId, run); } - /** Replace only adjacent waiting work; the running action and intervening actions keep their order. */ - humanLatest(viewerId: string, key: string, run: () => Promise): Promise { - if (this.closed || this.owner !== viewerId) return this.human(viewerId, run); + /** + * Merge into only adjacent waiting work with the same key; the running action and + * intervening actions keep their order. Work sharing a key must share its input type. + */ + humanLatest( + viewerId: string, + key: string, + input: A, + run: (input: A) => Promise, + merge: (waiting: A, next: A) => A = (_waiting, next) => next, + ): Promise { + if (this.closed || this.owner !== viewerId) return this.human(viewerId, () => run(input)); const latest = this.latestHuman; if (latest?.entry.viewerId === viewerId && latest.entry.key === key) { + latest.entry.input = merge(latest.entry.input as A, input); latest.entry.run = run; return latest.result; } - const entry = { viewerId, key, run }; + const entry = { viewerId, key, input, run }; const result = this.human(viewerId, async () => { if (this.latestHuman?.entry === entry) this.latestHuman = null; - await entry.run(); + await entry.run(entry.input); }); this.latestHuman = { entry, result }; return result; diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 688b974e7658d..ce1830b8c5710 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -1,4 +1,8 @@ +// @effect-diagnostics nodeBuiltinImport:off - FIFO gates must be released with a synchronous +// open on the main thread, because the Effect FileSystem queues behind the pinned libuv pool. import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; import { describe, expect, it } from "@effect/vitest"; import { @@ -9,9 +13,11 @@ import { ProviderInstanceId, type ServerSettings as ContractServerSettings, } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -248,6 +254,42 @@ const makeFileIdentityFixture = Effect.fn("AgentSessionScanner.test.makeFileIden }, ); +const LIBUV_POOL_SIZE = Number(process.env.UV_THREADPOOL_SIZE ?? 4); + +/** + * Opening a FIFO for reading waits in `open()` until a writer appears, like a + * TCC-protected file in a headless macOS daemon, and pins one libuv pool thread + * that fiber interruption cannot free. The finalizer opens it for writing on the + * main thread, which releases every waiting reader even with the pool exhausted. + */ +const makeOpenGate = Effect.fn("AgentSessionScanner.test.makeOpenGate")(function* ( + gatePath: string, +) { + NodeChildProcess.execFileSync("mkfifo", [gatePath]); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + try { + NodeFS.closeSync( + NodeFS.openSync(gatePath, NodeFS.constants.O_WRONLY | NodeFS.constants.O_NONBLOCK), + ); + } catch { + // ENXIO: no reader is waiting. + } + }), + ); +}); + +/** + * Resolves once a reader has opened the FIFO, so its read deadline is already + * scheduled on the TestClock. The writer stays open until the scope closes, so + * the reader sees no EOF and has to wait out that deadline. + */ +const awaitGateReader = (gatePath: string) => + Effect.acquireRelease( + Effect.promise(() => NodeFS.promises.open(gatePath, NodeFS.constants.O_WRONLY)), + (handle) => Effect.promise(() => handle.close()), + ); + it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { describe("scan", () => { it.effect("reads Claude project cwds from transcripts, newest first", () => @@ -1408,9 +1450,11 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { const claudeHomePath = yield* makeTempDir("t3code-record-budget-claude-"); const codexHomePath = yield* makeTempDir("t3code-record-budget-codex-"); const workspace = yield* makeTempDir("t3code-record-budget-workspace-"); - for (const [sessionId, padding, mtimeMs] of [ - ["excessive", "\n".repeat(100_001), nowMs], - ["older", "", nowMs - 1_000], + const exactLimit = makeRecordLimitTranscript(workspace, false); + // The newer transcript has 100,001 records; the older one has exactly 100,000. + for (const [sessionId, contents, mtimeMs] of [ + ["excessive", exactLimit.replace("record-limit-session", "excessive") + "{}\n", nowMs], + ["older", exactLimit, nowMs - 1_000], ] as const) { yield* writeTranscript({ filePath: path.join( @@ -1421,18 +1465,56 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { "24", `rollout-${sessionId}.jsonl`, ), + contents, + mtimeMs, + }); + } + const outcomes = yield* runRecentThreadOutcomes({ + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + }); + expect(outcomes.map((outcome) => outcome._tag)).toEqual(["Skipped", "Importable"]); + expect(outcomes[1]).toMatchObject({ + thread: { providerSessionId: "record-limit-session" }, + }); + }), + ); + + it.effect("imports every transcript that fits the per-file record limit", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-shared-records-claude-"); + const codexHomePath = yield* makeTempDir("t3code-shared-records-codex-"); + const workspace = yield* makeTempDir("t3code-shared-records-workspace-"); + // Together these exceed 100,000 records, but each one is individually valid. + const recordCounts = [20_000, 20_000, 20_000, 58_000]; + for (const [index, recordCount] of recordCounts.entries()) { + yield* writeTranscript({ + filePath: path.join( + codexHomePath, + "sessions", + "2026", + "08", + "24", + `rollout-${index}.jsonl`, + ), contents: [ encodeTranscriptRecord({ type: "session_meta", - payload: { id: sessionId, cwd: workspace }, + payload: { id: `session-${index}`, cwd: workspace }, }), encodeTranscriptRecord({ type: "event_msg", payload: { type: "user_message", message: "Imported prompt" }, }), - ].join("\n") + padding, - mtimeMs, + ].join("\n") + + "\n" + + "{}\n".repeat(recordCount - 2), + mtimeMs: nowMs - index * 1_000, }); } const outcomes = yield* runRecentThreadOutcomes({ @@ -1440,8 +1522,11 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { codexHomePath, workspaceRoot: workspace, }); - expect(outcomes.map((outcome) => outcome._tag)).toEqual(["Skipped", "Importable"]); - expect(outcomes[1]).toMatchObject({ thread: { providerSessionId: "older" } }); + expect( + outcomes.map((outcome) => + outcome._tag === "Importable" ? outcome.thread.providerSessionId : outcome._tag, + ), + ).toEqual(["session-0", "session-1", "session-2", "session-3"]); }), ); @@ -1807,6 +1892,255 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }); }); +describe.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "AgentSessionScanner scan with a git config open() that never returns", + () => { + it.effect( + "completes every scan and leaves the libuv pool free when .git/config is a FIFO", + () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const repo = yield* makeTempDir("t3code-workspace-fifo-config-"); + yield* fileSystem.makeDirectory(path.join(repo, ".git")); + yield* makeOpenGate(path.join(repo, ".git", "config")); + const transcriptPath = path.join(claudeHomePath, "projects", "-fifo", "a.jsonl"); + yield* writeTranscript({ + filePath: transcriptPath, + contents: claudeSessionLine(repo), + mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"), + }); + + for (let attempt = 1; attempt <= LIBUV_POOL_SIZE + 1; attempt++) { + const scan = yield* Effect.forkChild( + runScan({ claudeHomePath, codexHomePath }).pipe( + Effect.map(({ candidates }) => candidates.map(({ path }) => path)), + ), + ); + yield* Effect.scoped( + Effect.gen(function* () { + yield* awaitGateReader(path.join(repo, ".git", "config")); + yield* TestClock.adjust("2 seconds"); + expect(yield* Fiber.join(scan), `scan ${attempt}`).toEqual([repo]); + }), + ); + } + // Hangs if the scans left libuv pool threads stuck in open(). + yield* fileSystem.readFileString(transcriptPath); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("still reads the git identity of repositories next to a blocked one", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const repos = [ + yield* makeTempDir("t3code-workspace-before-"), + yield* makeTempDir("t3code-workspace-blocked-"), + yield* makeTempDir("t3code-workspace-after-"), + ] as const; + for (const [index, repo] of repos.entries()) { + yield* fileSystem.makeDirectory(path.join(repo, ".git")); + const configPath = path.join(repo, ".git", "config"); + if (index === 1) yield* makeOpenGate(configPath); + else + yield* fileSystem.writeFileString( + configPath, + `[remote "origin"]\n\turl = git@github.com:pingdotgg/repo-${index}.git\n`, + ); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, "a.jsonl"), + contents: claudeSessionLine(repo), + mtimeMs: Date.parse(`2026-01-0${index + 1}T00:00:00.000Z`), + }); + } + + for (let attempt = 1; attempt <= 2; attempt++) { + const scan = yield* Effect.forkChild(runScan({ claudeHomePath, codexHomePath })); + const result = yield* Effect.scoped( + Effect.gen(function* () { + yield* awaitGateReader(path.join(repos[1], ".git", "config")); + yield* TestClock.adjust("2 seconds"); + return yield* Fiber.join(scan); + }), + ); + expect( + result.candidates.map((candidate) => ({ path: candidate.path, git: candidate.git })), + `scan ${attempt}`, + ).toEqual([ + { + path: repos[2], + git: { remoteKey: "github.com/pingdotgg/repo-2", repository: "pingdotgg/repo-2" }, + }, + { path: repos[1], git: { remoteKey: null, repository: null } }, + { + path: repos[0], + git: { remoteKey: "github.com/pingdotgg/repo-0", repository: "pingdotgg/repo-0" }, + }, + ]); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("reads every blocked git config of a scan under one deadline", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const root = yield* makeTempDir("t3code-workspace-blocked-configs-"); + const repos = [path.join(root, "repo-a"), path.join(root, "repo-b")]; + for (const repo of repos) { + yield* fileSystem.makeDirectory(path.join(repo, ".git"), { recursive: true }); + yield* makeOpenGate(path.join(repo, ".git", "config")); + } + // Two linked worktrees of one bare repository share its blocked config. + const bareGitDir = path.join(root, "bare.git"); + yield* fileSystem.makeDirectory(bareGitDir); + yield* makeOpenGate(path.join(bareGitDir, "config")); + const worktrees = [path.join(root, "wt-1"), path.join(root, "wt-2")]; + for (const worktree of worktrees) { + const gitDir = path.join(bareGitDir, "worktrees", path.basename(worktree)); + yield* fileSystem.makeDirectory(gitDir, { recursive: true }); + yield* fileSystem.writeFileString(path.join(gitDir, "commondir"), "../..\n"); + yield* fileSystem.makeDirectory(worktree); + yield* fileSystem.writeFileString(path.join(worktree, ".git"), `gitdir: ${gitDir}\n`); + } + for (const [index, cwd] of [...repos, ...worktrees].entries()) { + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, "a.jsonl"), + contents: claudeSessionLine(cwd), + mtimeMs: Date.parse(`2026-01-0${index + 1}T00:00:00.000Z`), + }); + } + + const scan = yield* Effect.forkChild( + runScan({ claudeHomePath, codexHomePath }).pipe( + Effect.map(({ candidates }) => candidates.map(({ path }) => path).toSorted()), + ), + ); + // Every blocked config is open before any deadline passes; reading them + // one after another would leave the later ones unopened. + yield* Effect.forEach( + [...repos.map((repo) => path.join(repo, ".git")), bareGitDir], + (gitDir) => awaitGateReader(path.join(gitDir, "config")), + { concurrency: "unbounded" }, + ); + yield* TestClock.adjust("2 seconds"); + expect(yield* Fiber.join(scan)).toEqual(repos); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("completes every scan when a .git pointer file or commondir never opens", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const root = yield* makeTempDir("t3code-workspace-blocked-pointers-"); + const pointerCheckout = path.join(root, "pointer"); + yield* fileSystem.makeDirectory(pointerCheckout); + yield* makeOpenGate(path.join(pointerCheckout, ".git")); + const worktree = path.join(root, "worktree"); + const worktreeGitDir = path.join(root, "main", ".git", "worktrees", "worktree"); + yield* fileSystem.makeDirectory(worktreeGitDir, { recursive: true }); + yield* makeOpenGate(path.join(worktreeGitDir, "commondir")); + yield* fileSystem.makeDirectory(worktree); + yield* fileSystem.writeFileString( + path.join(worktree, ".git"), + `gitdir: ${worktreeGitDir}\n`, + ); + for (const [index, cwd] of [pointerCheckout, worktree].entries()) { + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, "a.jsonl"), + contents: claudeSessionLine(cwd), + mtimeMs: Date.parse(`2026-01-0${index + 1}T00:00:00.000Z`), + }); + } + + // One scanner across scans: later scans skip the files that blocked. + yield* Effect.gen(function* () { + const scanner = yield* AgentSessionScanner.AgentSessionScanner; + const scanPaths = scanner.scan.pipe( + Effect.map(({ candidates }) => candidates.map(({ path }) => path)), + ); + const first = yield* Effect.forkChild(scanPaths); + // Pointer files are read first, then the commondir files they lead to. + for (const gatePath of [ + path.join(pointerCheckout, ".git"), + path.join(worktreeGitDir, "commondir"), + ]) { + yield* Effect.scoped( + Effect.gen(function* () { + yield* awaitGateReader(gatePath); + yield* TestClock.adjust("2 seconds"); + }), + ); + } + expect(yield* Fiber.join(first)).toEqual([pointerCheckout]); + for (let attempt = 2; attempt <= LIBUV_POOL_SIZE + 1; attempt++) { + expect(yield* scanPaths, `scan ${attempt}`).toEqual([pointerCheckout]); + } + }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath }))); + // Hangs if the scans left libuv pool threads stuck in open(). + yield* fileSystem.readFileString(path.join(worktree, ".git")); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("reads a once-blocked git config again after the retry interval", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const repo = yield* makeTempDir("t3code-workspace-unblocked-config-"); + yield* fileSystem.makeDirectory(path.join(repo, ".git")); + const configPath = path.join(repo, ".git", "config"); + yield* makeOpenGate(configPath); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-unblocked", "a.jsonl"), + contents: claudeSessionLine(repo), + mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"), + }); + const gitOfScan = (scan: AgentSessionScanner.AgentSessionScanner["Service"]["scan"]) => + scan.pipe(Effect.map(({ candidates }) => candidates.map(({ git }) => git))); + + yield* Effect.gen(function* () { + const scanner = yield* AgentSessionScanner.AgentSessionScanner; + const blockedScan = yield* Effect.forkChild(gitOfScan(scanner.scan)); + yield* Effect.scoped( + Effect.gen(function* () { + yield* awaitGateReader(configPath); + yield* TestClock.adjust("2 seconds"); + expect(yield* Fiber.join(blockedScan)).toEqual([ + { remoteKey: null, repository: null }, + ]); + }), + ); + + yield* fileSystem.remove(configPath); + yield* fileSystem.writeFileString( + configPath, + `[remote "origin"]\n\turl = git@github.com:pingdotgg/unblocked.git\n`, + ); + expect(yield* gitOfScan(scanner.scan), "a blocked path is skipped for a while").toEqual([ + { remoteKey: null, repository: null }, + ]); + + yield* TestClock.adjust("10 minutes"); + expect(yield* gitOfScan(scanner.scan)).toEqual([ + { remoteKey: "github.com/pingdotgg/unblocked", repository: "pingdotgg/unblocked" }, + ]); + }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath }))); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + }, +); + describe("parseAgentSessionTranscript", () => { it.each([false, true])( "handles the exact record limit and an interior blank overflow=%s", diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index bbd3ba5a631e0..3ed97f8a7d8f4 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -13,6 +13,7 @@ import { type AgentSessionScanResult, type ProviderInstanceConfig, } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -30,6 +31,7 @@ import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider"; import * as ServerConfig from "../config.ts"; +import * as ProcessRunner from "../processRunner.ts"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts"; import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; @@ -64,6 +66,21 @@ const MAX_IMPORT_BYTES = 4 * 1024 * 1024 * 1024; const MAX_IMPORT_TRANSCRIPTS = 100; const MAX_IMPORT_RECORDS = 100_000; +/** + * open() of a file under macOS privacy protection waits on a consent prompt + * that a headless server never gets, and a FIFO waits for a writer. Either + * pins a libuv pool thread that interruption cannot free, so git files of + * arbitrary transcript cwds are read by a `cat` child we can kill instead. + */ +const GIT_FILE_READ_DEADLINE = "2 seconds"; +const MAX_GIT_FILE_BYTES = 1024 * 1024; +// Reads run concurrently, so each phase waits one deadline per batch of this +// many blocked files rather than one per blocked file. +const GIT_FILE_READ_CONCURRENCY = 16; +// A blocked path is skipped for a while, then read again in case it was fixed. +const BLOCKED_GIT_FILE_RETRY_MS = 5 * 60 * 1000; +const MAX_BLOCKED_GIT_FILE_PATHS = 1024; + const TranscriptContentBlock = Schema.Struct({ type: Schema.optional(Schema.String), text: Schema.optional(Schema.String), @@ -718,6 +735,7 @@ function sameTranscriptIdentity(left: TranscriptIdentity, right: TranscriptIdent /** @public */ export const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; + const processRunner = yield* ProcessRunner.ProcessRunner; // Concurrent client imports must not hold multiple selected-history budgets. const importReadLock = yield* Semaphore.make(1); const path = yield* Path.Path; @@ -726,7 +744,8 @@ export const make = Effect.gen(function* () { const projectStore = yield* ProjectStore.ProjectStoreV2; const baseDir = path.resolve(serverConfig.baseDir); const worktreesDir = path.resolve(serverConfig.worktreesDir); - const foldWorktreeCase = (yield* HostProcess.Platform) === "win32"; + const isWindows = (yield* HostProcess.Platform) === "win32"; + const foldWorktreeCase = isWindows; const hostEnvironment = yield* HostProcess.Environment; const homeDir = yield* HostProcess.HomeDirectory; // `/private/tmp` is what macOS reports for sessions started in `/tmp`. @@ -773,48 +792,122 @@ export const make = Effect.gen(function* () { return `path:${normalizeProjectPathForComparison(realPath)}`; }); - const readGitIdentity = Effect.fn("AgentSessionScanner.readGitIdentity")(function* ( - directory: string, - ): Effect.fn.Return< - | { readonly _tag: "Repository"; readonly git: AgentSessionProjectGit | null } - | { readonly _tag: "Worktree" } - | { readonly _tag: "NotGit" } - > { - const gitPath = path.join(directory, ".git"); - const gitStats = yield* statOption(gitPath); - if (Option.isNone(gitStats)) return { _tag: "NotGit" } as const; - let gitDir = gitPath; - if (gitStats.value.type !== "Directory") { - const pointer = yield* fileSystem - .readFileString(gitPath) - .pipe(Effect.orElseSucceed(() => "")); - const target = /^gitdir:\s*(.+)$/m.exec(pointer)?.[1]?.trim(); - if (target === undefined || target.length === 0) return { _tag: "NotGit" } as const; - gitDir = path.resolve(directory, target); + // Paths whose own read outlived the deadline, mapped to when they may be read + // again. Without this every later scan would wait out the deadline again for + // each phase that touches them. + const blockedGitFilePaths = new Map(); + + /** Reads small files without the libuv pool; "" when missing, unreadable or blocked. */ + const readGitFiles = Effect.fn("AgentSessionScanner.readGitFiles")(function* ( + filePaths: ReadonlyArray, + ) { + const unique = Array.from(new Set(filePaths)); + const now = yield* Clock.currentTimeMillis; + const contents = yield* Effect.forEach( + unique, + (filePath) => { + // No privacy prompts or FIFOs to block open() here. + if (isWindows) { + return fileSystem.readFileString(filePath).pipe(Effect.orElseSucceed(() => "")); + } + if ((blockedGitFilePaths.get(filePath) ?? 0) > now) return Effect.succeed(""); + blockedGitFilePaths.delete(filePath); + return processRunner + .run({ + command: "cat", + args: ["--", filePath], + timeout: GIT_FILE_READ_DEADLINE, + timeoutBehavior: "timedOutResult", + maxOutputBytes: MAX_GIT_FILE_BYTES, + outputMode: "truncate", + }) + .pipe( + Effect.map((result) => { + if (result.timedOut) { + if (blockedGitFilePaths.size >= MAX_BLOCKED_GIT_FILE_PATHS) { + blockedGitFilePaths.delete(blockedGitFilePaths.keys().next().value!); + } + blockedGitFilePaths.set(filePath, now + BLOCKED_GIT_FILE_RETRY_MS); + } + return result.code === 0 ? result.stdout : ""; + }), + Effect.orElseSucceed(() => ""), + ); + }, + { concurrency: isWindows ? 1 : GIT_FILE_READ_CONCURRENCY }, + ); + return new Map(unique.map((filePath, index) => [filePath, contents[index]!])); + }); + + /** Reads every directory's git identity in three phases of concurrent reads. */ + const readGitIdentities = Effect.fn("AgentSessionScanner.readGitIdentities")(function* ( + directories: ReadonlyArray, + ) { + type GitIdentity = + | { readonly _tag: "Repository"; readonly git: AgentSessionProjectGit | null } + | { readonly _tag: "Worktree" } + | { readonly _tag: "NotGit" }; + const identities = new Map(); + const repositories: Array<{ directory: string; gitDir: string; linkedWorktree: boolean }> = []; + const pointers: Array<{ directory: string; gitPath: string }> = []; + for (const directory of directories) { + const gitPath = path.join(directory, ".git"); + const gitStats = yield* statOption(gitPath); + if (Option.isNone(gitStats)) identities.set(directory, { _tag: "NotGit" }); + else if (gitStats.value.type === "Directory") { + repositories.push({ directory, gitDir: gitPath, linkedWorktree: false }); + } else pointers.push({ directory, gitPath }); } - const linkedWorktree = - gitStats.value.type !== "Directory" && /[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir); - if (linkedWorktree) { - const commonDir = yield* fileSystem - .readFileString(path.join(gitDir, "commondir")) - .pipe(Effect.orElseSucceed(() => "")); - if (commonDir.trim().length === 0) return { _tag: "Worktree" } as const; - gitDir = path.resolve(gitDir, commonDir.trim()); + + const pointerTexts = yield* readGitFiles(pointers.map(({ gitPath }) => gitPath)); + const linkedWorktrees: Array<{ directory: string; gitDir: string }> = []; + for (const { directory, gitPath } of pointers) { + const target = /^gitdir:\s*(.+)$/m.exec(pointerTexts.get(gitPath) ?? "")?.[1]?.trim(); + if (target === undefined || target.length === 0) { + identities.set(directory, { _tag: "NotGit" }); + continue; + } + const gitDir = path.resolve(directory, target); + if (/[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir)) { + linkedWorktrees.push({ directory, gitDir }); + } else repositories.push({ directory, gitDir, linkedWorktree: false }); } - const configText = yield* fileSystem - .readFileString(path.join(gitDir, "config")) - .pipe(Effect.orElseSucceed(() => "")); - // Bare repositories have no main checkout, so offer their linked worktrees independently. - if (linkedWorktree && !isBareGitConfig(configText)) return { _tag: "Worktree" } as const; - const originUrl = parseOriginUrlFromGitConfig(configText); - return { - _tag: "Repository", - git: { - remoteKey: - originUrl === null ? null : sourceControlDefinitions.repositoryKeyFromRemote(originUrl), - repository: repositoryPathFromRemoteUrl(originUrl), - }, - } as const; + + const commonDirTexts = yield* readGitFiles( + linkedWorktrees.map(({ gitDir }) => path.join(gitDir, "commondir")), + ); + for (const { directory, gitDir } of linkedWorktrees) { + const commonDir = (commonDirTexts.get(path.join(gitDir, "commondir")) ?? "").trim(); + if (commonDir.length === 0) identities.set(directory, { _tag: "Worktree" }); + else + repositories.push({ + directory, + gitDir: path.resolve(gitDir, commonDir), + linkedWorktree: true, + }); + } + + const configTexts = yield* readGitFiles( + repositories.map(({ gitDir }) => path.join(gitDir, "config")), + ); + for (const { directory, gitDir, linkedWorktree } of repositories) { + const configText = configTexts.get(path.join(gitDir, "config")) ?? ""; + // Bare repositories have no main checkout, so offer their linked worktrees independently. + if (linkedWorktree && !isBareGitConfig(configText)) { + identities.set(directory, { _tag: "Worktree" }); + continue; + } + const originUrl = parseOriginUrlFromGitConfig(configText); + identities.set(directory, { + _tag: "Repository", + git: { + remoteKey: + originUrl === null ? null : sourceControlDefinitions.repositoryKeyFromRemote(originUrl), + repository: repositoryPathFromRemoteUrl(originUrl), + }, + }); + } + return identities; }); const readCwd = Effect.fn("AgentSessionScanner.readCwd")(function* ( @@ -903,7 +996,6 @@ export const make = Effect.gen(function* () { const readTranscript = Effect.fn("AgentSessionScanner.readTranscript")(function* ( filePath: string, expected: ReturnType, - recordLimit: number, source: AgentSessionSource, ) { if (expected.size > MAX_IMPORTED_TRANSCRIPT_BYTES) return null; @@ -937,7 +1029,7 @@ export const make = Effect.gen(function* () { const finishRecord = () => { reader.write(decoder.decode()); recordCount += 1; - if (recordCount > recordLimit) return false; + if (recordCount > MAX_IMPORT_RECORDS) return false; const value = reader.finish(); const decoded = decodeTranscriptValue(value); if (Option.isNone(decoded) && source === "pi") { @@ -997,7 +1089,7 @@ export const make = Effect.gen(function* () { if (recordStarted && !(yield* Effect.try(finishRecord))) return null; return sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat)) - ? { records, recordCount, cwd, claudeFields } + ? { records, cwd, claudeFields } : null; }), ), @@ -1404,6 +1496,30 @@ export const make = Effect.gen(function* () { git: AgentSessionProjectGit | null; } >(); + // Resolve every candidate directory first so one batch reads all git identities. + const directories = new Map>(); + for (const candidate of raw) { + const expanded = expandHomePath(candidate.cwd.trim(), homeDir); + if (!path.isAbsolute(expanded)) continue; + const resolved = path.resolve(expanded); + if (directories.has(resolved) || isExcludedProjectPath(resolved)) continue; + const stats = yield* statOption(resolved); + if (Option.isNone(stats) || stats.value.type !== "Directory") { + directories.set(resolved, Option.none()); + continue; + } + const realPath = yield* fileSystem + .realPath(resolved) + .pipe(Effect.orElseSucceed(() => resolved)); + // Symlinks can disguise excluded worktree paths; re-check their targets. + directories.set(resolved, isExcludedProjectPath(realPath) ? Option.none() : stats); + } + const directoryGitIdentities = yield* readGitIdentities( + Array.from(directories).flatMap(([directory, stats]) => + Option.isSome(stats) ? [directory] : [], + ), + ); + const directoryKeys = new Map(); const gitIdentities = new Map(); @@ -1411,28 +1527,16 @@ export const make = Effect.gen(function* () { const expanded = expandHomePath(candidate.cwd.trim(), homeDir); if (!path.isAbsolute(expanded)) continue; const resolved = path.resolve(expanded); - if (isExcludedProjectPath(resolved)) continue; + const stats = directories.get(resolved); + if (stats === undefined || Option.isNone(stats)) continue; let key = directoryKeys.get(resolved); if (key === undefined) { - const stats = yield* statOption(resolved); - if (Option.isNone(stats) || stats.value.type !== "Directory") { - directoryKeys.set(resolved, ""); - continue; - } - const realPath = yield* fileSystem - .realPath(resolved) - .pipe(Effect.orElseSucceed(() => resolved)); - // Symlinks can disguise excluded worktree paths; re-check their targets. - if (isExcludedProjectPath(realPath)) { + const gitIdentity = directoryGitIdentities.get(resolved); + if (gitIdentity === undefined || gitIdentity._tag === "Worktree") { key = ""; } else { - const gitIdentity = yield* readGitIdentity(resolved); - if (gitIdentity._tag === "Worktree") { - key = ""; - } else { - key = yield* directoryIdentity(resolved, stats.value); - gitIdentities.set(key, gitIdentity._tag === "Repository" ? gitIdentity.git : null); - } + key = yield* directoryIdentity(resolved, stats.value); + gitIdentities.set(key, gitIdentity._tag === "Repository" ? gitIdentity.git : null); } directoryKeys.set(resolved, key); } @@ -1563,17 +1667,13 @@ export const make = Effect.gen(function* () { const codexThreadNamesByHome = new Map>(); let bytesRemaining = MAX_IMPORT_BYTES; let transcriptsRemaining = MAX_IMPORT_TRANSCRIPTS; - let recordsRemaining = MAX_IMPORT_RECORDS; return Stream.fromIteratorSucceed(eligibleTranscripts.values(), 1).pipe( Stream.mapEffect(({ candidate, transcript }) => Effect.gen(function* () { const completed = completedByFile.get( `${candidate.providerInstanceId}\0${transcript.filePath}`, ); - if ( - completed === undefined && - (transcriptsRemaining === 0 || bytesRemaining === 0 || recordsRemaining === 0) - ) { + if (completed === undefined && (transcriptsRemaining === 0 || bytesRemaining === 0)) { return Option.some({ _tag: "Skipped" }); } const stats = yield* statOption(transcript.filePath); @@ -1596,7 +1696,6 @@ export const make = Effect.gen(function* () { } if ( transcriptsRemaining === 0 || - recordsRemaining === 0 || identity.size > MAX_IMPORTED_TRANSCRIPT_BYTES || identity.size > bytesRemaining ) { @@ -1604,16 +1703,10 @@ export const make = Effect.gen(function* () { } transcriptsRemaining -= 1; bytesRemaining -= identity.size; - const snapshot = yield* readTranscript( - transcript.filePath, - identity, - recordsRemaining, - candidate.source, - ); + const snapshot = yield* readTranscript(transcript.filePath, identity, candidate.source); if (snapshot === null) { return Option.some({ _tag: "Skipped" }); } - recordsRemaining -= snapshot.recordCount; if (Option.isNone(snapshot.cwd)) { return Option.some({ _tag: "Skipped" }); @@ -1680,4 +1773,6 @@ export const make = Effect.gen(function* () { return AgentSessionScanner.of({ scan, recentThreads }); }); -export const layer = Layer.effect(AgentSessionScanner, make); +export const layer = Layer.effect(AgentSessionScanner, make).pipe( + Layer.provide(ProcessRunner.layer), +); diff --git a/apps/server/src/provider/Drivers/codexUsage.test.ts b/apps/server/src/provider/Drivers/codexUsage.test.ts index 3820ce0cf5234..74812bafb5099 100644 --- a/apps/server/src/provider/Drivers/codexUsage.test.ts +++ b/apps/server/src/provider/Drivers/codexUsage.test.ts @@ -1,7 +1,18 @@ import { describe, expect, it } from "@effect/vitest"; import { totalTokens } from "@t3tools/provider-core/server/usage"; -import { codexUsageFormat, initialCodexScanState, parseCodexLine } from "./codexUsage.ts"; +import { + type CodexScanState, + codexUsageFormat, + initialCodexScanState, + parseCodexLine as parseCodexRecords, +} from "./codexUsage.ts"; + +function parseCodexLine(line: string, state: CodexScanState) { + const records = parseCodexRecords(line, state); + expect(records.length).toBeLessThanOrEqual(1); + return records[0] ?? null; +} describe("parseCodexLine", () => { const sessionMeta = JSON.stringify({ @@ -326,6 +337,119 @@ describe("parseCodexLine", () => { expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1); }); + it("bills only the reported request when usage records sit between reconciling snapshots", () => { + const state = initialCodexScanState(); + const usageRecord = (usage: unknown) => + JSON.stringify({ + type: "token_usage_record", + timestamp: "2026-08-01T05:17:45.000Z", + payload: { usage }, + }); + parseCodexLine(turnContext, state); + parseCodexLine(counted(counters(100, 20), counters(100, 20)), state); + for (const usage of [counters(40, 5), counters(60, 15), counters(30, 3)]) { + expect(parseCodexLine(usageRecord(usage), state)).toBeNull(); + } + expect( + parseCodexLine(counted(counters(100, 20), counters(200, 40)), state)?.totals.outputTokens, + ).toBe(20); + // Records explained by an earlier snapshot cannot bridge a later gap. + parseCodexLine(usageRecord(counters(10, 2)), state); + expect(parseCodexLine(counted(counters(10, 2), counters(340, 65)), state)).toBeNull(); + expect(state.malformedRecords).toBe(1); + }); + + it("bills each interrupted turn's request with the model, tier and time it was read under", () => { + const state = initialCodexScanState(); + const line = (type: string, time: string, payload: Record) => + JSON.stringify({ type, timestamp: `2026-11-0${time}Z`, payload }); + const context = (time: string, turn_id: string, model: string) => + line("turn_context", time, { turn_id, model }); + const tier = (time: string, service_tier: string) => + line("event_msg", time, { + type: "thread_settings_applied", + thread_settings: { service_tier }, + }); + const request = (time: string, usage: unknown) => line("token_usage_record", time, { usage }); + const snapshot = (time: string, last: unknown, total: unknown) => + line("event_msg", time, { + type: "token_count", + info: { last_token_usage: last, total_token_usage: total }, + }); + const parsed = [ + line("session_meta", "1T23:59:50", { id: "session-a", model_provider: "openai" }), + context("1T23:59:50", "turn-1", "gpt-6-sol"), + request("1T23:59:51", counters(100, 20)), + snapshot("1T23:59:52", counters(100, 20), counters(100, 20)), + // One interrupted turn whose requests straddle midnight. + request("1T23:59:59", counters(150, 10)), + request("2T00:00:01", counters(50, 5)), + tier("2T00:00:02", "priority"), + context("2T00:00:02", "turn-2", "gpt-6-astra"), + request("2T00:00:03", counters(50, 5)), + request("2T00:00:04", counters(30, 5)), + tier("2T00:00:05", "default"), + context("2T00:00:05", "turn-3", "gpt-6-sol"), + request("2T00:00:06", counters(200, 30)), + snapshot("2T00:00:07", counters(200, 30), counters(580, 75)), + ].flatMap((value) => parseCodexRecords(value, state)); + + const at = (time: string) => Date.parse(`2026-11-0${time}Z`); + expect( + parsed.map((record) => ({ + tokens: totalTokens(record.totals), + model: record.model, + speed: record.speed, + timestampMs: record.timestampMs, + unresolvedServiceTierTurnId: record.unresolvedServiceTierTurnId, + })), + ).toEqual([ + { + tokens: 120, + model: "gpt-6-sol", + speed: "standard", + timestampMs: at("1T23:59:52"), + unresolvedServiceTierTurnId: "turn-1", + }, + { + tokens: 160, + model: "gpt-6-sol", + speed: "standard", + timestampMs: at("1T23:59:59"), + unresolvedServiceTierTurnId: "turn-1", + }, + { + tokens: 55, + model: "gpt-6-sol", + speed: "standard", + timestampMs: at("2T00:00:01"), + unresolvedServiceTierTurnId: "turn-1", + }, + { + tokens: 55, + model: "gpt-6-astra", + speed: "fast", + timestampMs: at("2T00:00:03"), + unresolvedServiceTierTurnId: undefined, + }, + { + tokens: 35, + model: "gpt-6-astra", + speed: "fast", + timestampMs: at("2T00:00:04"), + unresolvedServiceTierTurnId: undefined, + }, + { + tokens: 230, + model: "gpt-6-sol", + speed: "standard", + timestampMs: at("2T00:00:07"), + unresolvedServiceTierTurnId: undefined, + }, + ]); + expect(state.malformedRecords).toBe(0); + }); + it("does not bill a context-window estimate or lose the following real request", () => { const state = initialCodexScanState(); parseCodexLine(turnContext, state); @@ -664,5 +788,26 @@ describe("parseCodexLine", () => { skipped: codexUsageFormat.readMalformedRecords?.(state), }).toEqual({ processed: [120, 0, 120, 35], skipped: 0 }); }); + + it("bills the child's first request when its turn is interrupted before any snapshot", () => { + const state = initialCodexScanState(); + const forkInstant = "2026-08-01T05:00:00.000Z"; + const request = (timestamp: string, usage: unknown) => + JSON.stringify({ type: "token_usage_record", timestamp, payload: { usage } }); + const billed = [ + meta({ id: "child", timestamp: forkInstant, forkedFromId: "parent" }), + stamped(forkInstant, turnContext), + request("2026-08-01T05:00:00.001Z", counters(100, 20)), + stamped("2026-08-01T05:00:00.001Z", counted(counters(100, 20), counters(100, 20))), + request("2026-08-01T05:00:06.000Z", counters(150, 10)), + request("2026-08-01T05:00:10.000Z", counters(200, 30)), + stamped("2026-08-01T05:00:10.000Z", counted(counters(200, 30), counters(450, 60))), + ].flatMap((line) => parseCodexRecords(line, state)); + + expect({ + processed: billed.map((record) => totalTokens(record.totals)), + skipped: codexUsageFormat.readMalformedRecords?.(state), + }).toEqual({ processed: [160, 230], skipped: 0 }); + }); }); }); diff --git a/apps/server/src/provider/Drivers/codexUsage.ts b/apps/server/src/provider/Drivers/codexUsage.ts index 20939e54db799..90f7c78b849f8 100644 --- a/apps/server/src/provider/Drivers/codexUsage.ts +++ b/apps/server/src/provider/Drivers/codexUsage.ts @@ -5,7 +5,6 @@ import * as Schema from "effect/Schema"; import { parseTimestampMs, - totalTokens, type ProviderUsageReader, type TranscriptUsageFormat, type UsageRecord, @@ -58,6 +57,7 @@ function readCodexTokenUsage(value: unknown): CodexTokenUsage | null { // A zeroed baseline rebases the counters, so the sequence start measured against it is forgotten. function rebaseCodexUsage(state: CodexScanState, cumulative: CodexTokenUsage) { state.lastCumulativeUsage = cumulative; + delete state.unreportedRequests; if (cumulative.input_tokens + cumulative.output_tokens === 0) delete state.sequenceStartSignature; } @@ -67,18 +67,66 @@ function advanceCodexUsage(previous: CodexTokenUsage | null, last: CodexTokenUsa ); } +const CodexSpeed = Schema.Literals(["standard", "fast", "ultrafast"]); + +// What a request is billed as is fixed when it is read, not when a later snapshot reconciles it. +const CodexUnreportedRequest = Schema.Struct({ + timestampMs: Schema.Finite, + model: Schema.String, + turnId: Schema.String, + speed: CodexSpeed, + sawThreadSettings: Schema.Boolean, + usage: CodexTokenUsage, +}); +type CodexUnreportedRequest = typeof CodexUnreportedRequest.Type; +type CodexRequestAttribution = Omit; + +// An interrupted turn can end before a snapshot reports its last request. Bill those requests only +// when the `token_usage_record`s since the previous snapshot explain the whole gap; `last` is the +// final one. +function unreportedRequests( + previous: CodexTokenUsage | null, + cumulative: CodexTokenUsage, + last: CodexTokenUsage, + pending: readonly CodexUnreportedRequest[] | undefined, +) { + if ( + previous === null || + pending === undefined || + CODEX_USAGE_FIELDS.some( + (key) => + cumulative[key] - previous[key] !== + pending.reduce((sum, request) => sum + request.usage[key], 0), + ) + ) { + return null; + } + const final = pending.at(-1)!; + const remainder = readCodexTokenUsage( + Object.fromEntries(CODEX_USAGE_FIELDS.map((key) => [key, final.usage[key] - last[key]])), + ); + if (remainder === null) return null; + return [...pending.slice(0, -1), { ...final, usage: remainder }].filter( + (request) => request.usage.input_tokens + request.usage.output_tokens > 0, + ); +} + /** * Codex `token_count` events carry no model or service tier, so both are carried forward: the model * from the most recent `turn_context`, the tier from the most recent `thread_settings_applied`. */ export const CodexScanState = Schema.Struct({ model: Schema.mutableKey(Schema.String), - speed: Schema.mutableKey(Schema.Literals(["standard", "fast", "ultrafast"])), + speed: Schema.mutableKey(CodexSpeed), sessionId: Schema.mutableKey(Schema.String), lastUsageSignature: Schema.mutableKey(Schema.NullOr(Schema.String)), lastCumulativeUsage: Schema.mutableKey(Schema.NullOr(CodexTokenUsage)), // Optional so scan states cached before this field existed stay valid. sequenceStartSignature: Schema.mutableKey(Schema.optionalKey(Schema.String)), + // `token_usage_record` usage since the last cumulative snapshot, one entry per record. + unreportedRequests: Schema.mutableKey( + Schema.optionalKey(Schema.mutable(Schema.Array(CodexUnreportedRequest))), + ), malformedRecords: Schema.mutableKey(TokenCount), sawSessionMeta: Schema.mutableKey(Schema.Boolean), modelProvider: Schema.mutableKey(Schema.String), @@ -120,32 +168,44 @@ function isForkedSessionMeta(payload: Record): boolean { return typeof (spawn as Record)["parent_thread_id"] === "string"; } +// The first usage line past the copied burst ends suppression for the rest of the rollout. +function isForkCopy(state: CodexScanState, timestampMs: number): boolean { + if (!state.suppressingForkCopies) return false; + if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) { + state.forkCopyAnchorMs = timestampMs; + return true; + } + state.suppressingForkCopies = false; + state.lastUsageSignature = null; + return false; +} + /** * Cumulative counters validate request deltas. Older events without cumulative counters use * normalized consecutive-request deduplication. */ -export function parseCodexLine(line: string, state: CodexScanState): UsageRecord | null { +export function parseCodexLine(line: string, state: CodexScanState): readonly UsageRecord[] { let parsed: unknown; try { parsed = JSON.parse(line); } catch { - return null; + return []; } return parseCodexRecord(parsed, state); } -function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | null { - if (typeof parsed !== "object" || parsed === null) return null; +function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly UsageRecord[] { + if (typeof parsed !== "object" || parsed === null) return []; const record = parsed as Record; const payload = record["payload"]; - if (typeof payload !== "object" || payload === null) return null; + if (typeof payload !== "object" || payload === null) return []; const payloadRecord = payload as Record; const payloadType = payloadRecord["type"]; if (record["type"] === "session_meta") { // Only the first meta identifies this session; copied ancestor metas would misattribute later records. - if (state.sawSessionMeta) return null; + if (state.sawSessionMeta) return []; state.sawSessionMeta = true; const id = payloadRecord["id"] ?? payloadRecord["session_id"]; if (typeof id === "string") state.sessionId = id; @@ -157,7 +217,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | state.suppressingForkCopies = true; state.forkCopyAnchorMs = metaTimestampMs; } - return null; + return []; } if (record["type"] === "turn_context") { @@ -169,7 +229,18 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | payloadRecord["model"].length > 0 ? payloadRecord["turn_id"] : ""; - return null; + return []; + } + + // Several of these may sit between two snapshots, so they only explain a gap in the counters. + if (record["type"] === "token_usage_record") { + const timestampMs = parseTimestampMs(record["timestamp"]); + const usage = readCodexTokenUsage(payloadRecord["usage"]); + if (timestampMs === null || usage === null || state.model.length === 0) return []; + // Copied history is already billed in the parent. + if (isForkCopy(state, timestampMs)) return []; + (state.unreportedRequests ??= []).push({ ...codexAttribution(state, timestampMs), usage }); + return []; } if (payloadType === "thread_settings_applied") { @@ -178,53 +249,49 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | if (typeof settings === "object" && settings !== null) { state.speed = codexSpeed((settings as Record)["service_tier"]); } - return null; + return []; } - if (payloadType !== "token_count") return null; + if (payloadType !== "token_count") return []; const info = payloadRecord["info"]; - if (typeof info !== "object" || info === null) return null; + if (typeof info !== "object" || info === null) return []; const infoRecord = info as Record; // Codex may re-emit these counters after the model or timestamp becomes available. const timestampMs = parseTimestampMs(record["timestamp"]); - if (timestampMs === null || state.model.length === 0) return null; + if (timestampMs === null || state.model.length === 0) return []; const last = readCodexTokenUsage(infoRecord["last_token_usage"]); const rawCumulative = infoRecord["total_token_usage"]; const hasCumulative = rawCumulative !== undefined && rawCumulative !== null; const cumulative = hasCumulative ? readCodexTokenUsage(rawCumulative) : null; - if (state.suppressingForkCopies) { - if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) { - state.forkCopyAnchorMs = timestampMs; - // Copied history is already billed in the parent, but establishes the child's baseline. - const signature = last === null ? null : JSON.stringify(last); - if (cumulative !== null) rebaseCodexUsage(state, cumulative); - else if (!hasCumulative && last !== null && signature !== state.lastUsageSignature) { - state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, last); - } - state.lastUsageSignature = signature; - return null; + if (isForkCopy(state, timestampMs)) { + // Copied history is already billed in the parent, but establishes the child's baseline. + const signature = last === null ? null : JSON.stringify(last); + if (cumulative !== null) rebaseCodexUsage(state, cumulative); + else if (!hasCumulative && last !== null && signature !== state.lastUsageSignature) { + state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, last); } - state.suppressingForkCopies = false; - state.lastUsageSignature = null; + state.lastUsageSignature = signature; + return []; } const previous = state.lastCumulativeUsage; + const pending = state.unreportedRequests; // A valid snapshot remains the next baseline even when its paired request is malformed. if (cumulative !== null) rebaseCodexUsage(state, cumulative); if (last === null || (hasCumulative && cumulative === null)) { state.malformedRecords += 1; - return null; + return []; } // Zero-component counters report context size, not a request: fill_to_context_window, or the // post-compaction marker whose total is the new context size (its cumulative may reset to zero). if (last.input_tokens + last.output_tokens === 0) { state.lastUsageSignature = null; - return null; + return []; } if ( @@ -232,15 +299,16 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | previous !== null && CODEX_USAGE_FIELDS.every((key) => cumulative[key] === previous[key]) ) { - return null; + return []; } if (last.total_tokens !== last.input_tokens + last.output_tokens) { state.malformedRecords += 1; - return null; + return []; } const signature = JSON.stringify(last); + let unreported: readonly CodexUnreportedRequest[] = []; if (cumulative !== null) { // A session resumed in a new Codex process restarts its cumulative counters at this request. const restarted = CODEX_USAGE_FIELDS.every((key) => cumulative[key] === last[key]); @@ -248,7 +316,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | // Only the same event is a replay; a later request can restart with identical counters. if (restarted && sequenceStart === state.sequenceStartSignature) { state.lastCumulativeUsage = previous; - return null; + return []; } // Forks and paginated continuations can inherit totals without copying a counter snapshot. // Only bill the latest request, and require the unseen prefix to be valid usage too. @@ -259,26 +327,51 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | ) !== null : CODEX_USAGE_FIELDS.every((key) => cumulative[key] - previous[key] === last[key]); if (!restarted && !reconciled) { - state.malformedRecords += 1; - return null; + const bridged = unreportedRequests(previous, cumulative, last, pending); + if (bridged === null) { + state.malformedRecords += 1; + return []; + } + unreported = bridged; } if (restarted) state.sequenceStartSignature = sequenceStart; } else { - if (signature === state.lastUsageSignature) return null; + if (signature === state.lastUsageSignature) return []; // Advance expected totals for billed legacy requests so a cumulative re-emission is stale. const advanced = advanceCodexUsage(previous, last); if (advanced === null) { state.malformedRecords += 1; - return null; + return []; } state.lastCumulativeUsage = advanced; } state.lastUsageSignature = signature; - const inputTokens = last.input_tokens; - const cachedInputTokens = last.cached_input_tokens; - const cacheCreationTokens = last.cache_write_input_tokens; - const outputTokens = last.output_tokens; + return [ + ...unreported.map((request) => codexRequestRecord(state, request.usage, request)), + codexRequestRecord(state, last, codexAttribution(state, timestampMs)), + ]; +} + +function codexAttribution(state: CodexScanState, timestampMs: number): CodexRequestAttribution { + return { + timestampMs, + model: state.model, + turnId: state.turnId, + speed: state.speed, + sawThreadSettings: state.sawThreadSettings, + }; +} + +function codexRequestRecord( + state: CodexScanState, + usage: CodexTokenUsage, + { timestampMs, model, turnId, speed, sawThreadSettings }: CodexRequestAttribution, +): UsageRecord { + const inputTokens = usage.input_tokens; + const cachedInputTokens = usage.cached_input_tokens; + const cacheCreationTokens = usage.cache_write_input_tokens; + const outputTokens = usage.output_tokens; const totals: UsageTokenTotals = { // Codex reports `input_tokens` inclusive of the cached portion. @@ -287,24 +380,22 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | cacheCreationTokens, outputTokens, // Reported inside output_tokens, surfaced separately for the token mix. - reasoningTokens: last.reasoning_output_tokens, + reasoningTokens: usage.reasoning_output_tokens, }; - if (totalTokens(totals) === 0) return null; - return { provider: "codex", timestampMs, - model: state.model, + model, sessionId: state.sessionId, totals, reportedCostUsd: null, - speed: state.speed, - ...(!state.sawThreadSettings && + speed, + ...(!sawThreadSettings && state.modelProvider === "openai" && state.sessionId.length > 0 && - state.turnId.length > 0 - ? { unresolvedServiceTierTurnId: state.turnId } + turnId.length > 0 + ? { unresolvedServiceTierTurnId: turnId } : {}), dedupeKey: null, }; @@ -317,9 +408,6 @@ function codexSpeed(serviceTier: unknown): UsageSpeed { return "standard"; } -const orEmpty = (record: UsageRecord | null): readonly UsageRecord[] => - record === null ? [] : [record]; - export const codexUsageFormat: TranscriptUsageFormat = { selectFields: { type: true, @@ -335,12 +423,19 @@ export const codexUsageFormat: TranscriptUsageFormat = { forked_from_id: true, source: { subagent: { thread_spawn: { parent_thread_id: true } } }, info: { last_token_usage: true, total_token_usage: true }, + usage: true, }, }, // Metadata lines carry model, tier and session even without usage. - usageMarkers: ['"token_count"', '"turn_context"', '"thread_settings_applied"', '"session_meta"'], - parseLine: (line, state) => orEmpty(parseCodexLine(line, state)), - parseProjected: (projected, state) => orEmpty(parseCodexRecord(projected, state)), + usageMarkers: [ + '"token_count"', + '"token_usage_record"', + '"turn_context"', + '"thread_settings_applied"', + '"session_meta"', + ], + parseLine: parseCodexLine, + parseProjected: parseCodexRecord, state: { initial: initialCodexScanState, schema: CodexScanState }, readMalformedRecords: (state) => state.malformedRecords, // A rollout that moved after it was read leaves a copy in both places. diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 4dab48a05b2a5..afeb73de3df96 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -66,6 +66,7 @@ import { acceptImmediateWebhookDedupe, releaseWebhookReplay, decodePendingTask, + encodePendingTask, decodePendingRequest, dedupeError, } from "./webhookDedupe.ts"; @@ -880,7 +881,6 @@ export const layer = Layer.effect( : `${active.id}:webhook:${webhook.deliveryId}`; const commandId = CommandId.make(`scheduled-task:${fireKey}`); const messageId = MessageId.make(`scheduled-task-message:${fireKey}`); - // A webhook prompt was rendered from the row when the request arrived. const prompt = webhook?.prompt ?? active.prompt; // A bound thread can move to another project (No project to a project) while @@ -2331,10 +2331,21 @@ export const layer = Layer.effect( continue; } const prepared = yield* Effect.gen(function* () { - const task = yield* decodePendingTask(entry.task_json); + // A running row was already sent, so recovery keeps the prompt it was sent with. + const current = entry.state === "dispatching" ? yield* findTask(taskId) : null; + const snapshot = yield* decodePendingTask(entry.task_json); + // The snapshot keeps the identity runTask checks; the prompt is the one saved now. + const task = + current?.createdAt === snapshot.createdAt && current.prompt !== snapshot.prompt + ? { ...snapshot, prompt: current.prompt } + : snapshot; const request = yield* decodePendingRequest(entry.request_json); const frameId = Buffer.from(yield* random.randomBytes(6)).toString("hex"); - return { task, rendered: renderWebhookPrompt(task.prompt, request, frameId) }; + return { + task, + taskJson: task === snapshot ? null : yield* encodePendingTask(task), + rendered: renderWebhookPrompt(task.prompt, request, frameId), + }; }).pipe(Effect.exit); if (Exit.isFailure(prepared)) { if (Cause.hasInterruptsOnly(prepared.cause)) @@ -2347,11 +2358,13 @@ export const layer = Layer.effect( yield* remove; continue; } - const { task, rendered } = prepared.value; + const { task, taskJson, rendered } = prepared.value; if (rendered.prompt.trim().length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) { yield* markDeliveryFailed(entry.delivery_id, PROMPT_TOO_LONG); yield* releaseFailedDelivery(entry.delivery_id); } else { + if (taskJson !== null) + yield* sql`UPDATE scheduled_task_webhook_pending SET task_json = ${taskJson} WHERE delivery_id = ${entry.delivery_id}`; yield* sql`UPDATE scheduled_task_webhook_deliveries SET outcome = 'accepted', error = NULL, rendered_prompt = ${rendered.prompt.slice(0, WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT)}, missing_fields_json = ${encodeMissingFieldsJson(rendered.missing)} WHERE delivery_id = ${entry.delivery_id}`; if (!(yield* runWebhookDelivery(task, entry.delivery_id, rendered.prompt))) return; } diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts index bfafd3893e170..6303b38c05ce6 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts @@ -1031,6 +1031,106 @@ it.effect.each([1, 3])( }, ); +it.effect("a coalesced window dispatches the prompt saved after it opened", () => { + const workers = new Map>(); + return withService( + ({ service, launches }) => + Effect.gen(function* () { + const schedule = { + type: "webhook", + dedupe: { coalesceKey: "{{body.id}}", coalesceWindowSeconds: 10 }, + }; + const { task } = yield* service.upsert( + yield* webhookTaskInput({ prompt: "Use the original instructions.", schedule }), + ); + const bodyText = JSON.stringify({ id: "review" }); + yield* service.triggerWebhook( + requestFor(task, { bodyText, body: new TextEncoder().encode(bodyText) }), + ); + yield* service.upsert( + yield* webhookTaskInput({ prompt: "Use the updated instructions.", schedule }), + ); + yield* TestClock.adjust("10 seconds"); + yield* workers.get("webhook-coalescing")!; + const launched = yield* Queue.take(launches); + assert.equal(launched.initialMessage?.text, "Use the updated instructions."); + const owner = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries[0]!; + const { delivery } = yield* service.getWebhookDelivery({ + id: task.id, + deliveryId: owner.id, + }); + assert.equal(delivery.renderedPrompt, "Use the updated instructions."); + }), + { workers }, + ); +}); + +it.effect("retrying a running window keeps the prompt it was dispatched with", () => { + const workers = new Map>(); + return withService( + ({ service, sql, launches }) => + Effect.gen(function* () { + const schedule = { + type: "webhook", + dedupe: { coalesceKey: "{{body}}", coalesceWindowSeconds: 10 }, + }; + const save = (prompt: string) => + Effect.flatMap(webhookTaskInput({ prompt, schedule }), service.upsert); + const { task } = yield* save("Prompt when the window opened"); + yield* service.triggerWebhook(requestFor(task)); + yield* save("Prompt at dispatch"); + yield* sql`CREATE TRIGGER fail_completion BEFORE UPDATE ON scheduled_tasks + WHEN NEW.last_run_status = 'succeeded' BEGIN SELECT RAISE(FAIL, 'completion unavailable'); END`; + yield* TestClock.adjust("10 seconds"); + yield* drainPendingDispatch(workers); + const launched = yield* Queue.take(launches); + assert.equal(launched.initialMessage?.text, "Prompt at dispatch"); + yield* save("Prompt saved after dispatch"); + yield* sql`DROP TRIGGER fail_completion`; + yield* drainPendingDispatch(workers); + assert.equal((yield* sql`SELECT 1 FROM scheduled_task_webhook_pending`).length, 0); + const owner = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries[0]!; + const { delivery } = yield* service.getWebhookDelivery({ + id: task.id, + deliveryId: owner.id, + }); + assert.equal(delivery.renderedPrompt, "Prompt at dispatch"); + }), + { workers }, + ); +}); + +it.effect("a coalesced window fails its delivery when the task row cannot be read", () => { + const workers = new Map>(); + return withService( + ({ service, sql, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + schedule: { + type: "webhook", + dedupe: { coalesceKey: "{{body}}", coalesceWindowSeconds: 10 }, + }, + }), + ); + yield* service.triggerWebhook(requestFor(task)); + yield* sql`UPDATE scheduled_tasks SET model_selection_json = 'not json' WHERE task_id = ${task.id}`; + yield* TestClock.adjust("10 seconds"); + yield* drainPendingDispatch(workers); + assert.equal(yield* Queue.size(launches), 0); + assert.equal((yield* sql`SELECT 1 FROM scheduled_task_webhook_pending`).length, 0); + const [delivery] = yield* sql<{ + outcome: string; + error: string | null; + }>`SELECT outcome, error FROM scheduled_task_webhook_deliveries`; + assert.equal(delivery?.outcome, "dispatch_failed"); + // Failing before dispatch means a later successful read cannot send the stale snapshot. + assert.equal(delivery?.error, "The pending webhook payload could not be prepared."); + }), + { workers }, + ); +}); + it.effect("recovers a persisted coalescing window after restarting the service", () => { const workers = new Map>(); return withService( diff --git a/apps/server/src/scheduledTasks/webhookDedupe.ts b/apps/server/src/scheduledTasks/webhookDedupe.ts index 21d40b25ac5ed..76f04a97e6dfe 100644 --- a/apps/server/src/scheduledTasks/webhookDedupe.ts +++ b/apps/server/src/scheduledTasks/webhookDedupe.ts @@ -111,7 +111,7 @@ export const acceptImmediateWebhookDedupe = Effect.fn( }); const PendingTaskJson = Schema.fromJsonString(ScheduledTask); -const encodePendingTask = Schema.encodeEffect(PendingTaskJson); +export const encodePendingTask = Schema.encodeEffect(PendingTaskJson); export const decodePendingTask = Schema.decodeUnknownEffect(PendingTaskJson); const PendingRequestJson = Schema.fromJsonString( Schema.Struct({ diff --git a/apps/server/src/sourceControl/SourceControlRepositoryService.ts b/apps/server/src/sourceControl/SourceControlRepositoryService.ts index 44d31a43b6978..1e9c48893dad7 100644 --- a/apps/server/src/sourceControl/SourceControlRepositoryService.ts +++ b/apps/server/src/sourceControl/SourceControlRepositoryService.ts @@ -79,7 +79,8 @@ const CLONE_ENV = { // Force piped progress immediately; refuse credential prompts that would hang without a tty. GIT_PROGRESS_DELAY: "0", GIT_TERMINAL_PROMPT: "0", - LC_ALL: "C", + // English progress without overriding LC_CTYPE, which a global post-checkout hook inherits. + LANGUAGE: "C", } satisfies NodeJS.ProcessEnv; function mapRepositoryError(operation: string, provider: SourceControlProviderKind) { diff --git a/apps/server/src/triage/TriageService.ts b/apps/server/src/triage/TriageService.ts index f7a93f24a6641..14d12c0af9e15 100644 --- a/apps/server/src/triage/TriageService.ts +++ b/apps/server/src/triage/TriageService.ts @@ -23,7 +23,8 @@ const T3CODE_REPOSITORY_URL = "https://github.com/pingdotgg/t3code"; const GIT_ENV = { GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "", - LC_ALL: "C", + // English messages without overriding LC_CTYPE, which a global post-checkout hook inherits. + LANGUAGE: "C", } satisfies NodeJS.ProcessEnv; /** Starts in-app triage sessions: the same files `t3 triage` writes, plus a source clone. */ diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index 227fac19036b1..9cf97cd4c7c4d 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -2624,7 +2624,7 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); - it.live.each([4, 5, 6, 7, 8])( + it.live.each([4, 5, 6, 7, 8, 10])( "upgrades a v%s cache: reparses live Codex usage, keeps deleted rollouts and the old file", (version) => Effect.gen(function* () { @@ -2691,7 +2691,7 @@ describe("UsageService", () => { delete file.cs.lastCumulativeUsage; delete file.cs.malformedRecords; } - if (version === 8 && path === livePath) { + if (version >= 8 && path === livePath) { file.r = []; file.mr = 1; file.cs.malformedRecords = 1; @@ -2723,7 +2723,7 @@ describe("UsageService", () => { 60 + 20 * (version === 4 ? 1 : 2), ); yield* upgraded.awaitPersisted; - assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v10.json"); + assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v11.json"); assert.strictEqual( yield* Effect.promise(() => NodeFSP.readFile(legacyPath, "utf8")), legacy, @@ -2750,6 +2750,106 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); + it.live("re-parses a clean v10 Codex rollout that grew after an interrupted request", () => + Effect.gen(function* () { + const { home, settings } = yield* setup; + const sessions = NodePath.join(home, "codex", "sessions"); + const live = NodePath.join(sessions, "live.jsonl"); + const usage = (input: number, output: number) => ({ + input_tokens: input, + output_tokens: output, + total_tokens: input + output, + }); + const lines = (values: readonly unknown[]) => + values.map((value) => `${encodeUnknownJsonString(value)}\n`).join(""); + const request = (second: number, last: unknown) => ({ + type: "token_usage_record", + timestamp: `2026-08-01T10:00:0${second}Z`, + payload: { usage: last }, + }); + const tokenCount = (second: number, last: unknown, total: unknown) => ({ + type: "event_msg", + timestamp: `2026-08-01T10:00:0${second}Z`, + payload: { + type: "token_count", + info: { last_token_usage: last, total_token_usage: total }, + }, + }); + yield* Effect.promise(async () => { + await NodeFSP.mkdir(sessions, { recursive: true }); + await NodeFSP.writeFile( + live, + lines([ + { type: "session_meta", payload: { id: "live" } }, + { type: "turn_context", payload: { turn_id: "turn-1", model: "gpt-6-astra" } }, + request(1, usage(100, 20)), + tokenCount(1, usage(100, 20), usage(100, 20)), + // Interrupted after this request finished: no token_count reports it. + request(2, usage(150, 10)), + ]), + ); + }); + + yield* Effect.gen(function* () { + const { stateDir } = yield* ServerConfig.ServerConfig; + const tokens = (summary: UsageSummary) => + summary.buckets.reduce((sum, bucket) => sum + totalTokens(bucket.totals), 0); + const first = yield* UsageService.make; + assert.strictEqual(tokens(yield* first.readSummary(WINDOW)), 120); + yield* first.awaitPersisted; + + yield* Effect.promise(async () => { + const cachePath = NodePath.join(stateDir, SCAN_CACHE_FILE_NAME); + const document = decodeUnknownJsonString(await NodeFSP.readFile(cachePath, "utf8")) as { + files: Record }>; + }; + // The v10 parser ignored `token_usage_record`, so its clean state held nothing pending. + for (const file of Object.values(document.files)) { + file.cs = Object.fromEntries( + Object.entries(file.cs).filter(([key]) => !key.startsWith("unreported")), + ); + } + await NodeFSP.rm(cachePath); + await NodeFSP.writeFile( + NodePath.join(stateDir, "usage-scan-cache-v10.json"), + encodeUnknownJsonString({ ...document, version: 10 }), + ); + await NodeFSP.appendFile( + live, + lines([ + { type: "turn_context", payload: { turn_id: "turn-2", model: "gpt-6-astra" } }, + request(5, usage(200, 30)), + tokenCount(5, usage(200, 30), usage(450, 60)), + ]), + ); + }); + + const upgraded = yield* UsageService.make; + const summary = yield* upgraded.readSummary(WINDOW); + assert.deepStrictEqual( + { + tokens: tokens(summary), + malformedRecords: summary.sources.find( + (source) => source.fingerprint.provider === "codex", + )?.malformedRecords, + }, + { tokens: 510, malformedRecords: 0 }, + ); + }).pipe( + Effect.provide( + layerService({ + prefix: "usage-service-cache-v10-interrupted-test", + home, + settings, + ratesDocument: { + "gpt-6-astra": { input_cost_per_token: 0, output_cost_per_token: 1 }, + }, + }), + ), + ); + }).pipe(Effect.scoped), + ); + it.live("preserves saved tokens, costs and sessions after transcript cleanup and restart", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts index 477b8bb6fc4f6..fa659c4a443b3 100644 --- a/apps/server/src/usage/usageScanCache.test.ts +++ b/apps/server/src/usage/usageScanCache.test.ts @@ -161,7 +161,7 @@ describe("scan cache round trip", () => { expect(restored).toEqual(original); }); - it.each([5, 6, 7, 8])( + it.each([5, 6, 7, 8, 10])( "retains v%s history and compatible positions but invalidates obsolete state", (version) => { const original = cacheWith([["/gone.jsonl", 100, [record({ speed: "fast" })]]]); @@ -218,25 +218,25 @@ describe("scan cache round trip", () => { }; const restored = decodeScanCache(JSON.parse(JSON.stringify(legacy)), TEST_FORMAT_MAP); - expect(restored.get("/gone.jsonl")).toEqual({ - ...original.get("/gone.jsonl"), - size: -1, - position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, - }); - expect(restored.get("/gone-codex.jsonl")).toEqual({ - ...original.get("/gone-codex.jsonl"), - size: -1, - position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, - }); - expect(restored.get("/clean-codex.jsonl")).toEqual( - version >= 8 - ? cleanCodex + expect(restored.get("/gone.jsonl")).toEqual( + version >= 10 + ? original.get("/gone.jsonl") : { - ...cleanCodex, + ...original.get("/gone.jsonl"), size: -1, position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, }, ); + expect(restored.get("/gone-codex.jsonl")).toEqual({ + ...original.get("/gone-codex.jsonl"), + size: -1, + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, + }); + expect(restored.get("/clean-codex.jsonl")).toEqual({ + ...cleanCodex, + size: version >= 8 ? cleanCodex.size : -1, + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, + }); expect(restored.get("/gone-pi.jsonl")).toEqual( version >= 6 ? original.get("/gone-pi.jsonl") diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts index 70c0c3df17e3e..c9032d64c05bd 100644 --- a/apps/server/src/usage/usageScanCache.ts +++ b/apps/server/src/usage/usageScanCache.ts @@ -9,7 +9,7 @@ import * as Schema from "effect/Schema"; import { CLAUDE_SYNTHETIC_MODEL } from "../provider/Drivers/claudeUsage.ts"; import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts"; -const USAGE_SCAN_CACHE_VERSION = 10 as const; +const USAGE_SCAN_CACHE_VERSION = 11 as const; const SPEED_COMPATIBLE_SINCE_VERSION = 4; /** @@ -17,8 +17,9 @@ const SPEED_COMPATIBLE_SINCE_VERSION = 4; * replace it, dropping saved usage for deleted transcripts. Separate files keep * both. */ -export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v10.json"; +export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v11.json"; export const LEGACY_SCAN_CACHE_FILE_NAMES = [ + "usage-scan-cache-v10.json", "usage-scan-cache-v9.json", "usage-scan-cache-v8.json", "usage-scan-cache-v7.json", @@ -291,16 +292,19 @@ export function decodeScanCache( continue; } // Keep history for deleted rollouts, but re-parse incompatible reducer state. - // v9 repairs skipped initial Codex requests; clean v8 entries can still resume. + // v9 and v11 repair skipped Codex requests; clean v8+ entries stay served while unchanged. // v10 adds Claude advisor calls, which no older Claude entry holds. const legacy = (entry.p === "claude" && version < 10) || (format.state !== undefined && (version < 6 || - (entry.p === "codex" && (version < 8 || (version < 9 && malformedRecords > 0))))); + (entry.p === "codex" && (version < 8 || (version < 11 && malformedRecords > 0))))); // A corrupt state disqualifies the entry: resuming with it would attach // appended usage to the wrong model or replay fork-copied history. if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue; + // Before v11 a clean scan could end past an interrupted request whose usage its state dropped, + // so a grown file re-parses whole instead of resuming. + const resumable = !legacy && !(entry.p === "codex" && version < 11); const provider = entry.p; const records = decodeRecords(entry.r, provider); @@ -314,14 +318,14 @@ export function decodeScanCache( records, tailRecords, malformedRecords, - position: legacy - ? { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null } - : { + position: resumable + ? { resumeOffset: entry.o, guardLength: entry.gl, guardHash: entry.gh, state: entry.cs, - }, + } + : { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, }); } diff --git a/apps/server/src/usage/usageTranscriptReader.test.ts b/apps/server/src/usage/usageTranscriptReader.test.ts index f2b4fb43b48b4..105884d81ccfb 100644 --- a/apps/server/src/usage/usageTranscriptReader.test.ts +++ b/apps/server/src/usage/usageTranscriptReader.test.ts @@ -7,7 +7,7 @@ import * as NodePath from "node:path"; import * as NodeZlib from "node:zlib"; import { afterEach, assert, beforeEach, describe, it } from "@effect/vitest"; -import type { TranscriptUsageFormat } from "@t3tools/provider-core/server/usage"; +import { totalTokens, type TranscriptUsageFormat } from "@t3tools/provider-core/server/usage"; import * as Schema from "effect/Schema"; import { TEST_FORMATS } from "./usageTestFormats.ts"; @@ -381,6 +381,82 @@ describe("readTranscriptRecords resume", () => { }, ); + it.each([ + { mode: "buffered", streamingThresholdBytes: Infinity }, + { mode: "streaming", streamingThresholdBytes: 0 }, + ])( + "bills a Codex request whose turn was interrupted before its token_count ($mode)", + async (options) => { + const path = NodePath.join(dir, "rollout.jsonl"); + const usage = (input: number, output: number) => ({ + input_tokens: input, + cached_input_tokens: 0, + cache_write_input_tokens: 0, + output_tokens: output, + reasoning_output_tokens: 0, + total_tokens: input + output, + }); + const context = (turn: number) => ({ + type: "turn_context", + timestamp: `2026-11-02T10:00:0${turn * 4 - 4}.000Z`, + payload: { turn_id: `turn-${turn}`, model: "gpt-6-sol" }, + }); + const request = (turn: number, id: number, timestamp: string, last: unknown) => ({ + type: "token_usage_record", + timestamp, + payload: { turn_id: `turn-${turn}`, response_id: `resp_${id}`, usage: last }, + }); + const tokenCount = (timestamp: string, last: unknown, total: unknown) => ({ + type: "event_msg", + timestamp, + payload: { + type: "token_count", + info: { last_token_usage: last, total_token_usage: total }, + }, + }); + const lines = [ + { + type: "session_meta", + timestamp: "2026-11-02T10:00:00.000Z", + payload: { id: "aborted-turn-repro", model_provider: "openai" }, + }, + context(1), + request(1, 1, "2026-11-02T10:00:01.000Z", usage(100, 20)), + tokenCount("2026-11-02T10:00:01.001Z", usage(100, 20), usage(100, 20)), + // Interrupted after this request finished: no token_count reports it. + request(1, 2, "2026-11-02T10:00:02.000Z", usage(150, 10)), + { + type: "event_msg", + timestamp: "2026-11-02T10:00:03.000Z", + payload: { type: "turn_aborted", turn_id: "turn-1", reason: "interrupted" }, + }, + context(2), + request(2, 3, "2026-11-02T10:00:05.000Z", usage(200, 30)), + tokenCount("2026-11-02T10:00:05.001Z", usage(200, 30), usage(450, 60)), + ]; + // Lines longer than a read chunk take the projected path when streaming. + const padding = "x".repeat(256 * 1024); + await NodeFSP.writeFile( + path, + lines.map((line) => `${JSON.stringify({ padding, ...line })}\n`).join(""), + ); + + const result = await readTranscriptRecords(path, TEST_FORMATS.codex, undefined, options); + assert.isNotNull(result); + const requests = [...result.records, ...result.tailRecords] + .map((record) => totalTokens(record.totals)) + .toSorted((a, b) => a - b); + assert.deepStrictEqual( + { + billedTokens: requests.reduce((sum, tokens) => sum + tokens, 0), + requests, + malformedRecords: result.malformedRecords, + }, + { billedTokens: 510, requests: [120, 160, 230], malformedRecords: 0 }, + ); + }, + ); + it("re-parses from the start when the guard bytes no longer match", async () => { const path = NodePath.join(dir, "claude.jsonl"); await NodeFSP.writeFile(path, claudeLine(1, 5)); diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 5b90aeaa0331c..b76dff11362e8 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -1439,7 +1439,7 @@ it.effect.each([ return yield* Effect.die("expected Git command"); if (command.args[0] !== "fetch") return makeNonRepositoryHandle(); assert.deepEqual(command.args, ["fetch", "--quiet", "--", "origin"]); - assert.equal(command.options.env?.LC_ALL, "C"); + assert.equal(command.options.env?.LANGUAGE, "C"); assert.equal(command.options.env?.GIT_TERMINAL_PROMPT, "0"); yield* Ref.update(attempts, (count) => count + 1); return ChildProcessSpawner.makeHandle({ @@ -1863,7 +1863,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { command.args[0] === "branch" || command.args[0] === "checkout") ) { - locales.push(command.options.env?.LC_ALL); + locales.push(command.options.env?.LANGUAGE); } return delegate.spawn(command); }); @@ -4282,6 +4282,38 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { } }), ); + + // regression: #27749 hooks inherited the driver's forced LC_ALL=C + it.effect("runs post-checkout hooks under the server's own locale", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.GitVcsDriver; + const serverLocale = process.env.LC_ALL ?? "unset"; + const seenLocale = path.join(yield* makeTmpDir("git-hook-locale-"), "lc-all"); + yield* writeTextFile( + cwd, + "hooks/post-checkout", + `#!/bin/sh\necho "\${LC_ALL-unset}" > '${seenLocale}'\n[ "\${LC_ALL-unset}" = '${serverLocale}' ]\n`, + ); + yield* fs.chmod(path.join(cwd, "hooks/post-checkout"), 0o755); + yield* git(cwd, ["config", "core.hooksPath", path.join(cwd, "hooks")]); + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "locale"); + + const result = yield* driver + .createWorktree({ cwd, path: worktreePath, refName: initialBranch, newRefName: "locale" }) + .pipe(Effect.result); + + assert.equal( + (yield* fs.readFileString(seenLocale)).trim(), + serverLocale, + "post-checkout hook should see the server's LC_ALL", + ); + assert.isTrue(Result.isSuccess(result), "worktree creation failed in the hook"); + }), + ); it.effect.each(["commit", "short-commit", "tag", "revision"] as const)( "creates a worktree from a %s without recording it as a PR base", (kind) => @@ -4317,6 +4349,38 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + // regression: #28354 a failed worktree add left its new branch behind and blocked retries + it.effect("removes the new branch when the worktree cannot be added", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const path = yield* Path.Path; + const occupiedPath = yield* makeTmpDir("git-worktrees-"); + yield* writeTextFile(occupiedPath, "existing.txt", "occupied\n"); + const driver = yield* GitVcsDriver.GitVcsDriver; + + const failed = yield* driver + .createWorktree({ + cwd, + path: occupiedPath, + refName: initialBranch, + newRefName: "t3/collide", + }) + .pipe(Effect.result); + + assert.isTrue(Result.isFailure(failed)); + assert.equal(yield* git(cwd, ["branch", "--list", "t3/collide"]), ""); + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "retry"); + yield* driver.createWorktree({ + cwd, + path: worktreePath, + refName: initialBranch, + newRefName: "t3/collide", + }); + assert.equal(yield* git(worktreePath, ["branch", "--show-current"]), "t3/collide"); + }), + ); + it.effect("creates parallel worktrees in one repository without racing on its config", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index e8b3078002970..7db5190ed1397 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1198,7 +1198,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ...options, env: { ...options.env, - LC_ALL: "C", + // English diagnostics without overriding LC_CTYPE, which hooks inherit. + LANGUAGE: "C", }, }); @@ -4210,15 +4211,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } worktreePath = path.join(parentDir, repoName, directoryName); } - if (input.newRefName) { + const newRefName = input.newRefName; + if (newRefName) { // Kept apart from the checkout so the shared-config lock only covers the tracking write. yield* createBranchAt( "GitVcsDriver.createWorktree.createBranch", - { cwd: input.cwd, branch: input.newRefName, startPoint: input.refName }, + { cwd: input.cwd, branch: newRefName, startPoint: input.refName }, "git worktree add failed", ); } - const args = ["worktree", "add", "--", worktreePath, input.newRefName ?? input.refName]; + const args = ["worktree", "add", "--", worktreePath, newRefName ?? input.refName]; const progress = options?.progress; const onCheckoutProgress = progress?.onCheckoutProgress; @@ -4256,6 +4258,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } : {}), }, + ).pipe( + Effect.onError(() => + newRefName + ? deleteLocalBranch({ cwd: input.cwd, refName: newRefName, force: true }).pipe( + Effect.catch((cause) => + Effect.logWarning("could not remove the branch of a failed worktree", { cause }), + ), + ) + : Effect.void, + ), ); if (progress?.onWorktreeClaimed) { @@ -4314,7 +4326,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* timeoutMs: null, ...(onSubmoduleLine ? { - env: { LC_ALL: "C" }, + env: { LANGUAGE: "C" }, progress: { onStdoutLine: onSubmoduleLine, onStderrLine: onSubmoduleLine }, } : {}), @@ -4341,7 +4353,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ); } - const newRefName = input.newRefName; if (newRefName && base) { yield* Effect.gen(function* () { yield* writeConfigValue({ diff --git a/apps/server/src/vcs/VcsProcess.test.ts b/apps/server/src/vcs/VcsProcess.test.ts index 212415171bdc6..199ded803ee18 100644 --- a/apps/server/src/vcs/VcsProcess.test.ts +++ b/apps/server/src/vcs/VcsProcess.test.ts @@ -8,10 +8,12 @@ import * as Cause from "effect/Cause"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; import { ChildProcessSpawner } from "effect/process"; import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts"; @@ -316,6 +318,60 @@ describe("VcsProcess.run", () => { }), ); + it.effect("leaves git a slot while slow forge CLI processes are running", () => + Effect.gen(function* () { + const gate = yield* Deferred.make(); + const service = yield* VcsProcess.make.pipe( + Effect.provideService( + ProcessRunner.ProcessRunner, + ProcessRunner.ProcessRunner.of({ + run: (input) => + Effect.gen(function* () { + if (input.command !== "git") yield* Deferred.await(gate); + return { + stdout: "", + stderr: "", + code: ChildProcessSpawner.ExitCode(0), + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + stdoutInvalidUtf8: false, + stderrInvalidUtf8: false, + }; + }), + }), + ), + ); + + const forgeRuns = yield* Effect.forEach(Array.from({ length: 12 }), () => + service + .run({ + operation: "synthetic.forge.listChangeRequests", + command: "tea", + args: ["pulls", "list"], + cwd: "/workspace", + }) + .pipe(Effect.forkChild({ startImmediately: true })), + ); + const checkpoint = yield* service + .run({ + ...baseInput, + operation: VcsProcess.CHECKPOINT_CAPTURE_OPERATION, + args: ["rev-parse", "HEAD"], + }) + .pipe(Effect.timeoutOption("1 second"), Effect.forkChild({ startImmediately: true })); + yield* TestClock.adjust("1 second"); + + const gitResult = yield* Fiber.join(checkpoint); + yield* Deferred.succeed(gate, undefined); + yield* Fiber.joinAll(forgeRuns); + expect( + Option.isSome(gitResult), + "git waited behind forge CLI runs that held every VCS process slot", + ).toBe(true); + }), + ); + it.effect("keeps git from opening a folder laid out as a bare repository", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/vcs/VcsProcess.ts b/apps/server/src/vcs/VcsProcess.ts index 00218397481ff..c668a35e99272 100644 --- a/apps/server/src/vcs/VcsProcess.ts +++ b/apps/server/src/vcs/VcsProcess.ts @@ -65,6 +65,8 @@ const DEFAULT_TIMEOUT_MS = 30_000; const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000; const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]"; const VCS_PROCESS_CONCURRENCY = 8; +// Forge CLIs can take seconds per call; cap them together so git, checkpoints included, keeps slots. +const NON_GIT_PROCESS_CONCURRENCY = VCS_PROCESS_CONCURRENCY / 2; /** Shown to users when a Git command fails because another process holds the index lock. */ export const GIT_INDEX_LOCKED_DETAIL = @@ -183,6 +185,7 @@ export const make = Effect.gen(function* () { const processRunner = yield* ProcessRunner.ProcessRunner; const hostPlatform = yield* HostProcess.Platform; const vcsProcesses = yield* Semaphore.make(VCS_PROCESS_CONCURRENCY); + const nonGitProcesses = yield* Semaphore.make(NON_GIT_PROCESS_CONCURRENCY); const keyedProcesses = new Map(); const keyedPermit = (concurrency: NonNullable) => { let semaphore = keyedProcesses.get(concurrency.key); @@ -365,9 +368,8 @@ export const make = Effect.gen(function* () { }), ); } - return yield* input.concurrency === undefined - ? bounded - : keyedPermit(input.concurrency)(bounded); + const shared = input.command === "git" ? bounded : nonGitProcesses.withPermits(1)(bounded); + return yield* input.concurrency === undefined ? shared : keyedPermit(input.concurrency)(shared); }); return VcsProcess.of({ run }); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 1db1c80e56c96..aa52402920021 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -3174,13 +3174,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve )} {item.label} - {project && showProjectEnvironments ? ( - - ) : null} {project && canPinProject(project) ? ( toggleProjectGroupPin(project)} /> ) : null} + {project && showProjectEnvironments ? ( + + ) : null} {project ? (