Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import {
4 CheckpointId,
5 NodeId,
6 ProviderInstanceId,
7 ProviderSessionId,
8 ProviderTurnId,
9 ThreadId,
10 type OrchestrationV2ProviderTurn,
11} from "@t3tools/contracts";
12import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
13import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
14import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
15import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
16import * as DateTime from "effect/DateTime";
17import * as Deferred from "effect/Deferred";
18import * as Effect from "effect/Effect";
19import * as Fiber from "effect/Fiber";
20import * as FileSystem from "effect/FileSystem";
21import * as Layer from "effect/Layer";
22import * as Queue from "effect/Queue";
23import * as Schema from "effect/Schema";
24import * as Sink from "effect/Sink";
25import * as Stream from "effect/Stream";
26import * as TestClock from "effect/testing/TestClock";
27import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
28import { makePiAdapterV2, PI_PROVIDER } from "./adapter.ts";
29
30const layerTest = Layer.mergeAll(
31 NodeServices.layer,
32 IdAllocator.layer,
33 McpProviderSessions.layer,
34 TestProviderHost.layer().pipe(Layer.provide(NodeServices.layer)),
35);
36
37const time = (seconds: number) => DateTime.makeUnsafe(seconds * 1000);
38const entry = (
39 id: string,
40 parentId: string | null,
41 role: "user" | "assistant",
42 seconds: number,
43) => ({
44 type: "message",
45 id,
46 parentId,
47 timestamp: DateTime.formatIso(time(seconds)),
48 message: { role, content: [] },
49});
50const ref = (nativeId: string, strength: "strong" | "weak" = "strong") => ({
51 driver: PI_PROVIDER,
52 nativeId,
53 strength,
54});
55const decodeRequest = Schema.decodeUnknownSync(
56 Schema.fromJsonString(
57 Schema.Struct({
58 id: Schema.String,
59 type: Schema.String,
60 entryId: Schema.optional(Schema.String),
61 sessionPath: Schema.optional(Schema.String),
62 }),
63 ),
64);
65
66it.effect.each([
67 "earlier checkpoint",
68 "last checkpoint",
69 "uncaptured handoff",
70 "command-only handoff",
71 "legacy turns",
72 "checkpoint inherited by a prior fork",
73 "repeated rollback after a handoff",
74 "handoff prompt left in the source",
75 "a checkpoint recorded before upgrading, followed by a session switch",
76 "switch timed out after attaching",
77] as const)("restores exactly the retained Pi history for %s", (scenario) =>
78 Effect.gen(function* () {
79 const repro =
80 scenario === "a checkpoint recorded before upgrading, followed by a session switch";
81 const fs = yield* FileSystem.FileSystem;
82 const dir = yield* fs.makeTempDirectoryScoped();
83 const oldFile = `${dir}/old.jsonl`;
84 const currentFile = `${dir}/current.jsonl`;
85 const previousForkFile = `${dir}/previous-fork.jsonl`;
86 const forkedFile = `${dir}/forked.jsonl`;
87 const oldEntries = [
88 entry("u1", null, "user", 10),
89 entry("a1", "u1", "assistant", 15),
90 entry("u2", "a1", "user", 30),
91 entry("steer", "u2", "user", 33),
92 entry("a2", "steer", "assistant", 35),
93 ];
94 const inherited = scenario === "checkpoint inherited by a prior fork";
95 const handoffEntry = entry("u3", inherited ? "a2" : null, "user", 50);
96 const newEntries =
97 scenario === "command-only handoff"
98 ? []
99 : inherited
100 ? [...oldEntries, handoffEntry]
101 : [handoffEntry];
102 const repeated = scenario === "repeated rollback after a handoff";
103 const oldSuffix = repeated || scenario === "handoff prompt left in the source";
104 const sessions = new Map([
105 [oldFile, oldSuffix ? [...oldEntries, entry("discarded", "a2", "user", 45)] : oldEntries],
106 [currentFile, newEntries],
107 ]);
108 if (repeated) sessions.set(previousForkFile, [...oldEntries, entry("u3", "a2", "user", 50)]);
109 for (const [file, entries] of sessions) {
110 yield* fs.writeFileString(
111 file,
112 [{ type: "session", version: 3, cwd: process.cwd() }, ...entries]
113 .map((item) => JSON.stringify(item))
114 .join("\n") + "\n",
115 );
116 }
117
118 const output = yield* Queue.unbounded<Uint8Array>();
119 const switchApplied = yield* Deferred.make<void>();
120 const sessionRequests: { readonly type: string; readonly file: string }[] = [];
121 let liveFile = currentFile;
122 let pending = "";
123 const encoder = new TextEncoder();
124 const decoder = new TextDecoder();
125 const stdin = Sink.forEach((chunk: Uint8Array) =>
126 Effect.gen(function* () {
127 const lines = (pending + decoder.decode(chunk, { stream: true })).split("\n");
128 pending = lines.pop() ?? "";
129 for (const line of lines) {
130 const request = decodeRequest(line);
131 const entries = sessions.get(liveFile) ?? [];
132 let data: unknown = {};
133 let error: string | undefined;
134 if (request.type === "get_state") data = { sessionFile: liveFile };
135 if (request.type === "get_entries")
136 data = { entries, leafId: entries.at(-1)?.id ?? null };
137 if (request.type === "switch_session") {
138 if (request.sessionPath !== undefined && sessions.has(request.sessionPath)) {
139 liveFile = request.sessionPath;
140 sessionRequests.push({ type: "switch_session", file: liveFile });
141 if (scenario === "switch timed out after attaching") {
142 yield* Deferred.succeed(switchApplied, undefined);
143 continue;
144 }
145 data = { cancelled: false };
146 } else error = "Session not found";
147 }
148 if (request.type === "fork") {
149 const index = entries.findIndex(({ id }) => id === request.entryId);
150 if (index === -1) error = "Invalid entry ID for forking";
151 else {
152 sessionRequests.push({ type: "fork", file: liveFile });
153 sessions.set(forkedFile, entries.slice(0, index));
154 liveFile = forkedFile;
155 data = { cancelled: false };
156 }
157 }
158 yield* Queue.offer(
159 output,
160 encoder.encode(
161 JSON.stringify({
162 type: "response",
163 id: request.id,
164 command: request.type,
165 success: error === undefined,
166 data,
167 error,
168 }) + "\n",
169 ),
170 );
171 }
172 }),
173 );
174 const spawner = ChildProcessSpawner.make(() =>
175 Effect.succeed(
176 ChildProcessSpawner.makeHandle({
177 pid: ChildProcessSpawner.ProcessId(999_999_999),
178 exitCode: Effect.never,
179 isRunning: Effect.succeed(true),
180 kill: () => Effect.void,
181 unref: Effect.succeed(Effect.void),
182 stdin,
183 stdout: Stream.fromQueue(output),
184 stderr: Stream.empty,
185 all: Stream.empty,
186 getInputFd: () => Sink.drain,
187 getOutputFd: () => Stream.empty,
188 }),
189 ),
190 );
191 const instanceId = ProviderInstanceId.make("pi");
192 const adapter = yield* makePiAdapterV2({
193 instanceId,
194 settings: { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
195 environment: {},
196 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
197 const threadId = ThreadId.make("pi-rollback");
198 const modelSelection = { instanceId, model: "default" };
199 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
200 runtimeMode: "full-access",
201 interactionMode: "default",
202 cwd: process.cwd(),
203 });
204 const runtime = yield* adapter.openSession({
205 threadId,
206 providerSessionId: ProviderSessionId.make("pi-rollback"),
207 modelSelection,
208 runtimePolicy,
209 });
210 const events = yield* runtime.events.pipe(Stream.runDrain, Effect.result, Effect.forkScoped);
211 const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy });
212 const turns = (repeated ? [1, 2, 3, 4] : [1, 2, 3]).map(
213 (ordinal): OrchestrationV2ProviderTurn => ({
214 id: ProviderTurnId.make(`turn-${ordinal}`),
215 providerThreadId: providerThread.id,
216 nodeId: NodeId.make(`node-${ordinal}`),
217 runAttemptId: null,
218 nativeTurnRef:
219 ordinal === 3 && scenario === "command-only handoff"
220 ? null
221 : ordinal === 3 && (scenario === "uncaptured handoff" || repro)
222 ? ref("uncaptured", "weak")
223 : ref(`u${ordinal}`),
224 ...(scenario === "legacy turns" || (repro && ordinal < 3)
225 ? {}
226 : {
227 nativeThreadRef: ref(
228 ordinal < 3 ? oldFile : ordinal === 3 && repeated ? previousForkFile : currentFile,
229 ),
230 }),
231 ordinal,
232 status: "completed",
233 startedAt: time(ordinal * 20 - 10),
234 completedAt: time(ordinal * 20),
235 }),
236 );
237 const shouldFork = scenario === "earlier checkpoint" || scenario === "legacy turns";
238 const target = turns[shouldFork ? 0 : 1]!;
239 const rollback = runtime.rollbackThread({
240 providerThread,
241 target: {
242 type: "provider_turn",
243 checkpointId: CheckpointId.make("checkpoint"),
244 appRunOrdinal: target.ordinal,
245 providerTurn: target,
246 },
247 providerThreadTurns: turns,
248 });
249 if (scenario === "switch timed out after attaching") {
250 const attempt = yield* rollback.pipe(Effect.result, Effect.forkChild);
251 yield* Deferred.await(switchApplied);
252 assert.equal(liveFile, oldFile);
253 yield* TestClock.adjust("61 seconds");
254 assert.equal((yield* Fiber.join(attempt))._tag, "Failure");
255 yield* Fiber.join(events);
256 assert.include(["error", "stopped"], runtime.providerSession.status);
257 assert.deepEqual(sessionRequests, [{ type: "switch_session", file: oldFile }]);
258 return;
259 }
260 if (repro) {
261 const restored = yield* rollback.pipe(Effect.result);
262 assert.equal(restored._tag, "Success");
263 assert.deepEqual(
264 sessions.get(liveFile)?.map(({ id }) => id),
265 ["u1", "a1", "u2", "steer", "a2"],
266 );
267 return;
268 }
269 const restored = yield* rollback;
270 assert.equal(
271 restored.providerThread.nativeThreadRef?.nativeId,
272 shouldFork || inherited || oldSuffix ? forkedFile : oldFile,
273 );
274 assert.equal(
275 restored.providerThread.nativeConversationHeadRef?.nativeId,
276 shouldFork ? "a1" : "a2",
277 );
278 assert.deepEqual(
279 sessions.get(liveFile)?.map(({ id }) => id),
280 shouldFork ? ["u1", "a1"] : ["u1", "a1", "u2", "steer", "a2"],
281 );
282 assert.deepEqual(
283 sessionRequests,
284 inherited
285 ? [{ type: "fork", file: currentFile }]
286 : [
287 { type: "switch_session", file: repeated ? previousForkFile : oldFile },
288 ...(shouldFork || oldSuffix
289 ? [{ type: "fork", file: repeated ? previousForkFile : oldFile }]
290 : []),
291 ],
292 );
293 }).pipe(Effect.scoped, Effect.provide(layerTest)),
294);