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