Open History to see the last commit
1import { presentThreadShell } from "./models.ts";
2import { threadKey } from "./entities.ts";
3import {
4 EnvironmentId,
5 EventId,
6 MessageId,
7 ThreadId,
8 type ScopedThreadRef,
9 NodeId,
10 ProviderSessionId,
11 RuntimeRequestId,
12 TurnItemId,
13 type OrchestrationV2ThreadProjection,
14} from "@t3tools/contracts";
15import { describe, expect, it, vi } from "vite-plus/test";
16import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity";
17import * as Cause from "effect/Cause";
18import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
19import { v2Now, v2Projection, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
20import {
21 createQuestionHistoryProjector,
22 createChildThreadApprovalsAtom,
23 type PendingThreadRequests,
24 derivePendingThreadRequests,
25 declinePendingApprovals,
26 sendApprovalFeedback,
27 makeThreadRequestsResolvedAnnouncer,
28 onThreadRequestsResolved,
29 pruneResolvedUserInputDrafts,
30 resolvedQuestionDraftKeys,
31 seedUserInputDraftAnswers,
32 userInputDraftKey,
33 type ApprovalResponder,
34 type ThreadRequestsResolved,
35 type ThreadPendingApproval,
36} from "./threadRequests.ts";
37
38const requestId = RuntimeRequestId.make("async-question");
39const nodeId = NodeId.make("async-question-node");
40
41describe("declining approvals before sending", () => {
42 const approval: ThreadPendingApproval = {
43 requestId,
44 requestKind: "command",
45 createdAt: "2026-10-19T00:00:00Z",
46 responseCapability: "live",
47 };
48 const second: ThreadPendingApproval = {
49 ...approval,
50 requestId: RuntimeRequestId.make("second-approval"),
51 };
52
53 it("declines every pending approval before the send continues", async () => {
54 let resolve!: (value: Awaited<ReturnType<ApprovalResponder>>) => void;
55 const firstResponse = new Promise<Awaited<ReturnType<ApprovalResponder>>>((done) => {
56 resolve = done;
57 });
58 const respond = vi.fn<ApprovalResponder>(async (id) =>
59 id === requestId ? firstResponse : AsyncResult.success(undefined),
60 );
61 const send = vi.fn();
62 const submission = (async () => {
63 if (await declinePendingApprovals([approval, second], respond)) send();
64 })();
65 expect(respond).toHaveBeenCalledWith(requestId, "decline");
66 expect(send).not.toHaveBeenCalled();
67 resolve(AsyncResult.success(undefined));
68 await submission;
69 expect(respond).toHaveBeenCalledWith(second.requestId, "decline");
70 expect(send).toHaveBeenCalledOnce();
71 });
72
73 it.each([AsyncResult.failure(Cause.fail("decline failed")), undefined])(
74 "does not send when a decline is unsuccessful: %s",
75 async (response) => {
76 const send = vi.fn();
77 if (await declinePendingApprovals([approval], async () => response)) send();
78 expect(send).not.toHaveBeenCalled();
79 },
80 );
81
82 it("skips approvals the provider can no longer answer", async () => {
83 const respond = vi.fn(async () => AsyncResult.success(undefined));
84 expect(
85 await declinePendingApprovals(
86 [{ ...approval, responseCapability: "not_resumable" }],
87 respond,
88 ),
89 ).toBe(true);
90 expect(respond).not.toHaveBeenCalled();
91 });
92
93 it("sends feedback only to the displayed request, leaving other approvals pending", async () => {
94 const respond = vi.fn<ApprovalResponder>(async () => AsyncResult.success(undefined));
95 const pending = derivePendingThreadRequests({
96 runtimeRequests: [
97 {
98 ...projection.runtimeRequests[0]!,
99 kind: "command",
100 responseCapability: {
101 type: "live",
102 providerSessionId: ProviderSessionId.make("claude-session"),
103 supportsFeedback: true,
104 },
105 },
106 { ...projection.runtimeRequests[0]!, id: second.requestId, kind: "command" },
107 ],
108 turnItems: [],
109 });
110 expect(await sendApprovalFeedback(pending.approvals[0]!, " Safer please. ", respond)).toBe(
111 true,
112 );
113 expect(respond.mock.calls).toEqual([[approval.requestId, "decline", "Safer please."]]);
114 });
115
116 it("keeps feedback unsent when unsupported, stale, empty or rejected", async () => {
117 const respond = vi.fn<ApprovalResponder>(async () => AsyncResult.failure(Cause.fail("failed")));
118 expect(await sendApprovalFeedback(approval, "Safer please.", respond)).toBe(false);
119 expect(
120 await sendApprovalFeedback(
121 { ...approval, supportsFeedback: true, responseCapability: "not_resumable" },
122 "Safer please.",
123 respond,
124 ),
125 ).toBe(false);
126 expect(await sendApprovalFeedback({ ...approval, supportsFeedback: true }, " ", respond)).toBe(
127 false,
128 );
129 expect(respond).not.toHaveBeenCalled();
130 expect(
131 await sendApprovalFeedback({ ...approval, supportsFeedback: true }, "Safer please.", respond),
132 ).toBe(false);
133 });
134});
135
136describe("pruning resolved user input drafts", () => {
137 const answered = userInputDraftKey("env", "thread", "answered");
138 const pending = userInputDraftKey("env", "thread", "pending");
139 const otherThread = userInputDraftKey("env", "thread-2", "answered");
140 const otherEnvironment = userInputDraftKey("env-2", "thread", "answered");
141 const drafts = {
142 [answered]: 1,
143 [pending]: 2,
144 [otherThread]: 3,
145 [otherEnvironment]: 4,
146 };
147
148 it("drops only the thread's requests that are no longer pending", () => {
149 expect(pruneResolvedUserInputDrafts(drafts, "env", "thread", ["pending"])).toEqual({
150 [pending]: 2,
151 [otherThread]: 3,
152 [otherEnvironment]: 4,
153 });
154 });
155
156 it("returns the same record when nothing resolved", () => {
157 expect(pruneResolvedUserInputDrafts(drafts, "env", "thread", ["answered", "pending"])).toBe(
158 drafts,
159 );
160 });
161});
162
163describe("resolved question draft keys", () => {
164 const prefix = "env:question-thread-";
165 const key = (request: string, question: string) =>
166 `${prefix}${encodeURIComponent(JSON.stringify([request, question]))}`;
167
168 it("returns the thread's keys for requests that are no longer pending", () => {
169 const keys = [
170 key("pending", "first"),
171 key("pending", "second"),
172 key("pending-2", "first"),
173 key("answered", "first"),
174 "env:question-other-thread-x",
175 ];
176 expect(resolvedQuestionDraftKeys(keys, prefix, [RuntimeRequestId.make("pending")])).toEqual([
177 key("pending-2", "first"),
178 key("answered", "first"),
179 ]);
180 });
181});
182
183describe("announcing resolved thread requests", () => {
184 const environmentId = EnvironmentId.make("env");
185 const threadId = v2Projection.thread.id;
186 const first = RuntimeRequestId.make("first");
187 const second = RuntimeRequestId.make("second");
188
189 function record() {
190 const events: ThreadRequestsResolved[] = [];
191 const unsubscribe = onThreadRequestsResolved((event) => events.push(event));
192 return { events, [Symbol.dispose]: unsubscribe };
193 }
194
195 it("announces the first projection, then only when a request leaves pending", () => {
196 using recorder = record();
197 const announce = makeThreadRequestsResolvedAnnouncer(environmentId, threadId);
198
199 announce([first]);
200 announce([first, second]);
201 announce([first, second]);
202 announce([second]);
203
204 expect(recorder.events).toEqual([
205 { environmentId, threadId, pendingRequestIds: [first] },
206 { environmentId, threadId, pendingRequestIds: [second] },
207 ]);
208 });
209});
210
211describe("initial user input drafts", () => {
212 const questions = [
213 { id: "editor", initialAnswer: " Proposed commit\n\n" },
214 { id: "empty", initialAnswer: "" },
215 { id: "ordinary" },
216 { id: "choices", initialAnswer: "Ignore this", allowCustomAnswer: false },
217 ];
218
219 it("seeds editable answers and preserves edits and selections on later snapshots", () => {
220 const seeded = seedUserInputDraftAnswers(questions, {});
221 expect(seeded).toEqual({
222 editor: { customAnswer: " Proposed commit\n\n" },
223 empty: { customAnswer: "" },
224 });
225 const edits = {
226 ...seeded,
227 editor: { customAnswer: "" },
228 empty: { selectedOptionValues: ["empty"], customAnswer: "" },
229 };
230 expect(seedUserInputDraftAnswers(questions, edits)).toEqual(edits);
231 expect(
232 seedUserInputDraftAnswers(questions, { editor: { customAnswer: "Edited commit" } }).editor,
233 ).toEqual({ customAnswer: "Edited commit" });
234 expect(seedUserInputDraftAnswers(questions, {}).editor).toEqual({
235 customAnswer: " Proposed commit\n\n",
236 });
237 });
238});
239const projection: OrchestrationV2ThreadProjection = {
240 ...v2Projection,
241 runtimeRequests: [
242 {
243 id: requestId,
244 nodeId,
245 providerTurnId: null,
246 nativeRequestRef: null,
247 kind: "user_input",
248 status: "pending",
249 responseCapability: { type: "message" },
250 createdAt: v2Now,
251 resolvedAt: null,
252 },
253 ],
254 turnItems: [
255 {
256 id: TurnItemId.make("async-question-item"),
257 threadId: v2Projection.thread.id,
258 runId: null,
259 nodeId,
260 providerThreadId: null,
261 providerTurnId: null,
262 nativeItemRef: null,
263 parentItemId: null,
264 ordinal: 0,
265 status: "completed",
266 title: null,
267 startedAt: v2Now,
268 completedAt: v2Now,
269 updatedAt: v2Now,
270 type: "user_input_request",
271 requestId,
272 responseMode: "message",
273 questions: [
274 {
275 id: "next",
276 header: "Next",
277 question: "What should happen next?",
278 required: true,
279 allowCustomAnswer: false,
280 options: [{ label: "Continue", value: " continue ", description: "Resume work" }],
281 },
282 ],
283 },
284 ],
285};
286
287describe("pending v2 questions", () => {
288 it("keeps message responses available after the originating runtime exits", () => {
289 expect(projection.providerSessions).toEqual([]);
290 expect(derivePendingThreadRequests(projection).userInputs).toEqual([
291 {
292 requestId,
293 createdAt: "2026-06-20T00:00:00.000Z",
294 responseCapability: "message",
295 responseMode: "message",
296 dismissible: true,
297 questions: [
298 {
299 id: "next",
300 header: "Next",
301 question: "What should happen next?",
302 required: true,
303 allowCustomAnswer: false,
304 multiSelect: false,
305 options: [{ label: "Continue", value: " continue ", description: "Resume work" }],
306 },
307 ],
308 },
309 ]);
310 });
311
312 it("only marks asynchronous questions as dismissible", () => {
313 const live = {
314 ...projection,
315 runtimeRequests: projection.runtimeRequests.map((request) => ({
316 ...request,
317 responseCapability: {
318 type: "live" as const,
319 providerSessionId: ProviderSessionId.make("live-session"),
320 },
321 })),
322 turnItems: projection.turnItems.map((item) =>
323 item.type === "user_input_request" ? { ...item, responseMode: undefined } : item,
324 ),
325 };
326 expect(derivePendingThreadRequests(live).userInputs[0]?.dismissible).toBe(false);
327 });
328});
329
330it("restores old text answers without mutating history or replacing unchanged rows", () => {
331 const project = createQuestionHistoryProjector();
332 const item = projection.turnItems[0]!;
333 const row = {
334 item,
335 position: 0,
336 sourceItemId: item.id,
337 sourceThreadId: item.threadId,
338 visibility: "local" as const,
339 };
340 const rows = [row];
341 const pending = { visibleTurnItems: rows, runtimeRequests: projection.runtimeRequests };
342 expect(project(pending)).toBe(rows);
343 const answered = {
344 ...pending,
345 runtimeRequests: [
346 {
347 ...projection.runtimeRequests[0]!,
348 status: "resolved" as const,
349 answers: { next: "Continue" },
350 },
351 ],
352 };
353 const result = project(answered);
354 expect(result[0]?.item).toMatchObject({
355 questionAnswer: {
356 answers: { next: "Continue" },
357 attachmentsByQuestionId: {},
358 questionTextById: { next: "What should happen next?" },
359 },
360 });
361 expect(row.item).not.toHaveProperty("questionAnswer");
362 expect(project(answered)).toBe(result);
363 expect(project({ ...answered, visibleTurnItems: [...rows] })[0]).toBe(result[0]);
364});
365
366type QuestionItem = Extract<
367 OrchestrationV2ThreadProjection["turnItems"][number],
368 { readonly type: "user_input_request" }
369>;
370
371describe("question history through exact row replacements", () => {
372 const baseItem = {
373 threadId: v2Projection.thread.id,
374 runId: null,
375 nodeId,
376 providerThreadId: null,
377 providerTurnId: null,
378 nativeItemRef: null,
379 parentItemId: null,
380 status: "running" as const,
381 title: null,
382 startedAt: v2Now,
383 completedAt: null,
384 updatedAt: v2Now,
385 };
386 const assistantItem = (ordinal: number, text = "Hel") => ({
387 ...baseItem,
388 id: TurnItemId.make(`assistant-${ordinal}`),
389 ordinal,
390 type: "assistant_message" as const,
391 messageId: MessageId.make(`message-${ordinal}`),
392 text,
393 streaming: true,
394 });
395 const localRow = (
396 item: OrchestrationV2ThreadProjection["turnItems"][number],
397 position: number,
398 ) => ({
399 item,
400 position,
401 sourceItemId: item.id,
402 sourceThreadId: item.threadId,
403 visibility: "local" as const,
404 });
405 const updated = (
406 current: OrchestrationV2ThreadProjection,
407 item: OrchestrationV2ThreadProjection["turnItems"][number],
408 ) =>
409 applyOrchestrationV2ProjectionEvent(current, {
410 id: EventId.make(`event-${item.id}`),
411 type: "turn-item.updated",
412 threadId: current.thread.id,
413 occurredAt: v2Now,
414 payload: item,
415 })!;
416
417 it("reads only the replaced row and leaves the request index alone", () => {
418 const size = 1_000;
419 const counts = { items: 0, requestIds: 0 };
420 const items = Array.from({ length: size }, (_, index) => assistantItem(index));
421 const countedRows = items.map((item, index) => {
422 const row = localRow(item, index);
423 return Object.defineProperty(row, "item", {
424 enumerable: true,
425 get: () => {
426 counts.items += 1;
427 return item;
428 },
429 });
430 });
431 const countedRequests = Array.from({ length: 400 }, (_, index) => {
432 const request = {
433 ...projection.runtimeRequests[0]!,
434 id: RuntimeRequestId.make(`request-${index}`),
435 };
436 return Object.defineProperty(request, "id", {
437 enumerable: true,
438 get: () => {
439 counts.requestIds += 1;
440 return RuntimeRequestId.make(`request-${index}`);
441 },
442 });
443 });
444 const initial: OrchestrationV2ThreadProjection = {
445 ...v2Projection,
446 turnItems: items,
447 visibleTurnItems: countedRows,
448 runtimeRequests: countedRequests,
449 };
450 const project = createQuestionHistoryProjector();
451 const scan = (current: OrchestrationV2ThreadProjection) => {
452 counts.items = 0;
453 counts.requestIds = 0;
454 const result = project(current);
455 return { result, ...counts };
456 };
457 expect(scan(initial)).toMatchObject({ items: size, requestIds: 400 });
458
459 const adjacent = updated(initial, assistantItem(size - 1, "Hello"));
460 const hinted = scan(adjacent);
461 expect(hinted.result).toBe(adjacent.visibleTurnItems);
462 expect(hinted).toMatchObject({ items: 0, requestIds: 0 });
463
464 // A skipped delta has no hint for this exact pair, so it scans again.
465 const skipped = updated(
466 updated(adjacent, assistantItem(size - 1, "Hello t")),
467 assistantItem(size - 1, "Hello there"),
468 );
469 const fallback = scan(skipped);
470 expect(fallback.result).toBe(skipped.visibleTurnItems);
471 expect(fallback).toMatchObject({ items: size - 1, requestIds: 0 });
472 });
473
474 it("matches a full projection through streamed rows, request changes and answers", () => {
475 const question = projection.turnItems[0] as QuestionItem;
476 const resolved = (answers: Record<string, string>) => ({
477 ...projection.runtimeRequests[0]!,
478 status: "resolved" as const,
479 answers,
480 });
481 const explicitRequestId = RuntimeRequestId.make("explicit-question");
482 const explicitAnswer = {
483 requestId: explicitRequestId,
484 answers: { next: "Explicit" },
485 attachmentsByQuestionId: {},
486 questionTextById: { next: "What should happen next?" },
487 };
488 const unanswered: QuestionItem = {
489 ...question,
490 id: TurnItemId.make("explicit-question-item"),
491 ordinal: 1,
492 requestId: explicitRequestId,
493 };
494 const explicit: QuestionItem = { ...unanswered, questionAnswer: explicitAnswer };
495 const explicitRequest = {
496 ...resolved({ next: "From request" }),
497 id: explicitRequestId,
498 };
499 const stream = assistantItem(2);
500 const inherited = {
501 ...localRow({ ...question, id: TurnItemId.make("inherited-question-item") }, 3),
502 visibility: "inherited" as const,
503 sourceThreadId: ThreadId.make("parent-thread"),
504 };
505 const turnItems = [question, explicit, stream];
506 let current: OrchestrationV2ThreadProjection = {
507 ...v2Projection,
508 turnItems,
509 visibleTurnItems: [...turnItems.map(localRow), inherited],
510 runtimeRequests: [projection.runtimeRequests[0]!, explicitRequest],
511 };
512 const project = createQuestionHistoryProjector();
513 const step = (next: OrchestrationV2ThreadProjection) => {
514 current = next;
515 const result = project(next);
516 expect(result).toEqual(createQuestionHistoryProjector()(next));
517 return result;
518 };
519 const answerOf = (rows: ReadonlyArray<{ readonly item: unknown }>, index: number) =>
520 (rows[index]!.item as { readonly questionAnswer?: { readonly answers: unknown } })
521 .questionAnswer?.answers;
522
523 expect(step(current)).toBe(current.visibleTurnItems);
524 expect(step(updated(current, assistantItem(2, "Hello")))).toBe(current.visibleTurnItems);
525
526 // The last duplicate request wins, and every row asking it gets the answer.
527 const answered = step({
528 ...current,
529 runtimeRequests: [
530 projection.runtimeRequests[0]!,
531 resolved({ next: "Continue" }),
532 explicitRequest,
533 ],
534 });
535 expect(answerOf(answered, 0)).toEqual({ next: "Continue" });
536 expect(answerOf(answered, 1)).toEqual({ next: "Explicit" });
537 expect(answerOf(answered, 3)).toEqual({ next: "Continue" });
538
539 const whileOverlaid = step(updated(current, assistantItem(2, "Hello there")));
540 expect(whileOverlaid[0]).toBe(answered[0]);
541 expect(whileOverlaid[3]).toBe(answered[3]);
542
543 const changedAnswer = step({
544 ...current,
545 runtimeRequests: [resolved({ next: "Stop" }), explicitRequest],
546 });
547 expect(answerOf(changedAnswer, 0)).toEqual({ next: "Stop" });
548
549 const reopened = step({
550 ...current,
551 runtimeRequests: [projection.runtimeRequests[0]!, explicitRequest],
552 });
553 expect(reopened).toBe(current.visibleTurnItems);
554
555 // Dropping an explicit answer falls back to its resolved request.
556 const restored = step(updated(current, unanswered));
557 expect(answerOf(restored, 1)).toEqual({ next: "From request" });
558
559 const retitled: QuestionItem = {
560 ...unanswered,
561 questions: [{ ...question.questions[0]!, question: "Now what?" }],
562 };
563 const retitledRows = step(updated(current, retitled));
564 expect(retitledRows[1]!.item).toMatchObject({
565 questionAnswer: { questionTextById: { next: "Now what?" } },
566 });
567 });
568});
569
570it("loads only child approvals and retains their destination across environments", () => {
571 const local = EnvironmentId.make("local");
572 const remote = EnvironmentId.make("remote");
573 const parent = { environmentId: local, threadId: ThreadId.make("parent") };
574 const childId = ThreadId.make("child");
575 const children = Atom.make(
576 [local, remote].map((environmentId) => ({
577 ...presentThreadShell(environmentId, v2ThreadShell),
578 id: childId,
579 title: environmentId,
580 hasPendingApprovals: true,
581 })),
582 );
583 const details = Atom.family((key: string) =>
584 Atom.make<PendingThreadRequests | null>({
585 approvals: [
586 {
587 requestId: RuntimeRequestId.make(key),
588 requestKind: "command",
589 createdAt: "2026-10-19T00:00:00Z",
590 responseCapability: "live",
591 },
592 ],
593 userInputs: [],
594 }),
595 );
596 const readDetails = vi.fn((ref: ScopedThreadRef) => details(threadKey(ref)));
597 const approvalsAtom = createChildThreadApprovalsAtom({
598 childThreadInputsAtom: () => children,
599 pendingRequestsAtom: readDetails,
600 });
601 const registry = AtomRegistry.make();
602 const unmount = registry.mount(approvalsAtom(parent));
603 const pending = registry.get(approvalsAtom(parent));
604 expect(pending.map((entry) => entry.thread)).toEqual(
605 [local, remote].map((environmentId) => ({ environmentId, threadId: childId })),
606 );
607 expect(pending.map((entry) => entry.title)).toEqual(["local", "remote"]);
608 registry.set(details(threadKey({ environmentId: remote, threadId: childId })), {
609 approvals: [],
610 userInputs: [],
611 });
612 expect(registry.get(approvalsAtom(parent))).toEqual([pending[0]]);
613 readDetails.mockClear();
614 registry.set(
615 children,
616 registry
617 .get(children)
618 .map((child) => ({ ...child, hasPendingApprovals: false, hasPendingUserInput: true })),
619 );
620 expect(registry.get(approvalsAtom(parent))).toEqual([]);
621 expect(readDetails).not.toHaveBeenCalled();
622 unmount();
623 registry.dispose();
624});