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 hasProviderThread: () => Effect.die("unused hasProviderThread"),
149 getForkSourceRunIds: () => Effect.die("unused getForkSourceRunIds"),
150 getThreadTitles: () => Effect.die("unused getThreadTitles"),
151 getThreadLinkMetadata: () => Effect.die("unused getThreadLinkMetadata"),
152 findGuestShareThreadId: () => Effect.die("unused findGuestShareThreadId"),
153 getThread: () => Effect.die("unused getThread"),
154 findThread: () => Effect.die("unused findThread"),
155 getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"),
156 getThreadsWithPullRequests: () => Effect.die("unused getThreadsWithPullRequests"),
157 getThreadWorktreePaths: () => Effect.die("unused getThreadWorktreePaths"),
158 getThreadProjection: () => Effect.die("control effects must not load transcript"),
159 getTurnStartContext: () => Effect.die("unused"),
160 getTurnStartHistory: () => Effect.die("unused"),
161 getRuntimeRecoveryProjection: () => Effect.die("unused getRuntimeRecoveryProjection"),
162 getPlan: () => Effect.die("unused"),
163 hasUnpairedRunInterruptRequest: () => Effect.die("unused interrupt read"),
164 hasRunInterruptRequest: () => Effect.die("unused stop read"),
165 getRunProviderRecords: () => Effect.die("unused run provider read"),
166 getRunCardRecords: () => Effect.die("unused run card read"),
167 getThreadAttachmentIds: () => Effect.die("Unused attachment lookup"),
168 searchThread: () => Effect.die("unused"),
169 searchThreadStream: () => Stream.empty,
170 getThreadHistoryPage: () => Effect.die("unused"),
171 getTimelinePage: () => Effect.die("Unused timeline read"),
172 getMessageCount: () => Effect.die("unused message count"),
173 getTranscriptByteFloor: () => Effect.die("unused transcript byte floor"),
174 hasPendingDelegatedCompletion: () => Effect.die("unused hasPendingDelegatedCompletion"),
175 getSubagentCount: () => Effect.die("unused subagent count"),
176 getRunCount: () => Effect.die("unused run count"),
177 listAppOwnedChildThreadIds: () => Effect.die("unused listAppOwnedChildThreadIds"),
178 listLiveNestedThreads: () => Effect.die("unused listLiveNestedThreads"),
179 getNextTurnItemOrdinal: () => Effect.die("unused ordinal read"),
180 getTurnItem: () => Effect.die("unused turn item read"),
181 getMessagesById: () => Effect.die("unused getMessagesById"),
182 getThreadRecords: () => Effect.die("unused record read"),
183 getRuntimeRequest: () => Effect.die("unused getRuntimeRequest"),
184 getRunningTurnContext: () => Effect.die("unused getRunningTurnContext"),
185 getThreadProviderContext: () => Effect.die("unused getThreadProviderContext"),
186 getRuntimeResponseContext: () => Effect.die("unused getRuntimeResponseContext"),
187 getPendingNativeUserInputs: () => Effect.die("unused getPendingNativeUserInputs"),
188 getProviderControlContext,
189 getCheckpointContext: () => Effect.die("not used"),
190 getCheckpointRollbackContext: () => Effect.die("unused rollback context"),
191 getCheckpointCaptureContext: () => Effect.die("not used"),
192 getRunMessage: () => Effect.die("not used"),
193 getDelegatedChildControls: () => Effect.die("not used"),
194 getRun: () => Effect.die("not used"),
195 isNodeStored: () => Effect.die("not used"),
196 canStartQueuedRun: () => Effect.die("not used"),
197 getHeldQueuedRuns: () => Effect.die("not used"),
198 getRecoveryThreadIds: () => Effect.die("unused getRecoveryThreadIds"),
199 getUnreadableThreadIds: () => Effect.die("unused getUnreadableThreadIds"),
200 getThreadSnapshot: () => Effect.die("unused getThreadSnapshot"),
201 getThreadSnapshotWindow: () => Effect.die("unused getThreadSnapshotWindow"),
202 getPullRequestSnapshot: () => Effect.die("unused getPullRequestSnapshot"),
203 }),
204 );
205}
206
207function layerSessions(
208 liveSessionId: ProviderSessionId,
209 runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime,
210) {
211 return Layer.succeed(
212 ProviderSessionManager.ProviderSessionManagerV2,
213 ProviderSessionManager.ProviderSessionManagerV2.of({
214 shutdown: Effect.void,
215 checkCompatible: () => Effect.void,
216 open: () => Effect.die("unused open"),
217 get: (providerSessionId) =>
218 Effect.succeed(providerSessionId === liveSessionId ? Option.some(runtime) : Option.none()),
219 isLive: (providerSessionId) => Effect.succeed(providerSessionId === liveSessionId),
220 close: () => Effect.void,
221 closeInstance: () => Effect.void,
222 release: () => Effect.void,
223 detach: () => Effect.void,
224 otherWorkingThreads: () => Effect.succeed([]),
225 releaseUnlessBusy: () => Effect.succeed(true),
226 forgetLoadedProviderThread: () => Effect.void,
227 subscribePromptSuggestion: () => Stream.empty,
228 }),
229 );
230}
231
232it.effect(
233 "interrupts the historical session only for the exact committed restart replacement",
234 () =>
235 Effect.gen(function* () {
236 const now = yield* DateTime.now;
237 const threadId = ThreadId.make("thread:restart-session");
238 const oldSessionId = ProviderSessionId.make("provider-session:restart-session:old");
239 const replacementSessionId = ProviderSessionId.make(
240 "provider-session:restart-session:replacement",
241 );
242 const unrelatedSessionId = ProviderSessionId.make(
243 "provider-session:restart-session:unrelated",
244 );
245 const providerThreadId = ProviderThreadId.make("provider-thread:restart-session");
246 const providerTurnId = ProviderTurnId.make("provider-turn:restart-session");
247 const attemptId = RunAttemptId.make("run-attempt:restart-session");
248 const providerThread: OrchestrationV2ProviderThread = {
249 id: providerThreadId,
250 driver,
251 providerInstanceId,
252 providerSessionId: replacementSessionId,
253 appThreadId: threadId,
254 ownerNodeId: null,
255 nativeThreadRef: {
256 driver,
257 nativeId: "native-thread:restart-session",
258 strength: "strong",
259 },
260 nativeConversationHeadRef: null,
261 status: "not_loaded",
262 firstRunOrdinal: 1,
263 lastRunOrdinal: 1,
264 handoffIds: [],
265 forkedFrom: null,
266 createdAt: now,
267 updatedAt: now,
268 };
269 const projection = yield* Ref.make(
270 makeProjection({ now, threadId, providerThread, providerTurnId, attemptId }),
271 );
272 const interruptedThread = yield* Ref.make<OrchestrationV2ProviderThread | null>(null);
273 const providerSession = {
274 id: oldSessionId,
275 driver,
276 providerInstanceId,
277 status: "running" as const,
278 cwd: "/workspace",
279 model: modelSelection.model,
280 capabilities: CodexProviderCapabilitiesV2,
281 createdAt: now,
282 updatedAt: now,
283 lastError: null,
284 };
285 const runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime = {
286 instanceId: providerInstanceId,
287 driver,
288 providerSessionId: oldSessionId,
289 providerSession,
290 events: Stream.empty,
291 ensureThread: () => Effect.die("unused ensureThread"),
292 resumeThread: () => Effect.die("unused resumeThread"),
293 startTurn: () => Effect.die("unused startTurn"),
294 steerTurn: () => Effect.die("unused steerTurn"),
295 interruptTurn: ({ providerThread: target }) =>
296 Effect.all(
297 [
298 Ref.set(interruptedThread, target),
299 Ref.update(projection, (current) => ({
300 ...current,
301 providerTurns: current.providerTurns.map((turn) =>
302 turn.id === providerTurnId
303 ? { ...turn, status: "interrupted" as const, completedAt: now }
304 : turn,
305 ),
306 })),
307 ],
308 { discard: true },
309 ),
310 respondToRuntimeRequest: () => Effect.die("unused respondToRuntimeRequest"),
311 readThreadSnapshot: () => Effect.die("unused readThreadSnapshot"),
312 rollbackThread: () => Effect.die("unused rollbackThread"),
313 forkThread: () => Effect.die("unused forkThread"),
314 };
315 const layerProjection = layerProjectionStore((_threadId, target) =>
316 Ref.get(projection).pipe(
317 Effect.map((current) => ({
318 providerThread: current.providerThreads.find(
319 (thread) => thread.id === target.providerThreadId,
320 ),
321 providerTurn: current.providerTurns.find((turn) => turn.id === target.providerTurnId),
322 attempt: current.attempts.find((attempt) => attempt.id === target.attemptId),
323 message: undefined,
324 run: undefined,
325 })),
326 ),
327 );
328 const layerSessionManager = layerSessions(oldSessionId, runtime);
329 const layerControl = ProviderTurnControlService.layer.pipe(
330 Layer.provide(
331 Layer.mergeAll(
332 layerProjection,
333 layerSessionManager,
334 Layer.mock(EventSink.EventSinkV2)({}),
335 McpAppModelContext.layerEmpty,
336 ),
337 ),
338 );
339
340 const [ordinaryInterrupt, unrelatedRestart] = yield* Effect.gen(function* () {
341 const control = yield* ProviderTurnControlService.ProviderTurnControlServiceV2;
342 const ordinary = yield* Effect.exit(
343 control.interrupt({
344 threadId,
345 providerSessionId: oldSessionId,
346 providerThreadId,
347 providerTurnId,
348 }),
349 );
350 const unrelated = yield* Effect.exit(
351 control.interruptAndAwaitTerminal({
352 threadId,
353 providerSessionId: oldSessionId,
354 replacementProviderSessionId: unrelatedSessionId,
355 providerThreadId,
356 providerTurnId,
357 interruptedAttemptId: attemptId,
358 }),
359 );
360 return [ordinary, unrelated] as const;
361 }).pipe(Effect.provide(layerControl));
362
363 assert.isTrue(Exit.isFailure(ordinaryInterrupt));
364 assert.isTrue(Exit.isFailure(unrelatedRestart));
365 assert.isNull(yield* Ref.get(interruptedThread));
366
367 yield* Effect.gen(function* () {
368 const control = yield* ProviderTurnControlService.ProviderTurnControlServiceV2;
369 yield* control.interruptAndAwaitTerminal({
370 threadId,
371 providerSessionId: oldSessionId,
372 replacementProviderSessionId: replacementSessionId,
373 providerThreadId,
374 providerTurnId,
375 interruptedAttemptId: attemptId,
376 });
377 }).pipe(Effect.provide(layerControl));
378
379 const interrupted = yield* Ref.get(interruptedThread);
380 assert.isNotNull(interrupted);
381 assert.equal(interrupted?.providerSessionId, oldSessionId);
382 assert.equal(interrupted?.id, providerThreadId);
383 assert.equal(interrupted?.nativeThreadRef?.nativeId, "native-thread:restart-session");
384 }),
385);
386
387it.effect("steers a running turn with its sender and the thread's MCP app model context", () =>
388 Effect.gen(function* () {
389 const now = yield* DateTime.now;
390 const threadId = ThreadId.make("thread:steer-app-context");
391 const sessionId = ProviderSessionId.make("provider-session:steer-app-context");
392 const providerTurnId = ProviderTurnId.make("provider-turn:steer-app-context");
393 const attemptId = RunAttemptId.make("run-attempt:steer-app-context");
394 const providerThread = {
395 id: ProviderThreadId.make("provider-thread:steer-app-context"),
396 driver,
397 providerInstanceId,
398 providerSessionId: sessionId,
399 } as OrchestrationV2ProviderThread;
400 const projection = makeProjection({ now, threadId, providerThread, providerTurnId, attemptId });
401 const steered: Array<ProviderAdapter.ProviderAdapterV2SteerInput> = [];
402 const runtime = {
403 instanceId: providerInstanceId,
404 driver,
405 providerSessionId: sessionId,
406 steerTurn: (input: ProviderAdapter.ProviderAdapterV2SteerInput) =>
407 Effect.sync(() => void steered.push(input)),
408 } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime;
409 const layerControl = ProviderTurnControlService.layer.pipe(
410 Layer.provide(
411 Layer.mergeAll(
412 layerProjectionStore(() =>
413 Effect.succeed({
414 providerThread,
415 providerTurn: projection.providerTurns[0],
416 attempt: projection.attempts[0],
417 message: {
418 id: MessageId.make("message:steer-app-context"),
419 text: "What did the app report?",
420 attachments: [],
421 createdBy: "agent",
422 creationSource: "mcp",
423 senderThreadId: ThreadId.make("thread:steer-sender"),
424 } as unknown as NonNullable<
425 ProjectionStore.ProjectionProviderControlContext["message"]
426 >,
427 run: {
428 id: RunId.make("run:steer-app-context"),
429 status: "running",
430 activeAttemptId: attemptId,
431 } as OrchestrationV2Run,
432 }),
433 ),
434 layerSessions(sessionId, runtime),
435 Layer.mock(EventSink.EventSinkV2)({}),
436 Layer.mock(McpAppModelContext.McpAppModelContext)({
437 forThread: () =>
438 Effect.succeed([
439 {
440 itemId: "turn-item:call-1",
441 server: "tools",
442 tool: "picker",
443 text: "Pressed: blue",
444 updatedAt: "2026-11-23T14:02:17.000Z",
445 },
446 ]),
447 }),
448 ),
449 ),
450 );
451
452 yield* Effect.gen(function* () {
453 const control = yield* ProviderTurnControlService.ProviderTurnControlServiceV2;
454 yield* control.steer({
455 threadId,
456 providerSessionId: sessionId,
457 providerThreadId: providerThread.id,
458 providerTurnId,
459 messageId: MessageId.make("message:steer-app-context"),
460 });
461 }).pipe(Effect.provide(layerControl));
462
463 assert.equal(steered.length, 1);
464 assert.equal(
465 steered[0]!.message.text,
466 '[T3 Code: the agent in T3 thread "thread:steer-sender" sent this message, not the user.]\n\nWhat did the app report?',
467 );
468 assert.deepEqual("appContext" in steered[0]! ? steered[0].appContext : undefined, [
469 {
470 key: "mcp_app_turn-item_call-1",
471 text: "Pressed: blue",
472 updatedAt: "2026-11-23T14:02:17.000Z",
473 },
474 ]);
475 }),
476);