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

threadCommands.test.ts

377 lines15.2 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/reactivity";
22​
23import * as EnvironmentRegistry from "../connection/registry.ts";
24import * as 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.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.EnvironmentSupervisor["Service"]);
103 const runtime = Atom.runtime(
104 Layer.mergeAll(
105 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, {
106 run: (_environmentId, effect) =>
107 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
108 } as EnvironmentRegistry.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 ["setAutoSettle", { enabled: false }, { autoSettleDisabledAt: expect.any(Object) }],
136 ["reorderPin", { orderKey: "b" }, { pinOrderKey: "b" }],
137 ["reorderActive", { orderKey: "b" }, { activeOrderKey: "b" }],
138 ] as const;
139​
140 it.effect.each(actions)(
141 "shows %s before a delayed remote reply and rolls back a rejection",
142 ([action, input, expected]) =>
143 Effect.gen(function* () {
144 const h = yield* makeHarness();
145 const source = h.snapshotAtom(ENVIRONMENT_ID);
146 const initial = {
147 ...SNAPSHOT,
148 threads: [
149 {
150 ...SNAPSHOT.threads[0]!,
151 ...(action === "unsettle" || action === "pin"
152 ? { settledOverride: "settled" as const, settledAt: NOW }
153 : {}),
154 ...(action === "unsnooze" || action === "settle" || action === "pin"
155 ? { snoozedUntil: FUTURE, snoozedAt: NOW }
156 : {}),
157 ...(action === "unpin" || action === "settle"
158 ? { pinnedAt: NOW, pinOrderKey: "a" }
159 : {}),
160 },
161 ],
162 };
163 h.registry.set(source, initial);
164 const result = h.commands[action].run(h.registry, {
165 environmentId: ENVIRONMENT_ID,
166 input: {
167 threadId: THREAD_ID,
168 commandId: CommandId.make(action),
169 reason: "user",
170 enabled: false,
171 orderKey: "a",
172 snoozedUntil: "2099-01-01T00:00:00.000Z",
173 ...input,
174 },
175 });
176 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(expected);
177 const request = yield* Queue.take(h.requests);
178 expect(h.registry.get(source)).toBe(initial);
179 yield* Deferred.fail(request.reply, new Error("Remote rejected the action"));
180 expect((yield* Effect.promise(() => result))._tag).toBe("Failure");
181 expect(h.registry.get(h.visibleAtom)).toBe(initial);
182 }),
183 );
184​
185 it.effect("keeps the preview after acknowledgement until the matching shell update arrives", () =>
186 Effect.gen(function* () {
187 const h = yield* makeHarness();
188 const result = h.commands.settle.run(h.registry, {
189 environmentId: ENVIRONMENT_ID,
190 input: { threadId: THREAD_ID },
191 });
192 const request = yield* Queue.take(h.requests);
193 yield* Deferred.succeed(request.reply, { sequence: 3 });
194 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
195 const changed = {
196 ...SNAPSHOT,
197 snapshotSequence: 2,
198 threads: [{ ...SNAPSHOT.threads[0]!, title: "Renamed remotely" }],
199 };
200 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), changed);
201 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject({
202 title: "Renamed remotely",
203 settledOverride: "settled",
204 });
205 const confirmed = {
206 ...changed,
207 snapshotSequence: 3,
208 threads: [
209 {
210 ...changed.threads[0]!,
211 settledOverride: "settled" as const,
212 settledAt: DateTime.makeUnsafe("2026-09-12T12:00:00.000Z"),
213 },
214 ],
215 };
216 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
217 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
218 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), { ...SNAPSHOT, snapshotSequence: 4 });
219 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBeNull();
220 }),
221 );
222​
223 it.effect(
224 "shows a queued reverse action immediately and preserves it if the earlier action fails",
225 () =>
226 Effect.gen(function* () {
227 const h = yield* makeHarness();
228 const settle = h.commands.settle.run(h.registry, {
229 environmentId: ENVIRONMENT_ID,
230 input: { threadId: THREAD_ID },
231 });
232 const first = yield* Queue.take(h.requests);
233 const unsettle = h.commands.unsettle.run(h.registry, {
234 environmentId: ENVIRONMENT_ID,
235 input: { threadId: THREAD_ID, reason: "user" },
236 });
237 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("active");
238 yield* Deferred.fail(first.reply, new Error("Settle rejected"));
239 yield* Effect.promise(() => settle);
240 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("active");
241 const second = yield* Queue.take(h.requests);
242 expect(second.command.type).toBe("thread.unsettle");
243 const confirmed = {
244 ...SNAPSHOT,
245 snapshotSequence: 2,
246 threads: [{ ...SNAPSHOT.threads[0]!, settledOverride: "active" as const }],
247 };
248 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
249 yield* Deferred.succeed(second.reply, { sequence: 2 });
250 yield* Effect.promise(() => unsettle);
251 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
252 }),
253 );
254​
255 it.effect("isolates environments and does not restore a remotely removed thread", () =>
256 Effect.gen(function* () {
257 const h = yield* makeHarness();
258 const otherEnvironment = EnvironmentId.make("other-remote");
259 const result = h.commands.settle.run(h.registry, {
260 environmentId: ENVIRONMENT_ID,
261 input: { threadId: THREAD_ID },
262 });
263 const request = yield* Queue.take(h.requests);
264 expect(h.registry.get(h.commands.snapshotAtom(otherEnvironment))).toBe(SNAPSHOT);
265 const removed = { ...SNAPSHOT, snapshotSequence: 2, threads: [] };
266 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), removed);
267 expect(h.registry.get(h.visibleAtom)?.threads).toEqual([]);
268 yield* Deferred.fail(request.reply, new Error("Thread removed"));
269 yield* Effect.promise(() => result);
270 expect(h.registry.get(h.visibleAtom)).toBe(removed);
271 }),
272 );
273​
274 it.effect("keeps pending approvals visible while a lifecycle request is pending", () =>
275 Effect.gen(function* () {
276 const h = yield* makeHarness();
277 const blocked = {
278 ...SNAPSHOT,
279 threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: APPROVAL }],
280 };
281 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), blocked);
282 const result = h.commands.settle.run(h.registry, {
283 environmentId: ENVIRONMENT_ID,
284 input: { threadId: THREAD_ID },
285 });
286 const request = yield* Queue.take(h.requests);
287 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(blocked.threads[0]);
288 yield* Deferred.fail(request.reply, new Error("Approval pending"));
289 yield* Effect.promise(() => result);
290 }),
291 );
292​
293 const undoableActions = ["settle", "snooze"] as const;
294​
295 it.effect.each(undoableActions)("restores a confirmed %s when a queued undo fails", (action) =>
296 Effect.gen(function* () {
297 const h = yield* makeHarness();
298 const parked =
299 action === "settle" ? { settledOverride: "settled" as const } : { snoozedUntil: FUTURE };
300 const awake = action === "settle" ? { settledOverride: "active" } : { snoozedUntil: null };
301 const result = h.commands[action].run(h.registry, {
302 environmentId: ENVIRONMENT_ID,
303 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
304 });
305 const first = yield* Queue.take(h.requests);
306 const undo = h.commands[action === "settle" ? "unsettle" : "unsnooze"].run(h.registry, {
307 environmentId: ENVIRONMENT_ID,
308 input: { threadId: THREAD_ID, reason: "user" },
309 });
310 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
311 yield* Deferred.succeed(first.reply, { sequence: 2 });
312 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
313 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
314 const confirmed = {
315 ...SNAPSHOT,
316 snapshotSequence: 2,
317 threads: [{ ...SNAPSHOT.threads[0]!, ...parked }],
318 };
319 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
320 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
321 const second = yield* Queue.take(h.requests);
322 expect(second.command.type).toBe(action === "settle" ? "thread.unsettle" : "thread.unsnooze");
323 yield* Deferred.fail(second.reply, new Error("Undo rejected"));
324 expect((yield* Effect.promise(() => undo))._tag).toBe("Failure");
325 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
326 }),
327 );
328​
329 it.effect.each(undoableActions)(
330 "preserves a newer approval when the %s reply arrives after the shell",
331 (action) =>
332 Effect.gen(function* () {
333 const h = yield* makeHarness();
334 const result = h.commands[action].run(h.registry, {
335 environmentId: ENVIRONMENT_ID,
336 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
337 });
338 const request = yield* Queue.take(h.requests);
339 const newer = {
340 ...SNAPSHOT,
341 snapshotSequence: 3,
342 threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: APPROVAL }],
343 };
344 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), newer);
345 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(newer.threads[0]);
346 yield* Deferred.succeed(request.reply, { sequence: 2 });
347 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
348 expect(h.registry.get(h.visibleAtom)).toBe(newer);
349 }),
350 );
351​
352 it.effect.each(undoableActions)(
353 "shows an accepted %s while the shell still has an old input request",
354 (action) =>
355 Effect.gen(function* () {
356 const h = yield* makeHarness();
357 const stale = {
358 ...SNAPSHOT,
359 threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: USER_INPUT }],
360 };
361 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), stale);
362 const result = h.commands[action].run(h.registry, {
363 environmentId: ENVIRONMENT_ID,
364 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
365 });
366 const request = yield* Queue.take(h.requests);
367 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(stale.threads[0]);
368 yield* Deferred.succeed(request.reply, { sequence: 2 });
369 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
370 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(
371 action === "settle" ? { settledOverride: "settled" } : { snoozedUntil: FUTURE },
372 );
373 expect(h.registry.get(h.visibleAtom)?.threads[0]?.pendingRuntimeRequest).toBeNull();
374 expect(h.registry.get(h.snapshotAtom(ENVIRONMENT_ID))).toBe(stale);
375 }),
376 );
377});