Skip to content

Commit dfedee3

Browse files
renemifsudclaude
andcommitted
fix(server): an agent can mark its own thread unread when its turn ends
An agent that calls t3_thread_organize with mark_unread on its own thread mid-turn was refused, because marking unread rewinds the visit to just before the latest run completed and the latest run is the caller's active one. It now waits for that turn, the way settle does, marks the thread unread if the turn completed, and returns marksUnreadWhenTurnEnds=true. Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 66ee628 commit dfedee3

6 files changed

Lines changed: 182 additions & 6 deletions

File tree

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

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,11 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
301301
.settleThread({ ...common, byOwnAgent: caller?.id === projection.thread.id })
302302
.pipe(Effect.mapError(dispatchFailure));
303303
}
304+
if (input.action === "mark_unread") {
305+
return yield* threads
306+
.markThreadUnread({ ...common, byOwnAgent: caller?.id === projection.thread.id })
307+
.pipe(Effect.mapError(dispatchFailure));
308+
}
304309
let command: OrchestrationV2Command;
305310
switch (input.action) {
306311
case "snooze":
@@ -316,9 +321,6 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
316321
case "unsettle":
317322
command = { ...common, type: `thread.${input.action}`, reason: "user" };
318323
break;
319-
case "mark_unread":
320-
command = { ...common, type: "thread.mark-unread" };
321-
break;
322324
default:
323325
command = { ...common, type: `thread.${input.action}` };
324326
}

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

Lines changed: 2 additions & 1 deletion
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. 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.",
33+
"Pin, snooze, settle, archive, or mark a thread unread. Omit threadId for this thread. snooze requires snoozedUntil. Existing thread lifecycle rules apply. Settling or marking this thread unread takes effect when your turn completes, returning settlesWhenTurnEnds=true or marksUnreadWhenTurnEnds=true; a turn that fails or is interrupted, or a queued message, leaves the thread unchanged.",
3434
parameters: Schema.Struct({
3535
threadId: Schema.optional(ThreadId),
3636
action: Schema.Literals([
@@ -49,6 +49,7 @@ const ThreadOrganizeTool = Tool.make("t3_thread_organize", {
4949
success: Schema.Union([
5050
OrchestrationV2DispatchCommandResult,
5151
Schema.Struct({ settlesWhenTurnEnds: Schema.Literal(true) }),
52+
Schema.Struct({ marksUnreadWhenTurnEnds: Schema.Literal(true) }),
5253
]),
5354
failure: OrchestratorMcpFailure,
5455
failureMode: "return" as const,

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

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,3 +337,44 @@ it.effect.each([
337337
expect(dispatched).toEqual(settles ? ["thread.settle"] : []);
338338
}),
339339
);
340+
341+
it.effect.each([
342+
{ status: "completed" as const, marks: true },
343+
{ status: "failed" as const, marks: false },
344+
{ status: "interrupted" as const, marks: false },
345+
])("markUnreadAfterRun marks unread only when the run $status", ({ status, marks }) =>
346+
Effect.gen(function* () {
347+
const projectId = ProjectId.make("project:thread-management:mark-unread-after-run");
348+
const threadId = ThreadId.make("thread:thread-management:mark-unread-after-run");
349+
const runId = RunId.make("run:thread-management:mark-unread-after-run");
350+
const dispatched: Array<string> = [];
351+
const layerTest = ThreadManagementService.layer.pipe(
352+
Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
353+
Layer.provide(
354+
Layer.mock(Orchestrator.OrchestratorV2)({
355+
getThreadEventSequence: () => Effect.succeed(0),
356+
restartContinuationPending: () => Effect.succeed(false),
357+
getThreadRecords: () =>
358+
Effect.succeed({
359+
thread: { id: threadId, projectId, deletedAt: null },
360+
runs: [{ id: runId, status }],
361+
} as unknown as OrchestrationV2ThreadProjection),
362+
dispatch: (command) =>
363+
Effect.sync(() => {
364+
dispatched.push(command.type);
365+
return { sequence: 1, storedEvents: [] } as never;
366+
}),
367+
}),
368+
),
369+
Layer.provide(ServerSettings.layerTest()),
370+
Layer.provide(layerReceiptsTest),
371+
);
372+
const service = yield* ThreadManagementService.ThreadManagementService.pipe(
373+
Effect.provide(layerTest),
374+
);
375+
376+
yield* service.markUnreadAfterRun({ projectId, threadId, runId });
377+
378+
expect(dispatched).toEqual(marks ? ["thread.mark-unread"] : []);
379+
}),
380+
);

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

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,26 @@ export interface ThreadManagementServiceShape {
415415
{ readonly sequence: number } | { readonly settlesWhenTurnEnds: true },
416416
Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
417417
>;
418+
/**
419+
* Marking unread rewinds the visit to just before the latest run completed,
420+
* so an agent that marks its own thread unread uses this to wait for its
421+
* turn to end. A run that ends any other way leaves the thread as it was,
422+
* as does anything `thread.mark-unread` refuses then, such as a queued
423+
* message.
424+
*/
425+
readonly markUnreadAfterRun: (input: {
426+
readonly projectId: ProjectId;
427+
readonly threadId: ThreadId;
428+
readonly runId: RunId;
429+
}) => Effect.Effect<void, ThreadManagementFailure>;
430+
readonly markThreadUnread: (input: {
431+
readonly threadId: ThreadId;
432+
readonly commandId: CommandId;
433+
readonly byOwnAgent: boolean;
434+
}) => Effect.Effect<
435+
{ readonly sequence: number } | { readonly marksUnreadWhenTurnEnds: true },
436+
Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
437+
>;
418438
readonly interruptThread: (
419439
input: ThreadManagementInterruptInput,
420440
) => Effect.Effect<ThreadManagementInterruptResult, ThreadManagementFailure>;
@@ -505,7 +525,7 @@ function latestSteerableRun(
505525
.toSorted((left, right) => right.ordinal - left.ordinal)[0];
506526
}
507527

508-
const SETTLE_AFTER_RUN_WAIT_MS = 24 * 60 * 60 * 1_000;
528+
const AFTER_RUN_WAIT_MS = 24 * 60 * 60 * 1_000;
509529

510530
const make = Effect.gen(function* () {
511531
const threadDispatch = yield* ThreadCommandExecutor.ThreadCommandExecutor;
@@ -932,7 +952,7 @@ const make = Effect.gen(function* () {
932952
const settleAfterRun: ThreadManagementServiceShape["settleAfterRun"] = Effect.fn(
933953
"orchestrationV2.threadManagement.settleAfterRun",
934954
)(function* (input) {
935-
const { run } = yield* waitForThread({ ...input, timeoutMs: SETTLE_AFTER_RUN_WAIT_MS });
955+
const { run } = yield* waitForThread({ ...input, timeoutMs: AFTER_RUN_WAIT_MS });
936956
if (run?.status !== "completed") return;
937957
yield* dispatch({
938958
type: "thread.settle",
@@ -961,6 +981,38 @@ const make = Effect.gen(function* () {
961981
return { sequence: result.sequence };
962982
});
963983

984+
const markUnreadAfterRun: ThreadManagementServiceShape["markUnreadAfterRun"] = Effect.fn(
985+
"orchestrationV2.threadManagement.markUnreadAfterRun",
986+
)(function* (input) {
987+
const { run } = yield* waitForThread({ ...input, timeoutMs: AFTER_RUN_WAIT_MS });
988+
if (run?.status !== "completed") return;
989+
yield* dispatch({
990+
type: "thread.mark-unread",
991+
commandId: CommandId.make(`server:mark-unread-after-run:${input.runId}`),
992+
threadId: input.threadId,
993+
});
994+
});
995+
996+
const markThreadUnread: ThreadManagementServiceShape["markThreadUnread"] = Effect.fn(
997+
"orchestrationV2.threadManagement.markThreadUnread",
998+
)(function* (input) {
999+
const shell = input.byOwnAgent ? yield* orchestrator.getThreadShell(input.threadId) : null;
1000+
if (shell != null && shell.activeRunId !== null) {
1001+
yield* markUnreadAfterRun({
1002+
projectId: shell.projectId,
1003+
threadId: shell.id,
1004+
runId: shell.activeRunId,
1005+
}).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(layerScope));
1006+
return { marksUnreadWhenTurnEnds: true } as const;
1007+
}
1008+
const result = yield* dispatch({
1009+
type: "thread.mark-unread",
1010+
commandId: input.commandId,
1011+
threadId: input.threadId,
1012+
});
1013+
return { sequence: result.sequence };
1014+
});
1015+
9641016
const interruptThread: ThreadManagementServiceShape["interruptThread"] = Effect.fn(
9651017
"ThreadManagementService.interruptThread",
9661018
)(function* (input) {
@@ -1186,6 +1238,8 @@ const make = Effect.gen(function* () {
11861238
waitForThread,
11871239
settleAfterRun,
11881240
settleThread,
1241+
markUnreadAfterRun,
1242+
markThreadUnread,
11891243
interruptThread,
11901244
stopDelegatedTasks,
11911245
stopWorkflow,

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

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3700,6 +3700,82 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
37003700
}),
37013701
);
37023702

3703+
it.effect("marks a thread its own agent marked unread once the turn completes", () =>
3704+
Effect.gen(function* () {
3705+
const orchestrator = yield* Orchestrator.OrchestratorV2;
3706+
const eventSink = yield* EventSink.EventSinkV2;
3707+
const threadManagement = yield* ThreadManagementService.ThreadManagementService;
3708+
const projectId = ProjectId.make("runtime-layer-mark-unread-after-run-project");
3709+
const threadId = ThreadId.make("runtime-layer-mark-unread-after-run-thread");
3710+
3711+
yield* orchestrator.dispatch({
3712+
type: "thread.create",
3713+
createdBy: "user",
3714+
creationSource: "web",
3715+
commandId: CommandId.make("runtime-layer-mark-unread-after-run-create"),
3716+
threadId,
3717+
projectId,
3718+
title: "Mark unread after run",
3719+
modelSelection,
3720+
runtimeMode: "full-access",
3721+
interactionMode: "default",
3722+
branch: null,
3723+
worktreePath: "/tmp/runtime-layer-mark-unread-after-run",
3724+
});
3725+
yield* orchestrator.dispatch({
3726+
type: "message.dispatch",
3727+
createdBy: "user",
3728+
creationSource: "web",
3729+
commandId: CommandId.make("runtime-layer-mark-unread-after-run-message"),
3730+
threadId,
3731+
messageId: MessageId.make("runtime-layer-mark-unread-after-run-message"),
3732+
text: "Report back and then mark this thread unread.",
3733+
attachments: [],
3734+
modelSelection,
3735+
dispatchMode: { type: "start_immediately" },
3736+
});
3737+
const started = yield* orchestrator.getThreadProjection(threadId);
3738+
const run = started.runs[0];
3739+
if (run === undefined) return yield* Effect.die(new Error("Run missing."));
3740+
3741+
const markedUnread = yield* orchestrator
3742+
.streamStoredEventsFrom({ threadId, afterSequence: 0, eventType: "thread.marked-unread" })
3743+
.pipe(Stream.runHead, Effect.forkChild);
3744+
const result = yield* threadManagement.markThreadUnread({
3745+
threadId,
3746+
commandId: CommandId.make("runtime-layer-mark-unread-after-run-mark"),
3747+
byOwnAgent: true,
3748+
});
3749+
assert.deepEqual(result, { marksUnreadWhenTurnEnds: true });
3750+
assert.deepEqual(
3751+
(yield* orchestrator.getThreadProjection(threadId)).thread.lastVisitedAt,
3752+
started.thread.lastVisitedAt,
3753+
);
3754+
yield* TestClock.adjust("1 second");
3755+
const now = yield* DateTime.now;
3756+
yield* eventSink.write({
3757+
commandId: CommandId.make("runtime-layer-mark-unread-after-run-completed"),
3758+
events: [
3759+
{
3760+
id: EventId.make("runtime-layer-mark-unread-after-run-completed"),
3761+
type: "run.updated",
3762+
threadId,
3763+
runId: run.id,
3764+
occurredAt: now,
3765+
payload: { ...run, status: "completed", startedAt: now, completedAt: now },
3766+
},
3767+
],
3768+
});
3769+
yield* Fiber.join(markedUnread);
3770+
3771+
const projection = yield* orchestrator.getThreadProjection(threadId);
3772+
assert.deepEqual(
3773+
projection.thread.lastVisitedAt,
3774+
DateTime.subtract(now, { milliseconds: 1 }),
3775+
);
3776+
}),
3777+
);
3778+
37033779
it.effect("settles past held automatic runs but not held user messages", () =>
37043780
Effect.gen(function* () {
37053781
const orchestrator = yield* Orchestrator.OrchestratorV2;

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,8 @@ const makeTestRelay = Effect.fnUntraced(function* (
213213
waitForThread: unused,
214214
settleAfterRun: unused,
215215
settleThread: unused,
216+
markUnreadAfterRun: unused,
217+
markThreadUnread: unused,
216218
interruptThread: unused,
217219
stopWorkflow: () => Effect.die("unused stopWorkflow"),
218220
stopDelegatedTasks: unused,

0 commit comments

Comments
 (0)