@devries-cameron20 / t3code Mirror · read-only / commits / 719042d942
Fork 0

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 21, 14:45 UTC

fix(server): MCP-launched threads no longer flash in Inbox before Working (#36682)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

mmmattG committed Nov 14, 2026 at 21:57 UTC 719042d94255b0e77ffc3d3c3183c6fe5e59d5c1
8 files changed +195 -64
apps/server/src/mcp/OrchestratorMcpService.test.ts
+12 -1
@@ -2253,7 +2253,7 @@ describe("OrchestratorMcpService provider resolution", () => {
2253 cause: new Error("refused by the orchestrator"),
2254 }) as never,
2255 )
2256 - : Effect.succeed({} as never),
2256 + : Effect.succeed({ storedEvents: [] } as never),
2257 }),
2258 ServerSettings.layerTest(),
2259 providerRegistryLayer([
@@ -2637,6 +2637,17 @@ describe("OrchestratorMcpService provider resolution", () => {
2637 });
2638 const titled = yield* orchestrator.getThreadProjection(emojiAtLimit.threads[0]!.threadId);
2639 assert.equal(titled.thread.title, `${"a".repeat(76)}...`);
2640 + // One commit holds a prompted thread and its run, so no client sees it idle between.
2641 + const promptedCommits = yield* orchestrator
2642 + .streamStoredEventsFrom({ threadId: titled.thread.id })
2643 + .pipe(
2644 + Stream.filter(
2645 + ({ event }) => event.type === "thread.created" || event.type === "run.created",
2646 + ),
2647 + Stream.take(2),
2648 + Stream.runCollect,
2649 + );
2650 + assert.equal(promptedCommits[0]?.commandId, promptedCommits[1]?.commandId);
2651
2652 yield* settings.updateSettings({
2653 projectSettingsOverrides: {
apps/server/src/mcp/OrchestratorMcpService.ts
+21 -10
@@ -2994,7 +2994,20 @@ const make = Effect.gen(function* () {
2994 title: request.title,
2995 index,
2996 });
2997 - yield* threadManagement
2997 + const initialMessage =
2998 + request.prompt === undefined
2999 + ? undefined
3000 + : {
3001 + senderThreadId: scope.thread.threadId,
3002 + messageId: stableMessageId({
3003 + scope,
3004 + requestKey: key,
3005 + index,
3006 + }),
3007 + text: request.prompt,
3008 + attachments: [],
3009 + };
3010 + const created = yield* threadManagement
3011 .dispatch({
3012 type: "thread.create",
3013 createdBy: "agent",
@@ -3011,6 +3024,7 @@ const make = Effect.gen(function* () {
3024 ...(parent.thread.linkOrigin === undefined
3025 ? {}
3026 : { linkOrigin: parent.thread.linkOrigin }),
3027 + ...(initialMessage === undefined ? {} : { initialMessage }),
3028 })
3029 .pipe(
3030 Effect.mapError((error) =>
@@ -3024,9 +3038,14 @@ const make = Effect.gen(function* () {
3038 const resolvedModelSelection = (yield* threadManagement
3039 .getThreadRecords(threadId, [])
3040 .pipe(Effect.mapError(threadManagementFailure))).thread.modelSelection;
3027 - if (request.prompt !== undefined) {
3041 + // A replayed creation that carried no prompt has no run yet.
3042 + if (
3043 + initialMessage !== undefined &&
3044 + !created.storedEvents.some(({ event }) => event.type === "run.created")
3045 + ) {
3046 yield* threadManagement
3047 .dispatch({
3048 + ...initialMessage,
3049 type: "message.dispatch",
3050 createdBy: "agent",
3051 creationSource: "mcp",
@@ -3037,14 +3056,6 @@ const make = Effect.gen(function* () {
3056 index,
3057 }),
3058 threadId,
3040 - senderThreadId: scope.thread.threadId,
3041 - messageId: stableMessageId({
3042 - scope,
3043 - requestKey: key,
3044 - index,
3045 - }),
3046 - text: request.prompt,
3047 - attachments: [],
3059 modelSelection: resolvedModelSelection,
3060 dispatchMode: { type: "start_immediately" },
3061 })
apps/server/src/orchestration-v2/Orchestrator.ts
+36 -1
@@ -795,6 +795,28 @@ function metadataUpdateContinuation(
795 };
796 }
797
798 +// A later command for the first message would leave the new thread committed with no run,
799 +// and every client would show it idle until that command landed.
800 +function threadCreateInitialMessage(
801 + command: Extract<OrchestrationV2Command, { readonly type: "thread.create" }>,
802 +): Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }> | undefined {
803 + if (command.initialMessage === undefined) return undefined;
804 + const { workspaceStrategy, ...message } = command.initialMessage;
805 + return {
806 + ...message,
807 + type: "message.dispatch",
808 + commandId: command.commandId,
809 + threadId: command.threadId,
810 + modelSelection: command.modelSelection,
811 + dispatchMode:
812 + workspaceStrategy === undefined
813 + ? { type: "start_immediately" }
814 + : { type: "defer_start", workspaceStrategy },
815 + createdBy: command.createdBy,
816 + creationSource: command.creationSource,
817 + };
818 +}
819 +
820 // Provider wakes can start follow-up work; monitor updates only report progress.
821 // Dispatch takes the parent's lock for follow-ups because intake writes the parent.
822 function mayStartSubagentFollowup(
@@ -6882,6 +6904,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6904 ? projectionStore
6905 .getThreadRecords(command.threadId, ["messages"], { messageRoles: ["user"] })
6906 .pipe(
6907 + // A thread this command creates has no stored messages yet.
6908 + Effect.catchTags({
6909 + ProjectionStoreThreadNotFoundError: () => Effect.succeed({ messages: [] }),
6910 + }),
6911 Effect.map(({ messages }) => [...messages, ...userMessages]),
6912 Effect.map((all) => all.length > 0 && all.every(isNativeMaintenanceCommand)),
6913 mapDispatchError(command),
@@ -14760,9 +14786,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14786 | undefined;
14787 let updateDelegatedCompletionOnlyRunId: RunId | undefined;
14788 switch (command.type) {
14763 - case "thread.create":
14789 + case "thread.create": {
14790 yield* dispatchThreadCreate(command, events);
14791 + const initialMessage = threadCreateInitialMessage(command);
14792 + if (initialMessage !== undefined) {
14793 + cancelUnsettledEffects = yield* dispatchMessage(
14794 + withoutGuestAttribution(initialMessage),
14795 + events,
14796 + effects,
14797 + );
14798 + }
14799 break;
14800 + }
14801 case "thread.visit":
14802 yield* dispatchThreadVisit(command, events);
14803 break;
apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+37 -4
@@ -633,7 +633,7 @@ it.effect.each([" /COMPACT "])(
633 );
634 assert.isNull((yield* threads.getThreadProjection(launched.threadId)).thread.lastVisitedAt);
635 assert.isFalse(
636 - (yield* outbox.listByCommandId(CommandId.make("compact-title:initial-message"))).some(
636 + (yield* outbox.listByCommandId(CommandId.make("compact-title"))).some(
637 (effect) => effect.request.type === "thread-title.generate",
638 ),
639 );
@@ -776,7 +776,7 @@ it.effect("arms durable title generation after accepting the first message", ()
776 generateTitle: true,
777 };
778 const launched = yield* launches.launch(input);
779 - const generationCommandId = CommandId.make("command:launch:title-generation:initial-message");
779 + const generationCommandId = input.commandId;
780
781 const projection = yield* threads.getThreadProjection(launched.threadId);
782 assert.equal(projection.thread.title, "Generate my title");
@@ -850,9 +850,9 @@ it.effect("arms durable title generation after accepting the first message", ()
850 }),
851 );
852
853 -it.effect("does not update a reused thread title when the initial message is rejected", () =>
853 +it.effect("a rejected initial message leaves no title change and no new thread", () =>
854 Effect.gen(function* () {
855 - const harness = makeHarness();
855 + const harness = makeHarness({ adapters: [adapter, claudeAdapter] });
856 yield* Effect.gen(function* () {
857 const launches = yield* ThreadLaunch.ThreadLaunchService;
858 const threads = yield* ThreadManagement.ThreadManagementService;
@@ -897,6 +897,24 @@ it.effect("does not update a reused thread title when the initial message is rej
897 assert.isUndefined(projection.thread.titleRegeneration);
898 assert.isEmpty(projection.messages);
899 assert.isEmpty(yield* outbox.listByCommandId(CommandId.make(`${commandId}:initial-message`)));
900 +
901 + // The orchestrator refuses this goal command, after the launch's own checks pass.
902 + const newThreadId = ThreadId.make("thread:launch:rejected-new-thread");
903 + const rejected = yield* launches
904 + .launch({
905 + ...launchInput({
906 + command: "command:launch:rejected-new-thread",
907 + thread: newThreadId,
908 + message: "/goal pause",
909 + }),
910 + modelSelection: claudeModelSelection,
911 + })
912 + .pipe(Effect.flip);
913 + if (rejected._tag !== "ThreadLaunchError") {
914 + assert.fail(`expected ThreadLaunchError, got ${rejected._tag}`);
915 + }
916 + assert.equal(rejected.operation, "create-thread");
917 + assert.isNull(yield* threads.getThreadShell(newThreadId));
918 }).pipe(Effect.provide(harness.layer));
919 }),
920 );
@@ -1680,6 +1698,21 @@ it.effect("replays a server-allocated launch", () =>
1698 workspace: { type: "worktree", baseRef: "main" },
1699 });
1700 const first = yield* launches.launch(rest);
1701 + // One commit holds the thread and its first run, so no client sees the thread idle between.
1702 + const launchCommits = yield* threads
1703 + .streamStoredEventsFrom({ threadId: first.threadId })
1704 + .pipe(
1705 + Stream.filter(
1706 + (stored) =>
1707 + stored.event.type === "thread.created" || stored.event.type === "run.created",
1708 + ),
1709 + Stream.take(2),
1710 + Stream.runCollect,
1711 + );
1712 + assert.deepEqual(
1713 + Array.from(launchCommits, (stored) => stored.commandId),
1714 + [rest.commandId, rest.commandId],
1715 + );
1716 yield* Deferred.await(setupEntered);
1717 const retry = yield* launches.launch(rest);
1718 assert.equal(first.threadId, retry.threadId);
apps/server/src/orchestration-v2/ThreadLaunchService.ts
+59 -46
@@ -1133,6 +1133,26 @@ const make = Effect.gen(function* () {
1133 const initialBranch = yield* launchBranch(workspaceStrategy, project.workspaceRoot);
1134 const initialWorktreePath =
1135 workspaceStrategy.type === "existing_worktree" ? workspaceStrategy.worktreePath : null;
1136 + const initialMessage =
1137 + input.initialMessage === undefined
1138 + ? undefined
1139 + : {
1140 + messageId:
1141 + input.initialMessage.messageId ??
1142 + (yield* ids.allocate
1143 + .message({ threadId: candidateThreadId, ordinal: 1 })
1144 + .pipe(Effect.mapError(mapError(input, "dispatch-message", candidateThreadId)))),
1145 + text: input.initialMessage.text,
1146 + ...(input.initialMessage.scheduledTaskId === undefined
1147 + ? {}
1148 + : { scheduledTaskId: input.initialMessage.scheduledTaskId }),
1149 + ...(input.initialMessage.senderThreadId === undefined
1150 + ? {}
1151 + : { senderThreadId: input.initialMessage.senderThreadId }),
1152 + attachments: input.initialMessage.attachments,
1153 + ...(input.initialMessage.context ? { context: input.initialMessage.context } : {}),
1154 + ...(input.generateTitle === true ? { titleSeed: input.title } : {}),
1155 + };
1156 const claimDispatch =
1157 input.reuseExistingThread === true
1158 ? threads.dispatch({
@@ -1161,6 +1181,9 @@ const make = Effect.gen(function* () {
1181 : { delegatedFrom: input.delegatedFrom }),
1182 createdBy: input.createdBy,
1183 creationSource: input.creationSource,
1184 + ...(initialMessage === undefined
1185 + ? {}
1186 + : { initialMessage: { ...initialMessage, workspaceStrategy } }),
1187 });
1188 const claimed = yield* claimDispatch.pipe(
1189 Effect.mapError(
@@ -1180,53 +1203,43 @@ const make = Effect.gen(function* () {
1203 let runId: RunId | null = null;
1204 let messageSequence: number | undefined;
1205 let messageWasAlreadyAccepted = false;
1183 - if (input.initialMessage !== undefined) {
1184 - const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
1185 - const messageReceipt = yield* readReceipt(input, messageCommandId);
1186 - messageWasAlreadyAccepted = Option.isSome(messageReceipt);
1187 - const messageId =
1188 - input.initialMessage.messageId ??
1189 - (yield* ids.allocate
1190 - .message({ threadId, ordinal: 1 })
1191 - .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))));
1192 - const dispatched = yield* threads
1193 - .dispatch({
1194 - type: "message.dispatch",
1195 - commandId: messageCommandId,
1196 - threadId,
1197 - messageId,
1198 - text: input.initialMessage.text,
1199 - ...(input.initialMessage.scheduledTaskId === undefined
1200 - ? {}
1201 - : { scheduledTaskId: input.initialMessage.scheduledTaskId }),
1202 - ...(input.initialMessage.senderThreadId === undefined
1203 - ? {}
1204 - : { senderThreadId: input.initialMessage.senderThreadId }),
1205 - attachments: input.initialMessage.attachments,
1206 - ...(input.initialMessage.context ? { context: input.initialMessage.context } : {}),
1207 - ...(input.generateTitle === true ? { titleSeed: input.title } : {}),
1208 - modelSelection: input.modelSelection,
1209 - dispatchMode: { type: "defer_start", workspaceStrategy },
1210 - createdBy: input.createdBy,
1211 - creationSource: input.creationSource,
1212 - })
1213 - .pipe(
1214 - // An agent's launch can land on a thread that a replay, or a concurrent
1215 - // launch with the same key, created with broader modes. The orchestrator
1216 - // refuses the message under the thread's lock; the user's own clients
1217 - // launch into their own drafts, whatever modes those hold.
1218 - input.createdBy === "agent"
1219 - ? Effect.provideService(DispatchModeLimit, {
1220 - runtimeMode: input.runtimeMode,
1221 - interactionMode: input.interactionMode,
1222 - })
1223 - : (effect) => effect,
1224 - Effect.mapError(mapError(input, "dispatch-message", threadId)),
1225 - );
1206 + if (initialMessage !== undefined) {
1207 + // A new thread's claim carries its first message. A reused thread, or a replayed
1208 + // claim that carried none, takes it in a command of its own.
1209 + let accepted = claimed;
1210 + if (!claimed.storedEvents.some((stored) => stored.event.type === "run.created")) {
1211 + const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
1212 + const messageReceipt = yield* readReceipt(input, messageCommandId);
1213 + messageWasAlreadyAccepted = Option.isSome(messageReceipt);
1214 + accepted = yield* threads
1215 + .dispatch({
1216 + ...initialMessage,
1217 + type: "message.dispatch",
1218 + commandId: messageCommandId,
1219 + threadId,
1220 + modelSelection: input.modelSelection,
1221 + dispatchMode: { type: "defer_start", workspaceStrategy },
1222 + createdBy: input.createdBy,
1223 + creationSource: input.creationSource,
1224 + })
1225 + .pipe(
1226 + // An agent's launch can land on a thread that a replay, or a concurrent
1227 + // launch with the same key, created with broader modes. The orchestrator
1228 + // refuses the message under the thread's lock; the user's own clients
1229 + // launch into their own drafts, whatever modes those hold.
1230 + input.createdBy === "agent"
1231 + ? Effect.provideService(DispatchModeLimit, {
1232 + runtimeMode: input.runtimeMode,
1233 + interactionMode: input.interactionMode,
1234 + })
1235 + : (effect) => effect,
1236 + Effect.mapError(mapError(input, "dispatch-message", threadId)),
1237 + );
1238 + }
1239 // A concurrent retry can read no receipt and still replay the dispatch.
1227 - messageWasAlreadyAccepted ||= dispatched.replayed === true;
1228 - messageSequence = dispatched.sequence;
1229 - const runCreated = dispatched.storedEvents.find(
1240 + messageWasAlreadyAccepted ||= accepted.replayed === true;
1241 + messageSequence = accepted.sequence;
1242 + const runCreated = accepted.storedEvents.find(
1243 (stored) => stored.event.type === "run.created",
1244 );
1245 runId = runCreated?.event.type === "run.created" ? runCreated.event.payload.id : null;
apps/server/src/orchestration-v2/ThreadManagementService.test.ts
+7
@@ -68,6 +68,12 @@ it("stamps authoritative provenance on commands that create threads or messages"
68 threadId: ThreadId.make("thread:elsewhere"),
69 title: "Somewhere else",
70 },
71 + // A client's message goes through intake; only the server folds one into the creation.
72 + initialMessage: {
73 + messageId: MessageId.make("message:thread-management:forged"),
74 + text: "Forged",
75 + attachments: [],
76 + },
77 };
78
79 const stamped = ThreadManagementService.withCreationProvenance(command, {
@@ -80,6 +86,7 @@ it("stamps authoritative provenance on commands that create threads or messages"
86 });
87 expect(stamped).not.toHaveProperty("linkOrigin");
88 expect(stamped).not.toHaveProperty("delegatedFrom");
89 + expect(stamped).not.toHaveProperty("initialMessage");
90 });
91
92 const layerReceiptsTest = CommandReceiptStore.layer.pipe(
apps/server/src/orchestration-v2/ThreadManagementService.ts
+7 -2
@@ -84,8 +84,13 @@ export function withCreationProvenance(
84 ): OrchestrationV2Command {
85 switch (command.type) {
86 case "thread.create": {
87 - // Only the server stamps a link's origin, so a client cannot set one.
88 - const { linkOrigin: _linkOrigin, delegatedFrom: _delegatedFrom, ...rest } = command;
87 + // Only the server stamps a link's origin or folds in a first message, so a client cannot.
88 + const {
89 + linkOrigin: _linkOrigin,
90 + delegatedFrom: _delegatedFrom,
91 + initialMessage: _initialMessage,
92 + ...rest
93 + } = command;
94 return { ...rest, ...provenance };
95 }
96 case "message.dispatch":
packages/contracts/src/orchestrationV2.ts
+16
@@ -3109,6 +3109,22 @@ export const OrchestrationV2Command = Schema.Union([
3109 metadata: Schema.optional(OrchestrationV2ProviderThreadNativeMetadata),
3110 }),
3111 ),
3112 + /**
3113 + * Only the server sets this. The thread and its first run commit together, so no client sees
3114 + * the thread idle before its run exists. The run waits for `workspaceStrategy` when given one.
3115 + */
3116 + initialMessage: Schema.optional(
3117 + Schema.Struct({
3118 + messageId: MessageId,
3119 + text: Schema.String,
3120 + attachments: Schema.Array(ChatAttachment),
3121 + context: Schema.optional(OrchestrationMessageContext),
3122 + titleSeed: Schema.optional(TrimmedNonEmptyString),
3123 + scheduledTaskId: Schema.optional(ScheduledTaskId),
3124 + senderThreadId: Schema.optional(ThreadId),
3125 + workspaceStrategy: Schema.optional(OrchestrationV2ThreadLaunchWorkspaceStrategy),
3126 + }),
3127 + ),
3128 }),
3129 Schema.Struct({
3130 type: Schema.Literal("thread.archive"),