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

threadRequests.test.ts

273 lines8.8 KB

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