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