The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 14:30 UTC
feat(server): t3_thread_launch takes clientRequestId (#16654)
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Julius Marminge committed
Oct 27, 2026 at 14:04 UTC
888e444c1afe4619660b12cbd224e4e95ee7b2cb
8 files changed
+268
-17
apps/server/src/mcp/toolkits/project/handlers.test.ts
+162
-3
@@ -6,10 +6,13 @@ import {
6
type Project as ProjectRecord,
7
type ModelSelection,
8
type RuntimeMode,
9
+ type OrchestrationV2ThreadShell,
10
} from "@t3tools/contracts";
11
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
12
import * as NodeServices from "@effect/platform-node/NodeServices";
13
+import * as Cause from "effect/Cause";
14
import * as Effect from "effect/Effect";
15
+import * as Exit from "effect/Exit";
16
import * as FileSystem from "effect/FileSystem";
17
import * as Path from "effect/Path";
18
import * as Layer from "effect/Layer";
@@ -44,6 +47,10 @@ const clientLaunchHarness = (input: {
47
instanceId: ProviderInstanceId.make("claudeAgent"),
48
model: "claude-opus",
49
};
50
+ // The project's own default model, which a test can clear between launches.
51
+ const projectDefaults: { model: ModelSelection | null } = {
52
+ model: input.overrideModel === undefined ? modelSelection : null,
53
+ };
54
const layerDependencies = Layer.mergeAll(
55
ServerSettings.layerTest({
56
...(input.defaultRuntimeMode === undefined
@@ -71,7 +78,22 @@ const clientLaunchHarness = (input: {
78
issuedAt: 0,
79
capabilities: new Set(["orchestration" as const]),
80
}),
74
- Layer.mock(ThreadManagement.ThreadManagementService)({}),
81
+ Layer.mock(ThreadManagement.ThreadManagementService)({
82
+ // A thread exists once a launch started it.
83
+ getThreadShell: (threadId) => {
84
+ const launch = input.launched.find((candidate) => candidate.threadId === threadId);
85
+ return Effect.succeed(
86
+ launch === undefined
87
+ ? null
88
+ : ({
89
+ id: launch.threadId,
90
+ projectId: launch.projectId,
91
+ modelSelection: launch.modelSelection,
92
+ deletedAt: null,
93
+ } as unknown as OrchestrationV2ThreadShell),
94
+ );
95
+ },
96
+ }),
97
Layer.mock(ThreadLaunch.ThreadLaunchService)({
98
checkWorktreeBase: input.checkWorktreeBase ?? (() => Effect.void),
99
launch: (launch) => {
@@ -98,7 +120,7 @@ const clientLaunchHarness = (input: {
120
? Option.some({
121
id,
122
workspaceRoot: input.workspaceRoot ?? "/projects/client-target",
101
- defaultModelSelection: input.overrideModel === undefined ? modelSelection : null,
123
+ defaultModelSelection: projectDefaults.model,
124
} as unknown as ProjectRecord)
125
: Option.none(),
126
),
@@ -115,7 +137,7 @@ const clientLaunchHarness = (input: {
137
),
138
Layer.provideMerge(NodeServices.layer),
139
);
118
- return { projectId, modelSelection, dependencies: layerDependencies };
140
+ return { projectId, modelSelection, projectDefaults, dependencies: layerDependencies };
141
};
142
143
it.effect(
@@ -200,6 +222,100 @@ it.effect(
222
}),
223
);
224
225
+it.effect("a launch retried with the same clientRequestId replays the first one", () =>
226
+ Effect.gen(function* () {
227
+ const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
228
+ const { projectId, dependencies } = clientLaunchHarness({
229
+ runtimeModeCeiling: "auto",
230
+ launched,
231
+ });
232
+ const toolkit = yield* ProjectToolkit.pipe(
233
+ Effect.provide(
234
+ McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
235
+ ),
236
+ );
237
+ const launch = (clientRequestId: string | undefined) =>
238
+ toolkit
239
+ .handle("t3_thread_launch", {
240
+ title: "Fix",
241
+ projectId,
242
+ message: "Fix the bug",
243
+ ...(clientRequestId === undefined ? {} : { clientRequestId }),
244
+ })
245
+ .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
246
+
247
+ yield* launch("fix-1");
248
+ yield* launch("fix-1");
249
+ yield* launch("fix-2");
250
+ yield* launch(undefined);
251
+ yield* launch(undefined);
252
+ const ids = launched.map((input) => [input.commandId, input.threadId]);
253
+ // The same key sends the same command and thread ids, which the launch
254
+ // service replays instead of starting a second thread.
255
+ expect(ids[0]).toEqual(ids[1]);
256
+ expect(ids[0]?.[0]).toMatch(/^mcp:launch:[0-9a-f]{64}$/);
257
+ expect(ids[2]).not.toEqual(ids[0]);
258
+ // Without a key every launch is new.
259
+ expect(ids[3]).not.toEqual(ids[4]);
260
+ }),
261
+);
262
+
263
+it.effect("a launch key of any length or content gives a short id and never a defect", () =>
264
+ Effect.gen(function* () {
265
+ const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
266
+ const { projectId, dependencies } = clientLaunchHarness({
267
+ runtimeModeCeiling: "auto",
268
+ launched,
269
+ });
270
+ const toolkit = yield* ProjectToolkit.pipe(
271
+ Effect.provide(
272
+ McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
273
+ ),
274
+ );
275
+ const launch = (clientRequestId: string) =>
276
+ toolkit
277
+ .handle("t3_thread_launch", { title: "Fix", projectId, clientRequestId })
278
+ .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
279
+
280
+ // Percent-encoding would grow this six times; scratch folders are named from the id.
281
+ yield* launch("\u00e9".repeat(256));
282
+ expect(launched.map((input) => input.commandId)).toEqual([
283
+ expect.stringMatching(/^mcp:launch:[0-9a-f]{64}$/),
284
+ ]);
285
+
286
+ const loneSurrogate = yield* launch("key-\ud800").pipe(Effect.exit);
287
+ expect(Exit.isFailure(loneSurrogate) && Cause.hasDies(loneSurrogate.cause)).toBe(false);
288
+ expect(launched).toHaveLength(1);
289
+ }),
290
+);
291
+
292
+it.effect("a retried launch replays after the project loses its default model", () =>
293
+ Effect.gen(function* () {
294
+ const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
295
+ const { projectId, modelSelection, projectDefaults, dependencies } = clientLaunchHarness({
296
+ runtimeModeCeiling: "auto",
297
+ launched,
298
+ });
299
+ const toolkit = yield* ProjectToolkit.pipe(
300
+ Effect.provide(
301
+ McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
302
+ ),
303
+ );
304
+ const launch = toolkit
305
+ .handle("t3_thread_launch", { title: "Fix", projectId, clientRequestId: "fix-1" })
306
+ .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
307
+
308
+ yield* launch;
309
+ projectDefaults.model = null;
310
+ const retried = (yield* launch).at(-1)?.result;
311
+ expect(retried).toMatchObject({ projectId, modelSelection });
312
+ expect(launched.map((input) => input.threadId)).toEqual([
313
+ launched[0]?.threadId,
314
+ launched[0]?.threadId,
315
+ ]);
316
+ }),
317
+);
318
+
319
it.effect("a launch binds only an existing checkout that is one of the project's worktrees", () =>
320
Effect.gen(function* () {
321
const fileSystem = yield* FileSystem.FileSystem;
@@ -302,3 +418,46 @@ it.effect("a launch into a new worktree creates nothing when its base ref has no
418
expect(launched).toHaveLength(1);
419
}),
420
);
421
+
422
+it.effect("a retried worktree launch replays after its base ref is gone", () =>
423
+ Effect.gen(function* () {
424
+ const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
425
+ const base = { exists: true };
426
+ const { projectId, dependencies } = clientLaunchHarness({
427
+ runtimeModeCeiling: "auto",
428
+ launched,
429
+ checkWorktreeBase: ({ projectId, workspaceStrategy }) =>
430
+ base.exists || workspaceStrategy.type !== "worktree"
431
+ ? Effect.void
432
+ : Effect.fail(
433
+ new ThreadLaunch.ThreadLaunchBaseRefError({
434
+ projectId,
435
+ projectTitle: "Client target",
436
+ workspaceRoot: "/projects/client-target",
437
+ baseRef: workspaceStrategy.baseRef,
438
+ }),
439
+ ),
440
+ });
441
+ const toolkit = yield* ProjectToolkit.pipe(
442
+ Effect.provide(
443
+ McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
444
+ ),
445
+ );
446
+ const launch = toolkit
447
+ .handle("t3_thread_launch", {
448
+ title: "Fix",
449
+ projectId,
450
+ clientRequestId: "fix-worktree",
451
+ workspaceStrategy: { type: "worktree", baseRef: "feature", startFromOrigin: false },
452
+ })
453
+ .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
454
+
455
+ yield* launch;
456
+ base.exists = false;
457
+ expect((yield* launch).at(-1)?.result).toMatchObject({ projectId });
458
+ expect(launched.map((input) => input.threadId)).toEqual([
459
+ launched[0]?.threadId,
460
+ launched[0]?.threadId,
461
+ ]);
462
+ }),
463
+);
apps/server/src/mcp/toolkits/project/handlers.ts
+43
-6
@@ -1,5 +1,13 @@
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";
8
+import * as Crypto from "effect/Crypto";
9
import * as Effect from "effect/Effect";
10
+import * as Hex from "effect/encoding/Hex";
11
import * as FileSystem from "effect/FileSystem";
12
import * as Option from "effect/Option";
13
import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts";
@@ -48,6 +56,18 @@ const assertProjectWorktree = Effect.fn("mcp.assertProjectWorktree")(function* (
56
});
57
});
58
59
+/** A fixed-length id, so a long key fits in the scratch folder name derived from it. */
60
+const launchCommandId = Effect.fn("mcp.launchCommandId")(function* (
61
+ namespace: string,
62
+ key: string,
63
+) {
64
+ const crypto = yield* Crypto.Crypto;
65
+ // @effect-diagnostics-next-line preferSchemaOverJson:off - a JSON pair keeps the caller apart from the key.
66
+ const bytes = new TextEncoder().encode(JSON.stringify([namespace, key]));
67
+ const digest = yield* crypto.digest("SHA-256", bytes).pipe(Effect.mapError(unavailable));
68
+ return CommandId.make(`mcp:launch:${Hex.encode(digest)}`);
69
+});
70
+
71
const access = Effect.gen(function* () {
72
yield* readCaller();
73
return yield* Project.ProjectService;
@@ -58,8 +78,14 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
78
(input, { runtimeMode, interactionMode }) =>
79
Effect.gen(function* () {
80
const context = yield* readCaller();
61
- const { caller } = context;
62
- const commandId = yield* newCommandId();
81
+ const { caller, scope } = context;
82
+ // A retry with the same key replays the first launch: the ids derive
83
+ // from the caller and the key, and the launch service replays a
84
+ // command it already accepted.
85
+ const commandId =
86
+ input.clientRequestId === undefined
87
+ ? yield* newCommandId()
88
+ : yield* launchCommandId(scope.requestNamespace, input.clientRequestId);
89
const threadId = ThreadId.make(commandId);
90
const messageId = MessageId.make(commandId);
91
const attachments = input.attachments ?? [];
@@ -95,7 +121,17 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
121
Effect.mapError(unavailable),
122
Effect.map(Option.getOrUndefined),
123
);
98
- if (input.workspaceStrategy?.type === "existing_worktree") {
124
+ // A retry of an accepted launch replays it: it keeps the model it started
125
+ // with and skips the checks only a new launch needs, which the project
126
+ // may no longer pass, such as a base branch deleted since.
127
+ const launched =
128
+ input.clientRequestId === undefined
129
+ ? null
130
+ : yield* context.threads.getThreadShell(threadId).pipe(Effect.mapError(unavailable));
131
+ const launchedModel =
132
+ launched === null || launched.deletedAt !== null ? undefined : launched.modelSelection;
133
+ const replaying = launchedModel !== undefined;
134
+ if (!replaying && input.workspaceStrategy?.type === "existing_worktree") {
135
const project = yield* readProject;
136
if (project === undefined)
137
return yield* new OrchestratorMcpFailure({
@@ -106,7 +142,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
142
}
143
// Reject unresolved base refs before accepting a launch; worktree provisioning happens later.
144
const strategy = input.workspaceStrategy;
109
- if (strategy?.type === "worktree")
145
+ if (!replaying && strategy?.type === "worktree")
146
yield* ThreadLaunch.ThreadLaunchService.pipe(
147
Effect.flatMap((launches) =>
148
launches.checkWorktreeBase({ projectId, workspaceStrategy: strategy }),
@@ -127,7 +163,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
163
// project's effective defaults, as the composer does. Its mode stays
164
// within the ceiling it was approved with.
165
const projectDefaults =
130
- caller === undefined
166
+ caller === undefined && !replaying
167
? yield* ServerSettings.ServerSettingsService.pipe(
168
Effect.flatMap((settings) => settings.getSettings),
169
Effect.mapError(unavailable),
@@ -141,6 +177,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
177
: undefined;
178
const modelSelection =
179
input.modelSelection ??
180
+ launchedModel ??
181
caller?.modelSelection ??
182
projectDefaults?.defaultModelSelection ??
183
undefined;
apps/server/src/mcp/toolkits/project/tools.ts
+3
-1
@@ -13,6 +13,7 @@ import {
13
ProjectCreatePayload,
14
ProjectUpdatePayload,
15
ProjectId,
16
+ OrchestratorMcpClientRequestId,
17
OrchestratorMcpFailure,
18
SourceControlCloneRepositoryInput,
19
SourceControlCloneRepositoryResult,
@@ -101,7 +102,7 @@ const ProjectCloneTool = Tool.make("t3_project_clone", {
102
const ThreadLaunchTool = Tool.make("t3_thread_launch", {
103
...shared,
104
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`.",
106
parameters: Schema.Struct({
107
projectId: Schema.optional(ProjectId),
108
scratch: Schema.optional(
@@ -126,6 +127,7 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", {
127
}),
128
),
129
attachments: Schema.optional(Schema.Array(McpAttachmentInput).check(Schema.isMaxLength(8))),
130
+ clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
131
}),
132
success: Schema.Struct({
133
threadId: ThreadId,
apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+34
@@ -1423,6 +1423,40 @@ it.effect("replays an accepted launch after the project disables the instance",
1423
}).pipe(Effect.provide(harness.layer));
1424
});
1425
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
+
1460
it.effect("rejects a server-allocated launch replay with a mismatching thread id", () => {
1461
const harness = makeHarness();
1462
return Effect.gen(function* () {
apps/server/src/orchestration-v2/ThreadLaunchService.ts
+14
-2
@@ -49,6 +49,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
49
import type * as Orchestrator from "./Orchestrator.ts";
50
import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
51
import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
52
+import { DispatchModeLimit } from "./DispatchModeLimit.ts";
53
import * as ThreadManagement from "./ThreadManagementService.ts";
54
55
export type ThreadLaunchWorkspaceStrategy =
@@ -929,7 +930,6 @@ const make = Effect.gen(function* () {
930
if (project.id !== input.projectId) {
931
return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
932
}
932
-
933
let runId: RunId | null = null;
934
let messageWasAlreadyAccepted = false;
935
if (input.initialMessage !== undefined) {
@@ -962,7 +962,19 @@ const make = Effect.gen(function* () {
962
createdBy: input.createdBy,
963
creationSource: input.creationSource,
964
})
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
+ );
978
// A concurrent retry can read no receipt and still replay the dispatch.
979
messageWasAlreadyAccepted ||= dispatched.replayed === true;
980
const runCreated = dispatched.storedEvents.find(
apps/server/src/provider/agentContextBudget.json
+1
-1
@@ -1,5 +1,5 @@
1
{
2
"claudeSystemAppendBytes": 4857,
3
"codexAdditionalContextBytes": 5409,
4
- "mcpToolListJsonBytes": 42328
4
+ "mcpToolListJsonBytes": 42349
5
}
packages/contracts/src/orchestratorMcp.ts
+10
-3
@@ -30,6 +30,7 @@ import {
30
ThreadPullRequestKey,
31
ThreadPullRequestLinkSource,
32
} from "./threadPullRequest.ts";
33
+import { hasOnlyPairedSurrogates } from "./threadMetadataMcp.ts";
34
import { ThreadTitleRegeneration } from "./threadTitle.ts";
35
import {
36
OrchestrationV2Actor,
@@ -42,9 +43,15 @@ import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
43
44
const OrchestratorMcpPrompt = TrimmedNonEmptyString.check(Schema.isMaxLength(120_000));
45
const OrchestratorMcpTitle = TrimmedNonEmptyString.check(Schema.isMaxLength(512));
45
-const OrchestratorMcpClientRequestId = TrimmedNonEmptyString.check(
46
- Schema.isMaxLength(256),
47
-).annotate({ description: "Reuse it to retry the same call. A new call gets a new key." });
46
+export const OrchestratorMcpClientRequestId = TrimmedNonEmptyString.check(Schema.isMaxLength(256))
47
+ .check(
48
+ Schema.makeFilter((value) =>
49
+ hasOnlyPairedSurrogates(value)
50
+ ? true
51
+ : "clientRequestId must contain valid paired Unicode surrogates.",
52
+ ),
53
+ )
54
+ .annotate({ description: "Reuse it to retry the same call. A new call gets a new key." });
55
56
// OpenCode 1.15 serializes nested MCP union objects as JSON strings; decode that form at the boundary.
57
const OrchestratorMcpScheduleFromJsonString = Schema.fromJsonString(
packages/contracts/src/threadMetadataMcp.ts
+1
-1
@@ -10,7 +10,7 @@ import {
10
import { ThreadLinkedPullRequest } from "./threadPullRequest.ts";
11
import { ThreadTitleRegeneration } from "./threadTitle.ts";
12
13
-function hasOnlyPairedSurrogates(value: string): boolean {
13
+export function hasOnlyPairedSurrogates(value: string): boolean {
14
for (let index = 0; index < value.length; index += 1) {
15
const codeUnit = value.charCodeAt(index);
16
if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {