From 349b81e3bf1fff8e832f6c721a704c6e8664eacf Mon Sep 17 00:00:00 2001 From: Donald Silveira Date: Wed, 30 Sep 2026 23:03:25 -0300 Subject: [PATCH 1/4] feat(server): delegate tasks to nested Codex agents MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add an MCP tool to run provider tasks in the caller’s working copy - Track delegated threads in the Agents panel and return their results to the parent --- .../OrchestrationEngineHarness.integration.ts | 4 + .../src/delegation/DelegationService.test.ts | 410 +++++++++++++++ .../src/delegation/DelegationService.ts | 465 ++++++++++++++++++ apps/server/src/mcp/McpHttpServer.ts | 7 + .../src/mcp/toolkits/delegation/handlers.ts | 18 + .../src/mcp/toolkits/delegation/tools.ts | 51 ++ .../Layers/OrchestrationReactor.test.ts | 10 + .../Layers/OrchestrationReactor.ts | 3 + apps/server/src/server.ts | 2 + apps/web/src/components/AgentsPanel.tsx | 36 +- docs/user/thread-sidebar.md | 6 + .../src/state/subagentRuntime.ts | 6 + 12 files changed, 1012 insertions(+), 6 deletions(-) create mode 100644 apps/server/src/delegation/DelegationService.test.ts create mode 100644 apps/server/src/delegation/DelegationService.ts create mode 100644 apps/server/src/mcp/toolkits/delegation/handlers.ts create mode 100644 apps/server/src/mcp/toolkits/delegation/tools.ts diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index 669af4a18bc20..f4e3e7320c2f2 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -39,6 +39,7 @@ import { makeProviderRegistryLayer } from "../src/provider/testUtils/providerReg import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts"; import { ServerSettingsService } from "../src/serverSettings.ts"; import * as AutomationService from "../src/automation/AutomationService.ts"; +import * as DelegationService from "../src/delegation/DelegationService.ts"; import * as StorageCleanup from "../src/storageCleanup.ts"; import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts"; import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts"; @@ -387,6 +388,9 @@ export const makeOrchestrationIntegrationHarness = ( Layer.provideMerge( Layer.mock(AutomationService.AutomationService)({ start: () => Effect.void }), ), + Layer.provideMerge( + Layer.mock(DelegationService.DelegationService)({ start: () => Effect.void }), + ), Layer.provideMerge( Layer.succeed(StorageCleanup.StorageCleanup, { start: () => Effect.void, diff --git a/apps/server/src/delegation/DelegationService.test.ts b/apps/server/src/delegation/DelegationService.test.ts new file mode 100644 index 0000000000000..813ead43de9cd --- /dev/null +++ b/apps/server/src/delegation/DelegationService.test.ts @@ -0,0 +1,410 @@ +import { + CommandId, + EventId, + MessageId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + type OrchestrationCommand, + type OrchestrationEvent, + type OrchestrationLatestTurn, + type OrchestrationSession, + type OrchestrationThread, + type OrchestrationThreadActivity, + type OrchestrationThreadShell, + type ServerProvider, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import { assert, describe, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as PubSub from "effect/PubSub"; +import * as Queue from "effect/Queue"; +import * as Ref from "effect/Ref"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts"; +import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; +import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts"; +import * as DelegationService from "./DelegationService.ts"; + +const PROJECT_ID = ProjectId.make("delegation-project"); +const PARENT_ID = ThreadId.make("parent-thread"); +const AT = "2026-09-01T00:00:00.000Z"; + +const CODEX = { + instanceId: ProviderInstanceId.make("codex"), + driver: ProviderDriverKind.make("codex"), + displayName: "Codex", + enabled: true, + installed: true, + status: "ready", + models: [ + { slug: "gpt-5", name: "GPT-5", isCustom: false, isDefault: true }, + { slug: "gpt-5-mini", name: "GPT-5 mini", isCustom: false }, + ], +} as unknown as ServerProvider; + +const session = ( + threadId: ThreadId, + status: OrchestrationSession["status"], +): OrchestrationSession => ({ + threadId, + status, + providerName: "codex", + runtimeMode: "full-access", + activeTurnId: status === "running" ? TurnId.make("turn-1") : null, + lastError: null, + updatedAt: AT, +}); + +const shell = ( + id: ThreadId, + latestTurn: OrchestrationLatestTurn["state"] | null, + overrides: Partial = {}, +): OrchestrationThreadShell => ({ + id, + projectId: PROJECT_ID, + title: "Thread", + modelSelection: { instanceId: ProviderInstanceId.make("claudeAgent"), model: "opus" }, + runtimeMode: "full-access", + interactionMode: "default", + pullRequests: [], + branch: "feature", + worktreePath: "/tmp/worktree", + latestTurn: + latestTurn === null + ? null + : { + turnId: TurnId.make("turn-1"), + state: latestTurn, + requestedAt: AT, + startedAt: AT, + completedAt: latestTurn === "running" ? null : AT, + assistantMessageId: MessageId.make("final"), + }, + createdAt: AT, + updatedAt: AT, + archivedAt: null, + settledOverride: null, + settledAt: null, + session: null, + latestUserMessageAt: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false, + ...overrides, +}); + +const sessionSet = (threadId: ThreadId): OrchestrationEvent => ({ + sequence: 2, + eventId: EventId.make(`event-${threadId}`), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: AT, + commandId: CommandId.make(`command-${threadId}`), + causationEventId: null, + correlationId: null, + metadata: {}, + type: "thread.session-set", + payload: { threadId, session: session(threadId, "ready") }, +}); + +interface Harness { + readonly service: DelegationService.DelegationService["Service"]; + readonly setThread: (thread: OrchestrationThreadShell) => Effect.Effect; + readonly publish: (event: OrchestrationEvent) => Effect.Effect; + /** The next dispatched command, in order. */ + readonly nextCommand: Effect.Effect; + readonly pendingCommands: Effect.Effect; +} + +const withService = ( + body: (harness: Harness) => Effect.Effect, + options: { + readonly threads?: ReadonlyArray; + readonly startedActivities?: ReadonlyArray; + readonly deliveredMessages?: ReadonlyArray; + } = {}, +) => + Effect.gen(function* () { + const threads = yield* Ref.make>( + new Map( + ( + options.threads ?? [ + shell(PARENT_ID, "running", { session: session(PARENT_ID, "running") }), + ] + ).map((thread) => [thread.id, thread]), + ), + ); + const commands = yield* Queue.unbounded(); + const events = yield* PubSub.unbounded(); + const subscribed = yield* Deferred.make(); + const setThread = (thread: OrchestrationThreadShell) => + Ref.update(threads, (current) => new Map(current).set(thread.id, thread)); + const delivered = new Set(options.deliveredMessages ?? []); + + const layer = DelegationService.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(OrchestrationEngineService)({ + dispatch: (command) => + Effect.gen(function* () { + if (command.type === "thread.create") { + yield* setThread(shell(command.threadId, null, { title: command.title })); + } + yield* Queue.offer(commands, command); + return { sequence: 1 }; + }), + streamDomainEvents: Stream.unwrap( + PubSub.subscribe(events).pipe( + Effect.tap(() => Deferred.succeed(subscribed, undefined)), + Effect.map(Stream.fromSubscription), + ), + ), + }), + Layer.mock(ProjectionSnapshotQuery)({ + getThreadShellById: (threadId) => + Ref.get(threads).pipe(Effect.map((all) => Option.fromNullishOr(all.get(threadId)))), + getThreadDetailById: (threadId) => + Ref.get(threads).pipe( + Effect.map((all) => + Option.fromNullishOr(all.get(threadId)).pipe( + Option.map((thread): OrchestrationThread => ({ + ...thread, + deletedAt: null, + messages: [ + { + id: MessageId.make("final"), + role: "assistant", + text: "Found two bugs.", + turnId: TurnId.make("turn-1"), + streaming: false, + createdAt: AT, + updatedAt: AT, + }, + ], + proposedPlans: [], + activities: [], + checkpoints: [], + })), + ), + ), + ), + listActivitiesByKind: () => Effect.succeed(options.startedActivities ?? []), + getTurnStartMessage: ({ messageId }) => + Effect.succeed( + delivered.has(messageId) + ? Option.some({ + message: { + id: messageId, + role: "user" as const, + text: "", + turnId: null, + streaming: false, + createdAt: AT, + updatedAt: AT, + }, + hasOtherUserMessages: true, + }) + : Option.none(), + ), + }), + Layer.mock(ProviderRegistry)({ getProviders: Effect.succeed([CODEX]) }), + ), + ), + Layer.provideMerge(NodeServices.layer), + ); + const service = Context.get(yield* Layer.build(layer), DelegationService.DelegationService); + yield* service.start(); + yield* Deferred.await(subscribed); + return yield* body({ + service, + setThread, + publish: (event) => PubSub.publish(events, event).pipe(Effect.asVoid), + nextCommand: Queue.take(commands), + pendingCommands: Queue.size(commands), + }); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)); + +describe("DelegationService", () => { + it.effect("runs the task as a thread in the caller's working copy and lists it as an agent", () => + withService(({ service, nextCommand }) => + Effect.gen(function* () { + const result = yield* service.delegate({ + parentThreadId: PARENT_ID, + provider: "codex", + prompt: "Review the uncommitted changes.", + title: "Review changes", + }); + assert.strictEqual(result.model, "gpt-5"); + + const create = yield* nextCommand; + assert(create.type === "thread.create"); + assert.strictEqual(create.threadId, result.threadId); + assert.strictEqual(create.worktreePath, "/tmp/worktree"); + assert.strictEqual(create.branch, "feature"); + assert.deepStrictEqual(create.modelSelection, { + instanceId: CODEX.instanceId, + model: "gpt-5", + }); + + const turn = yield* nextCommand; + assert(turn.type === "thread.turn.start"); + assert.strictEqual(turn.threadId, result.threadId); + assert.include(turn.message.text, "Review the uncommitted changes."); + + const started = yield* nextCommand; + assert(started.type === "thread.activity.append"); + assert.strictEqual(started.threadId, PARENT_ID); + assert.strictEqual(started.activity.kind, "task.started"); + assert.deepInclude(started.activity.payload as object, { + taskId: result.threadId, + title: "Review changes", + role: "Codex", + agentKind: "agent", + delegatedThreadId: result.threadId, + }); + }), + ), + ); + + it.effect("reports the result back once the caller's turn has ended", () => + withService(({ service, setThread, publish, nextCommand, pendingCommands }) => + Effect.gen(function* () { + const { threadId: child } = yield* service.delegate({ + parentThreadId: PARENT_ID, + provider: "Codex", + prompt: "Review the uncommitted changes.", + title: "Review changes", + }); + for (let i = 0; i < 3; i++) yield* nextCommand; + + yield* setThread(shell(child, "completed", { session: session(child, "ready") })); + yield* publish(sessionSet(child)); + const completed = yield* nextCommand; + assert(completed.type === "thread.activity.append"); + assert.strictEqual(completed.threadId, PARENT_ID); + assert.strictEqual(completed.activity.kind, "task.completed"); + assert.deepInclude(completed.activity.payload as object, { + taskId: child, + status: "completed", + summary: "Found two bugs.", + }); + + // The caller is still mid-turn, so the result waits. + yield* service.drain; + assert.strictEqual(yield* pendingCommands, 0); + + yield* setThread(shell(PARENT_ID, "completed", { session: session(PARENT_ID, "ready") })); + yield* publish(sessionSet(PARENT_ID)); + const result = yield* nextCommand; + assert(result.type === "thread.turn.start"); + assert.strictEqual(result.threadId, PARENT_ID); + assert.strictEqual(result.message.messageId, MessageId.make(`delegation:${child}`)); + assert.include(result.message.text, 'Codex finished the delegated task "Review changes".'); + assert.include(result.message.text, "Found two bugs."); + }), + ), + ); + + it.effect("a delegated thread cannot delegate further", () => + withService(({ service }) => + Effect.gen(function* () { + const { threadId: child } = yield* service.delegate({ + parentThreadId: PARENT_ID, + provider: "codex", + prompt: "Review.", + }); + const error = yield* service + .delegate({ parentThreadId: child, provider: "codex", prompt: "Review again." }) + .pipe(Effect.flip); + assert.include(error.message, "cannot delegate further"); + }), + ), + ); + + it.effect("names the available providers when none matches", () => + withService(({ service }) => + Effect.gen(function* () { + const error = yield* service + .delegate({ parentThreadId: PARENT_ID, provider: "gemini", prompt: "Review." }) + .pipe(Effect.flip); + assert.include(error.message, "codex (Codex)"); + }), + ), + ); + + const startedActivity = (child: ThreadId): OrchestrationThreadActivity => ({ + id: EventId.make(`delegation:${child}:started`), + tone: "info", + kind: "task.started", + summary: "Delegated task started", + payload: { + taskId: child, + title: "Review changes", + role: "Codex", + delegatedThreadId: child, + parentThreadId: PARENT_ID, + }, + turnId: null, + createdAt: AT, + }); + + it.effect("after a restart, reports back a delegation that finished unreported", () => { + const finished = ThreadId.make("finished-child"); + const reported = ThreadId.make("reported-child"); + return withService( + ({ nextCommand, service, pendingCommands }) => + Effect.gen(function* () { + const completed = yield* nextCommand; + assert(completed.type === "thread.activity.append"); + assert.strictEqual( + completed.activity.id, + EventId.make(`delegation:${finished}:completed`), + ); + const result = yield* nextCommand; + assert(result.type === "thread.turn.start"); + assert.strictEqual(result.message.messageId, MessageId.make(`delegation:${finished}`)); + yield* service.drain; + assert.strictEqual(yield* pendingCommands, 0); + }), + { + threads: [ + shell(PARENT_ID, "completed", { session: session(PARENT_ID, "ready") }), + shell(finished, "interrupted", { session: session(finished, "stopped") }), + shell(reported, "completed", { session: session(reported, "ready") }), + ], + startedActivities: [startedActivity(finished), startedActivity(reported)], + deliveredMessages: [MessageId.make(`delegation:${reported}`)], + }, + ); + }); +}); + +describe("delegatedThreadStatus", () => { + it("waits while the turn runs and maps how it ended", () => { + const id = ThreadId.make("child"); + assert.strictEqual(DelegationService.delegatedThreadStatus(shell(id, null)), null); + assert.strictEqual( + DelegationService.delegatedThreadStatus( + shell(id, "running", { session: session(id, "running") }), + ), + null, + ); + assert.strictEqual( + DelegationService.delegatedThreadStatus(shell(id, "interrupted")), + "stopped", + ); + assert.strictEqual( + DelegationService.delegatedThreadStatus(shell(id, null, { session: session(id, "error") })), + "failed", + ); + }); +}); diff --git a/apps/server/src/delegation/DelegationService.ts b/apps/server/src/delegation/DelegationService.ts new file mode 100644 index 0000000000000..1a76183bef93d --- /dev/null +++ b/apps/server/src/delegation/DelegationService.ts @@ -0,0 +1,465 @@ +/** + * Lets an agent hand a task to another provider through the `t3-code` MCP + * server. The task runs as its own thread in the caller's working copy, the + * caller's Agents panel tracks it as a subagent, and its final message comes + * back to the caller's thread as a new message once that thread is idle. + * + * Nothing is stored outside the event log. The parent's `task.started` row + * names the child thread, and the result message has an id derived from the + * child, so after a restart the service finds every delegation that has not + * reported back yet and resumes watching it. + * + * @module DelegationService + */ +import { + CommandId, + DEFAULT_PROVIDER_INTERACTION_MODE, + EventId, + isProviderAvailable, + MessageId, + type OrchestrationThreadActivity, + type OrchestrationThreadShell, + type ProviderInstanceId, + type ServerProvider, + ThreadId, +} from "@t3tools/contracts"; +import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; +import { resolveProviderProfileFallbackModelSelection } from "@t3tools/shared/projectSettings"; +import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts"; +import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; +import { threadHasQueuedTurnStart } from "../orchestration/ThreadSettlementPolicy.ts"; +import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts"; +import { forkParked } from "../serverActivation.ts"; + +/** Long enough for a full review; past it the caller is pointed at the child thread. */ +const MAX_RESULT_CHARS = 40_000; +const MAX_TITLE_CHARS = 80; + +const CHILD_PROMPT_FOOTER = + "This task was delegated to you by another agent working in this project, in the same working copy. When you finish, your final message is sent back to that agent as the result, so make it complete and self-contained."; + +export class DelegationError extends Schema.TaggedError()("DelegationError", { + message: Schema.String, +}) {} + +export interface DelegateInput { + readonly parentThreadId: ThreadId; + /** A provider instance id, driver kind, or display name, such as "codex". */ + readonly provider: string; + readonly prompt: string; + readonly title?: string | undefined; + readonly model?: string | undefined; +} + +export interface DelegateResult { + readonly threadId: ThreadId; + readonly title: string; + readonly provider: ProviderInstanceId; + readonly model: string; +} + +export class DelegationService extends Context.Service< + DelegationService, + { + readonly start: () => Effect.Effect; + readonly delegate: (input: DelegateInput) => Effect.Effect; + /** Resolves once every queued check has run; for tests. */ + readonly drain: Effect.Effect; + } +>()("t3/delegation/DelegationService") {} + +interface Delegation { + readonly childThreadId: ThreadId; + readonly parentThreadId: ThreadId; + readonly title: string; + readonly providerName: string; +} + +type DelegationStatus = "completed" | "failed" | "stopped"; + +interface Outcome { + readonly delegation: Delegation; + readonly status: DelegationStatus; + /** The child's final message, or why it has none. */ + readonly text: string; +} + +const startedActivityId = (child: ThreadId) => EventId.make(`delegation:${child}:started`); +const completedActivityId = (child: ThreadId) => EventId.make(`delegation:${child}:completed`); +const resultMessageId = (child: ThreadId) => MessageId.make(`delegation:${child}`); + +/** How a delegated thread stands; `null` while its turn has not finished. */ +export function delegatedThreadStatus( + thread: Pick, +): DelegationStatus | null { + if (thread.session?.status === "starting" || thread.session?.status === "running") return null; + switch (thread.latestTurn?.state) { + case "completed": + return "completed"; + case "error": + return "failed"; + case "interrupted": + return "stopped"; + case "running": + return null; + default: + // No turn yet: still starting, unless the session failed before it could. + return thread.session?.status === "error" ? "failed" : null; + } +} + +/** Whether a message can start a new turn on the parent without steering or blocking one. */ +export function parentCanReceive(thread: OrchestrationThreadShell, now: string): boolean { + return !( + thread.hasPendingApprovals || + thread.hasPendingUserInput || + thread.session?.status === "starting" || + thread.session?.status === "running" || + threadHasQueuedTurnStart(thread, now) + ); +} + +export function resultMessageText(outcome: Outcome): string { + const { delegation, status } = outcome; + const heading = + status === "completed" + ? `${delegation.providerName} finished the delegated task "${delegation.title}".` + : status === "failed" + ? `${delegation.providerName} could not finish the delegated task "${delegation.title}".` + : `${delegation.providerName} was stopped before finishing the delegated task "${delegation.title}".`; + const body = + outcome.text.length > MAX_RESULT_CHARS + ? `${outcome.text.slice(0, MAX_RESULT_CHARS)}\n\n[Truncated. The full result is in the thread "${delegation.title}".]` + : outcome.text; + return `${heading}\n\n${body}`; +} + +const titleFrom = (input: DelegateInput) => { + const source = input.title?.trim() || input.prompt.trim().split("\n")[0]!.trim(); + return source.length > MAX_TITLE_CHARS ? `${source.slice(0, MAX_TITLE_CHARS - 1)}…` : source; +}; + +/** Matches an instance id first, then a driver kind or display name, preferring ready instances. */ +export function findProvider( + providers: ReadonlyArray, + query: string, +): ServerProvider | undefined { + const wanted = query.trim().toLowerCase(); + const usable = providers.filter((provider) => provider.enabled && isProviderAvailable(provider)); + const exact = usable.find((provider) => provider.instanceId.toLowerCase() === wanted); + if (exact) return exact; + const matches = usable.filter( + (provider) => + provider.driver.toLowerCase() === wanted || provider.displayName?.toLowerCase() === wanted, + ); + return matches.find((provider) => provider.status === "ready") ?? matches[0]; +} + +const providerLabel = (provider: ServerProvider) => provider.displayName ?? provider.driver; + +const make = Effect.gen(function* () { + const crypto = yield* Crypto.Crypto; + const engine = yield* OrchestrationEngine.OrchestrationEngineService; + const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; + const providerRegistry = yield* ProviderRegistry.ProviderRegistry; + + const nowIso = DateTime.now.pipe(Effect.map(DateTime.formatIso)); + const commandId = (tag: string) => + crypto.randomUUIDv4.pipe( + Effect.orDie, + Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)), + ); + const failWith = (message: string) => Effect.fail(new DelegationError({ message })); + + /** Delegations whose child is still working, by child thread. */ + const running = new Map(); + /** Finished delegations waiting for their parent to be free, by parent thread. */ + const undelivered = new Map>(); + + const appendParentActivity = ( + parentThreadId: ThreadId, + activity: Omit, + ) => + Effect.gen(function* () { + const createdAt = yield* nowIso; + yield* engine.dispatch({ + type: "thread.activity.append", + commandId: yield* commandId("delegation-activity"), + threadId: parentThreadId, + activity: { ...activity, turnId: null, createdAt }, + createdAt, + }); + }); + + const finalMessageOf = (childThreadId: ThreadId, status: DelegationStatus) => + Effect.gen(function* () { + const thread = yield* snapshots.getThreadDetailById(childThreadId); + if (Option.isNone(thread)) return "The delegated thread no longer exists."; + const messages = thread.value.messages; + const assistantMessageId = thread.value.latestTurn?.assistantMessageId; + const final = + messages.find((message) => message.id === assistantMessageId) ?? + messages.findLast((message) => message.role === "assistant"); + const text = final?.text.trim(); + if (text) return text; + if (status === "failed") { + return thread.value.session?.lastError ?? "The provider reported an error."; + } + return "It produced no final message."; + }); + + const deliver = Effect.fn("DelegationService.deliver")(function* (parentThreadId: ThreadId) { + const outcomes = undelivered.get(parentThreadId); + if (!outcomes || outcomes.length === 0) return; + const parent = yield* snapshots.getThreadShellById(parentThreadId); + if (Option.isNone(parent) || parent.value.archivedAt !== null) { + // Nobody is left to read it; the child thread still holds the result. + undelivered.delete(parentThreadId); + return; + } + if (!parentCanReceive(parent.value, yield* nowIso)) return; + const outcome = outcomes[0]!; + yield* engine.dispatch({ + type: "thread.turn.start", + commandId: yield* commandId("delegation-result"), + threadId: parentThreadId, + message: { + messageId: resultMessageId(outcome.delegation.childThreadId), + role: "user", + text: resultMessageText(outcome), + attachments: [], + }, + runtimeMode: parent.value.runtimeMode, + interactionMode: parent.value.interactionMode, + createdAt: yield* nowIso, + }); + // Dropped only once sent, so a failed send is retried on the parent's next event. + // Several results may be waiting; the next goes once this turn ends. + outcomes.shift(); + if (outcomes.length === 0) undelivered.delete(parentThreadId); + }); + + const settleChild = Effect.fn("DelegationService.settleChild")(function* ( + delegation: Delegation, + ) { + const child = yield* snapshots.getThreadShellById(delegation.childThreadId); + const status = Option.isNone(child) ? "stopped" : delegatedThreadStatus(child.value); + if (status === null) return; + running.delete(delegation.childThreadId); + const text = Option.isNone(child) + ? "The delegated thread was deleted before it finished." + : yield* finalMessageOf(delegation.childThreadId, status); + yield* appendParentActivity(delegation.parentThreadId, { + id: completedActivityId(delegation.childThreadId), + tone: status === "failed" ? "error" : "info", + kind: "task.completed", + summary: "Delegated task finished", + payload: { + taskId: delegation.childThreadId, + status, + summary: text, + delegatedThreadId: delegation.childThreadId, + }, + }); + const outcomes = undelivered.get(delegation.parentThreadId) ?? []; + outcomes.push({ delegation, status, text }); + undelivered.set(delegation.parentThreadId, outcomes); + yield* deliver(delegation.parentThreadId); + }); + + const check = (threadId: ThreadId) => + Effect.gen(function* () { + const delegation = running.get(threadId); + if (delegation) yield* settleChild(delegation); + if (undelivered.has(threadId)) yield* deliver(threadId); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("delegation check failed", { threadId, cause: Cause.pretty(cause) }), + ), + ); + + const worker = yield* makeDrainableWorker(check); + const isWatched = (threadId: ThreadId) => running.has(threadId) || undelivered.has(threadId); + + /** Delegations a previous process started and never reported back. */ + const recover = Effect.gen(function* () { + const started = yield* snapshots.listActivitiesByKind("task.started"); + for (const activity of started) { + const payload = activity.payload as Record | null; + if (!activity.id.startsWith("delegation:") || typeof payload !== "object" || !payload) { + continue; + } + const { delegatedThreadId, parentThreadId, title, role } = payload; + if (typeof delegatedThreadId !== "string" || typeof parentThreadId !== "string") continue; + const childThreadId = ThreadId.make(delegatedThreadId); + const delivered = yield* snapshots.getTurnStartMessage({ + threadId: ThreadId.make(parentThreadId), + messageId: resultMessageId(childThreadId), + }); + if (Option.isSome(delivered)) continue; + running.set(childThreadId, { + childThreadId, + parentThreadId: ThreadId.make(parentThreadId), + title: typeof title === "string" ? title : "Delegated task", + providerName: typeof role === "string" ? role : "The provider", + }); + yield* worker.enqueue(childThreadId); + } + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("could not recover delegations", { cause: Cause.pretty(cause) }), + ), + ); + + const start = Effect.fn("DelegationService.start")(function* () { + yield* forkParked( + Stream.runForEach(engine.streamDomainEvents.pipe(Stream.onStart(recover)), (event) => + // Session and checkpoint events end turns; activities resolve approvals and questions. + (event.type === "thread.session-set" || + event.type === "thread.turn-diff-completed" || + event.type === "thread.activity-appended" || + event.type === "thread.deleted" || + event.type === "thread.archived") && + isWatched(event.payload.threadId) + ? worker.enqueue(event.payload.threadId) + : Effect.void, + ), + ); + }); + + const delegate = Effect.fn("DelegationService.delegate")(function* (input: DelegateInput) { + if (running.has(input.parentThreadId)) { + return yield* failWith( + "This thread is itself a delegated task and cannot delegate further. Do the work here.", + ); + } + const parent = yield* snapshots + .getThreadShellById(input.parentThreadId) + .pipe(Effect.mapError(() => new DelegationError({ message: "Could not read this thread." }))); + if (Option.isNone(parent)) { + return yield* failWith(`Thread ${input.parentThreadId} was not found.`); + } + const providers = yield* providerRegistry.getProviders; + const provider = findProvider(providers, input.provider); + if (!provider) { + const available = providers + .filter((candidate) => candidate.enabled && isProviderAvailable(candidate)) + .map((candidate) => `${candidate.instanceId} (${providerLabel(candidate)})`); + return yield* failWith( + `No available provider matches "${input.provider}". Available: ${available.join(", ") || "none"}.`, + ); + } + let model: string; + if (input.model !== undefined) { + const wanted = input.model.trim().toLowerCase(); + const found = provider.models.find( + (candidate) => + candidate.slug.toLowerCase() === wanted || + candidate.aliases?.some((alias) => alias.toLowerCase() === wanted), + ); + if (!found) { + return yield* failWith( + `${providerLabel(provider)} has no model "${input.model}". Models: ${provider.models.map((candidate) => candidate.slug).join(", ")}.`, + ); + } + model = found.slug; + } else { + const fallback = resolveProviderProfileFallbackModelSelection( + { instanceIds: [provider.instanceId] }, + providers, + ); + if (!fallback) { + return yield* failWith(`${providerLabel(provider)} has no model to run with.`); + } + model = fallback.model; + } + + const title = titleFrom(input); + const childThreadId = ThreadId.make(yield* crypto.randomUUIDv4.pipe(Effect.orDie)); + const modelSelection = { instanceId: provider.instanceId, model }; + const createdAt = yield* nowIso; + const delegation: Delegation = { + childThreadId, + parentThreadId: input.parentThreadId, + title, + providerName: providerLabel(provider), + }; + yield* Effect.gen(function* () { + yield* engine.dispatch({ + type: "thread.create", + commandId: yield* commandId("delegation-thread-create"), + threadId: childThreadId, + projectId: parent.value.projectId, + title, + modelSelection, + runtimeMode: parent.value.runtimeMode, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + branch: parent.value.branch, + worktreePath: parent.value.worktreePath, + createdAt, + }); + // Registered before the turn starts so its first events are not missed. + running.set(childThreadId, delegation); + yield* engine.dispatch({ + type: "thread.turn.start", + commandId: yield* commandId("delegation-turn-start"), + threadId: childThreadId, + message: { + messageId: MessageId.make(yield* crypto.randomUUIDv4.pipe(Effect.orDie)), + role: "user", + text: `${input.prompt}\n\n---\n${CHILD_PROMPT_FOOTER}`, + attachments: [], + }, + modelSelection, + titleSeed: title, + runtimeMode: parent.value.runtimeMode, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt, + }); + yield* appendParentActivity(input.parentThreadId, { + id: startedActivityId(childThreadId), + tone: "info", + kind: "task.started", + summary: "Delegated task started", + payload: { + taskId: childThreadId, + title, + detail: title, + role: delegation.providerName, + model, + // Server-written rows skip ingestion, so they carry its classification stamp themselves. + agentKind: "agent", + delegatedThreadId: childThreadId, + parentThreadId: input.parentThreadId, + }, + }); + }).pipe( + Effect.tapCause(() => Effect.sync(() => running.delete(childThreadId))), + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.failCause(cause as Cause.Cause) + : Effect.logWarning("delegation failed to start", { cause: Cause.pretty(cause) }).pipe( + Effect.andThen(failWith("The delegated thread could not be started.")), + ), + ), + ); + // The turn may already be over if the provider failed fast. + yield* worker.enqueue(childThreadId); + return { threadId: childThreadId, title, provider: provider.instanceId, model }; + }); + + return DelegationService.of({ start, delegate, drain: worker.drain }); +}); + +export const layer = Layer.effect(DelegationService, make); diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 5a807fc328af0..4e8683efe3a6e 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -30,6 +30,8 @@ import { PreviewSnapshotToolkit, PreviewStandardToolkit, } from "./toolkits/preview/tools.ts"; +import { DelegationToolkitHandlersLive } from "./toolkits/delegation/handlers.ts"; +import { DelegationToolkit } from "./toolkits/delegation/tools.ts"; import { PullRequestsToolkitHandlersLive } from "./toolkits/pullRequests/handlers.ts"; import { PullRequestsToolkit } from "./toolkits/pullRequests/tools.ts"; import { @@ -647,6 +649,10 @@ export const PullRequestsToolkitRegistrationLive = McpServer.toolkit(PullRequest Layer.provide(PullRequestsToolkitHandlersLive), ); +export const DelegationToolkitRegistrationLive = McpServer.toolkit(DelegationToolkit).pipe( + Layer.provide(DelegationToolkitHandlersLive), +); + const DeviceStandardToolkitRegistrationLive = McpServer.toolkit(DeviceStandardToolkit).pipe( Layer.provide(DeviceStandardToolkitHandlersLive), ); @@ -670,5 +676,6 @@ const McpTransportLive = McpServer.layerHttp({ export const layer = Layer.mergeAll( PreviewToolkitRegistrationLive, PullRequestsToolkitRegistrationLive, + DelegationToolkitRegistrationLive, DeviceToolkitRegistrationLive, ).pipe(Layer.provideMerge(McpTransportLive)); diff --git a/apps/server/src/mcp/toolkits/delegation/handlers.ts b/apps/server/src/mcp/toolkits/delegation/handlers.ts new file mode 100644 index 0000000000000..43d1320b6726e --- /dev/null +++ b/apps/server/src/mcp/toolkits/delegation/handlers.ts @@ -0,0 +1,18 @@ +import * as Effect from "effect/Effect"; + +import * as DelegationService from "../../../delegation/DelegationService.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import { DelegationToolkit } from "./tools.ts"; + +export const DelegationToolkitHandlersLive = DelegationToolkit.toLayer( + Effect.succeed( + DelegationToolkit.of({ + delegate_task: (input) => + Effect.gen(function* () { + const scope = yield* McpInvocationContext.McpInvocationContext; + const delegation = yield* DelegationService.DelegationService; + return yield* delegation.delegate({ parentThreadId: scope.threadId, ...input }); + }), + }), + ), +); diff --git a/apps/server/src/mcp/toolkits/delegation/tools.ts b/apps/server/src/mcp/toolkits/delegation/tools.ts new file mode 100644 index 0000000000000..dfee909e9d46b --- /dev/null +++ b/apps/server/src/mcp/toolkits/delegation/tools.ts @@ -0,0 +1,51 @@ +import { TrimmedNonEmptyString } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import * as Tool from "effect/unstable/ai/Tool"; +import * as Toolkit from "effect/unstable/ai/Toolkit"; + +import * as DelegationService from "../../../delegation/DelegationService.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; + +export const DelegateTaskInput = Schema.Struct({ + provider: TrimmedNonEmptyString.annotate({ + description: + 'Which provider runs the task: an instance id or provider name such as "codex", "claudeAgent", "cursor" or "opencode". An unknown name fails with the list of available providers.', + }), + prompt: TrimmedNonEmptyString.annotate({ + description: + "The full task for the other agent. It starts with no knowledge of this conversation, so include everything it needs, such as what to review and what to report back.", + }), + title: Schema.optional( + TrimmedNonEmptyString.annotate({ + description: 'A short name for the task, for example "Review current changes".', + }), + ), + model: Schema.optional( + TrimmedNonEmptyString.annotate({ + description: "Model slug to run with. Defaults to the provider's default model.", + }), + ), +}); + +export const DelegateTaskResult = Schema.Struct({ + threadId: Schema.String, + title: Schema.String, + provider: Schema.String, + model: Schema.String, +}); + +const DelegateTaskTool = Tool.make("delegate_task", { + description: + "Hand a task to another coding agent, for example asking Codex to review the current work. It runs as its own T3 Code thread in this same working copy, shows in this thread's Agents panel, and returns immediately. When it finishes, its final message arrives in this thread as a new message, so do not poll or wait for it: tell the user what you delegated, then continue other work or end your turn. Avoid editing the same files while it runs.", + parameters: DelegateTaskInput, + success: DelegateTaskResult, + failure: DelegationService.DelegationError, + dependencies: [McpInvocationContext.McpInvocationContext, DelegationService.DelegationService], +}) + .annotate(Tool.Title, "Delegate task to another agent") + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, false) + .annotate(Tool.OpenWorld, true); + +export const DelegationToolkit = Toolkit.make(DelegateTaskTool); diff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts index d59ed5ce88854..fbf337810af11 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts @@ -17,6 +17,7 @@ import { makeOrchestrationReactor } from "./OrchestrationReactor.ts"; import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts"; import { StorageCleanup } from "../../storageCleanup.ts"; import { AutomationService } from "../../automation/AutomationService.ts"; +import { DelegationService } from "../../delegation/DelegationService.ts"; describe("OrchestrationReactor", () => { let runtime: ManagedRuntime.ManagedRuntime | null = null; @@ -41,6 +42,14 @@ describe("OrchestrationReactor", () => { }, }), ), + Layer.provideMerge( + Layer.mock(DelegationService)({ + start: () => { + started.push("delegations"); + return Effect.void; + }, + }), + ), Layer.provideMerge( Layer.succeed(StorageCleanup, { start: () => { @@ -142,6 +151,7 @@ describe("OrchestrationReactor", () => { "agent-awareness-relay", "storage-cleanup", "automations", + "delegations", ]); await Effect.runPromise(Scope.close(scope, Exit.void)); diff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.ts index 2b0278e1a7eb0..1f138ece2ad00 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationReactor.ts @@ -15,6 +15,7 @@ import * as ThreadPullRequestReactor from "../ThreadPullRequestReactor.ts"; import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts"; import * as StorageCleanup from "../../storageCleanup.ts"; import * as AutomationService from "../../automation/AutomationService.ts"; +import * as DelegationService from "../../delegation/DelegationService.ts"; export const makeOrchestrationReactor = Effect.gen(function* () { const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService; @@ -27,6 +28,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () { const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay; const storageCleanup = yield* StorageCleanup.StorageCleanup; const automations = yield* AutomationService.AutomationService; + const delegations = yield* DelegationService.DelegationService; const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () { yield* providerRuntimeIngestion.start(); @@ -39,6 +41,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () { yield* agentAwarenessRelay.start(); yield* storageCleanup.start(); yield* automations.start(); + yield* delegations.start(); }); return { diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 7c8afb774d10c..9c4d71fe33d59 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -93,6 +93,7 @@ import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor. import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts"; import * as ThreadSettlementReactor from "./orchestration/ThreadSettlementReactor.ts"; import * as AutomationService from "./automation/AutomationService.ts"; +import * as DelegationService from "./delegation/DelegationService.ts"; import * as StorageCleanup from "./storageCleanup.ts"; import * as PullRequestSyncReactor from "./orchestration/PullRequestSyncReactor.ts"; import * as ThreadPullRequestReactor from "./orchestration/ThreadPullRequestReactor.ts"; @@ -268,6 +269,7 @@ const ReactorLayerLive = Layer.empty.pipe( Layer.provideMerge(OrchestrationReactorLive), // Needs the thread deletion reactor, so it sits above the reactors that provide it. Layer.provideMerge(AutomationService.layer), + Layer.provideMerge(DelegationService.layer), Layer.provideMerge(ProviderRuntimeIngestionLive), Layer.provideMerge(ProviderCommandReactorLive), Layer.provideMerge(CheckpointReactorLive), diff --git a/apps/web/src/components/AgentsPanel.tsx b/apps/web/src/components/AgentsPanel.tsx index 7ca5b730b54e4..ca7813db317ba 100644 --- a/apps/web/src/components/AgentsPanel.tsx +++ b/apps/web/src/components/AgentsPanel.tsx @@ -11,6 +11,7 @@ * - Static status dots, DOM-write elapsed timers, plain token counters. */ import { useAtomValue } from "@effect/atom-react"; +import { Link } from "@tanstack/react-router"; import type { AgentPanelModel, AgentPanelWorkflowGroup, @@ -136,8 +137,17 @@ function agentActivityText(agent: RuntimeSubagent): string | null { ); } -/** Flat, non-interactive agent status line. No unfold. */ -function AgentRow({ agent }: { agent: RuntimeSubagent }) { +/** + * Flat agent status line. No unfold. A delegated task links to the thread it + * runs in, which holds its full transcript. + */ +function AgentRow({ + agent, + environmentId = null, +}: { + agent: RuntimeSubagent; + environmentId?: EnvironmentId | null; +}) { const visuals = STATUS_VISUALS[agent.status]; const statusLabel = agent.kind === "subagent_batch" && agent.status === "idle" ? "Idle" : visuals.label; @@ -154,8 +164,10 @@ function AgentRow({ agent }: { agent: RuntimeSubagent }) { agent.activationCount > 1 ? `run ${agent.activationCount}` : null, ].filter((value): value is string => value !== null); - return ( -
+ const rowClassName = + "grid h-[3.875rem] grid-cols-[0.375rem_minmax(0,1fr)_auto] grid-rows-[1.25rem_1.125rem_1rem] items-center gap-x-2 rounded-md px-1.5 py-1"; + const content = ( + <> @@ -187,8 +199,20 @@ function AgentRow({ agent }: { agent: RuntimeSubagent }) { {metadata.join(" · ")} {statusLabel} -
+ ); + if (agent.delegatedThreadId !== null && environmentId !== null) { + return ( + + {content} + + ); + } + return
{content}
; } function workflowIsLive(group: AgentPanelWorkflowGroup): boolean { @@ -561,7 +585,7 @@ export function AgentsPanel({ Direct spawns {model.directAgents.map((agent) => ( - + ))} ) : null} diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index b76e202dfa97b..4811a772f4a67 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -177,6 +177,12 @@ for custom configuration. On web and desktop, use **Agents** to follow work delegated to subagents. +An agent can also hand a task to another provider, for example "ask Codex to +review this". The task runs as its own thread in the same working copy and shows +in **Agents**; select it to open that thread. When it finishes, its final +message arrives in the original thread as a new message, and the agent picks up +from there. Stopping the delegated thread reports back too. + Expand a tool call in the conversation to see its full command and output. Summaries shorten shell wrappers and can still describe the latest call after it finishes; the call's own result shows its status. diff --git a/packages/client-runtime/src/state/subagentRuntime.ts b/packages/client-runtime/src/state/subagentRuntime.ts index e441de32db48f..e6305a883de6b 100644 --- a/packages/client-runtime/src/state/subagentRuntime.ts +++ b/packages/client-runtime/src/state/subagentRuntime.ts @@ -71,6 +71,8 @@ export interface RuntimeSubagent { readonly result: string | null; readonly error: string | null; readonly outputFile: string | null; + /** T3 Code thread the task runs in, when another agent was delegated it. */ + readonly delegatedThreadId: string | null; readonly parentAgentId: string | null; readonly agentIndex: number | null; readonly phaseIndex: number | null; @@ -240,6 +242,7 @@ interface MutableAgent { result: string | null; error: string | null; outputFile: string | null; + delegatedThreadId: string | null; parentAgentId: string | null; agentIndex: number | null; phaseIndex: number | null; @@ -297,6 +300,7 @@ function getOrCreate( result: null, error: null, outputFile: null, + delegatedThreadId: null, parentAgentId: asString(payload.parentAgentId) ?? null, agentIndex: asCount(payload.agentIndex) ?? null, phaseIndex: asCount(payload.phaseIndex) ?? null, @@ -356,6 +360,8 @@ function fillMetadata(agent: MutableAgent, payload: Record): vo } const outputFile = asString(payload.outputFile); if (outputFile) agent.outputFile = outputFile; + const delegatedThreadId = asString(payload.delegatedThreadId); + if (delegatedThreadId) agent.delegatedThreadId = delegatedThreadId; if (Array.isArray(payload.phases)) { const phases: SubagentWorkflowPhase[] = []; for (const entry of payload.phases) { From 39148d15cda992c3a9cb9c40167741bdbfba4dca Mon Sep 17 00:00:00 2001 From: Donald Silveira Date: Wed, 30 Sep 2026 23:22:36 -0300 Subject: [PATCH 2/4] refactor(server): keep delegation helpers private --- apps/server/src/delegation/DelegationService.ts | 6 +++--- apps/server/src/mcp/McpHttpServer.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/server/src/delegation/DelegationService.ts b/apps/server/src/delegation/DelegationService.ts index 1a76183bef93d..49e6cb52f329d 100644 --- a/apps/server/src/delegation/DelegationService.ts +++ b/apps/server/src/delegation/DelegationService.ts @@ -120,7 +120,7 @@ export function delegatedThreadStatus( } /** Whether a message can start a new turn on the parent without steering or blocking one. */ -export function parentCanReceive(thread: OrchestrationThreadShell, now: string): boolean { +function parentCanReceive(thread: OrchestrationThreadShell, now: string): boolean { return !( thread.hasPendingApprovals || thread.hasPendingUserInput || @@ -130,7 +130,7 @@ export function parentCanReceive(thread: OrchestrationThreadShell, now: string): ); } -export function resultMessageText(outcome: Outcome): string { +function resultMessageText(outcome: Outcome): string { const { delegation, status } = outcome; const heading = status === "completed" @@ -151,7 +151,7 @@ const titleFrom = (input: DelegateInput) => { }; /** Matches an instance id first, then a driver kind or display name, preferring ready instances. */ -export function findProvider( +function findProvider( providers: ReadonlyArray, query: string, ): ServerProvider | undefined { diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 4e8683efe3a6e..ca90672315706 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -649,7 +649,7 @@ export const PullRequestsToolkitRegistrationLive = McpServer.toolkit(PullRequest Layer.provide(PullRequestsToolkitHandlersLive), ); -export const DelegationToolkitRegistrationLive = McpServer.toolkit(DelegationToolkit).pipe( +const DelegationToolkitRegistrationLive = McpServer.toolkit(DelegationToolkit).pipe( Layer.provide(DelegationToolkitHandlersLive), ); From bcba4c1d46d40d174294e6ae666477472ae5239c Mon Sep 17 00:00:00 2001 From: Donald Silveira Date: Wed, 30 Sep 2026 23:34:14 -0300 Subject: [PATCH 3/4] fix(server): capture delegated output before turn completion - Finalize buffered assistant output before terminal session updates - Keep delegated threads from spawning nested tasks across restarts --- .../OrchestrationEngineHarness.integration.ts | 14 +- .../orchestrationEngine.integration.test.ts | 116 +++++++++++++ .../src/delegation/DelegationService.test.ts | 90 +++++++++- .../src/delegation/DelegationService.ts | 26 ++- .../Layers/ProviderRuntimeIngestion.ts | 159 +++++++++--------- 5 files changed, 310 insertions(+), 95 deletions(-) diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index f4e3e7320c2f2..0a97f69e6f73f 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -9,6 +9,7 @@ import { type OrchestrationEvent, type OrchestrationThread, type ProviderApprovalDecision, + type ServerProvider, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -189,6 +190,7 @@ export interface OrchestrationIntegrationHarness { readonly engine: OrchestrationEngineShape; readonly snapshotQuery: ProjectionSnapshotQuery["Service"]; readonly providerService: ProviderService["Service"]; + readonly delegation: DelegationService.DelegationService["Service"]; readonly checkpointStore: CheckpointStore.CheckpointStore["Service"]; readonly pendingApprovalRepository: ProjectionPendingApprovalRepository["Service"]; readonly waitForThread: ( @@ -234,6 +236,8 @@ export interface OrchestrationIntegrationHarness { interface MakeOrchestrationIntegrationHarnessOptions { readonly provider?: ProviderDriverKind; readonly realCodex?: boolean; + /** What the provider registry reports, for flows that pick a provider themselves. */ + readonly providers?: ReadonlyArray; /** Tracer for every fiber the harness runtime runs, including reactors. */ readonly tracer?: Tracer.Tracer; } @@ -306,7 +310,7 @@ export const makeOrchestrationIntegrationHarness = ( Layer.provide(AnalyticsService.layerTest), Layer.provide(providerEventLoggersLayer), ); - const providerRegistryLayer = makeProviderRegistryLayer(); + const providerRegistryLayer = makeProviderRegistryLayer(options?.providers); const checkpointStoreLayer = CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistry.layer)); const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive; @@ -388,9 +392,7 @@ export const makeOrchestrationIntegrationHarness = ( Layer.provideMerge( Layer.mock(AutomationService.AutomationService)({ start: () => Effect.void }), ), - Layer.provideMerge( - Layer.mock(DelegationService.DelegationService)({ start: () => Effect.void }), - ), + Layer.provideMerge(DelegationService.layer), Layer.provideMerge( Layer.succeed(StorageCleanup.StorageCleanup, { start: () => Effect.void, @@ -467,6 +469,9 @@ export const makeOrchestrationIntegrationHarness = ( const providerService = yield* tryRuntimePromise("load ProviderService service", () => runtime.runPromise(Effect.service(ProviderService)), ).pipe(Effect.orDie); + const delegation = yield* tryRuntimePromise("load DelegationService service", () => + runtime.runPromise(Effect.service(DelegationService.DelegationService)), + ).pipe(Effect.orDie); const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () => runtime.runPromise(Effect.service(CheckpointStore.CheckpointStore)), ).pipe(Effect.orDie); @@ -614,6 +619,7 @@ export const makeOrchestrationIntegrationHarness = ( engine, snapshotQuery, providerService, + delegation, checkpointStore, pendingApprovalRepository, waitForThread, diff --git a/apps/server/integration/orchestrationEngine.integration.test.ts b/apps/server/integration/orchestrationEngine.integration.test.ts index 68b566e2ee4ab..6cd816aff3d21 100644 --- a/apps/server/integration/orchestrationEngine.integration.test.ts +++ b/apps/server/integration/orchestrationEngine.integration.test.ts @@ -16,6 +16,7 @@ import { ThreadId, ModelSelection, ProviderInstanceId, + type ServerProvider, } from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; import * as Clock from "effect/Clock"; @@ -1416,3 +1417,118 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state", CLAUDE_AGENT_PROVIDER, ), ); + +const delegateToCodex = (input: { + readonly childEvents: TestTurnResponse["events"]; + readonly expectedResult: ReadonlyArray; +}) => + Effect.acquireUseRelease( + makeOrchestrationIntegrationHarness({ + provider: CODEX_PROVIDER, + providers: [ + { + instanceId: defaultInstanceIdForDriver(CODEX_PROVIDER), + driver: CODEX_PROVIDER, + displayName: "Codex", + enabled: true, + installed: true, + status: "ready", + models: [ + { + slug: DEFAULT_MODEL_BY_PROVIDER[CODEX_PROVIDER] ?? DEFAULT_MODEL, + name: "Default", + isCustom: false, + isDefault: true, + }, + ], + } as unknown as ServerProvider, + ], + }), + (harness) => + Effect.gen(function* () { + yield* seedProjectAndThread(harness); + yield* harness.adapterHarness!.queueTurnResponseForNextSession({ + events: input.childEvents, + }); + // The caller's turn that reads the result. + yield* harness.adapterHarness!.queueTurnResponseForNextSession({ events: [] }); + + const { threadId: child } = yield* harness.delegation.delegate({ + parentThreadId: THREAD_ID, + provider: "codex", + prompt: "Review the uncommitted changes.", + title: "Review changes", + }); + + const resultId = asMessageId(`delegation:${child}`); + const parent = yield* harness.waitForThread(THREAD_ID, (thread) => + thread.messages.some((message) => message.id === resultId), + ); + const result = parent.messages.find((message) => message.id === resultId)!; + for (const expected of input.expectedResult) { + assert.include(result.text, expected); + } + assert.notInclude(result.text, "It produced no final message."); + }), + (harness) => harness.dispose, + ).pipe(Effect.provide(NodeServices.layer)); + +it.live("delegation reports a buffered final message once the delegated turn completes", () => + delegateToCodex({ + childEvents: [ + { + type: "turn.started", + ...runtimeBase("evt-delegate-done-1", "2026-02-24T11:00:00.000Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + // No paragraph break, so the text stays buffered until the turn ends. + type: "message.delta", + ...runtimeBase("evt-delegate-done-2", "2026-02-24T11:00:00.100Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + delta: "Found two bugs.", + }, + { + type: "turn.completed", + ...runtimeBase("evt-delegate-done-3", "2026-02-24T11:00:00.200Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + status: "completed", + }, + ], + expectedResult: ['Codex finished the delegated task "Review changes".', "Found two bugs."], + }), +); + +it.live("delegation reports the buffered partial message of an aborted delegated turn", () => + delegateToCodex({ + childEvents: [ + { + type: "turn.started", + ...runtimeBase("evt-delegate-abort-1", "2026-02-24T11:01:00.000Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "message.delta", + ...runtimeBase("evt-delegate-abort-2", "2026-02-24T11:01:00.100Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + delta: "One bug so far.", + }, + { + type: "turn.aborted", + ...runtimeBase("evt-delegate-abort-3", "2026-02-24T11:01:00.200Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + payload: { reason: "Interrupted" }, + }, + ], + expectedResult: [ + 'Codex was stopped before finishing the delegated task "Review changes".', + "One bug so far.", + ], + }), +); diff --git a/apps/server/src/delegation/DelegationService.test.ts b/apps/server/src/delegation/DelegationService.test.ts index 813ead43de9cd..4f54ba161f9cc 100644 --- a/apps/server/src/delegation/DelegationService.test.ts +++ b/apps/server/src/delegation/DelegationService.test.ts @@ -130,7 +130,8 @@ const withService = ( options: { readonly threads?: ReadonlyArray; readonly startedActivities?: ReadonlyArray; - readonly deliveredMessages?: ReadonlyArray; + /** User messages already in the projection, as thread and message id. */ + readonly userMessages?: ReadonlyArray; } = {}, ) => Effect.gen(function* () { @@ -148,7 +149,9 @@ const withService = ( const subscribed = yield* Deferred.make(); const setThread = (thread: OrchestrationThreadShell) => Ref.update(threads, (current) => new Map(current).set(thread.id, thread)); - const delivered = new Set(options.deliveredMessages ?? []); + const userMessages = new Set( + (options.userMessages ?? []).map(([threadId, messageId]) => `${threadId}/${messageId}`), + ); const layer = DelegationService.layer.pipe( Layer.provide( @@ -159,6 +162,9 @@ const withService = ( if (command.type === "thread.create") { yield* setThread(shell(command.threadId, null, { title: command.title })); } + if (command.type === "thread.turn.start") { + userMessages.add(`${command.threadId}/${command.message.messageId}`); + } yield* Queue.offer(commands, command); return { sequence: 1 }; }), @@ -198,9 +204,9 @@ const withService = ( ), ), listActivitiesByKind: () => Effect.succeed(options.startedActivities ?? []), - getTurnStartMessage: ({ messageId }) => + getTurnStartMessage: ({ threadId, messageId }) => Effect.succeed( - delivered.has(messageId) + userMessages.has(`${threadId}/${messageId}`) ? Option.some({ message: { id: messageId, @@ -314,22 +320,84 @@ describe("DelegationService", () => { ), ); - it.effect("a delegated thread cannot delegate further", () => - withService(({ service }) => + it.effect("a delegated thread cannot delegate further, even after its task finished", () => + withService(({ service, setThread, publish, nextCommand }) => Effect.gen(function* () { const { threadId: child } = yield* service.delegate({ parentThreadId: PARENT_ID, provider: "codex", prompt: "Review.", }); - const error = yield* service + for (let i = 0; i < 3; i++) yield* nextCommand; + const nested = service .delegate({ parentThreadId: child, provider: "codex", prompt: "Review again." }) .pipe(Effect.flip); - assert.include(error.message, "cannot delegate further"); + assert.include((yield* nested).message, "cannot delegate further"); + + // Finished and reported, then continued by the user. + yield* setThread(shell(child, "completed", { session: session(child, "ready") })); + yield* publish(sessionSet(child)); + yield* nextCommand; + assert.include((yield* nested).message, "cannot delegate further"); }), ), ); + it.effect("a delegated thread cannot delegate after a restart", () => { + const child = ThreadId.make("reported-child"); + return withService( + ({ service }) => + Effect.gen(function* () { + const error = yield* service + .delegate({ parentThreadId: child, provider: "codex", prompt: "Review again." }) + .pipe(Effect.flip); + assert.include(error.message, "cannot delegate further"); + }), + { + threads: [ + shell(PARENT_ID, "completed", { session: session(PARENT_ID, "ready") }), + shell(child, "completed", { session: session(child, "ready") }), + ], + userMessages: [ + [child, MessageId.make(`delegation-task:${child}`)], + [PARENT_ID, MessageId.make(`delegation:${child}`)], + ], + }, + ); + }); + + it.effect("reports a task stopped before its turn started", () => + withService( + ({ service, setThread, publish, nextCommand }) => + Effect.gen(function* () { + const { threadId: child } = yield* service.delegate({ + parentThreadId: PARENT_ID, + provider: "codex", + prompt: "Review.", + title: "Review changes", + }); + for (let i = 0; i < 3; i++) yield* nextCommand; + + yield* setThread(shell(child, null, { session: session(child, "stopped") })); + yield* publish(sessionSet(child)); + const completed = yield* nextCommand; + assert(completed.type === "thread.activity.append"); + assert.deepInclude(completed.activity.payload as object, { + taskId: child, + status: "stopped", + }); + const result = yield* nextCommand; + assert(result.type === "thread.turn.start"); + assert.strictEqual(result.threadId, PARENT_ID); + assert.include( + result.message.text, + 'Codex was stopped before finishing the delegated task "Review changes".', + ); + }), + { threads: [shell(PARENT_ID, "completed", { session: session(PARENT_ID, "ready") })] }, + ), + ); + it.effect("names the available providers when none matches", () => withService(({ service }) => Effect.gen(function* () { @@ -382,7 +450,7 @@ describe("DelegationService", () => { shell(reported, "completed", { session: session(reported, "ready") }), ], startedActivities: [startedActivity(finished), startedActivity(reported)], - deliveredMessages: [MessageId.make(`delegation:${reported}`)], + userMessages: [[PARENT_ID, MessageId.make(`delegation:${reported}`)]], }, ); }); @@ -402,6 +470,10 @@ describe("delegatedThreadStatus", () => { DelegationService.delegatedThreadStatus(shell(id, "interrupted")), "stopped", ); + assert.strictEqual( + DelegationService.delegatedThreadStatus(shell(id, null, { session: session(id, "stopped") })), + "stopped", + ); assert.strictEqual( DelegationService.delegatedThreadStatus(shell(id, null, { session: session(id, "error") })), "failed", diff --git a/apps/server/src/delegation/DelegationService.ts b/apps/server/src/delegation/DelegationService.ts index 49e6cb52f329d..26989897125ea 100644 --- a/apps/server/src/delegation/DelegationService.ts +++ b/apps/server/src/delegation/DelegationService.ts @@ -98,6 +98,8 @@ interface Outcome { const startedActivityId = (child: ThreadId) => EventId.make(`delegation:${child}:started`); const completedActivityId = (child: ThreadId) => EventId.make(`delegation:${child}:completed`); const resultMessageId = (child: ThreadId) => MessageId.make(`delegation:${child}`); +/** The task message that opens a delegated thread; its presence marks the thread as delegated. */ +const taskMessageId = (child: ThreadId) => MessageId.make(`delegation-task:${child}`); /** How a delegated thread stands; `null` while its turn has not finished. */ export function delegatedThreadStatus( @@ -114,8 +116,16 @@ export function delegatedThreadStatus( case "running": return null; default: - // No turn yet: still starting, unless the session failed before it could. - return thread.session?.status === "error" ? "failed" : null; + // No turn yet: still starting, unless the session failed or stopped before it could. + switch (thread.session?.status) { + case "error": + return "failed"; + case "stopped": + case "interrupted": + return "stopped"; + default: + return null; + } } } @@ -339,7 +349,15 @@ const make = Effect.gen(function* () { }); const delegate = Effect.fn("DelegationService.delegate")(function* (input: DelegateInput) { - if (running.has(input.parentThreadId)) { + // Read from the thread itself, so the rule holds after the task finishes, when the + // user continues it, and across restarts. + const delegated = yield* snapshots + .getTurnStartMessage({ + threadId: input.parentThreadId, + messageId: taskMessageId(input.parentThreadId), + }) + .pipe(Effect.mapError(() => new DelegationError({ message: "Could not read this thread." }))); + if (Option.isSome(delegated)) { return yield* failWith( "This thread is itself a delegated task and cannot delegate further. Do the work here.", ); @@ -416,7 +434,7 @@ const make = Effect.gen(function* () { commandId: yield* commandId("delegation-turn-start"), threadId: childThreadId, message: { - messageId: MessageId.make(yield* crypto.randomUUIDv4.pipe(Effect.orDie)), + messageId: taskMessageId(childThreadId), role: "user", text: `${input.prompt}\n\n---\n${CHILD_PROMPT_FOOTER}`, attachments: [], diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 2584a75782004..6006f391e7a65 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -1864,6 +1864,87 @@ const make = Effect.gen(function* () { ? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId) : null; + // Save the turn's output before its terminal session state: leaving + // "running" is what readers take as the turn being over, so the final + // message must already be there. + if (isTerminalTurn) { + const turnId = toTurnId(event.turnId); + if (turnId) { + const userInputActivities = + yield* projectionThreadActivityRepository.listUserInputLifecycleByThreadId({ + threadId: thread.id, + }); + const pendingRequestIds = new Set(); + for (const activity of userInputActivities) { + const payload = + typeof activity.payload === "object" && activity.payload !== null + ? (activity.payload as Record) + : null; + const requestId = payload?.requestId; + if (typeof requestId !== "string") continue; + if ( + activity.kind === "user-input.requested" && + activity.turnId === turnId && + payload?.responseMode !== "message" + ) { + pendingRequestIds.add(requestId); + } else if (activity.kind === "user-input.resolved") { + pendingRequestIds.delete(requestId); + } + } + // A terminal turn cannot accept native callback answers. Message-mode + // questions may outlive that turn and still accept a later user message. + for (const requestId of pendingRequestIds) { + yield* orchestrationEngine.dispatch({ + type: "thread.activity.append", + commandId: yield* providerCommandId(event, "terminal-user-input-resolved"), + threadId: thread.id, + activity: { + id: EventId.make(`${event.eventId}:user-input-resolved:${requestId}`), + createdAt: now, + tone: "info", + kind: "user-input.resolved", + summary: "User input dismissed", + payload: { requestId }, + turnId, + }, + createdAt: now, + }); + } + const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId); + yield* Effect.forEach( + assistantMessageIds, + (assistantMessageId) => + getThreadMessageById(thread.id, assistantMessageId).pipe( + Effect.flatMap((existingMessage) => + finalizeAssistantMessage({ + event, + threadId: thread.id, + messageId: assistantMessageId, + turnId, + createdAt: now, + commandTag: "assistant-complete-finalize", + finalDeltaCommandTag: "assistant-delta-finalize-fallback", + hasProjectedMessage: existingMessage !== undefined, + }), + ), + ), + { concurrency: 1 }, + ).pipe(Effect.asVoid); + yield* clearAssistantMessageIdsForTurn(thread.id, turnId); + yield* clearAssistantSegmentStateForTurn(thread.id, turnId); + yield* clearAssistantSegmentStateForTurn(thread.id, turnId, "reasoning"); + + yield* finalizeBufferedProposedPlan({ + event, + threadId: thread.id, + planId: proposedPlanIdForTurn(thread.id, turnId), + turnId, + updatedAt: now, + }); + } + } + if ( event.type === "session.started" || event.type === "session.state.changed" || @@ -2347,84 +2428,6 @@ const make = Effect.gen(function* () { }); } - if (isTerminalTurn) { - const turnId = toTurnId(event.turnId); - if (turnId) { - const userInputActivities = - yield* projectionThreadActivityRepository.listUserInputLifecycleByThreadId({ - threadId: thread.id, - }); - const pendingRequestIds = new Set(); - for (const activity of userInputActivities) { - const payload = - typeof activity.payload === "object" && activity.payload !== null - ? (activity.payload as Record) - : null; - const requestId = payload?.requestId; - if (typeof requestId !== "string") continue; - if ( - activity.kind === "user-input.requested" && - activity.turnId === turnId && - payload?.responseMode !== "message" - ) { - pendingRequestIds.add(requestId); - } else if (activity.kind === "user-input.resolved") { - pendingRequestIds.delete(requestId); - } - } - // A terminal turn cannot accept native callback answers. Message-mode - // questions may outlive that turn and still accept a later user message. - for (const requestId of pendingRequestIds) { - yield* orchestrationEngine.dispatch({ - type: "thread.activity.append", - commandId: yield* providerCommandId(event, "terminal-user-input-resolved"), - threadId: thread.id, - activity: { - id: EventId.make(`${event.eventId}:user-input-resolved:${requestId}`), - createdAt: now, - tone: "info", - kind: "user-input.resolved", - summary: "User input dismissed", - payload: { requestId }, - turnId, - }, - createdAt: now, - }); - } - const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId); - yield* Effect.forEach( - assistantMessageIds, - (assistantMessageId) => - getThreadMessageById(thread.id, assistantMessageId).pipe( - Effect.flatMap((existingMessage) => - finalizeAssistantMessage({ - event, - threadId: thread.id, - messageId: assistantMessageId, - turnId, - createdAt: now, - commandTag: "assistant-complete-finalize", - finalDeltaCommandTag: "assistant-delta-finalize-fallback", - hasProjectedMessage: existingMessage !== undefined, - }), - ), - ), - { concurrency: 1 }, - ).pipe(Effect.asVoid); - yield* clearAssistantMessageIdsForTurn(thread.id, turnId); - yield* clearAssistantSegmentStateForTurn(thread.id, turnId); - yield* clearAssistantSegmentStateForTurn(thread.id, turnId, "reasoning"); - - yield* finalizeBufferedProposedPlan({ - event, - threadId: thread.id, - planId: proposedPlanIdForTurn(thread.id, turnId), - turnId, - updatedAt: now, - }); - } - } - if (event.type === "session.exited") { yield* clearTurnStateForSession(thread.id); } From b527e83a7ed8e7c21a34480966da0fa6af2acdca Mon Sep 17 00:00:00 2001 From: Donald Silveira Date: Wed, 30 Sep 2026 23:53:34 -0300 Subject: [PATCH 4/4] fix(server): preserve delegated output on reconnect and errors --- .../orchestrationEngine.integration.test.ts | 78 ++++++++++++ .../src/delegation/DelegationService.test.ts | 113 +++++++++++++++--- .../src/delegation/DelegationService.ts | 50 ++++---- .../Layers/ProjectionPipeline.ts | 3 +- .../Layers/ProviderRuntimeIngestion.ts | 13 ++ 5 files changed, 219 insertions(+), 38 deletions(-) diff --git a/apps/server/integration/orchestrationEngine.integration.test.ts b/apps/server/integration/orchestrationEngine.integration.test.ts index 6cd816aff3d21..058ef55962271 100644 --- a/apps/server/integration/orchestrationEngine.integration.test.ts +++ b/apps/server/integration/orchestrationEngine.integration.test.ts @@ -1532,3 +1532,81 @@ it.live("delegation reports the buffered partial message of an aborted delegated ], }), ); + +it.live("delegation reports an aborted turn as stopped when the session was reconnecting", () => + delegateToCodex({ + childEvents: [ + { + type: "turn.started", + ...runtimeBase("evt-delegate-reconnect-1", "2026-02-24T11:02:00.000Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "message.delta", + ...runtimeBase("evt-delegate-reconnect-2", "2026-02-24T11:02:00.100Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + delta: "One bug so far.", + }, + { + // Codex reports a reconnect as "starting" while the turn stays active. + type: "session.state.changed", + ...runtimeBase("evt-delegate-reconnect-3", "2026-02-24T11:02:00.150Z"), + threadId: THREAD_ID, + payload: { state: "starting" }, + }, + { + type: "turn.aborted", + ...runtimeBase("evt-delegate-reconnect-4", "2026-02-24T11:02:00.200Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + payload: { reason: "Interrupted" }, + }, + ], + expectedResult: [ + 'Codex was stopped before finishing the delegated task "Review changes".', + "One bug so far.", + ], + }), +); + +it.live("delegation reports buffered output when an error precedes the failed completion", () => + delegateToCodex({ + childEvents: [ + { + type: "turn.started", + ...runtimeBase("evt-delegate-error-1", "2026-02-24T11:03:00.000Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + }, + { + type: "message.delta", + ...runtimeBase("evt-delegate-error-2", "2026-02-24T11:03:00.100Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + delta: "Found one bug.", + }, + { + // Codex queues the usage-limit error ahead of the failed turn/completed. + type: "runtime.error", + ...runtimeBase("evt-delegate-error-3", "2026-02-24T11:03:00.150Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + payload: { message: "Usage limit reached.", class: "provider_error" }, + }, + { + type: "turn.completed", + ...runtimeBase("evt-delegate-error-4", "2026-02-24T11:03:00.200Z"), + threadId: THREAD_ID, + turnId: FIXTURE_TURN_ID, + status: "failed", + }, + ], + expectedResult: [ + 'Codex could not finish the delegated task "Review changes".', + "Found one bug.", + "Usage limit reached.", + ], + }), +); diff --git a/apps/server/src/delegation/DelegationService.test.ts b/apps/server/src/delegation/DelegationService.test.ts index 4f54ba161f9cc..1e5ab9b2443e3 100644 --- a/apps/server/src/delegation/DelegationService.test.ts +++ b/apps/server/src/delegation/DelegationService.test.ts @@ -8,6 +8,7 @@ import { type OrchestrationCommand, type OrchestrationEvent, type OrchestrationLatestTurn, + type OrchestrationMessage, type OrchestrationSession, type OrchestrationThread, type OrchestrationThreadActivity, @@ -116,6 +117,16 @@ const sessionSet = (threadId: ThreadId): OrchestrationEvent => ({ payload: { threadId, session: session(threadId, "ready") }, }); +const assistantMessage = (id: string, text: string): OrchestrationMessage => ({ + id: MessageId.make(id), + role: "assistant", + text, + turnId: TurnId.make("turn-1"), + streaming: false, + createdAt: AT, + updatedAt: AT, +}); + interface Harness { readonly service: DelegationService.DelegationService["Service"]; readonly setThread: (thread: OrchestrationThreadShell) => Effect.Effect; @@ -132,6 +143,10 @@ const withService = ( readonly startedActivities?: ReadonlyArray; /** User messages already in the projection, as thread and message id. */ readonly userMessages?: ReadonlyArray; + /** Threads a previous process created as delegated tasks. */ + readonly delegatedThreads?: ReadonlyArray; + /** What every thread's detail holds; one final answer by default. */ + readonly messages?: ReadonlyArray; } = {}, ) => Effect.gen(function* () { @@ -152,6 +167,13 @@ const withService = ( const userMessages = new Set( (options.userMessages ?? []).map(([threadId, messageId]) => `${threadId}/${messageId}`), ); + /** The command id of each thread's creation event. */ + const createdBy = new Map( + (options.delegatedThreads ?? []).map((threadId) => [ + threadId, + CommandId.make(`server:delegation-thread-create:${threadId}`), + ]), + ); const layer = DelegationService.layer.pipe( Layer.provide( @@ -160,6 +182,7 @@ const withService = ( dispatch: (command) => Effect.gen(function* () { if (command.type === "thread.create") { + createdBy.set(command.threadId, command.commandId); yield* setThread(shell(command.threadId, null, { title: command.title })); } if (command.type === "thread.turn.start") { @@ -168,6 +191,11 @@ const withService = ( yield* Queue.offer(commands, command); return { sequence: 1 }; }), + // Only the first event's command id is read. + readThreadEvents: ({ threadId }) => { + const commandId = createdBy.get(threadId); + return commandId ? Stream.make({ ...sessionSet(threadId), commandId }) : Stream.empty; + }, streamDomainEvents: Stream.unwrap( PubSub.subscribe(events).pipe( Effect.tap(() => Deferred.succeed(subscribed, undefined)), @@ -185,17 +213,7 @@ const withService = ( Option.map((thread): OrchestrationThread => ({ ...thread, deletedAt: null, - messages: [ - { - id: MessageId.make("final"), - role: "assistant", - text: "Found two bugs.", - turnId: TurnId.make("turn-1"), - streaming: false, - createdAt: AT, - updatedAt: AT, - }, - ], + messages: options.messages ?? [assistantMessage("final", "Found two bugs.")], proposedPlans: [], activities: [], checkpoints: [], @@ -343,7 +361,8 @@ describe("DelegationService", () => { ), ); - it.effect("a delegated thread cannot delegate after a restart", () => { + // Its messages are gone too, as after a rewind to the start. + it.effect("a delegated thread cannot delegate after a restart or a rewind", () => { const child = ThreadId.make("reported-child"); return withService( ({ service }) => @@ -358,14 +377,76 @@ describe("DelegationService", () => { shell(PARENT_ID, "completed", { session: session(PARENT_ID, "ready") }), shell(child, "completed", { session: session(child, "ready") }), ], - userMessages: [ - [child, MessageId.make(`delegation-task:${child}`)], - [PARENT_ID, MessageId.make(`delegation:${child}`)], - ], + userMessages: [[PARENT_ID, MessageId.make(`delegation:${child}`)]], + delegatedThreads: [child], + messages: [], }, ); }); + const settleChild = ( + service: Harness["service"], + harness: Pick, + latestTurn: OrchestrationLatestTurn["state"], + childSession: OrchestrationSession["status"], + lastError: string | null = null, + ) => + Effect.gen(function* () { + const { threadId: child } = yield* service.delegate({ + parentThreadId: PARENT_ID, + provider: "codex", + prompt: "Review.", + title: "Review changes", + }); + for (let i = 0; i < 3; i++) yield* harness.nextCommand; + yield* harness.setThread( + shell(child, latestTurn, { session: { ...session(child, childSession), lastError } }), + ); + yield* harness.publish(sessionSet(child)); + yield* harness.nextCommand; + const result = yield* harness.nextCommand; + assert(result.type === "thread.turn.start"); + return result.message.text; + }); + + it.effect("reports the turn's last message even when the turn points at earlier commentary", () => + withService( + ({ service, ...harness }) => + Effect.gen(function* () { + const text = yield* settleChild(service, harness, "completed", "ready"); + assert.include(text, "Found two bugs."); + assert.notInclude(text, "Looking at the diff."); + }), + { + threads: [shell(PARENT_ID, "completed", { session: session(PARENT_ID, "ready") })], + // The shell's turn points at "final"; here that id is the commentary. + messages: [ + assistantMessage("final", "Looking at the diff."), + assistantMessage("answer", "Found two bugs."), + ], + }, + ), + ); + + it.effect("a failed task reports its partial message with the error", () => + withService( + ({ service, ...harness }) => + Effect.gen(function* () { + const text = yield* settleChild( + service, + harness, + "error", + "error", + "Usage limit reached.", + ); + assert.include(text, 'Codex could not finish the delegated task "Review changes".'); + assert.include(text, "Found two bugs."); + assert.include(text, "Error: Usage limit reached."); + }), + { threads: [shell(PARENT_ID, "completed", { session: session(PARENT_ID, "ready") })] }, + ), + ); + it.effect("reports a task stopped before its turn started", () => withService( ({ service, setThread, publish, nextCommand }) => diff --git a/apps/server/src/delegation/DelegationService.ts b/apps/server/src/delegation/DelegationService.ts index 26989897125ea..748929a202197 100644 --- a/apps/server/src/delegation/DelegationService.ts +++ b/apps/server/src/delegation/DelegationService.ts @@ -98,8 +98,8 @@ interface Outcome { const startedActivityId = (child: ThreadId) => EventId.make(`delegation:${child}:started`); const completedActivityId = (child: ThreadId) => EventId.make(`delegation:${child}:completed`); const resultMessageId = (child: ThreadId) => MessageId.make(`delegation:${child}`); -/** The task message that opens a delegated thread; its presence marks the thread as delegated. */ -const taskMessageId = (child: ThreadId) => MessageId.make(`delegation-task:${child}`); +/** Tags the command that creates a delegated thread; its creation event keeps it for good. */ +const CREATE_COMMAND_TAG = "delegation-thread-create"; /** How a delegated thread stands; `null` while its turn has not finished. */ export function delegatedThreadStatus( @@ -216,17 +216,15 @@ const make = Effect.gen(function* () { Effect.gen(function* () { const thread = yield* snapshots.getThreadDetailById(childThreadId); if (Option.isNone(thread)) return "The delegated thread no longer exists."; - const messages = thread.value.messages; - const assistantMessageId = thread.value.latestTurn?.assistantMessageId; - const final = - messages.find((message) => message.id === assistantMessageId) ?? - messages.findLast((message) => message.role === "assistant"); + const assistant = thread.value.messages.filter((message) => message.role === "assistant"); + const turnId = thread.value.latestTurn?.turnId; + // The turn's last message, not its message pointer: a checkpoint captured before the + // answer landed can leave the pointer on earlier commentary. + const final = assistant.findLast((message) => message.turnId === turnId) ?? assistant.at(-1); const text = final?.text.trim(); - if (text) return text; - if (status === "failed") { - return thread.value.session?.lastError ?? "The provider reported an error."; - } - return "It produced no final message."; + if (status !== "failed") return text || "It produced no final message."; + const error = thread.value.session?.lastError ?? "The provider reported an error."; + return text ? `${text}\n\nError: ${error}` : error; }); const deliver = Effect.fn("DelegationService.deliver")(function* (parentThreadId: ThreadId) { @@ -349,15 +347,25 @@ const make = Effect.gen(function* () { }); const delegate = Effect.fn("DelegationService.delegate")(function* (input: DelegateInput) { - // Read from the thread itself, so the rule holds after the task finishes, when the - // user continues it, and across restarts. - const delegated = yield* snapshots - .getTurnStartMessage({ + // Read from the thread's creation event, so the rule holds after the task finishes, when + // the user continues or rewinds it, and across restarts. + const created = yield* engine + .readThreadEvents({ threadId: input.parentThreadId, - messageId: taskMessageId(input.parentThreadId), + fromSequenceExclusive: 0, + toSequenceInclusive: Number.MAX_SAFE_INTEGER, + limit: 1, }) - .pipe(Effect.mapError(() => new DelegationError({ message: "Could not read this thread." }))); - if (Option.isSome(delegated)) { + .pipe( + Stream.runHead, + Effect.mapError(() => new DelegationError({ message: "Could not read this thread." })), + ); + if ( + Option.exists( + created, + (event) => event.commandId?.startsWith(`server:${CREATE_COMMAND_TAG}:`) === true, + ) + ) { return yield* failWith( "This thread is itself a delegated task and cannot delegate further. Do the work here.", ); @@ -416,7 +424,7 @@ const make = Effect.gen(function* () { yield* Effect.gen(function* () { yield* engine.dispatch({ type: "thread.create", - commandId: yield* commandId("delegation-thread-create"), + commandId: yield* commandId(CREATE_COMMAND_TAG), threadId: childThreadId, projectId: parent.value.projectId, title, @@ -434,7 +442,7 @@ const make = Effect.gen(function* () { commandId: yield* commandId("delegation-turn-start"), threadId: childThreadId, message: { - messageId: taskMessageId(childThreadId), + messageId: MessageId.make(yield* crypto.randomUUIDv4.pipe(Effect.orDie)), role: "user", text: `${input.prompt}\n\n---\n${CHILD_PROMPT_FOOTER}`, attachments: [], diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 1acb3c360b15f..75c119b9b15fd 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -1593,9 +1593,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti const session = yield* projectionThreadSessionRepository.getByThreadId({ threadId: event.payload.threadId, }); + // A reconnecting session reports "starting" but still owns its turn. const turnStillRunning = Option.isSome(session) && - session.value.status === "running" && + (session.value.status === "running" || session.value.status === "starting") && session.value.activeTurnId === event.payload.turnId; const settlesTurn = !event.payload.streaming && !turnStillRunning; const existingTurn = yield* projectionTurnRepository.getByTurnId({ diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 6006f391e7a65..6a8e1746572b2 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -2440,6 +2440,19 @@ const make = Effect.gen(function* () { : activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId); if (shouldApplyRuntimeError) { + // The error session ends the turn for readers, and Codex sends its + // turn.completed only after this. Flush, not finalize: if the + // provider carries on, the message keeps streaming. + const erroredTurnId = eventTurnId ?? activeTurnId; + if (erroredTurnId !== null) { + yield* flushBufferedAssistantMessagesForTurn({ + event, + threadId: thread.id, + turnId: erroredTurnId, + createdAt: now, + commandTag: "assistant-delta-flush-on-runtime-error", + }); + } yield* orchestrationEngine.dispatch({ type: "thread.session.set", commandId: yield* providerCommandId(event, "runtime-error-session-set"),