Open History to see the last commit
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 };
126}
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 getLimitRecoveryCandidates: () => Effect.die("unused getLimitRecoveryCandidates"),
218 getShellSnapshot: () => Effect.die("unused getShellSnapshot"),
219 getThreadShell: () => Effect.die("unused getThreadShell"),
220 getThread: () => Ref.get(projection).pipe(Effect.map((state) => state.thread)),
221 getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"),
222 getThreadsWithPullRequests: () => Effect.die("unused getThreadsWithPullRequests"),
223 getThreadProjection: () => Effect.die("control effects must not load transcript"),
224 getTurnStartContext: () => Effect.die("unused"),
225 getTurnStartHistory: () => Effect.die("unused"),
226 getRuntimeRecoveryProjection: () => Effect.die("unused getRuntimeRecoveryProjection"),
227 getPlan: () => Effect.die("unused"),
228 hasUnpairedRunInterruptRequest: () => Effect.die("unused interrupt read"),
229 getThreadAttachmentIds: () => Effect.die("Unused attachment lookup"),
230 getTimelinePage: () => Effect.die("Unused timeline read"),
231 getMessageCount: () => Effect.die("unused message count"),
232 getNextTurnItemOrdinal: () => Effect.die("unused ordinal read"),
233 getThreadRecords: () => Effect.die("unused record read"),
234 getRuntimeRequest: () => Effect.die("unused getRuntimeRequest"),
235 getRunningTurnContext: () => Effect.die("unused getRunningTurnContext"),
236 getThreadProviderContext: () => Effect.die("unused getThreadProviderContext"),
237 getRuntimeResponseContext: () => Effect.die("unused getRuntimeResponseContext"),
238 getPendingNativeUserInputs: () => Effect.die("unused getPendingNativeUserInputs"),
239 getProviderControlContext: (_threadId, target) =>
240 Ref.get(projection).pipe(
241 Effect.map((current) => ({
242 providerThread: current.providerThreads.find(
243 (thread) => thread.id === target.providerThreadId,
244 ),
245 providerTurn: current.providerTurns.find(
246 (turn) => turn.id === target.providerTurnId,
247 ),
248 attempt: current.attempts.find((attempt) => attempt.id === target.attemptId),
249 message: undefined,
250 run: undefined,
251 })),
252 ),
253 getCheckpointContext: () => Effect.die("not used"),
254 getCheckpointCaptureContext: () => Effect.die("not used"),
255 getRunMessage: () => Effect.die("not used"),
256 canStartQueuedRun: () => Effect.die("not used"),
257 getRecoveryThreadIds: () => Effect.die("unused getRecoveryThreadIds"),
258 getUnreadableThreadIds: () => Effect.die("unused getUnreadableThreadIds"),
259 getThreadSnapshot: () => Effect.die("unused getThreadSnapshot"),
260 getThreadSnapshotWindow: () => Effect.die("unused getThreadSnapshotWindow"),
261 }),
262 );
263 const sessionManagerLayer = Layer.succeed(
264 ProviderSessionManagerV2,
265 ProviderSessionManagerV2.of({
266 shutdown: Effect.void,
267 open: () => Effect.die("unused open"),
268 get: (providerSessionId) =>
269 Effect.succeed(
270 providerSessionId === oldSessionId ? Option.some(runtime) : Option.none(),
271 ),
272 close: () => Effect.void,
273 closeInstance: () => Effect.void,
274 release: () => Effect.void,
275 detach: () => Effect.void,
276 }),
277 );
278 const controlLayer = providerTurnControlLayer.pipe(
279 Layer.provide(Layer.merge(projectionLayer, sessionManagerLayer)),
280 );
281
282 const [ordinaryInterrupt, unrelatedRestart] = yield* Effect.gen(function* () {
283 const control = yield* ProviderTurnControlServiceV2;
284 const ordinary = yield* Effect.exit(
285 control.interrupt({
286 threadId,
287 providerSessionId: oldSessionId,
288 providerThreadId,
289 providerTurnId,
290 }),
291 );
292 const unrelated = yield* Effect.exit(
293 control.interruptAndAwaitTerminal({
294 threadId,
295 providerSessionId: oldSessionId,
296 replacementProviderSessionId: unrelatedSessionId,
297 providerThreadId,
298 providerTurnId,
299 interruptedAttemptId: attemptId,
300 }),
301 );
302 return [ordinary, unrelated] as const;
303 }).pipe(Effect.provide(controlLayer));
304
305 assert.isTrue(Exit.isFailure(ordinaryInterrupt));
306 assert.isTrue(Exit.isFailure(unrelatedRestart));
307 assert.isNull(yield* Ref.get(interruptedThread));
308
309 yield* Effect.gen(function* () {
310 const control = yield* ProviderTurnControlServiceV2;
311 yield* control.interruptAndAwaitTerminal({
312 threadId,
313 providerSessionId: oldSessionId,
314 replacementProviderSessionId: replacementSessionId,
315 providerThreadId,
316 providerTurnId,
317 interruptedAttemptId: attemptId,
318 });
319 }).pipe(Effect.provide(controlLayer));
320
321 const interrupted = yield* Ref.get(interruptedThread);
322 assert.isNotNull(interrupted);
323 assert.equal(interrupted?.providerSessionId, oldSessionId);
324 assert.equal(interrupted?.id, providerThreadId);
325 assert.equal(interrupted?.nativeThreadRef?.nativeId, "native-thread:restart-session");
326 }),
327);