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

threadRequests.test.ts

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