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

threadCommands.test.ts

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