Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProviderTurnControlService.test.ts

460 lines18.0 KB

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