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

ProviderTurnControlService.test.ts

314 lines11.3 KB

1import { assert, it } from "@effect/vitest";
2import {
3 type ModelSelection,
4 NodeId,
5 type OrchestrationV2ProviderThread,
6 type OrchestrationV2ThreadProjection,
7 ProjectId,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 ProviderSessionId,
11 ProviderThreadId,
12 ProviderTurnId,
13 RunAttemptId,
14 RunId,
15 ThreadId,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as Exit from "effect/Exit";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Ref from "effect/Ref";
23import * as Stream from "effect/Stream";
24​
25import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
26import { ProjectionStoreV2 } from "./ProjectionStore.ts";
27import type { ProviderAdapterV2SessionRuntime } from "./ProviderAdapter.ts";
28import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
29import {
30 layer as providerTurnControlLayer,
31 ProviderTurnControlServiceV2,
32} from "./ProviderTurnControlService.ts";
33​
34const driver = ProviderDriverKind.make("codex");
35const providerInstanceId = ProviderInstanceId.make("codex");
36const modelSelection = {
37 instanceId: providerInstanceId,
38 model: "gpt-5.4",
39} satisfies ModelSelection;
40​
41function makeProjection(input: {
42 readonly now: DateTime.Utc;
43 readonly threadId: ThreadId;
44 readonly providerThread: OrchestrationV2ProviderThread;
45 readonly providerTurnId: ProviderTurnId;
46 readonly attemptId: RunAttemptId;
47}): OrchestrationV2ThreadProjection {
48 const runId = RunId.make("run:restart-session");
49 const nodeId = NodeId.make("node:restart-session");
50 return {
51 thread: {
52 createdBy: "user",
53 creationSource: "web",
54 id: input.threadId,
55 projectId: ProjectId.make("project:restart-session"),
56 title: "Restart session",
57 providerInstanceId,
58 modelSelection,
59 runtimeMode: "full-access",
60 interactionMode: "default",
61 branch: null,
62 worktreePath: "/workspace",
63 activeProviderThreadId: input.providerThread.id,
64 lineage: {
65 parentThreadId: null,
66 relationshipToParent: null,
67 rootThreadId: input.threadId,
68 },
69 forkedFrom: null,
70 createdAt: input.now,
71 updatedAt: input.now,
72 archivedAt: null,
73 settledOverride: null,
74 settledAt: null,
75 lastVisitedAt: null,
76 deletedAt: null,
77 },
78 runs: [],
79 attempts: [
80 {
81 id: input.attemptId,
82 runId,
83 attemptOrdinal: 1,
84 rootNodeId: nodeId,
85 providerInstanceId,
86 providerThreadId: input.providerThread.id,
87 providerTurnId: input.providerTurnId,
88 reason: "initial",
89 status: "superseded",
90 startedAt: input.now,
91 completedAt: input.now,
92 },
93 ],
94 nodes: [],
95 subagents: [],
96 providerSessions: [],
97 providerThreads: [input.providerThread],
98 providerTurns: [
99 {
100 id: input.providerTurnId,
101 providerThreadId: input.providerThread.id,
102 nodeId,
103 runAttemptId: input.attemptId,
104 nativeTurnRef: {
105 driver,
106 nativeId: "native-turn:restart-session",
107 strength: "strong",
108 },
109 ordinal: 1,
110 status: "running",
111 startedAt: input.now,
112 completedAt: null,
113 },
114 ],
115 runtimeRequests: [],
116 messages: [],
117 plans: [],
118 turnItems: [],
119 checkpointScopes: [],
120 checkpoints: [],
121 contextHandoffs: [],
122 contextTransfers: [],
123 visibleTurnItems: [],
124 updatedAt: input.now,
125 };
127​
128it.effect(
129 "interrupts the historical session only for the exact committed restart replacement",
130 () =>
131 Effect.gen(function* () {
132 const now = yield* DateTime.now;
133 const threadId = ThreadId.make("thread:restart-session");
134 const oldSessionId = ProviderSessionId.make("provider-session:restart-session:old");
135 const replacementSessionId = ProviderSessionId.make(
136 "provider-session:restart-session:replacement",
137 );
138 const unrelatedSessionId = ProviderSessionId.make(
139 "provider-session:restart-session:unrelated",
140 );
141 const providerThreadId = ProviderThreadId.make("provider-thread:restart-session");
142 const providerTurnId = ProviderTurnId.make("provider-turn:restart-session");
143 const attemptId = RunAttemptId.make("run-attempt:restart-session");
144 const providerThread: OrchestrationV2ProviderThread = {
145 id: providerThreadId,
146 driver,
147 providerInstanceId,
148 // The restart command has already projected this replacement binding
149 // before the process-bound restart effect executes.
150 providerSessionId: replacementSessionId,
151 appThreadId: threadId,
152 ownerNodeId: null,
153 nativeThreadRef: {
154 driver,
155 nativeId: "native-thread:restart-session",
156 strength: "strong",
157 },
158 nativeConversationHeadRef: null,
159 status: "not_loaded",
160 firstRunOrdinal: 1,
161 lastRunOrdinal: 1,
162 handoffIds: [],
163 forkedFrom: null,
164 createdAt: now,
165 updatedAt: now,
166 };
167 const projection = yield* Ref.make(
168 makeProjection({ now, threadId, providerThread, providerTurnId, attemptId }),
169 );
170 const interruptedThread = yield* Ref.make<OrchestrationV2ProviderThread | null>(null);
171 const providerSession = {
172 id: oldSessionId,
173 driver,
174 providerInstanceId,
175 status: "running" as const,
176 cwd: "/workspace",
177 model: modelSelection.model,
178 capabilities: CodexProviderCapabilitiesV2,
179 createdAt: now,
180 updatedAt: now,
181 lastError: null,
182 };
183 const runtime: ProviderAdapterV2SessionRuntime = {
184 instanceId: providerInstanceId,
185 driver,
186 providerSessionId: oldSessionId,
187 providerSession,
188 events: Stream.empty,
189 ensureThread: () => Effect.die("unused ensureThread"),
190 resumeThread: () => Effect.die("unused resumeThread"),
191 startTurn: () => Effect.die("unused startTurn"),
192 steerTurn: () => Effect.die("unused steerTurn"),
193 interruptTurn: ({ providerThread: target }) =>
194 Effect.all(
195 [
196 Ref.set(interruptedThread, target),
197 Ref.update(projection, (current) => ({
198 ...current,
199 providerTurns: current.providerTurns.map((turn) =>
200 turn.id === providerTurnId
201 ? { ...turn, status: "interrupted" as const, completedAt: now }
202 : turn,
203 ),
204 })),
205 ],
206 { discard: true },
207 ),
208 respondToRuntimeRequest: () => Effect.die("unused respondToRuntimeRequest"),
209 readThreadSnapshot: () => Effect.die("unused readThreadSnapshot"),
210 rollbackThread: () => Effect.die("unused rollbackThread"),
211 forkThread: () => Effect.die("unused forkThread"),
212 };
213 const projectionLayer = Layer.succeed(
214 ProjectionStoreV2,
215 ProjectionStoreV2.of({
216 apply: () => Effect.void,
217 getShellSnapshot: () => Effect.die("unused getShellSnapshot"),
218 getThreadShell: () => Effect.die("unused getThreadShell"),
219 getThread: () => Ref.get(projection).pipe(Effect.map((state) => state.thread)),
220 getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"),
221 getThreadProjection: () => Effect.die("control effects must not load transcript"),
222 getRuntimeRecoveryProjection: () => Effect.die("unused getRuntimeRecoveryProjection"),
223 getPlan: () => Effect.die("unused"),
224 getRuntimeRequest: () => Effect.die("unused getRuntimeRequest"),
225 getRunningTurnContext: () => Effect.die("unused getRunningTurnContext"),
226 getThreadProviderContext: () => Effect.die("unused getThreadProviderContext"),
227 getRuntimeResponseContext: () => Effect.die("unused getRuntimeResponseContext"),
228 getPendingNativeUserInputs: () => Effect.die("unused getPendingNativeUserInputs"),
229 getProviderControlContext: (_threadId, target) =>
230 Ref.get(projection).pipe(
231 Effect.map((current) => ({
232 providerThread: current.providerThreads.find(
233 (thread) => thread.id === target.providerThreadId,
234 ),
235 providerTurn: current.providerTurns.find(
236 (turn) => turn.id === target.providerTurnId,
237 ),
238 attempt: current.attempts.find((attempt) => attempt.id === target.attemptId),
239 message: undefined,
240 run: undefined,
241 })),
242 ),
243 getCheckpointContext: () => Effect.die("not used"),
244 getRecoveryThreadIds: () => Effect.die("unused getRecoveryThreadIds"),
245 getUnreadableThreadIds: () => Effect.die("unused getUnreadableThreadIds"),
246 getThreadSnapshot: () => Effect.die("unused getThreadSnapshot"),
247 getThreadSnapshotWindow: () => Effect.die("unused getThreadSnapshotWindow"),
248 }),
249 );
250 const sessionManagerLayer = Layer.succeed(
251 ProviderSessionManagerV2,
252 ProviderSessionManagerV2.of({
253 shutdown: Effect.void,
254 open: () => Effect.die("unused open"),
255 get: (providerSessionId) =>
256 Effect.succeed(
257 providerSessionId === oldSessionId ? Option.some(runtime) : Option.none(),
258 ),
259 close: () => Effect.void,
260 closeInstance: () => Effect.void,
261 release: () => Effect.void,
262 detach: () => Effect.void,
263 }),
264 );
265 const controlLayer = providerTurnControlLayer.pipe(
266 Layer.provide(Layer.merge(projectionLayer, sessionManagerLayer)),
267 );
268​
269 const [ordinaryInterrupt, unrelatedRestart] = yield* Effect.gen(function* () {
270 const control = yield* ProviderTurnControlServiceV2;
271 const ordinary = yield* Effect.exit(
272 control.interrupt({
273 threadId,
274 providerSessionId: oldSessionId,
275 providerThreadId,
276 providerTurnId,
277 }),
278 );
279 const unrelated = yield* Effect.exit(
280 control.interruptAndAwaitTerminal({
281 threadId,
282 providerSessionId: oldSessionId,
283 replacementProviderSessionId: unrelatedSessionId,
284 providerThreadId,
285 providerTurnId,
286 interruptedAttemptId: attemptId,
287 }),
288 );
289 return [ordinary, unrelated] as const;
290 }).pipe(Effect.provide(controlLayer));
291​
292 assert.isTrue(Exit.isFailure(ordinaryInterrupt));
293 assert.isTrue(Exit.isFailure(unrelatedRestart));
294 assert.isNull(yield* Ref.get(interruptedThread));
295​
296 yield* Effect.gen(function* () {
297 const control = yield* ProviderTurnControlServiceV2;
298 yield* control.interruptAndAwaitTerminal({
299 threadId,
300 providerSessionId: oldSessionId,
301 replacementProviderSessionId: replacementSessionId,
302 providerThreadId,
303 providerTurnId,
304 interruptedAttemptId: attemptId,
305 });
306 }).pipe(Effect.provide(controlLayer));
307​
308 const interrupted = yield* Ref.get(interruptedThread);
309 assert.isNotNull(interrupted);
310 assert.equal(interrupted?.providerSessionId, oldSessionId);
311 assert.equal(interrupted?.id, providerThreadId);
312 assert.equal(interrupted?.nativeThreadRef?.nativeId, "native-thread:restart-session");
313 }),
314);