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
239 it("seeds a question with the id __proto__ as its own draft", () => {
240 const seeded = seedUserInputDraftAnswers(
241 [
242 { id: "__proto__", initialAnswer: "Proposed" },
243 { id: "name", initialAnswer: "Control" },
244 ],
245 {},
246 );
247
248 expect(JSON.stringify(seeded)).toBe(
249 '{"__proto__":{"customAnswer":"Proposed"},"name":{"customAnswer":"Control"}}',
250 );
251 });
252});
253const projection: OrchestrationV2ThreadProjection = {
254 ...v2Projection,
255 runtimeRequests: [
256 {
257 id: requestId,
258 nodeId,
259 providerTurnId: null,
260 nativeRequestRef: null,
261 kind: "user_input",
262 status: "pending",
263 responseCapability: { type: "message" },
264 createdAt: v2Now,
265 resolvedAt: null,
266 },
267 ],
268 turnItems: [
269 {
270 id: TurnItemId.make("async-question-item"),
271 threadId: v2Projection.thread.id,
272 runId: null,
273 nodeId,
274 providerThreadId: null,
275 providerTurnId: null,
276 nativeItemRef: null,
277 parentItemId: null,
278 ordinal: 0,
279 status: "completed",
280 title: null,
281 startedAt: v2Now,
282 completedAt: v2Now,
283 updatedAt: v2Now,
284 type: "user_input_request",
285 requestId,
286 responseMode: "message",
287 questions: [
288 {
289 id: "next",
290 header: "Next",
291 question: "What should happen next?",
292 required: true,
293 allowCustomAnswer: false,
294 options: [{ label: "Continue", value: " continue ", description: "Resume work" }],
295 },
296 ],
297 },
298 ],
299};
300
301describe("pending v2 questions", () => {
302 it("keeps message responses available after the originating runtime exits", () => {
303 expect(projection.providerSessions).toEqual([]);
304 expect(derivePendingThreadRequests(projection).userInputs).toEqual([
305 {
306 requestId,
307 createdAt: "2026-06-20T00:00:00.000Z",
308 responseCapability: "message",
309 responseMode: "message",
310 dismissible: true,
311 questions: [
312 {
313 id: "next",
314 header: "Next",
315 question: "What should happen next?",
316 required: true,
317 allowCustomAnswer: false,
318 multiSelect: false,
319 options: [{ label: "Continue", value: " continue ", description: "Resume work" }],
320 },
321 ],
322 },
323 ]);
324 });
325
326 it("only marks asynchronous questions as dismissible", () => {
327 const live = {
328 ...projection,
329 runtimeRequests: projection.runtimeRequests.map((request) => ({
330 ...request,
331 responseCapability: {
332 type: "live" as const,
333 providerSessionId: ProviderSessionId.make("live-session"),
334 },
335 })),
336 turnItems: projection.turnItems.map((item) =>
337 item.type === "user_input_request" ? { ...item, responseMode: undefined } : item,
338 ),
339 };
340 expect(derivePendingThreadRequests(live).userInputs[0]?.dismissible).toBe(false);
341 });
342});
343
344it("restores old text answers without mutating history or replacing unchanged rows", () => {
345 const project = createQuestionHistoryProjector();
346 const item = projection.turnItems[0]!;
347 const row = {
348 item,
349 position: 0,
350 sourceItemId: item.id,
351 sourceThreadId: item.threadId,
352 visibility: "local" as const,
353 };
354 const rows = [row];
355 const pending = { visibleTurnItems: rows, runtimeRequests: projection.runtimeRequests };
356 expect(project(pending)).toBe(rows);
357 const answered = {
358 ...pending,
359 runtimeRequests: [
360 {
361 ...projection.runtimeRequests[0]!,
362 status: "resolved" as const,
363 answers: { next: "Continue" },
364 },
365 ],
366 };
367 const result = project(answered);
368 expect(result[0]?.item).toMatchObject({
369 questionAnswer: {
370 answers: { next: "Continue" },
371 attachmentsByQuestionId: {},
372 questionTextById: { next: "What should happen next?" },
373 },
374 });
375 expect(row.item).not.toHaveProperty("questionAnswer");
376 expect(project(answered)).toBe(result);
377 expect(project({ ...answered, visibleTurnItems: [...rows] })[0]).toBe(result[0]);
378});
379
380type QuestionItem = Extract<
381 OrchestrationV2ThreadProjection["turnItems"][number],
382 { readonly type: "user_input_request" }
383>;
384
385describe("question history through exact row replacements", () => {
386 const baseItem = {
387 threadId: v2Projection.thread.id,
388 runId: null,
389 nodeId,
390 providerThreadId: null,
391 providerTurnId: null,
392 nativeItemRef: null,
393 parentItemId: null,
394 status: "running" as const,
395 title: null,
396 startedAt: v2Now,
397 completedAt: null,
398 updatedAt: v2Now,
399 };
400 const assistantItem = (ordinal: number, text = "Hel") => ({
401 ...baseItem,
402 id: TurnItemId.make(`assistant-${ordinal}`),
403 ordinal,
404 type: "assistant_message" as const,
405 messageId: MessageId.make(`message-${ordinal}`),
406 text,
407 streaming: true,
408 });
409 const localRow = (
410 item: OrchestrationV2ThreadProjection["turnItems"][number],
411 position: number,
412 ) => ({
413 item,
414 position,
415 sourceItemId: item.id,
416 sourceThreadId: item.threadId,
417 visibility: "local" as const,
418 });
419 const updated = (
420 current: OrchestrationV2ThreadProjection,
421 item: OrchestrationV2ThreadProjection["turnItems"][number],
422 ) =>
423 applyOrchestrationV2ProjectionEvent(current, {
424 id: EventId.make(`event-${item.id}`),
425 type: "turn-item.updated",
426 threadId: current.thread.id,
427 occurredAt: v2Now,
428 payload: item,
429 })!;
430
431 it("reads only the replaced row and leaves the request index alone", () => {
432 const size = 1_000;
433 const counts = { items: 0, requestIds: 0 };
434 const items = Array.from({ length: size }, (_, index) => assistantItem(index));
435 const countedRows = items.map((item, index) => {
436 const row = localRow(item, index);
437 return Object.defineProperty(row, "item", {
438 enumerable: true,
439 get: () => {
440 counts.items += 1;
441 return item;
442 },
443 });
444 });
445 const countedRequests = Array.from({ length: 400 }, (_, index) => {
446 const request = {
447 ...projection.runtimeRequests[0]!,
448 id: RuntimeRequestId.make(`request-${index}`),
449 };
450 return Object.defineProperty(request, "id", {
451 enumerable: true,
452 get: () => {
453 counts.requestIds += 1;
454 return RuntimeRequestId.make(`request-${index}`);
455 },
456 });
457 });
458 const initial: OrchestrationV2ThreadProjection = {
459 ...v2Projection,
460 turnItems: items,
461 visibleTurnItems: countedRows,
462 runtimeRequests: countedRequests,
463 };
464 const project = createQuestionHistoryProjector();
465 const scan = (current: OrchestrationV2ThreadProjection) => {
466 counts.items = 0;
467 counts.requestIds = 0;
468 const result = project(current);
469 return { result, ...counts };
470 };
471 expect(scan(initial)).toMatchObject({ items: size, requestIds: 400 });
472
473 const adjacent = updated(initial, assistantItem(size - 1, "Hello"));
474 const hinted = scan(adjacent);
475 expect(hinted.result).toBe(adjacent.visibleTurnItems);
476 expect(hinted).toMatchObject({ items: 0, requestIds: 0 });
477
478 // A skipped delta has no hint for this exact pair, so it scans again.
479 const skipped = updated(
480 updated(adjacent, assistantItem(size - 1, "Hello t")),
481 assistantItem(size - 1, "Hello there"),
482 );
483 const fallback = scan(skipped);
484 expect(fallback.result).toBe(skipped.visibleTurnItems);
485 expect(fallback).toMatchObject({ items: size - 1, requestIds: 0 });
486 });
487
488 it("matches a full projection through streamed rows, request changes and answers", () => {
489 const question = projection.turnItems[0] as QuestionItem;
490 const resolved = (answers: Record<string, string>) => ({
491 ...projection.runtimeRequests[0]!,
492 status: "resolved" as const,
493 answers,
494 });
495 const explicitRequestId = RuntimeRequestId.make("explicit-question");
496 const explicitAnswer = {
497 requestId: explicitRequestId,
498 answers: { next: "Explicit" },
499 attachmentsByQuestionId: {},
500 questionTextById: { next: "What should happen next?" },
501 };
502 const unanswered: QuestionItem = {
503 ...question,
504 id: TurnItemId.make("explicit-question-item"),
505 ordinal: 1,
506 requestId: explicitRequestId,
507 };
508 const explicit: QuestionItem = { ...unanswered, questionAnswer: explicitAnswer };
509 const explicitRequest = {
510 ...resolved({ next: "From request" }),
511 id: explicitRequestId,
512 };
513 const stream = assistantItem(2);
514 const inherited = {
515 ...localRow({ ...question, id: TurnItemId.make("inherited-question-item") }, 3),
516 visibility: "inherited" as const,
517 sourceThreadId: ThreadId.make("parent-thread"),
518 };
519 const turnItems = [question, explicit, stream];
520 let current: OrchestrationV2ThreadProjection = {
521 ...v2Projection,
522 turnItems,
523 visibleTurnItems: [...turnItems.map(localRow), inherited],
524 runtimeRequests: [projection.runtimeRequests[0]!, explicitRequest],
525 };
526 const project = createQuestionHistoryProjector();
527 const step = (next: OrchestrationV2ThreadProjection) => {
528 current = next;
529 const result = project(next);
530 expect(result).toEqual(createQuestionHistoryProjector()(next));
531 return result;
532 };
533 const answerOf = (rows: ReadonlyArray<{ readonly item: unknown }>, index: number) =>
534 (rows[index]!.item as { readonly questionAnswer?: { readonly answers: unknown } })
535 .questionAnswer?.answers;
536
537 expect(step(current)).toBe(current.visibleTurnItems);
538 expect(step(updated(current, assistantItem(2, "Hello")))).toBe(current.visibleTurnItems);
539
540 // The last duplicate request wins, and every row asking it gets the answer.
541 const answered = step({
542 ...current,
543 runtimeRequests: [
544 projection.runtimeRequests[0]!,
545 resolved({ next: "Continue" }),
546 explicitRequest,
547 ],
548 });
549 expect(answerOf(answered, 0)).toEqual({ next: "Continue" });
550 expect(answerOf(answered, 1)).toEqual({ next: "Explicit" });
551 expect(answerOf(answered, 3)).toEqual({ next: "Continue" });
552
553 const whileOverlaid = step(updated(current, assistantItem(2, "Hello there")));
554 expect(whileOverlaid[0]).toBe(answered[0]);
555 expect(whileOverlaid[3]).toBe(answered[3]);
556
557 const changedAnswer = step({
558 ...current,
559 runtimeRequests: [resolved({ next: "Stop" }), explicitRequest],
560 });
561 expect(answerOf(changedAnswer, 0)).toEqual({ next: "Stop" });
562
563 const reopened = step({
564 ...current,
565 runtimeRequests: [projection.runtimeRequests[0]!, explicitRequest],
566 });
567 expect(reopened).toBe(current.visibleTurnItems);
568
569 // Dropping an explicit answer falls back to its resolved request.
570 const restored = step(updated(current, unanswered));
571 expect(answerOf(restored, 1)).toEqual({ next: "From request" });
572
573 const retitled: QuestionItem = {
574 ...unanswered,
575 questions: [{ ...question.questions[0]!, question: "Now what?" }],
576 };
577 const retitledRows = step(updated(current, retitled));
578 expect(retitledRows[1]!.item).toMatchObject({
579 questionAnswer: { questionTextById: { next: "Now what?" } },
580 });
581 });
582});
583
584it("loads only child approvals and retains their destination across environments", () => {
585 const local = EnvironmentId.make("local");
586 const remote = EnvironmentId.make("remote");
587 const parent = { environmentId: local, threadId: ThreadId.make("parent") };
588 const childId = ThreadId.make("child");
589 const children = Atom.make(
590 [local, remote].map((environmentId) => ({
591 ...presentThreadShell(environmentId, v2ThreadShell),
592 id: childId,
593 title: environmentId,
594 hasPendingApprovals: true,
595 })),
596 );
597 const details = Atom.family((key: string) =>
598 Atom.make<PendingThreadRequests | null>({
599 approvals: [
600 {
601 requestId: RuntimeRequestId.make(key),
602 requestKind: "command",
603 createdAt: "2026-10-19T00:00:00Z",
604 responseCapability: "live",
605 },
606 ],
607 userInputs: [],
608 }),
609 );
610 const readDetails = vi.fn((ref: ScopedThreadRef) => details(threadKey(ref)));
611 const approvalsAtom = createChildThreadApprovalsAtom({
612 childThreadInputsAtom: () => children,
613 pendingRequestsAtom: readDetails,
614 });
615 const registry = AtomRegistry.make();
616 const unmount = registry.mount(approvalsAtom(parent));
617 const pending = registry.get(approvalsAtom(parent));
618 expect(pending.map((entry) => entry.thread)).toEqual(
619 [local, remote].map((environmentId) => ({ environmentId, threadId: childId })),
620 );
621 expect(pending.map((entry) => entry.title)).toEqual(["local", "remote"]);
622 registry.set(details(threadKey({ environmentId: remote, threadId: childId })), {
623 approvals: [],
624 userInputs: [],
625 });
626 expect(registry.get(approvalsAtom(parent))).toEqual([pending[0]]);
627 readDetails.mockClear();
628 registry.set(
629 children,
630 registry
631 .get(children)
632 .map((child) => ({ ...child, hasPendingApprovals: false, hasPendingUserInput: true })),
633 );
634 expect(registry.get(approvalsAtom(parent))).toEqual([]);
635 expect(readDetails).not.toHaveBeenCalled();
636 unmount();
637 registry.dispose();
638});