Skip to content

Commit bb78361

Browse files
feat(server): t3_thread_launch takes clientRequestId
A launch had no retry key, so an agent (or another environment calling on its behalf) that lost the response could only guess whether the thread was created, and a retry started a second one. t3_thread_launch now takes an optional clientRequestId. The command, thread and message ids derive from the caller and the key, and the launch service already replays a command it accepted, so a retry returns the first thread. Without a key every launch is new, as before. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 4fac0b1 commit bb78361

6 files changed

Lines changed: 214 additions & 13 deletions

File tree

‎apps/server/src/mcp/toolkits/project/handlers.test.ts‎

Lines changed: 131 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
type Project as ProjectRecord,
77
type ModelSelection,
88
type RuntimeMode,
9+
type OrchestrationV2ThreadShell,
910
} from "@t3tools/contracts";
1011
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
1112
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -44,6 +45,10 @@ const clientLaunchHarness = (input: {
4445
instanceId: ProviderInstanceId.make("claudeAgent"),
4546
model: "claude-opus",
4647
};
48+
// The project's own default model, which a test can clear between launches.
49+
const projectDefaults: { model: ModelSelection | null } = {
50+
model: input.overrideModel === undefined ? modelSelection : null,
51+
};
4752
const layerDependencies = Layer.mergeAll(
4853
ServerSettings.layerTest({
4954
...(input.defaultRuntimeMode === undefined
@@ -71,7 +76,22 @@ const clientLaunchHarness = (input: {
7176
issuedAt: 0,
7277
capabilities: new Set(["orchestration" as const]),
7378
}),
74-
Layer.mock(ThreadManagement.ThreadManagementService)({}),
79+
Layer.mock(ThreadManagement.ThreadManagementService)({
80+
// A thread exists once a launch started it.
81+
getThreadShell: (threadId) => {
82+
const launch = input.launched.find((candidate) => candidate.threadId === threadId);
83+
return Effect.succeed(
84+
launch === undefined
85+
? null
86+
: ({
87+
id: launch.threadId,
88+
projectId: launch.projectId,
89+
modelSelection: launch.modelSelection,
90+
deletedAt: null,
91+
} as unknown as OrchestrationV2ThreadShell),
92+
);
93+
},
94+
}),
7595
Layer.mock(ThreadLaunch.ThreadLaunchService)({
7696
checkWorktreeBase: input.checkWorktreeBase ?? (() => Effect.void),
7797
launch: (launch) => {
@@ -98,7 +118,7 @@ const clientLaunchHarness = (input: {
98118
? Option.some({
99119
id,
100120
workspaceRoot: input.workspaceRoot ?? "/projects/client-target",
101-
defaultModelSelection: input.overrideModel === undefined ? modelSelection : null,
121+
defaultModelSelection: projectDefaults.model,
102122
} as unknown as ProjectRecord)
103123
: Option.none(),
104124
),
@@ -115,7 +135,7 @@ const clientLaunchHarness = (input: {
115135
),
116136
Layer.provideMerge(NodeServices.layer),
117137
);
118-
return { projectId, modelSelection, dependencies: layerDependencies };
138+
return { projectId, modelSelection, projectDefaults, dependencies: layerDependencies };
119139
};
120140

121141
it.effect(
@@ -200,6 +220,71 @@ it.effect(
200220
}),
201221
);
202222

223+
it.effect("a launch retried with the same clientRequestId replays the first one", () =>
224+
Effect.gen(function* () {
225+
const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
226+
const { projectId, dependencies } = clientLaunchHarness({
227+
runtimeModeCeiling: "auto",
228+
launched,
229+
});
230+
const toolkit = yield* ProjectToolkit.pipe(
231+
Effect.provide(
232+
McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
233+
),
234+
);
235+
const launch = (clientRequestId: string | undefined) =>
236+
toolkit
237+
.handle("t3_thread_launch", {
238+
title: "Fix",
239+
projectId,
240+
message: "Fix the bug",
241+
...(clientRequestId === undefined ? {} : { clientRequestId }),
242+
})
243+
.pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
244+
245+
yield* launch("fix-1");
246+
yield* launch("fix-1");
247+
yield* launch("fix-2");
248+
yield* launch(undefined);
249+
yield* launch(undefined);
250+
const ids = launched.map((input) => [input.commandId, input.threadId]);
251+
// The same key sends the same command and thread ids, which the launch
252+
// service replays instead of starting a second thread.
253+
expect(ids[0]).toEqual(ids[1]);
254+
expect(ids[0]?.[0]).toContain("client%3Asession-1");
255+
expect(ids[2]).not.toEqual(ids[0]);
256+
// Without a key every launch is new.
257+
expect(ids[3]).not.toEqual(ids[4]);
258+
}),
259+
);
260+
261+
it.effect("a retried launch replays after the project loses its default model", () =>
262+
Effect.gen(function* () {
263+
const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
264+
const { projectId, modelSelection, projectDefaults, dependencies } = clientLaunchHarness({
265+
runtimeModeCeiling: "auto",
266+
launched,
267+
});
268+
const toolkit = yield* ProjectToolkit.pipe(
269+
Effect.provide(
270+
McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
271+
),
272+
);
273+
const launch = toolkit
274+
.handle("t3_thread_launch", { title: "Fix", projectId, clientRequestId: "fix-1" })
275+
.pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
276+
277+
yield* launch;
278+
projectDefaults.model = null;
279+
const retried = (yield* launch).at(-1)?.result;
280+
expect(retried).toMatchObject({ projectId, modelSelection });
281+
expect(launched.map((input) => input.threadId)).toEqual([
282+
launched[0]?.threadId,
283+
launched[0]?.threadId,
284+
]);
285+
}),
286+
);
287+
203288
it.effect("a launch binds only an existing checkout that is one of the project's worktrees", () =>
204289
Effect.gen(function* () {
205290
const fileSystem = yield* FileSystem.FileSystem;
@@ -302,3 +387,46 @@ it.effect("a launch into a new worktree creates nothing when its base ref has no
302387
expect(launched).toHaveLength(1);
303388
}),
304389
);
390+
391+
it.effect("a retried worktree launch replays after its base ref is gone", () =>
392+
Effect.gen(function* () {
393+
const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
394+
const base = { exists: true };
395+
const { projectId, dependencies } = clientLaunchHarness({
396+
runtimeModeCeiling: "auto",
397+
launched,
398+
checkWorktreeBase: ({ projectId, workspaceStrategy }) =>
399+
base.exists || workspaceStrategy.type !== "worktree"
400+
? Effect.void
401+
: Effect.fail(
402+
new ThreadLaunch.ThreadLaunchBaseRefError({
403+
projectId,
404+
projectTitle: "Client target",
405+
workspaceRoot: "/projects/client-target",
406+
baseRef: workspaceStrategy.baseRef,
407+
}),
408+
),
409+
});
410+
const toolkit = yield* ProjectToolkit.pipe(
411+
Effect.provide(
412+
McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
413+
),
414+
);
415+
const launch = toolkit
416+
.handle("t3_thread_launch", {
417+
title: "Fix",
418+
projectId,
419+
clientRequestId: "fix-worktree",
420+
workspaceStrategy: { type: "worktree", baseRef: "feature", startFromOrigin: false },
421+
})
422+
.pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
423+
424+
yield* launch;
425+
base.exists = false;
426+
expect((yield* launch).at(-1)?.result).toMatchObject({ projectId });
427+
expect(launched.map((input) => input.threadId)).toEqual([
428+
launched[0]?.threadId,
429+
launched[0]?.threadId,
430+
]);
431+
}),
432+
);

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

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
import { MessageId, ThreadId, OrchestratorMcpFailure, ProjectId } from "@t3tools/contracts";
1+
import {
2+
CommandId,
3+
MessageId,
4+
ThreadId,
5+
OrchestratorMcpFailure,
6+
ProjectId,
7+
} from "@t3tools/contracts";
28
import * as Effect from "effect/Effect";
39
import * as FileSystem from "effect/FileSystem";
410
import * as Option from "effect/Option";
@@ -58,8 +64,16 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
5864
(input, { runtimeMode, interactionMode }) =>
5965
Effect.gen(function* () {
6066
const context = yield* readCaller();
61-
const { caller } = context;
62-
const commandId = yield* newCommandId();
67+
const { caller, scope } = context;
68+
// A retry with the same key replays the first launch: the ids derive
69+
// from the caller and the key, and the launch service replays a
70+
// command it already accepted.
71+
const commandId =
72+
input.clientRequestId === undefined
73+
? yield* newCommandId()
74+
: CommandId.make(
75+
`mcp:launch:${encodeURIComponent(scope.requestNamespace)}:${encodeURIComponent(input.clientRequestId)}`,
76+
);
6377
const threadId = ThreadId.make(commandId);
6478
const messageId = MessageId.make(commandId);
6579
const attachments = input.attachments ?? [];
@@ -95,7 +109,17 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
95109
Effect.mapError(unavailable),
96110
Effect.map(Option.getOrUndefined),
97111
);
98-
if (input.workspaceStrategy?.type === "existing_worktree") {
112+
// A retry of an accepted launch replays it: it keeps the model it started
113+
// with and skips the checks only a new launch needs, which the project
114+
// may no longer pass, such as a base branch deleted since.
115+
const launched =
116+
input.clientRequestId === undefined
117+
? null
118+
: yield* context.threads.getThreadShell(threadId).pipe(Effect.mapError(unavailable));
119+
const launchedModel =
120+
launched === null || launched.deletedAt !== null ? undefined : launched.modelSelection;
121+
const replaying = launchedModel !== undefined;
122+
if (!replaying && input.workspaceStrategy?.type === "existing_worktree") {
99123
const project = yield* readProject;
100124
if (project === undefined)
101125
return yield* new OrchestratorMcpFailure({
@@ -106,7 +130,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
106130
}
107131
// Reject unresolved base refs before accepting a launch; worktree provisioning happens later.
108132
const strategy = input.workspaceStrategy;
109-
if (strategy?.type === "worktree")
133+
if (!replaying && strategy?.type === "worktree")
110134
yield* ThreadLaunch.ThreadLaunchService.pipe(
111135
Effect.flatMap((launches) =>
112136
launches.checkWorktreeBase({ projectId, workspaceStrategy: strategy }),
@@ -127,7 +151,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
127151
// project's effective defaults, as the composer does. Its mode stays
128152
// within the ceiling it was approved with.
129153
const projectDefaults =
130-
caller === undefined
154+
caller === undefined && !replaying
131155
? yield* ServerSettings.ServerSettingsService.pipe(
132156
Effect.flatMap((settings) => settings.getSettings),
133157
Effect.mapError(unavailable),
@@ -141,6 +165,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
141165
: undefined;
142166
const modelSelection =
143167
input.modelSelection ??
168+
launchedModel ??
144169
caller?.modelSelection ??
145170
projectDefaults?.defaultModelSelection ??
146171
undefined;

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
ProjectCreatePayload,
1414
ProjectUpdatePayload,
1515
ProjectId,
16+
OrchestratorMcpClientRequestId,
1617
OrchestratorMcpFailure,
1718
SourceControlCloneRepositoryInput,
1819
SourceControlCloneRepositoryResult,
@@ -101,7 +102,7 @@ const ProjectCloneTool = Tool.make("t3_project_clone", {
101102
const ThreadLaunchTool = Tool.make("t3_thread_launch", {
102103
...shared,
103104
description:
104-
"Create one new top-level thread, bound to its workspace before the agent starts. Task in `message`. Omit `projectId`, model and modes to inherit yours (outside a thread, pass `projectId` or `scratch`); modes cannot exceed yours. No retry key: after an error or lost reply, check `t3_thread_list` before retrying. Follow it with `t3_thread_read` or `t3_thread_wait`. Mention it with its `link`.",
105+
"Create one new top-level thread, bound to its workspace before the agent starts. Task in `message`. Omit `projectId`, model and modes to inherit yours (outside a thread, pass `projectId` or `scratch`); modes cannot exceed yours. After an error or lost reply, retry with the same `clientRequestId`. Follow it with `t3_thread_read` or `t3_thread_wait`. Mention it with its `link`.",
105106
parameters: Schema.Struct({
106107
projectId: Schema.optional(ProjectId),
107108
scratch: Schema.optional(
@@ -126,6 +127,7 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", {
126127
}),
127128
),
128129
attachments: Schema.optional(Schema.Array(McpAttachmentInput).check(Schema.isMaxLength(8))),
130+
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
129131
}),
130132
success: Schema.Struct({
131133
threadId: ThreadId,

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

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1423,6 +1423,40 @@ it.effect("replays an accepted launch after the project disables the instance",
14231423
}).pipe(Effect.provide(harness.layer));
14241424
});
14251425

1426+
it.effect("an agent's launch never starts work above the modes it asks for", () => {
1427+
const harness = makeHarness();
1428+
return Effect.gen(function* () {
1429+
const launches = yield* ThreadLaunch.ThreadLaunchService;
1430+
const threads = yield* ThreadManagement.ThreadManagementService;
1431+
// The first launch, at full access, creates the thread without a message.
1432+
const created = yield* launches.launch(
1433+
launchInput({ command: "command:launch:narrowed-retry", thread: "thread:narrowed" }),
1434+
);
1435+
// The same key comes back from a narrower agent, now carrying a message,
1436+
// as a retry or a concurrent launch that lost the create would.
1437+
const failed = yield* launches
1438+
.launch({
1439+
...launchInput({
1440+
command: "command:launch:narrowed-retry",
1441+
thread: "thread:narrowed",
1442+
message: "Run this",
1443+
}),
1444+
runtimeMode: "approval-required",
1445+
interactionMode: "plan",
1446+
createdBy: "agent",
1447+
creationSource: "mcp",
1448+
})
1449+
.pipe(Effect.flip);
1450+
if (failed._tag !== "ThreadLaunchError") {
1451+
assert.fail(`expected ThreadLaunchError, got ${failed._tag}`);
1452+
}
1453+
assert.equal(failed.operation, "dispatch-message");
1454+
const projection = yield* threads.getThreadProjection(created.threadId);
1455+
assert.equal(projection.runs.length, 0);
1456+
assert.equal(projection.messages.length, 0);
1457+
}).pipe(Effect.provide(harness.layer));
1458+
});
1459+
14261460
it.effect("rejects a server-allocated launch replay with a mismatching thread id", () => {
14271461
const harness = makeHarness();
14281462
return Effect.gen(function* () {

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

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
4949
import type * as Orchestrator from "./Orchestrator.ts";
5050
import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
5151
import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
52+
import { DispatchModeLimit } from "./DispatchModeLimit.ts";
5253
import * as ThreadManagement from "./ThreadManagementService.ts";
5354

5455
export type ThreadLaunchWorkspaceStrategy =
@@ -929,7 +930,6 @@ const make = Effect.gen(function* () {
929930
if (project.id !== input.projectId) {
930931
return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
931932
}
932-
933933
let runId: RunId | null = null;
934934
let messageWasAlreadyAccepted = false;
935935
if (input.initialMessage !== undefined) {
@@ -962,7 +962,19 @@ const make = Effect.gen(function* () {
962962
createdBy: input.createdBy,
963963
creationSource: input.creationSource,
964964
})
965-
.pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)));
965+
.pipe(
966+
// An agent's launch can land on a thread that a replay, or a concurrent
967+
// launch with the same key, created with broader modes. The orchestrator
968+
// refuses the message under the thread's lock; the user's own clients
969+
// launch into their own drafts, whatever modes those hold.
970+
input.createdBy === "agent"
971+
? Effect.provideService(DispatchModeLimit, {
972+
runtimeMode: input.runtimeMode,
973+
interactionMode: input.interactionMode,
974+
})
975+
: (effect) => effect,
976+
Effect.mapError(mapError(input, "dispatch-message", threadId)),
977+
);
966978
// A concurrent retry can read no receipt and still replay the dispatch.
967979
messageWasAlreadyAccepted ||= dispatched.replayed === true;
968980
const runCreated = dispatched.storedEvents.find(

‎packages/contracts/src/orchestratorMcp.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
4242

4343
const OrchestratorMcpPrompt = TrimmedNonEmptyString.check(Schema.isMaxLength(120_000));
4444
const OrchestratorMcpTitle = TrimmedNonEmptyString.check(Schema.isMaxLength(512));
45-
const OrchestratorMcpClientRequestId = TrimmedNonEmptyString.check(
45+
export const OrchestratorMcpClientRequestId = TrimmedNonEmptyString.check(
4646
Schema.isMaxLength(256),
4747
).annotate({ description: "Reuse it to retry the same call. A new call gets a new key." });
4848

0 commit comments

Comments
 (0)