Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import {
3 CommandId,
4 RuntimeRequestId,
5 EnvironmentId,
6 RunId,
7 ORCHESTRATION_V2_WS_METHODS,
8 ProjectId,
9 ProviderInstanceId,
10 ThreadId,
11 type OrchestrationV2Command,
12 type OrchestrationV2ShellSnapshot,
13} from "@t3tools/contracts";
14import * as DateTime from "effect/DateTime";
15import * as Crypto from "effect/Crypto";
16import * as Deferred from "effect/Deferred";
17import * as Effect from "effect/Effect";
18import * as Exit from "effect/Exit";
19import * as Fiber from "effect/Fiber";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Queue from "effect/Queue";
23import * as Scope from "effect/Scope";
24import * as SubscriptionRef from "effect/SubscriptionRef";
25import { Atom, AtomRegistry } from "effect/reactivity";
26
27import * as EnvironmentRegistry from "../connection/registry.ts";
28import * as EnvironmentSupervisor from "../connection/supervisor.ts";
29import type { RpcSession } from "../rpc/session.ts";
30import { createThreadEnvironmentAtoms } from "./threadCommands.ts";
31import * as ThreadHistoryController from "./threadHistoryController.ts";
32
33const ENVIRONMENT_ID = EnvironmentId.make("remote");
34const THREAD_ID = ThreadId.make("thread");
35const NOW = DateTime.makeUnsafe("2026-09-12T10:00:00.000Z");
36const FUTURE = DateTime.makeUnsafe("2099-01-01T00:00:00.000Z");
37const APPROVAL = {
38 id: RuntimeRequestId.make("approval"),
39 kind: "command" as const,
40 createdAt: NOW,
41};
42const USER_INPUT = {
43 id: RuntimeRequestId.make("input"),
44 kind: "user_input" as const,
45 createdAt: NOW,
46};
47const SNAPSHOT: OrchestrationV2ShellSnapshot = {
48 snapshotSequence: 1,
49 schemaVersion: 2,
50 archivedThreads: [],
51 projects: [],
52 threads: [
53 {
54 id: THREAD_ID,
55 projectId: ProjectId.make("project"),
56 title: "Remote thread",
57 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
58 runtimeMode: "full-access",
59 interactionMode: "default",
60 branch: null,
61 worktreePath: null,
62 createdBy: "user",
63 creationSource: "web",
64 providerInstanceId: ProviderInstanceId.make("codex"),
65 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
66 forkedFrom: null,
67 activeProviderThreadId: null,
68 latestRunId: null,
69 activeRunId: null,
70 status: "idle",
71 pendingRuntimeRequest: null,
72 latestVisibleMessage: null,
73 itemCount: 0,
74 visibleItemCount: 0,
75 deletedAt: null,
76 createdAt: NOW,
77 updatedAt: NOW,
78 archivedAt: null,
79 settledOverride: null,
80 settledAt: null,
81 pullRequests: [],
82 latestUserMessageAt: null,
83 hasActionableProposedPlan: false,
84 },
85 ],
86};
87
88const makeHarness = Effect.fn("TestThreadCommands.makeHarness")(function* (options?: {
89 readonly reconcilePendingWork?: (threadId: ThreadId) => Effect.Effect<void>;
90}) {
91 const requests = yield* Queue.unbounded<{
92 command: OrchestrationV2Command;
93 reply: Deferred.Deferred<{ sequence: number }, Error>;
94 }>();
95 const reconciled = yield* Queue.unbounded<ThreadId>();
96 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
97 target: { environmentId: ENVIRONMENT_ID },
98 session: yield* SubscriptionRef.make(
99 Option.some({
100 client: {
101 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
102 Effect.gen(function* () {
103 const reply = yield* Deferred.make<{ sequence: number }, Error>();
104 yield* Queue.offer(requests, { command, reply });
105 return yield* Deferred.await(reply);
106 }),
107 },
108 } as unknown as RpcSession),
109 ),
110 } as EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
111 const runtime = Atom.runtime(
112 Layer.mergeAll(
113 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, {
114 run: (_environmentId, effect) =>
115 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
116 } as EnvironmentRegistry.EnvironmentRegistry["Service"]),
117 Layer.succeed(
118 Crypto.Crypto,
119 Crypto.make({
120 randomBytes: (size) => new Uint8Array(size),
121 digest: (_algorithm, data) => Effect.succeed(data),
122 }),
123 ),
124 Layer.succeed(
125 ThreadHistoryController.ThreadHistoryController,
126 ThreadHistoryController.ThreadHistoryController.of({
127 register: () => Effect.die("unused"),
128 unregister: () => Effect.void,
129 loadEarlier: () => Effect.die("unused"),
130 reconcilePendingWork: (_environmentId, threadId) =>
131 options?.reconcilePendingWork?.(threadId) ?? Queue.offer(reconciled, threadId),
132 }),
133 ),
134 ),
135 );
136 const snapshotAtom = Atom.family((_environmentId: EnvironmentId) => Atom.make(SNAPSHOT));
137 const commands = createThreadEnvironmentAtoms(runtime, snapshotAtom);
138 const registry = AtomRegistry.make();
139 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
140 const visibleAtom = commands.snapshotAtom(ENVIRONMENT_ID);
141 registry.mount(visibleAtom);
142 return { registry, commands, snapshotAtom, visibleAtom, requests, reconciled };
143});
144
145describe("interrupt turn", () => {
146 // A stale cached item has nothing left to interrupt, so the server can reject Stop.
147 it.effect("reconciles pending work when the server rejects the interrupt", () =>
148 Effect.gen(function* () {
149 const h = yield* makeHarness();
150 const result = h.commands.interruptTurn.run(h.registry, {
151 environmentId: ENVIRONMENT_ID,
152 input: { threadId: THREAD_ID, runId: RunId.make("finished-run") },
153 });
154 const request = yield* Queue.take(h.requests);
155 expect(request.command.type).toBe("run.interrupt");
156 yield* Deferred.fail(request.reply, new Error("Run is not interruptible"));
157 expect((yield* Effect.promise(() => result))._tag).toBe("Failure");
158 expect(yield* Queue.take(h.reconciled)).toBe(THREAD_ID);
159 }),
160 );
161
162 // Mirrors the thread state's handler: the lookup runs in the thread's scope and is joined.
163 const stopWithBlockedLookup = Effect.fn("stopWithBlockedLookup")(function* () {
164 const threadScope = yield* Scope.make();
165 const asked = yield* Deferred.make<void>();
166 const h = yield* makeHarness({
167 reconcilePendingWork: () =>
168 Deferred.succeed(asked, undefined).pipe(
169 Effect.andThen(Effect.never),
170 Effect.forkIn(threadScope),
171 Effect.flatMap(Fiber.join),
172 ),
173 });
174 const result = h.commands.interruptTurn.run(h.registry, {
175 environmentId: ENVIRONMENT_ID,
176 input: { threadId: THREAD_ID, runId: RunId.make("running-run") },
177 });
178 const request = yield* Queue.take(h.requests);
179 yield* Deferred.succeed(request.reply, { sequence: 1 });
180 yield* Deferred.await(asked);
181 return { threadScope, result };
182 });
183
184 it.effect("resolves Stop without waiting for the pending work lookup", () =>
185 Effect.gen(function* () {
186 const { threadScope, result } = yield* stopWithBlockedLookup();
187 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
188 yield* Scope.close(threadScope, Exit.void);
189 }),
190 );
191
192 it.effect("keeps an accepted Stop when the thread closes during the lookup", () =>
193 Effect.gen(function* () {
194 const { threadScope, result } = yield* stopWithBlockedLookup();
195 yield* Scope.close(threadScope, Exit.void);
196 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
197 }),
198 );
199});
200
201describe("remote thread lifecycle commands", () => {
202 const actions = [
203 ["settle", {}, { settledOverride: "settled", pinnedAt: null, snoozedUntil: null }],
204 ["unsettle", { reason: "user" }, { settledOverride: "active", settledAt: null }],
205 ["snooze", { snoozedUntil: "2099-01-01T00:00:00.000Z" }, { snoozedUntil: FUTURE }],
206 ["unsnooze", { reason: "user" }, { snoozedUntil: null, snoozedAt: null }],
207 ["pin", { orderKey: "a" }, { pinnedAt: expect.any(Object), pinOrderKey: "a" }],
208 ["unpin", {}, { pinnedAt: null, pinOrderKey: null }],
209 ["setAutoSettle", { enabled: false }, { autoSettleDisabledAt: expect.any(Object) }],
210 ["reorderPin", { orderKey: "b" }, { pinOrderKey: "b" }],
211 ["reorderActive", { orderKey: "b" }, { activeOrderKey: "b" }],
212 ] as const;
213
214 it.effect.each(actions)(
215 "shows %s before a delayed remote reply and rolls back a rejection",
216 ([action, input, expected]) =>
217 Effect.gen(function* () {
218 const h = yield* makeHarness();
219 const source = h.snapshotAtom(ENVIRONMENT_ID);
220 const initial = {
221 ...SNAPSHOT,
222 threads: [
223 {
224 ...SNAPSHOT.threads[0]!,
225 ...(action === "unsettle" || action === "pin"
226 ? { settledOverride: "settled" as const, settledAt: NOW }
227 : {}),
228 ...(action === "unsnooze" || action === "settle" || action === "pin"
229 ? { snoozedUntil: FUTURE, snoozedAt: NOW }
230 : {}),
231 ...(action === "unpin" || action === "settle"
232 ? { pinnedAt: NOW, pinOrderKey: "a" }
233 : {}),
234 },
235 ],
236 };
237 h.registry.set(source, initial);
238 const result = h.commands[action].run(h.registry, {
239 environmentId: ENVIRONMENT_ID,
240 input: {
241 threadId: THREAD_ID,
242 commandId: CommandId.make(action),
243 reason: "user",
244 enabled: false,
245 orderKey: "a",
246 snoozedUntil: "2099-01-01T00:00:00.000Z",
247 ...input,
248 },
249 });
250 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(expected);
251 const request = yield* Queue.take(h.requests);
252 expect(h.registry.get(source)).toBe(initial);
253 yield* Deferred.fail(request.reply, new Error("Remote rejected the action"));
254 expect((yield* Effect.promise(() => result))._tag).toBe("Failure");
255 expect(h.registry.get(h.visibleAtom)).toBe(initial);
256 }),
257 );
258
259 it.effect("restamps snoozedAt when re-snoozing to the same wake time", () =>
260 Effect.gen(function* () {
261 const h = yield* makeHarness();
262 const earlierSnoozedAt = DateTime.makeUnsafe("2000-01-01T00:00:00.000Z");
263 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), {
264 ...SNAPSHOT,
265 threads: [{ ...SNAPSHOT.threads[0]!, snoozedUntil: FUTURE, snoozedAt: earlierSnoozedAt }],
266 });
267 const result = h.commands.snooze.run(h.registry, {
268 environmentId: ENVIRONMENT_ID,
269 input: { threadId: THREAD_ID, snoozedUntil: DateTime.formatIso(FUTURE) },
270 });
271 const snoozedAt = h.registry.get(h.visibleAtom)?.threads[0]?.snoozedAt;
272 expect(DateTime.toEpochMillis(snoozedAt!)).toBeGreaterThan(
273 DateTime.toEpochMillis(earlierSnoozedAt),
274 );
275 const request = yield* Queue.take(h.requests);
276 yield* Deferred.succeed(request.reply, { sequence: 2 });
277 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
278 }),
279 );
280
281 it.effect("keeps the preview after acknowledgement until the matching shell update arrives", () =>
282 Effect.gen(function* () {
283 const h = yield* makeHarness();
284 const result = h.commands.settle.run(h.registry, {
285 environmentId: ENVIRONMENT_ID,
286 input: { threadId: THREAD_ID },
287 });
288 const request = yield* Queue.take(h.requests);
289 yield* Deferred.succeed(request.reply, { sequence: 3 });
290 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
291 const changed = {
292 ...SNAPSHOT,
293 snapshotSequence: 2,
294 threads: [{ ...SNAPSHOT.threads[0]!, title: "Renamed remotely" }],
295 };
296 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), changed);
297 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject({
298 title: "Renamed remotely",
299 settledOverride: "settled",
300 });
301 const confirmed = {
302 ...changed,
303 snapshotSequence: 3,
304 threads: [
305 {
306 ...changed.threads[0]!,
307 settledOverride: "settled" as const,
308 settledAt: DateTime.makeUnsafe("2026-09-12T12:00:00.000Z"),
309 },
310 ],
311 };
312 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
313 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
314 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), { ...SNAPSHOT, snapshotSequence: 4 });
315 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBeNull();
316 }),
317 );
318
319 it.effect(
320 "shows a queued reverse action immediately and preserves it if the earlier action fails",
321 () =>
322 Effect.gen(function* () {
323 const h = yield* makeHarness();
324 const settle = h.commands.settle.run(h.registry, {
325 environmentId: ENVIRONMENT_ID,
326 input: { threadId: THREAD_ID },
327 });
328 const first = yield* Queue.take(h.requests);
329 const unsettle = h.commands.unsettle.run(h.registry, {
330 environmentId: ENVIRONMENT_ID,
331 input: { threadId: THREAD_ID, reason: "user" },
332 });
333 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("active");
334 yield* Deferred.fail(first.reply, new Error("Settle rejected"));
335 yield* Effect.promise(() => settle);
336 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("active");
337 const second = yield* Queue.take(h.requests);
338 expect(second.command.type).toBe("thread.unsettle");
339 const confirmed = {
340 ...SNAPSHOT,
341 snapshotSequence: 2,
342 threads: [{ ...SNAPSHOT.threads[0]!, settledOverride: "active" as const }],
343 };
344 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
345 yield* Deferred.succeed(second.reply, { sequence: 2 });
346 yield* Effect.promise(() => unsettle);
347 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
348 }),
349 );
350
351 it.effect("isolates environments and does not restore a remotely removed thread", () =>
352 Effect.gen(function* () {
353 const h = yield* makeHarness();
354 const otherEnvironment = EnvironmentId.make("other-remote");
355 const result = h.commands.settle.run(h.registry, {
356 environmentId: ENVIRONMENT_ID,
357 input: { threadId: THREAD_ID },
358 });
359 const request = yield* Queue.take(h.requests);
360 expect(h.registry.get(h.commands.snapshotAtom(otherEnvironment))).toBe(SNAPSHOT);
361 const removed = { ...SNAPSHOT, snapshotSequence: 2, threads: [] };
362 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), removed);
363 expect(h.registry.get(h.visibleAtom)?.threads).toEqual([]);
364 yield* Deferred.fail(request.reply, new Error("Thread removed"));
365 yield* Effect.promise(() => result);
366 expect(h.registry.get(h.visibleAtom)).toBe(removed);
367 }),
368 );
369
370 const undoableActions = ["settle", "snooze"] as const;
371
372 it.effect.each(undoableActions)("restores a confirmed %s when a queued undo fails", (action) =>
373 Effect.gen(function* () {
374 const h = yield* makeHarness();
375 const parked =
376 action === "settle" ? { settledOverride: "settled" as const } : { snoozedUntil: FUTURE };
377 const awake = action === "settle" ? { settledOverride: "active" } : { snoozedUntil: null };
378 const result = h.commands[action].run(h.registry, {
379 environmentId: ENVIRONMENT_ID,
380 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
381 });
382 const first = yield* Queue.take(h.requests);
383 const undo = h.commands[action === "settle" ? "unsettle" : "unsnooze"].run(h.registry, {
384 environmentId: ENVIRONMENT_ID,
385 input: { threadId: THREAD_ID, reason: "user" },
386 });
387 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
388 yield* Deferred.succeed(first.reply, { sequence: 2 });
389 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
390 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
391 const confirmed = {
392 ...SNAPSHOT,
393 snapshotSequence: 2,
394 threads: [{ ...SNAPSHOT.threads[0]!, ...parked }],
395 };
396 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
397 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
398 const second = yield* Queue.take(h.requests);
399 expect(second.command.type).toBe(action === "settle" ? "thread.unsettle" : "thread.unsnooze");
400 yield* Deferred.fail(second.reply, new Error("Undo rejected"));
401 expect((yield* Effect.promise(() => undo))._tag).toBe("Failure");
402 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
403 }),
404 );
405
406 it.effect.each(undoableActions)(
407 "preserves a newer approval when the %s reply arrives after the shell",
408 (action) =>
409 Effect.gen(function* () {
410 const h = yield* makeHarness();
411 const result = h.commands[action].run(h.registry, {
412 environmentId: ENVIRONMENT_ID,
413 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
414 });
415 const request = yield* Queue.take(h.requests);
416 const newer = {
417 ...SNAPSHOT,
418 snapshotSequence: 3,
419 threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: APPROVAL }],
420 };
421 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), newer);
422 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(newer.threads[0]);
423 yield* Deferred.succeed(request.reply, { sequence: 2 });
424 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
425 expect(h.registry.get(h.visibleAtom)).toBe(newer);
426 }),
427 );
428
429 it.effect.each(undoableActions)(
430 "shows an accepted %s while the shell still has an old input request",
431 (action) =>
432 Effect.gen(function* () {
433 const h = yield* makeHarness();
434 const stale = {
435 ...SNAPSHOT,
436 threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: USER_INPUT }],
437 };
438 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), stale);
439 const result = h.commands[action].run(h.registry, {
440 environmentId: ENVIRONMENT_ID,
441 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
442 });
443 const request = yield* Queue.take(h.requests);
444 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(stale.threads[0]);
445 yield* Deferred.succeed(request.reply, { sequence: 2 });
446 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
447 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(
448 action === "settle" ? { settledOverride: "settled" } : { snoozedUntil: FUTURE },
449 );
450 expect(h.registry.get(h.visibleAtom)?.threads[0]?.pendingRuntimeRequest).toBeNull();
451 expect(h.registry.get(h.snapshotAtom(ENVIRONMENT_ID))).toBe(stale);
452 }),
453 );
454});