Skip to content
TypeScript

fix(server): interrupts started by an agent no longer say "by user" in the timeline (#24299)

Julius Marminge7d87be359696
diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts
index 2c11d6e3b6e..8f39c2e452a 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.ts
@@ -278,6 +278,11 @@ function threadManagementFailure(error: unknown): OrchestratorMcpFailure {
}
}
+// Without a reason, a Stop reads as the user's (see RunExecutionService.USER_STOP_REASON).
+function agentStopReason(reason: string | undefined): string {
+ return reason === undefined ? "Stopped by an agent" : `Stopped by an agent: ${reason}`;
+}
+
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
@@ -2379,14 +2384,14 @@ const make = Effect.gen(function* () {
);
const stopChild = Effect.gen(function* () {
const commandId = stableCommandId({ scope, requestKey: key, operation: "cancel-task" });
- const reason = input.reason;
+ const reason = agentStopReason(input.reason);
yield* threadManagement
.dispatch({
type: "thread.stop",
commandId,
threadId: current.childThreadId,
stopDelegatedTasks: false,
- ...(reason === undefined ? {} : { reason }),
+ reason,
})
.pipe(
Effect.mapError((error) =>
@@ -2907,7 +2912,7 @@ const make = Effect.gen(function* () {
}),
threadId: input.threadId,
...(input.runId === undefined ? {} : { runId: input.runId }),
- ...(input.reason === undefined ? {} : { reason: input.reason }),
+ reason: agentStopReason(input.reason),
})
.pipe(
Effect.mapError((error) =>
diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
index 09b4bd4f424..d47fb11fe6a 100644
--- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
+++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
@@ -491,6 +491,14 @@ describe("orchestrator MCP toolkit", () => {
expect(finalProjection.runs.find((run) => run.id === queuedFollowup.runId)?.status).toBe(
"completed",
);
+ expect(
+ finalProjection.turnItems.find(
+ (item) =>
+ item.runId === runningFollowup.runId && item.type === "run_interrupt_result",
+ ),
+ ).toMatchObject({
+ message: "Stopped by an agent: Allow the queued replay follow-up to run.",
+ });
yield* orchestrator
.streamStoredEventsFrom({
threadId: parentThreadId,
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 33b434169fe..d2e9333c699 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -8977,6 +8977,31 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}
});
+ const runInterruptReason = Effect.fnUntraced(function* (
+ command: Extract<
+ OrchestrationV2ServerCommand,
+ { readonly type: "run.interrupt" | "thread.background-work.settle" }
+ >,
+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
+ runId: RunId,
+ ) {
+ const isRequest = (
+ item: OrchestrationV2TurnItem,
+ ): item is Extract<OrchestrationV2TurnItem, { readonly type: "run_interrupt_request" }> =>
+ item.runId === runId && item.type === "run_interrupt_request";
+ const pending = (yield* Ref.get(events))
+ .flatMap((event) => (event.type === "turn-item.updated" ? [event.payload] : []))
+ .findLast(isRequest);
+ if (pending !== undefined) return pending.message;
+ const { turnItems } = yield* projectionStore
+ .getThreadRecords(command.threadId, ["turnItems"], {
+ turnItemTypes: ["run_interrupt_request"],
+ turnItemRunIds: [runId],
+ })
+ .pipe(mapDispatchError(command));
+ return turnItems.find(isRequest)?.message;
+ });
+
// A successful Stop may have no terminal event to ingest: the session or
// native turn already died, or its final write failed when storage filled.
const settleInterruptedRun = Effect.fn("Orchestrator.settleInterruptedRun")(function* (input: {
@@ -9127,6 +9152,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
run,
rootNode,
providerThread,
+ reason: yield* runInterruptReason(input.command, input.events, run.id),
completedAt: input.now,
}),
});
@@ -9226,7 +9252,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
completedAt: now,
updatedAt: now,
type: "run_interrupt_request",
- message: command.reason ?? "Interrupt requested",
+ message: command.reason ?? RunExecutionService.USER_STOP_REASON,
},
});
});
@@ -9755,7 +9781,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
completedAt: now,
updatedAt: now,
type: "run_interrupt_request",
- message: command.reason ?? "Interrupt requested",
+ message: command.reason ?? RunExecutionService.USER_STOP_REASON,
};
const otherProviderInterrupts: Array<PendingOrchestrationEffectV2> = [];
diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
index 89ae2cc2c0c..4eb988ec430 100644
--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
@@ -191,6 +191,19 @@ export const layer: Layer.Layer<
}),
)
.pipe(Effect.catchCause(() => Effect.succeed(false))),
+ loadRunInterruptReason: () =>
+ projectionStore
+ .getThreadRecords(input.threadId, ["turnItems"], {
+ turnItemTypes: ["run_interrupt_request"],
+ turnItemRunIds: [input.runId],
+ })
+ .pipe(
+ Effect.map(({ turnItems }) => {
+ const request = turnItems.find((item) => item.type === "run_interrupt_request");
+ return request?.type === "run_interrupt_request" ? request.message : undefined;
+ }),
+ Effect.catchCause(() => Effect.succeed(undefined)),
+ ),
};
};
@@ -1319,6 +1332,7 @@ export const layer: Layer.Layer<
shouldStartProviderTurn: runControls.shouldStartProviderTurn,
shouldFinalizeRun: runControls.shouldFinalizeRun,
hasUnpairedRunInterruptRequest: runControls.hasUnpairedRunInterruptRequest,
+ loadRunInterruptReason: runControls.loadRunInterruptReason,
message: {
messageId: message.id,
text: userText,
diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts
index a2b4f1de5bc..11ab94cefa6 100644
--- a/apps/server/src/orchestration-v2/RunExecutionService.ts
+++ b/apps/server/src/orchestration-v2/RunExecutionService.ts
@@ -573,6 +573,7 @@ export interface RunExecutionServiceV2StartRootRunInput {
readonly shouldStartProviderTurn?: () => Effect.Effect<boolean, ProjectionStoreV2Error>;
readonly shouldFinalizeRun?: () => Effect.Effect<boolean, ProjectionStoreV2Error>;
readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
+ readonly loadRunInterruptReason?: () => Effect.Effect<string | undefined, never>;
readonly message: ProviderAdapter.ProviderAdapterV2TurnMessage;
readonly modelSelection: ModelSelection;
readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
@@ -621,6 +622,7 @@ export const layer: Layer.Layer<
readonly attempt: OrchestrationV2RunAttempt;
readonly shouldFinalizeRun?: () => Effect.Effect<boolean, ProjectionStoreV2Error>;
readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
+ readonly loadRunInterruptReason?: () => Effect.Effect<string | undefined, never>;
readonly openRunOwnedSubagents?: OpenRunOwnedSubagentProjection;
readonly interruptedProviderTurn?: OrchestrationV2ProviderTurn;
readonly terminal: ProviderTerminalEvent;
@@ -647,6 +649,10 @@ export const layer: Layer.Layer<
? false
: yield* input.hasUnpairedRunInterruptRequest();
if (hasUnpairedRequest) {
+ const reason =
+ input.loadRunInterruptReason === undefined
+ ? undefined
+ : yield* input.loadRunInterruptReason();
yield* eventSink.writeWithEffects({
effects: [],
events: [
@@ -663,6 +669,7 @@ export const layer: Layer.Layer<
run: input.run,
rootNode: input.rootNode,
providerThread: input.providerThread,
+ reason,
completedAt,
}),
},
@@ -674,6 +681,10 @@ export const layer: Layer.Layer<
return;
}
const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId });
+ const reason =
+ input.terminal.status === "interrupted" && input.loadRunInterruptReason !== undefined
+ ? yield* input.loadRunInterruptReason()
+ : undefined;
const open = input.openRunOwnedSubagents ?? emptyOpenRunOwnedSubagentProjection();
const hasOpenSubagentProjection =
open.subagents.size > 0 ||
@@ -791,6 +802,7 @@ export const layer: Layer.Layer<
run: input.run,
rootNode: input.rootNode,
providerThread: input.providerThread,
+ reason,
completedAt,
}),
},
@@ -1060,6 +1072,9 @@ export const layer: Layer.Layer<
: {
hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest,
}),
+ ...(input.loadRunInterruptReason === undefined
+ ? {}
+ : { loadRunInterruptReason: input.loadRunInterruptReason }),
openRunOwnedSubagents: openSubagents,
terminal,
failureItemPersisted: terminal.status === "failed",
@@ -1684,11 +1699,19 @@ export const layer: Layer.Layer<
}),
);
+/**
+ * Clients send Stop without a reason; server callers acting for an agent
+ * always set one, so a missing reason means a person stopped the run.
+ */
+export const USER_STOP_REASON = "Stopped by user";
+
export function makeInterruptResultTurnItem(input: {
readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
readonly run: OrchestrationV2Run;
readonly rootNode: OrchestrationV2ExecutionNode;
readonly providerThread: OrchestrationV2ProviderThread;
+ /** The Stop's own reason, from its run_interrupt_request item. */
+ readonly reason: string | undefined;
readonly completedAt: DateTime.Utc;
}): OrchestrationV2TurnItem {
return {
@@ -1713,6 +1736,6 @@ export function makeInterruptResultTurnItem(input: {
completedAt: input.completedAt,
updatedAt: input.completedAt,
type: "run_interrupt_result",
- message: "Run interrupted by user",
+ message: input.reason ?? "Stopped by the provider",
};
}