@devries-cameron20 / t3code-1 / commits / 3cd98dcbae
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): a secret card closes after the steering restart that supersedes it (#34634)

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

Ali-Al1 committed Nov 19, 2026 at 20:40 UTC 3cd98dcbaed2052851c66bc355c23bf8767a558b
4 files changed +412 -6
apps/server/src/mcp/OrchestratorMcpService.activity.test.ts
+89
@@ -7,6 +7,7 @@ import {
7 ProjectId,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 + RunAttemptId,
11 RunId,
12 ScheduledTaskId,
13 SECRET_REQUEST_UNSAVED_NOTE,
@@ -1202,3 +1203,91 @@ it("requestSecret returns the unsaved note for a declined, cancelled or timed-ou
1203 { status: "timed_out", note: SECRET_REQUEST_UNSAVED_NOTE.timed_out },
1204 ]);
1205 });
1206 +
1207 +it("requestSecret cancels its card when a steering restart supersedes the request", async () => {
1208 + const originalRoot = NodeId.make("node-mcp-secret-root-original");
1209 + const steeredRoot = NodeId.make("node-mcp-secret-root-steered");
1210 + const dispatched: Array<{
1211 + readonly type: string;
1212 + readonly turnItemId?: TurnItemId;
1213 + readonly nodeId?: NodeId;
1214 + readonly secretStatus?: string;
1215 + }> = [];
1216 + let steered = false;
1217 + const projection = () => {
1218 + const card = dispatched.find(
1219 + (command) => command.type === "secret_request.record" && command.secretStatus === "pending",
1220 + );
1221 + return {
1222 + thread: baseThread({
1223 + threadId: parentThreadId,
1224 + title: "Parent",
1225 + instanceId: parentInstanceId,
1226 + model: "gpt-5.4",
1227 + }),
1228 + runs: [
1229 + {
1230 + ...makeRun({ id: activeRunId, ordinal: 1, status: "running" }),
1231 + rootNodeId: steered ? steeredRoot : originalRoot,
1232 + activeAttemptId: RunAttemptId.make("attempt-mcp-secret-original"),
1233 + },
1234 + ],
1235 + visibleTurnItems: [],
1236 + turnItems:
1237 + card === undefined
1238 + ? []
1239 + : [{ type: "secret_request", id: card.turnItemId, secretStatus: "pending" }],
1240 + providerTurns: [],
1241 + runtimeRequests: [],
1242 + messages: [],
1243 + contextTransfers: [],
1244 + subagents: [],
1245 + updatedAt: now,
1246 + } as unknown as OrchestrationV2ThreadProjection;
1247 + };
1248 + const layer = layerOrchestratorService.pipe(
1249 + Layer.provide(
1250 + Layer.mergeAll(
1251 + Layer.mock(ThreadManagementService.ThreadManagementService)({
1252 + getThreadRecords: () => Effect.sync(projection),
1253 + getThreadShell: () =>
1254 + Effect.sync(() => projection().thread as unknown as OrchestrationV2ThreadShell),
1255 + dispatch: (command) =>
1256 + Effect.sync(() => {
1257 + dispatched.push(command as (typeof dispatched)[number]);
1258 + // The user steers right after the card opens, replacing the run's root.
1259 + if (command.type === "secret_request.record" && command.secretStatus === "pending") {
1260 + steered = true;
1261 + }
1262 + return undefined as never;
1263 + }),
1264 + } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
1265 + ServerSettings.layerTest(),
1266 + Layer.mock(ProviderRegistry.ProviderRegistry)({
1267 + getProviders: Effect.succeed([]),
1268 + } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
1269 + Layer.mock(ProjectService.ProjectService)({}),
1270 + Layer.mock(SecretRequests.SecretRequests)({}),
1271 + Layer.mock(RemoteDelegation.RemoteDelegation)({}),
1272 + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
1273 + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}),
1274 + NodeCrypto.layer,
1275 + ),
1276 + ),
1277 + );
1278 +
1279 + await Effect.gen(function* () {
1280 + const service = yield* OrchestratorMcpService.OrchestratorMcpService;
1281 + const result = yield* service.requestSecret(makeScope(), {
1282 + label: "Booking details",
1283 + reason: "To check the passenger in.",
1284 + timeoutMs: 60_000,
1285 + });
1286 + // The wait ended the moment its attempt was superseded instead of blocking
1287 + // the agent's turn until the timeout, and the card closed with it.
1288 + expect(result).toEqual({ status: "cancelled", note: SECRET_REQUEST_UNSAVED_NOTE.cancelled });
1289 + const records = dispatched.filter((command) => command.type === "secret_request.record");
1290 + expect(records.map((command) => command.secretStatus)).toEqual(["pending", "cancelled"]);
1291 + expect(records.every((command) => command.nodeId === originalRoot)).toBe(true);
1292 + }).pipe(Effect.provide(layer), Effect.runPromise);
1293 +});
apps/server/src/mcp/OrchestratorMcpService.ts
+7
@@ -2588,6 +2588,13 @@ const make = Effect.gen(function* () {
2588 yield* record("cancelled");
2589 return "cancelled" as const;
2590 }
2591 + // A steering restart replaced the run's root, so this request belonged to
2592 + // the superseded attempt: its card can never be answered into that attempt,
2593 + // and the call must stop blocking the agent's turn.
2594 + if (current.rootNodeId !== nodeId) {
2595 + yield* record("cancelled");
2596 + return "cancelled" as const;
2597 + }
2598 yield* Effect.sleep(Duration.millis(SECRET_REQUEST_POLL_INTERVAL_MS));
2599 }
2600 }).pipe(
apps/server/src/orchestration-v2/Orchestrator.ts
+24 -6
@@ -10791,14 +10791,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10791 ),
10792 );
10793 const run = projection.runs.find((candidate) => candidate.id === command.runId);
10794 - if (run === undefined || run.rootNodeId !== command.nodeId) {
10794 + if (run === undefined) {
10795 return yield* new OrchestratorDispatchError({
10796 commandId: command.commandId,
10797 commandType: command.type,
10798 - cause: `Node ${command.nodeId} is not the root of run ${command.runId}.`,
10798 + cause: `Run ${command.runId} was not found.`,
10799 });
10800 }
10801 const existing = projection.turnItems.find((item) => item.id === command.turnItemId);
10802 + // Only a new card needs its run's current root. A steer restarts the run
10803 + // under a new root, and the card asked before it must still close.
10804 + if (existing === undefined && run.rootNodeId !== command.nodeId) {
10805 + return yield* new OrchestratorDispatchError({
10806 + commandId: command.commandId,
10807 + commandType: command.type,
10808 + cause: `Node ${command.nodeId} is not the root of run ${command.runId}.`,
10809 + });
10810 + }
10811 if (existing !== undefined && existing.type !== "secret_request") {
10812 return yield* new OrchestratorDispatchError({
10813 commandId: command.commandId,
@@ -10813,6 +10822,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10822 cause: `Secret request ${command.turnItemId} belongs to another run.`,
10823 });
10824 }
10825 + const nodeId = existing?.nodeId ?? command.nodeId;
10826 const now = yield* DateTime.now;
10827 const unchanged =
10828 existing !== undefined &&
@@ -10824,9 +10834,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10834 id: command.turnItemId,
10835 threadId: command.threadId,
10836 runId: command.runId,
10827 - nodeId: command.nodeId,
10828 - providerThreadId: run.providerThreadId,
10829 - providerTurnId: providerTurnForRun(projection, run)?.id ?? null,
10837 + nodeId,
10838 + // An update keeps where the card was asked, even after a restart.
10839 + ...(existing === undefined
10840 + ? {
10841 + providerThreadId: run.providerThreadId,
10842 + providerTurnId: providerTurnForRun(projection, run)?.id ?? null,
10843 + }
10844 + : {
10845 + providerThreadId: existing.providerThreadId,
10846 + providerTurnId: existing.providerTurnId,
10847 + }),
10848 nativeItemRef: null,
10849 parentItemId: null,
10850 ordinal: existing?.ordinal ?? (yield* nextTurnItemOrdinal(projection)),
@@ -10870,7 +10888,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10888 type: "turn-item.updated",
10889 threadId: command.threadId,
10890 runId: command.runId,
10873 - nodeId: command.nodeId,
10891 + nodeId,
10892 providerInstanceId: run.providerInstanceId,
10893 occurredAt: now,
10894 payload: turnItem,
apps/server/src/orchestration-v2/SecretRequestRecord.test.ts new
+292
@@ -0,0 +1,292 @@
1 +import { assert, it } from "@effect/vitest";
2 +import {
3 + CommandId,
4 + EventId,
5 + MessageId,
6 + NodeId,
7 + ProjectId,
8 + ProviderDriverKind,
9 + ProviderInstanceId,
10 + ProviderSessionId,
11 + ProviderThreadId,
12 + ProviderTurnId,
13 + RunAttemptId,
14 + RunId,
15 + ThreadId,
16 + TurnItemId,
17 +} from "@t3tools/contracts";
18 +import * as DateTime from "effect/DateTime";
19 +import * as Effect from "effect/Effect";
20 +import * as Layer from "effect/Layer";
21 +import * as SqlitePersistence from "../persistence/Sqlite.ts";
22 +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
23 +import * as EffectOutbox from "./EffectOutbox.ts";
24 +import * as Orchestrator from "./Orchestrator.ts";
25 +import * as ProjectionStore from "./ProjectionStore.ts";
26 +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
27 +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
28 +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
29 +
30 +const instanceId = ProviderInstanceId.make("codex");
31 +const modelSelection = { instanceId, model: "gpt-5.1-codex" };
32 +const adapter = {
33 + instanceId,
34 + driver: ProviderDriverKind.make("codex"),
35 + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
36 + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
37 + openSession: () => Effect.die("No provider process needed for record controls"),
38 +} as ProviderAdapter.ProviderAdapterV2["Service"];
39 +const layerDatabase = SqlitePersistence.layerMemory;
40 +const layerTest = Layer.mergeAll(
41 + layerDatabase,
42 + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
43 + EffectOutbox.layer.pipe(Layer.provide(layerDatabase)),
44 + ProviderReplayHarness.layerWithRegistry(
45 + { name: "secret-request-record" },
46 + ProviderAdapterRegistry.layerFromAdapters([adapter]),
47 + { databaseLayer: layerDatabase, runEffectWorker: false },
48 + ),
49 +);
50 +
51 +const projectId = ProjectId.make("project:secret-request-record");
52 +const threadId = ThreadId.make("thread:secret-request-record");
53 +const sessionId = ProviderSessionId.make("session:secret-request-record");
54 +const providerThreadId = ProviderThreadId.make("provider-thread:secret-request-record");
55 +const runId = RunId.make("run:secret-request-record");
56 +const firstAttemptId = RunAttemptId.make("attempt:secret-request-record:1");
57 +const steeredAttemptId = RunAttemptId.make("attempt:secret-request-record:2");
58 +const originalRoot = NodeId.make("node:secret-request-record:original");
59 +const steeredRoot = NodeId.make("node:secret-request-record:steered");
60 +const originalTurnId = ProviderTurnId.make("provider-turn:secret-request-record:original");
61 +const messageId = MessageId.make("message:secret-request-record");
62 +const cardId = TurnItemId.make("turn-item:secret-request:secret-request-record");
63 +const staleCardId = TurnItemId.make("turn-item:secret-request:secret-request-record:stale");
64 +const now = DateTime.makeUnsafe("2026-11-11T20:00:00.000Z");
65 +
66 +/**
67 + * A pending secret card must stay closable after a steering restart replaces the
68 + * run's root node: the call that opened it only ever carries the card's own node,
69 + * so rejecting that node wedges the card open forever.
70 + */
71 +it.effect("closes a secret card recorded under an earlier root after a steering restart", () =>
72 + Effect.gen(function* () {
73 + const orchestrator = yield* Orchestrator.OrchestratorV2;
74 + const projections = yield* ProjectionStore.ProjectionStoreV2;
75 + yield* orchestrator.dispatch({
76 + type: "thread.create",
77 + commandId: CommandId.make("create-secret-request-record"),
78 + threadId,
79 + projectId,
80 + title: "Secret request record",
81 + modelSelection,
82 + runtimeMode: "full-access",
83 + interactionMode: "default",
84 + branch: null,
85 + worktreePath: null,
86 + createdBy: "user",
87 + creationSource: "web",
88 + });
89 + yield* projections.apply({
90 + id: EventId.make("secret-request-record:session"),
91 + type: "provider-session.attached",
92 + threadId,
93 + occurredAt: now,
94 + payload: {
95 + id: sessionId,
96 + driver: adapter.driver,
97 + providerInstanceId: instanceId,
98 + status: "ready",
99 + cwd: "/repo",
100 + model: modelSelection.model,
101 + capabilities: CodexProviderCapabilitiesV2,
102 + createdAt: now,
103 + updatedAt: now,
104 + lastError: null,
105 + },
106 + });
107 + yield* projections.apply({
108 + id: EventId.make("secret-request-record:provider-thread"),
109 + type: "provider-thread.updated",
110 + threadId,
111 + occurredAt: now,
112 + payload: {
113 + id: providerThreadId,
114 + driver: adapter.driver,
115 + providerInstanceId: instanceId,
116 + providerSessionId: sessionId,
117 + appThreadId: threadId,
118 + ownerNodeId: null,
119 + nativeThreadRef: { driver: adapter.driver, nativeId: "native-thread", strength: "strong" },
120 + nativeConversationHeadRef: null,
121 + status: "idle",
122 + firstRunOrdinal: 1,
123 + lastRunOrdinal: 1,
124 + handoffIds: [],
125 + forkedFrom: null,
126 + createdAt: now,
127 + updatedAt: now,
128 + },
129 + });
130 + yield* projections.apply({
131 + id: EventId.make("secret-request-record:run"),
132 + type: "run.created",
133 + threadId,
134 + occurredAt: now,
135 + payload: {
136 + id: runId,
137 + threadId,
138 + ordinal: 1,
139 + providerInstanceId: instanceId,
140 + modelSelection,
141 + providerThreadId,
142 + userMessageId: messageId,
143 + rootNodeId: originalRoot,
144 + activeAttemptId: firstAttemptId,
145 + status: "running",
146 + requestedAt: now,
147 + startedAt: now,
148 + completedAt: null,
149 + checkpointId: null,
150 + contextHandoffId: null,
151 + },
152 + });
153 + yield* projections.apply({
154 + id: EventId.make("secret-request-record:attempt-1"),
155 + type: "run-attempt.created",
156 + threadId,
157 + occurredAt: now,
158 + payload: {
159 + id: firstAttemptId,
160 + runId,
161 + attemptOrdinal: 1,
162 + rootNodeId: originalRoot,
163 + providerInstanceId: instanceId,
164 + providerThreadId,
165 + providerTurnId: null,
166 + reason: "initial",
167 + status: "running",
168 + startedAt: now,
169 + completedAt: null,
170 + },
171 + });
172 +
173 + // The first attempt reached the provider; the card is asked on that turn.
174 + yield* projections.apply({
175 + id: EventId.make("secret-request-record:turn"),
176 + type: "provider-turn.updated",
177 + threadId,
178 + occurredAt: now,
179 + payload: {
180 + id: originalTurnId,
181 + providerThreadId,
182 + nodeId: originalRoot,
183 + runAttemptId: firstAttemptId,
184 + nativeTurnRef: null,
185 + ordinal: 1,
186 + status: "running",
187 + startedAt: now,
188 + completedAt: null,
189 + },
190 + });
191 +
192 + const record = (commandId: string, nodeId: NodeId, turnItemId: TurnItemId) =>
193 + orchestrator.dispatch({
194 + type: "secret_request.record",
195 + commandId: CommandId.make(commandId),
196 + threadId,
197 + runId,
198 + nodeId,
199 + turnItemId,
200 + label: "Booking details",
201 + reason: "To check the passenger in.",
202 + secretStatus: "pending" as const,
203 + });
204 + const readCard = (id: TurnItemId) =>
205 + projections
206 + .getThreadRecords(threadId, ["turnItems"], {
207 + turnItemTypes: ["secret_request"],
208 + messageRoles: [],
209 + })
210 + .pipe(
211 + Effect.map((records) => {
212 + const item = records.turnItems.find((candidate) => candidate.id === id);
213 + return item?.type === "secret_request" ? item : undefined;
214 + }),
215 + );
216 +
217 + yield* record("secret-request-record:open", originalRoot, cardId);
218 + const opened = yield* readCard(cardId);
219 + assert.equal(opened?.secretStatus, "pending");
220 + assert.equal(opened?.providerTurnId, originalTurnId);
221 +
222 + // The user steers while the card waits: the run's root moves to a new attempt.
223 + yield* projections.apply({
224 + id: EventId.make("secret-request-record:run-steered"),
225 + type: "run.updated",
226 + threadId,
227 + occurredAt: now,
228 + payload: {
229 + id: runId,
230 + threadId,
231 + ordinal: 1,
232 + providerInstanceId: instanceId,
233 + modelSelection,
234 + providerThreadId,
235 + userMessageId: messageId,
236 + rootNodeId: steeredRoot,
237 + activeAttemptId: steeredAttemptId,
238 + status: "starting",
239 + requestedAt: now,
240 + startedAt: now,
241 + completedAt: null,
242 + checkpointId: null,
243 + contextHandoffId: null,
244 + },
245 + });
246 + yield* projections.apply({
247 + id: EventId.make("secret-request-record:attempt-2"),
248 + type: "run-attempt.created",
249 + threadId,
250 + occurredAt: now,
251 + payload: {
252 + id: steeredAttemptId,
253 + runId,
254 + attemptOrdinal: 2,
255 + rootNodeId: steeredRoot,
256 + providerInstanceId: instanceId,
257 + providerThreadId,
258 + providerTurnId: null,
259 + reason: "steering_restart",
260 + status: "pending",
261 + startedAt: null,
262 + completedAt: null,
263 + },
264 + });
265 +
266 + // The waiting call only carries the card's own node; closing must still work.
267 + yield* orchestrator.dispatch({
268 + type: "secret_request.record",
269 + commandId: CommandId.make("secret-request-record:close"),
270 + threadId,
271 + runId,
272 + nodeId: originalRoot,
273 + turnItemId: cardId,
274 + label: "Booking details",
275 + reason: "To check the passenger in.",
276 + secretStatus: "cancelled" as const,
277 + });
278 + const cancelled = yield* readCard(cardId);
279 + assert.equal(cancelled?.secretStatus, "cancelled");
280 + assert.equal(cancelled?.status, "cancelled");
281 + // Closing through the card's own node keeps the identity it was asked with,
282 + // even though the run's active attempt has no provider turn of its own.
283 + assert.equal(cancelled?.nodeId, originalRoot);
284 + assert.equal(cancelled?.providerTurnId, originalTurnId);
285 +
286 + // A new card may not be opened under the stale root.
287 + const stale = yield* Effect.flip(
288 + record("secret-request-record:stale-open", originalRoot, staleCardId),
289 + );
290 + assert.match(String((stale as { cause?: unknown }).cause ?? ""), /is not the root of run/);
291 + }).pipe(Effect.provide(layerTest)),
292 +);