Open History to see the last commit
1import { presentThreadShell } from "./models.ts";
2import { threadKey } from "./entities.ts";
3import {
4 EnvironmentId,
5 ThreadId,
6 type ScopedThreadRef,
7 NodeId,
8 ProviderSessionId,
9 RuntimeRequestId,
10 TurnItemId,
11 type OrchestrationV2ThreadProjection,
12} from "@t3tools/contracts";
13import { describe, expect, it, vi } from "vite-plus/test";
14import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity";
15import * as Cause from "effect/Cause";
16import { v2Now, v2Projection, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
17import {
18 createQuestionHistoryProjector,
19 createChildThreadApprovalsAtom,
20 type PendingThreadRequests,
21 derivePendingThreadRequests,
22 declinePendingApprovals,
23 sendApprovalFeedback,
24 makeThreadRequestsResolvedAnnouncer,
25 onThreadRequestsResolved,
26 pruneResolvedUserInputDrafts,
27 resolvedQuestionDraftKeys,
28 seedUserInputDraftAnswers,
29 userInputDraftKey,
30 type ApprovalResponder,
31 type ThreadRequestsResolved,
32 type ThreadPendingApproval,
33} from "./threadRequests.ts";
34
35const requestId = RuntimeRequestId.make("async-question");
36const nodeId = NodeId.make("async-question-node");
37
38describe("declining approvals before sending", () => {
39 const approval: ThreadPendingApproval = {
40 requestId,
41 requestKind: "command",
42 createdAt: "2026-10-19T00:00:00Z",
43 responseCapability: "live",
44 };
45 const second: ThreadPendingApproval = {
46 ...approval,
47 requestId: RuntimeRequestId.make("second-approval"),
48 };
49
50 it("declines every pending approval before the send continues", async () => {
51 let resolve!: (value: Awaited<ReturnType<ApprovalResponder>>) => void;
52 const firstResponse = new Promise<Awaited<ReturnType<ApprovalResponder>>>((done) => {
53 resolve = done;
54 });
55 const respond = vi.fn<ApprovalResponder>(async (id) =>
56 id === requestId ? firstResponse : AsyncResult.success(undefined),
57 );
58 const send = vi.fn();
59 const submission = (async () => {
60 if (await declinePendingApprovals([approval, second], respond)) send();
61 })();
62 expect(respond).toHaveBeenCalledWith(requestId, "decline");
63 expect(send).not.toHaveBeenCalled();
64 resolve(AsyncResult.success(undefined));
65 await submission;
66 expect(respond).toHaveBeenCalledWith(second.requestId, "decline");
67 expect(send).toHaveBeenCalledOnce();
68 });
69
70 it.each([AsyncResult.failure(Cause.fail("decline failed")), undefined])(
71 "does not send when a decline is unsuccessful: %s",
72 async (response) => {
73 const send = vi.fn();
74 if (await declinePendingApprovals([approval], async () => response)) send();
75 expect(send).not.toHaveBeenCalled();
76 },
77 );
78
79 it("skips approvals the provider can no longer answer", async () => {
80 const respond = vi.fn(async () => AsyncResult.success(undefined));
81 expect(
82 await declinePendingApprovals(
83 [{ ...approval, responseCapability: "not_resumable" }],
84 respond,
85 ),
86 ).toBe(true);
87 expect(respond).not.toHaveBeenCalled();
88 });
89
90 it("sends feedback only to the displayed request, leaving other approvals pending", async () => {
91 const respond = vi.fn<ApprovalResponder>(async () => AsyncResult.success(undefined));
92 const pending = derivePendingThreadRequests({
93 runtimeRequests: [
94 {
95 ...projection.runtimeRequests[0]!,
96 kind: "command",
97 responseCapability: {
98 type: "live",
99 providerSessionId: ProviderSessionId.make("claude-session"),
100 supportsFeedback: true,
101 },
102 },
103 { ...projection.runtimeRequests[0]!, id: second.requestId, kind: "command" },
104 ],
105 turnItems: [],
106 });
107 expect(await sendApprovalFeedback(pending.approvals[0]!, " Safer please. ", respond)).toBe(
108 true,
109 );
110 expect(respond.mock.calls).toEqual([[approval.requestId, "decline", "Safer please."]]);
111 });
112
113 it("keeps feedback unsent when unsupported, stale, empty or rejected", async () => {
114 const respond = vi.fn<ApprovalResponder>(async () => AsyncResult.failure(Cause.fail("failed")));
115 expect(await sendApprovalFeedback(approval, "Safer please.", respond)).toBe(false);
116 expect(
117 await sendApprovalFeedback(
118 { ...approval, supportsFeedback: true, responseCapability: "not_resumable" },
119 "Safer please.",
120 respond,
121 ),
122 ).toBe(false);
123 expect(await sendApprovalFeedback({ ...approval, supportsFeedback: true }, " ", respond)).toBe(
124 false,
125 );
126 expect(respond).not.toHaveBeenCalled();
127 expect(
128 await sendApprovalFeedback({ ...approval, supportsFeedback: true }, "Safer please.", respond),
129 ).toBe(false);
130 });
131});
132
133describe("pruning resolved user input drafts", () => {
134 const answered = userInputDraftKey("env", "thread", "answered");
135 const pending = userInputDraftKey("env", "thread", "pending");
136 const otherThread = userInputDraftKey("env", "thread-2", "answered");
137 const otherEnvironment = userInputDraftKey("env-2", "thread", "answered");
138 const drafts = {
139 [answered]: 1,
140 [pending]: 2,
141 [otherThread]: 3,
142 [otherEnvironment]: 4,
143 };
144
145 it("drops only the thread's requests that are no longer pending", () => {
146 expect(pruneResolvedUserInputDrafts(drafts, "env", "thread", ["pending"])).toEqual({
147 [pending]: 2,
148 [otherThread]: 3,
149 [otherEnvironment]: 4,
150 });
151 });
152
153 it("returns the same record when nothing resolved", () => {
154 expect(pruneResolvedUserInputDrafts(drafts, "env", "thread", ["answered", "pending"])).toBe(
155 drafts,
156 );
157 });
158});
159
160describe("resolved question draft keys", () => {
161 const prefix = "env:question-thread-";
162 const key = (request: string, question: string) =>
163 `${prefix}${encodeURIComponent(JSON.stringify([request, question]))}`;
164
165 it("returns the thread's keys for requests that are no longer pending", () => {
166 const keys = [
167 key("pending", "first"),
168 key("pending", "second"),
169 key("pending-2", "first"),
170 key("answered", "first"),
171 "env:question-other-thread-x",
172 ];
173 expect(resolvedQuestionDraftKeys(keys, prefix, [RuntimeRequestId.make("pending")])).toEqual([
174 key("pending-2", "first"),
175 key("answered", "first"),
176 ]);
177 });
178});
179
180describe("announcing resolved thread requests", () => {
181 const environmentId = EnvironmentId.make("env");
182 const threadId = v2Projection.thread.id;
183 const first = RuntimeRequestId.make("first");
184 const second = RuntimeRequestId.make("second");
185
186 function record() {
187 const events: ThreadRequestsResolved[] = [];
188 const unsubscribe = onThreadRequestsResolved((event) => events.push(event));
189 return { events, [Symbol.dispose]: unsubscribe };
190 }
191
192 it("announces the first projection, then only when a request leaves pending", () => {
193 using recorder = record();
194 const announce = makeThreadRequestsResolvedAnnouncer(environmentId, threadId);
195
196 announce([first]);
197 announce([first, second]);
198 announce([first, second]);
199 announce([second]);
200
201 expect(recorder.events).toEqual([
202 { environmentId, threadId, pendingRequestIds: [first] },
203 { environmentId, threadId, pendingRequestIds: [second] },
204 ]);
205 });
206});
207
208describe("initial user input drafts", () => {
209 const questions = [
210 { id: "editor", initialAnswer: " Proposed commit\n\n" },
211 { id: "empty", initialAnswer: "" },
212 { id: "ordinary" },
213 { id: "choices", initialAnswer: "Ignore this", allowCustomAnswer: false },
214 ];
215
216 it("seeds editable answers and preserves edits and selections on later snapshots", () => {
217 const seeded = seedUserInputDraftAnswers(questions, {});
218 expect(seeded).toEqual({
219 editor: { customAnswer: " Proposed commit\n\n" },
220 empty: { customAnswer: "" },
221 });
222 const edits = {
223 ...seeded,
224 editor: { customAnswer: "" },
225 empty: { selectedOptionValues: ["empty"], customAnswer: "" },
226 };
227 expect(seedUserInputDraftAnswers(questions, edits)).toEqual(edits);
228 expect(
229 seedUserInputDraftAnswers(questions, { editor: { customAnswer: "Edited commit" } }).editor,
230 ).toEqual({ customAnswer: "Edited commit" });
231 expect(seedUserInputDraftAnswers(questions, {}).editor).toEqual({
232 customAnswer: " Proposed commit\n\n",
233 });
234 });
235});
236const projection: OrchestrationV2ThreadProjection = {
237 ...v2Projection,
238 runtimeRequests: [
239 {
240 id: requestId,
241 nodeId,
242 providerTurnId: null,
243 nativeRequestRef: null,
244 kind: "user_input",
245 status: "pending",
246 responseCapability: { type: "message" },
247 createdAt: v2Now,
248 resolvedAt: null,
249 },
250 ],
251 turnItems: [
252 {
253 id: TurnItemId.make("async-question-item"),
254 threadId: v2Projection.thread.id,
255 runId: null,
256 nodeId,
257 providerThreadId: null,
258 providerTurnId: null,
259 nativeItemRef: null,
260 parentItemId: null,
261 ordinal: 0,
262 status: "completed",
263 title: null,
264 startedAt: v2Now,
265 completedAt: v2Now,
266 updatedAt: v2Now,
267 type: "user_input_request",
268 requestId,
269 responseMode: "message",
270 questions: [
271 {
272 id: "next",
273 header: "Next",
274 question: "What should happen next?",
275 required: true,
276 allowCustomAnswer: false,
277 options: [{ label: "Continue", value: " continue ", description: "Resume work" }],
278 },
279 ],
280 },
281 ],
282};
283
284describe("pending v2 questions", () => {
285 it("keeps message responses available after the originating runtime exits", () => {
286 expect(projection.providerSessions).toEqual([]);
287 expect(derivePendingThreadRequests(projection).userInputs).toEqual([
288 {
289 requestId,
290 createdAt: "2026-06-20T00:00:00.000Z",
291 responseCapability: "message",
292 responseMode: "message",
293 dismissible: true,
294 questions: [
295 {
296 id: "next",
297 header: "Next",
298 question: "What should happen next?",
299 required: true,
300 allowCustomAnswer: false,
301 multiSelect: false,
302 options: [{ label: "Continue", value: " continue ", description: "Resume work" }],
303 },
304 ],
305 },
306 ]);
307 });
308
309 it("only marks asynchronous questions as dismissible", () => {
310 const live = {
311 ...projection,
312 runtimeRequests: projection.runtimeRequests.map((request) => ({
313 ...request,
314 responseCapability: {
315 type: "live" as const,
316 providerSessionId: ProviderSessionId.make("live-session"),
317 },
318 })),
319 turnItems: projection.turnItems.map((item) =>
320 item.type === "user_input_request" ? { ...item, responseMode: undefined } : item,
321 ),
322 };
323 expect(derivePendingThreadRequests(live).userInputs[0]?.dismissible).toBe(false);
324 });
325});
326
327it("restores old text answers without mutating history or replacing unchanged rows", () => {
328 const project = createQuestionHistoryProjector();
329 const item = projection.turnItems[0]!;
330 const row = {
331 item,
332 position: 0,
333 sourceItemId: item.id,
334 sourceThreadId: item.threadId,
335 visibility: "local" as const,
336 };
337 const rows = [row];
338 const pending = { visibleTurnItems: rows, runtimeRequests: projection.runtimeRequests };
339 expect(project(pending)).toBe(rows);
340 const answered = {
341 ...pending,
342 runtimeRequests: [
343 {
344 ...projection.runtimeRequests[0]!,
345 status: "resolved" as const,
346 answers: { next: "Continue" },
347 },
348 ],
349 };
350 const result = project(answered);
351 expect(result[0]?.item).toMatchObject({
352 questionAnswer: {
353 answers: { next: "Continue" },
354 attachmentsByQuestionId: {},
355 questionTextById: { next: "What should happen next?" },
356 },
357 });
358 expect(row.item).not.toHaveProperty("questionAnswer");
359 expect(project(answered)).toBe(result);
360 expect(project({ ...answered, visibleTurnItems: [...rows] })[0]).toBe(result[0]);
361});
362
363it("loads only child approvals and retains their destination across environments", () => {
364 const local = EnvironmentId.make("local");
365 const remote = EnvironmentId.make("remote");
366 const parent = { environmentId: local, threadId: ThreadId.make("parent") };
367 const childId = ThreadId.make("child");
368 const children = Atom.make(
369 [local, remote].map((environmentId) => ({
370 ...presentThreadShell(environmentId, v2ThreadShell),
371 id: childId,
372 title: environmentId,
373 hasPendingApprovals: true,
374 })),
375 );
376 const details = Atom.family((key: string) =>
377 Atom.make<PendingThreadRequests | null>({
378 approvals: [
379 {
380 requestId: RuntimeRequestId.make(key),
381 requestKind: "command",
382 createdAt: "2026-10-19T00:00:00Z",
383 responseCapability: "live",
384 },
385 ],
386 userInputs: [],
387 }),
388 );
389 const readDetails = vi.fn((ref: ScopedThreadRef) => details(threadKey(ref)));
390 const approvalsAtom = createChildThreadApprovalsAtom({
391 childThreadInputsAtom: () => children,
392 pendingRequestsAtom: readDetails,
393 });
394 const registry = AtomRegistry.make();
395 const unmount = registry.mount(approvalsAtom(parent));
396 const pending = registry.get(approvalsAtom(parent));
397 expect(pending.map((entry) => entry.thread)).toEqual(
398 [local, remote].map((environmentId) => ({ environmentId, threadId: childId })),
399 );
400 expect(pending.map((entry) => entry.title)).toEqual(["local", "remote"]);
401 registry.set(details(threadKey({ environmentId: remote, threadId: childId })), {
402 approvals: [],
403 userInputs: [],
404 });
405 expect(registry.get(approvalsAtom(parent))).toEqual([pending[0]]);
406 readDetails.mockClear();
407 registry.set(
408 children,
409 registry
410 .get(children)
411 .map((child) => ({ ...child, hasPendingApprovals: false, hasPendingUserInput: true })),
412 );
413 expect(registry.get(approvalsAtom(parent))).toEqual([]);
414 expect(readDetails).not.toHaveBeenCalled();
415 unmount();
416 registry.dispose();
417});