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 { 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 { 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;
77}
78
79interface ProbeProps {
80 environmentId: EnvironmentId;
81 projection: OrchestrationV2ThreadProjection;
82 loading?: boolean;
83}
84
85function useProbeRequests({ environmentId, projection, loading = false }: ProbeProps) {
86 const promptRef = useRef("");
87 const composerRef = useRef(null);
88 return usePendingThreadRequests({
89 environmentId,
90 activeThreadId: projection.thread.id,
91 serverProjection: loading ? null : projection,
92 supportsQuestionAttachments: false,
93 composerDraftTarget: { environmentId, threadId: projection.thread.id },
94 setComposerDraftPrompt: (target, prompt) =>
95 useComposerDraftStore.getState().setPrompt(target, prompt),
96 promptRef,
97 composerRef,
98 setThreadError: () => {},
99 });
100}
101
102let requests: ReturnType<typeof usePendingThreadRequests>;
103
104function PendingRequestsProbe(props: ProbeProps) {
105 const state = useProbeRequests(props);
106 useLayoutEffect(() => {
107 requests = state;
108 });
109 return null;
110}
111
112it("retains answers, selections and question position after leaving chat, including while the projection reloads", async () => {
113 using _timers = fakeTimers();
114 const environmentId = EnvironmentId.make("remount-environment");
115 const projection = questionProjection(threadRef.threadId);
116 const probe = (loading = false) => (
117 <PendingRequestsProbe environmentId={environmentId} projection={projection} loading={loading} />
118 );
119 await using screen = await render(probe());
120 await act(() =>
121 requests.onChangeActivePendingUserInputCustomAnswer("question-0", "Keep my text"),
122 );
123 await act(() => requests.onAdvanceActivePendingUserInput());
124 await act(() => requests.onSelectActivePendingUserInputOption("question-1", "Incremental"));
125 await act(() => requests.onAdvanceActivePendingUserInput());
126 const expected = {
127 activePendingQuestionIndex: 2,
128 activePendingDraftAnswers: {
129 "question-0": { customAnswer: "Keep my text" },
130 "question-1": { selectedOptionValues: ["Incremental"] },
131 },
132 };
133 expect(requests).toMatchObject(expected);
134
135 // New thread and Settings both unmount the chat that owns this hook.
136 await screen.rerender(null);
137 await screen.rerender(probe());
138 expect(requests).toMatchObject(expected);
139
140 await screen.rerender(null);
141 await screen.rerender(probe(true));
142 expect(requests.activePendingUserInput).toBeNull();
143 await screen.rerender(probe());
144 expect(requests).toMatchObject(expected);
145});
146
147it("tells the user when an option click moves their typed answer into the hidden composer draft", async () => {
148 using _timers = fakeTimers();
149 const environmentId = EnvironmentId.make("displaced-environment");
150 const draftTarget = { environmentId, threadId: threadRef.threadId };
151 const draftPrompt = () => useComposerDraftStore.getState().getComposerDraft(draftTarget)?.prompt;
152 using toast = vi.spyOn(toastManager, "add");
153 await using _screen = await render(
154 <PendingRequestsProbe
155 environmentId={environmentId}
156 projection={questionProjection(threadRef.threadId)}
157 />,
158 );
159
160 await act(() => requests.onSelectActivePendingUserInputOption("question-0", "Incremental"));
161 expect(toast).not.toHaveBeenCalled();
162
163 await act(() => requests.onChangeActivePendingUserInputCustomAnswer("question-0", "first try"));
164 await act(() => requests.onSelectActivePendingUserInputOption("question-0", "Incremental"));
165 expect(draftPrompt()).toBe("first try");
166 expect(toast).toHaveBeenCalledTimes(1);
167 expect(toast).toHaveBeenCalledWith(
168 expect.objectContaining({
169 type: "info",
170 title: "Your typed text was set aside",
171 description: "It will be back in the composer once the question is answered.",
172 data: { threadRef: draftTarget },
173 }),
174 );
175
176 await act(() => requests.onChangeActivePendingUserInputCustomAnswer("question-0", "second try"));
177 expect(draftPrompt()).toBe("first try");
178 expect(requests.activePendingDraftAnswers["question-0"]).toMatchObject({
179 customAnswer: "second try",
180 });
181 expect(toast).toHaveBeenCalledTimes(1);
182});
183
184function QuestionPositionProbe(props: ProbeProps) {
185 const state = useProbeRequests(props);
186 return (
187 <>
188 <output>Question {state.activePendingQuestionIndex + 1}</output>
189 <button
190 type="button"
191 onClick={() => state.onSelectActivePendingUserInputOption("question-0", "Incremental")}
192 >
193 Choose Incremental
194 </button>
195 <button type="button" onClick={() => state.onAdvanceActivePendingUserInput()}>
196 Submit
197 </button>
198 </>
199 );
200}
201
202it("stays on an unanswered question when the composer submits", async () => {
203 await using screen = await render(
204 <QuestionPositionProbe
205 environmentId={EnvironmentId.make("unanswered-environment")}
206 projection={questionProjection(threadRef.threadId)}
207 />,
208 );
209 const submit = screen.getByRole("button", { name: "Submit" });
210 await userEvent.click(submit);
211 await expect.element(screen.getByRole("status")).toHaveTextContent("Question 1");
212
213 await userEvent.click(screen.getByRole("button", { name: "Choose Incremental" }));
214 await userEvent.click(submit);
215 await expect.element(screen.getByRole("status")).toHaveTextContent("Question 2");
216});
217
218it("isolates drafts by environment, thread and request and discards only resolved requests", async () => {
219 using _timers = fakeTimers();
220 const environmentId = EnvironmentId.make("scope-environment");
221 const projection = questionProjection(threadRef.threadId);
222 const scopes = [
223 { environmentId, projection },
224 { environmentId: EnvironmentId.make("other-environment"), projection },
225 { environmentId, projection: questionProjection(ThreadId.make("other-thread")) },
226 { environmentId, projection: questionProjection(threadRef.threadId, ["second", "first"]) },
227 ];
228 await using screen = await render(null);
229 const show = (scope: ComponentProps<typeof PendingRequestsProbe>) =>
230 screen.rerender(<PendingRequestsProbe {...scope} />);
231 for (const [index, scope] of scopes.entries()) {
232 await show(scope);
233 expect(requests.activePendingQuestionIndex).toBe(0);
234 expect(requests.activePendingDraftAnswers["question-0"]?.customAnswer).toBeUndefined();
235 await act(() =>
236 requests.onChangeActivePendingUserInputCustomAnswer("question-0", `Answer ${index}`),
237 );
238 await act(() => requests.onAdvanceActivePendingUserInput());
239 }
240
241 // "first" was answered on another device.
242 await show({
243 environmentId,
244 projection: {
245 ...projection,
246 runtimeRequests: projection.runtimeRequests.map((request) =>
247 request.id === "first"
248 ? { ...request, status: "resolved", resolvedAt: projection.updatedAt }
249 : request,
250 ),
251 },
252 });
253 expect(requests.activePendingUserInput?.requestId).toBe("second");
254 await act(() =>
255 makeThreadRequestsResolvedAnnouncer(
256 environmentId,
257 threadRef.threadId,
258 )([
259 { id: RuntimeRequestId.make("first"), status: "resolved" },
260 { id: RuntimeRequestId.make("second"), status: "pending" },
261 ]),
262 );
263 for (const [index, scope] of scopes.entries()) {
264 await show(scope);
265 expect(requests.activePendingQuestionIndex).toBe(index === 0 ? 0 : 1);
266 expect(requests.activePendingDraftAnswers["question-0"]?.customAnswer).toBe(
267 index === 0 ? undefined : `Answer ${index}`,
268 );
269 }
270});