diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 8dcd025c82481..3f1c51581c21d 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -1471,6 +1471,27 @@ const make = Effect.gen(function* () { : Effect.void; }; + // A background subagent keeps calling tools after the run that started it settles. Its + // delegations join that latest run, whose completion cohort wakes the thread once they finish. + const backgroundSubagentRun = Effect.fn("OrchestratorMcpService.backgroundSubagentRun")( + function* (scope: McpInvocationScope, threadId: ThreadId) { + const shell = yield* threadManagement + .getThreadShell(threadId) + .pipe(Effect.mapError(threadManagementFailure)); + if ( + shell?.activeRunId !== null || + shell.latestRunId === null || + !isLiveCallerShell(shell, scope.thread?.providerInstanceId) + ) { + return undefined; + } + const { runs } = yield* loadThreadRecords(threadId, ["runs"], { + runIds: [shell.latestRunId], + }); + return runs[0]; + }, + ); + const loadReadableThread = Effect.fn("OrchestratorMcpService.loadReadableThread")(function* ( scope: McpInvocationScope, threadId: ThreadId, @@ -2703,9 +2724,9 @@ const make = Effect.gen(function* () { "A local task runs in this thread's project. Omit target.projectId, or pass target.environmentId to run it in that environment's project.", ); } - const parentRun = parent.runs - .filter(ThreadManagementService.isActiveRun) - .toSorted((left, right) => right.ordinal - left.ordinal)[0]; + const parentRun = + ThreadManagementService.latestActiveRun(parent) ?? + (yield* backgroundSubagentRun(scope, parent.thread.id)); if ( parentRun === undefined || parentRun.rootNodeId === null || diff --git a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts index bbc3fbf06940d..aff11dacad26e 100644 --- a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts +++ b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts @@ -17,6 +17,7 @@ import { ThreadId, TurnItemId, type OrchestrationV2DomainEvent, + type ServerProvider, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -57,6 +58,15 @@ const layerOrchestratorService = OrchestratorMcpService.layer.pipe( const driver = ProviderDriverKind.make("claudeAgent"); const instanceId = ProviderInstanceId.make("claudeAgent"); const modelSelection = { instanceId, model: "claude-test" }; +const provider = { + instanceId, + driver, + enabled: true, + installed: true, + status: "ready", + auth: { status: "authenticated" }, + models: [{ slug: modelSelection.model, name: modelSelection.model, isCustom: false }], +} as unknown as ServerProvider; // Cancellation races with turn completion and checkpoint capture; "recorded" restarts before the Stop outbox runs. const cancelBackgroundOnlyTask = ( @@ -66,7 +76,14 @@ const cancelBackgroundOnlyTask = ( remote = false, }: { readonly remote?: boolean; - readonly cancelAt?: "settled" | "checkpoint" | "turn" | "recorded" | "monitor" | "refused"; + readonly cancelAt?: + | "settled" + | "checkpoint" + | "turn" + | "recorded" + | "monitor" + | "refused" + | "delegate"; } = {}, ) => Effect.scoped( @@ -214,7 +231,9 @@ const cancelBackgroundOnlyTask = ( Layer.provide( Layer.mergeAll( layerAdapters, - Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([provider]), + }), Layer.mock(ProjectService.ProjectService)({}), Layer.mock(SecretRequests.SecretRequests)({}), Layer.mock(RemoteDelegation.RemoteDelegation)({}), @@ -529,6 +548,16 @@ const cancelBackgroundOnlyTask = ( capabilities: new Set(["orchestration"]), issuedAt: 1, }; + if (cancelAt === "delegate") { + // The child's run settled while its native subagent still runs, and that subagent delegates. + const childScope: McpInvocationScope = { + ...scope, + thread: { ...scope.thread!, threadId: task.childThreadId! }, + }; + const delegated = yield* service.delegateTask(childScope, { task: "Reply OK." }); + assert.equal(delegated.status, "starting"); + return undefined; + } const before = yield* service.taskStatus(scope, task.id); assert.equal(before.status, "running"); assert.equal(before.workState, turnSettled ? "waiting_for_children" : "working"); @@ -694,3 +723,7 @@ it.effect("a refused descendant stop does not settle or dispose its parent task" it.effect("task_cancel stops a remote descendant without reacquiring its parent lock", () => cancelBackgroundOnlyTask("command", { remote: true }), ); + +it.effect("a native background subagent delegates after its parent's run completes", () => + cancelBackgroundOnlyTask("subagent", { cancelAt: "delegate" }), +); diff --git a/apps/server/src/mcp/threadAccess.ts b/apps/server/src/mcp/threadAccess.ts index f387f481e24a6..d21495f0ff7c7 100644 --- a/apps/server/src/mcp/threadAccess.ts +++ b/apps/server/src/mcp/threadAccess.ts @@ -19,6 +19,7 @@ import { threadLinkCandidates, threadLinkRefs, } from "@t3tools/shared/threadLinks"; +import { hasPendingBackgroundSubagent } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; @@ -199,10 +200,7 @@ export const isLiveCallerShell = ( shell.archivedAt === null && shell.providerInstanceId === providerInstanceId && (shell.activeRunId !== null || - (shell.pendingBackgroundTasks?.some( - (task) => task.kind === "subagent" && task.providerInstanceId === providerInstanceId, - ) ?? - false)); + hasPendingBackgroundSubagent(shell.pendingBackgroundTasks, providerInstanceId)); /** Thread callers need a live run or its background subagent in an unarchived thread. OAuth clients rely on their session and ceiling. */ export function assertLiveCaller({ caller, scope }: Caller) { diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 5cd22ccfa5bb6..0a2d5ce427a9f 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -92,6 +92,7 @@ import { recordThreadOpen } from "@t3tools/shared/paletteSearch"; import { backgroundWorkHoldsCompletion, derivePendingBackgroundWork, + hasPendingBackgroundSubagent, pendingBackgroundTurnItems, } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import * as Context from "effect/Context"; @@ -9507,6 +9508,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* Ref.update(effects, (existing) => [...existing, pendingEffect]); }); + // A native background subagent keeps working, and delegating, after the latest run settles. + const backgroundSubagentOutlivesRun = (run: OrchestrationV2Run) => + projectionStore.getThreadShell(run.threadId).pipe( + Effect.map( + (shell) => + shell !== null && + shell.archivedAt === null && + shell.activeRunId === null && + shell.latestRunId === run.id && + hasPendingBackgroundSubagent(shell.pendingBackgroundTasks, run.providerInstanceId), + ), + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: run.threadId, cause }), + ), + ); + const dispatchDelegatedTaskRequest = Effect.fn("orchestrationV2.dispatch.delegatedTaskRequest")( function* ( command: Extract, @@ -9523,7 +9540,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const parentRun = parentProjection.runs.find( (candidate) => candidate.id === command.parentRunId, ); - if (parentRun === undefined || !isActiveRun(parentRun)) { + if ( + parentRun === undefined || + !(isActiveRun(parentRun) || (yield* backgroundSubagentOutlivesRun(parentRun))) + ) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index f834c7cc355b9..d83fdc92f111b 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -1602,8 +1602,20 @@ describe("deriveMessagesTimelineRows", () => { message("steer", 10, "user", "steer"), work("work-after-steer", 15), message("final", 30, "assistant"), + { + kind: "event", + id: "late-subagent", + createdAt: time(50), + projectedItem: { item: { type: "subagent", status: "completed", runId } } as never, + }, ], - latestRun: { runId, status: "completed", startedAt: time(0), completedAt: time(30) }, + // A later wake run is the latest, so this turn's times come from its entries. + latestRun: { + runId: RunId.make("wake-run"), + status: "completed", + startedAt: time(55), + completedAt: time(58), + }, isWorking: false, expandedRunIds, turnDiffSummaries: [], @@ -1618,6 +1630,7 @@ describe("deriveMessagesTimelineRows", () => { "steer", `turn-fold:${segmentKey}`, "final", + "late-subagent", ]); expect(collapsed[1]).toMatchObject({ label: "Worked for 30s" }); expect(collapsed[3]).toMatchObject({ label: "Continued for 20s", createdAt: time(10) }); @@ -1629,6 +1642,7 @@ describe("deriveMessagesTimelineRows", () => { `turn-fold:${segmentKey}`, "work-after-steer", "final", + "late-subagent", ]); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 8d282aff42689..5e3e26bf4f389 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -1236,8 +1236,20 @@ function deriveTurnFolds(input: { const isLatestInterruptedTurn = input.latestRun?.runId === runId && input.latestRun.status === "interrupted"; // A turn cut short by a steer leaves trailing work entries behind its - // terminal message — take whichever ended last. - const lastEntryEnd = timelineEntryEnd(lastEntry); + // terminal message — take whichever ended last. A subagent card after it was + // spawned by background work once the turn settled, so it adds no turn time. + const lateSubagentIds = new Set( + group.entries.flatMap((entry, index) => + index > terminalEntryIndex && + entry.kind === "event" && + entry.projectedItem.item.type === "subagent" + ? [entry.id] + : [], + ), + ); + const lastTurnEntry = + group.entries.findLast((entry) => !lateSubagentIds.has(entry.id)) ?? lastEntry; + const lastEntryEnd = timelineEntryEnd(lastTurnEntry); const elapsedMs = input.latestRun?.runId === runId && input.latestRun.startedAt && input.latestRun.completedAt ? computeElapsedMs(input.latestRun.startedAt, input.latestRun.completedAt) @@ -1276,8 +1288,10 @@ function deriveTurnFolds(input: { if (anchorEntry === undefined || !hidesNonCompactionWork(entries)) continue; const segmentMs = computeElapsedMs( steer.createdAt, - entries.map(timelineEntryEnd).reduce(maxIsoTimestamp, null) ?? - steer.createdAt, + entries + .filter((entry) => !lateSubagentIds.has(entry.id)) + .map(timelineEntryEnd) + .reduce(maxIsoTimestamp, null) ?? steer.createdAt, ); foldsByAnchorEntryId.set(anchorEntry.id, { runId: RunId.make(`${runId}:steer:${steer.id}`), diff --git a/packages/shared/src/orchestrationV2PendingBackgroundWork.ts b/packages/shared/src/orchestrationV2PendingBackgroundWork.ts index 3b25db88acecd..8928d30cba0bb 100644 --- a/packages/shared/src/orchestrationV2PendingBackgroundWork.ts +++ b/packages/shared/src/orchestrationV2PendingBackgroundWork.ts @@ -87,6 +87,18 @@ export function deriveBlockedOnThreadWait(input: { return hasWait; } +/** A provider instance's background subagent outlives its run and still calls tools. */ +export function hasPendingBackgroundSubagent( + tasks: ReadonlyArray | undefined, + providerInstanceId: OrchestrationV2ProviderThread["providerInstanceId"] | undefined, +): boolean { + return ( + tasks?.some( + (task) => task.kind === "subagent" && task.providerInstanceId === providerInstanceId, + ) ?? false + ); +} + export function backgroundWorkHoldsCompletion( tasks: ReadonlyArray>, ): boolean {