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

threadRequests.test.ts

355 lines11.4 KB

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