diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts index 5ad39510d1..44c7aee5e3 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.test.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts @@ -307,6 +307,77 @@ describe("DesktopBackendManager", () => { }), ); + // The first probe's body stalls after the headers, or never ends past the 64 KiB read cap. + it.effect.each([ + { body: "stalled" as const, proven: true, readyAfterProbes: 2 }, + { body: "stalled" as const, proven: false, readyAfterProbes: 2 }, + { body: "endless" as const, proven: true, readyAfterProbes: 1 }, + ])( + "a $body probe body settles within its timeout (launch proof: $proven)", + ({ body, proven, readyAfterProbes }) => + Effect.gen(function* () { + const probes = yield* Ref.make(0); + const probed = yield* Deferred.make(); + const ready = yield* Deferred.make(); + const exit = yield* Deferred.make(); + const proof = "proof-for-abc"; + const firstBody = () => + new ReadableStream({ + start: (controller) => { + if (body === "endless") { + controller.enqueue(new TextEncoder().encode(proof.padEnd(70_000, "x"))); + } + }, + }); + const instance = yield* makeTestInstance({ + config: { + ...pollingConfig, + ...(proven + ? { + readinessProbe: Effect.succeed({ + path: "/launch-proof?challenge=abc", + accept: (text: string) => + Effect.succeed( + text === proof || (text.startsWith(proof) && text.length === 64 * 1024), + ), + }), + } + : {}), + }, + onReady: Deferred.succeed(ready, undefined).pipe(Effect.asVoid), + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.acquireRelease( + Effect.succeed(makeProcess({ exitCode: Deferred.await(exit) })), + () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)), + ), + ), + ), + httpClientLayer: layerHttpClient((request) => + Ref.getAndUpdate(probes, (count) => count + 1).pipe( + Effect.tap(() => Deferred.succeed(probed, undefined)), + Effect.map((count) => + HttpClientResponse.fromWeb( + request, + new Response(count === 0 ? firstBody() : proof, { status: 200 }), + ), + ), + ), + ), + }); + yield* instance.start; + yield* Deferred.await(probed); + // Past the probe timeout, then past the retry interval it starts. + yield* TestClock.adjust(Duration.seconds(1)); + yield* TestClock.adjust(Duration.seconds(1)); + + yield* Deferred.await(ready); + assert.equal(yield* Ref.get(probes), readyAfterProbes); + yield* instance.stop(); + }), + ); + it.effect("notices a WSL backend soon after it listens despite slow refused connects", () => Effect.gen(function* () { const ready = yield* Deferred.make(); diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index d411bed538..cb50a44585 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -281,6 +281,7 @@ export interface ThreadFeedLatestRun { readonly providerStartingLabel?: string; readonly providerStartingLabelMsg?: string; readonly providerStarting?: { readonly driver: string }; + readonly awaitedEarlierSubagents?: number; } /** Long Android headers can ANR despite one-line display; cap labels only, preserving expanded and copied text. */ @@ -1514,7 +1515,8 @@ function latestRunsEqual(left: ThreadFeedLatestRun | null, right: ThreadFeedLate left.turnEnded === right.turnEnded && left.providerStartingLabel === right.providerStartingLabel && left.providerStartingLabelMsg === right.providerStartingLabelMsg && - left.providerStarting?.driver === right.providerStarting?.driver) + left.providerStarting?.driver === right.providerStarting?.driver && + left.awaitedEarlierSubagents === right.awaitedEarlierSubagents) ); } @@ -2022,7 +2024,13 @@ export function deriveThreadFeedPresentation( const waitingOn = activeRunId === null ? 0 - : countSubagentsBlockingRun(feed, activeRunId, feedEntryTurnItems, !zen); + : countSubagentsBlockingRun( + feed, + activeRunId, + feedEntryTurnItems, + !zen, + latestRun?.awaitedEarlierSubagents, + ); result.push( thinkingRow( activeWorkStartedAt, diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index 3f0da9eaf4..fe0bdde298 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -1532,6 +1532,7 @@ describe("source control tools", () => { thread: branchThread, pullRequests: { diff: (input) => Effect.succeed(pages[input.cursor ?? "first"]!), + summary: () => Effect.succeed({ state: "open", headSha: "fed9876" } as never), submitReview: (input) => Effect.sync(() => void reviews.push(input)), }, }); @@ -1567,6 +1568,23 @@ describe("source control tools", () => { }) .pipe(Effect.flip); expect(error.message).toContain("a.ts line 40 (new side) is not in this PR's diff"); + // Pinned to a head that moved, the line is gone because of the new commits. + const moved = yield* harness + .call("pull_request_review", { + verdict: "comment", + expectedHeadSha: "abc1234", + comments: [{ path: "a.ts", line: 40, body: "Here?" }], + }) + .pipe(Effect.flip); + expect(moved.message).toContain("The head is now fed9876, not abc1234"); + const current = yield* harness + .call("pull_request_review", { + verdict: "comment", + expectedHeadSha: "fed9876", + comments: [{ path: "a.ts", line: 40, body: "Here?" }], + }) + .pipe(Effect.flip); + expect(current.message).toContain("a.ts line 40 (new side) is not in this PR's diff"); expect(reviews).toHaveLength(1); }), ); diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index 6e553c5b62..973f13dd8c 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -17,6 +17,7 @@ import { TrimmedNonEmptyString, pullRequestConversationThreads, } from "@onicode/contracts"; +import { isHeadSha } from "@onicode/shared/git"; import * as Cause from "effect/Cause"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; @@ -450,8 +451,7 @@ const make = Effect.gen(function* () { const headSha = layer.number !== ref.number ? layer.headSha - : layer.headSha !== undefined && - PullRequestService.isHeadSha(layer.headSha, input.expectedHeadSha) + : layer.headSha !== undefined && isHeadSha(layer.headSha, input.expectedHeadSha) ? layer.headSha : input.expectedHeadSha; if (headSha === undefined) @@ -487,6 +487,7 @@ const make = Effect.gen(function* () { const reviewComments = Effect.fn("PullRequestsToolkit.reviewComments")(function* ( ref: PullRequestRef, comments: ReadonlyArray, + expectedHeadSha: string | undefined, ) { const placed = new Map(); const unplaced = () => comments.filter((comment) => !placed.has(comment)); @@ -515,6 +516,17 @@ const make = Effect.gen(function* () { } const missing = unplaced()[0]; if (missing !== undefined) { + // A line can be missing because the head moved, which the agent fixes by reading it again. + if (expectedHeadSha !== undefined) { + const { headSha } = yield* pullRequests + .summary(ref, { bypassCache: true }) + .pipe(Effect.mapError(forgeFailure)); + if (headSha !== undefined && !isHeadSha(headSha, expectedHeadSha)) { + return yield* new PullRequestForgeError({ + detail: `The head is now ${headSha}, not ${expectedHeadSha}. Review the new commits first.`, + }); + } + } return yield* new PullRequestForgeError({ detail: `${missing.path} line ${missing.startLine ?? missing.line} (${missing.side ?? "new"} side) is not in this PR's diff. Comment on a changed line or one shown around it.`, }); @@ -1210,7 +1222,7 @@ const make = Effect.gen(function* () { }); } const { target, ref } = yield* locate(input); - const comments = yield* reviewComments(ref, input.comments ?? []); + const comments = yield* reviewComments(ref, input.comments ?? [], input.expectedHeadSha); yield* pullRequests .submitReview({ ...ref, diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 5aeff053ee..e5c059859c 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -79,6 +79,7 @@ import { import { MAX_AGENT_TERMINAL_OUTPUT_CHARS } from "@onicode/provider-acp/server/runtimeModel"; import { extractXAiAcpSubagentUpdate, + extractXAiAwaitedSubagentIds, makeGrokAdapterV2, makeXAiPromptCompletionRuntime, normalizeXAiAcpToolCallState, @@ -11059,6 +11060,185 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest), Effect.scoped), ); + it.effect.each([ + { ends: "the poll returns", end: "returns", untilMarker: [true, false, true, "marker"] }, + { + ends: "the prompt ends inside the poll", + end: "inside", + untilMarker: [true, false, "marker"], + }, + { + ends: "the poll drops its timeout", + end: "untimed", + untilMarker: [true, false, true, "marker"], + }, + ] as const)( + "marks a Grok child awaited only while a blocking poll names it, until $ends", + ({ end, untilMarker }) => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const instanceId = ProviderInstanceId.make("acp-grok-poll"); + const threadId = ThreadId.make("thread-acp-grok-poll"); + const childSessionId = "019f44a6-4820-7402-925d-bc862ee71200"; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + const poll = (toolCallId: string, rawInput: Record) => + sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call", + toolCallId, + title: "get_command_or_subagent_output", + kind: "other", + status: "pending", + rawInput: { task_ids: [childSessionId], ...rawInput }, + }, + }); + const pollReturned = (toolCallId: string) => + sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call_update", + toolCallId, + status: "completed", + rawOutput: { type: "Text", text: "Status: running" }, + }, + }); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + continuationRequests: { offer: () => Effect.void }, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + extractSubagentUpdate: extractXAiAcpSubagentUpdate, + extractSubagentWait: extractXAiAwaitedSubagentIds, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Effect.gen(function* () { + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call", + toolCallId: "tool-call-spawn", + title: "spawn_subagent", + kind: "other", + status: "completed", + rawInput: { description: "Researcher", prompt: "Research" }, + rawOutput: { + type: "Text", + text: `Subagent started in background.\nsubagent_id: ${childSessionId}`, + }, + }, + }); + // Without a timeout the poll only reads the child's status. + yield* poll("tool-call-peek", {}); + yield* pollReturned("tool-call-peek"); + yield* poll("tool-call-wait", { timeout_ms: 15_000 }); + if (end === "untimed") { + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "tool-call-wait", + status: "in_progress", + rawInput: { task_ids: [childSessionId], timeout_ms: 0 }, + }, + }); + } + if (end === "returns") yield* pollReturned("tool-call-wait"); + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call", + toolCallId: "tool-call-marker", + title: "Read", + kind: "read", + status: "completed", + rawInput: { path: "README.md" }, + }, + }); + return { stopReason: "end_turn" as const }; + }), + }), + }), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-grok-poll"), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const turnInput = makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + }); + yield* runtime.startTurn(turnInput); + const seen: Array = []; + while (seen.at(-1)?.type !== "turn.terminal") seen.push(yield* Queue.take(events)); + // Each change, in order; a status update may re-emit the same value. + const changes = (values: ReadonlyArray) => + values.filter((value, index) => index === 0 || values[index - 1] !== value); + assert.deepEqual( + changes( + seen.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "subagent" + ? [event.turnItem.background] + : [], + ), + ), + [true, false, true], + ); + assert.deepEqual( + changes( + seen.flatMap((event) => + event.type === "subagent.updated" ? [event.subagent.awaitedByRunId] : [], + ), + ), + [undefined, turnInput.runId, undefined], + ); + // The marker tool comes after the poll section, before the turn ends. + const trace = changes( + seen.flatMap((event): Array => { + if (event.type !== "turn_item.updated") return []; + if (event.turnItem.type === "subagent") return [event.turnItem.background ?? false]; + return event.turnItem.nativeItemRef?.nativeId === "tool-call-marker" ? ["marker"] : []; + }), + ); + assert.deepEqual(trace.slice(0, trace.indexOf("marker") + 1), [...untilMarker]); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + it.effect( "user attach flushes a deferred terminal but leaves wake traffic for its continuation", () => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 5e9c10f71e..10e530def6 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -15888,6 +15888,12 @@ describe("ClaudeAdapterV2 background wake turns", () => { name: "Bash", input: { command: movedScript }, }, + { + type: "tool_use", + id: "toolu_moved_timer", + name: "Bash", + input: { command: "sleep 300; date" }, + }, ], }, parent_tool_use_id: null, @@ -15909,6 +15915,20 @@ describe("ClaudeAdapterV2 background wake turns", () => { session_id: WAKE_NATIVE_SESSION, }), ); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: "moved-timer", + tool_use_id: "toolu_moved_timer", + description: "Wait before the next check", + is_backgrounded: false, + task_type: "local_bash", + uuid: "00000000-0000-4000-8000-000000000207", + session_id: WAKE_NATIVE_SESSION, + }), + ); yield* Queue.offer( harness.sdkMessages, claudeSdkFrame({ @@ -15921,6 +15941,12 @@ describe("ClaudeAdapterV2 background wake turns", () => { task_type: "local_bash", description: `\n${movedScript}`, }, + // A foreground timer Claude moved to the background is a timer all the same. + { + task_id: "moved-timer", + task_type: "local_bash", + description: "Wait before the next check", + }, ], uuid: "00000000-0000-4000-8000-000000000206", session_id: WAKE_NATIVE_SESSION, @@ -15939,6 +15965,8 @@ describe("ClaudeAdapterV2 background wake turns", () => { ["endless_sleep", "sleep infinity", false], ["delayed_server", "sleep 5 && npm run dev", false], ["substituted_server", 'sleep 60; echo "$(npm run dev)"', false], + // Past the roster's 1,000-character preview, which would cut off the server. + ["long_server", `sleep 5 && echo ${"x".repeat(1_000)} && npm run dev`, false], ] as const; yield* Queue.offer( harness.sdkMessages, @@ -15995,6 +16023,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { [ [WAKE_TASK_ID, false], ["moved-build", false], + ["moved-timer", true], ...sleeps.map(([taskId, , awaited]) => [taskId, awaited]), ], ); @@ -24994,6 +25023,19 @@ describe("ClaudeAdapterV2 background wake turns", () => { : [], ); assert.deepEqual(childEfforts, ["low", undefined, "max"]); + // Its owner waits on a nested task, not the root, even when Claude omits spawn_depth. + const rowBackground = new Map( + harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "subagent" + ? [[event.turnItem.nativeItemRef?.nativeId, event.turnItem.background] as const] + : [], + ), + ); + assert.deepEqual(Object.fromEntries(rowBackground), { + [`task-${OUTER_TOOL_USE_ID}`]: undefined, + [`task-${UNSPECIFIED_TOOL_USE_ID}`]: true, + [`task-${OVERRIDING_TOOL_USE_ID}`]: true, + }); }).pipe( Effect.provideService(WorkflowAgentTranscriptReadObserver, (read) => read.agentId === `task-${UNSPECIFIED_TOOL_USE_ID}` diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index c74b81a1df..1b3020917b 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2709,9 +2709,9 @@ const CLAUDE_SLEEP_TIMER_REPORT = /^[ \t]*(?:$|(?:date|echo|printf|true|:)(?:[ \ // A background command that only sleeps for a finite time, then at most prints the time or a // note, is a timer the agent set to check back, which Claude wakes it for when it ends. Any other // step (`sleep 5 && npm run dev`) may never end, so that command is not a timer. -function isClaudeSleepTimer(command: string | undefined): boolean { - const start = command === undefined ? null : CLAUDE_SLEEP_TIMER_START.exec(command); - if (command === undefined || start === null) return false; +function isClaudeSleepTimer(command: string): boolean { + const start = CLAUDE_SLEEP_TIMER_START.exec(command); + if (start === null) return false; const steps = splitClaudeSleepTimerSteps(command.slice(start[0].length)); return steps !== undefined && steps.every((step) => CLAUDE_SLEEP_TIMER_REPORT.test(step)); } @@ -4482,6 +4482,26 @@ function claudePendingBackgroundTasksFromRoster( ); } +interface ClaudeBackgroundTaskListing { + readonly task: OrchestrationV2PendingBackgroundTask; + /** The whole command, which the task holds only a preview of. */ + readonly command: string | undefined; +} + +// The agent ends its turn on a monitor or timer, so one counts as awaited once, when first listed. +function claudeListingStartsWait( + { task, command }: ClaudeBackgroundTaskListing, + previous: OrchestrationV2PendingBackgroundTask | undefined, +): boolean { + if (task.kind === "monitor") return previous?.kind !== "monitor"; + return ( + task.kind === "command" && + command !== undefined && + previous?.command === undefined && + isClaudeSleepTimer(command) + ); +} + function parseClaudeBackgroundTaskEntry( entry: unknown, monitorTasks: ReadonlyMap, @@ -7819,25 +7839,32 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* ( nativeThreadId: string, - tasks: ReadonlyArray, + listings: ReadonlyArray, ) { - yield* Ref.update(pendingBackgroundTasksByNativeThread, (current) => { - const updated = new Map(current); - if (tasks.length === 0) { - updated.delete(nativeThreadId); - } else { - updated.set( - nativeThreadId, - new Map( - tasks.map((task) => { - const previous = current.get(nativeThreadId)?.get(task.taskId); - return [task.taskId, { ...previous, ...task }] as const; - }), - ), + const tasks = listings.map(({ task }) => task); + const startedWaits = yield* Ref.modify( + pendingBackgroundTasksByNativeThread, + (current) => { + const previous = rosterForNativeThread(current, nativeThreadId); + const updated = new Map(current); + if (tasks.length === 0) { + updated.delete(nativeThreadId); + } else { + updated.set( + nativeThreadId, + new Map( + tasks.map((task) => [task.taskId, { ...previous.get(task.taskId), ...task }]), + ), + ); + } + const startedWaits = listings.flatMap((listing) => + claudeListingStartsWait(listing, previous.get(listing.task.taskId)) + ? [listing.task.taskId] + : [], ); - } - return updated; - }); + return [startedWaits, updated] as const; + }, + ); yield* rememberOpaqueTasks(tasks); if (tasks.length > 0) { yield* markWakeEligibleOpaqueBackgroundTasks( @@ -7856,25 +7883,25 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( else updated.set(nativeThreadId, kept); return updated; }); + yield* addTaskIdsToNativeThreadSet( + awaitedBackgroundTasksByNativeThread, + nativeThreadId, + startedWaits, + ); }); const upsertPendingBackgroundTask = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* ( nativeThreadId: string, - task: OrchestrationV2PendingBackgroundTask, + listing: ClaudeBackgroundTaskListing, ) { + const { task } = listing; const startedWait = yield* Ref.modify( pendingBackgroundTasksByNativeThread, (current) => { const roster = new Map(rosterForNativeThread(current, nativeThreadId)); - const previous = roster.get(task.taskId); - const startedWait = - task.kind === "monitor" - ? previous?.kind !== "monitor" - : task.kind === "command" && - previous?.command === undefined && - isClaudeSleepTimer(task.command); + const startedWait = claudeListingStartsWait(listing, roster.get(task.taskId)); roster.set(task.taskId, task); return [startedWait, new Map(current).set(nativeThreadId, roster)] as const; }, @@ -11664,10 +11691,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); }); - const backgroundTaskLaunch = ( + const listBackgroundTask = ( activeContext: ActiveClaudeTurnContext | null, toolUseId: string | undefined, - ): Pick => { + task: OrchestrationV2PendingBackgroundTask, + ): ClaudeBackgroundTaskListing => { // A background subagent keeps launching shells after the root turn settles. const launch = toolUseId === undefined @@ -11678,14 +11706,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( launch?.toolName === "Monitor" ? firstStringInputField(launch.input, ["command"]) : undefined; - if (launch === undefined || command === undefined) return {}; + if (launch === undefined || command === undefined) return { task, command: undefined }; return { - command: backgroundWorkTextPreview(command), - itemId: idAllocator.derive.turnItemFromProviderItem({ - driver: CLAUDE_PROVIDER, - nativeItemId: launch.nativeItemId, - }), - sourceThreadId: launch.threadId, + task: { + command: backgroundWorkTextPreview(command), + itemId: idAllocator.derive.turnItemFromProviderItem({ + driver: CLAUDE_PROVIDER, + nativeItemId: launch.nativeItemId, + }), + sourceThreadId: launch.threadId, + ...task, + }, + command, }; }; @@ -11702,7 +11734,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (!Array.isArray(roster)) { return false; } - const nextTasks: OrchestrationV2PendingBackgroundTask[] = []; + const listings: ClaudeBackgroundTaskListing[] = []; const listedTaskIds = new Set( roster.flatMap((entry) => { const taskId = @@ -11731,13 +11763,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const task = parseClaudeBackgroundTaskEntry(entry, monitorTasks, toolUseIds); if (task !== null) { // A foreground command Claude moved to the background first appears here. - nextTasks.push({ - ...backgroundTaskLaunch(input.activeContext, task.nativeItemId), - ...task, - }); + listings.push(listBackgroundTask(input.activeContext, task.nativeItemId, task)); } } - yield* replacePendingBackgroundTasks(input.nativeThreadId, nextTasks); + yield* replacePendingBackgroundTasks(input.nativeThreadId, listings); rosterChanged = true; } else if (message.type === "system" && message.subtype === "task_started") { if (!isClaudeNonSubagentTask(message)) { @@ -11758,22 +11787,26 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (message.is_backgrounded === false) { return false; } - yield* upsertPendingBackgroundTask(input.nativeThreadId, { - ...backgroundTaskLaunch(input.activeContext, message.tool_use_id), - ...claudePendingBackgroundTask({ - taskId: message.task_id, - taskType: claudeTaskTypeFromSdkMessage(message), - startedByMonitor: yield* isClaudeMonitorTask({ - nativeThreadId: input.nativeThreadId, + yield* upsertPendingBackgroundTask( + input.nativeThreadId, + listBackgroundTask( + input.activeContext, + message.tool_use_id, + claudePendingBackgroundTask({ taskId: message.task_id, - toolUseId: message.tool_use_id, + taskType: claudeTaskTypeFromSdkMessage(message), + startedByMonitor: yield* isClaudeMonitorTask({ + nativeThreadId: input.nativeThreadId, + taskId: message.task_id, + toolUseId: message.tool_use_id, + }), + description: + typeof message.description === "string" ? message.description : undefined, + parentTaskId: Reflect.get(message, "parent_task_id"), + toolUseId, }), - description: - typeof message.description === "string" ? message.description : undefined, - parentTaskId: Reflect.get(message, "parent_task_id"), - toolUseId, - }), - }); + ), + ); rosterChanged = true; } else if (message.type === "system" && message.subtype === "task_notification") { yield* endClaudeMonitorTasks((taskId) => taskId === message.task_id); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 82358d9673..c3d60e688b 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -11771,105 +11771,181 @@ describe("CodexAdapterV2 post-settle continuation", () => { ); it.effect.each([ - { ends: "the wait returns", turnEnds: false }, - { ends: "the turn ends inside the wait", turnEnds: true }, - ])("marks a Codex child awaited only while a wait call names it, until $ends", ({ turnEnds }) => - Effect.gen(function* () { - const collab = (tool: "spawnAgent" | "wait", status: "inProgress" | "completed") => ({ - type: "collabAgentToolCall", - id: `call-codex-${tool}`, - tool, - status, - senderThreadId: RESUME_NATIVE_THREAD, - receiverThreadIds: [RESUME_CHILD_THREAD], - agentsStates: - status === "completed" - ? { [RESUME_CHILD_THREAD]: { status: "running", message: `${tool} returned` } } - : {}, - }); - const frame = ( - method: "item/started" | "item/completed", - item: ReturnType, - ) => ({ - type: "emit_inbound" as const, - frame: { - method, - params: { - item, - threadId: RESUME_NATIVE_THREAD, - turnId: RESUME_NATIVE_TURN, - ...(method === "item/started" - ? { startedAtMs: 1782622441000 } - : { completedAtMs: 1782622442000 }), + { ends: "the wait returns", turnEnds: false, otherThreadTurn: false }, + { ends: "the turn ends inside the wait", turnEnds: true, otherThreadTurn: false }, + // One app-server serves several threads; another thread's turn end frees nothing here. + { + ends: "the wait returns after another thread's turn", + turnEnds: false, + otherThreadTurn: true, + }, + ])( + "marks a Codex child awaited only while a wait call names it, until $ends", + ({ turnEnds, otherThreadTurn }) => + Effect.gen(function* () { + const OTHER_NATIVE_THREAD = "native-codex-other-thread"; + const OTHER_NATIVE_TURN = "native-codex-other-turn"; + const otherPreamble = codexReplayPreamble({ + nativeThreadId: OTHER_NATIVE_THREAD, + nativeTurnId: OTHER_NATIVE_TURN, + prompt: "Other work", + }); + const otherThreadEntries: Array = [ + ...otherPreamble.slice(3, 5).map((entry) => withReplayRequestId(entry, 4)), + ...otherPreamble.slice(5, 7).map((entry) => withReplayRequestId(entry, 5)), + otherPreamble[7]!, + { + type: "emit_inbound", + label: "other-turn-completed", + frame: { + method: "turn/completed", + params: { + threadId: OTHER_NATIVE_THREAD, + turn: makeCodexReplayTurn({ id: OTHER_NATIVE_TURN, status: "completed" }), + }, + }, }, - }, - }); - const harness = yield* makeCodexReplayHarness( - makeCodexReplayTranscript({ - scenario: RESUME_SCENARIO, - entries: [ - ...codexReplayPreamble({ - nativeThreadId: RESUME_NATIVE_THREAD, - nativeTurnId: RESUME_NATIVE_TURN, - prompt: RESUME_PROMPT, - }), - frame("item/completed", collab("spawnAgent", "completed")), - frame("item/started", collab("wait", "inProgress")), - turnEnds - ? { - type: "emit_inbound" as const, - frame: { - method: "turn/completed", - params: { - threadId: RESUME_NATIVE_THREAD, - turn: makeCodexReplayTurn({ id: RESUME_NATIVE_TURN, status: "completed" }), + ]; + const waitReleased = yield* Deferred.make(); + const collab = (tool: "spawnAgent" | "wait", status: "inProgress" | "completed") => ({ + type: "collabAgentToolCall", + id: `call-codex-${tool}`, + tool, + status, + senderThreadId: RESUME_NATIVE_THREAD, + receiverThreadIds: [RESUME_CHILD_THREAD], + agentsStates: + status === "completed" + ? { [RESUME_CHILD_THREAD]: { status: "running", message: `${tool} returned` } } + : {}, + }); + const frame = ( + method: "item/started" | "item/completed", + item: ReturnType, + ) => ({ + type: "emit_inbound" as const, + frame: { + method, + params: { + item, + threadId: RESUME_NATIVE_THREAD, + turnId: RESUME_NATIVE_TURN, + ...(method === "item/started" + ? { startedAtMs: 1782622441000 } + : { completedAtMs: 1782622442000 }), + }, + }, + }); + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: RESUME_SCENARIO, + entries: [ + ...codexReplayPreamble({ + nativeThreadId: RESUME_NATIVE_THREAD, + nativeTurnId: RESUME_NATIVE_TURN, + prompt: RESUME_PROMPT, + }), + frame("item/completed", collab("spawnAgent", "completed")), + frame("item/started", collab("wait", "inProgress")), + ...(otherThreadTurn ? otherThreadEntries : []), + turnEnds + ? { + type: "emit_inbound" as const, + frame: { + method: "turn/completed", + params: { + threadId: RESUME_NATIVE_THREAD, + turn: makeCodexReplayTurn({ id: RESUME_NATIVE_TURN, status: "completed" }), + }, }, + } + : // The wait timed out with the child still running. + { + ...frame("item/completed", collab("wait", "completed")), + label: "wait-completed", }, - } - : // The wait timed out with the child still running. - frame("item/completed", collab("wait", "completed")), - ], - }), - ); - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ + ], + }), + undefined, + undefined, + undefined, + (entry) => + otherThreadTurn && entry.label === "wait-completed" + ? Deferred.await(waitReleased) + : Effect.void, + ); + const turnInput = makeCodexTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now: yield* DateTime.now, attemptId: RunAttemptId.make("attempt-codex-wait"), text: RESUME_PROMPT, - }), - ); - // Each change of the flag, in order; a state update may re-emit the same value. - const transitions = () => - harness.events - .flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.type === "subagent" - ? [event.turnItem.background] - : [], - ) - .filter((background, index, all) => index === 0 || all[index - 1] !== background); - yield* harness.until(() => - turnEnds - ? harness.events.some((event) => event.type === "turn.terminal") - : harness.events.some( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.result === "wait returned", - ), - ); - assert.deepEqual(transitions(), [true, false, true]); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, + }); + yield* harness.runtime.startTurn(turnInput); + // Each change of the flag, in order; a state update may re-emit the same value. + const transitions = () => + harness.events + .flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "subagent" + ? [event.turnItem.background] + : [], + ) + .filter((background, index, all) => index === 0 || all[index - 1] !== background); + // The run whose wait holds the parent, which clients count even when it launched no row. + const awaitedByRuns = () => + harness + .subagentUpdates() + .map((event) => event.subagent.awaitedByRunId) + .filter((runId, index, all) => index === 0 || all[index - 1] !== runId); + if (otherThreadTurn) { + const otherThreadId = ThreadId.make("thread-codex-other"); + const otherProviderThread = yield* harness.runtime.ensureThread({ + threadId: otherThreadId, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }); + // Forked: the replay holds the wait's end until this thread's turn is checked. + const otherTurn = yield* harness.runtime + .startTurn( + makeCodexTestTurnInput({ + threadId: otherThreadId, + providerThread: otherProviderThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-codex-other"), + text: "Other work", + }), + ) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* harness.until(() => + harness.events.some((event) => event.type === "turn.terminal"), + ); + assert.deepEqual(transitions(), [true, false]); + assert.deepEqual(awaitedByRuns(), [undefined, turnInput.runId]); + yield* Deferred.succeed(waitReleased, undefined); + yield* Fiber.join(otherTurn); + } + yield* harness.until(() => + turnEnds + ? harness.events.some((event) => event.type === "turn.terminal") + : harness.events.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "subagent" && + event.turnItem.result === "wait returned", + ), + ); + assert.deepEqual(transitions(), [true, false, true]); + assert.deepEqual(awaitedByRuns(), [undefined, turnInput.runId, undefined]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), ), ), - ), ); it.effect("preserves a subagent result across a trailing empty final and resume", () => diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index cd091b304b..6e01eb0034 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -3408,8 +3408,13 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( input.subagent.background = true; input.subagent.awaitedBy = null; } + const { awaitedByRunId: _awaitedByRunId, ...unawaited } = prior; + const awaitedByRunId = isOrchestrationV2WorkActive(status) + ? (input.subagent.awaitedBy?.projectionRunId ?? null) + : null; const task = { - ...prior, + ...unawaited, + ...(awaitedByRunId === null ? {} : { awaitedByRunId }), status, ...(input.reopen ? { diff --git a/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts b/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts index ddda635c90..e94a028601 100644 --- a/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts +++ b/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts @@ -41,6 +41,8 @@ const stopEarlierBackgroundWork = ({ failedStart = false, stopWithQueue, olderStart = false, + resumedOlder = false, + steeredTail = false, backgroundWorkAfterStop, stalledRun, workflowMember = false, @@ -50,6 +52,10 @@ const stopEarlierBackgroundWork = ({ readonly backgroundWorkAfterStop?: "running" | "unknown"; readonly stopWithQueue?: "thread.stop" | "run.interrupt"; readonly olderStart?: boolean; + /** The held older run was resumed, so it ended after the runs queued behind it. */ + readonly resumedOlder?: boolean; + /** The queued message was steered into the latest run, so its own run never started. */ + readonly steeredTail?: boolean; readonly workflowMember?: boolean; readonly stalledRun?: "missing-session-terminal" | "returned-interrupt" | "superseded-attempt"; }) => @@ -994,7 +1000,9 @@ const stopEarlierBackgroundWork = ({ threadId, runId: queued.id, occurredAt: now, - payload: { ...queued, queueHeld: true }, + payload: steeredTail + ? { ...queued, status: "cancelled", queuePosition: null, completedAt: now } + : { ...queued, queueHeld: true }, }, { id: EventId.make("latest-run-settled"), @@ -1026,6 +1034,26 @@ const stopEarlierBackgroundWork = ({ }); } + if (resumedOlder) { + const older = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.id === watcherRun.runId, + )!; + yield* sink.write({ + events: [ + { + id: EventId.make("older-run-ended-last"), + type: "run.updated", + threadId, + runId: older.id, + occurredAt: now, + payload: { ...older, completedAt: DateTime.add(now, { seconds: 1 }) }, + }, + ], + }); + } + + const stopTarget = + olderStart || resumedOlder ? watcherRun : failedStart ? failedRun : latestRun; yield* orchestrator.dispatch( stopWithQueue === "thread.stop" ? { @@ -1037,11 +1065,7 @@ const stopEarlierBackgroundWork = ({ type: "run.interrupt", commandId: CommandId.make("stop-background-work"), threadId, - runId: olderStart - ? watcherRun.runId - : failedStart - ? failedRun.runId - : latestRun.runId, + runId: stopTarget.runId, ...(stopWithQueue === undefined ? {} : { holdQueue: true }), }, ); @@ -1050,17 +1074,28 @@ const stopEarlierBackgroundWork = ({ assert.sameDeepMembers( interrupts.map((interrupt) => [interrupt.providerThread.id, interrupt.providerTurnId]), [ - ...(olderStart || failedStart ? [] : [[otherProviderThreadId, latestRun.providerTurnId]]), - [codexProviderThread.id, reviewerRun.providerTurnId], + ...(olderStart || resumedOlder || failedStart + ? [] + : [[otherProviderThreadId, latestRun.providerTurnId]]), + [ + codexProviderThread.id, + resumedOlder ? watcherRun.providerTurnId : reviewerRun.providerTurnId, + ], ], ); const after = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual( + after.turnItems.flatMap((item) => + item.type === "run_interrupt_request" ? [item.runId] : [], + ), + [stopTarget.runId], + ); if (olderStart) { assert.equal(after.runs.find((run) => run.id === watcherRun.runId)?.status, "interrupted"); } if (stopWithQueue !== undefined) { - assert.equal(after.runs.at(-1)?.status, "queued"); - assert.equal(after.runs.at(-1)?.queueHeld, true); + assert.equal(after.runs.at(-1)?.status, steeredTail ? "cancelled" : "queued"); + if (!steeredTail) assert.equal(after.runs.at(-1)?.queueHeld, true); assert.lengthOf(started, 1); } assert.deepEqual( @@ -1137,6 +1172,11 @@ it.effect.each(["thread.stop", "run.interrupt"] as const)( (stopType) => stopEarlierBackgroundWork({ stopWithQueue: stopType, olderStart: true }), ); +it.effect.each([{ resumedOlder: true }, { steeredTail: true }])( + "Stop targets the run that ran last, not the highest ordinal (%o)", + (row) => stopEarlierBackgroundWork({ stopWithQueue: "thread.stop", ...row }), +); + it.effect.each(["missing-session-terminal", "returned-interrupt", "superseded-attempt"] as const)( "Stop recovers a stalled run after %s without changing a newer attempt", (stalledRun) => stopEarlierBackgroundWork({ stalledRun }), diff --git a/apps/server/src/orchestration-v2/IdleCompaction.test.ts b/apps/server/src/orchestration-v2/IdleCompaction.test.ts index 83653cb945..765cb8cfaf 100644 --- a/apps/server/src/orchestration-v2/IdleCompaction.test.ts +++ b/apps/server/src/orchestration-v2/IdleCompaction.test.ts @@ -14,6 +14,7 @@ import { ThreadId, TurnItemId, } from "@onicode/contracts"; +import { latestExecutedRun } from "@onicode/shared/orchestrationV2ThreadError"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -202,6 +203,34 @@ describe("idleCompactionWindow", () => { // A turn Claude itself reported as cancelled did run, so it stays the latest. steered.runs = steered.runs.map((run) => ({ ...run, startedAt: at(-MINUTE_MS) })); expect(idleCompactionWindow(steered, NOW_MS)).toBeNull(); + // A held message resumed after a later run ended: the run that ended last is the latest. + const resumed = records(cache); + resumed.runs = [ + ...resumed.runs, + { + ...resumed.runs[0]!, + id: RunId.make("run-2"), + ordinal: 2, + userMessageId: MessageId.make("message-2"), + status: "interrupted", + startedAt: at(-2 * MINUTE_MS), + completedAt: at(-MINUTE_MS), + }, + ]; + expect(idleCompactionWindow(resumed, NOW_MS)?.runId).toBe(runId); + resumed.runs = [ + ...resumed.runs, + { + ...resumed.runs[0]!, + id: RunId.make("run-3"), + ordinal: 3, + userMessageId: MessageId.make("message-3"), + status: "queued", + startedAt: null, + completedAt: null, + }, + ]; + expect(idleCompactionWindow(resumed, NOW_MS)).toBeNull(); const archived = records(cache); archived.thread = { ...archived.thread, archivedAt: at() }; expect(idleCompactionWindow(archived, NOW_MS)).toBeNull(); @@ -377,7 +406,10 @@ describe("IdleCompactionService", () => { }, ); - it.effect("keeps the latest run's compaction when an earlier run reports completed again", () => + it.effect.each([ + { case: "keeps the latest run's compaction when an earlier run reports completed again" }, + { case: "compacts an earlier run resumed after a later one was interrupted", resumed: true }, + ])("$case", ({ resumed }) => Effect.gen(function* () { yield* TestClock.setTime(NOW_MS); const base = records({ cacheExpiresInMs: 10 * MINUTE_MS }); @@ -389,6 +421,7 @@ describe("IdleCompactionService", () => { id: laterRunId, ordinal: 2, userMessageId: laterMessageId, + ...(resumed ? { status: "interrupted" as const, completedAt: at(-MINUTE_MS) } : {}), }; const cancelledRun = { ...earlierRun, @@ -444,6 +477,23 @@ describe("IdleCompactionService", () => { getThreadRecords: (_threadId, _keys, options) => Effect.succeed({ ...data, + // As the store reads them: the asked statuses, plus the run that ran last or the + // highest one started. + runs: data.runs.filter( + (run) => + options?.runStatuses === undefined || + options.runStatuses.includes(run.status) || + (options.includeLatestExecutedRun === true && + run === latestExecutedRun(data.runs)) || + (options.includeLatestRun === true && + run === + data.runs + .filter( + (candidate) => + candidate.status !== "cancelled" || candidate.startedAt !== null, + ) + .at(-1)), + ), messages: data.messages.filter( (message) => options?.messageRunIds === undefined || @@ -464,7 +514,7 @@ describe("IdleCompactionService", () => { yield* Deferred.await(streamDone); yield* TestClock.adjust(9 * MINUTE_MS); }).pipe(Effect.provide(dependencies)); - expect(dispatched).toEqual(["server:idle-compact:idle-thread:run-2"]); + expect(dispatched).toEqual([`server:idle-compact:idle-thread:run-${resumed ? 1 : 2}`]); }), ); }); diff --git a/apps/server/src/orchestration-v2/IdleCompaction.ts b/apps/server/src/orchestration-v2/IdleCompaction.ts index ea14b3cadf..8fa81c75fe 100644 --- a/apps/server/src/orchestration-v2/IdleCompaction.ts +++ b/apps/server/src/orchestration-v2/IdleCompaction.ts @@ -2,6 +2,7 @@ import { isListedThreadLineage, type OrchestrationV2ThreadProjection } from "@on import { compactionSinceUsage } from "@onicode/provider-core/server/handoffBudget"; import { COMPACTION_SUGGESTION_MIN_TOKENS } from "@onicode/shared/claudeCompaction"; import { derivePendingBackgroundWork } from "@onicode/shared/orchestrationV2PendingBackgroundWork"; +import { latestExecutedRun } from "@onicode/shared/orchestrationV2ThreadError"; import * as DateTime from "effect/DateTime"; // Claude Code's idleCompaction defaults to 200K and won't go below 100K. Below @@ -52,13 +53,9 @@ export function idleCompactionWindow( if (thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs) return null; if (!isListedThreadLineage(thread.lineage)) return null; - // A removed or steered queued message leaves a cancelled run that never started. - const latestRun = runs - .filter((run) => run.status !== "cancelled" || run.startedAt !== null) - .reduce<(typeof runs)[number] | null>( - (latest, run) => (latest === null || run.ordinal > latest.ordinal ? run : latest), - null, - ); + // A queued message is the user's next turn; compacting first would delay it. + if (runs.some((run) => run.status === "queued")) return null; + const latestRun = latestExecutedRun(runs); if (latestRun?.status !== "completed" || latestRun.completedAt === null) return null; const message = messages.find((candidate) => candidate.id === latestRun.userMessageId); // Never compact a compaction, so one idle spell compacts at most once. diff --git a/apps/server/src/orchestration-v2/IdleCompactionService.ts b/apps/server/src/orchestration-v2/IdleCompactionService.ts index f983a51041..105d989d34 100644 --- a/apps/server/src/orchestration-v2/IdleCompactionService.ts +++ b/apps/server/src/orchestration-v2/IdleCompactionService.ts @@ -7,6 +7,7 @@ import { type RunId, type ThreadId, } from "@onicode/contracts"; +import { latestExecutedRun } from "@onicode/shared/orchestrationV2ThreadError"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -66,10 +67,10 @@ export const make = Effect.gen(function* () { { messageRunIds: [runId], turnItemStatuses: ["pending", "running", "waiting"], - // The latest run, active runs that hold background work, and rolled-back runs whose - // items it ignores. - runStatuses: ["preparing", "starting", "running", "rolled_back"], - includeLatestRun: true, + // The run that ran last, queued and active runs, and rolled-back runs whose items it + // ignores. + runStatuses: ["queued", "preparing", "starting", "running", "waiting", "rolled_back"], + includeLatestExecutedRun: true, // Without an active provider thread there is no session to compact. providerThreadIds: activeProviderThreadIds, providerTurnThreadIds: activeProviderThreadIds, @@ -88,12 +89,7 @@ export const make = Effect.gen(function* () { ) ) return; - const latestRun = records.runs - .filter((run) => run.status !== "cancelled" || run.startedAt !== null) - .reduce<(typeof records.runs)[number] | undefined>( - (latest, run) => (latest === undefined || run.ordinal > latest.ordinal ? run : latest), - undefined, - ); + const latestRun = latestExecutedRun(records.runs); // A late update for an earlier run replaced the latest run's timer, so take it over. if (latestRun?.status === "completed" && latestRun.id !== runId) { runId = latestRun.id; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 3fc0d14edd..f01ca90e20 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -5107,7 +5107,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio !runningRunExists && backgroundWorkHoldsCompletion( derivePendingBackgroundWork({ - latestRun: projection.runs.findLast((run) => run.status !== "queued"), + latestRun: latestExecutedRun(projection.runs), providerThreads: projection.providerThreads, turnItems: projection.turnItems.filter( (item) => item.type !== "subagent" || item.origin !== "app_owned", @@ -12443,6 +12443,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } } + // An answer by message sends its files in question order; a live answer already names every file. + const questionFiles = new Map(Object.entries(command.attachmentsByQuestionId ?? {})); + const messageFiles = + runtimeRequest.responseCapability.type === "message" && + approvalTurnItem?.type === "user_input_request" + ? approvalTurnItem.questions.flatMap((question) => { + const files = questionFiles.get(question.id); + return files === undefined ? [] : [[question.id, files] as const]; + }) + : undefined; + const now = yield* DateTime.now; const resolvedRequest = { ...runtimeRequest, @@ -12566,12 +12577,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio occurredAt: now, payload: { ...approvalTurnItem, - ...(approvalTurnItem.type === "user_input_request" && answers !== undefined + ...(approvalTurnItem.type === "user_input_request" && + (answers !== undefined || command.attachmentsByQuestionId !== undefined) ? { questionAnswer: { requestId: command.requestId, - answers, - attachmentsByQuestionId: command.attachmentsByQuestionId ?? {}, + answers: answers ?? {}, + attachmentsByQuestionId: + messageFiles === undefined + ? (command.attachmentsByQuestionId ?? {}) + : Object.fromEntries(messageFiles), questionTextById: Object.fromEntries( approvalTurnItem.questions.map((question) => [ question.id, @@ -12628,7 +12643,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, messageId: MessageId.make(`async-answer:${command.requestId}`), text: replies.join("\n\n"), - attachments: Object.values(command.attachmentsByQuestionId ?? {}).flat(), + attachments: (messageFiles ?? []).flatMap(([, files]) => files), createdBy: "user" as const, creationSource: "server" as const, dispatchMode, @@ -14073,11 +14088,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio "runs" | "nodes" | "subagents" | "turnItems" | "providerThreads" >; readonly stoppedProviderThreadId: OrchestrationV2ProviderThread["id"] | null; - readonly throughRunOrdinal: number; + readonly stoppedRun: OrchestrationV2Run; readonly now: DateTime.Utc; }) { const emitEvent = emit(input.events, input.command); - const runOrdinals = new Map(input.projection.runs.map((run) => [run.id, run.ordinal])); + const runsById = new Map(input.projection.runs.map((run) => [run.id, run])); const childThreadIds = new Set(); const liveness = new Map(); const hasLiveSession = Effect.fn("Orchestrator.hasLiveSession")(function* ( @@ -14118,8 +14133,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio turnItems: input.projection.turnItems, runs: input.projection.runs, })) { - const itemRunOrdinal = item.runId === null ? undefined : runOrdinals.get(item.runId); - if (itemRunOrdinal !== undefined && itemRunOrdinal > input.throughRunOrdinal) continue; + const run = item.runId === null ? undefined : runsById.get(item.runId); + if (run !== undefined && runRanAfter(run, input.stoppedRun)) continue; const providerThreadId = item.providerThreadId ?? null; if ( providerThreadId !== null && @@ -14128,7 +14143,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { continue; } - const run = input.projection.runs.find((candidate) => candidate.id === item.runId); yield* emitEvent({ type: "turn-item.updated", threadId: input.command.threadId, @@ -14185,6 +14199,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } else if (yield* hasLiveSession(providerThread.id)) { continue; } + const lastRun = input.projection.runs.find( + (run) => run.ordinal === providerThread.lastRunOrdinal, + ); yield* emitEvent({ type: "provider-thread.updated", threadId: input.command.threadId, @@ -14195,8 +14212,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...providerThread, status: providerThread.status === "active" && - providerThread.lastRunOrdinal !== null && - providerThread.lastRunOrdinal <= input.throughRunOrdinal + lastRun !== undefined && + !runRanAfter(lastRun, input.stoppedRun) ? "idle" : providerThread.status, pendingBackgroundTasks: [], @@ -14851,7 +14868,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio events, projection, stoppedProviderThreadId: command.providerThreadId, - throughRunOrdinal: stoppedRun.ordinal, + stoppedRun, now, }); }, @@ -15019,7 +15036,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? undefined : projection.providerThreads.find((candidate) => candidate.id === run?.providerThreadId); const hasBackgroundWork = - run?.id === projection.runs.findLast((candidate) => candidate.status !== "queued")?.id && + run?.id === latestExecutedRun(projection.runs)?.id && derivePendingBackgroundWork({ latestRun: run, providerThreads: projection.providerThreads, @@ -15102,17 +15119,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const otherProviderInterrupts: Array = []; if (hasBackgroundWork || command.holdQueue === true) { - const runOrdinals = new Map( - projection.runs.map((candidate) => [candidate.id, candidate.ordinal]), - ); - const runOrdinalOf = (item: (typeof projection.turnItems)[number]) => - item.runId === null ? -1 : (runOrdinals.get(item.runId) ?? -1); + const runsById = new Map(projection.runs.map((candidate) => [candidate.id, candidate])); // Interrupt each provider thread at its latest pending turn so settlement covers all its work. // Use the item's provider turn: native subagent items name the child thread but the parent turn, // and interrupting the parent turn reaches the subagent. const latestTurnByProviderThread = new Map< OrchestrationV2ProviderThread["id"], - { readonly turn: (typeof projection.providerTurns)[number]; readonly runOrdinal: number } + { + readonly turn: (typeof projection.providerTurns)[number]; + readonly owner: OrchestrationV2Run | undefined; + } >(); for (const item of pendingBackgroundTurnItems({ turnItems: projection.turnItems, @@ -15122,10 +15138,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio (candidate) => candidate.id === item.providerTurnId, ); if (turn === undefined || turn.providerThreadId === providerThread.id) continue; - const runOrdinal = runOrdinalOf(item); + const owner = item.runId === null ? undefined : runsById.get(item.runId); const latest = latestTurnByProviderThread.get(turn.providerThreadId); - if (latest === undefined || runOrdinal > latest.runOrdinal) { - latestTurnByProviderThread.set(turn.providerThreadId, { turn, runOrdinal }); + if ( + latest === undefined || + (owner !== undefined && (latest.owner === undefined || runRanAfter(owner, latest.owner))) + ) { + latestTurnByProviderThread.set(turn.providerThreadId, { turn, owner }); } } for (const { turn } of latestTurnByProviderThread.values()) { @@ -15343,7 +15362,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio events, projection, stoppedProviderThreadId: providerThread.id, - throughRunOrdinal: run.ordinal, + stoppedRun: run, now, }); yield* Ref.update(effects, (existing) => [...existing, ...otherProviderInterrupts]); @@ -15625,20 +15644,21 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) ? Effect.void : Ref.update(effects, (existing) => [...existing, delegatedTasksStopEffect(command)]); - const latestRun = projection.runs.findLast((run) => run.status !== "queued"); + const executed = latestExecutedRun(projection.runs); const target = projection.runs.findLast( (run) => run.status === "preparing" || run.status === "starting" || run.status === "running", ) ?? - (derivePendingBackgroundWork({ - latestRun, + (executed !== null && + derivePendingBackgroundWork({ + latestRun: executed, providerThreads: projection.providerThreads, turnItems: projection.turnItems, activeProviderThreadId: projection.thread.activeProviderThreadId, runs: projection.runs, }).length > 0 - ? latestRun + ? executed : undefined); if (target !== undefined) { const interruptEvents = yield* Ref.make>([]); @@ -15676,7 +15696,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const now = yield* DateTime.now; // Record that Stop reached the turn it could not interrupt and the thread's last executed // run, so a late tool call from their agent starts nothing. - const executed = latestExecutedRun(projection.runs); const reached = new Map(); if (target !== undefined) reached.set(target.id, target); if (executed !== null && !hasLiveRun({ runs: [executed] })) reached.set(executed.id, executed); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index a496d1bd5a..974b749fff 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -8020,7 +8020,8 @@ export const layer: Layer.Layer = findCursorEndIndex(indexed, decodeThreadHistoryCursor(cursor)), indexed.length - 1, ); - while (workMode !== undefined) { + while (true) { + if (workMode === undefined) break; const { page } = selection; const span = [...page.items.slice(0, 1), ...page.items.slice(-1)].map( (row) => row.canonicalPosition, diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index fd4ed10339..ed6c117a8f 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -557,6 +557,8 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* const capabilitiesGate = { entered: Effect.void as Effect.Effect }; // Pauses a steer that changes the selection after it read the target run, holding the lock. const selectionGate = { entered: Effect.void as Effect.Effect }; + // Pauses an automatic promotion that chose its steers, before it asks for the thread's lock. + const stopReadGate = { entered: Effect.void as Effect.Effect }; const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = { instanceId, driver, @@ -694,6 +696,10 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* store .getProviderControlContext(threadId, target) .pipe(Effect.tap(() => Effect.suspend(afterSteerTargetRead))), + hasRunInterruptRequest: (threadId, runId) => + store + .hasRunInterruptRequest(threadId, runId) + .pipe(Effect.tap(() => Effect.suspend(() => stopReadGate.entered))), }), }, ); @@ -752,6 +758,7 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* startFirstTurn, capabilitiesGate, selectionGate, + stopReadGate, }; }); @@ -2382,95 +2389,102 @@ it.effect("releases a steer whose hold was written after its turn left it", () = }), ); -it.effect("starts the queue when Resume lands before a held steer is released", () => - Effect.gen(function* () { - const { layer, startFirstTurn, started } = yield* nextTurnSelectionHarness( - "resume-before-steer-release", - false, - true, - Effect.void, - true, - undefined, - undefined, - [], - false, - ); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const sink = yield* EventSink.EventSinkV2; - const locks = yield* ThreadCommandExecutor.ThreadCommandExecutor; - const threadId = yield* startFirstTurn; - yield* writeCompaction(threadId, "running"); - const target = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make("steer"), - threadId, - messageId: MessageId.make("message:steered"), - text: "steered", - attachments: [], - dispatchMode: { type: "steer_active", targetRunId: target.id }, - createdBy: "user", - creationSource: "web", - }); - const held = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!; - assert.equal(held.steerWhenReadyRunId, target.id); - - // Holding the thread's lock puts the release's read first and Resume ahead of its command. - const locked = yield* Deferred.make(); - const unlock = yield* Deferred.make(); - const holder = yield* locks - .withLock( - threadId, - Deferred.succeed(locked, undefined).pipe(Effect.andThen(Deferred.await(unlock))), - ) - .pipe(Effect.forkChild); - yield* Deferred.await(locked); - const now = yield* DateTime.now; - // Recovery stopped the turn and held what was queued behind it. - yield* sink.write({ - commandId: CommandId.make("command:runtime-reconcile:resume-before-steer-release"), - events: [ - { - id: EventId.make("recovery-holds-steer"), - type: "run.updated", - threadId, - runId: held.id, - occurredAt: now, - payload: { ...held, queueHeld: true }, - }, - { - id: EventId.make("recovery-cancels-target"), - type: "run.updated", - threadId, - runId: target.id, - occurredAt: now, - payload: { ...target, status: "cancelled", completedAt: now }, - }, - ], - }); - yield* orchestrator.recoverDelegatedTasks; - const resume = yield* orchestrator - .dispatch({ type: "queue.resume", commandId: CommandId.make("resume"), threadId }) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.succeed(unlock, undefined); - yield* Fiber.join(holder); - const resumed = yield* Fiber.join(resume); - yield* sink.stream({ afterSequence: resumed.sequence, eventType: "run.updated" }).pipe( - Stream.filter( - (stored) => - stored.event.type === "run.updated" && - stored.event.runId === held.id && - stored.event.payload.status !== "queued", - ), - Stream.take(1), - Stream.runDrain, +it.effect.each(["released", "refused"] as const)( + "starts the queue when Resume lands before a held steer is %s", + (ending) => + Effect.gen(function* () { + const { layer, startFirstTurn, started, stopReadGate } = yield* nextTurnSelectionHarness( + `resume-before-steer-${ending}`, + false, + true, + Effect.void, + true, + undefined, + undefined, + [], + false, ); - yield* worker.drain(); - assert.equal(started.at(-1)?.runId, held.id); - }).pipe(Effect.provide(layer)); - }), + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const sink = yield* EventSink.EventSinkV2; + const locks = yield* ThreadCommandExecutor.ThreadCommandExecutor; + const threadId = yield* startFirstTurn; + yield* writeCompaction(threadId, "running"); + const target = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("steer"), + threadId, + messageId: MessageId.make("message:steered"), + text: "steered", + attachments: [], + dispatchMode: { type: "steer_active", targetRunId: target.id }, + createdBy: "user", + creationSource: "web", + }); + const held = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!; + assert.equal(held.steerWhenReadyRunId, target.id); + + const paused = yield* Deferred.make(); + const proceed = yield* Deferred.make(); + const pause = Deferred.succeed(paused, undefined).pipe( + Effect.andThen(Deferred.await(proceed)), + ); + if (ending === "released") { + // Holding the thread's lock puts the release's read first and Resume ahead of its command. + yield* locks.withLock(threadId, pause).pipe(Effect.forkChild); + } else { + // The turn can take the steer now, but ends before the promotion reaches it. + stopReadGate.entered = pause; + yield* writeCompaction(threadId, "completed"); + } + yield* Deferred.await(paused); + stopReadGate.entered = Effect.void; + const now = yield* DateTime.now; + // Recovery stopped the turn and held what was queued behind it. + yield* sink.write({ + commandId: CommandId.make(`command:runtime-reconcile:resume-before-steer-${ending}`), + events: [ + { + id: EventId.make("recovery-holds-steer"), + type: "run.updated", + threadId, + runId: held.id, + occurredAt: now, + payload: { ...held, queueHeld: true }, + }, + { + id: EventId.make("recovery-cancels-target"), + type: "run.updated", + threadId, + runId: target.id, + occurredAt: now, + payload: { ...target, status: "cancelled", completedAt: now }, + }, + ], + }); + yield* orchestrator.recoverDelegatedTasks; + const resume = yield* orchestrator + .dispatch({ type: "queue.resume", commandId: CommandId.make("resume"), threadId }) + .pipe(Effect.forkChild({ startImmediately: true })); + if (ending === "refused") yield* Fiber.await(resume); + yield* Deferred.succeed(proceed, undefined); + const resumed = yield* Fiber.join(resume); + yield* sink.stream({ afterSequence: resumed.sequence, eventType: "run.updated" }).pipe( + Stream.filter( + (stored) => + stored.event.type === "run.updated" && + stored.event.runId === held.id && + stored.event.payload.status !== "queued", + ), + Stream.take(1), + Stream.runDrain, + ); + yield* worker.drain(); + assert.equal(started.at(-1)?.runId, held.id); + }).pipe(Effect.provide(layer)); + }), ); it.effect("resumes a stopped queue for a steer that missed a completed turn", () => diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index 333e827d02..e949772504 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -1552,13 +1552,20 @@ it.effect.each([ activeAttemptId: "attempt", providerThreadId, }, - // A queued follow-up neither supersedes the request nor becomes the target. + // A follow-up that never ran neither supersedes the request nor becomes the target. { id: RunId.make("run:queued-follow-up"), ordinal: 2, status: "queued", providerThreadId, }, + { + id: RunId.make("run:steered-follow-up"), + ordinal: 3, + status: "cancelled", + startedAt: null, + providerThreadId, + }, ], providerThreads: [ { id: providerThreadId, appThreadId: threadId, providerSessionId }, diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 53fc5142df..d752c587cc 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1663,17 +1663,9 @@ const make = Effect.gen(function* () { "providerThreads", "providerTurns", ]); - // The run Force stop acts on: the active one, else the latest that started. Queued - // follow-ups never ran, so they neither count as targets nor supersede the request. - const target = - latestActiveRun(records) ?? - records.runs - .filter((run) => run.status !== "queued") - .reduce( - (current, run) => - current === undefined || run.ordinal > current.ordinal ? run : current, - undefined, - ); + // The run Force stop acts on: the active one, else the last that ran, as Stop picks it. + // Messages that never ran neither count as targets nor supersede the request. + const target = latestActiveRun(records) ?? latestExecutedRun(records.runs) ?? undefined; if (input.runId !== undefined && input.runId !== target?.id) { return yield* new OrchestrationV2ForceStopThreadError({ threadId: input.threadId, @@ -1897,7 +1889,6 @@ const make = Effect.gen(function* () { child: ProjectionRecords<"runs" | "providerThreads" | "turnItems" | "subagents">, ) { if (child.thread.deletedAt !== null) return false; - const latestRun = child.runs.findLast((run) => run.status !== "queued"); // Held queues resume out of ordinal order; limit recovery follows the run that ended last. const executed = latestExecutedRun(child.runs); const hasStoppableRun = child.runs.some( @@ -1930,7 +1921,7 @@ const make = Effect.gen(function* () { child.thread.limitRecovery?.autoResume === true || (child.thread.pullRequests ?? []).some((link) => link.watch !== undefined) || derivePendingBackgroundWork({ - latestRun, + latestRun: executed, providerThreads: child.providerThreads, turnItems: child.turnItems, activeProviderThreadId: child.thread.activeProviderThreadId, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 2ea8206b87..74325b19ff 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -2772,13 +2772,16 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { }), ); - it.effect("sends an async answer's files as attachments on the answer message", () => + it.effect.each([ + { name: "typed", answers: { color: "", sizes: ["Small"], note: "" }, files: ["color"] }, + { name: "files-only", answers: undefined, files: ["unknown", "sizes", "color"] }, + ])("sends an async answer's files as attachments on the answer message ($name)", (row) => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; - const threadId = ThreadId.make("runtime-async-question-files"); + const threadId = ThreadId.make(`runtime-async-question-files-${row.name}`); yield* orchestrator.dispatch({ type: "thread.create", - commandId: CommandId.make("runtime-async-question-files-create"), + commandId: CommandId.make(`runtime-async-question-files-create-${row.name}`), createdBy: "user", creationSource: "web", threadId, @@ -2790,26 +2793,46 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { branch: null, worktreePath: process.cwd(), }); - const { requestId } = yield* seedPendingQuestion(threadId, null, { type: "message" }); - const screenshot = { + const { requestId, itemId } = yield* seedPendingQuestion(threadId, null, { + type: "message", + }); + const fileFor = (questionId: string) => ({ type: "image" as const, id: createAttachmentId(threadId)!, - name: "screen.png", + name: `${questionId}.png`, mimeType: "image/png", sizeBytes: 3, - }; + }); yield* orchestrator.dispatch({ type: "runtime-request.respond", - commandId: CommandId.make("runtime-async-question-files-answer"), + commandId: CommandId.make(`runtime-async-question-files-answer-${row.name}`), threadId, requestId, - answers: { color: "", sizes: ["Small"], note: "" }, - attachmentsByQuestionId: { color: [screenshot] }, + ...(row.answers === undefined ? {} : { answers: row.answers }), + attachmentsByQuestionId: Object.fromEntries( + row.files.map((questionId) => [questionId, [fileFor(questionId)]]), + ), }); const answered = yield* orchestrator.getThreadProjection(threadId); assert.equal(answered.messages.length, 1); - assert.equal(answered.messages[0]?.text, "Which color?\n\nWhich sizes?\nSmall"); - assert.deepEqual(answered.messages[0]?.attachments, [screenshot]); + assert.equal( + answered.messages[0]?.text, + `Which color?\n\nWhich sizes?${row.answers === undefined ? "" : "\nSmall"}`, + ); + const asked = ["color", "sizes"].filter((questionId) => row.files.includes(questionId)); + assert.deepEqual( + answered.messages[0]?.attachments?.map((file) => file.name), + asked.map((questionId) => `${questionId}.png`), + ); + const answeredItem = answered.turnItems.find((item) => item.id === itemId); + assert.equal(answeredItem?.type, "user_input_request"); + if (answeredItem?.type === "user_input_request") { + assert.deepEqual(answeredItem.questionAnswer?.answers, row.answers ?? {}); + assert.sameMembers( + Object.keys(answeredItem.questionAnswer?.attachmentsByQuestionId ?? {}), + asked, + ); + } }), ); @@ -8659,133 +8682,162 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }, { name: "an unmarked background command", work: "command" as const, settles: true }, { name: "a task delegated to another thread", work: "delegated" as const, settles: true }, - ])("settling a completed turn that left $name running settles: $settles", ({ work, settles }) => - Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const eventSink = yield* EventSink.EventSinkV2; - const threadId = ThreadId.make(`runtime-layer-settle-background-${work}`); + { + name: "a native subagent, resumed after a later run rolled back,", + work: "subagent" as const, + settles: false, + rolledBackLater: true, + }, + ])( + "settling a completed turn that left $name running settles: $settles", + ({ work, settles, rolledBackLater }) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make( + `runtime-layer-settle-background-${work}${rolledBackLater === true ? "-rolled-back" : ""}`, + ); - yield* orchestrator.dispatch({ - type: "thread.create", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make(`${threadId}:create`), - threadId, - projectId: ProjectId.make(`${threadId}:project`), - title: "Settle with background work", - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: `/tmp/${threadId}`, - }); - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make(`${threadId}:message`), - threadId, - messageId: MessageId.make(`${threadId}:message`), - text: "Start the work in the background.", - attachments: [], - modelSelection, - dispatchMode: { type: "start_immediately" }, - }); - const before = yield* orchestrator.getThreadProjection(threadId); - const run = before.runs[0]; - const providerThread = before.providerThreads[0]; - if (run === undefined || providerThread === undefined) { - return yield* Effect.die(new Error("Run or provider thread missing.")); - } - const now = yield* DateTime.now; - const subagentItem = (origin: "provider_native" | "app_owned") => ({ - id: EventId.make(`${threadId}:subagent`), - type: "turn-item.updated" as const, - threadId, - runId: run.id, - ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }), - providerInstanceId: run.providerInstanceId, - occurredAt: now, - payload: { - id: TurnItemId.make(`${threadId}:subagent`), - type: "subagent" as const, + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: ProjectId.make(`${threadId}:project`), + title: "Settle with background work", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: `/tmp/${threadId}`, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${threadId}:message`), + threadId, + messageId: MessageId.make(`${threadId}:message`), + text: "Start the work in the background.", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + const before = yield* orchestrator.getThreadProjection(threadId); + const run = before.runs[0]; + const providerThread = before.providerThreads[0]; + if (run === undefined || providerThread === undefined) { + return yield* Effect.die(new Error("Run or provider thread missing.")); + } + const now = yield* DateTime.now; + const subagentItem = (origin: "provider_native" | "app_owned") => ({ + id: EventId.make(`${threadId}:subagent`), + type: "turn-item.updated" as const, threadId, runId: run.id, - nodeId: run.rootNodeId, - providerThreadId: providerThread.id, - providerTurnId: null, - nativeItemRef: null, - parentItemId: null, - ordinal: 2, - status: "running" as const, - title: "Review", - startedAt: now, - completedAt: null, - updatedAt: now, - subagentId: NodeId.make(`${threadId}:subagent`), - origin, - driver: providerThread.driver, - providerInstanceId: providerThread.providerInstanceId, - childThreadId: origin === "app_owned" ? ThreadId.make(`${threadId}:child`) : null, - prompt: "Review the change", - result: null, - }, - }); - const roster = (awaited: boolean) => ({ - id: EventId.make(`${threadId}:roster`), - type: "provider-thread.updated" as const, - threadId, - occurredAt: now, - payload: { - ...providerThread, - updatedAt: now, - pendingBackgroundTasks: [ - { - taskId: "background-command", - kind: "command" as const, - ...(awaited ? { awaited: true as const } : {}), - }, - ], - }, - }); - yield* eventSink.write({ - events: [ - work === "subagent" - ? subagentItem("provider_native") - : work === "delegated" - ? subagentItem("app_owned") - : roster(work === "awaited-command"), - { - id: EventId.make(`${threadId}:completed`), - type: "run.updated", + ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }), + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { + id: TurnItemId.make(`${threadId}:subagent`), + type: "subagent" as const, threadId, runId: run.id, - occurredAt: now, - payload: { ...run, status: "completed", startedAt: now, completedAt: now }, + nodeId: run.rootNodeId, + providerThreadId: providerThread.id, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "running" as const, + title: "Review", + startedAt: now, + completedAt: null, + updatedAt: now, + subagentId: NodeId.make(`${threadId}:subagent`), + origin, + driver: providerThread.driver, + providerInstanceId: providerThread.providerInstanceId, + childThreadId: origin === "app_owned" ? ThreadId.make(`${threadId}:child`) : null, + prompt: "Review the change", + result: null, }, - ], - }); + }); + const roster = (awaited: boolean) => ({ + id: EventId.make(`${threadId}:roster`), + type: "provider-thread.updated" as const, + threadId, + occurredAt: now, + payload: { + ...providerThread, + updatedAt: now, + pendingBackgroundTasks: [ + { + taskId: "background-command", + kind: "command" as const, + ...(awaited ? { awaited: true as const } : {}), + }, + ], + }, + }); + yield* eventSink.write({ + events: [ + work === "subagent" + ? subagentItem("provider_native") + : work === "delegated" + ? subagentItem("app_owned") + : roster(work === "awaited-command"), + { + id: EventId.make(`${threadId}:completed`), + type: "run.updated", + threadId, + runId: run.id, + occurredAt: now, + payload: { ...run, status: "completed", startedAt: now, completedAt: now }, + }, + ...(rolledBackLater === true + ? [ + { + id: EventId.make(`${threadId}:rolled-back`), + type: "run.updated" as const, + threadId, + runId: RunId.make(`${threadId}:rolled-back`), + occurredAt: now, + payload: { + ...run, + id: RunId.make(`${threadId}:rolled-back`), + ordinal: run.ordinal + 1, + status: "rolled_back" as const, + startedAt: DateTime.subtract(now, { seconds: 2 }), + completedAt: DateTime.subtract(now, { seconds: 1 }), + }, + }, + ] + : []), + ], + }); - const settle = orchestrator.dispatch({ - type: "thread.settle", - commandId: CommandId.make(`${threadId}:settle`), - threadId, - }); - if (settles) { - yield* settle; + const settle = orchestrator.dispatch({ + type: "thread.settle", + commandId: CommandId.make(`${threadId}:settle`), + threadId, + }); + if (settles) { + yield* settle; + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.equal(projection.thread.settledOverride, "settled"); + return; + } + const error = yield* settle.pipe(Effect.flip); + assert.equal(error._tag, "OrchestratorDispatchError"); + assert.equal( + error.cause, + `Thread ${threadId} is still running background agents or commands, and settling would end them. Wait for them to finish, or press Stop, then settle.`, + ); const projection = yield* orchestrator.getThreadProjection(threadId); - assert.equal(projection.thread.settledOverride, "settled"); - return; - } - const error = yield* settle.pipe(Effect.flip); - assert.equal(error._tag, "OrchestratorDispatchError"); - assert.equal( - error.cause, - `Thread ${threadId} is still running background agents or commands, and settling would end them. Wait for them to finish, or press Stop, then settle.`, - ); - const projection = yield* orchestrator.getThreadProjection(threadId); - assert.isNull(projection.thread.settledOverride); - }), + assert.isNull(projection.thread.settledOverride); + }), ); it.effect("settles past held automatic messages but preserves a held user queue", () => diff --git a/apps/server/src/project/ProjectFaviconResolver.test.ts b/apps/server/src/project/ProjectFaviconResolver.test.ts index be0ca405a3..da2f189da4 100644 --- a/apps/server/src/project/ProjectFaviconResolver.test.ts +++ b/apps/server/src/project/ProjectFaviconResolver.test.ts @@ -4,6 +4,7 @@ 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 { TestClock } from "effect/testing"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; @@ -357,6 +358,44 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { }), ); + it.effect.each(["ENAMETOOLONG", "EINVAL"])( + "tries the next icon link when the filesystem rejects a declared one's name (%s)", + (code) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* makeTempDir; + yield* writeTextFile( + cwd, + "app/root.tsx", + `export const links = () => [ + { rel: "icon", href: "<%= BASE_URL %>favicon.ico" }, + { rel: "icon", href: "/brand.svg" }, +];`, + ); + yield* writeTextFile(cwd, "brand.svg", "brand"); + const resolver = yield* makeResolverWithFileSystem( + FileSystem.FileSystem.of({ + ...fileSystem, + stat: (filePath) => + filePath.includes("<%=") + ? Effect.fail( + PlatformError.systemError({ + _tag: "Unknown", + module: "FileSystem", + method: "stat", + pathOrDescriptor: filePath, + cause: Object.assign(new Error(code), { code }), + }), + ) + : fileSystem.stat(filePath), + }), + ); + + expect(yield* resolver.resolvePath(cwd)).toBe(path.join(cwd, "brand.svg")); + }), + ); + it.effect("skips icon metadata paths outside the workspace", () => Effect.gen(function* () { const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; diff --git a/apps/server/src/project/ProjectFaviconResolver.ts b/apps/server/src/project/ProjectFaviconResolver.ts index 3896625396..deeeab19f2 100644 --- a/apps/server/src/project/ProjectFaviconResolver.ts +++ b/apps/server/src/project/ProjectFaviconResolver.ts @@ -165,13 +165,19 @@ export const optionOnNotFound = ( }), ); -// A path through a file (ENOTDIR) or a symlink loop names no file either. +// Codes Node maps to no specific reason: an over-long name, or characters Windows rejects. +const INVALID_PATH_CODES = new Set(["ENAMETOOLONG", "EINVAL"]); + +// A path through a file (ENOTDIR), a symlink loop, or a name no filesystem takes names no file either. const optionOnMissing = ( effect: Effect.Effect, ): Effect.Effect, PlatformError.PlatformError, R> => optionOnNotFound(effect).pipe( Effect.catchIf( - (error) => error.reason._tag === "BadResource", + (error) => + error.reason._tag === "BadResource" || + (error.reason._tag === "Unknown" && + INVALID_PATH_CODES.has((error.reason.cause as { readonly code?: unknown })?.code)), () => Effect.succeedNone, ), ); diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index d2f82bfd6b..e7cf0898a7 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -1,3 +1,4 @@ +import { isHeadSha } from "@onicode/shared/git"; import { isSshRemoteUrl } from "@onicode/shared/sourceControl"; import { parseDiffFilePaths } from "@onicode/source-control-core/server/diffFileRevisions"; import * as Cache from "effect/Cache"; @@ -773,12 +774,6 @@ function httpRemoteHost(remoteUrl: string): string | null { } } -/** Whether `expected` names `head`: the full SHA, or a hex prefix of at least 7 characters. */ -export const isHeadSha = (head: string, expected: string) => { - const wanted = expected.toLowerCase(); - return /^[0-9a-f]{7,}$/.test(wanted) ? head.toLowerCase().startsWith(wanted) : head === expected; -}; - // Capture before the provider read so a slow response keeps its original freshness through caches. const observeRead = Effect.fnUntraced(function* (read: Effect.Effect) { const observedAt = yield* Clock.currentTimeMillis; diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts index 13c995e452..10fbad9521 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts @@ -76,6 +76,8 @@ function withFakeClaudeEnv( cwdMustNotBe?: string; settingsLog?: string; claudeConfig?: Partial; + environment?: NodeJS.ProcessEnv; + routeModelCatalog?: Parameters[3]; }, effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect, ) { @@ -114,6 +116,7 @@ function withFakeClaudeEnv( ...Object.fromEntries( Object.entries(fakeClaudeEnv).filter(([, value]) => value !== undefined), ), + ...input.environment, PATH: `${binDir}${pathDelimiter}${hostEnv.PATH ?? ""}`, }; @@ -122,6 +125,7 @@ function withFakeClaudeEnv( config, environment, Effect.succeed(SYNTHETIC_CLAUDE_MODEL_CATALOG), + input.routeModelCatalog, ); return yield* effectFn(textGeneration); }).pipe(Effect.scoped); @@ -152,19 +156,32 @@ it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => { [project, "project"], [checkout, "checkout"], ] as const) { - yield* fs.makeDirectory(directory); + yield* fs.makeDirectory(path.join(directory, ".claude-home"), { recursive: true }); yield* fs.writeFileString( path.join(directory, "claude.json"), JSON.stringify({ env: { ORIGIN: origin } }), ); + // A pull request can carry a settings file where a relative config dir points. + yield* fs.writeFileString( + path.join(directory, ".claude-home", "settings.json"), + JSON.stringify({ env: { USER_SETTINGS: origin } }), + ); } const settingsLog = path.join(root, "settings.json"); + const routedFrom: Array = []; yield* withFakeClaudeEnv( { output: JSON.stringify({ structured_output: { stops: [] } }), expectedTools: "Read,Grep,Glob,Bash", settingsLog, - claudeConfig: { homePath: path.join(root, "home"), launchArgs: "--settings claude.json" }, + claudeConfig: { launchArgs: "--settings claude.json" }, + environment: { CLAUDE_CONFIG_DIR: ".claude-home" }, + configDirMustBe: path.join(project, ".claude-home"), + routeModelCatalog: (catalog, cwd) => + Effect.sync(() => { + routedFrom.push(cwd); + return catalog; + }), }, (textGeneration) => textGeneration.generateReviewGuide({ @@ -174,9 +191,10 @@ it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => { }), ); expect(JSON.parse(yield* fs.readFileString(settingsLog))).toEqual({ - env: { ORIGIN: "project" }, + env: { USER_SETTINGS: "project", ORIGIN: "project" }, disableAllHooks: true, }); + expect(routedFrom).toEqual([project]); }), ); diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts index 56619cb375..e4176f8105 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts @@ -272,7 +272,14 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu ), ) : cwd; - const catalog = yield* routeModelCatalog(yield* scopedModelCatalog, workingDirectory); + // The investigated checkout holds the change under review, not the user's files. + const settingsCwd = investigate?.projectCwd ?? workingDirectory; + const configDir = claudeEnvironment.CLAUDE_CONFIG_DIR?.trim(); + // The CLI would resolve a relative config dir in the folder it runs in. + const runEnvironment = configDir + ? { ...claudeEnvironment, CLAUDE_CONFIG_DIR: path.resolve(settingsCwd, configDir) } + : claudeEnvironment; + const catalog = yield* routeModelCatalog(yield* scopedModelCatalog, settingsCwd); const resolvedModelSelection = { ...modelSelection, model: resolveClaudeModelSlug(catalog, modelSelection.model), @@ -311,7 +318,6 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined; const launchArgSettings = yield* readClaudeLaunchArgSettings({ settings: claudeSettings, - // The investigated checkout holds the change under review, not the user's files. cwd: investigate?.projectCwd ?? cwd, fileSystem, path, @@ -323,7 +329,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu const settings = { ...(investigate ? investigationSettings( - yield* readClaudeUserSettings(claudeSettings, workingDirectory, claudeEnvironment).pipe( + yield* readClaudeUserSettings(claudeSettings, settingsCwd, runEnvironment).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), ), @@ -354,7 +360,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu // `claude -p` accepts images only as content blocks of a stream-json user message. const apiModelId = resolveClaudeCatalogApiModelId(catalog, resolvedModelSelection); - const textOnlyKey = `${workingDirectory}\n${apiModelId}`; + const textOnlyKey = `${settingsCwd}\n${apiModelId}`; const imageBlocks = textOnlyModels.has(textOnlyKey) ? [] : yield* readImageBlocks(attachments, prompt); @@ -409,10 +415,10 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu "--permission-mode", "dontAsk", ], - { env: claudeEnvironment }, + { env: runEnvironment }, ); const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, { - env: claudeEnvironment, + env: runEnvironment, cwd: workingDirectory, shell: spawnCommand.shell, stdin: { diff --git a/apps/server/src/workflows/WorkflowAgentLinks.test.ts b/apps/server/src/workflows/WorkflowAgentLinks.test.ts index c2832d900c..30b75e0159 100644 --- a/apps/server/src/workflows/WorkflowAgentLinks.test.ts +++ b/apps/server/src/workflows/WorkflowAgentLinks.test.ts @@ -1,4 +1,4 @@ -import { EnvironmentId, OrchestratorMcpFailure } from "@onicode/contracts"; +import { EnvironmentId, OrchestratorMcpFailure, type RuntimeMode } from "@onicode/contracts"; import { assert, it } from "@effect/vitest"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -8,6 +8,7 @@ import * as TestClock from "effect/testing/TestClock"; import * as PeerLinks from "../peer/PeerLinks.ts"; import * as PeerMcpClient from "../peer/PeerMcpClient.ts"; +import * as ServerSettings from "../serverSettings.ts"; import * as WorkflowAgentLinks from "./WorkflowAgentLinks.ts"; const isFailure = Schema.is(OrchestratorMcpFailure); @@ -20,10 +21,14 @@ interface Call { } /** The other environment, played by the test: each tool answers from a list, in order. */ -const peer = (answers: Record>, enabled = true) => { +const peer = ( + answers: Record>, + enabled = true, + maxRuntimeMode?: RuntimeMode, +) => { const calls: Array = []; const left = new Map(Object.entries(answers).map(([tool, list]) => [tool, [...list]])); - const layer = Layer.merge( + const layer = Layer.mergeAll( Layer.succeed( PeerMcpClient.PeerMcpClient, PeerMcpClient.PeerMcpClient.of({ @@ -41,6 +46,12 @@ const peer = (answers: Record>, enabled = true) = }), ), Layer.mock(PeerLinks.PeerLinks)({ enabled: Effect.succeed(enabled) }), + Layer.mock(ServerSettings.ServerSettingsService)({ + managedPolicy: + maxRuntimeMode === undefined + ? undefined + : { organization: "Example Corp", lockedSettings: [], limits: { maxRuntimeMode } }, + }), ); return { calls, layer }; }; @@ -109,6 +120,25 @@ it.effect("starts a thread there by the project's folder, with the step's key as }); // The link's own access is the ceiling, not a mode narrower than it. assert.equal(launch?.runtimeMode, "full-access"); + + // An administrator's ceiling here holds over a full-access link too. + const capped = peer( + { + oni_project_list: [ + { projects: [{ id: "p-app", workspaceRoot: "/work/app" }], nextCursor: null }, + ], + oni_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }], + }, + true, + "auto", + ); + yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.start(input, "env-b", "workflow:k", EnvironmentId.make("env-a")), + ), + capped.layer, + ); + assert.equal(capped.calls.at(-1)?.runtimeMode, "auto"); }), ); diff --git a/apps/server/src/workflows/WorkflowAgentLinks.ts b/apps/server/src/workflows/WorkflowAgentLinks.ts index 0d16be5fbc..e002f48d00 100644 --- a/apps/server/src/workflows/WorkflowAgentLinks.ts +++ b/apps/server/src/workflows/WorkflowAgentLinks.ts @@ -22,6 +22,7 @@ import type * as Schema from "effect/Schema"; import { ProjectToolkit } from "../mcp/toolkits/project/tools.ts"; import * as PeerLinks from "../peer/PeerLinks.ts"; import * as PeerMcpClient from "../peer/PeerMcpClient.ts"; +import * as ServerSettings from "../serverSettings.ts"; import { type AgentResult, type AgentTurn, @@ -31,10 +32,6 @@ import { type WorkflowAgents, } from "./WorkflowAgents.ts"; -// A run acts for whoever owns this environment, not for an agent with modes of its own, so the -// only ceiling on what it starts there is the access the link was paired with. -const LIMITS = { runtimeMode: "full-access", interactionMode: "default" } as const; - // A proxy on the route may drop a request idle for about 100 s, so a wait goes out in pieces, // no longer than the 45 s a peer waits at most. const WAIT_PIECE = Duration.seconds(45); @@ -61,6 +58,13 @@ type Service = WorkflowAgents["Service"]; export const make = Effect.gen(function* () { const peers = yield* PeerMcpClient.PeerMcpClient; const links = yield* PeerLinks.PeerLinks; + const settings = yield* ServerSettings.ServerSettingsService; + // A run acts for whoever owns this environment, not for an agent with modes of its own, so it is + // held to the link's access and to the administrator's ceiling here, as its steps here are. + const limits = { + runtimeMode: settings.managedPolicy?.limits?.maxRuntimeMode ?? "full-access", + interactionMode: "default", + } as const; const ask = >( environment: string, @@ -73,7 +77,7 @@ export const make = Effect.gen(function* () { environmentId: environment as EnvironmentId, tool, arguments: args, - limits: LIMITS, + limits, success, }) .pipe(Effect.retry({ ...retried, while: (error) => !isFinal(error) })); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index a64103ddfd..2bc65ba96d 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -523,7 +523,7 @@ function maxIsoTimestamp(a: string | null, b: string | null): string | null { export type TimelineLatestRun = Pick< ThreadRunSummary, - "runId" | "status" | "startedAt" | "completedAt" | "turnEnded" + "runId" | "status" | "startedAt" | "completedAt" | "turnEnded" | "awaitedEarlierSubagents" >; const LIVE_ACTIVITY_ROW_ID = "live-activity-row"; @@ -2429,6 +2429,9 @@ export function deriveMessagesTimelineRows( unsettledRunId, timelineEntryTurnItems, input.toolCallVisibility !== "zen", + input.latestRun?.runId === unsettledRunId + ? (input.latestRun.awaitedEarlierSubagents ?? 0) + : 0, ); nextRows.push({ kind: "thinking", diff --git a/evals/mcp-tool-use/README.md b/evals/mcp-tool-use/README.md index 85fb9dcfe7..b34830fd75 100644 --- a/evals/mcp-tool-use/README.md +++ b/evals/mcp-tool-use/README.md @@ -360,7 +360,7 @@ pnpm mcp-tool-use:compare runs/tools/results.jsonl runs/raw/results.jsonl `compare` regrades every row with this checkout's cases and prints, per case and arm: pass rate, model calls, forge calls (Onicode forge tools plus `gh`/`cafe`/`glab`/`src` commands), failed forge calls, forge output in KB, requested sleep, `--help` calls, tokens and cost. Cost charges cache writes as cache reads, so the order the runs went in doesn't decide which arm looks cheaper. -Both arms see the same world. Shell mocks apply to either arm's commands, so an agent in the tools arm that reaches for `gh` hits the same rate limit. Where the real tools refuse, the tools arm is refused too: `pull_request_merge` and `pull_request_review` compare `expectedHeadSha` with the full head, as `PullRequestService` does, and an approval without one is refused. A `{"$error": "..."}` mock fails any Onicode tool with that text. `expectRaw` grades the raw arm when its right outcome differs: only Onicode can watch a PR, so the raw arm passes `cli-babysit-green` by waiting on the checks. +Both arms see the same world. Shell mocks apply to either arm's commands, so an agent in the tools arm that reaches for `gh` hits the same rate limit. Where the real tools refuse, the tools arm is refused too: `pull_request_merge` and `pull_request_review` refuse an `expectedHeadSha` that is neither the head nor a hex prefix of it of at least 7 characters, as `PullRequestService` does. As the tool schemas do, a merge without one and a blank one on either tool are refused, and an approval without one is refused. A `{"$error": "..."}` mock fails any Onicode tool with that text. `expectRaw` grades the raw arm when its right outcome differs: only Onicode can watch a PR, so the raw arm passes `cli-babysit-green` by waiting on the checks. Some cases are capability cases rather than mistake cases: diff --git a/evals/mcp-tool-use/run.test.ts b/evals/mcp-tool-use/run.test.ts index dc9c2701f8..b6fafa8efc 100644 --- a/evals/mcp-tool-use/run.test.ts +++ b/evals/mcp-tool-use/run.test.ts @@ -1589,19 +1589,46 @@ it.effect( // The server pushes an unpushed branch itself, so the first create opens the PR. assert.isNotTrue((yield* call("a", "pull_request_create", create)).is_error); - const short = yield* call("c", "pull_request_merge", { + // As PullRequestService: the full head or a hex prefix of at least 7 characters. + const moved = yield* call("c", "pull_request_merge", { + number: 7, + expectedHeadSha: "c3a91f3", + }); + assert.isTrue(moved.is_error); + assert.include(String(moved.content), `The head is now ${head}`); + const short = yield* call("c2", "pull_request_merge", { number: 7, expectedHeadSha: "c3a91f2", }); - assert.isTrue(short.is_error); - assert.include(String(short.content), `The head is now ${head}`); + assert.isNotTrue(short.is_error); const full = yield* call("d", "pull_request_merge", { number: 7, expectedHeadSha: head }); assert.isNotTrue(full.is_error); + // As the tool schemas: merge needs a SHA, and a blank one is refused wherever it is given. + const unpinnedMerge = yield* call("d2", "pull_request_merge", { number: 7 }); + assert.isTrue(unpinnedMerge.is_error); + assert.include(String(unpinnedMerge.content), "expectedHeadSha"); + const blankMerge = yield* call("d3", "pull_request_merge", { + number: 7, + expectedHeadSha: " ", + }); + assert.isTrue(blankMerge.is_error); + assert.include(String(blankMerge.content), "non-blank"); + const blankComment = { number: 7, verdict: "comment", body: "Hi.", expectedHeadSha: " " }; + const blankCommentResult = yield* call("d4", "pull_request_review", blankComment); + assert.isTrue(blankCommentResult.is_error); + assert.include(String(blankCommentResult.content), "non-blank"); const unpinned = yield* call("e", "pull_request_review", { number: 7, verdict: "approve" }); assert.include(String(unpinned.content), "Approving needs expectedHeadSha"); - const stale = { number: 7, verdict: "approve", expectedHeadSha: "c3a91f2" }; + const blank = { number: 7, verdict: "approve", expectedHeadSha: " " }; + assert.include( + String((yield* call("e2", "pull_request_review", blank)).content), + "non-blank", + ); + const stale = { number: 7, verdict: "approve", expectedHeadSha: "c3a91f3" }; assert.isTrue((yield* call("f", "pull_request_review", stale)).is_error); + const prefix = { number: 7, verdict: "approve", expectedHeadSha: "C3A91F27" }; + assert.isNotTrue((yield* call("f2", "pull_request_review", prefix)).is_error); const pinned = { number: 7, verdict: "approve", expectedHeadSha: head }; assert.isNotTrue((yield* call("g", "pull_request_review", pinned)).is_error); assert.isNotTrue( diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.ts index a31cec39ed..eebdb1e548 100644 --- a/evals/mcp-tool-use/run.ts +++ b/evals/mcp-tool-use/run.ts @@ -50,6 +50,7 @@ import { ThreadId, } from "@onicode/contracts"; import { projectComposerContextForProvider } from "@onicode/shared/composerContextReferences"; +import { isHeadSha } from "@onicode/shared/git"; import { THEME_GUIDE } from "@onicode/shared/themeCss"; import { formatThreadLink } from "@onicode/shared/threadLinks"; import { buildCodexAdditionalContext } from "../../apps/server/src/provider/CodexDeveloperInstructions.ts"; @@ -2276,17 +2277,20 @@ const recordForgeChange = ( */ const productRefusal = (sample: Sample, name: string, input: Readonly>) => { const world = sample.testCase.setup.world; - if ( - name === "pull_request_review" && - input.verdict === "approve" && - typeof input.expectedHeadSha !== "string" - ) { + const pinsHead = name === "pull_request_merge" || name === "pull_request_review"; + const sha = input.expectedHeadSha; + // The tool schemas: required on merge, and a TrimmedNonEmptyString wherever it is given. + if (pinsHead && sha === undefined && name === "pull_request_merge") { + return 'Missing key\n at ["expectedHeadSha"]'; + } + if (pinsHead && sha !== undefined && (typeof sha !== "string" || sha.trim() === "")) { + return `Expected a non-blank string, got ${JSON.stringify(sha)}\n at ["expectedHeadSha"]`; + } + const expected = typeof sha === "string" ? sha.trim() : undefined; + if (name === "pull_request_review" && input.verdict === "approve" && expected === undefined) { return "Approving needs expectedHeadSha: the headSha pull_request_read reported for the commits you reviewed."; } - if ( - (name === "pull_request_merge" || name === "pull_request_review") && - typeof input.expectedHeadSha === "string" - ) { + if (pinsHead && expected !== undefined) { const own = branchPullRequest(sample); const number = input.number ?? own.number; const pr = worldPullRequests(sample).find((candidate) => Number(candidate.number) === number); @@ -2297,8 +2301,8 @@ const productRefusal = (sample: Sample, name: string, input: Readonly { ); it.effect.each(["waiting", "completed", "rolled_back"] as const)( - "dispatches Stop for %s runs with background commands except rollback", + "dispatches Stop for %s runs with background commands and a queued follow-up except rollback", (status) => Effect.gen(function* () { const waitingRunId = RunId.make("run-waiting"); @@ -930,6 +930,23 @@ describe("V2 environment commands", () => { checkpointId: null, contextHandoffId: null, }, + { + id: RunId.make("run-queued"), + threadId: v2ThreadId, + ordinal: 2, + providerInstanceId: v2Projection.thread.providerInstanceId, + modelSelection: v2Projection.thread.modelSelection, + providerThreadId: null, + userMessageId: MessageId.make("message-queued"), + rootNodeId: null, + activeAttemptId: null, + status: "queued", + requestedAt: v2Now, + startedAt: null, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }, ], turnItems: [ { diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index 4c466b14e5..f87a7d6ba6 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -937,7 +937,8 @@ export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThrea run.status === "waiting", )?.id; if (runId === undefined) { - const latestRun = projection.runs.at(-1); + // Servers without thread.stop stop background work only through this run. + const latestRun = projection.runs.findLast((run) => run.status !== "queued"); if ( derivePendingBackgroundWork({ latestRun, diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index 627199ed4c..071d382613 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -105,6 +105,8 @@ export interface ThreadRunSummary { readonly instanceId: ProviderInstanceId; readonly driver: ProviderDriverKind; }; + /** Live subagents of earlier runs that this run's wait call holds it on. */ + readonly awaitedEarlierSubagents?: number; readonly sourcePlanRef?: { readonly threadId: ThreadId; readonly planId: PlanId; diff --git a/packages/client-runtime/src/state/subagentRuntime.test.ts b/packages/client-runtime/src/state/subagentRuntime.test.ts index bbcf4da404..be1c335071 100644 --- a/packages/client-runtime/src/state/subagentRuntime.test.ts +++ b/packages/client-runtime/src/state/subagentRuntime.test.ts @@ -15,6 +15,7 @@ import { import * as DateTime from "effect/DateTime"; import { + countSubagentsAwaitedFromEarlierRuns, countSubagentsBlockingRun, deriveWorkflowGroups, isWorkflowScriptMessage, @@ -424,6 +425,28 @@ describe("countSubagentsBlockingRun", () => { expect(count([child("a", "running", false), reply("m2")], false)).toBe(0); }); + it("adds the children of earlier runs that the run's wait holds it on", () => { + const earlier = RunId.make("earlier-run"); + expect( + countSubagentsAwaitedFromEarlierRuns( + [ + { runId: earlier, status: "running", awaitedByRunId: runId }, + { runId: earlier, status: "completed", awaitedByRunId: runId }, + { runId: earlier, status: "running", awaitedByRunId: earlier }, + { runId: earlier, status: "running" }, + // Its own row in the run counts it. + { runId, status: "running", awaitedByRunId: runId }, + ], + runId, + ), + ).toBe(1); + const withEarlier = (items: ReadonlyArray, repliesShown: boolean) => + countSubagentsBlockingRun(items, runId, (item) => [item], repliesShown, 1); + expect(withEarlier([reply("m1")], true)).toBe(1); + expect(withEarlier([child("a", "running", false), reply("m1")], true)).toBe(2); + expect(withEarlier([reply("m2")], false)).toBe(0); + }); + it("stops at an entry that holds no turn item", () => { expect( countSubagentsBlockingRun([[child("a")], null, [child("b")]], runId, (items) => items, true), diff --git a/packages/client-runtime/src/state/subagentRuntime.ts b/packages/client-runtime/src/state/subagentRuntime.ts index 07e3c1a2f0..e03bf23139 100644 --- a/packages/client-runtime/src/state/subagentRuntime.ts +++ b/packages/client-runtime/src/state/subagentRuntime.ts @@ -102,10 +102,28 @@ export function isLiveSubagentTurnItem(item: OrchestrationV2TurnItem): boolean { return item.type === "subagent" && isOrchestrationV2WorkActive(item.status); } +/** Live subagents an earlier run launched that a wait call of run `runId` holds it on. */ +export function countSubagentsAwaitedFromEarlierRuns( + subagents: ReadonlyArray>, + runId: RunId, +): number { + let count = 0; + for (const subagent of subagents) { + if ( + subagent.awaitedByRunId === runId && + subagent.runId !== runId && + isOrchestrationV2WorkActive(subagent.status) + ) + count += 1; + } + return count; +} + /** * Live subagents the run's parent waits on: rows marked awaited anywhere in the run, and unflagged - * rows (older servers) in its tail past task lists and delegate calls. A finished reply there is the - * parent's status while shown as its own row; zen hides it, so the live row shows it instead. + * rows (older servers) in its tail past task lists and delegate calls, plus `earlierAwaited`, the + * awaited children of earlier runs. A finished reply there is the parent's status while shown as + * its own row; zen hides it, so the live row shows it instead. */ export function countSubagentsBlockingRun( entries: ReadonlyArray, @@ -115,8 +133,9 @@ export function countSubagentsBlockingRun( entry: Entry, ) => OrchestrationV2TurnItem | ReadonlyArray | null, repliesShown: boolean, + earlierAwaited = 0, ): number { - let running = 0; + let running = earlierAwaited; let inTail = true; let sawSubagent = false; // False once the walk is done: another run's item, or a zen reply the live row shows. @@ -129,7 +148,10 @@ export function countSubagentsBlockingRun( } else if (!inTail) { return true; } else if (item.type === "assistant_message") { - if (!repliesShown && !sawSubagent) return false; + if (!repliesShown && !sawSubagent) { + running = 0; + return false; + } if (!repliesShown || sawSubagent || item.streaming) inTail = false; } else if (item.type !== "todo_list" && !isDelegateLaunch(item)) { inTail = false; diff --git a/packages/client-runtime/src/state/threadExecution.test.ts b/packages/client-runtime/src/state/threadExecution.test.ts index 590c1e7870..7bd53eb15b 100644 --- a/packages/client-runtime/src/state/threadExecution.test.ts +++ b/packages/client-runtime/src/state/threadExecution.test.ts @@ -704,10 +704,11 @@ describe("presentRunStop", () => { state: "unresponsive", }, { - name: "a settled run whose background work ignored Stop, with a queued follow-up", + name: "a settled run whose background work ignored Stop, with queued and steered follow-ups", runs: [ { ...running, status: "completed" as const, completedAt: now }, run("run-queued", 2, "queued"), + { ...run("run-steered", 3, "cancelled"), startedAt: null, completedAt: now }, ], turnItems: [{ ...request, unresponsiveAt: now }], state: "unresponsive", diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.ts index 6287138bd8..0a10f8198f 100644 --- a/packages/client-runtime/src/state/threadExecution.ts +++ b/packages/client-runtime/src/state/threadExecution.ts @@ -54,6 +54,7 @@ import { } from "./models.ts"; import { commandDisplayText } from "../work-log/commandLabel.ts"; import { formatSubagentDisplayTitle } from "./subagentDisplay.ts"; +import { countSubagentsAwaitedFromEarlierRuns } from "./subagentRuntime.ts"; import { mFallback, msg } from "gt-i18n"; import { markedTextEnglish } from "../errors/translatable.ts"; import type { MFunctionType } from "gt-i18n/types"; @@ -104,7 +105,7 @@ export function deriveProviderExtensionStatuses( } function latestMatchingRun( - projection: ThreadStructure, + projection: Pick, predicate: (run: OrchestrationV2ThreadProjection["runs"][number]) => boolean, ): OrchestrationV2ThreadProjection["runs"][number] | null { return projection.runs.reduce( @@ -211,6 +212,9 @@ function summarizeThreadRun( (candidate) => candidate.providerInstanceId === run.providerInstanceId, ); const phase = startupPhaseFor(projection, session); + const awaitedEarlierSubagents = ACTIVITY_RUN_STATUSES.has(run.status) + ? countSubagentsAwaitedFromEarlierRuns(projection.subagents, run.id) + : 0; return { runId: run.id, status: run.status, @@ -234,6 +238,7 @@ function summarizeThreadRun( : providerStarting(run, session, phase, providers) : { turnEnded: true }), ...(run.sourcePlanRef === undefined ? {} : { sourcePlanRef: run.sourcePlanRef }), + ...(awaitedEarlierSubagents === 0 ? {} : { awaitedEarlierSubagents }), }; } @@ -709,19 +714,8 @@ export interface RunStopPresentation { export function presentRunStop( projection: Pick, ): RunStopPresentation | null { - let active: ThreadStructure["runs"][number] | null = null; - let latest: ThreadStructure["runs"][number] | null = null; - for (const candidate of projection.runs) { - // Queued follow-ups never ran, so they hold no Stop of their own. - if (candidate.status !== "queued" && candidate.ordinal > (latest?.ordinal ?? -1)) - latest = candidate; - if ( - INTERRUPTIBLE_RUN_STATUSES.has(candidate.status) && - candidate.ordinal > (active?.ordinal ?? -1) - ) - active = candidate; - } - const run = active ?? latest; + const active = latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status)); + const run = active ?? latestExecutedRun(projection.runs); if (run === null) return null; let request: | Extract diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index ee51372b74..e0b8401884 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1075,6 +1075,8 @@ export const OrchestrationV2Subagent = Schema.Struct({ completionDelivery: Schema.optional(OrchestrationV2DelegatedCompletionTaskDelivery), // The run whose unfinished task was cancelled, committed with its Stop. cancelledRunId: Schema.optional(RunId), + /** The run whose running wait call holds its parent on this subagent. Absent from older servers. */ + awaitedByRunId: Schema.optional(RunId), status: Schema.Literals([ "idle", "pending", diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 14ba0f5a01..d5f5d3ab19 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -723,6 +723,8 @@ export interface AcpAdapterV2Flavor { readonly extractSubagentUpdate?: ( toolCall: AcpToolCallState, ) => AcpAdapterV2SubagentUpdate | undefined; + /** The child sessions a running tool call holds the parent on until the call returns. */ + readonly extractSubagentWait?: (toolCall: AcpToolCallState) => ReadonlyArray; readonly isProvisionalSubagentTool?: (toolCall: AcpToolCallState) => boolean; readonly normalizeToolCall?: (toolCall: AcpToolCallState) => AcpToolCallState; readonly isCancelledToolCall?: (payload: unknown) => boolean; @@ -2114,6 +2116,8 @@ export function acpCompletedTurnShouldTerminalizeTool( interface ActiveAcpSubagent { task: OrchestrationV2Subagent; background?: true; + // Running wait calls on this child, by tool call id, with the run each holds. + readonly waitCalls: Map>; readonly childThreadId: ThreadId; readonly childRootNodeId: OrchestrationV2ExecutionNode["id"]; readonly turnItemId: OrchestrationV2TurnItem["id"]; @@ -2159,6 +2163,11 @@ function acpSubagentStatusBlocksTurnSettlement(status: OrchestrationV2Subagent[" return status === "running" || status === "pending"; } +function acpSubagentRowBackground(subagent: ActiveAcpSubagent) { + if (subagent.waitCalls.size > 0) return { background: false }; + return subagent.background ? { background: true } : {}; +} + function acpSubagentHasPendingBackgroundWork(subagent: ActiveAcpSubagent): boolean { return ( acpSubagentStatusBlocksTurnSettlement(subagent.task.status) || !subagent.terminalStatusProjected @@ -4150,6 +4159,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( childItemOrdinals: new Map(), nextChildOrdinal: 101, terminalStatusProjected: false, + waitCalls: new Map(), toolState: { tools: new Map(), toolUpdatesSkipped: new Map(), @@ -4261,8 +4271,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* emitSubagentAssistant(subagent, update.result); } const result = update.result ?? subagent.task.result ?? (subagent.assistantText || null); + const { awaitedByRunId: _awaitedByRunId, ...unawaited } = subagent.task; + const awaitedByRunId = acpSubagentStatusIsTerminal(taskStatus) + ? undefined + : subagent.waitCalls.values().next().value; subagent.task = { - ...subagent.task, + ...unawaited, + ...(awaitedByRunId === undefined ? {} : { awaitedByRunId }), status: taskStatus, result, completedAt: acpSubagentStatusIsTerminal(taskStatus) ? now : null, @@ -4338,7 +4353,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( childThreadId, prompt: subagent.task.prompt, result, - ...(subagent.background ? { background: true } : {}), + ...acpSubagentRowBackground(subagent), }, }); if (acpSubagentStatusIsTerminal(taskStatus)) { @@ -4346,6 +4361,53 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } }); + // `waits` names every child a running call holds now; null ends the call, undefined ends all. + const updateSubagentWaits = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + toolCallId: string | undefined, + waits: ReadonlyArray | null, + ) { + for (const subagent of context.subagents.values()) { + const wasAwaited = subagent.waitCalls.size > 0; + if (toolCallId === undefined) { + subagent.waitCalls.clear(); + } else if ( + waits !== null && + subagent.childSessionId !== null && + waits.includes(subagent.childSessionId) + ) { + subagent.waitCalls.set(toolCallId, context.input.runId); + } else { + subagent.waitCalls.delete(toolCallId); + } + if ( + wasAwaited === subagent.waitCalls.size > 0 || + !acpSubagentStatusBlocksTurnSettlement(subagent.task.status) + ) + continue; + yield* emitSubagent(context, { + nativeTaskId: subagent.task.nativeTaskRef?.nativeId ?? subagent.task.id, + prompt: subagent.task.prompt, + title: subagent.task.title, + model: subagent.task.model, + status: subagent.task.status === "pending" ? "pending" : "running", + childSessionId: subagent.childSessionId, + result: subagent.task.result, + suppressNormalTool: true, + }); + } + }); + + // Finalize waits for background work; no call of the ended prompt holds the parent. + const settlePrompt = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + status: NonNullable, + ) { + context.promptSettled = true; + context.promptSettledStatus = status; + yield* updateSubagentWaits(context, undefined, null); + }); + const nativeChild = (sessionId: string) => { let child = nativeChildren.get(sessionId); if (child === undefined) { @@ -4899,6 +4961,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (toolCall.status === "failed" && context.stoppedToolCallIds.has(toolCall.toolCallId) ? "interrupted" : undefined); + if (flavor.extractSubagentWait !== undefined) { + const callStatus = stoppedStatus ?? toolStatus(toolCall.status); + yield* updateSubagentWaits( + context, + toolCall.toolCallId, + callStatus === "pending" || callStatus === "running" + ? flavor.extractSubagentWait(toolCall) + : null, + ); + } if ( followsAgentWorkState && projectedStatus === undefined && @@ -7349,7 +7421,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( childThreadId: subagent.childThreadId, prompt: subagent.task.prompt, result, - ...(subagent.background ? { background: true } : {}), + ...acpSubagentRowBackground(subagent), }, }); if (acpSubagentStatusIsTerminal(status)) { @@ -9327,6 +9399,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Fiber.interrupt(watchdog).pipe(Effect.forkDetach, Effect.asVoid); } yield* cancelOutcomeResume(context); + // A wait the turn ended inside never returns, so it no longer holds its children. + yield* updateSubagentWaits(context, undefined, null); const directStopQuarantine = yield* Ref.get(stoppedRunQuarantine); if (flavor.subagentsIdleOnTurnCompletion === true) { for (const subagent of context.subagents.values()) { @@ -10154,8 +10228,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( : "cancelled" : "completed"; if (defersFinalizeForBackgroundWork && !context.interrupted) { - context.promptSettled = true; - context.promptSettledStatus = status; + yield* settlePrompt(context, status); for (const [taskId, completion] of context.backgroundCommands) { if (completion === null) continue; yield* finishRegisteredBackgroundTool({ taskId, ...completion }); @@ -10611,8 +10684,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); return; } - context.promptSettled = true; - context.promptSettledStatus = "completed"; + yield* settlePrompt(context, "completed"); // The replayed reply ended before the prompt counted as settled. yield* idleReportedSubagents(context); if (drainedWakeCount === 0) { diff --git a/packages/provider-grok/src/server/adapter.ts b/packages/provider-grok/src/server/adapter.ts index b430efe5e6..60f92fa873 100644 --- a/packages/provider-grok/src/server/adapter.ts +++ b/packages/provider-grok/src/server/adapter.ts @@ -43,6 +43,7 @@ import { extractXAiAcpSubagentUpdate, extractXAiAskUserQuestionIdentity, extractXAiAskUserQuestions, + extractXAiAwaitedSubagentIds, extractXAiBackgroundTaskCompletion, extractXAiKilledBackgroundTasks, extractXAiMonitorTaskId, @@ -442,6 +443,7 @@ export function makeGrokAcpAdapterFlavor( }), registerExtensions: registerGrokAcpExtensions, extractSubagentUpdate: extractXAiAcpSubagentUpdate, + extractSubagentWait: extractXAiAwaitedSubagentIds, extractSubagentEndNotice: extractXAiAcpSubagentEndNotice, normalizeToolCall: normalizeXAiAcpToolCallState, extractProposedPlanMarkdown: (toolCall) => diff --git a/packages/provider-grok/src/server/xaiAcpExtension.test.ts b/packages/provider-grok/src/server/xaiAcpExtension.test.ts index f7e96857b8..461c8d86f4 100644 --- a/packages/provider-grok/src/server/xaiAcpExtension.test.ts +++ b/packages/provider-grok/src/server/xaiAcpExtension.test.ts @@ -15,6 +15,7 @@ import { extractXAiAcpSubagentEndNotice, extractXAiAcpSubagentUpdate, extractXAiAskUserQuestions, + extractXAiAwaitedSubagentIds, extractXAiBackgroundTaskCompletion, extractXAiKilledBackgroundTasks, extractXAiMonitorTaskId, @@ -210,6 +211,40 @@ describe("XAiAcpExtension", () => { }); }); + const XAI_POLLED_CHILD_ID = "019f44a6-4820-7402-925d-bc862ee711dd"; + // Recorded frames (grok_background_* fixtures) carry a display title, the canonical name in + // `_meta["x.ai/tool"]`, and an omitted timeout as null. + const recordedPoll = (name: string, rawInput: Record) => ({ + title: `Get task output: ${XAI_POLLED_CHILD_ID}`, + meta: { "x.ai/tool": { version: 1, name, kind: "background_task_action" } }, + rawInput: { variant: "TaskOutput", ...rawInput }, + }); + it.each([ + { title: "get_command_or_subagent_output", rawInput: { timeout_ms: 15_000 }, awaited: true }, + { title: "get_command_or_subagent_output", rawInput: {}, awaited: false }, + { title: "get_command_or_subagent_output", rawInput: { timeout_ms: 0 }, awaited: false }, + { title: "wait_commands_or_subagents", rawInput: { mode: "wait_all" }, awaited: true }, + { title: "Read", rawInput: { timeout_ms: 15_000 }, awaited: false }, + { + ...recordedPoll("get_command_or_subagent_output", { timeout_ms: 15_000 }), + awaited: true, + }, + { ...recordedPoll("get_command_or_subagent_output", { timeout_ms: null }), awaited: false }, + { ...recordedPoll("wait_commands_or_subagents", { timeout_ms: null }), awaited: true }, + ])("holds the parent on the polled children only for a blocking poll: %j", (row) => { + expect( + extractXAiAwaitedSubagentIds({ + toolCallId: "call-poll", + title: row.title, + status: "inProgress", + data: { + ...("meta" in row ? { meta: row.meta } : {}), + rawInput: { task_ids: [XAI_POLLED_CHILD_ID, "call-bg-1-0"], ...row.rawInput }, + }, + }), + ).toEqual(row.awaited ? [XAI_POLLED_CHILD_ID] : []); + }); + it("attributes multi-task get_output envelopes to the result task_id", () => { expect( extractXAiAcpSubagentUpdate({ diff --git a/packages/provider-grok/src/server/xaiAcpExtension.ts b/packages/provider-grok/src/server/xaiAcpExtension.ts index 4689574993..658eefa1aa 100644 --- a/packages/provider-grok/src/server/xaiAcpExtension.ts +++ b/packages/provider-grok/src/server/xaiAcpExtension.ts @@ -220,12 +220,21 @@ function isXAiSpawnOrTaskTool( return false; } +// Display titles such as "Get task output: " leave the canonical name in metadata. +function xAiCanonicalToolName(toolCall: AcpToolCallState): string { + const name = unknownRecord(unknownRecord(toolCall.data.meta)?.["x.ai/tool"])?.name; + return nonEmptyString(name) ?? titleKey(toolCall); +} + function isXAiGetSubagentOutputTool( toolCall: AcpToolCallState, rawInput: Record | undefined, ): boolean { const title = titleKey(toolCall); + const name = xAiCanonicalToolName(toolCall); if ( + name === "get_command_or_subagent_output" || + name === "wait_commands_or_subagents" || title === "get_command_or_subagent_output" || title.includes("get_command_or_subagent_output") || title === "wait_commands_or_subagents" @@ -836,6 +845,21 @@ function statusFromGetOutputTool( return "running"; } +/** + * The subagents an output call waits for: a positive `timeout_ms` blocks until they finish, while + * none (absent or null) or 0 only reads their status. `wait_commands_or_subagents` waits 30 s by default. + */ +export function extractXAiAwaitedSubagentIds(toolCall: AcpToolCallState): ReadonlyArray { + const rawInput = unknownRecord(toolCall.data.rawInput); + if (!isXAiGetSubagentOutputTool(toolCall, rawInput)) return []; + const timeout = rawInput?.timeout_ms; + const waits = + typeof timeout === "number" + ? timeout > 0 + : timeout == null && xAiCanonicalToolName(toolCall) === "wait_commands_or_subagents"; + return waits ? taskIdsFromGetOutputTool(toolCall, rawInput) : []; +} + /** Spawn ACKs return immediately; keep subagents running until a child or hydration terminal. */ export function extractXAiAcpSubagentUpdate( toolCall: AcpToolCallState, diff --git a/packages/provider-grok/src/testing.ts b/packages/provider-grok/src/testing.ts index ed5ed41088..1782e7b9e2 100644 --- a/packages/provider-grok/src/testing.ts +++ b/packages/provider-grok/src/testing.ts @@ -22,6 +22,7 @@ export { makeGrokTextGeneration } from "./server/textGeneration.ts"; export { grokUsageResponseToLimits, readGrokAccount } from "./server/usageLimits.ts"; export { extractXAiAcpSubagentUpdate, + extractXAiAwaitedSubagentIds, makeXAiPromptCompletionRuntime, normalizeXAiAcpToolCallState, registerXAiBackgroundTaskTracking, diff --git a/packages/shared/src/git.ts b/packages/shared/src/git.ts index 4bc289ff3a..b555cf595d 100644 --- a/packages/shared/src/git.ts +++ b/packages/shared/src/git.ts @@ -12,6 +12,12 @@ import * as Result from "effect/Result"; import { foldLatinDiacritics } from "./path.ts"; export const WORKTREE_BRANCH_PREFIX = "onicode"; + +/** Whether `expected` names `head`: the full SHA, or a hex prefix of at least 7 characters. */ +export const isHeadSha = (head: string, expected: string) => { + const wanted = expected.toLowerCase(); + return /^[0-9a-f]{7,}$/.test(wanted) ? head.toLowerCase().startsWith(wanted) : head === expected; +}; const TEMP_WORKTREE_HEX_TOKEN = "[0-9a-f]{8}"; const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp( `^${WORKTREE_BRANCH_PREFIX}[-/]${TEMP_WORKTREE_HEX_TOKEN}$`, diff --git a/packages/shared/src/httpReadiness.ts b/packages/shared/src/httpReadiness.ts index 7e65aafa28..9bb43fe02b 100644 --- a/packages/shared/src/httpReadiness.ts +++ b/packages/shared/src/httpReadiness.ts @@ -3,9 +3,27 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schedule from "effect/Schedule"; -import { HttpClient, HttpClientRequest } from "effect/http"; +import * as Stream from "effect/Stream"; +import { HttpClient, HttpClientRequest, type HttpClientResponse } from "effect/http"; const DEFAULT_HTTP_READY_PROBE_TIMEOUT_MS = 1_000; +const MAX_READINESS_BODY_BYTES = 64 * 1024; + +const readCappedBody = (response: HttpClientResponse.HttpClientResponse) => + response.stream.pipe( + Stream.mapAccum( + () => MAX_READINESS_BODY_BYTES, + (left, chunk: Uint8Array) => { + const part = chunk.subarray(0, left); + const rest = left - part.byteLength; + return [rest, [{ part, rest }]] as const; + }, + ), + Stream.takeUntil(({ rest }) => rest === 0), + Stream.map(({ part }) => part), + Stream.decodeText(), + Stream.mkString, + ); function describeReadinessCause(cause: unknown): unknown { if (cause instanceof Error) { @@ -83,9 +101,20 @@ export const waitForHttpReady = Effect.fn("shared.httpReadiness.waitForHttpReady HttpClient.transform((effect) => Effect.gen(function* () { attempt += 1; + // A listener that sends headers and then stalls its body fails this probe, not the whole wait. const responseOption = yield* effect.pipe( + Effect.tap((response) => + readCappedBody(response).pipe( + Effect.orElseSucceed(() => ""), + Effect.flatMap((body) => input.accept?.(body) ?? Effect.succeed(true)), + Effect.flatMap((accepted) => + accepted + ? Effect.void + : Effect.fail(fail({ kind: "response-not-accepted", attempt })), + ), + ), + ), Effect.timeoutOption(Duration.millis(probeTimeoutMs)), - Effect.mapError((cause) => fail(cause)), ); return yield* Effect.fromOption(responseOption, () => fail({ @@ -104,18 +133,6 @@ export const waitForHttpReady = Effect.fn("shared.httpReadiness.waitForHttpReady ), ), ), - HttpClient.tap((response) => - response.text.pipe( - Effect.orElseSucceed(() => ""), - Effect.flatMap((body) => input.accept?.(body) ?? Effect.succeed(true)), - Effect.flatMap((accepted) => - accepted ? Effect.void : Effect.fail(fail({ kind: "response-not-accepted", attempt })), - ), - Effect.tapError((cause) => - Ref.set(lastProbeFailure, { attempt, cause: describeReadinessCause(cause) }), - ), - ), - ), HttpClient.retry(retryPolicy), );