Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import { assert, it } from "@effect/vitest";
3import {
4 type CommandId,
5 EnvironmentId,
6 ProjectId,
7 ProviderInstanceId,
8 RunId,
9 ThreadId,
10 threadMoveMessageId,
11} from "@t3tools/contracts";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Ref from "effect/Ref";
15
16import * as SqlitePersistence from "../persistence/Sqlite.ts";
17import * as EventSink from "./EventSink.ts";
18import * as EventStore from "./EventStore.ts";
19import { OrchestratorDispatchError } from "./Orchestrator.ts";
20import * as ProjectionStore from "./ProjectionStore.ts";
21import * as ThreadImportService from "./ThreadImportService.ts";
22import * as ThreadManagement from "./ThreadManagementService.ts";
23
24// A thread handed off from another environment arrives with its conversation as run-less
25// imported history, which the orchestrator hands to the first run here. The run itself is
26// the orchestrator's; this covers what the import writes and that a retry writes nothing.
27
28const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" };
29const source = {
30 environmentId: EnvironmentId.make("environment:laptop"),
31 threadId: ThreadId.make("thread:on-the-laptop"),
32 handoffId: "handoff-1",
33};
34const history = [
35 {
36 role: "user" as const,
37 text: "Find why the login test flakes.",
38 createdAt: "2026-10-06T10:00:00.000Z",
39 },
40 {
41 role: "assistant" as const,
42 text: "The session cookie races the redirect.",
43 createdAt: "2026-10-06T10:01:00.000Z",
44 },
45];
46const request = {
47 source,
48 projectId: ProjectId.make("project:box"),
49 title: "Flaky login test",
50 modelSelection,
51 runtimeMode: "full-access" as const,
52 interactionMode: "default" as const,
53 linkOrigin: { sessionId: "session-laptop", label: "T3 Code · Laptop" },
54 messages: history,
55 continuationPrompt: "Carry on from where you stopped on the laptop.",
56};
57
58const stores = Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe(
59 Layer.provideMerge(SqlitePersistence.layerMemory),
60);
61
62const layerFor = (dispatched: Ref.Ref<ReadonlyArray<CommandId>>, rejectContinuation = false) =>
63 ThreadImportService.layer.pipe(
64 Layer.provide(
65 Layer.unwrap(
66 Effect.gen(function* () {
67 const projections = yield* ProjectionStore.ProjectionStoreV2;
68 return Layer.mock(ThreadManagement.ThreadManagementService)({
69 getThreadShell: (threadId) => projections.getThreadShell(threadId).pipe(Effect.orDie),
70 dispatch: (command) =>
71 Ref.update(dispatched, (seen) => [...seen, command.commandId]).pipe(
72 Effect.andThen(
73 rejectContinuation
74 ? Effect.fail(
75 new OrchestratorDispatchError({
76 commandId: command.commandId,
77 commandType: command.type,
78 cause: "The model is unavailable.",
79 }),
80 )
81 : Effect.succeed({} as never),
82 ),
83 ),
84 getThreadRecords: (threadId) =>
85 Effect.succeed({
86 runs: [
87 { id: RunId.make("run:continued"), userMessageId: threadMoveMessageId(threadId) },
88 { id: RunId.make("run:later"), userMessageId: "message:later" },
89 ],
90 } as never),
91 });
92 }),
93 ),
94 ),
95 Layer.provide(EventSink.layer),
96 Layer.provideMerge(stores),
97 Layer.provide(NodeCrypto.layer),
98 );
99
100it.effect("an import writes the conversation as imported history, once", () =>
101 Effect.gen(function* () {
102 const dispatched = yield* Ref.make<ReadonlyArray<CommandId>>([]);
103 yield* Effect.gen(function* () {
104 const imports = yield* ThreadImportService.ThreadImportService;
105 const projections = yield* ProjectionStore.ProjectionStoreV2;
106
107 const first = yield* imports.importThread(request);
108 assert.isTrue(first.created);
109 assert.equal(first.runId, RunId.make("run:continued"));
110 const projection = yield* projections.getThreadProjection(first.threadId);
111 assert.equal(projection.thread.historyOrigin, "v1_import");
112 assert.deepEqual(projection.thread.linkOrigin, request.linkOrigin);
113 assert.deepEqual(
114 projection.messages.map((message) => [message.role, message.text, message.runId]),
115 history.map((message) => [message.role, message.text, null]),
116 );
117
118 // A retry returns the same thread, writes nothing, and replays the same command.
119 const retried = yield* imports.importThread(request);
120 assert.deepEqual(retried, { ...first, created: false });
121 const after = yield* projections.getThreadProjection(first.threadId);
122 assert.equal(after.messages.length, history.length);
123 const commands = yield* Ref.get(dispatched);
124 assert.equal(commands.length, 2);
125 assert.equal(commands[0], commands[1]);
126
127 // Landing in another project is refused, not silently moved.
128 const moved = yield* imports
129 .importThread({ ...request, projectId: ProjectId.make("project:other") })
130 .pipe(Effect.flip);
131 assert.equal(moved._tag, "ThreadImportProjectMismatchError");
132
133 // Another link cannot continue a thread it did not move here.
134 const foreign = yield* imports
135 .importThread({
136 ...request,
137 linkOrigin: { sessionId: "session-other", label: "T3 Code · Other" },
138 })
139 .pipe(Effect.flip);
140 assert.equal(foreign._tag, "ThreadImportOtherLinkError");
141
142 // Another handoff of the same source thread is a new thread; without a prompt, no run.
143 const again = yield* imports.importThread({
144 ...request,
145 source: { ...source, handoffId: "handoff-2" },
146 continuationPrompt: undefined,
147 });
148 assert.notEqual(again.threadId, first.threadId);
149 assert.isNull(again.runId);
150 assert.equal((yield* Ref.get(dispatched)).length, 2);
151 }).pipe(Effect.provide(layerFor(dispatched)));
152 }),
153);
154
155it.effect("a continuation failure still confirms the imported thread", () =>
156 Effect.gen(function* () {
157 const dispatched = yield* Ref.make<ReadonlyArray<CommandId>>([]);
158 yield* Effect.gen(function* () {
159 const imports = yield* ThreadImportService.ThreadImportService;
160 const first = yield* imports.importThread(request);
161 assert.isTrue(first.created);
162 assert.isNull(first.runId);
163 const retried = yield* imports.importThread(request);
164 assert.deepEqual(retried, { ...first, created: false });
165 }).pipe(Effect.provide(layerFor(dispatched, true)));
166 }),
167);