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

threadCommands.test.ts

399 lines16.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("restamps snoozedAt when re-snoozing to the same wake time", () =>
186 Effect.gen(function* () {
187 const h = yield* makeHarness();
188 const earlierSnoozedAt = DateTime.makeUnsafe("2000-01-01T00:00:00.000Z");
189 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), {
190 ...SNAPSHOT,
191 threads: [{ ...SNAPSHOT.threads[0]!, snoozedUntil: FUTURE, snoozedAt: earlierSnoozedAt }],
192 });
193 const result = h.commands.snooze.run(h.registry, {
194 environmentId: ENVIRONMENT_ID,
195 input: { threadId: THREAD_ID, snoozedUntil: DateTime.formatIso(FUTURE) },
196 });
197 const snoozedAt = h.registry.get(h.visibleAtom)?.threads[0]?.snoozedAt;
198 expect(DateTime.toEpochMillis(snoozedAt!)).toBeGreaterThan(
199 DateTime.toEpochMillis(earlierSnoozedAt),
200 );
201 const request = yield* Queue.take(h.requests);
202 yield* Deferred.succeed(request.reply, { sequence: 2 });
203 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
204 }),
205 );
206​
207 it.effect("keeps the preview after acknowledgement until the matching shell update arrives", () =>
208 Effect.gen(function* () {
209 const h = yield* makeHarness();
210 const result = h.commands.settle.run(h.registry, {
211 environmentId: ENVIRONMENT_ID,
212 input: { threadId: THREAD_ID },
213 });
214 const request = yield* Queue.take(h.requests);
215 yield* Deferred.succeed(request.reply, { sequence: 3 });
216 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
217 const changed = {
218 ...SNAPSHOT,
219 snapshotSequence: 2,
220 threads: [{ ...SNAPSHOT.threads[0]!, title: "Renamed remotely" }],
221 };
222 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), changed);
223 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject({
224 title: "Renamed remotely",
225 settledOverride: "settled",
226 });
227 const confirmed = {
228 ...changed,
229 snapshotSequence: 3,
230 threads: [
231 {
232 ...changed.threads[0]!,
233 settledOverride: "settled" as const,
234 settledAt: DateTime.makeUnsafe("2026-09-12T12:00:00.000Z"),
235 },
236 ],
237 };
238 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
239 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
240 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), { ...SNAPSHOT, snapshotSequence: 4 });
241 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBeNull();
242 }),
243 );
244​
245 it.effect(
246 "shows a queued reverse action immediately and preserves it if the earlier action fails",
247 () =>
248 Effect.gen(function* () {
249 const h = yield* makeHarness();
250 const settle = h.commands.settle.run(h.registry, {
251 environmentId: ENVIRONMENT_ID,
252 input: { threadId: THREAD_ID },
253 });
254 const first = yield* Queue.take(h.requests);
255 const unsettle = h.commands.unsettle.run(h.registry, {
256 environmentId: ENVIRONMENT_ID,
257 input: { threadId: THREAD_ID, reason: "user" },
258 });
259 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("active");
260 yield* Deferred.fail(first.reply, new Error("Settle rejected"));
261 yield* Effect.promise(() => settle);
262 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("active");
263 const second = yield* Queue.take(h.requests);
264 expect(second.command.type).toBe("thread.unsettle");
265 const confirmed = {
266 ...SNAPSHOT,
267 snapshotSequence: 2,
268 threads: [{ ...SNAPSHOT.threads[0]!, settledOverride: "active" as const }],
269 };
270 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
271 yield* Deferred.succeed(second.reply, { sequence: 2 });
272 yield* Effect.promise(() => unsettle);
273 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
274 }),
275 );
276​
277 it.effect("isolates environments and does not restore a remotely removed thread", () =>
278 Effect.gen(function* () {
279 const h = yield* makeHarness();
280 const otherEnvironment = EnvironmentId.make("other-remote");
281 const result = h.commands.settle.run(h.registry, {
282 environmentId: ENVIRONMENT_ID,
283 input: { threadId: THREAD_ID },
284 });
285 const request = yield* Queue.take(h.requests);
286 expect(h.registry.get(h.commands.snapshotAtom(otherEnvironment))).toBe(SNAPSHOT);
287 const removed = { ...SNAPSHOT, snapshotSequence: 2, threads: [] };
288 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), removed);
289 expect(h.registry.get(h.visibleAtom)?.threads).toEqual([]);
290 yield* Deferred.fail(request.reply, new Error("Thread removed"));
291 yield* Effect.promise(() => result);
292 expect(h.registry.get(h.visibleAtom)).toBe(removed);
293 }),
294 );
295​
296 it.effect("keeps pending approvals visible while a lifecycle request is pending", () =>
297 Effect.gen(function* () {
298 const h = yield* makeHarness();
299 const blocked = {
300 ...SNAPSHOT,
301 threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: APPROVAL }],
302 };
303 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), blocked);
304 const result = h.commands.settle.run(h.registry, {
305 environmentId: ENVIRONMENT_ID,
306 input: { threadId: THREAD_ID },
307 });
308 const request = yield* Queue.take(h.requests);
309 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(blocked.threads[0]);
310 yield* Deferred.fail(request.reply, new Error("Approval pending"));
311 yield* Effect.promise(() => result);
312 }),
313 );
314​
315 const undoableActions = ["settle", "snooze"] as const;
316​
317 it.effect.each(undoableActions)("restores a confirmed %s when a queued undo fails", (action) =>
318 Effect.gen(function* () {
319 const h = yield* makeHarness();
320 const parked =
321 action === "settle" ? { settledOverride: "settled" as const } : { snoozedUntil: FUTURE };
322 const awake = action === "settle" ? { settledOverride: "active" } : { snoozedUntil: null };
323 const result = h.commands[action].run(h.registry, {
324 environmentId: ENVIRONMENT_ID,
325 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
326 });
327 const first = yield* Queue.take(h.requests);
328 const undo = h.commands[action === "settle" ? "unsettle" : "unsnooze"].run(h.registry, {
329 environmentId: ENVIRONMENT_ID,
330 input: { threadId: THREAD_ID, reason: "user" },
331 });
332 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
333 yield* Deferred.succeed(first.reply, { sequence: 2 });
334 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
335 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
336 const confirmed = {
337 ...SNAPSHOT,
338 snapshotSequence: 2,
339 threads: [{ ...SNAPSHOT.threads[0]!, ...parked }],
340 };
341 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
342 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
343 const second = yield* Queue.take(h.requests);
344 expect(second.command.type).toBe(action === "settle" ? "thread.unsettle" : "thread.unsnooze");
345 yield* Deferred.fail(second.reply, new Error("Undo rejected"));
346 expect((yield* Effect.promise(() => undo))._tag).toBe("Failure");
347 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
348 }),
349 );
350​
351 it.effect.each(undoableActions)(
352 "preserves a newer approval when the %s reply arrives after the shell",
353 (action) =>
354 Effect.gen(function* () {
355 const h = yield* makeHarness();
356 const result = h.commands[action].run(h.registry, {
357 environmentId: ENVIRONMENT_ID,
358 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
359 });
360 const request = yield* Queue.take(h.requests);
361 const newer = {
362 ...SNAPSHOT,
363 snapshotSequence: 3,
364 threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: APPROVAL }],
365 };
366 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), newer);
367 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(newer.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)).toBe(newer);
371 }),
372 );
373​
374 it.effect.each(undoableActions)(
375 "shows an accepted %s while the shell still has an old input request",
376 (action) =>
377 Effect.gen(function* () {
378 const h = yield* makeHarness();
379 const stale = {
380 ...SNAPSHOT,
381 threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: USER_INPUT }],
382 };
383 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), stale);
384 const result = h.commands[action].run(h.registry, {
385 environmentId: ENVIRONMENT_ID,
386 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
387 });
388 const request = yield* Queue.take(h.requests);
389 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(stale.threads[0]);
390 yield* Deferred.succeed(request.reply, { sequence: 2 });
391 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
392 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(
393 action === "settle" ? { settledOverride: "settled" } : { snoozedUntil: FUTURE },
394 );
395 expect(h.registry.get(h.visibleAtom)?.threads[0]?.pendingRuntimeRequest).toBeNull();
396 expect(h.registry.get(h.snapshotAtom(ENVIRONMENT_ID))).toBe(stale);
397 }),
398 );
399});