Open History to see the last commit
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 togglePendingUserInputOptionSelection,
15 type PendingUserInputDraftAnswer,
16} from "../../pendingUserInput";
17
18vi.mock(import("../ChatMarkdown"), async (importOriginal) => ({
19 ...(await importOriginal()),
20 default: (({ text }: { text: string }) => <p>{text}</p>) as never,
21}));
22
23import { makeThreadProjectionFixture } from "../../test-fixtures";
24import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
25import { usePendingThreadRequests } from "./usePendingThreadRequests";
26
27const threadRef = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") };
28
29const prompt = {
30 requestId: RuntimeRequestId.make("question-navigation"),
31 createdAt: "2026-10-09T00:00:00.000Z",
32 dismissible: false,
33 responseCapability: "live" as const,
34 questions: [0, 1, 2].map((index) => ({
35 id: `question-${index}`,
36 header: `Question ${index + 1}`,
37 question: `Choose for question ${index + 1}`,
38 options: [{ label: "Incremental", description: "One module at a time" }],
39 multiSelect: false,
40 })),
41};
42
43function Questions({ initialIndex = 0 }: { initialIndex?: number }) {
44 const [questionIndex, setQuestionIndex] = useState(initialIndex);
45 const [answers, setAnswers] = useState<Record<string, PendingUserInputDraftAnswer>>({});
46 const advance = () => setQuestionIndex(questionIndex + 1);
47 return (
48 <>
49 <output>{questionIndex}</output>
50 <button onClick={advance}>Next</button>
51 <button onClick={() => setQuestionIndex(questionIndex - 1)}>Previous</button>
52 <ComposerPendingUserInputPanel
53 pendingUserInputs={[prompt]}
54 cwd="/repo"
55 threadRef={threadRef}
56 disabled={false}
57 respondingRequestIds={[]}
58 answers={answers}
59 questionIndex={questionIndex}
60 onAdvance={advance}
61 onToggleOption={(questionId, value) => {
62 const question = prompt.questions.find((entry) => entry.id === questionId)!;
63 setAnswers((existing) => ({
64 ...existing,
65 [questionId]: togglePendingUserInputOptionSelection(
66 question,
67 existing[questionId],
68 value,
69 ),
70 }));
71 }}
72 onDismiss={() => {}}
73 />
74 </>
75 );
76}
77
78let root: Root;
79let container: HTMLDivElement;
80beforeEach(() => {
81 vi.useFakeTimers();
82 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
83 container = document.createElement("div");
84 document.body.append(container);
85 root = createRoot(container);
86});
87afterEach(async () => {
88 await act(async () => root.unmount());
89 container.remove();
90 vi.unstubAllGlobals();
91 vi.useRealTimers();
92});
93
94function buttonWithText(text: string) {
95 const button = [...document.querySelectorAll("button")].find((element) =>
96 element.textContent?.includes(text),
97 );
98 expect(button, `button ${text}`).toBeDefined();
99 return button!;
100}
101
102async function chooseOption() {
103 await act(async () => buttonWithText("Incremental").click());
104}
105
106async function navigate(label: string) {
107 await act(async () => buttonWithText(label).click());
108}
109
110function activeIndex() {
111 return container.querySelector("output")!.textContent;
112}
113
114it("does not skip the next unanswered question after manual advance", async () => {
115 await act(async () => root.render(<Questions />));
116 await chooseOption();
117 await navigate("Next");
118 expect(activeIndex()).toBe("1");
119 await act(async () => vi.advanceTimersByTime(200));
120 expect(activeIndex()).toBe("1");
121
122 await chooseOption();
123 await act(async () => vi.advanceTimersByTime(200));
124 expect(activeIndex()).toBe("2");
125});
126
127it("does not undo previous-question navigation with a stale timer", async () => {
128 await act(async () => root.render(<Questions initialIndex={1} />));
129 await chooseOption();
130 await navigate("Previous");
131 await act(async () => vi.advanceTimersByTime(200));
132 expect(activeIndex()).toBe("0");
133});
134
135it("still auto-advances once after the answer draft rerenders the same question", async () => {
136 await act(async () => root.render(<Questions />));
137 await chooseOption();
138 await act(async () => vi.advanceTimersByTime(200));
139 expect(activeIndex()).toBe("1");
140 await act(async () => vi.advanceTimersByTime(200));
141 expect(activeIndex()).toBe("1");
142});
143
144function questionProjection(threadId: ThreadId, requestIds = ["first", "second"]) {
145 const projection = makeThreadProjectionFixture();
146 return {
147 ...projection,
148 thread: { ...projection.thread, id: threadId },
149 runtimeRequests: requestIds.map((id) => ({
150 id: RuntimeRequestId.make(id),
151 nodeId: NodeId.make(id),
152 providerTurnId: null,
153 nativeRequestRef: null,
154 kind: "user_input" as const,
155 status: "pending" as const,
156 responseCapability: { type: "message" as const },
157 createdAt: projection.updatedAt,
158 resolvedAt: null,
159 })),
160 turnItems: requestIds.map((id, ordinal) => ({
161 id: TurnItemId.make(id),
162 threadId,
163 runId: null,
164 nodeId: NodeId.make(id),
165 providerThreadId: null,
166 providerTurnId: null,
167 nativeItemRef: null,
168 parentItemId: null,
169 ordinal,
170 status: "completed" as const,
171 title: null,
172 startedAt: projection.updatedAt,
173 completedAt: projection.updatedAt,
174 updatedAt: projection.updatedAt,
175 type: "user_input_request" as const,
176 requestId: RuntimeRequestId.make(id),
177 questions: prompt.questions,
178 })),
179 } satisfies OrchestrationV2ThreadProjection;
180}
181
182let requests: ReturnType<typeof usePendingThreadRequests>;
183
184function PendingRequestsProbe({
185 environmentId,
186 projection,
187 loading = false,
188}: {
189 environmentId: EnvironmentId;
190 projection: OrchestrationV2ThreadProjection;
191 loading?: boolean;
192}) {
193 const promptRef = useRef("");
194 const composerRef = useRef(null);
195 const state = usePendingThreadRequests({
196 environmentId,
197 activeThreadId: projection.thread.id,
198 activeThread: projection.thread,
199 serverProjection: loading ? null : projection,
200 supportsQuestionAttachments: false,
201 composerDraftTarget: { environmentId, threadId: projection.thread.id },
202 setComposerDraftPrompt: () => {},
203 promptRef,
204 composerRef,
205 setThreadError: () => {},
206 });
207 useLayoutEffect(() => {
208 requests = state;
209 });
210 return null;
211}
212
213it("retains answers, selections and question position after leaving chat, including while the projection reloads", async () => {
214 const environmentId = EnvironmentId.make("remount-environment");
215 const projection = questionProjection(threadRef.threadId);
216 const render = (loading = false) =>
217 act(() =>
218 root.render(
219 <PendingRequestsProbe
220 environmentId={environmentId}
221 projection={projection}
222 loading={loading}
223 />,
224 ),
225 );
226 await render();
227 await act(() =>
228 requests.onChangeActivePendingUserInputCustomAnswer("question-0", "Keep my text"),
229 );
230 await act(() => requests.onAdvanceActivePendingUserInput());
231 await act(() => requests.onSelectActivePendingUserInputOption("question-1", "Incremental"));
232 await act(() => requests.onAdvanceActivePendingUserInput());
233 const expected = {
234 activePendingQuestionIndex: 2,
235 activePendingDraftAnswers: {
236 "question-0": { customAnswer: "Keep my text" },
237 "question-1": { selectedOptionValues: ["Incremental"] },
238 },
239 };
240 expect(requests).toMatchObject(expected);
241
242 // New thread and Settings both unmount the chat that owns this hook.
243 await act(() => root.render(null));
244 await render();
245 expect(requests).toMatchObject(expected);
246
247 await act(() => root.render(null));
248 await render(true);
249 expect(requests.activePendingUserInput).toBeNull();
250 await render();
251 expect(requests).toMatchObject(expected);
252});
253
254it("isolates drafts by environment, thread and request and discards only resolved requests", async () => {
255 const environmentId = EnvironmentId.make("scope-environment");
256 const projection = questionProjection(threadRef.threadId);
257 const scopes = [
258 { environmentId, projection },
259 { environmentId: EnvironmentId.make("other-environment"), projection },
260 { environmentId, projection: questionProjection(ThreadId.make("other-thread")) },
261 { environmentId, projection: questionProjection(threadRef.threadId, ["second", "first"]) },
262 ];
263 const show = (scope: ComponentProps<typeof PendingRequestsProbe>) =>
264 act(() => root.render(<PendingRequestsProbe {...scope} />));
265 for (const [index, scope] of scopes.entries()) {
266 await show(scope);
267 expect(requests.activePendingQuestionIndex).toBe(0);
268 expect(requests.activePendingDraftAnswers["question-0"]?.customAnswer).toBeUndefined();
269 await act(() =>
270 requests.onChangeActivePendingUserInputCustomAnswer("question-0", `Answer ${index}`),
271 );
272 await act(() => requests.onAdvanceActivePendingUserInput());
273 }
274
275 await show({
276 environmentId,
277 projection: {
278 ...projection,
279 runtimeRequests: projection.runtimeRequests.map((request) =>
280 request.id === "first"
281 ? { ...request, status: "resolved", resolvedAt: projection.updatedAt }
282 : request,
283 ),
284 },
285 });
286 expect(requests.activePendingUserInput?.requestId).toBe("second");
287 for (const [index, scope] of scopes.entries()) {
288 await show(scope);
289 expect(requests.activePendingQuestionIndex).toBe(index === 0 ? 0 : 1);
290 expect(requests.activePendingDraftAnswers["question-0"]?.customAnswer).toBe(
291 index === 0 ? undefined : `Answer ${index}`,
292 );
293 }
294});