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

threadCommands.test.ts

373 lines15.0 KB

1import { describe, expect, it } from "@effect/vitest";
2import {
3 CommandId,
4 RuntimeRequestId,
5 EnvironmentId,
6 ORCHESTRATION_V2_WS_METHODS,
7 ProjectId,
8 ProviderInstanceId,
9 ThreadId,
10 type OrchestrationV2Command,
11 type OrchestrationV2ShellSnapshot,
12} from "@t3tools/contracts";
13import * as DateTime from "effect/DateTime";
14import * as Crypto from "effect/Crypto";
15import * as Deferred from "effect/Deferred";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Queue from "effect/Queue";
20import * as SubscriptionRef from "effect/SubscriptionRef";
21import { Atom, AtomRegistry } from "effect/unstable/reactivity";
22​
23import { EnvironmentRegistry } from "../connection/registry.ts";
24import { EnvironmentSupervisor } from "../connection/supervisor.ts";
25import type { RpcSession } from "../rpc/session.ts";
26import { createThreadEnvironmentAtoms } from "./threadCommands.ts";
27​
28const ENVIRONMENT_ID = EnvironmentId.make("remote");
29const THREAD_ID = ThreadId.make("thread");
30const NOW = DateTime.makeUnsafe("2026-09-12T10:00:00.000Z");
31const FUTURE = DateTime.makeUnsafe("2099-01-01T00:00:00.000Z");
32const APPROVAL = {
33 id: RuntimeRequestId.make("approval"),
34 kind: "command" as const,
35 createdAt: NOW,
36};
37const USER_INPUT = {
38 id: RuntimeRequestId.make("input"),
39 kind: "user_input" as const,
40 createdAt: NOW,
41};
42const SNAPSHOT: OrchestrationV2ShellSnapshot = {
43 snapshotSequence: 1,
44 schemaVersion: 2,
45 archivedThreads: [],
46 projects: [],
47 threads: [
48 {
49 id: THREAD_ID,
50 projectId: ProjectId.make("project"),
51 title: "Remote thread",
52 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
53 runtimeMode: "full-access",
54 interactionMode: "default",
55 branch: null,
56 worktreePath: null,
57 createdBy: "user",
58 creationSource: "web",
59 providerInstanceId: ProviderInstanceId.make("codex"),
60 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
61 forkedFrom: null,
62 activeProviderThreadId: null,
63 latestRunId: null,
64 activeRunId: null,
65 status: "idle",
66 pendingRuntimeRequest: null,
67 latestVisibleMessage: null,
68 itemCount: 0,
69 visibleItemCount: 0,
70 deletedAt: null,
71 createdAt: NOW,
72 updatedAt: NOW,
73 archivedAt: null,
74 settledOverride: null,
75 settledAt: null,
76 pullRequests: [],
77 latestUserMessageAt: null,
78 hasActionableProposedPlan: false,
79 },
80 ],
81};
82​
83const makeHarness = Effect.fn("TestThreadCommands.makeHarness")(function* () {
84 const requests = yield* Queue.unbounded<{
85 command: OrchestrationV2Command;
86 reply: Deferred.Deferred<{ sequence: number }, Error>;
87 }>();
88 const supervisor = EnvironmentSupervisor.of({
89 target: { environmentId: ENVIRONMENT_ID },
90 session: yield* SubscriptionRef.make(
91 Option.some({
92 client: {
93 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
94 Effect.gen(function* () {
95 const reply = yield* Deferred.make<{ sequence: number }, Error>();
96 yield* Queue.offer(requests, { command, reply });
97 return yield* Deferred.await(reply);
98 }),
99 },
100 } as unknown as RpcSession),
101 ),
102 } as EnvironmentSupervisor["Service"]);
103 const runtime = Atom.runtime(
104 Layer.mergeAll(
105 Layer.succeed(EnvironmentRegistry, {
106 run: (_environmentId, effect) =>
107 Effect.provideService(effect, EnvironmentSupervisor, supervisor),
108 } as EnvironmentRegistry["Service"]),
109 Layer.succeed(
110 Crypto.Crypto,
111 Crypto.make({
112 randomBytes: (size) => new Uint8Array(size),
113 digest: (_algorithm, data) => Effect.succeed(data),
114 }),
115 ),
116 ),
117 );
118 const snapshotAtom = Atom.family((_environmentId: EnvironmentId) => Atom.make(SNAPSHOT));
119 const commands = createThreadEnvironmentAtoms(runtime, snapshotAtom);
120 const registry = AtomRegistry.make();
121 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
122 const visibleAtom = commands.snapshotAtom(ENVIRONMENT_ID);
123 registry.mount(visibleAtom);
124 return { registry, commands, snapshotAtom, visibleAtom, requests };
125});
126​
127describe("remote thread lifecycle commands", () => {
128 const actions = [
129 ["settle", {}, { settledOverride: "settled", pinnedAt: null, snoozedUntil: null }],
130 ["unsettle", { reason: "user" }, { settledOverride: "active", settledAt: null }],
131 ["snooze", { snoozedUntil: "2099-01-01T00:00:00.000Z" }, { snoozedUntil: FUTURE }],
132 ["unsnooze", { reason: "user" }, { snoozedUntil: null, snoozedAt: null }],
133 ["pin", { orderKey: "a" }, { pinnedAt: expect.any(Object), pinOrderKey: "a" }],
134 ["unpin", {}, { pinnedAt: null, pinOrderKey: null }],
135 ["reorderPin", { orderKey: "b" }, { pinOrderKey: "b" }],
136 ["reorderActive", { orderKey: "b" }, { activeOrderKey: "b" }],
137 ] as const;
138​
139 for (const [action, input, expected] of actions) {
140 it.effect(`shows ${action} before a delayed remote reply and rolls back a rejection`, () =>
141 Effect.gen(function* () {
142 const h = yield* makeHarness();
143 const source = h.snapshotAtom(ENVIRONMENT_ID);
144 const initial = {
145 ...SNAPSHOT,
146 threads: [
147 {
148 ...SNAPSHOT.threads[0]!,
149 ...(action === "unsettle" || action === "pin"
150 ? { settledOverride: "settled" as const, settledAt: NOW }
151 : {}),
152 ...(action === "unsnooze" || action === "settle" || action === "pin"
153 ? { snoozedUntil: FUTURE, snoozedAt: NOW }
154 : {}),
155 ...(action === "unpin" || action === "settle"
156 ? { pinnedAt: NOW, pinOrderKey: "a" }
157 : {}),
158 },
159 ],
160 };
161 h.registry.set(source, initial);
162 const result = h.commands[action].run(h.registry, {
163 environmentId: ENVIRONMENT_ID,
164 input: {
165 threadId: THREAD_ID,
166 commandId: CommandId.make(action),
167 reason: "user",
168 orderKey: "a",
169 snoozedUntil: "2099-01-01T00:00:00.000Z",
170 ...input,
171 },
172 });
173 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(expected);
174 const request = yield* Queue.take(h.requests);
175 expect(h.registry.get(source)).toBe(initial);
176 yield* Deferred.fail(request.reply, new Error("Remote rejected the action"));
177 expect((yield* Effect.promise(() => result))._tag).toBe("Failure");
178 expect(h.registry.get(h.visibleAtom)).toBe(initial);
179 }),
180 );
181 }
182​
183 it.effect("keeps the preview after acknowledgement until the matching shell update arrives", () =>
184 Effect.gen(function* () {
185 const h = yield* makeHarness();
186 const result = h.commands.settle.run(h.registry, {
187 environmentId: ENVIRONMENT_ID,
188 input: { threadId: THREAD_ID },
189 });
190 const request = yield* Queue.take(h.requests);
191 yield* Deferred.succeed(request.reply, { sequence: 3 });
192 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
193 const changed = {
194 ...SNAPSHOT,
195 snapshotSequence: 2,
196 threads: [{ ...SNAPSHOT.threads[0]!, title: "Renamed remotely" }],
197 };
198 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), changed);
199 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject({
200 title: "Renamed remotely",
201 settledOverride: "settled",
202 });
203 const confirmed = {
204 ...changed,
205 snapshotSequence: 3,
206 threads: [
207 {
208 ...changed.threads[0]!,
209 settledOverride: "settled" as const,
210 settledAt: DateTime.makeUnsafe("2026-09-12T12:00:00.000Z"),
211 },
212 ],
213 };
214 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
215 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
216 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), { ...SNAPSHOT, snapshotSequence: 4 });
217 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBeNull();
218 }),
219 );
220​
221 it.effect(
222 "shows a queued reverse action immediately and preserves it if the earlier action fails",
223 () =>
224 Effect.gen(function* () {
225 const h = yield* makeHarness();
226 const settle = h.commands.settle.run(h.registry, {
227 environmentId: ENVIRONMENT_ID,
228 input: { threadId: THREAD_ID },
229 });
230 const first = yield* Queue.take(h.requests);
231 const unsettle = h.commands.unsettle.run(h.registry, {
232 environmentId: ENVIRONMENT_ID,
233 input: { threadId: THREAD_ID, reason: "user" },
234 });
235 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("active");
236 yield* Deferred.fail(first.reply, new Error("Settle rejected"));
237 yield* Effect.promise(() => settle);
238 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("active");
239 const second = yield* Queue.take(h.requests);
240 expect(second.command.type).toBe("thread.unsettle");
241 const confirmed = {
242 ...SNAPSHOT,
243 snapshotSequence: 2,
244 threads: [{ ...SNAPSHOT.threads[0]!, settledOverride: "active" as const }],
245 };
246 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
247 yield* Deferred.succeed(second.reply, { sequence: 2 });
248 yield* Effect.promise(() => unsettle);
249 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
250 }),
251 );
252​
253 it.effect("isolates environments and does not restore a remotely removed thread", () =>
254 Effect.gen(function* () {
255 const h = yield* makeHarness();
256 const otherEnvironment = EnvironmentId.make("other-remote");
257 const result = h.commands.settle.run(h.registry, {
258 environmentId: ENVIRONMENT_ID,
259 input: { threadId: THREAD_ID },
260 });
261 const request = yield* Queue.take(h.requests);
262 expect(h.registry.get(h.commands.snapshotAtom(otherEnvironment))).toBe(SNAPSHOT);
263 const removed = { ...SNAPSHOT, snapshotSequence: 2, threads: [] };
264 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), removed);
265 expect(h.registry.get(h.visibleAtom)?.threads).toEqual([]);
266 yield* Deferred.fail(request.reply, new Error("Thread removed"));
267 yield* Effect.promise(() => result);
268 expect(h.registry.get(h.visibleAtom)).toBe(removed);
269 }),
270 );
271​
272 it.effect("keeps pending approvals visible while a lifecycle request is pending", () =>
273 Effect.gen(function* () {
274 const h = yield* makeHarness();
275 const blocked = {
276 ...SNAPSHOT,
277 threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: APPROVAL }],
278 };
279 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), blocked);
280 const result = h.commands.settle.run(h.registry, {
281 environmentId: ENVIRONMENT_ID,
282 input: { threadId: THREAD_ID },
283 });
284 const request = yield* Queue.take(h.requests);
285 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(blocked.threads[0]);
286 yield* Deferred.fail(request.reply, new Error("Approval pending"));
287 yield* Effect.promise(() => result);
288 }),
289 );
290​
291 for (const action of ["settle", "snooze"] as const) {
292 it.effect(`restores a confirmed ${action} when a queued undo fails`, () =>
293 Effect.gen(function* () {
294 const h = yield* makeHarness();
295 const parked =
296 action === "settle" ? { settledOverride: "settled" as const } : { snoozedUntil: FUTURE };
297 const awake = action === "settle" ? { settledOverride: "active" } : { snoozedUntil: null };
298 const result = h.commands[action].run(h.registry, {
299 environmentId: ENVIRONMENT_ID,
300 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
301 });
302 const first = yield* Queue.take(h.requests);
303 const undo = h.commands[action === "settle" ? "unsettle" : "unsnooze"].run(h.registry, {
304 environmentId: ENVIRONMENT_ID,
305 input: { threadId: THREAD_ID, reason: "user" },
306 });
307 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
308 yield* Deferred.succeed(first.reply, { sequence: 2 });
309 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
310 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
311 const confirmed = {
312 ...SNAPSHOT,
313 snapshotSequence: 2,
314 threads: [{ ...SNAPSHOT.threads[0]!, ...parked }],
315 };
316 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
317 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
318 const second = yield* Queue.take(h.requests);
319 expect(second.command.type).toBe(
320 action === "settle" ? "thread.unsettle" : "thread.unsnooze",
321 );
322 yield* Deferred.fail(second.reply, new Error("Undo rejected"));
323 expect((yield* Effect.promise(() => undo))._tag).toBe("Failure");
324 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
325 }),
326 );
327​
328 it.effect(`preserves a newer approval when the ${action} reply arrives after the shell`, () =>
329 Effect.gen(function* () {
330 const h = yield* makeHarness();
331 const result = h.commands[action].run(h.registry, {
332 environmentId: ENVIRONMENT_ID,
333 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
334 });
335 const request = yield* Queue.take(h.requests);
336 const newer = {
337 ...SNAPSHOT,
338 snapshotSequence: 3,
339 threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: APPROVAL }],
340 };
341 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), newer);
342 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(newer.threads[0]);
343 yield* Deferred.succeed(request.reply, { sequence: 2 });
344 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
345 expect(h.registry.get(h.visibleAtom)).toBe(newer);
346 }),
347 );
348​
349 it.effect(`shows an accepted ${action} while the shell still has an old input request`, () =>
350 Effect.gen(function* () {
351 const h = yield* makeHarness();
352 const stale = {
353 ...SNAPSHOT,
354 threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: USER_INPUT }],
355 };
356 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), stale);
357 const result = h.commands[action].run(h.registry, {
358 environmentId: ENVIRONMENT_ID,
359 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
360 });
361 const request = yield* Queue.take(h.requests);
362 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(stale.threads[0]);
363 yield* Deferred.succeed(request.reply, { sequence: 2 });
364 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
365 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(
366 action === "settle" ? { settledOverride: "settled" } : { snoozedUntil: FUTURE },
367 );
368 expect(h.registry.get(h.visibleAtom)?.threads[0]?.pendingRuntimeRequest).toBeNull();
369 expect(h.registry.get(h.snapshotAtom(ENVIRONMENT_ID))).toBe(stale);
370 }),
371 );
372 }
373});