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

ComposerPendingUserInputPanel.navigation.browser.test.tsx

294 lines11.2 KB

1import {
2 EnvironmentId,
3 NodeId,
4 RuntimeRequestId,
5 ThreadId,
6 TurnItemId,
7 type OrchestrationV2ThreadProjection,
8} from "@t3tools/contracts";
9import { makeThreadRequestsResolvedAnnouncer } from "@t3tools/client-runtime/state/thread-requests";
10import { useLayoutEffect, useRef, type ComponentProps } from "react";
11import { expect, it, vi } from "vite-plus/test";
12import { userEvent } from "vite-plus/test/browser";
13​
14vi.mock(import("../ChatMarkdown"), async (importOriginal) => ({
15 ...(await importOriginal()),
16 default: (({ text }: { text: string }) => <p>{text}</p>) as never,
17}));
18​
19import { act, fakeTimers, render } from "../../../test/render";
20import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
21import { makeThreadProjectionFixture } from "../../test-fixtures";
22import { toastManager } from "../ui/toast";
23import { usePendingThreadRequests } from "./usePendingThreadRequests";
24​
25const threadRef = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") };
26​
27const prompt = {
28 requestId: RuntimeRequestId.make("question-navigation"),
29 createdAt: "2026-10-09T00:00:00.000Z",
30 dismissible: false,
31 responseCapability: "live" as const,
32 questions: [0, 1, 2].map((index) => ({
33 id: `question-${index}`,
34 header: `Question ${index + 1}`,
35 question: `Choose for question ${index + 1}`,
36 options: [{ label: "Incremental", description: "One module at a time" }],
37 multiSelect: false,
38 })),
39};
40​
41function questionProjection(threadId: ThreadId, requestIds = ["first", "second"]) {
42 const projection = makeThreadProjectionFixture();
43 return {
44 ...projection,
45 thread: { ...projection.thread, id: threadId },
46 runtimeRequests: requestIds.map((id) => ({
47 id: RuntimeRequestId.make(id),
48 nodeId: NodeId.make(id),
49 providerTurnId: null,
50 nativeRequestRef: null,
51 kind: "user_input" as const,
52 status: "pending" as const,
53 responseCapability: { type: "message" as const },
54 createdAt: projection.updatedAt,
55 resolvedAt: null,
56 })),
57 turnItems: requestIds.map((id, ordinal) => ({
58 id: TurnItemId.make(id),
59 threadId,
60 runId: null,
61 nodeId: NodeId.make(id),
62 providerThreadId: null,
63 providerTurnId: null,
64 nativeItemRef: null,
65 parentItemId: null,
66 ordinal,
67 status: "completed" as const,
68 title: null,
69 startedAt: projection.updatedAt,
70 completedAt: projection.updatedAt,
71 updatedAt: projection.updatedAt,
72 type: "user_input_request" as const,
73 requestId: RuntimeRequestId.make(id),
74 questions: prompt.questions,
75 })),
76 } satisfies OrchestrationV2ThreadProjection;
78​
79interface ProbeProps {
80 environmentId: EnvironmentId;
81 projection: OrchestrationV2ThreadProjection;
82 loading?: boolean;
83 draftTarget?: DraftId;
85​
86function useProbeRequests({ environmentId, projection, loading = false, draftTarget }: ProbeProps) {
87 const promptRef = useRef("");
88 const composerRef = useRef(null);
89 return usePendingThreadRequests({
90 environmentId,
91 activeThreadId: projection.thread.id,
92 serverProjection: loading ? null : projection,
93 supportsQuestionAttachments: false,
94 composerDraftTarget: draftTarget ?? { environmentId, threadId: projection.thread.id },
95 setComposerDraftPrompt: (target, prompt) =>
96 useComposerDraftStore.getState().setPrompt(target, prompt),
97 promptRef,
98 composerRef,
99 setThreadError: () => {},
100 });
102​
103let requests: ReturnType<typeof usePendingThreadRequests>;
104​
105function PendingRequestsProbe(props: ProbeProps) {
106 const state = useProbeRequests(props);
107 useLayoutEffect(() => {
108 requests = state;
109 });
110 return null;
112​
113it("retains answers, selections and question position after leaving chat, including while the projection reloads", async () => {
114 using _timers = fakeTimers();
115 const environmentId = EnvironmentId.make("remount-environment");
116 const projection = questionProjection(threadRef.threadId);
117 const probe = (loading = false) => (
118 <PendingRequestsProbe environmentId={environmentId} projection={projection} loading={loading} />
119 );
120 await using screen = await render(probe());
121 await act(() =>
122 requests.onChangeActivePendingUserInputCustomAnswer("question-0", "Keep my text"),
123 );
124 await act(() => requests.onAdvanceActivePendingUserInput());
125 await act(() => requests.onSelectActivePendingUserInputOption("question-1", "Incremental"));
126 await act(() => requests.onAdvanceActivePendingUserInput());
127 const expected = {
128 activePendingQuestionIndex: 2,
129 activePendingDraftAnswers: {
130 "question-0": { customAnswer: "Keep my text" },
131 "question-1": { selectedOptionValues: ["Incremental"] },
132 },
133 };
134 expect(requests).toMatchObject(expected);
135​
136 // New thread and Settings both unmount the chat that owns this hook.
137 await screen.rerender(null);
138 await screen.rerender(probe());
139 expect(requests).toMatchObject(expected);
140​
141 await screen.rerender(null);
142 await screen.rerender(probe(true));
143 expect(requests.activePendingUserInput).toBeNull();
144 await screen.rerender(probe());
145 expect(requests).toMatchObject(expected);
146});
147​
148it("tells the user when an option click moves their typed answer into the hidden composer draft", async () => {
149 using _timers = fakeTimers();
150 const environmentId = EnvironmentId.make("displaced-environment");
151 const draftTarget = { environmentId, threadId: threadRef.threadId };
152 const draftPrompt = () => useComposerDraftStore.getState().getComposerDraft(draftTarget)?.prompt;
153 using toast = vi.spyOn(toastManager, "add");
154 const probe = (threadId: ThreadId) => (
155 <PendingRequestsProbe environmentId={environmentId} projection={questionProjection(threadId)} />
156 );
157 await using screen = await render(probe(threadRef.threadId));
158​
159 await act(() => requests.onSelectActivePendingUserInputOption("question-0", "Incremental"));
160 expect(toast).not.toHaveBeenCalled();
161​
162 await act(() => requests.onChangeActivePendingUserInputCustomAnswer("question-0", "first try"));
163 await act(() => requests.onSelectActivePendingUserInputOption("question-0", "Incremental"));
164 expect(draftPrompt()).toBe("first try");
165 expect(toast).toHaveBeenCalledTimes(1);
166 expect(toast).toHaveBeenCalledWith(
167 expect.objectContaining({
168 type: "info",
169 title: "Your typed text was set aside",
170 description: "It will be back in the composer once the question is answered.",
171 data: { threadRef: draftTarget },
172 }),
173 );
174​
175 await act(() => requests.onChangeActivePendingUserInputCustomAnswer("question-0", "second try"));
176 expect(draftPrompt()).toBe("first try");
177 expect(requests.activePendingDraftAnswers["question-0"]).toMatchObject({
178 customAnswer: "second try",
179 });
180 expect(toast).toHaveBeenCalledTimes(1);
181​
182 // The hook outlives a thread switch; text set aside in another thread is in another draft.
183 await screen.rerender(probe(ThreadId.make("other-thread")));
184 await act(() => requests.onChangeActivePendingUserInputCustomAnswer("question-0", "elsewhere"));
185 await act(() => requests.onSelectActivePendingUserInputOption("question-0", "Incremental"));
186 await screen.rerender(probe(threadRef.threadId));
187​
188 // regression: #35205 undo puts the set-aside text back, so the draft must not keep a copy to resend
189 await act(() => requests.onChangeActivePendingUserInputCustomAnswer("question-0", "first try"));
190 expect(draftPrompt() ?? "").toBe("");
191​
192 // Text set aside into a queued-message edit draft never withdraws from the thread draft.
193 await screen.rerender(
194 <PendingRequestsProbe
195 environmentId={environmentId}
196 projection={questionProjection(threadRef.threadId)}
197 draftTarget={DraftId.make("queued-edit")}
198 />,
199 );
200 await act(() => requests.onChangeActivePendingUserInputCustomAnswer("question-0", "foo"));
201 await act(() => requests.onSelectActivePendingUserInputOption("question-0", "Incremental"));
202 await screen.rerender(probe(threadRef.threadId));
203 useComposerDraftStore.getState().setPrompt(draftTarget, "foo");
204 await act(() => requests.onChangeActivePendingUserInputCustomAnswer("question-0", "foo"));
205 expect(draftPrompt()).toBe("foo");
206});
207​
208function QuestionPositionProbe(props: ProbeProps) {
209 const state = useProbeRequests(props);
210 return (
211 <>
212 <output>Question {state.activePendingQuestionIndex + 1}</output>
213 <button
214 type="button"
215 onClick={() => state.onSelectActivePendingUserInputOption("question-0", "Incremental")}
216 >
217 Choose Incremental
218 </button>
219 <button type="button" onClick={() => state.onAdvanceActivePendingUserInput()}>
220 Submit
221 </button>
222 </>
223 );
225​
226it("stays on an unanswered question when the composer submits", async () => {
227 await using screen = await render(
228 <QuestionPositionProbe
229 environmentId={EnvironmentId.make("unanswered-environment")}
230 projection={questionProjection(threadRef.threadId)}
231 />,
232 );
233 const submit = screen.getByRole("button", { name: "Submit" });
234 await userEvent.click(submit);
235 await expect.element(screen.getByRole("status")).toHaveTextContent("Question 1");
236​
237 await userEvent.click(screen.getByRole("button", { name: "Choose Incremental" }));
238 await userEvent.click(submit);
239 await expect.element(screen.getByRole("status")).toHaveTextContent("Question 2");
240});
241​
242it("isolates drafts by environment, thread and request and discards only resolved requests", async () => {
243 using _timers = fakeTimers();
244 const environmentId = EnvironmentId.make("scope-environment");
245 const projection = questionProjection(threadRef.threadId);
246 const scopes = [
247 { environmentId, projection },
248 { environmentId: EnvironmentId.make("other-environment"), projection },
249 { environmentId, projection: questionProjection(ThreadId.make("other-thread")) },
250 { environmentId, projection: questionProjection(threadRef.threadId, ["second", "first"]) },
251 ];
252 await using screen = await render(null);
253 const show = (scope: ComponentProps<typeof PendingRequestsProbe>) =>
254 screen.rerender(<PendingRequestsProbe {...scope} />);
255 for (const [index, scope] of scopes.entries()) {
256 await show(scope);
257 expect(requests.activePendingQuestionIndex).toBe(0);
258 expect(requests.activePendingDraftAnswers["question-0"]?.customAnswer).toBeUndefined();
259 await act(() =>
260 requests.onChangeActivePendingUserInputCustomAnswer("question-0", `Answer ${index}`),
261 );
262 await act(() => requests.onAdvanceActivePendingUserInput());
263 }
264​
265 // "first" was answered on another device.
266 await show({
267 environmentId,
268 projection: {
269 ...projection,
270 runtimeRequests: projection.runtimeRequests.map((request) =>
271 request.id === "first"
272 ? { ...request, status: "resolved", resolvedAt: projection.updatedAt }
273 : request,
274 ),
275 },
276 });
277 expect(requests.activePendingUserInput?.requestId).toBe("second");
278 await act(() =>
279 makeThreadRequestsResolvedAnnouncer(
280 environmentId,
281 threadRef.threadId,
282 )([
283 { id: RuntimeRequestId.make("first"), status: "resolved" },
284 { id: RuntimeRequestId.make("second"), status: "pending" },
285 ]),
286 );
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});