Skip to content

Commit ca9a5e0

Browse files
t3dotggclaude
andcommitted
fix(server): an agent can settle its own thread when its turn ends
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 9381533 commit ca9a5e0

7 files changed

Lines changed: 156 additions & 14 deletions

File tree

‎apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts‎

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -767,17 +767,13 @@ describe("orchestrator MCP toolkit", () => {
767767
const invoke = (name: string, args: Record<string, unknown>) =>
768768
invokeAs(invocation, name, args);
769769

770-
const refusedSettle = yield* invoke("t3_thread_organize", { action: "settle" });
771-
expect(refusedSettle.isError).toBe(true);
772-
expect(refusedSettle.structuredContent).toBeUndefined();
773-
expect(declaredFailure(refusedSettle)).toEqual({
774-
_tag: "OrchestratorMcpFailure",
775-
code: "orchestration_error",
776-
message: `Thread ${parentThreadId} has active or blocked work and cannot be settled.`,
777-
});
778-
const afterRefusedSettle = yield* orchestrator.getThreadProjection(parentThreadId);
779-
expect(afterRefusedSettle.thread.settledOverride).not.toBe("settled");
780-
expect(afterRefusedSettle.runs.find((run) => run.id === parentRun?.id)?.status).toBe(
770+
// Settling would stop the session, so the agent's own turn keeps running.
771+
const deferredSettle = yield* invoke("t3_thread_organize", { action: "settle" });
772+
expect(deferredSettle.isError).toBe(false);
773+
expect(deferredSettle.structuredContent).toEqual({ settlesWhenTurnEnds: true });
774+
const afterDeferredSettle = yield* orchestrator.getThreadProjection(parentThreadId);
775+
expect(afterDeferredSettle.thread.settledOverride).not.toBe("settled");
776+
expect(afterDeferredSettle.runs.find((run) => run.id === parentRun?.id)?.status).toBe(
781777
"running",
782778
);
783779

‎apps/server/src/mcp/toolkits/thread/handlers.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,23 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
292292
),
293293
t3_thread_organize: writesThread((input) =>
294294
Effect.gen(function* () {
295-
const { threads, projection } = yield* readThread(input.threadId);
295+
const { threads, projection, caller } = yield* readThread(input.threadId);
296+
// An agent settling its own thread is always mid-turn, and settling
297+
// stops the provider session. Its thread settles when the turn completes.
298+
if (
299+
input.action === "settle" &&
300+
caller?.id === projection.thread.id &&
301+
caller.activeRunId !== null
302+
) {
303+
yield* threads
304+
.settleAfterRun({
305+
projectId: caller.projectId,
306+
threadId: caller.id,
307+
runId: caller.activeRunId,
308+
})
309+
.pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach);
310+
return { settlesWhenTurnEnds: true as const };
311+
}
296312
const common = { commandId: yield* newCommandId(), threadId: projection.thread.id };
297313
let command: OrchestrationV2Command;
298314
switch (input.action) {

‎apps/server/src/mcp/toolkits/thread/tools.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import * as McpInvocationContext from "../../McpInvocationContext.ts";
3030

3131
const ThreadOrganizeTool = Tool.make("t3_thread_organize", {
3232
description:
33-
"Pin, snooze, settle, archive, or mark a thread unread. Omit threadId for this thread. snooze requires snoozedUntil. Existing thread lifecycle rules apply; this does not schedule a future action.",
33+
"Pin, snooze, settle, archive, or mark a thread unread. Omit threadId for this thread. snooze requires snoozedUntil. Existing thread lifecycle rules apply. Settling this thread takes effect when your turn completes, returning settlesWhenTurnEnds=true; a turn that fails or is interrupted, or a queued message, leaves it active.",
3434
parameters: Schema.Struct({
3535
threadId: Schema.optional(ThreadId),
3636
action: Schema.Literals([
@@ -46,7 +46,10 @@ const ThreadOrganizeTool = Tool.make("t3_thread_organize", {
4646
]),
4747
snoozedUntil: Schema.optional(IsoDateTime),
4848
}),
49-
success: OrchestrationV2DispatchCommandResult,
49+
success: Schema.Union([
50+
OrchestrationV2DispatchCommandResult,
51+
Schema.Struct({ settlesWhenTurnEnds: Schema.Literal(true) }),
52+
]),
5053
failure: OrchestratorMcpFailure,
5154
failureMode: "return" as const,
5255
dependencies: [

‎apps/server/src/orchestration-v2/ThreadManagementService.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,3 +473,40 @@ it.effect("waitForThread reads the run again only when the run updates", () =>
473473
expect(reads).toBe(2);
474474
}),
475475
);
476+
477+
it.effect.each([
478+
{ status: "completed" as const, settles: true },
479+
{ status: "failed" as const, settles: false },
480+
{ status: "interrupted" as const, settles: false },
481+
])("settleAfterRun settles only when the run $status", ({ status, settles }) =>
482+
Effect.gen(function* () {
483+
const projectId = ProjectId.make("project:thread-management:settle-after-run");
484+
const threadId = ThreadId.make("thread:thread-management:settle-after-run");
485+
const runId = RunId.make("run:thread-management:settle-after-run");
486+
const dispatched: Array<string> = [];
487+
const layerTest = ThreadManagementService.layer.pipe(
488+
Layer.provide(
489+
Layer.mock(Orchestrator.OrchestratorV2)({
490+
getThreadEventSequence: () => Effect.succeed(0),
491+
getThreadRecords: () =>
492+
Effect.succeed({
493+
thread: { id: threadId, projectId, deletedAt: null },
494+
runs: [{ id: runId, status }],
495+
} as unknown as OrchestrationV2ThreadProjection),
496+
dispatch: (command) =>
497+
Effect.sync(() => {
498+
dispatched.push(command.type);
499+
return { sequence: 1, storedEvents: [] } as never;
500+
}),
501+
}),
502+
),
503+
);
504+
const service = yield* ThreadManagementService.ThreadManagementService.pipe(
505+
Effect.provide(layerTest),
506+
);
507+
508+
yield* service.settleAfterRun({ projectId, threadId, runId });
509+
510+
expect(dispatched).toEqual(settles ? ["thread.settle"] : []);
511+
}),
512+
);

‎apps/server/src/orchestration-v2/ThreadManagementService.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,18 @@ export interface ThreadManagementServiceShape {
326326
readonly waitForThread: (
327327
input: ThreadManagementWaitInput,
328328
) => Effect.Effect<ThreadManagementWaitResult, ThreadManagementError>;
329+
/**
330+
* Waits for `runId` to end, then settles the thread if the run completed.
331+
* Settling stops the provider session, so an agent that settles its own
332+
* thread uses this to wait for its turn to end. A run that ends any other
333+
* way leaves the thread active, as does anything `thread.settle` refuses
334+
* then, such as a queued message.
335+
*/
336+
readonly settleAfterRun: (input: {
337+
readonly projectId: ProjectId;
338+
readonly threadId: ThreadId;
339+
readonly runId: RunId;
340+
}) => Effect.Effect<void, ThreadManagementFailure>;
329341
readonly interruptThread: (
330342
input: ThreadManagementInterruptInput,
331343
) => Effect.Effect<ThreadManagementInterruptResult, ThreadManagementFailure>;
@@ -402,6 +414,8 @@ function latestSteerableRun(
402414
.toSorted((left, right) => right.ordinal - left.ordinal)[0];
403415
}
404416

417+
const SETTLE_AFTER_RUN_WAIT_MS = 24 * 60 * 60 * 1_000;
418+
405419
const make = Effect.gen(function* () {
406420
const orchestrator = yield* Orchestrator.OrchestratorV2;
407421
const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
@@ -724,6 +738,19 @@ const make = Effect.gen(function* () {
724738
return { threadId: input.threadId, run, timedOut: !isTerminalRunStatus(run.status) };
725739
});
726740

741+
const settleAfterRun: ThreadManagementServiceShape["settleAfterRun"] = Effect.fn(
742+
"orchestrationV2.threadManagement.settleAfterRun",
743+
)(function* (input) {
744+
// A turn that outlives this wait leaves its thread active.
745+
const { run } = yield* waitForThread({ ...input, timeoutMs: SETTLE_AFTER_RUN_WAIT_MS });
746+
if (run?.status !== "completed") return;
747+
yield* dispatch({
748+
type: "thread.settle",
749+
commandId: CommandId.make(`server:settle-after-run:${input.runId}`),
750+
threadId: input.threadId,
751+
});
752+
});
753+
727754
const interruptThread: ThreadManagementServiceShape["interruptThread"] = (input) =>
728755
Effect.gen(function* () {
729756
const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
@@ -829,6 +856,7 @@ const make = Effect.gen(function* () {
829856
listProjectThreads,
830857
sendToThread,
831858
waitForThread,
859+
settleAfterRun,
832860
interruptThread,
833861
stopDelegatedTasks,
834862
getThreadEventSequence: orchestrator.getThreadEventSequence,

‎apps/server/src/orchestration-v2/runtimeLayer.test.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3373,6 +3373,67 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
33733373
}),
33743374
);
33753375

3376+
it.effect("settles a thread after the run it waits on completes", () =>
3377+
Effect.gen(function* () {
3378+
const orchestrator = yield* Orchestrator.OrchestratorV2;
3379+
const eventSink = yield* EventSink.EventSinkV2;
3380+
const threadManagement = yield* ThreadManagementService.ThreadManagementService;
3381+
const projectId = ProjectId.make("runtime-layer-settle-after-run-project");
3382+
const threadId = ThreadId.make("runtime-layer-settle-after-run-thread");
3383+
3384+
yield* orchestrator.dispatch({
3385+
type: "thread.create",
3386+
createdBy: "user",
3387+
creationSource: "web",
3388+
commandId: CommandId.make("runtime-layer-settle-after-run-create"),
3389+
threadId,
3390+
projectId,
3391+
title: "Settle after run",
3392+
modelSelection,
3393+
runtimeMode: "full-access",
3394+
interactionMode: "default",
3395+
branch: null,
3396+
worktreePath: "/tmp/runtime-layer-settle-after-run",
3397+
});
3398+
yield* orchestrator.dispatch({
3399+
type: "message.dispatch",
3400+
createdBy: "user",
3401+
creationSource: "web",
3402+
commandId: CommandId.make("runtime-layer-settle-after-run-message"),
3403+
threadId,
3404+
messageId: MessageId.make("runtime-layer-settle-after-run-message"),
3405+
text: "Fix it and then settle this thread.",
3406+
attachments: [],
3407+
modelSelection,
3408+
dispatchMode: { type: "start_immediately" },
3409+
});
3410+
const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0];
3411+
if (run === undefined) return yield* Effect.die(new Error("Run missing."));
3412+
3413+
const settling = yield* threadManagement
3414+
.settleAfterRun({ projectId, threadId, runId: run.id })
3415+
.pipe(Effect.forkChild);
3416+
const now = yield* DateTime.now;
3417+
yield* eventSink.write({
3418+
commandId: CommandId.make("runtime-layer-settle-after-run-completed"),
3419+
events: [
3420+
{
3421+
id: EventId.make("runtime-layer-settle-after-run-completed"),
3422+
type: "run.updated",
3423+
threadId,
3424+
runId: run.id,
3425+
occurredAt: now,
3426+
payload: { ...run, status: "completed", startedAt: now, completedAt: now },
3427+
},
3428+
],
3429+
});
3430+
yield* Fiber.join(settling);
3431+
3432+
const projection = yield* orchestrator.getThreadProjection(threadId);
3433+
assert.equal(projection.thread.settledOverride, "settled");
3434+
}),
3435+
);
3436+
33763437
it.effect("settles past held automatic runs but not held user messages", () =>
33773438
Effect.gen(function* () {
33783439
const orchestrator = yield* Orchestrator.OrchestratorV2;

‎apps/server/src/relay/AgentAwarenessRelay.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,7 @@ const makeTestRelay = Effect.fnUntraced(function* (
206206
listProjectThreads: unused,
207207
sendToThread: unused,
208208
waitForThread: unused,
209+
settleAfterRun: unused,
209210
interruptThread: unused,
210211
stopDelegatedTasks: unused,
211212
getThreadEventSequence: unused,

0 commit comments

Comments
 (0)