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

threadCommands.test.ts

1,116 lines43.6 KB

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 type OrchestrationV2ThreadFamily,
15} from "@t3tools/contracts";
16import * as DateTime from "effect/DateTime";
17import * as SecureRandom from "effect/crypto/SecureRandom";
18import * as Deferred from "effect/Deferred";
19import * as Cause from "effect/Cause";
20import * as Effect from "effect/Effect";
21import * as Exit from "effect/Exit";
22import * as Fiber from "effect/Fiber";
23import * as Layer from "effect/Layer";
24import * as Option from "effect/Option";
25import * as Queue from "effect/Queue";
26import * as Scope from "effect/Scope";
27import * as Stream from "effect/Stream";
28import * as SubscriptionRef from "effect/SubscriptionRef";
29import { RpcClientError } from "effect/rpc";
30import * as Socket from "effect/socket/Socket";
31import { Atom, AtomRegistry } from "effect/reactivity";
32​
33import * as EnvironmentRegistry from "../connection/registry.ts";
34import {
35 AVAILABLE_CONNECTION_STATE,
36 BearerConnectionTarget,
37 type SupervisorConnectionState,
38} from "../connection/model.ts";
39import * as EnvironmentSupervisor from "../connection/supervisor.ts";
40import type { RpcSession } from "../rpc/session.ts";
41import {
42 makeThreadTriageOutboxStore,
43 ThreadTriageOutboxStore,
44} from "../platform/threadTriageOutboxStore.ts";
45import type { EnvironmentShellState, EnvironmentShellStatus } from "./shell.ts";
46import { createThreadEnvironmentAtoms } from "./threadCommands.ts";
47import * as ThreadHistoryController from "./threadHistoryController.ts";
48​
49const ENVIRONMENT_ID = EnvironmentId.make("remote");
50const THREAD_ID = ThreadId.make("thread");
51const NOW = DateTime.makeUnsafe("2026-09-12T10:00:00.000Z");
52const FUTURE = DateTime.makeUnsafe("2099-01-01T00:00:00.000Z");
53const APPROVAL = {
54 id: RuntimeRequestId.make("approval"),
55 kind: "command" as const,
56 createdAt: NOW,
57};
58const USER_INPUT = {
59 id: RuntimeRequestId.make("input"),
60 kind: "user_input" as const,
61 createdAt: NOW,
62};
63const SNAPSHOT: OrchestrationV2ShellSnapshot = {
64 snapshotSequence: 1,
65 schemaVersion: 2,
66 archivedThreads: [],
67 projects: [],
68 threads: [
69 {
70 id: THREAD_ID,
71 projectId: ProjectId.make("project"),
72 title: "Remote thread",
73 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
74 runtimeMode: "full-access",
75 interactionMode: "default",
76 branch: null,
77 worktreePath: null,
78 createdBy: "user",
79 creationSource: "web",
80 providerInstanceId: ProviderInstanceId.make("codex"),
81 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
82 forkedFrom: null,
83 activeProviderThreadId: null,
84 latestRunId: null,
85 activeRunId: null,
86 status: "idle",
87 pendingRuntimeRequest: null,
88 latestVisibleMessage: null,
89 itemCount: 0,
90 visibleItemCount: 0,
91 deletedAt: null,
92 createdAt: NOW,
93 updatedAt: NOW,
94 archivedAt: null,
95 settledOverride: null,
96 settledAt: null,
97 pullRequests: [],
98 latestUserMessageAt: null,
99 hasActionableProposedPlan: false,
100 },
101 ],
102};
103​
104let randomCalls = 0;
105​
106const makeHarness = Effect.fn("TestThreadCommands.makeHarness")(function* (options?: {
107 readonly loadEarlier?: () => Effect.Effect<ThreadHistoryController.ThreadHistoryLoadEarlierResult>;
108 readonly reconcilePendingWork?: (threadId: ThreadId) => Effect.Effect<void>;
109 readonly connected?: boolean;
110 /** Shared between harnesses to stand in for a restart. */
111 readonly storage?: { value: string | null };
112 readonly family?: (input: {
113 threadId: ThreadId;
114 }) => Effect.Effect<OrchestrationV2ThreadFamily, Error>;
115}) {
116 const requests = yield* Queue.unbounded<{
117 command: OrchestrationV2Command;
118 reply: Deferred.Deferred<{ sequence: number }, Error>;
119 }>();
120 const reconciled = yield* Queue.unbounded<ThreadId>();
121 const liveSession = Option.some({
122 client: {
123 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
124 Effect.gen(function* () {
125 const reply = yield* Deferred.make<{ sequence: number }, Error>();
126 yield* Queue.offer(requests, { command, reply });
127 return yield* Deferred.await(reply);
128 }),
129 [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: (input: { threadId: ThreadId }) =>
130 options?.family?.(input) ?? Effect.die("unused"),
131 },
132 } as unknown as RpcSession);
133 const session = yield* SubscriptionRef.make(
134 options?.connected === false ? Option.none<RpcSession>() : liveSession,
135 );
136 const connectionFollowed = yield* Deferred.make<void>();
137 const connection = yield* SubscriptionRef.make<SupervisorConnectionState>({
138 ...AVAILABLE_CONNECTION_STATE,
139 desired: true,
140 phase: "connected",
141 });
142 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
143 target: new BearerConnectionTarget({
144 environmentId: ENVIRONMENT_ID,
145 label: "Test",
146 connectionId: "test",
147 }),
148 state: connection,
149 session,
150 } as EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
151 const storage = options?.storage ?? { value: null };
152 const store = makeThreadTriageOutboxStore((next) =>
153 Effect.sync(() => {
154 storage.value = next(storage.value) ?? storage.value;
155 }),
156 );
157 const runtime = Atom.runtime(
158 Layer.mergeAll(
159 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, {
160 run: (_environmentId, effect) =>
161 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
162 followStream: (_environmentId, stream) =>
163 Stream.provideService(
164 stream,
165 EnvironmentSupervisor.EnvironmentSupervisor,
166 supervisor,
167 ).pipe(Stream.onStart(Deferred.succeed(connectionFollowed, undefined))),
168 } as EnvironmentRegistry.EnvironmentRegistry["Service"]),
169 Layer.succeed(
170 SecureRandom.SecureRandom,
171 // Distinct per call, so a resend under a fresh command id would show.
172 SecureRandom.make((size) => new Uint8Array(size).fill(++randomCalls % 256)),
173 ),
174 Layer.succeed(ThreadTriageOutboxStore, store),
175 Layer.succeed(
176 ThreadHistoryController.ThreadHistoryController,
177 ThreadHistoryController.ThreadHistoryController.of({
178 register: () => Effect.die("unused"),
179 unregister: () => Effect.void,
180 loadEarlier: () => options?.loadEarlier?.() ?? Effect.die("unused"),
181 reconcilePendingWork: (_environmentId, threadId) =>
182 options?.reconcilePendingWork?.(threadId) ?? Queue.offer(reconciled, threadId),
183 }),
184 ),
185 ),
186 );
187 const snapshotAtom = Atom.family((_environmentId: EnvironmentId) =>
188 Atom.make<OrchestrationV2ShellSnapshot | null>(SNAPSHOT),
189 );
190 const statusAtom = Atom.family((_environmentId: EnvironmentId) =>
191 Atom.make<EnvironmentShellStatus>(options?.connected === false ? "cached" : "live"),
192 );
193 const history = Atom.family(() => Atom.make<EnvironmentShellState["commandHistory"]>(undefined));
194 const commands = createThreadEnvironmentAtoms(runtime, snapshotAtom, statusAtom, history);
195 const registry = AtomRegistry.make();
196 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
197 const visibleAtom = commands.snapshotAtom(ENVIRONMENT_ID);
198 registry.mount(visibleAtom);
199 const pendingSyncAtom = commands.pendingSyncAtom(ENVIRONMENT_ID);
200 registry.mount(pendingSyncAtom);
201 const reconnect = (status: EnvironmentShellStatus = "live") =>
202 SubscriptionRef.set(session, liveSession).pipe(
203 Effect.andThen(Effect.sync(() => registry.set(statusAtom(ENVIRONMENT_ID), status))),
204 );
205 return {
206 registry,
207 commands,
208 snapshotAtom,
209 statusAtom,
210 history,
211 visibleAtom,
212 pendingSyncAtom,
213 reconnect,
214 store,
215 requests,
216 reconciled,
217 connection,
218 connectionFollowed,
219 };
220});
221​
222describe("history loading", () => {
223 it.effect("sends a message on the thread while earlier history is loading", () =>
224 Effect.gen(function* () {
225 const historyStarted = yield* Deferred.make<void>();
226 const historyReply =
227 yield* Deferred.make<ThreadHistoryController.ThreadHistoryLoadEarlierResult>();
228 const h = yield* makeHarness({
229 loadEarlier: () =>
230 Deferred.succeed(historyStarted, undefined).pipe(
231 Effect.andThen(Deferred.await(historyReply)),
232 ),
233 });
234 yield* Effect.addFinalizer(() => Deferred.succeed(historyReply, { _tag: "loaded" }));
235 const history = yield* Effect.forkChild(
236 Effect.exit(
237 h.commands.loadEarlierHistory.run(h.registry, {
238 environmentId: ENVIRONMENT_ID,
239 input: { threadId: THREAD_ID },
240 }),
241 ),
242 { startImmediately: true },
243 );
244 yield* Deferred.await(historyStarted);
245 const send = yield* Effect.forkChild(
246 Effect.exit(
247 h.commands.startTurn.run(h.registry, {
248 environmentId: ENVIRONMENT_ID,
249 input: {
250 threadId: THREAD_ID,
251 message: {
252 messageId: MessageId.make("message"),
253 role: "user",
254 text: "Send while history loads",
255 attachments: [],
256 },
257 runtimeMode: "full-access",
258 interactionMode: "default",
259 dispatchMode: "start",
260 },
261 }),
262 ),
263 { startImmediately: true },
264 );
265 // Dispatched after Send on another thread, so it arrives first only if Send is queued.
266 const controlThreadId = ThreadId.make("control-thread");
267 const control = yield* Effect.forkChild(
268 Effect.exit(
269 h.commands.interruptTurn.run(h.registry, {
270 environmentId: ENVIRONMENT_ID,
271 input: { threadId: controlThreadId, runId: RunId.make("control-run") },
272 }),
273 ),
274 { startImmediately: true },
275 );
276 const first = yield* Queue.take(h.requests);
277 yield* Deferred.succeed(first.reply, { sequence: 1 });
278 yield* Deferred.succeed(historyReply, { _tag: "loaded" });
279 const second = yield* Queue.take(h.requests);
280 yield* Deferred.succeed(second.reply, { sequence: 2 });
281 const results = yield* Fiber.joinAll([history, send, control]);
282​
283 expect(first.command).toMatchObject({ type: "message.dispatch", threadId: THREAD_ID });
284 expect(second.command).toMatchObject({ type: "run.interrupt", threadId: controlThreadId });
285 expect(results.map((value) => value._tag)).toEqual(["Success", "Success", "Success"]);
286 }),
287 );
288});
289​
290describe("interrupt turn", () => {
291 // A stale cached item has nothing left to interrupt, so the server can reject Stop.
292 it.effect("reconciles pending work when the server rejects the interrupt", () =>
293 Effect.gen(function* () {
294 const h = yield* makeHarness();
295 const result = yield* Effect.forkChild(
296 Effect.exit(
297 h.commands.interruptTurn.run(h.registry, {
298 environmentId: ENVIRONMENT_ID,
299 input: { threadId: THREAD_ID, runId: RunId.make("finished-run") },
300 }),
301 ),
302 { startImmediately: true },
303 );
304 const request = yield* Queue.take(h.requests);
305 expect(request.command.type).toBe("run.interrupt");
306 yield* Deferred.fail(request.reply, new Error("Run is not interruptible"));
307 expect((yield* Fiber.join(result))._tag).toBe("Failure");
308 expect(yield* Queue.take(h.reconciled)).toBe(THREAD_ID);
309 }),
310 );
311​
312 // Mirrors the thread state's handler: the lookup runs in the thread's scope and is joined.
313 const stopWithBlockedLookup = Effect.fn("stopWithBlockedLookup")(function* () {
314 const threadScope = yield* Scope.make();
315 const asked = yield* Deferred.make<void>();
316 const h = yield* makeHarness({
317 reconcilePendingWork: () =>
318 Deferred.succeed(asked, undefined).pipe(
319 Effect.andThen(Effect.never),
320 Effect.forkIn(threadScope),
321 Effect.flatMap(Fiber.join),
322 ),
323 });
324 const result = yield* Effect.forkChild(
325 Effect.exit(
326 h.commands.interruptTurn.run(h.registry, {
327 environmentId: ENVIRONMENT_ID,
328 input: { threadId: THREAD_ID, runId: RunId.make("running-run") },
329 }),
330 ),
331 { startImmediately: true },
332 );
333 const request = yield* Queue.take(h.requests);
334 yield* Deferred.succeed(request.reply, { sequence: 1 });
335 yield* Deferred.await(asked);
336 return { threadScope, result };
337 });
338​
339 it.effect("resolves Stop without waiting for the pending work lookup", () =>
340 Effect.gen(function* () {
341 const { threadScope, result } = yield* stopWithBlockedLookup();
342 expect((yield* Fiber.join(result))._tag).toBe("Success");
343 yield* Scope.close(threadScope, Exit.void);
344 }),
345 );
346​
347 it.effect("keeps an accepted Stop when the thread closes during the lookup", () =>
348 Effect.gen(function* () {
349 const { threadScope, result } = yield* stopWithBlockedLookup();
350 yield* Scope.close(threadScope, Exit.void);
351 expect((yield* Fiber.join(result))._tag).toBe("Success");
352 }),
353 );
354});
355​
356describe("title regeneration", () => {
357 it.effect("resolves with the outcome recorded for its own request", () =>
358 Effect.gen(function* () {
359 const h = yield* makeHarness();
360 const source = h.snapshotAtom(ENVIRONMENT_ID);
361 const thread = SNAPSHOT.threads[0]!;
362 const target = { environmentId: ENVIRONMENT_ID, input: { threadId: THREAD_ID } };
363 const earlier = {
364 requestId: CommandId.make("earlier"),
365 status: "renamed" as const,
366 completedAt: NOW,
367 };
368​
369 h.registry.set(source, null);
370 const result = yield* Effect.forkChild(
371 Effect.exit(h.commands.regenerateTitle.run(h.registry, target)),
372 { startImmediately: true },
373 );
374 const request = yield* Queue.take(h.requests);
375 const requestId = request.command.commandId;
376 yield* Deferred.succeed(request.reply, { sequence: 2 });
377 yield* Deferred.await(h.connectionFollowed);
378 h.registry.set(source, {
379 ...SNAPSHOT,
380 snapshotSequence: 2,
381 threads: [
382 {
383 ...thread,
384 titleRegeneration: { requestId, startedAt: NOW },
385 lastTitleRegeneration: earlier,
386 },
387 ],
388 });
389 h.registry.set(source, {
390 ...SNAPSHOT,
391 snapshotSequence: 3,
392 threads: [],
393 archivedThreads: [
394 {
395 ...thread,
396 archivedAt: NOW,
397 titleRegeneration: null,
398 lastTitleRegeneration: {
399 requestId,
400 status: "failed",
401 message: "model unavailable",
402 completedAt: NOW,
403 },
404 },
405 ],
406 });
407 const outcome = yield* Fiber.join(result);
408 expect(outcome).toMatchObject({
409 _tag: "Success",
410 value: { status: "failed", message: "model unavailable" },
411 });
412​
413 const superseded = yield* Effect.forkChild(
414 Effect.exit(h.commands.regenerateTitle.run(h.registry, target)),
415 { startImmediately: true },
416 );
417 const second = yield* Queue.take(h.requests);
418 h.registry.set(source, {
419 ...SNAPSHOT,
420 snapshotSequence: 4,
421 threads: [{ ...thread, titleRegeneration: null, lastTitleRegeneration: earlier }],
422 });
423 yield* Deferred.succeed(second.reply, { sequence: 4 });
424 expect(yield* Fiber.join(superseded)).toMatchObject({
425 _tag: "Success",
426 value: null,
427 });
428 }),
429 );
430​
431 it.effect("settles without an outcome when the environment disconnects while waiting", () =>
432 Effect.gen(function* () {
433 const h = yield* makeHarness();
434 const result = yield* Effect.forkChild(
435 Effect.exit(
436 h.commands.regenerateTitle.run(h.registry, {
437 environmentId: ENVIRONMENT_ID,
438 input: { threadId: THREAD_ID },
439 }),
440 ),
441 { startImmediately: true },
442 );
443 const request = yield* Queue.take(h.requests);
444 yield* Deferred.succeed(request.reply, { sequence: 2 });
445 yield* SubscriptionRef.update(h.connection, (state) => ({
446 ...state,
447 phase: "backoff" as const,
448 }));
449 expect(yield* Fiber.join(result)).toMatchObject({ _tag: "Success", value: null });
450 }),
451 );
452});
453​
454describe("remote thread lifecycle commands", () => {
455 const actions = [
456 ["settle", {}, { settledOverride: "settled", pinnedAt: null, snoozedUntil: null }],
457 ["unsettle", { reason: "user" }, { settledOverride: "active", settledAt: null }],
458 ["snooze", { snoozedUntil: "2099-01-01T00:00:00.000Z" }, { snoozedUntil: FUTURE }],
459 ["unsnooze", { reason: "user" }, { snoozedUntil: null, snoozedAt: null }],
460 ["pin", { orderKey: "a" }, { pinnedAt: expect.any(Object), pinOrderKey: "a" }],
461 ["unpin", {}, { pinnedAt: null, pinOrderKey: null }],
462 ["setAutoSettle", { enabled: false }, { autoSettleDisabledAt: expect.any(Object) }],
463 ["reorderPin", { orderKey: "b" }, { pinOrderKey: "b" }],
464 ["reorderActive", { orderKey: "b" }, { activeOrderKey: "b" }],
465 ] as const;
466​
467 it.effect.each(actions)(
468 "shows %s before a delayed remote reply and rolls back a rejection",
469 ([action, input, expected]) =>
470 Effect.gen(function* () {
471 const h = yield* makeHarness();
472 const source = h.snapshotAtom(ENVIRONMENT_ID);
473 const initial = {
474 ...SNAPSHOT,
475 threads: [
476 {
477 ...SNAPSHOT.threads[0]!,
478 ...(action === "unsettle" || action === "pin"
479 ? { settledOverride: "settled" as const, settledAt: NOW }
480 : {}),
481 ...(action === "unsnooze" || action === "settle" || action === "pin"
482 ? { snoozedUntil: FUTURE, snoozedAt: NOW }
483 : {}),
484 ...(action === "unpin" || action === "settle"
485 ? { pinnedAt: NOW, pinOrderKey: "a" }
486 : {}),
487 },
488 ],
489 };
490 h.registry.set(source, initial);
491 const result = yield* Effect.forkChild(
492 Effect.exit(
493 h.commands[action].run(h.registry, {
494 environmentId: ENVIRONMENT_ID,
495 input: {
496 threadId: THREAD_ID,
497 commandId: CommandId.make(action),
498 reason: "user",
499 enabled: false,
500 orderKey: "a",
501 snoozedUntil: "2099-01-01T00:00:00.000Z",
502 ...input,
503 },
504 }),
505 ),
506 { startImmediately: true },
507 );
508 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(expected);
509 const request = yield* Queue.take(h.requests);
510 expect(h.registry.get(source)).toBe(initial);
511 yield* Deferred.fail(request.reply, new Error("Remote rejected the action"));
512 expect((yield* Fiber.join(result))._tag).toBe("Failure");
513 expect(h.registry.get(h.visibleAtom)).toBe(initial);
514 }),
515 );
516​
517 it.effect.each(["early", "late", "resume"])("shows restored placement after %s", (when) =>
518 Effect.scoped(
519 Effect.gen(function* () {
520 const h = yield* makeHarness();
521 const source = h.snapshotAtom(ENVIRONMENT_ID);
522 h.registry.set(source, { ...SNAPSHOT, snapshotSequence: 10 });
523 const settle = yield* Effect.forkChild(
524 h.commands.settle.run(h.registry, {
525 environmentId: ENVIRONMENT_ID,
526 input: { threadId: THREAD_ID },
527 }),
528 { startImmediately: true },
529 );
530 const request = yield* Queue.take(h.requests);
531 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("settled");
532 if (when === "late") h.registry.set(source, SNAPSHOT);
533 yield* Deferred.succeed(request.reply, { sequence: 11 });
534 yield* Fiber.join(settle);
535​
536 h.registry.set(h.statusAtom(ENVIRONMENT_ID), "synchronizing");
537 if (when !== "resume") h.registry.set(source, SNAPSHOT);
538 else h.registry.set(h.history(ENVIRONMENT_ID), { synchronizedSession: {} as RpcSession });
539 h.registry.set(h.statusAtom(ENVIRONMENT_ID), "live");
540​
541 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBeNull();
542 }),
543 ),
544 );
545​
546 it.effect("restamps snoozedAt when re-snoozing to the same wake time", () =>
547 Effect.gen(function* () {
548 const h = yield* makeHarness();
549 const earlierSnoozedAt = DateTime.makeUnsafe("2000-01-01T00:00:00.000Z");
550 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), {
551 ...SNAPSHOT,
552 threads: [{ ...SNAPSHOT.threads[0]!, snoozedUntil: FUTURE, snoozedAt: earlierSnoozedAt }],
553 });
554 const result = yield* Effect.forkChild(
555 Effect.exit(
556 h.commands.snooze.run(h.registry, {
557 environmentId: ENVIRONMENT_ID,
558 input: { threadId: THREAD_ID, snoozedUntil: DateTime.formatIso(FUTURE) },
559 }),
560 ),
561 { startImmediately: true },
562 );
563 const snoozedAt = h.registry.get(h.visibleAtom)?.threads[0]?.snoozedAt;
564 expect(DateTime.toEpochMillis(snoozedAt!)).toBeGreaterThan(
565 DateTime.toEpochMillis(earlierSnoozedAt),
566 );
567 const request = yield* Queue.take(h.requests);
568 yield* Deferred.succeed(request.reply, { sequence: 2 });
569 expect((yield* Fiber.join(result))._tag).toBe("Success");
570 }),
571 );
572​
573 it.effect("keeps the preview after acknowledgement until the matching shell update arrives", () =>
574 Effect.gen(function* () {
575 const h = yield* makeHarness();
576 const result = yield* Effect.forkChild(
577 Effect.exit(
578 h.commands.settle.run(h.registry, {
579 environmentId: ENVIRONMENT_ID,
580 input: { threadId: THREAD_ID },
581 }),
582 ),
583 { startImmediately: true },
584 );
585 const request = yield* Queue.take(h.requests);
586 yield* Deferred.succeed(request.reply, { sequence: 3 });
587 expect((yield* Fiber.join(result))._tag).toBe("Success");
588 const changed = {
589 ...SNAPSHOT,
590 snapshotSequence: 2,
591 threads: [{ ...SNAPSHOT.threads[0]!, title: "Renamed remotely" }],
592 };
593 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), changed);
594 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject({
595 title: "Renamed remotely",
596 settledOverride: "settled",
597 });
598 const confirmed = {
599 ...changed,
600 snapshotSequence: 3,
601 threads: [
602 {
603 ...changed.threads[0]!,
604 settledOverride: "settled" as const,
605 settledAt: DateTime.makeUnsafe("2026-09-12T12:00:00.000Z"),
606 },
607 ],
608 };
609 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
610 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
611 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), { ...SNAPSHOT, snapshotSequence: 4 });
612 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBeNull();
613 }),
614 );
615​
616 it.effect(
617 "shows a queued reverse action immediately and preserves it if the earlier action fails",
618 () =>
619 Effect.gen(function* () {
620 const h = yield* makeHarness();
621 const settle = yield* Effect.forkChild(
622 Effect.exit(
623 h.commands.settle.run(h.registry, {
624 environmentId: ENVIRONMENT_ID,
625 input: { threadId: THREAD_ID },
626 }),
627 ),
628 { startImmediately: true },
629 );
630 const first = yield* Queue.take(h.requests);
631 const unsettle = yield* Effect.forkChild(
632 Effect.exit(
633 h.commands.unsettle.run(h.registry, {
634 environmentId: ENVIRONMENT_ID,
635 input: { threadId: THREAD_ID, reason: "user" },
636 }),
637 ),
638 { startImmediately: true },
639 );
640 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("active");
641 yield* Deferred.fail(first.reply, new Error("Settle rejected"));
642 yield* Fiber.join(settle);
643 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("active");
644 const second = yield* Queue.take(h.requests);
645 expect(second.command.type).toBe("thread.unsettle");
646 const confirmed = {
647 ...SNAPSHOT,
648 snapshotSequence: 2,
649 threads: [{ ...SNAPSHOT.threads[0]!, settledOverride: "active" as const }],
650 };
651 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
652 yield* Deferred.succeed(second.reply, { sequence: 2 });
653 yield* Fiber.join(unsettle);
654 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
655 }),
656 );
657​
658 it.effect("isolates environments and does not restore a remotely removed thread", () =>
659 Effect.gen(function* () {
660 const h = yield* makeHarness();
661 const otherEnvironment = EnvironmentId.make("other-remote");
662 const result = yield* Effect.forkChild(
663 Effect.exit(
664 h.commands.settle.run(h.registry, {
665 environmentId: ENVIRONMENT_ID,
666 input: { threadId: THREAD_ID },
667 }),
668 ),
669 { startImmediately: true },
670 );
671 const request = yield* Queue.take(h.requests);
672 expect(h.registry.get(h.commands.snapshotAtom(otherEnvironment))).toBe(SNAPSHOT);
673 expect(h.registry.get(h.commands.rowActionsAtom(ENVIRONMENT_ID))).toBe(1);
674 expect(h.registry.get(h.commands.rowActionsAtom(otherEnvironment))).toBe(0);
675 const removed = { ...SNAPSHOT, snapshotSequence: 2, threads: [] };
676 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), removed);
677 expect(h.registry.get(h.visibleAtom)?.threads).toEqual([]);
678 yield* Deferred.fail(request.reply, new Error("Thread removed"));
679 yield* Fiber.join(result);
680 expect(h.registry.get(h.visibleAtom)).toBe(removed);
681 }),
682 );
683​
684 const undoableActions = ["settle", "snooze"] as const;
685​
686 it.effect.each(undoableActions)("restores a confirmed %s when a queued undo fails", (action) =>
687 Effect.gen(function* () {
688 const h = yield* makeHarness();
689 const parked =
690 action === "settle" ? { settledOverride: "settled" as const } : { snoozedUntil: FUTURE };
691 const awake = action === "settle" ? { settledOverride: "active" } : { snoozedUntil: null };
692 const result = yield* Effect.forkChild(
693 Effect.exit(
694 h.commands[action].run(h.registry, {
695 environmentId: ENVIRONMENT_ID,
696 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
697 }),
698 ),
699 { startImmediately: true },
700 );
701 const first = yield* Queue.take(h.requests);
702 const undo = yield* Effect.forkChild(
703 Effect.exit(
704 h.commands[action === "settle" ? "unsettle" : "unsnooze"].run(h.registry, {
705 environmentId: ENVIRONMENT_ID,
706 input: { threadId: THREAD_ID, reason: "user" },
707 }),
708 ),
709 { startImmediately: true },
710 );
711 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
712 yield* Deferred.succeed(first.reply, { sequence: 2 });
713 expect((yield* Fiber.join(result))._tag).toBe("Success");
714 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
715 const confirmed = {
716 ...SNAPSHOT,
717 snapshotSequence: 2,
718 threads: [{ ...SNAPSHOT.threads[0]!, ...parked }],
719 };
720 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
721 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
722 const second = yield* Queue.take(h.requests);
723 expect(second.command.type).toBe(action === "settle" ? "thread.unsettle" : "thread.unsnooze");
724 yield* Deferred.fail(second.reply, new Error("Undo rejected"));
725 expect((yield* Fiber.join(undo))._tag).toBe("Failure");
726 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
727 }),
728 );
729​
730 it.effect.each(undoableActions)(
731 "preserves a newer approval when the %s reply arrives after the shell",
732 (action) =>
733 Effect.gen(function* () {
734 const h = yield* makeHarness();
735 const result = yield* Effect.forkChild(
736 Effect.exit(
737 h.commands[action].run(h.registry, {
738 environmentId: ENVIRONMENT_ID,
739 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
740 }),
741 ),
742 { startImmediately: true },
743 );
744 const request = yield* Queue.take(h.requests);
745 const newer = {
746 ...SNAPSHOT,
747 snapshotSequence: 3,
748 threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: APPROVAL }],
749 };
750 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), newer);
751 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(newer.threads[0]);
752 yield* Deferred.succeed(request.reply, { sequence: 2 });
753 expect((yield* Fiber.join(result))._tag).toBe("Success");
754 expect(h.registry.get(h.visibleAtom)).toBe(newer);
755 }),
756 );
757​
758 it.effect.each(undoableActions)(
759 "shows an accepted %s while the shell still has an old input request",
760 (action) =>
761 Effect.gen(function* () {
762 const h = yield* makeHarness();
763 const stale = {
764 ...SNAPSHOT,
765 threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: USER_INPUT }],
766 };
767 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), stale);
768 const result = yield* Effect.forkChild(
769 Effect.exit(
770 h.commands[action].run(h.registry, {
771 environmentId: ENVIRONMENT_ID,
772 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
773 }),
774 ),
775 { startImmediately: true },
776 );
777 const request = yield* Queue.take(h.requests);
778 if (action === "settle") {
779 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(stale.threads[0]);
780 } else {
781 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject({
782 snoozedUntil: FUTURE,
783 pendingRuntimeRequest: USER_INPUT,
784 });
785 }
786 yield* Deferred.succeed(request.reply, { sequence: 2 });
787 expect((yield* Fiber.join(result))._tag).toBe("Success");
788 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(
789 action === "settle" ? { settledOverride: "settled" } : { snoozedUntil: FUTURE },
790 );
791 expect(h.registry.get(h.visibleAtom)?.threads[0]?.pendingRuntimeRequest).toEqual(
792 action === "settle" ? null : USER_INPUT,
793 );
794 expect(h.registry.get(h.snapshotAtom(ENVIRONMENT_ID))).toBe(stale);
795 }),
796 );
797 it.effect("acknowledges a new question when snoozing again to the same wake time", () =>
798 Effect.gen(function* () {
799 const h = yield* makeHarness();
800 const initial = {
801 ...SNAPSHOT,
802 threads: [
803 {
804 ...SNAPSHOT.threads[0]!,
805 pendingRuntimeRequest: USER_INPUT,
806 snoozedAt: DateTime.makeUnsafe("2026-09-12T09:00:00.000Z"),
807 snoozedUntil: FUTURE,
808 },
809 ],
810 };
811 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), initial);
812 const result = yield* Effect.forkChild(
813 Effect.exit(
814 h.commands.snooze.run(h.registry, {
815 environmentId: ENVIRONMENT_ID,
816 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
817 }),
818 ),
819 { startImmediately: true },
820 );
821 const request = yield* Queue.take(h.requests);
822 const snoozed = h.registry.get(h.visibleAtom)?.threads[0];
823 expect(DateTime.toEpochMillis(snoozed!.snoozedAt!)).toBeGreaterThanOrEqual(
824 DateTime.toEpochMillis(USER_INPUT.createdAt),
825 );
826 expect(snoozed?.pendingRuntimeRequest).toEqual(USER_INPUT);
827 yield* Deferred.succeed(request.reply, { sequence: 2 });
828 expect((yield* Fiber.join(result))._tag).toBe("Success");
829 }),
830 );
831});
832​
833const waitFor = <A>(
834 registry: AtomRegistry.AtomRegistry,
835 atom: Atom.Atom<A>,
836 done: (value: A) => boolean,
837) =>
838 Effect.callback<void>((resume) => {
839 if (done(registry.get(atom))) return resume(Effect.void);
840 const unsubscribe = registry.subscribe(atom, (value) => {
841 if (!done(value)) return;
842 unsubscribe();
843 resume(Effect.void);
844 });
845 return Effect.sync(unsubscribe);
846 });
847​
848// regression: #24532 settle and snooze while the thread's machine is offline
849describe("settle and snooze while the environment is offline", () => {
850 type Harness = Effect.Success<ReturnType<typeof makeHarness>>;
851 const target = { environmentId: ENVIRONMENT_ID, input: { threadId: THREAD_ID } };
852 const snooze = {
853 environmentId: ENVIRONMENT_ID,
854 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
855 };
856 const undo = {
857 environmentId: ENVIRONMENT_ID,
858 input: { threadId: THREAD_ID, reason: "user" as const },
859 };
860 const queued = (h: Harness) => h.store.update((stored) => stored);
861 const nothingPending = (h: Harness) =>
862 waitFor(h.registry, h.pendingSyncAtom, (threads) => threads.size === 0);
863 /** Commands on one thread go out in order, so this one arrives first only if no other was sent. */
864 const expectNothingSent = Effect.fn("expectNothingSent")(function* (h: Harness) {
865 const pin = yield* Effect.forkChild(
866 h.commands.pin.run(h.registry, {
867 environmentId: ENVIRONMENT_ID,
868 input: { threadId: THREAD_ID, orderKey: "a" },
869 }),
870 { startImmediately: true },
871 );
872 const request = yield* Queue.take(h.requests);
873 expect(request.command.type).toBe("thread.pin");
874 yield* Deferred.succeed(request.reply, { sequence: 9 });
875 yield* Fiber.join(pin);
876 });
877​
878 it.effect.each([
879 ["settle", { settledOverride: "settled" }],
880 ["snooze", { snoozedUntil: FUTURE }],
881 ] as const)("shows a %s at once and sends it once the shell is live", ([action, shown]) =>
882 Effect.gen(function* () {
883 const h = yield* makeHarness({ connected: false });
884 const run =
885 action === "settle"
886 ? h.commands.settle.run(h.registry, target)
887 : h.commands.snooze.run(h.registry, snooze);
888 expect(Exit.isSuccess(yield* Effect.exit(run))).toBe(true);
889 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(shown);
890 expect([...h.registry.get(h.pendingSyncAtom)]).toEqual([THREAD_ID]);
891 const entries = yield* queued(h);
892 expect(entries).toHaveLength(1);
893​
894 yield* h.reconnect();
895 const request = yield* Queue.take(h.requests);
896 expect(request.command).toMatchObject({
897 type: `thread.${action}`,
898 threadId: THREAD_ID,
899 commandId: entries[0]!.commandId,
900 });
901 yield* Deferred.succeed(request.reply, { sequence: 2 });
902 yield* nothingPending(h);
903 expect(yield* queued(h)).toEqual([]);
904 yield* expectNothingSent(h);
905 }),
906 );
907​
908 it.effect("drops a queued settle when the thread changed on the server meanwhile", () =>
909 Effect.gen(function* () {
910 const h = yield* makeHarness({ connected: false });
911 yield* Effect.exit(h.commands.settle.run(h.registry, target));
912 yield* h.reconnect("synchronizing");
913 const changed = {
914 ...SNAPSHOT,
915 snapshotSequence: 5,
916 threads: [
917 {
918 ...SNAPSHOT.threads[0]!,
919 latestRunId: RunId.make("run-2"),
920 itemCount: 3,
921 },
922 ],
923 };
924 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), changed);
925 h.registry.set(h.statusAtom(ENVIRONMENT_ID), "live");
926 yield* nothingPending(h);
927 expect(yield* queued(h)).toEqual([]);
928 expect(h.registry.get(h.visibleAtom)).toBe(changed);
929 yield* expectNothingSent(h);
930 }),
931 );
932​
933 it.effect("un-settling a queued settle cancels it without contacting the server", () =>
934 Effect.gen(function* () {
935 const h = yield* makeHarness({ connected: false });
936 yield* Effect.exit(h.commands.settle.run(h.registry, target));
937 // The undo plan stops here: the server never cleared the placement or snooze.
938 expect(yield* h.commands.unsettle.run(h.registry, undo)).toMatchObject({
939 cancelledOnDevice: true,
940 });
941 expect(h.registry.get(h.pendingSyncAtom).size).toBe(0);
942 expect(yield* queued(h)).toEqual([]);
943 expect(h.registry.get(h.visibleAtom)).toBe(SNAPSHOT);
944 yield* h.reconnect();
945 yield* expectNothingSent(h);
946 }),
947 );
948​
949 it.effect("waking cancels the snooze stored now, also when another tab replaced it", () =>
950 Effect.gen(function* () {
951 const storage = { value: null as string | null };
952 const h = yield* makeHarness({ connected: false, storage });
953 const otherTab = yield* makeHarness({ connected: false, storage });
954 yield* Effect.exit(h.commands.snooze.run(h.registry, snooze));
955 yield* Effect.exit(
956 otherTab.commands.snooze.run(otherTab.registry, {
957 ...snooze,
958 input: { ...snooze.input, snoozedUntil: "2099-02-01T00:00:00.000Z" },
959 }),
960 );
961 yield* h.commands.unsnooze.run(h.registry, undo);
962 expect(yield* queued(h)).toEqual([]);
963 }),
964 );
965​
966 it.effect("skips a change another tab cancelled while an earlier send failed", () =>
967 Effect.gen(function* () {
968 const storage = { value: null as string | null };
969 const h = yield* makeHarness({ connected: false, storage });
970 const otherTab = yield* makeHarness({ connected: false, storage });
971 const second = { ...SNAPSHOT.threads[0]!, id: ThreadId.make("second") };
972 const twoThreads = { ...SNAPSHOT, threads: [SNAPSHOT.threads[0]!, second] };
973 for (const tab of [h, otherTab])
974 tab.registry.set(tab.snapshotAtom(ENVIRONMENT_ID), twoThreads);
975 const settleSecond = { environmentId: ENVIRONMENT_ID, input: { threadId: second.id } };
976 yield* Effect.exit(h.commands.settle.run(h.registry, target));
977 yield* Effect.exit(h.commands.settle.run(h.registry, settleSecond));
978​
979 yield* h.reconnect();
980 const first = yield* Queue.take(h.requests);
981 yield* otherTab.commands.unsettle.run(otherTab.registry, {
982 ...settleSecond,
983 input: { ...settleSecond.input, reason: "user" as const },
984 });
985 yield* Deferred.fail(
986 first.reply,
987 new RpcClientError.RpcClientError({ reason: new Socket.SocketCloseError({ code: 1006 }) }),
988 );
989 // The replay re-reads storage before the next change, which drops the cancelled one.
990 yield* waitFor(h.registry, h.pendingSyncAtom, (threads) => !threads.has(second.id));
991 yield* expectNothingSent(h);
992 }),
993 );
994​
995 it.effect("sends a settle queued before a restart", () =>
996 Effect.gen(function* () {
997 const storage = { value: null as string | null };
998 const before = yield* makeHarness({ connected: false, storage });
999 yield* Effect.exit(before.commands.settle.run(before.registry, target));
1000 const [entry] = yield* queued(before);
1001​
1002 const h = yield* makeHarness({ connected: false, storage });
1003 yield* waitFor(h.registry, h.pendingSyncAtom, (threads) => threads.has(THREAD_ID));
1004 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("settled");
1005 yield* h.reconnect();
1006 const request = yield* Queue.take(h.requests);
1007 expect(request.command).toMatchObject({
1008 type: "thread.settle",
1009 commandId: entry!.commandId,
1010 });
1011 yield* Deferred.succeed(request.reply, { sequence: 2 });
1012 yield* nothingPending(h);
1013 }),
1014 );
1015​
1016 it.effect("refuses a snooze while a settle is queued, keeping the settle", () =>
1017 Effect.gen(function* () {
1018 const h = yield* makeHarness({ connected: false });
1019 yield* Effect.exit(h.commands.settle.run(h.registry, target));
1020 const before = yield* queued(h);
1021 const result = yield* Effect.exit(h.commands.snooze.run(h.registry, snooze));
1022 expect(Exit.isFailure(result) && Cause.squash(result.cause)).toMatchObject({
1023 _tag: "EnvironmentRpcUnavailableError",
1024 message: "Test is not connected.",
1025 });
1026 expect(yield* queued(h)).toEqual(before);
1027 }),
1028 );
1029​
1030 // regression: a reconnect shell that trims older settled threads leaves the snoozed row out
1031 describe("when the reconnect shell leaves the thread out as older settled", () => {
1032 // The shell keeps the 25 newest settled top-level threads; the host settled a 26th meanwhile.
1033 const settled = { ...SNAPSHOT.threads[0]!, settledOverride: "settled" as const };
1034 const rows = Array.from({ length: 26 }, (_, index) => {
1035 const id = index === 0 ? THREAD_ID : ThreadId.make(`row-${index}`);
1036 const lineage = { rootThreadId: id, parentThreadId: null, relationshipToParent: null };
1037 return { ...settled, id, lineage, settledAt: DateTime.makeUnsafe(1000 + index) };
1038 });
1039 const shellAt = (snapshotSequence: number, threads = rows.slice(1), count = 1) => ({
1040 ...SNAPSHOT,
1041 snapshotSequence,
1042 threads,
1043 olderSettled: {
1044 before: DateTime.formatIso(threads.at(-25)!.settledAt),
1045 asOfSequence: snapshotSequence,
1046 counts: count === 0 ? [] : [{ projectId: rows[0]!.projectId, count }],
1047 },
1048 });
1049 type Read = (h: Harness) => Effect.Effect<OrchestrationV2ThreadFamily, Error>;
1050 const family = (snapshotSequence: number, threads = [rows[0]!]) =>
1051 Effect.succeed({ snapshotSequence, threads });
1052 const unreachable: Read = () =>
1053 Effect.fail(
1054 new RpcClientError.RpcClientError({ reason: new Socket.SocketCloseError({ code: 1006 }) }),
1055 );
1056 const replay = Effect.fn("replay")(function* (reads: ReadonlyArray<Read>) {
1057 const asks = yield* Queue.unbounded<void>();
1058 const ref: { h?: Harness } = {};
1059 let call = 0;
1060 // Signals once the read has settled, so a failed read is handled before the next reconnect.
1061 const family = () =>
1062 Effect.suspend(() => reads[call++]!(ref.h!)).pipe(
1063 Effect.ensuring(Queue.offer(asks, undefined)),
1064 );
1065 const h = (ref.h = yield* makeHarness({ connected: false, family }));
1066 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), shellAt(1, rows.slice(0, 25), 0));
1067 yield* Effect.exit(h.commands.snooze.run(h.registry, snooze));
1068 const [entry] = yield* queued(h);
1069 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), shellAt(2));
1070 // A failed read keeps the snooze until the next time the shell is live.
1071 for (const _ of [0, ...reads.filter((read) => read === unreachable)]) {
1072 yield* h.reconnect("synchronizing");
1073 yield* h.reconnect();
1074 yield* Effect.raceFirst(Queue.take(asks), nothingPending(h));
1076 const sent: Array<string> = [];
1077 yield* Effect.forkChild(
1078 Effect.forever(
1079 Queue.take(h.requests).pipe(
1080 Effect.tap((request) => Effect.sync(() => sent.push(request.command.commandId))),
1081 Effect.flatMap((request) => Deferred.succeed(request.reply, { sequence: 9 })),
1082 ),
1083 ),
1084 );
1085 yield* nothingPending(h);
1086 return { sent, commandId: entry!.commandId, readCount: call };
1087 });
1088 const moveShell = (h: Harness, threads: typeof rows) =>
1089 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), shellAt(3, threads));
1090 const deltaDuringRead: Read = (h) =>
1091 Effect.suspend(() => (moveShell(h, rows.slice(1)), family(2)));
1092​
1093 it.effect.each<[string, ReadonlyArray<Read>, boolean]>([
1094 ["sends it when the host still has the thread unchanged", [() => family(2)], true],
1095 ["keeps it while the host cannot be asked", [unreachable, () => family(2)], true],
1097 "drops it for a host snooze the shell has not caught up with",
1099 (h) =>
1100 Effect.suspend(() => {
1101 moveShell(h, [{ ...rows[0]!, title: "Renamed" }, ...rows.slice(1)]);
1102 return family(4, [{ ...rows[0]!, snoozedUntil: FUTURE, snoozedAt: NOW }]);
1103 }),
1104 ],
1105 false,
1106 ],
1107 ["reads again after a newer shell, then sends it", [deltaDuringRead, () => family(3)], true],
1108 ])("%s", ([, reads, sends]) =>
1109 Effect.gen(function* () {
1110 const { sent, commandId, readCount } = yield* replay(reads);
1111 expect(readCount).toBe(reads.length);
1112 expect(sent).toEqual(sends ? [commandId] : []);
1113 }),
1114 );
1115 });
1116});