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

threadCommands.test.ts

509 lines20.9 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 Crypto from "effect/Crypto";
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 Crypto.Crypto,
121 Crypto.make({
122 randomBytes: (size) => new Uint8Array(size),
123 digest: (_algorithm, data) => Effect.succeed(data),
124 }),
125 ),
126 Layer.succeed(
127 ThreadHistoryController.ThreadHistoryController,
128 ThreadHistoryController.ThreadHistoryController.of({
129 register: () => Effect.die("unused"),
130 unregister: () => Effect.void,
131 loadEarlier: () => options?.loadEarlier?.() ?? Effect.die("unused"),
132 reconcilePendingWork: (_environmentId, threadId) =>
133 options?.reconcilePendingWork?.(threadId) ?? Queue.offer(reconciled, threadId),
134 }),
135 ),
136 ),
137 );
138 const snapshotAtom = Atom.family((_environmentId: EnvironmentId) => Atom.make(SNAPSHOT));
139 const commands = createThreadEnvironmentAtoms(runtime, snapshotAtom);
140 const registry = AtomRegistry.make();
141 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
142 const visibleAtom = commands.snapshotAtom(ENVIRONMENT_ID);
143 registry.mount(visibleAtom);
144 return { registry, commands, snapshotAtom, visibleAtom, requests, reconciled };
145});
146​
147describe("history loading", () => {
148 it.effect("sends a message on the thread while earlier history is loading", () =>
149 Effect.gen(function* () {
150 const historyStarted = yield* Deferred.make<void>();
151 const historyReply =
152 yield* Deferred.make<ThreadHistoryController.ThreadHistoryLoadEarlierResult>();
153 const h = yield* makeHarness({
154 loadEarlier: () =>
155 Deferred.succeed(historyStarted, undefined).pipe(
156 Effect.andThen(Deferred.await(historyReply)),
157 ),
158 });
159 yield* Effect.addFinalizer(() => Deferred.succeed(historyReply, { _tag: "loaded" }));
160 const history = h.commands.loadEarlierHistory.run(h.registry, {
161 environmentId: ENVIRONMENT_ID,
162 input: { threadId: THREAD_ID },
163 });
164 yield* Deferred.await(historyStarted);
165 const send = h.commands.startTurn.run(h.registry, {
166 environmentId: ENVIRONMENT_ID,
167 input: {
168 threadId: THREAD_ID,
169 message: {
170 messageId: MessageId.make("message"),
171 role: "user",
172 text: "Send while history loads",
173 attachments: [],
174 },
175 runtimeMode: "full-access",
176 interactionMode: "default",
177 dispatchMode: "start",
178 },
179 });
180 // Dispatched after Send on another thread, so it arrives first only if Send is queued.
181 const controlThreadId = ThreadId.make("control-thread");
182 const control = h.commands.interruptTurn.run(h.registry, {
183 environmentId: ENVIRONMENT_ID,
184 input: { threadId: controlThreadId, runId: RunId.make("control-run") },
185 });
186 const first = yield* Queue.take(h.requests);
187 yield* Deferred.succeed(first.reply, { sequence: 1 });
188 yield* Deferred.succeed(historyReply, { _tag: "loaded" });
189 const second = yield* Queue.take(h.requests);
190 yield* Deferred.succeed(second.reply, { sequence: 2 });
191 const results = yield* Effect.promise(() => Promise.all([history, send, control]));
192​
193 expect(first.command).toMatchObject({ type: "message.dispatch", threadId: THREAD_ID });
194 expect(second.command).toMatchObject({ type: "run.interrupt", threadId: controlThreadId });
195 expect(results.map((value) => value._tag)).toEqual(["Success", "Success", "Success"]);
196 }),
197 );
198});
199​
200describe("interrupt turn", () => {
201 // A stale cached item has nothing left to interrupt, so the server can reject Stop.
202 it.effect("reconciles pending work when the server rejects the interrupt", () =>
203 Effect.gen(function* () {
204 const h = yield* makeHarness();
205 const result = h.commands.interruptTurn.run(h.registry, {
206 environmentId: ENVIRONMENT_ID,
207 input: { threadId: THREAD_ID, runId: RunId.make("finished-run") },
208 });
209 const request = yield* Queue.take(h.requests);
210 expect(request.command.type).toBe("run.interrupt");
211 yield* Deferred.fail(request.reply, new Error("Run is not interruptible"));
212 expect((yield* Effect.promise(() => result))._tag).toBe("Failure");
213 expect(yield* Queue.take(h.reconciled)).toBe(THREAD_ID);
214 }),
215 );
216​
217 // Mirrors the thread state's handler: the lookup runs in the thread's scope and is joined.
218 const stopWithBlockedLookup = Effect.fn("stopWithBlockedLookup")(function* () {
219 const threadScope = yield* Scope.make();
220 const asked = yield* Deferred.make<void>();
221 const h = yield* makeHarness({
222 reconcilePendingWork: () =>
223 Deferred.succeed(asked, undefined).pipe(
224 Effect.andThen(Effect.never),
225 Effect.forkIn(threadScope),
226 Effect.flatMap(Fiber.join),
227 ),
228 });
229 const result = h.commands.interruptTurn.run(h.registry, {
230 environmentId: ENVIRONMENT_ID,
231 input: { threadId: THREAD_ID, runId: RunId.make("running-run") },
232 });
233 const request = yield* Queue.take(h.requests);
234 yield* Deferred.succeed(request.reply, { sequence: 1 });
235 yield* Deferred.await(asked);
236 return { threadScope, result };
237 });
238​
239 it.effect("resolves Stop without waiting for the pending work lookup", () =>
240 Effect.gen(function* () {
241 const { threadScope, result } = yield* stopWithBlockedLookup();
242 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
243 yield* Scope.close(threadScope, Exit.void);
244 }),
245 );
246​
247 it.effect("keeps an accepted Stop when the thread closes during the lookup", () =>
248 Effect.gen(function* () {
249 const { threadScope, result } = yield* stopWithBlockedLookup();
250 yield* Scope.close(threadScope, Exit.void);
251 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
252 }),
253 );
254});
255​
256describe("remote thread lifecycle commands", () => {
257 const actions = [
258 ["settle", {}, { settledOverride: "settled", pinnedAt: null, snoozedUntil: null }],
259 ["unsettle", { reason: "user" }, { settledOverride: "active", settledAt: null }],
260 ["snooze", { snoozedUntil: "2099-01-01T00:00:00.000Z" }, { snoozedUntil: FUTURE }],
261 ["unsnooze", { reason: "user" }, { snoozedUntil: null, snoozedAt: null }],
262 ["pin", { orderKey: "a" }, { pinnedAt: expect.any(Object), pinOrderKey: "a" }],
263 ["unpin", {}, { pinnedAt: null, pinOrderKey: null }],
264 ["setAutoSettle", { enabled: false }, { autoSettleDisabledAt: expect.any(Object) }],
265 ["reorderPin", { orderKey: "b" }, { pinOrderKey: "b" }],
266 ["reorderActive", { orderKey: "b" }, { activeOrderKey: "b" }],
267 ] as const;
268​
269 it.effect.each(actions)(
270 "shows %s before a delayed remote reply and rolls back a rejection",
271 ([action, input, expected]) =>
272 Effect.gen(function* () {
273 const h = yield* makeHarness();
274 const source = h.snapshotAtom(ENVIRONMENT_ID);
275 const initial = {
276 ...SNAPSHOT,
277 threads: [
278 {
279 ...SNAPSHOT.threads[0]!,
280 ...(action === "unsettle" || action === "pin"
281 ? { settledOverride: "settled" as const, settledAt: NOW }
282 : {}),
283 ...(action === "unsnooze" || action === "settle" || action === "pin"
284 ? { snoozedUntil: FUTURE, snoozedAt: NOW }
285 : {}),
286 ...(action === "unpin" || action === "settle"
287 ? { pinnedAt: NOW, pinOrderKey: "a" }
288 : {}),
289 },
290 ],
291 };
292 h.registry.set(source, initial);
293 const result = h.commands[action].run(h.registry, {
294 environmentId: ENVIRONMENT_ID,
295 input: {
296 threadId: THREAD_ID,
297 commandId: CommandId.make(action),
298 reason: "user",
299 enabled: false,
300 orderKey: "a",
301 snoozedUntil: "2099-01-01T00:00:00.000Z",
302 ...input,
303 },
304 });
305 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(expected);
306 const request = yield* Queue.take(h.requests);
307 expect(h.registry.get(source)).toBe(initial);
308 yield* Deferred.fail(request.reply, new Error("Remote rejected the action"));
309 expect((yield* Effect.promise(() => result))._tag).toBe("Failure");
310 expect(h.registry.get(h.visibleAtom)).toBe(initial);
311 }),
312 );
313​
314 it.effect("restamps snoozedAt when re-snoozing to the same wake time", () =>
315 Effect.gen(function* () {
316 const h = yield* makeHarness();
317 const earlierSnoozedAt = DateTime.makeUnsafe("2000-01-01T00:00:00.000Z");
318 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), {
319 ...SNAPSHOT,
320 threads: [{ ...SNAPSHOT.threads[0]!, snoozedUntil: FUTURE, snoozedAt: earlierSnoozedAt }],
321 });
322 const result = h.commands.snooze.run(h.registry, {
323 environmentId: ENVIRONMENT_ID,
324 input: { threadId: THREAD_ID, snoozedUntil: DateTime.formatIso(FUTURE) },
325 });
326 const snoozedAt = h.registry.get(h.visibleAtom)?.threads[0]?.snoozedAt;
327 expect(DateTime.toEpochMillis(snoozedAt!)).toBeGreaterThan(
328 DateTime.toEpochMillis(earlierSnoozedAt),
329 );
330 const request = yield* Queue.take(h.requests);
331 yield* Deferred.succeed(request.reply, { sequence: 2 });
332 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
333 }),
334 );
335​
336 it.effect("keeps the preview after acknowledgement until the matching shell update arrives", () =>
337 Effect.gen(function* () {
338 const h = yield* makeHarness();
339 const result = h.commands.settle.run(h.registry, {
340 environmentId: ENVIRONMENT_ID,
341 input: { threadId: THREAD_ID },
342 });
343 const request = yield* Queue.take(h.requests);
344 yield* Deferred.succeed(request.reply, { sequence: 3 });
345 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
346 const changed = {
347 ...SNAPSHOT,
348 snapshotSequence: 2,
349 threads: [{ ...SNAPSHOT.threads[0]!, title: "Renamed remotely" }],
350 };
351 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), changed);
352 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject({
353 title: "Renamed remotely",
354 settledOverride: "settled",
355 });
356 const confirmed = {
357 ...changed,
358 snapshotSequence: 3,
359 threads: [
360 {
361 ...changed.threads[0]!,
362 settledOverride: "settled" as const,
363 settledAt: DateTime.makeUnsafe("2026-09-12T12:00:00.000Z"),
364 },
365 ],
366 };
367 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
368 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
369 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), { ...SNAPSHOT, snapshotSequence: 4 });
370 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBeNull();
371 }),
372 );
373​
374 it.effect(
375 "shows a queued reverse action immediately and preserves it if the earlier action fails",
376 () =>
377 Effect.gen(function* () {
378 const h = yield* makeHarness();
379 const settle = h.commands.settle.run(h.registry, {
380 environmentId: ENVIRONMENT_ID,
381 input: { threadId: THREAD_ID },
382 });
383 const first = yield* Queue.take(h.requests);
384 const unsettle = h.commands.unsettle.run(h.registry, {
385 environmentId: ENVIRONMENT_ID,
386 input: { threadId: THREAD_ID, reason: "user" },
387 });
388 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("active");
389 yield* Deferred.fail(first.reply, new Error("Settle rejected"));
390 yield* Effect.promise(() => settle);
391 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("active");
392 const second = yield* Queue.take(h.requests);
393 expect(second.command.type).toBe("thread.unsettle");
394 const confirmed = {
395 ...SNAPSHOT,
396 snapshotSequence: 2,
397 threads: [{ ...SNAPSHOT.threads[0]!, settledOverride: "active" as const }],
398 };
399 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
400 yield* Deferred.succeed(second.reply, { sequence: 2 });
401 yield* Effect.promise(() => unsettle);
402 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
403 }),
404 );
405​
406 it.effect("isolates environments and does not restore a remotely removed thread", () =>
407 Effect.gen(function* () {
408 const h = yield* makeHarness();
409 const otherEnvironment = EnvironmentId.make("other-remote");
410 const result = h.commands.settle.run(h.registry, {
411 environmentId: ENVIRONMENT_ID,
412 input: { threadId: THREAD_ID },
413 });
414 const request = yield* Queue.take(h.requests);
415 expect(h.registry.get(h.commands.snapshotAtom(otherEnvironment))).toBe(SNAPSHOT);
416 const removed = { ...SNAPSHOT, snapshotSequence: 2, threads: [] };
417 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), removed);
418 expect(h.registry.get(h.visibleAtom)?.threads).toEqual([]);
419 yield* Deferred.fail(request.reply, new Error("Thread removed"));
420 yield* Effect.promise(() => result);
421 expect(h.registry.get(h.visibleAtom)).toBe(removed);
422 }),
423 );
424​
425 const undoableActions = ["settle", "snooze"] as const;
426​
427 it.effect.each(undoableActions)("restores a confirmed %s when a queued undo fails", (action) =>
428 Effect.gen(function* () {
429 const h = yield* makeHarness();
430 const parked =
431 action === "settle" ? { settledOverride: "settled" as const } : { snoozedUntil: FUTURE };
432 const awake = action === "settle" ? { settledOverride: "active" } : { snoozedUntil: null };
433 const result = h.commands[action].run(h.registry, {
434 environmentId: ENVIRONMENT_ID,
435 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
436 });
437 const first = yield* Queue.take(h.requests);
438 const undo = h.commands[action === "settle" ? "unsettle" : "unsnooze"].run(h.registry, {
439 environmentId: ENVIRONMENT_ID,
440 input: { threadId: THREAD_ID, reason: "user" },
441 });
442 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
443 yield* Deferred.succeed(first.reply, { sequence: 2 });
444 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
445 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
446 const confirmed = {
447 ...SNAPSHOT,
448 snapshotSequence: 2,
449 threads: [{ ...SNAPSHOT.threads[0]!, ...parked }],
450 };
451 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
452 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
453 const second = yield* Queue.take(h.requests);
454 expect(second.command.type).toBe(action === "settle" ? "thread.unsettle" : "thread.unsnooze");
455 yield* Deferred.fail(second.reply, new Error("Undo rejected"));
456 expect((yield* Effect.promise(() => undo))._tag).toBe("Failure");
457 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
458 }),
459 );
460​
461 it.effect.each(undoableActions)(
462 "preserves a newer approval when the %s reply arrives after the shell",
463 (action) =>
464 Effect.gen(function* () {
465 const h = yield* makeHarness();
466 const result = h.commands[action].run(h.registry, {
467 environmentId: ENVIRONMENT_ID,
468 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
469 });
470 const request = yield* Queue.take(h.requests);
471 const newer = {
472 ...SNAPSHOT,
473 snapshotSequence: 3,
474 threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: APPROVAL }],
475 };
476 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), newer);
477 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(newer.threads[0]);
478 yield* Deferred.succeed(request.reply, { sequence: 2 });
479 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
480 expect(h.registry.get(h.visibleAtom)).toBe(newer);
481 }),
482 );
483​
484 it.effect.each(undoableActions)(
485 "shows an accepted %s while the shell still has an old input request",
486 (action) =>
487 Effect.gen(function* () {
488 const h = yield* makeHarness();
489 const stale = {
490 ...SNAPSHOT,
491 threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: USER_INPUT }],
492 };
493 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), stale);
494 const result = h.commands[action].run(h.registry, {
495 environmentId: ENVIRONMENT_ID,
496 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
497 });
498 const request = yield* Queue.take(h.requests);
499 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(stale.threads[0]);
500 yield* Deferred.succeed(request.reply, { sequence: 2 });
501 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
502 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(
503 action === "settle" ? { settledOverride: "settled" } : { snoozedUntil: FUTURE },
504 );
505 expect(h.registry.get(h.visibleAtom)?.threads[0]?.pendingRuntimeRequest).toBeNull();
506 expect(h.registry.get(h.snapshotAtom(ENVIRONMENT_ID))).toBe(stale);
507 }),
508 );
509});