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

ComposerPendingUserInputPanel.navigation.browser.test.tsx

418 lines13.7 KB

1import {
2 EnvironmentId,
3 NodeId,
4 RuntimeRequestId,
5 ThreadId,
6 TurnItemId,
7 type OrchestrationV2ThreadProjection,
8} from "@t3tools/contracts";
9import { act, useLayoutEffect, useRef, useState, type ComponentProps } from "react";
10import { createRoot, type Root } from "react-dom/client";
11import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
12​
13import {
14 setPendingUserInputCustomAnswer,
15 togglePendingUserInputOptionSelection,
16 type PendingUserInputDraftAnswer,
17} from "../../pendingUserInput";
18import type { PendingUserInput } from "../../session-logic";
19​
20vi.mock(import("../ChatMarkdown"), async (importOriginal) => ({
21 ...(await importOriginal()),
22 default: (({ text }: { text: string }) => <p>{text}</p>) as never,
23}));
24​
25import { makeThreadProjectionFixture } from "../../test-fixtures";
26import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
27import { usePendingThreadRequests } from "./usePendingThreadRequests";
28​
29const threadRef = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") };
30​
31const prompt = {
32 requestId: RuntimeRequestId.make("question-navigation"),
33 createdAt: "2026-10-09T00:00:00.000Z",
34 dismissible: false,
35 responseCapability: "live" as const,
36 questions: [0, 1, 2].map((index) => ({
37 id: `question-${index}`,
38 header: `Question ${index + 1}`,
39 question: `Choose for question ${index + 1}`,
40 options: [{ label: "Incremental", description: "One module at a time" }],
41 multiSelect: false,
42 })),
43};
44​
45const previewPrompt = {
46 ...prompt,
47 questions: prompt.questions.map((question, index) => ({
48 ...question,
49 options: ["First", "Second"].map((label) => ({
50 label,
51 value: index === 1 ? label : "same-answer",
52 description: "",
53 preview: `Preview body: ${label}, question ${index + 1}`,
54 })),
55 })),
56};
57​
58function Questions({
59 initialIndex = 0,
60 pendingPrompt = prompt,
61}: {
62 initialIndex?: number;
63 pendingPrompt?: PendingUserInput;
64}) {
65 const [questionIndex, setQuestionIndex] = useState(initialIndex);
66 const [answers, setAnswers] = useState<Record<string, PendingUserInputDraftAnswer>>({});
67 const question = pendingPrompt.questions[questionIndex]!;
68 const advance = () => setQuestionIndex(questionIndex + 1);
69 return (
70 <>
71 <output>{questionIndex}</output>
72 <button onClick={advance}>Next</button>
73 <button onClick={() => setQuestionIndex(questionIndex - 1)}>Previous</button>
74 <input
75 aria-label="Custom answer"
76 value={answers[question.id]?.customAnswer ?? ""}
77 onChange={(event) => {
78 const value = event.currentTarget.value;
79 setAnswers((existing) => ({
80 ...existing,
81 [question.id]: setPendingUserInputCustomAnswer(existing[question.id], value, question),
82 }));
83 }}
84 />
85 <ComposerPendingUserInputPanel
86 pendingUserInputs={[pendingPrompt]}
87 cwd="/repo"
88 threadRef={threadRef}
89 disabled={false}
90 respondingRequestIds={[]}
91 answers={answers}
92 questionIndex={questionIndex}
93 onAdvance={advance}
94 onToggleOption={(questionId, value) => {
95 const question = pendingPrompt.questions.find((entry) => entry.id === questionId)!;
96 setAnswers((existing) => ({
97 ...existing,
98 [questionId]: togglePendingUserInputOptionSelection(
99 question,
100 existing[questionId],
101 value,
102 ),
103 }));
104 }}
105 onDismiss={() => {}}
106 />
107 </>
108 );
110​
111let root: Root;
112let container: HTMLDivElement;
113beforeEach(() => {
114 vi.useFakeTimers();
115 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
116 container = document.createElement("div");
117 document.body.append(container);
118 root = createRoot(container);
119});
120afterEach(async () => {
121 await act(async () => root.unmount());
122 container.remove();
123 vi.unstubAllGlobals();
124 vi.useRealTimers();
125});
126​
127function buttonWithText(text: string) {
128 const button = [...document.querySelectorAll("button")].find((element) =>
129 element.textContent?.includes(text),
130 );
131 expect(button, `button ${text}`).toBeDefined();
132 return button!;
134​
135async function chooseOption() {
136 await act(async () => buttonWithText("Incremental").click());
138​
139async function navigate(label: string) {
140 await act(async () => buttonWithText(label).click());
142​
143function activeIndex() {
144 return container.querySelector("output")!.textContent;
146​
147it("does not skip the next unanswered question after manual advance", async () => {
148 await act(async () => root.render(<Questions />));
149 await chooseOption();
150 await navigate("Next");
151 expect(activeIndex()).toBe("1");
152 await act(async () => vi.advanceTimersByTime(200));
153 expect(activeIndex()).toBe("1");
154​
155 await chooseOption();
156 await act(async () => vi.advanceTimersByTime(200));
157 expect(activeIndex()).toBe("2");
158});
159​
160it("does not undo previous-question navigation with a stale timer", async () => {
161 await act(async () => root.render(<Questions initialIndex={1} />));
162 await chooseOption();
163 await navigate("Previous");
164 await act(async () => vi.advanceTimersByTime(200));
165 expect(activeIndex()).toBe("0");
166});
167​
168it("still auto-advances once after the answer draft rerenders the same question", async () => {
169 await act(async () => root.render(<Questions />));
170 await chooseOption();
171 await act(async () => vi.advanceTimersByTime(200));
172 expect(activeIndex()).toBe("1");
173 await act(async () => vi.advanceTimersByTime(200));
174 expect(activeIndex()).toBe("1");
175});
176​
177function questionProjection(threadId: ThreadId, requestIds = ["first", "second"]) {
178 const projection = makeThreadProjectionFixture();
179 return {
180 ...projection,
181 thread: { ...projection.thread, id: threadId },
182 runtimeRequests: requestIds.map((id) => ({
183 id: RuntimeRequestId.make(id),
184 nodeId: NodeId.make(id),
185 providerTurnId: null,
186 nativeRequestRef: null,
187 kind: "user_input" as const,
188 status: "pending" as const,
189 responseCapability: { type: "message" as const },
190 createdAt: projection.updatedAt,
191 resolvedAt: null,
192 })),
193 turnItems: requestIds.map((id, ordinal) => ({
194 id: TurnItemId.make(id),
195 threadId,
196 runId: null,
197 nodeId: NodeId.make(id),
198 providerThreadId: null,
199 providerTurnId: null,
200 nativeItemRef: null,
201 parentItemId: null,
202 ordinal,
203 status: "completed" as const,
204 title: null,
205 startedAt: projection.updatedAt,
206 completedAt: projection.updatedAt,
207 updatedAt: projection.updatedAt,
208 type: "user_input_request" as const,
209 requestId: RuntimeRequestId.make(id),
210 questions: prompt.questions,
211 })),
212 } satisfies OrchestrationV2ThreadProjection;
214​
215let requests: ReturnType<typeof usePendingThreadRequests>;
216​
217function PendingRequestsProbe({
218 environmentId,
219 projection,
220 loading = false,
221}: {
222 environmentId: EnvironmentId;
223 projection: OrchestrationV2ThreadProjection;
224 loading?: boolean;
225}) {
226 const promptRef = useRef("");
227 const composerRef = useRef(null);
228 const state = usePendingThreadRequests({
229 environmentId,
230 activeThreadId: projection.thread.id,
231 activeThread: projection.thread,
232 serverProjection: loading ? null : projection,
233 supportsQuestionAttachments: false,
234 composerDraftTarget: { environmentId, threadId: projection.thread.id },
235 setComposerDraftPrompt: () => {},
236 promptRef,
237 composerRef,
238 setThreadError: () => {},
239 });
240 useLayoutEffect(() => {
241 requests = state;
242 });
243 return null;
245​
246it("retains answers, selections and question position after leaving chat, including while the projection reloads", async () => {
247 const environmentId = EnvironmentId.make("remount-environment");
248 const projection = questionProjection(threadRef.threadId);
249 const render = (loading = false) =>
250 act(() =>
251 root.render(
252 <PendingRequestsProbe
253 environmentId={environmentId}
254 projection={projection}
255 loading={loading}
256 />,
257 ),
258 );
259 await render();
260 await act(() =>
261 requests.onChangeActivePendingUserInputCustomAnswer("question-0", "Keep my text"),
262 );
263 await act(() => requests.onAdvanceActivePendingUserInput());
264 await act(() => requests.onSelectActivePendingUserInputOption("question-1", "Incremental"));
265 await act(() => requests.onAdvanceActivePendingUserInput());
266 const expected = {
267 activePendingQuestionIndex: 2,
268 activePendingDraftAnswers: {
269 "question-0": { customAnswer: "Keep my text" },
270 "question-1": { selectedOptionValues: ["Incremental"] },
271 },
272 };
273 expect(requests).toMatchObject(expected);
274​
275 // New thread and Settings both unmount the chat that owns this hook.
276 await act(() => root.render(null));
277 await render();
278 expect(requests).toMatchObject(expected);
279​
280 await act(() => root.render(null));
281 await render(true);
282 expect(requests.activePendingUserInput).toBeNull();
283 await render();
284 expect(requests).toMatchObject(expected);
285});
286​
287it("isolates drafts by environment, thread and request and discards only resolved requests", async () => {
288 const environmentId = EnvironmentId.make("scope-environment");
289 const projection = questionProjection(threadRef.threadId);
290 const scopes = [
291 { environmentId, projection },
292 { environmentId: EnvironmentId.make("other-environment"), projection },
293 { environmentId, projection: questionProjection(ThreadId.make("other-thread")) },
294 { environmentId, projection: questionProjection(threadRef.threadId, ["second", "first"]) },
295 ];
296 const show = (scope: ComponentProps<typeof PendingRequestsProbe>) =>
297 act(() => root.render(<PendingRequestsProbe {...scope} />));
298 for (const [index, scope] of scopes.entries()) {
299 await show(scope);
300 expect(requests.activePendingQuestionIndex).toBe(0);
301 expect(requests.activePendingDraftAnswers["question-0"]?.customAnswer).toBeUndefined();
302 await act(() =>
303 requests.onChangeActivePendingUserInputCustomAnswer("question-0", `Answer ${index}`),
304 );
305 await act(() => requests.onAdvanceActivePendingUserInput());
306 }
307​
308 await show({
309 environmentId,
310 projection: {
311 ...projection,
312 runtimeRequests: projection.runtimeRequests.map((request) =>
313 request.id === "first"
314 ? { ...request, status: "resolved", resolvedAt: projection.updatedAt }
315 : request,
316 ),
317 },
318 });
319 expect(requests.activePendingUserInput?.requestId).toBe("second");
320 for (const [index, scope] of scopes.entries()) {
321 await show(scope);
322 expect(requests.activePendingQuestionIndex).toBe(index === 0 ? 0 : 1);
323 expect(requests.activePendingDraftAnswers["question-0"]?.customAnswer).toBe(
324 index === 0 ? undefined : `Answer ${index}`,
325 );
326 }
327});
328​
329function expectPreview(text: string | null) {
330 const previews = [...container.querySelectorAll("p")]
331 .map((element) => element.textContent)
332 .filter((content) => content?.startsWith("Preview body:"));
333 expect(previews).toEqual(text === null ? [] : [`Preview body: ${text}`]);
335​
336async function typeCustomAnswer(value: string) {
337 const input = container.querySelector("input")!;
338 await act(async () => {
339 input.focus();
340 Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
341 input.dispatchEvent(new Event("input", { bubbles: true }));
342 });
344​
345it("previews options by focus, click, and shortcut index but only restores unambiguous saved selections", async () => {
346 await act(async () => root.render(<Questions pendingPrompt={previewPrompt} />));
347 expectPreview("First, question 1");
348​
349 await act(async () => buttonWithText("Second").focus());
350 expectPreview("Second, question 1");
351 await act(async () => buttonWithText("First").focus());
352 expectPreview("First, question 1");
353​
354 await act(async () => buttonWithText("Second").click());
355 expectPreview("Second, question 1");
356 await act(async () => document.dispatchEvent(new KeyboardEvent("keydown", { key: "1" })));
357 expectPreview("First, question 1");
358 await act(async () => document.dispatchEvent(new KeyboardEvent("keydown", { key: "2" })));
359 expectPreview("Second, question 1");
360​
361 await act(async () => vi.advanceTimersByTime(200));
362 expect(activeIndex()).toBe("1");
363 expectPreview("First, question 2");
364​
365 await act(async () => buttonWithText("Second").focus());
366 expectPreview("Second, question 2");
367 await act(async () =>
368 root.render(
369 <Questions
370 pendingPrompt={{ ...previewPrompt, requestId: RuntimeRequestId.make("replacement") }}
371 />,
372 ),
373 );
374 expectPreview("First, question 2");
375​
376 await act(async () => buttonWithText("Second").click());
377 expectPreview("Second, question 2");
378 await navigate("Next");
379 expectPreview("First, question 3");
380 await navigate("Previous");
381 expectPreview("Second, question 2");
382​
383 await navigate("Previous");
384 expectPreview(null);
385 await act(async () =>
386 root.render(
387 <Questions
388 pendingPrompt={{ ...previewPrompt, requestId: RuntimeRequestId.make("remounted") }}
389 />,
390 ),
391 );
392 expectPreview(null);
393 await act(async () => buttonWithText("Second").click());
394 expectPreview("Second, question 1");
395});
396​
397it("hides and clears hovered or focused previews while a custom answer is active", async () => {
398 await act(async () => root.render(<Questions pendingPrompt={previewPrompt} />));
399 await act(async () =>
400 buttonWithText("Second").dispatchEvent(new MouseEvent("mouseover", { bubbles: true })),
401 );
402 expectPreview("Second, question 1");
403​
404 await typeCustomAnswer("Use a different approach");
405 expectPreview(null);
406 await typeCustomAnswer("");
407 expectPreview("First, question 1");
408​
409 await typeCustomAnswer("Use a different approach");
410 await act(async () => buttonWithText("Second").focus());
411 expectPreview(null);
412 await act(async () =>
413 buttonWithText("Second").dispatchEvent(new MouseEvent("mouseover", { bubbles: true })),
414 );
415 expectPreview(null);
416 await typeCustomAnswer("");
417 expectPreview("First, question 1");
418});