Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 MessageId,
4 type ModelSelection,
5 NodeId,
6 type OrchestrationV2ProviderThread,
7 type OrchestrationV2Run,
8 type OrchestrationV2ThreadProjection,
9 ProjectId,
10 ProviderDriverKind,
11 ProviderInstanceId,
12 ProviderSessionId,
13 ProviderThreadId,
14 ProviderTurnId,
15 RunAttemptId,
16 RunId,
17 ThreadId,
18} from "@t3tools/contracts";
19import * as DateTime from "effect/DateTime";
20import * as Effect from "effect/Effect";
21import * as Exit from "effect/Exit";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import * as Ref from "effect/Ref";
25import * as Stream from "effect/Stream";
26
27import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
28import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts";
29import * as EventSink from "./EventSink.ts";
30import * as ProjectionStore from "./ProjectionStore.ts";
31import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
32import * as ProviderSessionManager from "./ProviderSessionManager.ts";
33import * as ProviderTurnControlService from "./ProviderTurnControlService.ts";
34
35const driver = ProviderDriverKind.make("codex");
36const providerInstanceId = ProviderInstanceId.make("codex");
37const modelSelection = {
38 instanceId: providerInstanceId,
39 model: "gpt-5.4",
40} satisfies ModelSelection;
41
42function makeProjection(input: {
43 readonly now: DateTime.Utc;
44 readonly threadId: ThreadId;
45 readonly providerThread: OrchestrationV2ProviderThread;
46 readonly providerTurnId: ProviderTurnId;
47 readonly attemptId: RunAttemptId;
48}): OrchestrationV2ThreadProjection {
49 const runId = RunId.make("run:restart-session");
50 const nodeId = NodeId.make("node:restart-session");
51 return {
52 thread: {
53 createdBy: "user",
54 creationSource: "web",
55 id: input.threadId,
56 projectId: ProjectId.make("project:restart-session"),
57 title: "Restart session",
58 providerInstanceId,
59 modelSelection,
60 runtimeMode: "full-access",
61 interactionMode: "default",
62 branch: null,
63 worktreePath: "/workspace",
64 activeProviderThreadId: input.providerThread.id,
65 lineage: {
66 parentThreadId: null,
67 relationshipToParent: null,
68 rootThreadId: input.threadId,
69 },
70 forkedFrom: null,
71 createdAt: input.now,
72 updatedAt: input.now,
73 archivedAt: null,
74 settledOverride: null,
75 settledAt: null,
76 lastVisitedAt: null,
77 deletedAt: null,
78 },
79 runs: [],
80 attempts: [
81 {
82 id: input.attemptId,
83 runId,
84 attemptOrdinal: 1,
85 rootNodeId: nodeId,
86 providerInstanceId,
87 providerThreadId: input.providerThread.id,
88 providerTurnId: input.providerTurnId,
89 reason: "initial",
90 status: "superseded",
91 startedAt: input.now,
92 completedAt: input.now,
93 },
94 ],
95 nodes: [],
96 subagents: [],
97 providerSessions: [],
98 providerThreads: [input.providerThread],
99 providerTurns: [
100 {
101 id: input.providerTurnId,
102 providerThreadId: input.providerThread.id,
103 nodeId,
104 runAttemptId: input.attemptId,
105 nativeTurnRef: {
106 driver,
107 nativeId: "native-turn:restart-session",
108 strength: "strong",
109 },
110 ordinal: 1,
111 status: "running",
112 startedAt: input.now,
113 completedAt: null,
114 },
115 ],
116 runtimeRequests: [],
117 messages: [],
118 plans: [],
119 turnItems: [],
120 checkpointScopes: [],
121 checkpoints: [],
122 contextHandoffs: [],
123 contextTransfers: [],
124 visibleTurnItems: [],
125 updatedAt: input.now,
126 };
127}
128
129function layerProjectionStore(
130 getProviderControlContext: ProjectionStore.ProjectionStoreV2["Service"]["getProviderControlContext"],
131) {
132 return Layer.succeed(
133 ProjectionStore.ProjectionStoreV2,
134 ProjectionStore.ProjectionStoreV2.of({
135 apply: () => Effect.void,
136 getLimitRecoveryCandidates: () => Effect.die("unused getLimitRecoveryCandidates"),
137 getLimitRecoveryWakeAt: () => Effect.die("unused getLimitRecoveryWakeAt"),
138 getOpenRemoteDelegatedTasks: Effect.die("unused getOpenRemoteDelegatedTasks"),
139 getAgentAwarenessSnapshot: () => Effect.die("unused awareness snapshot"),
140 getShellSnapshot: () => Effect.die("unused getShellSnapshot"),
141 listActiveSubagentThreadIds: () => Effect.die("unused listActiveSubagentThreadIds"),
142 countThreads: () => Effect.die("unused countThreads"),
143 listActiveShellIndex: () => Effect.die("unused listActiveShellIndex"),
144 listActiveThreads: () => Effect.die("unused listActiveThreads"),
145 listOlderSettledThreads: () => Effect.die("unused listOlderSettledThreads"),
146 readShellSnapshot: () => Effect.die("unused readShellSnapshot"),
147 getThreadShell: () => Effect.die("unused getThreadShell"),
148 getForkSourceRunIds: () => Effect.die("unused getForkSourceRunIds"),
149 getThreadTitles: () => Effect.die("unused getThreadTitles"),
150 getThreadLinkMetadata: () => Effect.die("unused getThreadLinkMetadata"),
151 findGuestShareThreadId: () => Effect.die("unused findGuestShareThreadId"),
152 getThread: () => Effect.die("unused getThread"),
153 findThread: () => Effect.die("unused findThread"),
154 getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"),
155 getThreadsWithPullRequests: () => Effect.die("unused getThreadsWithPullRequests"),
156 getThreadWorktreePaths: () => Effect.die("unused getThreadWorktreePaths"),
157 getThreadProjection: () => Effect.die("control effects must not load transcript"),
158 getTurnStartContext: () => Effect.die("unused"),
159 getTurnStartHistory: () => Effect.die("unused"),
160 getRuntimeRecoveryProjection: () => Effect.die("unused getRuntimeRecoveryProjection"),
161 getPlan: () => Effect.die("unused"),
162 hasUnpairedRunInterruptRequest: () => Effect.die("unused interrupt read"),
163 hasRunInterruptRequest: () => Effect.die("unused stop read"),
164 getRunProviderRecords: () => Effect.die("unused run provider read"),
165 getRunCardRecords: () => Effect.die("unused run card read"),
166 getThreadAttachmentIds: () => Effect.die("Unused attachment lookup"),
167 searchThread: () => Effect.die("unused"),
168 searchThreadStream: () => Stream.empty,
169 getThreadHistoryPage: () => Effect.die("unused"),
170 getTimelinePage: () => Effect.die("Unused timeline read"),
171 getMessageCount: () => Effect.die("unused message count"),
172 getTranscriptByteFloor: () => Effect.die("unused transcript byte floor"),
173 hasPendingDelegatedCompletion: () => Effect.die("unused hasPendingDelegatedCompletion"),
174 getSubagentCount: () => Effect.die("unused subagent count"),
175 getRunCount: () => Effect.die("unused run count"),
176 listAppOwnedChildThreadIds: () => Effect.die("unused listAppOwnedChildThreadIds"),
177 getNextTurnItemOrdinal: () => Effect.die("unused ordinal read"),
178 getTurnItem: () => Effect.die("unused turn item read"),
179 getMessagesById: () => Effect.die("unused getMessagesById"),
180 getThreadRecords: () => Effect.die("unused record read"),
181 getRuntimeRequest: () => Effect.die("unused getRuntimeRequest"),
182 getRunningTurnContext: () => Effect.die("unused getRunningTurnContext"),
183 getThreadProviderContext: () => Effect.die("unused getThreadProviderContext"),
184 getRuntimeResponseContext: () => Effect.die("unused getRuntimeResponseContext"),
185 getPendingNativeUserInputs: () => Effect.die("unused getPendingNativeUserInputs"),
186 getProviderControlContext,
187 getCheckpointContext: () => Effect.die("not used"),
188 getCheckpointRollbackContext: () => Effect.die("unused rollback context"),
189 getCheckpointCaptureContext: () => Effect.die("not used"),
190 getRunMessage: () => Effect.die("not used"),
191 getDelegatedChildControls: () => Effect.die("not used"),
192 getRun: () => Effect.die("not used"),
193 isNodeStored: () => Effect.die("not used"),
194 canStartQueuedRun: () => Effect.die("not used"),
195 getHeldQueuedRuns: () => Effect.die("not used"),
196 getRecoveryThreadIds: () => Effect.die("unused getRecoveryThreadIds"),
197 getUnreadableThreadIds: () => Effect.die("unused getUnreadableThreadIds"),
198 getThreadSnapshot: () => Effect.die("unused getThreadSnapshot"),
199 getThreadSnapshotWindow: () => Effect.die("unused getThreadSnapshotWindow"),
200 getPullRequestSnapshot: () => Effect.die("unused getPullRequestSnapshot"),
201 }),
202 );
203}
204
205function layerSessions(
206 liveSessionId: ProviderSessionId,
207 runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime,
208) {
209 return Layer.succeed(
210 ProviderSessionManager.ProviderSessionManagerV2,
211 ProviderSessionManager.ProviderSessionManagerV2.of({
212 shutdown: Effect.void,
213 open: () => Effect.die("unused open"),
214 get: (providerSessionId) =>
215 Effect.succeed(providerSessionId === liveSessionId ? Option.some(runtime) : Option.none()),
216 isLive: (providerSessionId) => Effect.succeed(providerSessionId === liveSessionId),
217 close: () => Effect.void,
218 closeInstance: () => Effect.void,
219 release: () => Effect.void,
220 detach: () => Effect.void,
221 otherWorkingThreads: () => Effect.succeed([]),
222 releaseUnlessBusy: () => Effect.succeed(true),
223 forgetLoadedProviderThread: () => Effect.void,
224 subscribePromptSuggestion: () => Stream.empty,
225 }),
226 );
227}
228
229it.effect(
230 "interrupts the historical session only for the exact committed restart replacement",
231 () =>
232 Effect.gen(function* () {
233 const now = yield* DateTime.now;
234 const threadId = ThreadId.make("thread:restart-session");
235 const oldSessionId = ProviderSessionId.make("provider-session:restart-session:old");
236 const replacementSessionId = ProviderSessionId.make(
237 "provider-session:restart-session:replacement",
238 );
239 const unrelatedSessionId = ProviderSessionId.make(
240 "provider-session:restart-session:unrelated",
241 );
242 const providerThreadId = ProviderThreadId.make("provider-thread:restart-session");
243 const providerTurnId = ProviderTurnId.make("provider-turn:restart-session");
244 const attemptId = RunAttemptId.make("run-attempt:restart-session");
245 const providerThread: OrchestrationV2ProviderThread = {
246 id: providerThreadId,
247 driver,
248 providerInstanceId,
249 providerSessionId: replacementSessionId,
250 appThreadId: threadId,
251 ownerNodeId: null,
252 nativeThreadRef: {
253 driver,
254 nativeId: "native-thread:restart-session",
255 strength: "strong",
256 },
257 nativeConversationHeadRef: null,
258 status: "not_loaded",
259 firstRunOrdinal: 1,
260 lastRunOrdinal: 1,
261 handoffIds: [],
262 forkedFrom: null,
263 createdAt: now,
264 updatedAt: now,
265 };
266 const projection = yield* Ref.make(
267 makeProjection({ now, threadId, providerThread, providerTurnId, attemptId }),
268 );
269 const interruptedThread = yield* Ref.make<OrchestrationV2ProviderThread | null>(null);
270 const providerSession = {
271 id: oldSessionId,
272 driver,
273 providerInstanceId,
274 status: "running" as const,
275 cwd: "/workspace",
276 model: modelSelection.model,
277 capabilities: CodexProviderCapabilitiesV2,
278 createdAt: now,
279 updatedAt: now,
280 lastError: null,
281 };
282 const runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime = {
283 instanceId: providerInstanceId,
284 driver,
285 providerSessionId: oldSessionId,
286 providerSession,
287 events: Stream.empty,
288 ensureThread: () => Effect.die("unused ensureThread"),
289 resumeThread: () => Effect.die("unused resumeThread"),
290 startTurn: () => Effect.die("unused startTurn"),
291 steerTurn: () => Effect.die("unused steerTurn"),
292 interruptTurn: ({ providerThread: target }) =>
293 Effect.all(
294 [
295 Ref.set(interruptedThread, target),
296 Ref.update(projection, (current) => ({
297 ...current,
298 providerTurns: current.providerTurns.map((turn) =>
299 turn.id === providerTurnId
300 ? { ...turn, status: "interrupted" as const, completedAt: now }
301 : turn,
302 ),
303 })),
304 ],
305 { discard: true },
306 ),
307 respondToRuntimeRequest: () => Effect.die("unused respondToRuntimeRequest"),
308 readThreadSnapshot: () => Effect.die("unused readThreadSnapshot"),
309 rollbackThread: () => Effect.die("unused rollbackThread"),
310 forkThread: () => Effect.die("unused forkThread"),
311 };
312 const layerProjection = layerProjectionStore((_threadId, target) =>
313 Ref.get(projection).pipe(
314 Effect.map((current) => ({
315 providerThread: current.providerThreads.find(
316 (thread) => thread.id === target.providerThreadId,
317 ),
318 providerTurn: current.providerTurns.find((turn) => turn.id === target.providerTurnId),
319 attempt: current.attempts.find((attempt) => attempt.id === target.attemptId),
320 message: undefined,
321 run: undefined,
322 })),
323 ),
324 );
325 const layerSessionManager = layerSessions(oldSessionId, runtime);
326 const layerControl = ProviderTurnControlService.layer.pipe(
327 Layer.provide(
328 Layer.mergeAll(
329 layerProjection,
330 layerSessionManager,
331 Layer.mock(EventSink.EventSinkV2)({}),
332 McpAppModelContext.layerEmpty,
333 ),
334 ),
335 );
336
337 const [ordinaryInterrupt, unrelatedRestart] = yield* Effect.gen(function* () {
338 const control = yield* ProviderTurnControlService.ProviderTurnControlServiceV2;
339 const ordinary = yield* Effect.exit(
340 control.interrupt({
341 threadId,
342 providerSessionId: oldSessionId,
343 providerThreadId,
344 providerTurnId,
345 }),
346 );
347 const unrelated = yield* Effect.exit(
348 control.interruptAndAwaitTerminal({
349 threadId,
350 providerSessionId: oldSessionId,
351 replacementProviderSessionId: unrelatedSessionId,
352 providerThreadId,
353 providerTurnId,
354 interruptedAttemptId: attemptId,
355 }),
356 );
357 return [ordinary, unrelated] as const;
358 }).pipe(Effect.provide(layerControl));
359
360 assert.isTrue(Exit.isFailure(ordinaryInterrupt));
361 assert.isTrue(Exit.isFailure(unrelatedRestart));
362 assert.isNull(yield* Ref.get(interruptedThread));
363
364 yield* Effect.gen(function* () {
365 const control = yield* ProviderTurnControlService.ProviderTurnControlServiceV2;
366 yield* control.interruptAndAwaitTerminal({
367 threadId,
368 providerSessionId: oldSessionId,
369 replacementProviderSessionId: replacementSessionId,
370 providerThreadId,
371 providerTurnId,
372 interruptedAttemptId: attemptId,
373 });
374 }).pipe(Effect.provide(layerControl));
375
376 const interrupted = yield* Ref.get(interruptedThread);
377 assert.isNotNull(interrupted);
378 assert.equal(interrupted?.providerSessionId, oldSessionId);
379 assert.equal(interrupted?.id, providerThreadId);
380 assert.equal(interrupted?.nativeThreadRef?.nativeId, "native-thread:restart-session");
381 }),
382);
383
384it.effect("steers a running turn with its sender and the thread's MCP app model context", () =>
385 Effect.gen(function* () {
386 const now = yield* DateTime.now;
387 const threadId = ThreadId.make("thread:steer-app-context");
388 const sessionId = ProviderSessionId.make("provider-session:steer-app-context");
389 const providerTurnId = ProviderTurnId.make("provider-turn:steer-app-context");
390 const attemptId = RunAttemptId.make("run-attempt:steer-app-context");
391 const providerThread = {
392 id: ProviderThreadId.make("provider-thread:steer-app-context"),
393 driver,
394 providerInstanceId,
395 providerSessionId: sessionId,
396 } as OrchestrationV2ProviderThread;
397 const projection = makeProjection({ now, threadId, providerThread, providerTurnId, attemptId });
398 const steered: Array<ProviderAdapter.ProviderAdapterV2SteerInput> = [];
399 const runtime = {
400 instanceId: providerInstanceId,
401 driver,
402 providerSessionId: sessionId,
403 steerTurn: (input: ProviderAdapter.ProviderAdapterV2SteerInput) =>
404 Effect.sync(() => void steered.push(input)),
405 } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime;
406 const layerControl = ProviderTurnControlService.layer.pipe(
407 Layer.provide(
408 Layer.mergeAll(
409 layerProjectionStore(() =>
410 Effect.succeed({
411 providerThread,
412 providerTurn: projection.providerTurns[0],
413 attempt: projection.attempts[0],
414 message: {
415 id: MessageId.make("message:steer-app-context"),
416 text: "What did the app report?",
417 attachments: [],
418 createdBy: "agent",
419 creationSource: "mcp",
420 senderThreadId: ThreadId.make("thread:steer-sender"),
421 } as unknown as NonNullable<
422 ProjectionStore.ProjectionProviderControlContext["message"]
423 >,
424 run: {
425 id: RunId.make("run:steer-app-context"),
426 status: "running",
427 activeAttemptId: attemptId,
428 } as OrchestrationV2Run,
429 }),
430 ),
431 layerSessions(sessionId, runtime),
432 Layer.mock(EventSink.EventSinkV2)({}),
433 Layer.mock(McpAppModelContext.McpAppModelContext)({
434 forThread: () =>
435 Effect.succeed([
436 {
437 itemId: "turn-item:call-1",
438 server: "tools",
439 tool: "picker",
440 text: "Pressed: blue",
441 updatedAt: "2026-11-23T14:02:17.000Z",
442 },
443 ]),
444 }),
445 ),
446 ),
447 );
448
449 yield* Effect.gen(function* () {
450 const control = yield* ProviderTurnControlService.ProviderTurnControlServiceV2;
451 yield* control.steer({
452 threadId,
453 providerSessionId: sessionId,
454 providerThreadId: providerThread.id,
455 providerTurnId,
456 messageId: MessageId.make("message:steer-app-context"),
457 });
458 }).pipe(Effect.provide(layerControl));
459
460 assert.equal(steered.length, 1);
461 assert.equal(
462 steered[0]!.message.text,
463 '[T3 Code: the agent in T3 thread "thread:steer-sender" sent this message, not the user.]\n\nWhat did the app report?',
464 );
465 assert.deepEqual("appContext" in steered[0]! ? steered[0].appContext : undefined, [
466 {
467 key: "mcp_app_turn-item_call-1",
468 text: "Pressed: blue",
469 updatedAt: "2026-11-23T14:02:17.000Z",
470 },
471 ]);
472 }),
473);