diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 5a936dadef325..b026f41c1be40 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -55,6 +55,14 @@ import { advertisedJsonSchema } from "./advertisedJsonSchema.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; import * as McpToolAccess from "./McpToolAccess.ts"; import * as McpToolExposure from "./McpToolExposure.ts"; +import { + failureFingerprintFromExit, + loopGuardScopeKey, + loopGuardTtlMs, + makeToolCallLoopGuard, + toolCallLoopBlockedResult, + toolCallLoopKey, +} from "./McpToolLoopGuard.ts"; import * as McpWebhookTransport from "./McpWebhookTransport.ts"; import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender"; import { compactT3McpToolOutput } from "@t3tools/shared/toolOutput"; @@ -1305,6 +1313,52 @@ const withToolResultCapture = Effect.fn("McpHttpServer.withToolResultCapture")(f return yield* registration.pipe(Effect.provideService(McpServer.McpServer, capturingServer)); }); +const withToolLoopGuard = Effect.fn("McpHttpServer.withToolLoopGuard")(function* ( + registration: Effect.Effect, +) { + const server = yield* McpServer.McpServer; + const mcpSessions = yield* Effect.serviceOption(McpProviderSessions.McpProviderSessions); + const guard = yield* makeToolCallLoopGuard(); + const guardedServer = McpServer.McpServer.of({ + ...server, + addTool: Effect.fn("McpServer.addTool")(function (options) { + const toolName = options.tool.name; + return server.addTool({ + ...options, + handle: Effect.fnUntraced(function* (payload) { + const scope = Option.getOrUndefined( + yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext), + ); + const thread = scope?.thread; + const epoch = + thread === undefined || Option.isNone(mcpSessions) + ? undefined + : yield* mcpSessions.value.toolResultEpoch(thread.threadId); + const scopeKey = loopGuardScopeKey(scope, epoch); + if (scopeKey === undefined) return yield* options.handle(payload); + const ttlMs = loopGuardTtlMs(scope); + const key = toolCallLoopKey(scopeKey, toolName, payload); + const decision = yield* guard.check(key, ttlMs); + if (decision.blocked) { + yield* Effect.logWarning("mcp.tool.identical-failure-loop-blocked", { + tool: toolName, + priorFailures: decision.priorFailures, + ...(thread === undefined ? {} : { threadId: thread.threadId }), + }); + return toolCallLoopBlockedResult(toolName, decision.priorFailures); + } + return yield* options + .handle(payload) + .pipe( + Effect.onExit((exit) => guard.record(key, failureFingerprintFromExit(exit), ttlMs)), + ); + }), + }); + }), + }); + return yield* registration.pipe(Effect.provideService(McpServer.McpServer, guardedServer)); +}); + /** Each tool call gets a span named for its tool; arguments stay out, as they carry prompts and IDs. */ const withToolSpans = Effect.fn("McpHttpServer.withToolSpans")(function* ( registration: Effect.Effect, @@ -1388,8 +1442,10 @@ export const toolkitRegistration = , EX, Layer.effectDiscard( withToolAnalytics( withToolResultCapture( - withToolSpans( - withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + withToolLoopGuard( + withToolSpans( + withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + ), ), ), ), @@ -1407,9 +1463,9 @@ const imageToolRegistration = , A, E, R, register: Effect.Effect, handlers: McpToolAccess.HandlersLayer, ) => - Layer.effectDiscard(withToolAnalytics(withToolResultCapture(withToolSpans(register)))).pipe( - Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)), - ); + Layer.effectDiscard( + withToolAnalytics(withToolResultCapture(withToolLoopGuard(withToolSpans(register)))), + ).pipe(Layer.provide(McpToolAccess.HandlersLayer.layer(handlers))); export const layerHtmlToolkit = Layer.mergeAll( toolkitRegistration(HtmlRenderToolkit, HtmlHandlers.layerRender), diff --git a/apps/server/src/mcp/McpToolLoopGuard.test.ts b/apps/server/src/mcp/McpToolLoopGuard.test.ts new file mode 100644 index 0000000000000..7b4e05fbdaea1 --- /dev/null +++ b/apps/server/src/mcp/McpToolLoopGuard.test.ts @@ -0,0 +1,690 @@ +import { assert, describe, expect, it } from "@effect/vitest"; +import { + CommandId, + EnvironmentId, + MessageId, + OrchestratorMcpFailure, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ProviderThreadId, + ProviderTurnId, + RunId, + ThreadId, + type OrchestrationV2ThreadShell, +} from "@t3tools/contracts"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; +import { SEND_TO_USER_MAX_LENGTH } from "@t3tools/shared/toolOutput"; +import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as Queue from "effect/Queue"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; + +import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import * as EffectWorker from "../orchestration-v2/EffectWorker.ts"; +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as McpHttpServer from "./McpHttpServer.ts"; +import * as McpInvocationContext from "./McpInvocationContext.ts"; +import * as McpToolAccess from "./McpToolAccess.ts"; +import { + CLIENT_LOOP_GUARD_TTL_MS, + failureFingerprintFromExit, + loopGuardScopeKey, + loopGuardTtlMs, + makeToolCallLoopGuard, + MAX_IDENTICAL_FAILING_TOOL_CALLS, + TOOL_CALL_LOOP_BLOCKED_CODE, + toolCallLoopKey, +} from "./McpToolLoopGuard.ts"; + +const threadId = ThreadId.make("thread:antigravity-delegate"); +const envId = EnvironmentId.make("env:asus"); +const instanceId = ProviderInstanceId.make("antigravity"); +const client = McpSchema.McpServerClient.of({ + clientId: 1, + protocolVersion: "2025-06-18", + clientCapabilities: {}, + clientInfo: { name: "antigravity", version: "1.0.0" }, + initializePayload: { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "antigravity", version: "1.0.0" }, + }, + getClient: Effect.die("unused"), +}); + +const declaredFailure = (result: McpSchema.CallToolResult) => { + const text = result.content[0]; + return result.isError === true && text?.type === "text" ? JSON.parse(text.text) : undefined; +}; + +const threadScope = ( + overrides: Partial> = {}, +): McpInvocationContext.McpInvocationScope => ({ + environmentId: envId, + requestNamespace: "session:antigravity", + thread: { + threadId, + providerSessionId: "provider-session:antigravity-1", + providerInstanceId: instanceId, + ...overrides, + }, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 0, +}); + +const liveAntigravityThreadsLayer = Layer.succeed(ThreadManagementService.ThreadManagementService, { + getThreadShell: (id: ThreadId) => + Effect.succeed({ + id, + archivedAt: null, + deletedAt: null, + activeRunId: RunId.make("run:active-1"), + providerInstanceId: instanceId, + runtimeMode: "full-access", + interactionMode: "default", + pendingBackgroundTasks: [], + } as unknown as OrchestrationV2ThreadShell), +} as unknown as ThreadManagementService.ThreadManagementService["Service"]); + +describe("McpToolLoopGuard", () => { + it.effect( + "blocks a third identical failing call and resets on argument/error change or success", + () => + Effect.gen(function* () { + const guard = yield* makeToolCallLoopGuard(); + const scopeKey = loopGuardScopeKey(threadScope(), 0)!; + const key = toolCallLoopKey(scopeKey, "send_to_user", { message: "too long" }); + + assert.equal(MAX_IDENTICAL_FAILING_TOOL_CALLS, 2); + assert.deepEqual(yield* guard.check(key), { blocked: false }); + + const errA = failureFingerprintFromExit( + Exit.fail(new McpSchema.InvalidParams({ message: "Expected length <= 4000" })), + ); + yield* guard.record(key, errA); + assert.deepEqual(yield* guard.check(key), { blocked: false }); + + // A different error resets the consecutive-same-failure count. + const errB = failureFingerprintFromExit( + Exit.fail(new McpSchema.InvalidParams({ message: "Different error" })), + ); + yield* guard.record(key, errB); + assert.deepEqual(yield* guard.check(key), { blocked: false }); + + // Two identical failures with errB trip the guard before a 3rd attempt. + yield* guard.record(key, errB); + assert.deepEqual(yield* guard.check(key), { blocked: true, priorFailures: 2 }); + + // Changed arguments use a distinct key and remain allowed. + const changedKey = toolCallLoopKey(scopeKey, "send_to_user", { message: "short" }); + assert.deepEqual(yield* guard.check(changedKey), { blocked: false }); + + // A success clears the failure streak. + const ok = failureFingerprintFromExit( + Exit.succeed( + new McpSchema.CallToolResult({ + isError: false, + content: [{ type: "text", text: "ok" }], + }), + ), + ); + assert.isNull(ok); + yield* guard.record(key, ok); + assert.deepEqual(yield* guard.check(key), { blocked: false }); + }), + ); + + it("excludes linked peer-transport callers from loop-guard scoping", () => { + const linkedPeerScope: McpInvocationContext.McpInvocationScope = { + environmentId: envId, + requestNamespace: "peer:r720", + thread: undefined, + client: { + sessionId: "peer-session-1", + label: "R720", + access: "full-access", + linked: true, + }, + capabilities: new Set(["orchestration"]), + issuedAt: 0, + }; + assert.isUndefined(loopGuardScopeKey(linkedPeerScope, undefined)); + }); + + it.effect( + "Dec 2 Antigravity Neon replay: blocks a 3rd identical send_to_user call over the 4,000-char cap", + () => + Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const scope = threadScope(); + const oversized = "N".repeat(SEND_TO_USER_MAX_LENGTH + 250); + const invoke = (message: string) => + server + .callTool({ name: "send_to_user", arguments: { message } }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + ); + + // Attempts 1 and 2 fail schema validation identically. + const first = yield* invoke(oversized).pipe(Effect.flip); + expect(first).toMatchObject({ _tag: "InvalidParams" }); + const second = yield* invoke(oversized).pipe(Effect.flip); + expect(second).toMatchObject({ _tag: "InvalidParams" }); + + // Attempt 3 with the exact same payload is blocked before schema/handler execution. + const third = yield* invoke(oversized); + expect(third.isError).toBe(true); + expect(third.structuredContent).toMatchObject({ + _tag: "ToolCallLoopBlocked", + code: TOOL_CALL_LOOP_BLOCKED_CODE, + tool: "send_to_user", + priorFailures: 2, + }); + + // Changing the message to fit under the 4,000-character cap succeeds immediately. + const fixed = yield* invoke("Concise summary under cap."); + expect(fixed.isError).not.toBe(true); + }).pipe( + Effect.provide( + McpHttpServer.layerMessageToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provideMerge(McpProviderSessions.layer), + Layer.provide(liveAntigravityThreadsLayer), + ), + ), + ), + ); + + it.effect( + "Dec 2 Antigravity Carbon replay: blocks a 3rd identical failing silent_ack call before handler execution", + () => + Effect.gen(function* () { + const handlerCalls = yield* Ref.make(0); + const activeRun = yield* Ref.make(null); + const ProbeTool = Tool.make("silent_ack_probe", { + description: "Probe tool mirroring silent_ack handler failures.", + parameters: Schema.Struct({ reason: Schema.optional(Schema.String) }), + success: Schema.Struct({ ok: Schema.Literal(true) }), + failure: OrchestratorMcpFailure, + failureMode: "return", + dependencies: [ + McpInvocationContext.McpInvocationContext, + ThreadManagementService.ThreadManagementService, + ], + }).annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + const ProbeToolkit = Toolkit.make(ProbeTool); + const ProbeHandlers = McpToolAccess.toLayer(ProbeToolkit, { + silent_ack_probe: McpToolAccess.readsAsCaller(() => + Ref.update(handlerCalls, (n) => n + 1).pipe( + Effect.andThen( + Effect.fail( + new OrchestratorMcpFailure({ + code: "parent_not_active", + message: "The calling provider no longer owns an active thread run.", + }), + ), + ), + ), + ), + }); + + const threadsLayer = Layer.succeed(ThreadManagementService.ThreadManagementService, { + getThreadShell: (id: ThreadId) => + Ref.get(activeRun).pipe( + Effect.map( + (activeRunId) => + ({ + id, + archivedAt: null, + deletedAt: null, + activeRunId, + providerInstanceId: instanceId, + runtimeMode: "full-access", + interactionMode: "default", + pendingBackgroundTasks: [], + }) as unknown as OrchestrationV2ThreadShell, + ), + ), + } as unknown as ThreadManagementService.ThreadManagementService["Service"]); + + const layer = Layer.mergeAll( + McpHttpServer.layerMessageToolkit, + McpHttpServer.toolkitRegistration(ProbeToolkit, ProbeHandlers), + ).pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provideMerge(McpProviderSessions.layer), + Layer.provide(threadsLayer), + ); + + yield* Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const scope = threadScope(); + const call = (name: string, args: Record) => + server + .callTool({ name, arguments: args }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + ); + + // Real silent_ack failing parent_not_active (no active run) twice -> 3rd attempt blocked. + const ack1 = yield* call("silent_ack", { reason: "done" }); + expect(ack1.isError).toBe(true); + expect(declaredFailure(ack1)).toMatchObject({ code: "parent_not_active" }); + + const ack2 = yield* call("silent_ack", { reason: "done" }); + expect(ack2.isError).toBe(true); + expect(declaredFailure(ack2)).toMatchObject({ code: "parent_not_active" }); + + const ack3 = yield* call("silent_ack", { reason: "done" }); + expect(ack3.isError).toBe(true); + expect(ack3.structuredContent).toMatchObject({ + _tag: "ToolCallLoopBlocked", + code: TOOL_CALL_LOOP_BLOCKED_CODE, + tool: "silent_ack", + priorFailures: 2, + }); + + // Verify handler execution count stops strictly at 2 (never executes a 3rd time). + yield* call("silent_ack_probe", { reason: "loop" }); + yield* call("silent_ack_probe", { reason: "loop" }); + const blocked = yield* call("silent_ack_probe", { reason: "loop" }); + expect(blocked.isError).toBe(true); + expect(blocked.structuredContent).toMatchObject({ + code: TOOL_CALL_LOOP_BLOCKED_CODE, + tool: "silent_ack_probe", + priorFailures: 2, + }); + assert.equal(yield* Ref.get(handlerCalls), 2); + + // A genuinely new active turn clears tool results (bumping epoch) and resets the guard budget. + const sessions = yield* McpProviderSessions.McpProviderSessions; + yield* sessions.clearToolResults(threadId); + yield* Ref.set(activeRun, RunId.make("run:new-parent-followup")); + const afterNewRun = yield* call("silent_ack", { reason: "done" }); + expect(afterNewRun.isError).not.toBe(true); + }).pipe(Effect.provide(layer)); + }), + ); + + it.effect( + "expires non-linked external client streaks after TTL and resets immediately on success", + () => + Effect.gen(function* () { + const handlerCalls = yield* Ref.make(0); + const shouldFail = yield* Ref.make(true); + const ClientProbeTool = Tool.make("external_client_probe", { + description: "Probe tool for external non-linked MCP client TTL testing.", + parameters: Schema.Struct({ action: Schema.String }), + success: Schema.Struct({ ok: Schema.Literal(true) }), + failure: OrchestratorMcpFailure, + failureMode: "return", + dependencies: [McpInvocationContext.McpInvocationContext], + }); + const ClientProbeToolkit = Toolkit.make(ClientProbeTool); + const ClientProbeHandlers = McpToolAccess.toLayer(ClientProbeToolkit, { + external_client_probe: McpToolAccess.reads(() => + Ref.update(handlerCalls, (n) => n + 1).pipe( + Effect.andThen(Ref.get(shouldFail)), + Effect.flatMap((failing) => + failing + ? Effect.fail( + new OrchestratorMcpFailure({ + code: "orchestration_error", + message: "Transient external failure.", + }), + ) + : Effect.succeed({ ok: true as const }), + ), + ), + ), + }); + + const externalClientScope: McpInvocationContext.McpInvocationScope = { + environmentId: envId, + requestNamespace: "client:ext-1", + thread: undefined, + client: { + sessionId: "ext-session-1", + label: "External CLI", + access: "full-access", + linked: false, + }, + capabilities: new Set(["orchestration"]), + issuedAt: 0, + }; + assert.equal(loopGuardTtlMs(externalClientScope), CLIENT_LOOP_GUARD_TTL_MS); + + const layer = McpHttpServer.toolkitRegistration( + ClientProbeToolkit, + ClientProbeHandlers, + ).pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provideMerge(McpProviderSessions.layer), + ); + + yield* Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const call = () => + server + .callTool({ name: "external_client_probe", arguments: { action: "sync" } }) + .pipe( + Effect.provideService( + McpInvocationContext.McpInvocationContext, + externalClientScope, + ), + Effect.provideService(McpSchema.McpServerClient, client), + ); + + expect((yield* call()).isError).toBe(true); + expect((yield* call()).isError).toBe(true); + const blocked = yield* call(); + expect(blocked.isError).toBe(true); + expect(blocked.structuredContent).toMatchObject({ + code: TOOL_CALL_LOOP_BLOCKED_CODE, + tool: "external_client_probe", + priorFailures: 2, + }); + assert.equal(yield* Ref.get(handlerCalls), 2); + + // Still blocked just before TTL expires. + yield* TestClock.adjust(Duration.millis(CLIENT_LOOP_GUARD_TTL_MS - 1)); + const stillBlocked = yield* call(); + expect(stillBlocked.structuredContent).toMatchObject({ + code: TOOL_CALL_LOOP_BLOCKED_CODE, + }); + assert.equal(yield* Ref.get(handlerCalls), 2); + + // Once TTL elapses, the client can retry and succeed. + yield* TestClock.adjust(Duration.millis(1)); + yield* Ref.set(shouldFail, false); + const recovered = yield* call(); + expect(recovered.isError).not.toBe(true); + assert.equal(yield* Ref.get(handlerCalls), 3); + + // A success clears a streak immediately without waiting for TTL. + yield* Ref.set(shouldFail, true); + expect((yield* call()).isError).toBe(true); + yield* Ref.set(shouldFail, false); + expect((yield* call()).isError).not.toBe(true); + yield* Ref.set(shouldFail, true); + expect((yield* call()).isError).toBe(true); + expect((yield* call()).isError).toBe(true); + assert.equal(yield* Ref.get(handlerCalls), 7); + const blockedAgain = yield* call(); + expect(blockedAgain.structuredContent).toMatchObject({ + code: TOOL_CALL_LOOP_BLOCKED_CODE, + }); + assert.equal(yield* Ref.get(handlerCalls), 7); + }).pipe(Effect.provide(layer)); + }), + ); + + it.live( + "non-ACP provider resets loop-guard budget across turns via ProviderSessionManager without adapter clearToolResults", + () => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("non-acp-loop-guard-reset"); + const codexDriver = ProviderDriverKind.make("codex"); + const codexInstanceId = ProviderInstanceId.make("codex"); + const nonAcpThreadId = ThreadId.make("thread:codex-non-acp-loop-guard"); + const handlerCalls = yield* Ref.make(0); + const shouldFail = yield* Ref.make(true); + const sessionIdsUsed: Array = []; + + const NonAcpProbeTool = Tool.make("non_acp_probe", { + description: "Probe tool for non-ACP per-turn loop-guard reset testing.", + parameters: Schema.Struct({ target: Schema.String }), + success: Schema.Struct({ ok: Schema.Literal(true) }), + failure: OrchestratorMcpFailure, + failureMode: "return", + dependencies: [McpInvocationContext.McpInvocationContext], + }).annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + const NonAcpProbeToolkit = Toolkit.make(NonAcpProbeTool); + const NonAcpProbeHandlers = McpToolAccess.toLayer(NonAcpProbeToolkit, { + non_acp_probe: McpToolAccess.readsAsCaller(() => + Ref.update(handlerCalls, (n) => n + 1).pipe( + Effect.andThen(Ref.get(shouldFail)), + Effect.flatMap((failing) => + failing + ? Effect.fail( + new OrchestratorMcpFailure({ + code: "orchestration_error", + message: "Transient non-ACP failure.", + }), + ) + : Effect.succeed({ ok: true as const }), + ), + ), + ), + }); + + // Non-ACP adapter: never calls `clearToolResults` and reuses one provider session across turns. + const codexAdapter: ProviderAdapter.ProviderAdapterV2["Service"] = { + instanceId: codexInstanceId, + driver: codexDriver, + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), + openSession: (session) => + Effect.gen(function* () { + const createdAt = yield* DateTime.now; + const events = yield* Queue.unbounded(); + return { + instanceId: codexInstanceId, + driver: codexDriver, + providerSessionId: session.providerSessionId, + providerSession: { + id: session.providerSessionId, + driver: codexDriver, + providerInstanceId: codexInstanceId, + status: "ready", + cwd, + model: "gpt-5", + capabilities: CodexProviderCapabilitiesV2, + createdAt, + updatedAt: createdAt, + lastError: null, + }, + events: Stream.fromQueue(events), + ensureThread: ({ threadId: id }) => + Effect.succeed({ + id: ProviderThreadId.make(`provider-thread:${id}`), + driver: codexDriver, + providerInstanceId: codexInstanceId, + providerSessionId: session.providerSessionId, + appThreadId: id, + ownerNodeId: null, + nativeThreadRef: { + driver: codexDriver, + nativeId: `native:${id}`, + strength: "strong", + }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt, + updatedAt: createdAt, + }), + resumeThread: ({ providerThread }) => Effect.succeed(providerThread), + startTurn: (turn) => + Effect.gen(function* () { + sessionIdsUsed.push(session.providerSessionId); + const ts = yield* DateTime.now; + const providerTurnId = ProviderTurnId.make(`provider-turn:${turn.attemptId}`); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver: codexDriver, + providerTurn: { + id: providerTurnId, + providerThreadId: turn.providerThread.id, + nodeId: turn.rootNodeId, + runAttemptId: turn.attemptId, + nativeTurnRef: null, + ordinal: turn.providerTurnOrdinal, + status: "running", + startedAt: ts, + completedAt: null, + }, + }); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver: codexDriver, + providerTurn: { + id: providerTurnId, + providerThreadId: turn.providerThread.id, + nodeId: turn.rootNodeId, + runAttemptId: turn.attemptId, + nativeTurnRef: null, + ordinal: turn.providerTurnOrdinal, + status: "completed", + startedAt: ts, + completedAt: ts, + }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver: codexDriver, + providerThreadId: turn.providerThread.id, + providerTurnId, + runOrdinal: turn.runOrdinal, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + }), + steerTurn: () => Effect.die("unused"), + interruptTurn: () => Effect.void, + respondToRuntimeRequest: () => Effect.die("unused"), + readThreadSnapshot: () => Effect.die("unused"), + rollbackThread: () => Effect.die("unused"), + forkThread: () => Effect.die("unused"), + }; + }), + }; + + const layer = Layer.mergeAll( + ProviderReplayHarness.layerWithRegistry( + { name: "non-acp-loop-guard-reset" }, + ProviderAdapterRegistry.layerSingle(codexAdapter), + { runEffectWorker: false, runContinuationWorker: false }, + ), + McpHttpServer.toolkitRegistration(NonAcpProbeToolkit, NonAcpProbeHandlers).pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provideMerge(McpProviderSessions.layer), + ), + ); + + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const mcpServer = yield* McpServer.McpServer; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create:codex-non-acp"), + threadId: nonAcpThreadId, + projectId: ProjectId.make("project:t3code"), + title: "Codex non-ACP loop guard", + modelSelection: { instanceId: codexInstanceId, model: "gpt-5" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + + const runTurn = (ordinal: number) => + Effect.gen(function* () { + const completed = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.threadId === nonAcpThreadId && + event.payload.ordinal === ordinal && + event.payload.status === "completed", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`dispatch:codex-turn-${ordinal}`), + threadId: nonAcpThreadId, + messageId: MessageId.make(`msg:codex-turn-${ordinal}`), + text: `Turn ${ordinal}`, + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + yield* Fiber.join(completed); + // Drain turn-end checkpoint capture so the next turn starts immediately instead of queueing. + yield* worker.drain(); + }); + + // Turn 1: non-ACP provider starts turn -> 2 identical failures block the 3rd attempt. + yield* runTurn(1); + const reusedSessionId = sessionIdsUsed[0]!; + const epochTurn1 = yield* mcpSessions.toolResultEpoch(nonAcpThreadId); + const codexScope = threadScope({ + threadId: nonAcpThreadId, + providerSessionId: reusedSessionId, + providerInstanceId: codexInstanceId, + }); + const invoke = () => + mcpServer + .callTool({ name: "non_acp_probe", arguments: { target: "status" } }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, codexScope), + Effect.provideService(McpSchema.McpServerClient, client), + ); + + expect((yield* invoke()).isError).toBe(true); + expect((yield* invoke()).isError).toBe(true); + const blockedTurn1 = yield* invoke(); + expect(blockedTurn1.isError).toBe(true); + expect(blockedTurn1.structuredContent).toMatchObject({ + _tag: "ToolCallLoopBlocked", + code: TOOL_CALL_LOOP_BLOCKED_CODE, + tool: "non_acp_probe", + priorFailures: 2, + }); + assert.equal(yield* Ref.get(handlerCalls), 2); + + // Turn 2: reuses the exact same providerSessionId without adapter clearToolResults. + yield* Ref.set(shouldFail, false); + yield* runTurn(2); + assert.equal(sessionIdsUsed[1], reusedSessionId); + assert.isAbove(yield* mcpSessions.toolResultEpoch(nonAcpThreadId), epochTurn1); + + // Same tool + args + providerSessionId now succeeds cleanly on Turn 2. + const turn2Result = yield* invoke(); + expect(turn2Result.isError).not.toBe(true); + assert.equal(yield* Ref.get(handlerCalls), 3); + }).pipe(Effect.provide(layer)); + }), + ); +}); diff --git a/apps/server/src/mcp/McpToolLoopGuard.ts b/apps/server/src/mcp/McpToolLoopGuard.ts new file mode 100644 index 0000000000000..cc28d566ed98f --- /dev/null +++ b/apps/server/src/mcp/McpToolLoopGuard.ts @@ -0,0 +1,178 @@ +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import { McpSchema } from "effect/ai"; +import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Option from "effect/Option"; +import * as Predicate from "effect/Predicate"; +import * as Ref from "effect/Ref"; + +import { toolOutcome } from "../telemetry/ProviderDimensions.ts"; +import type * as McpInvocationContext from "./McpInvocationContext.ts"; + +/** Allow one retry after an initial failure; refuse a third identical failing attempt unchanged. */ +export const MAX_IDENTICAL_FAILING_TOOL_CALLS = 2; +export const TOOL_CALL_LOOP_BLOCKED_CODE = "repeated_failure_blocked"; +/** External non-linked MCP clients have no turn epoch, so failure streaks expire after 60s. */ +export const CLIENT_LOOP_GUARD_TTL_MS = 60_000; +const MAX_TRACKED_KEYS = 512; + +interface FailureStreak { + readonly failureKey: string; + readonly count: number; + readonly updatedAtMs: number; +} + +const textOfContent = (content: ReadonlyArray): string => + content + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n") + .trim(); + +const stringProperty = (value: unknown, key: string): string | undefined => + Predicate.isReadonlyObject(value) && typeof value[key] === "string" ? value[key] : undefined; + +/** + * Classifies an MCP tool exit for loop detection: + * - `string`: normalized failure fingerprint + * - `null`: tool succeeded (clears any prior streak for this call) + * - `undefined`: neutral outcome (interrupt or elicitation) + */ +export function failureFingerprintFromExit( + exit: Exit.Exit, +): string | null | undefined { + if (Exit.isFailure(exit)) { + if (Cause.hasInterruptsOnly(exit.cause)) return undefined; + const error = Option.getOrElse(Cause.findErrorOption(exit.cause), () => + Cause.squash(exit.cause), + ); + const tag = stringProperty(error, "_tag") ?? (error instanceof Error ? error.name : ""); + const code = stringProperty(error, "code") ?? ""; + const message = + stringProperty(error, "message") ?? (error instanceof Error ? error.message : String(error)); + return `fail:${tag}:${code}:${message.trim()}`; + } + const value = exit.value; + if (value instanceof McpSchema.InputRequired) return undefined; + const outcome = toolOutcome(value); + if (value.isError !== true && outcome.outcome !== "error") return null; + const tag = stringProperty(value.structuredContent, "_tag") ?? ""; + const code = outcome.outcome === "error" ? outcome.errorCode : ""; + const structuredMessage = stringProperty(value.structuredContent, "message") ?? ""; + const text = textOfContent(value.content); + return `result:${tag}:${code}:${structuredMessage || text}`; +} + +/** Server-to-server peer link transport is excluded so remote follower retries keep working. */ +export function loopGuardScopeKey( + scope: McpInvocationContext.McpInvocationScope | undefined, + toolResultEpoch: number | undefined, +): string | undefined { + if (scope === undefined) return undefined; + if (scope.thread !== undefined) { + return `thread:${scope.thread.threadId}:${scope.thread.providerSessionId}:${toolResultEpoch ?? 0}`; + } + if (scope.client !== undefined && scope.client.linked !== true) { + return `client:${scope.client.sessionId}`; + } + return undefined; +} + +export function loopGuardTtlMs( + scope: McpInvocationContext.McpInvocationScope | undefined, +): number | undefined { + if (scope?.thread !== undefined) return undefined; + if (scope?.client !== undefined && scope.client.linked !== true) { + return CLIENT_LOOP_GUARD_TTL_MS; + } + return undefined; +} + +export function toolCallLoopKey(scopeKey: string, toolName: string, payload: unknown): string { + return `${scopeKey}\0${toolName}\0${McpProviderSessions.hashToolInput(payload)}`; +} + +export function toolCallLoopBlockedResult( + toolName: string, + priorFailures: number, +): McpSchema.CallToolResult { + const message = `Blocked: \`${toolName}\` with identical arguments already failed ${priorFailures} times with the same error. Do not retry this call unchanged; change the arguments or take a different approach.`; + return new McpSchema.CallToolResult({ + isError: true, + structuredContent: { + _tag: "ToolCallLoopBlocked", + code: TOOL_CALL_LOOP_BLOCKED_CODE, + tool: toolName, + priorFailures, + message, + }, + content: [{ type: "text", text: message }], + }); +} + +export interface ToolCallLoopGuard { + readonly check: ( + key: string, + ttlMs?: number, + ) => Effect.Effect< + { readonly blocked: true; readonly priorFailures: number } | { readonly blocked: false } + >; + readonly record: ( + key: string, + fingerprint: string | null | undefined, + ttlMs?: number, + ) => Effect.Effect; +} + +const isExpired = (entry: FailureStreak, nowMs: number, ttlMs: number | undefined): boolean => + ttlMs !== undefined && nowMs - entry.updatedAtMs >= ttlMs; + +export const makeToolCallLoopGuard = Effect.fn("McpToolLoopGuard.make")(function* () { + const streaks = yield* Ref.make(new Map()); + return { + check: Effect.fn("McpToolLoopGuard.check")(function* (key: string, ttlMs?: number) { + const current = yield* Ref.get(streaks); + const entry = current.get(key); + if (entry === undefined) return { blocked: false } as const; + if (ttlMs !== undefined && isExpired(entry, yield* Clock.currentTimeMillis, ttlMs)) { + return { blocked: false } as const; + } + return entry.count >= MAX_IDENTICAL_FAILING_TOOL_CALLS + ? ({ blocked: true, priorFailures: entry.count } as const) + : ({ blocked: false } as const); + }), + record: Effect.fn("McpToolLoopGuard.record")(function* ( + key: string, + fingerprint: string | null | undefined, + ttlMs?: number, + ) { + if (fingerprint === undefined) return; + const nowMs = yield* Clock.currentTimeMillis; + yield* Ref.update(streaks, (current) => { + if (fingerprint === null) { + if (!current.has(key)) return current; + const next = new Map(current); + next.delete(key); + return next; + } + const next = new Map(current); + const existing = next.get(key); + const previous = + existing !== undefined && !isExpired(existing, nowMs, ttlMs) ? existing : undefined; + const updated: FailureStreak = + previous?.failureKey === fingerprint + ? { failureKey: fingerprint, count: previous.count + 1, updatedAtMs: nowMs } + : { failureKey: fingerprint, count: 1, updatedAtMs: nowMs }; + next.delete(key); + next.set(key, updated); + while (next.size > MAX_TRACKED_KEYS) { + const oldest = next.keys().next().value; + if (oldest === undefined) break; + next.delete(oldest); + } + return next; + }); + }), + } satisfies ToolCallLoopGuard; +}); diff --git a/apps/server/src/orchestration-v2/AgentOutputGate.test.ts b/apps/server/src/orchestration-v2/AgentOutputGate.test.ts index 93e2cc2a6a5f9..36d6ab95920b0 100644 --- a/apps/server/src/orchestration-v2/AgentOutputGate.test.ts +++ b/apps/server/src/orchestration-v2/AgentOutputGate.test.ts @@ -1,7 +1,9 @@ import { assert, describe, it } from "@effect/vitest"; import { + EnvironmentId, EventId, MessageId, + NodeId, ProjectId, ProviderInstanceId, RunId, @@ -44,12 +46,22 @@ const baseThread = ( overrides: Partial< Pick< OrchestrationV2AppThread, - "deletedAt" | "archivedAt" | "lineage" | "replacedByThreadId" | "settledOverride" + | "deletedAt" + | "archivedAt" + | "lineage" + | "delegatedFrom" + | "replacedByThreadId" + | "settledOverride" > > = {}, ): Pick< OrchestrationV2AppThread, - "deletedAt" | "archivedAt" | "lineage" | "replacedByThreadId" | "settledOverride" + | "deletedAt" + | "archivedAt" + | "lineage" + | "delegatedFrom" + | "replacedByThreadId" + | "settledOverride" > => ({ deletedAt: null, archivedAt: null, @@ -64,8 +76,10 @@ const baseThread = ( }); const baseRun = ( - overrides: Partial> = {}, -): Pick => ({ + overrides: Partial< + Pick + > = {}, +): Pick => ({ id: runId, status: "completed", userMessageId: agentMsgId, @@ -199,6 +213,28 @@ describe("AgentOutputGate policy", () => { turnItems: [assistantItem("a1", "Child task summary.")], }); assert.deepEqual(subagent, { action: "allow", reason: "subagent_thread" }); + + const remoteDelegate = evaluateAgentOutputGate({ + thread: baseThread({ + delegatedFrom: { + environmentId: EnvironmentId.make("env:r720"), + threadId: ThreadId.make("thread:lead"), + title: "Lead", + }, + }), + run: baseRun(), + userMessage: userMessage("agent"), + turnItems: [assistantItem("a1", "Remote delegate report.")], + }); + assert.deepEqual(remoteDelegate, { action: "allow", reason: "subagent_thread" }); + + const delegatedRun = evaluateAgentOutputGate({ + thread: baseThread(), + run: baseRun({ delegatedTaskId: NodeId.make("node:delegated-task") }), + userMessage: userMessage("agent"), + turnItems: [assistantItem("a1", "Delegated task summary.")], + }); + assert.deepEqual(delegatedRun, { action: "allow", reason: "subagent_thread" }); }); it("allows agent-originated turns that already used an explicit channel tool", () => { @@ -370,4 +406,68 @@ describe("AgentOutputGateReactor", () => { }).pipe(Effect.provide(layer)); }), ); + + it.effect("dispatches 0 bounces for a completed remote delegated thread (delegatedFrom)", () => + Effect.gen(function* () { + const dispatched = yield* Ref.make>([]); + const layer = Layer.mergeAll( + Layer.mock(Orchestrator.OrchestratorV2)({ + streamDomainEvents: Stream.empty, + dispatch: (command) => + Ref.update(dispatched, (list) => [...list, command]).pipe( + Effect.as({ sequence: 1, storedEvents: [] } as never), + ), + }), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadShell: () => Effect.succeed({ activeRunId: null, latestRunId: runId } as never), + getThreadRecords: () => + Effect.succeed({ + thread: { + ...baseThread({ + delegatedFrom: { + environmentId: EnvironmentId.make("env:r720"), + threadId: ThreadId.make("thread:lead"), + title: "Lead", + }, + }), + id: threadId, + projectId: ProjectId.make("project:gate"), + providerInstanceId: ProviderInstanceId.make("antigravity"), + }, + runs: [ + { + ...baseRun({ id: runId, userMessageId: agentMsgId }), + providerInstanceId: ProviderInstanceId.make("antigravity"), + }, + ], + messages: [ + { + id: agentMsgId, + threadId, + runId, + role: "user", + text: "Run audit", + ...userMessage("agent"), + }, + ], + turnItems: [assistantItem("a1", "Full delegate audit report.", runId)], + } as never), + getMessagesById: () => Effect.succeed(new Map()), + }), + Layer.mock(EventSink.EventSinkV2)({ + write: () => Effect.succeed([] as never), + }), + Layer.mock(IdAllocator.IdAllocatorV2)({ + allocate: { event: () => Effect.succeed(EventId.make("evt:1")) } as never, + derive: {} as never, + }), + ); + + yield* Effect.gen(function* () { + const reactor = yield* AgentOutputGateReactor.make; + yield* reactor.evaluateCompletedRun({ threadId, runId }); + assert.equal((yield* Ref.get(dispatched)).length, 0); + }).pipe(Effect.provide(layer)); + }), + ); }); diff --git a/apps/server/src/orchestration-v2/AgentOutputGate.ts b/apps/server/src/orchestration-v2/AgentOutputGate.ts index b83c2904b25e2..5c0e5cf60db06 100644 --- a/apps/server/src/orchestration-v2/AgentOutputGate.ts +++ b/apps/server/src/orchestration-v2/AgentOutputGate.ts @@ -1,5 +1,6 @@ import { CommandId, + isDelegatedAppThread, MessageId, type OrchestrationV2AppThread, type OrchestrationV2ConversationMessage, @@ -17,7 +18,7 @@ import { const OUTPUT_GATE_BOUNCE_MESSAGE_PREFIX = "message:output-gate-bounce:"; export const OUTPUT_GATE_BOUNCE_PROMPT = - "Triggered by an agent/automation wake, not the user — plain assistant text stays folded and is not delivered. Route your response now: call `send_to_user` if it is for the founder, `t3_thread_send` or `ask_agent` if it is for another agent, or `silent_ack` if nothing needs delivery."; + "Triggered by an agent/automation wake, not the user: plain assistant text stays folded and is not delivered. Route your response now: call `send_to_user` if it is for the founder, `t3_thread_send` or `ask_agent` if it is for another agent, or `silent_ack` if nothing needs delivery."; const EXPLICIT_CHANNEL_TOOL_IDS: ReadonlySet = new Set([ SEND_TO_USER_TOOL_NAME, @@ -100,9 +101,14 @@ export type AgentOutputGateDecision = export function evaluateAgentOutputGate(input: { readonly thread: Pick< OrchestrationV2AppThread, - "deletedAt" | "archivedAt" | "lineage" | "replacedByThreadId" | "settledOverride" + | "deletedAt" + | "archivedAt" + | "lineage" + | "delegatedFrom" + | "replacedByThreadId" + | "settledOverride" >; - readonly run: Pick; + readonly run: Pick; readonly userMessage: | Pick< OrchestrationV2ConversationMessage, @@ -134,7 +140,7 @@ export function evaluateAgentOutputGate(input: { if (input.thread.lineage.sideChat === true) { return { action: "allow", reason: "side_chat" }; } - if (input.thread.lineage.relationshipToParent === "subagent") { + if (isDelegatedAppThread(input.thread) || input.run.delegatedTaskId !== undefined) { return { action: "allow", reason: "subagent_thread" }; } if (!isAgentOriginatedWake(input.userMessage)) { diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.ts index 32c862270c177..d7833718c748c 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.ts @@ -1,6 +1,7 @@ import { type ChatAttachment, CommandId, + isDelegatedAppThread, type OrchestrationV2Command, OrchestrationV2ProviderCapabilities, type OrchestrationV2GoalCommand, @@ -17,6 +18,8 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; +import { isOutputGateBounceMessageId } from "./AgentOutputGate.ts"; + export const SteeringExecutionPolicyV2 = Schema.Literals(["active_steering", "interrupt_restart"]); export type SteeringExecutionPolicyV2 = typeof SteeringExecutionPolicyV2.Type; @@ -82,6 +85,43 @@ export function isNativeMaintenanceCommand(message: { ); } +/** + * Completed delegated threads (local subagents and remote `delegatedFrom` tasks) must not + * restart automatically on server/system wakes without genuinely new user or parent input. + */ +export function shouldSuppressCompletedDelegateDispatch( + projection: Pick, + command: Pick< + Extract, + | "messageId" + | "createdBy" + | "creationSource" + | "notification" + | "delegatedCompletion" + | "steerFollowUpOfRunId" + | "restartContinuationOfRunId" + | "usageLimitContinuationOfRunId" + | "idleCompaction" + >, +): boolean { + if (!isDelegatedAppThread(projection.thread)) return false; + if (projection.runs.some((run) => isActiveRun(run) || run.status === "queued")) return false; + if (latestExecutedRun(projection.runs)?.status !== "completed") return false; + if (command.createdBy === "user") return false; + if (command.steerFollowUpOfRunId !== undefined) return false; + if (command.delegatedCompletion !== undefined) return false; + if (command.creationSource === "provider") return false; + if ( + command.restartContinuationOfRunId !== undefined || + command.usageLimitContinuationOfRunId !== undefined || + command.idleCompaction !== undefined || + isOutputGateBounceMessageId(command.messageId) + ) { + return true; + } + return command.notification?.source.kind === "system"; +} + /** * A goal command sent into active work stops that work when it starts or * replaces goal work, or ends a goal that is driving the run. diff --git a/apps/server/src/orchestration-v2/CompletedDelegateNoRerun.test.ts b/apps/server/src/orchestration-v2/CompletedDelegateNoRerun.test.ts new file mode 100644 index 0000000000000..273e5adced06d --- /dev/null +++ b/apps/server/src/orchestration-v2/CompletedDelegateNoRerun.test.ts @@ -0,0 +1,558 @@ +import { assert, describe, it } from "@effect/vitest"; +import { + CommandId, + EnvironmentId, + MessageId, + NodeId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ProviderThreadId, + ProviderTurnId, + RunId, + ThreadId, + TurnItemId, + type OrchestrationV2AppThread, + type OrchestrationV2Run, +} from "@t3tools/contracts"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; + +import { AcpProviderCapabilitiesV2 } from "@t3tools/provider-acp/server/adapter"; +import { + evaluateAgentOutputGate, + OUTPUT_GATE_BOUNCE_PROMPT, + outputGateBounceCommandId, + outputGateBounceMessageId, +} from "./AgentOutputGate.ts"; +import { shouldSuppressCompletedDelegateDispatch } from "./CommandPolicy.ts"; +import * as EffectWorker from "./EffectWorker.ts"; +import { idleCompactionWindow } from "./IdleCompaction.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import { restartContinuationBlocked } from "./RestartContinuation.ts"; +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; + +const driver = ProviderDriverKind.make("antigravity"); +const instanceId = ProviderInstanceId.make("antigravity"); +const leadEnvId = EnvironmentId.make("env:r720"); +const leadThreadId = ThreadId.make("thread:lead-clo-1368"); +const now = DateTime.makeUnsafe("2026-12-02T12:00:00.000Z"); + +const makeAntigravityTestAdapter = ( + cwd: string, + replyTextForThread: (threadId: ThreadId) => string, +) => { + const startedTurns: Array<{ readonly threadId: ThreadId; readonly text: string }> = []; + const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = { + instanceId, + driver, + getCapabilities: () => Effect.succeed(AcpProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), + openSession: (session) => + Effect.gen(function* () { + const createdAt = yield* DateTime.now; + const events = yield* Queue.unbounded(); + return { + instanceId, + driver, + providerSessionId: session.providerSessionId, + providerSession: { + id: session.providerSessionId, + driver, + providerInstanceId: instanceId, + status: "ready", + cwd, + model: "gemini-4-neon", + capabilities: AcpProviderCapabilitiesV2, + createdAt, + updatedAt: createdAt, + lastError: null, + }, + events: Stream.fromQueue(events), + ensureThread: ({ threadId }) => + Effect.succeed({ + id: ProviderThreadId.make(`provider-thread:${threadId}`), + driver, + providerInstanceId: instanceId, + providerSessionId: session.providerSessionId, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { driver, nativeId: `native:${threadId}`, strength: "strong" }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt, + updatedAt: createdAt, + }), + resumeThread: ({ providerThread }) => Effect.succeed(providerThread), + startTurn: (turn) => + Effect.gen(function* () { + startedTurns.push({ threadId: turn.threadId, text: turn.message.text }); + const ts = yield* DateTime.now; + const providerTurnId = ProviderTurnId.make(`provider-turn:${turn.attemptId}`); + const replyText = replyTextForThread(turn.threadId); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { + id: providerTurnId, + providerThreadId: turn.providerThread.id, + nodeId: turn.rootNodeId, + runAttemptId: turn.attemptId, + nativeTurnRef: null, + ordinal: turn.providerTurnOrdinal, + status: "running", + startedAt: ts, + completedAt: null, + }, + }); + yield* Queue.offer(events, { + type: "turn_item.updated", + driver, + turnItem: { + type: "assistant_message", + id: TurnItemId.make(`assistant:${turn.attemptId}`), + threadId: turn.threadId, + runId: turn.runId, + nodeId: turn.rootNodeId, + providerThreadId: turn.providerThread.id, + providerTurnId, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "completed", + title: null, + startedAt: ts, + completedAt: ts, + updatedAt: ts, + messageId: MessageId.make(`assistant-msg:${turn.attemptId}`), + text: replyText, + streaming: false, + }, + }); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { + id: providerTurnId, + providerThreadId: turn.providerThread.id, + nodeId: turn.rootNodeId, + runAttemptId: turn.attemptId, + nativeTurnRef: null, + ordinal: turn.providerTurnOrdinal, + status: "completed", + startedAt: ts, + completedAt: ts, + }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver, + providerThreadId: turn.providerThread.id, + providerTurnId, + runOrdinal: turn.runOrdinal, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + }), + steerTurn: () => Effect.die("unused"), + interruptTurn: () => Effect.void, + respondToRuntimeRequest: () => Effect.die("unused"), + readThreadSnapshot: () => Effect.die("unused"), + rollbackThread: () => Effect.die("unused"), + forkThread: () => Effect.die("unused"), + }; + }), + }; + return { adapter, startedTurns }; +}; + +describe("Completed delegate no-rerun guards (CLO-1368 M0 item 8)", () => { + it.live( + "Dec 2 Antigravity replay: Neon and Carbon remote delegates have zero restarts after completion, while new parent/user input still runs", + () => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("dec2-antigravity-delegates"); + const neonThreadId = ThreadId.make("thread:asus-gemini-neon"); + const carbonThreadId = ThreadId.make("thread:asus-gemini-carbon"); + const { adapter, startedTurns } = makeAntigravityTestAdapter(cwd, (id) => + id === neonThreadId + ? `${"Neon detailed audit report. ".repeat(200)}` + : "Carbon completed verification with no issues.", + ); + const layerTest = ProviderReplayHarness.layerWithRegistry( + { name: "dec2-antigravity-delegates" }, + ProviderAdapterRegistry.layerSingle(adapter), + { runEffectWorker: false, runContinuationWorker: false }, + ); + + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const watchRunCompleted = (threadId: ThreadId, expectedOrdinal: number) => + orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.threadId === threadId && + event.payload.ordinal === expectedOrdinal && + event.payload.status === "completed", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + + const launchRemoteDelegate = ( + threadId: ThreadId, + title: string, + model: string, + prompt: string, + ) => + Effect.gen(function* () { + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`create:${threadId}`), + threadId, + projectId: ProjectId.make("project:t3code"), + title, + modelSelection: { instanceId, model }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + linkOrigin: { + sessionId: "peer-session:r720", + label: "R720", + }, + delegatedFrom: { + environmentId: leadEnvId, + threadId: leadThreadId, + title: "Lead", + }, + createdBy: "agent", + creationSource: "mcp", + }); + const completed = yield* watchRunCompleted(threadId, 1); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`start:${threadId}`), + threadId, + messageId: MessageId.make(`msg:start:${threadId}`), + text: prompt, + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "agent", + creationSource: "mcp", + }); + yield* worker.drain(); + yield* Fiber.join(completed); + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.equal(projection.runs.length, 1); + assert.equal(projection.runs[0]!.status, "completed"); + return projection; + }); + + const neonProjection = yield* launchRemoteDelegate( + neonThreadId, + "Gemini Neon delegate", + "gemini-4-neon", + "Audit the runtime plan and return the full report.", + ); + const carbonProjection = yield* launchRemoteDelegate( + carbonThreadId, + "Gemini Carbon delegate", + "gemini-4-carbon", + "Verify the diff and summarize findings.", + ); + const neonRun = neonProjection.runs[0]!; + const carbonRun = carbonProjection.runs[0]!; + + // 1. AgentOutputGate must allow completed remote delegates without bouncing. + assert.deepEqual( + evaluateAgentOutputGate({ + thread: neonProjection.thread, + run: neonRun, + userMessage: neonProjection.messages.find((m) => m.id === neonRun.userMessageId), + turnItems: neonProjection.turnItems, + assistantMessages: neonProjection.messages, + }), + { action: "allow", reason: "subagent_thread" }, + ); + assert.deepEqual( + evaluateAgentOutputGate({ + thread: carbonProjection.thread, + run: carbonRun, + userMessage: carbonProjection.messages.find((m) => m.id === carbonRun.userMessageId), + turnItems: carbonProjection.turnItems, + assistantMessages: carbonProjection.messages, + }), + { action: "allow", reason: "subagent_thread" }, + ); + + // 2. Direct server/system automatic restarts (even while turn-end checkpoint capture is pending) + // must be suppressed by Orchestrator without queuing a second run. + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: outputGateBounceCommandId(neonRun.id), + threadId: neonThreadId, + messageId: outputGateBounceMessageId(neonRun.id), + text: OUTPUT_GATE_BOUNCE_PROMPT, + notification: { + source: { kind: "monitor" }, + outcome: "updated", + summary: "Output routing reminder", + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`server:system-nudge:${carbonRun.id}`), + threadId: carbonThreadId, + messageId: MessageId.make(`message:system-nudge:${carbonRun.id}`), + text: "Delegation reminder", + notification: { + source: { kind: "system" }, + outcome: "updated", + summary: "Delegation reminder", + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`server:idle-compact:${neonThreadId}:${neonRun.id}`), + threadId: neonThreadId, + messageId: MessageId.make(`idle-compact:${neonThreadId}:${neonRun.id}`), + text: "/compact", + attachments: [], + idleCompaction: "beforeCacheExpires", + dispatchMode: { type: "start_immediately" }, + createdBy: "agent", + creationSource: "server", + }); + yield* worker.drain(); + + const neonAfterAuto = yield* orchestrator.getThreadProjection(neonThreadId); + const carbonAfterAuto = yield* orchestrator.getThreadProjection(carbonThreadId); + assert.equal(neonAfterAuto.runs.length, 1, "Neon had zero restarts after completion"); + assert.equal(carbonAfterAuto.runs.length, 1, "Carbon had zero restarts after completion"); + assert.equal(startedTurns.length, 2, "Only the initial delegated turns ran"); + + // 3. Genuinely new parent input (t3_thread_send via MCP) still runs cleanly. + const neonFollowUpDone = yield* watchRunCompleted(neonThreadId, 2); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("parent-followup:neon"), + threadId: neonThreadId, + messageId: MessageId.make("msg:parent-followup:neon"), + text: "Follow up on section 2.2 row 14.", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "mcp", + }); + yield* worker.drain(); + yield* Fiber.join(neonFollowUpDone); + assert.equal((yield* orchestrator.getThreadProjection(neonThreadId)).runs.length, 2); + + // 4. Genuinely new human user input still runs cleanly. + const carbonFollowUpDone = yield* watchRunCompleted(carbonThreadId, 2); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("user-followup:carbon"), + threadId: carbonThreadId, + messageId: MessageId.make("msg:user-followup:carbon"), + text: "Can you clarify item 2?", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + yield* Fiber.join(carbonFollowUpDone); + assert.equal((yield* orchestrator.getThreadProjection(carbonThreadId)).runs.length, 2); + }).pipe(Effect.provide(layerTest)); + }), + ); + + it("blocks idle compaction and restart continuation on completed remote delegates", () => { + const threadId = ThreadId.make("thread:remote-delegate-guards"); + const runId = RunId.make("run:remote-delegate-1"); + const remoteThread = { + id: threadId, + deletedAt: null, + archivedAt: null, + settledAt: null, + settledOverride: null, + snoozedUntil: null, + activeProviderThreadId: ProviderThreadId.make("pt:1"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null }, + delegatedFrom: { + environmentId: leadEnvId, + threadId: leadThreadId, + title: "Lead", + }, + } as unknown as OrchestrationV2AppThread; + const completedRun = { + id: runId, + threadId, + ordinal: 1, + status: "completed", + userMessageId: MessageId.make("msg:1"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + providerThreadId: ProviderThreadId.make("pt:1"), + activeAttemptId: null, + startedAt: now, + completedAt: now, + } as unknown as OrchestrationV2Run; + + assert.isNull( + idleCompactionWindow( + { + thread: remoteThread, + runs: [completedRun], + messages: [ + { + id: MessageId.make("msg:1"), + text: "Run audit", + } as never, + ], + providerThreads: [], + providerTurns: [], + runtimeRequests: [], + turnItems: [], + contextTransfers: [], + }, + DateTime.toEpochMillis(now), + ), + ); + + assert.isTrue( + restartContinuationBlocked( + { + thread: remoteThread, + runtimeRequests: [], + providerTurns: [], + turnItems: [], + }, + completedRun, + now, + true, + ), + ); + }); + + it("policy distinguishes automatic restarts from genuine user/parent/child-work input", () => { + const threadId = ThreadId.make("thread:policy-delegate"); + const projection = { + thread: { + lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null }, + delegatedFrom: { environmentId: leadEnvId, threadId: leadThreadId, title: "Lead" }, + } as unknown as OrchestrationV2AppThread, + runs: [ + { + id: RunId.make("run:1"), + ordinal: 1, + status: "completed", + startedAt: now, + completedAt: now, + } as unknown as OrchestrationV2Run, + ], + }; + + // Automatic server output-gate bounce / system nudge / compaction -> suppressed + assert.isTrue( + shouldSuppressCompletedDelegateDispatch(projection, { + messageId: outputGateBounceMessageId(RunId.make("run:1")), + createdBy: "agent", + creationSource: "server", + notification: { source: { kind: "monitor" }, outcome: "updated", summary: "Bounce" }, + }), + ); + assert.isTrue( + shouldSuppressCompletedDelegateDispatch(projection, { + messageId: MessageId.make("message:delegation-nudge:run:1:1"), + createdBy: "agent", + creationSource: "server", + notification: { source: { kind: "system" }, outcome: "updated", summary: "Nudge" }, + }), + ); + assert.isTrue( + shouldSuppressCompletedDelegateDispatch(projection, { + messageId: MessageId.make("message:idle-compact"), + createdBy: "agent", + creationSource: "server", + idleCompaction: "beforeCacheExpires", + }), + ); + + // Genuine user, parent MCP send, grandchild completion, provider background work, or non-bounce monitor -> allowed + assert.isFalse( + shouldSuppressCompletedDelegateDispatch(projection, { + messageId: MessageId.make("message:user-followup"), + createdBy: "user", + creationSource: "web", + }), + ); + assert.isFalse( + shouldSuppressCompletedDelegateDispatch(projection, { + messageId: MessageId.make("message:parent-followup"), + createdBy: "agent", + creationSource: "mcp", + }), + ); + assert.isFalse( + shouldSuppressCompletedDelegateDispatch(projection, { + messageId: MessageId.make("message:grandchild-completion"), + createdBy: "agent", + creationSource: "server", + delegatedCompletion: { + parentRunId: RunId.make("run:1"), + generation: 1, + taskIds: [NodeId.make("node:grandchild")], + }, + }), + ); + assert.isFalse( + shouldSuppressCompletedDelegateDispatch(projection, { + messageId: MessageId.make("message:provider-monitor-completed"), + createdBy: "agent", + creationSource: "provider", + notification: { + source: { kind: "monitor" }, + outcome: "completed", + summary: 'Monitor "sleep 60" finished', + }, + }), + ); + assert.isFalse( + shouldSuppressCompletedDelegateDispatch(projection, { + messageId: MessageId.make("message:followup-automatic-wake"), + createdBy: "agent", + creationSource: "server", + notification: { + source: { kind: "monitor" }, + outcome: "updated", + summary: "Monitor updated", + }, + }), + ); + }); +}); diff --git a/apps/server/src/orchestration-v2/DelegationNudgeReactor.ts b/apps/server/src/orchestration-v2/DelegationNudgeReactor.ts index fca9ac5fcea3e..48027aa473ad9 100644 --- a/apps/server/src/orchestration-v2/DelegationNudgeReactor.ts +++ b/apps/server/src/orchestration-v2/DelegationNudgeReactor.ts @@ -1,5 +1,6 @@ import { CommandId, + isDelegatedAppThread, MessageId, type OrchestrationV2DomainEvent, type OrchestrationV2Run, @@ -160,11 +161,13 @@ export const make = Effect.gen(function* () { item: OrchestrationV2TurnItem | null, ) { const records = yield* projections.getThreadRecords(threadId, ["runs"]); + if (isDelegatedAppThread(records.thread)) return; const setting = records.thread.delegationNudge; if (setting?.enabled !== true) return; const run = records.runs.find((candidate) => candidate.id === runId); if (run === undefined || (run.status !== "running" && run.status !== "starting")) return; const watch = watchFor(run); + const previousStats = watch.stats; if (watch.seen.size === 0 && run.delegationNudge === undefined) { const prior = yield* projections.getThreadRecords(threadId, ["turnItems"], { turnItemRunId: run.id, @@ -179,7 +182,7 @@ export const make = Effect.gen(function* () { watch.stats.delegations > 0 || watch.stats.countedToolCalls < threshold ) { - if (item !== null) yield* record(threadId, run, watch.stats); + if (item !== null && watch.stats !== previousStats) yield* record(threadId, run, watch.stats); return; } const note = delegationNudgeNote(threshold, watch.stats.nudgesFired > 0); diff --git a/apps/server/src/orchestration-v2/IdleCompaction.ts b/apps/server/src/orchestration-v2/IdleCompaction.ts index 5d68d558ed8e0..83099d1b615a2 100644 --- a/apps/server/src/orchestration-v2/IdleCompaction.ts +++ b/apps/server/src/orchestration-v2/IdleCompaction.ts @@ -1,4 +1,8 @@ -import { isListedThreadLineage, type OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import { + isDelegatedAppThread, + isListedThreadLineage, + type OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; import { COMPACTION_SUGGESTION_MIN_TOKENS } from "@t3tools/shared/claudeCompaction"; import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { isWaitingDigestRun } from "@t3tools/shared/orchestrationV2ThreadError"; @@ -51,7 +55,7 @@ export function idleCompactionWindow( if (thread.settledAt !== null || thread.settledOverride === "settled") return null; if (thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs) return null; - if (!isListedThreadLineage(thread.lineage)) return null; + if (!isListedThreadLineage(thread.lineage) || isDelegatedAppThread(thread)) return null; // A removed or steered queued message leaves a cancelled run that never started. const latestRun = runs .filter( diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index aa2babc0b6341..e1266d65a1707 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -44,6 +44,7 @@ import { PR_WATCH_STALE_MINUTES, type GuestMessageId, isCompactionCommandMessage, + isDelegatedAppThread, isDeliveredProviderTurn, isOrchestrationV2WorkActive, isProviderNativeSubagentThread, @@ -164,6 +165,7 @@ import { providerTurnCapabilities, resolveMessageDispatch, resolveMessageDispatchIntent, + shouldSuppressCompletedDelegateDispatch, } from "./CommandPolicy.ts"; import { CommandReceiptStoreV2, type CommandReceiptV2 } from "./CommandReceiptStore.ts"; import { @@ -8558,6 +8560,36 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return; } + const completedDelegateProjection = + isDelegatedAppThread(projection.thread) && + projection.runs.some((run) => run.status === "waiting") + ? { + thread: projection.thread, + // `readCommandProjection` masks a completed run as `waiting` during turn-end capture. + runs: (yield* projectionStore + .getThreadRecords(command.threadId, ["runs"]) + .pipe(mapDispatchError(command))).runs, + } + : projection; + if (shouldSuppressCompletedDelegateDispatch(completedDelegateProjection, command)) { + yield* Effect.logInfo("orchestration-v2.completed-delegate.auto-restart-suppressed", { + threadId: command.threadId, + commandId: command.commandId, + creationSource: command.creationSource, + notificationKind: command.notification?.source.kind, + }); + yield* emit( + events, + command, + )({ + type: "thread.metadata-updated", + threadId: command.threadId, + occurredAt: yield* DateTime.now, + payload: projection.thread, + }); + return; + } + if (projection.thread.lastVisitedAt === null && !isNativeMaintenanceCommand(command)) { const now = yield* DateTime.now; // Null keeps imported history read. The first fresh dispatch establishes diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index aecbcd067b3ec..db3d990384c2d 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2633,7 +2633,8 @@ export const layerWithOptions = ( // start instead of running it on a runtime being torn down. Effect.flatMap((marked) => marked - ? Effect.void + ? // Every provider's turn starts on a fresh tool-result epoch so loop-guard streaks reset across turns. + mcpSessions.clearToolResults(input.threadId) : Effect.fail( new ProviderAdapter.ProviderAdapterTurnStartError({ driver: runtime.driver, diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts index 806f17c20c197..6f04cb9861f9c 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.ts @@ -2,6 +2,7 @@ import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { CommandId, + isDelegatedAppThread, isOrchestrationV2WorkActive, latestProviderTurnForAttempt, MessageId, @@ -56,7 +57,8 @@ export function restartContinuationBlocked( thread.archivedAt !== null || thread.deletedAt !== null || thread.settledOverride === "settled" || - (thread.snoozedUntil != null && DateTime.isGreaterThan(thread.snoozedUntil, now)) + (thread.snoozedUntil != null && DateTime.isGreaterThan(thread.snoozedUntil, now)) || + (settled && source.status === "completed" && isDelegatedAppThread(thread)) ) return true; const turn = latestProviderTurnForAttempt(projection.providerTurns, source.activeAttemptId); diff --git a/apps/server/src/orchestration-v2/testkit/pullRequestFixtures.ts b/apps/server/src/orchestration-v2/testkit/pullRequestFixtures.ts index 63b490cc7e9d1..655b38ec30c20 100644 --- a/apps/server/src/orchestration-v2/testkit/pullRequestFixtures.ts +++ b/apps/server/src/orchestration-v2/testkit/pullRequestFixtures.ts @@ -23,6 +23,7 @@ export interface PullRequestTestThread { readonly branchPullRequest?: ThreadLinkedPullRequest | null; readonly latestUserMessageAt: string | null; readonly lineage?: OrchestrationV2ThreadShell["lineage"]; + readonly delegatedFrom?: OrchestrationV2ThreadShell["delegatedFrom"]; readonly createdAt: string; readonly updatedAt: string; readonly archivedAt: string | null; @@ -52,6 +53,7 @@ export function v2PullRequestThread(thread: PullRequestTestThread): Orchestratio parentThreadId: null, relationshipToParent: null, }, + ...(thread.delegatedFrom === undefined ? {} : { delegatedFrom: thread.delegatedFrom }), forkedFrom: null, latestRunId: null, activeRunId: null, diff --git a/apps/server/src/pullRequest/PullRequestWatchService.test.ts b/apps/server/src/pullRequest/PullRequestWatchService.test.ts index 2a02bd7967952..6c48454d99afc 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.test.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.test.ts @@ -1,4 +1,5 @@ import { + EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, @@ -312,6 +313,22 @@ describe("PullRequestWatchService", () => { .pipe(Effect.flip); expect(error).toMatchObject({ _tag: "PullRequestWatchFromSubagentError" }); expect(yield* Ref.get(harness.commands)).toEqual([]); + + const remoteHarness = yield* makeHarness({ + thread: { + ...makeThread([makeLink(1, { headBranch: "feature" })]), + delegatedFrom: { + environmentId: EnvironmentId.make("env:r720"), + threadId: ThreadId.make("parent"), + title: "Parent", + }, + }, + }); + const remoteError = yield* remoteHarness + .setWatching(true, { repository: "t3tools/t3code", number: 1 }) + .pipe(Effect.flip); + expect(remoteError).toMatchObject({ _tag: "PullRequestWatchFromSubagentError" }); + expect(yield* Ref.get(remoteHarness.commands)).toEqual([]); }), ); }); diff --git a/apps/server/src/pullRequest/PullRequestWatchService.ts b/apps/server/src/pullRequest/PullRequestWatchService.ts index 953f956445f3f..2fc6108e1648a 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.ts @@ -1,5 +1,6 @@ import { CommandId, + isDelegatedAppThread, PR_WATCH_STALE_MINUTES, ThreadId, type OrchestrationV2ThreadShell, @@ -117,7 +118,7 @@ const make = Effect.gen(function* () { threadPullRequestsOf(shell).find( (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target), ); - if (watching && thread.lineage.relationshipToParent === "subagent") { + if (watching && isDelegatedAppThread(thread)) { return yield* new PullRequestWatchFromSubagentError(); } const before = watchedLink(thread);