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

ComposerPendingUserInputPanel.navigation.browser.test.tsx

227 lines7.9 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 { makeThreadProjectionFixture } from "../../test-fixtures";
21import { usePendingThreadRequests } from "./usePendingThreadRequests";
22​
23const threadRef = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") };
24​
25const prompt = {
26 requestId: RuntimeRequestId.make("question-navigation"),
27 createdAt: "2026-10-09T00:00:00.000Z",
28 dismissible: false,
29 responseCapability: "live" as const,
30 questions: [0, 1, 2].map((index) => ({
31 id: `question-${index}`,
32 header: `Question ${index + 1}`,
33 question: `Choose for question ${index + 1}`,
34 options: [{ label: "Incremental", description: "One module at a time" }],
35 multiSelect: false,
36 })),
37};
38​
39function questionProjection(threadId: ThreadId, requestIds = ["first", "second"]) {
40 const projection = makeThreadProjectionFixture();
41 return {
42 ...projection,
43 thread: { ...projection.thread, id: threadId },
44 runtimeRequests: requestIds.map((id) => ({
45 id: RuntimeRequestId.make(id),
46 nodeId: NodeId.make(id),
47 providerTurnId: null,
48 nativeRequestRef: null,
49 kind: "user_input" as const,
50 status: "pending" as const,
51 responseCapability: { type: "message" as const },
52 createdAt: projection.updatedAt,
53 resolvedAt: null,
54 })),
55 turnItems: requestIds.map((id, ordinal) => ({
56 id: TurnItemId.make(id),
57 threadId,
58 runId: null,
59 nodeId: NodeId.make(id),
60 providerThreadId: null,
61 providerTurnId: null,
62 nativeItemRef: null,
63 parentItemId: null,
64 ordinal,
65 status: "completed" as const,
66 title: null,
67 startedAt: projection.updatedAt,
68 completedAt: projection.updatedAt,
69 updatedAt: projection.updatedAt,
70 type: "user_input_request" as const,
71 requestId: RuntimeRequestId.make(id),
72 questions: prompt.questions,
73 })),
74 } satisfies OrchestrationV2ThreadProjection;
76​
77interface ProbeProps {
78 environmentId: EnvironmentId;
79 projection: OrchestrationV2ThreadProjection;
80 loading?: boolean;
82​
83function useProbeRequests({ environmentId, projection, loading = false }: ProbeProps) {
84 const promptRef = useRef("");
85 const composerRef = useRef(null);
86 return usePendingThreadRequests({
87 environmentId,
88 activeThreadId: projection.thread.id,
89 serverProjection: loading ? null : projection,
90 supportsQuestionAttachments: false,
91 composerDraftTarget: { environmentId, threadId: projection.thread.id },
92 setComposerDraftPrompt: () => {},
93 promptRef,
94 composerRef,
95 setThreadError: () => {},
96 });
98​
99let requests: ReturnType<typeof usePendingThreadRequests>;
100​
101function PendingRequestsProbe(props: ProbeProps) {
102 const state = useProbeRequests(props);
103 useLayoutEffect(() => {
104 requests = state;
105 });
106 return null;
108​
109it("retains answers, selections and question position after leaving chat, including while the projection reloads", async () => {
110 using _timers = fakeTimers();
111 const environmentId = EnvironmentId.make("remount-environment");
112 const projection = questionProjection(threadRef.threadId);
113 const probe = (loading = false) => (
114 <PendingRequestsProbe environmentId={environmentId} projection={projection} loading={loading} />
115 );
116 await using screen = await render(probe());
117 await act(() =>
118 requests.onChangeActivePendingUserInputCustomAnswer("question-0", "Keep my text"),
119 );
120 await act(() => requests.onAdvanceActivePendingUserInput());
121 await act(() => requests.onSelectActivePendingUserInputOption("question-1", "Incremental"));
122 await act(() => requests.onAdvanceActivePendingUserInput());
123 const expected = {
124 activePendingQuestionIndex: 2,
125 activePendingDraftAnswers: {
126 "question-0": { customAnswer: "Keep my text" },
127 "question-1": { selectedOptionValues: ["Incremental"] },
128 },
129 };
130 expect(requests).toMatchObject(expected);
131​
132 // New thread and Settings both unmount the chat that owns this hook.
133 await screen.rerender(null);
134 await screen.rerender(probe());
135 expect(requests).toMatchObject(expected);
136​
137 await screen.rerender(null);
138 await screen.rerender(probe(true));
139 expect(requests.activePendingUserInput).toBeNull();
140 await screen.rerender(probe());
141 expect(requests).toMatchObject(expected);
142});
143​
144function QuestionPositionProbe(props: ProbeProps) {
145 const state = useProbeRequests(props);
146 return (
147 <>
148 <output>Question {state.activePendingQuestionIndex + 1}</output>
149 <button
150 type="button"
151 onClick={() => state.onSelectActivePendingUserInputOption("question-0", "Incremental")}
152 >
153 Choose Incremental
154 </button>
155 <button type="button" onClick={() => state.onAdvanceActivePendingUserInput()}>
156 Submit
157 </button>
158 </>
159 );
161​
162it("stays on an unanswered question when the composer submits", async () => {
163 await using screen = await render(
164 <QuestionPositionProbe
165 environmentId={EnvironmentId.make("unanswered-environment")}
166 projection={questionProjection(threadRef.threadId)}
167 />,
168 );
169 const submit = screen.getByRole("button", { name: "Submit" });
170 await userEvent.click(submit);
171 await expect.element(screen.getByRole("status")).toHaveTextContent("Question 1");
172​
173 await userEvent.click(screen.getByRole("button", { name: "Choose Incremental" }));
174 await userEvent.click(submit);
175 await expect.element(screen.getByRole("status")).toHaveTextContent("Question 2");
176});
177​
178it("isolates drafts by environment, thread and request and discards only resolved requests", async () => {
179 using _timers = fakeTimers();
180 const environmentId = EnvironmentId.make("scope-environment");
181 const projection = questionProjection(threadRef.threadId);
182 const scopes = [
183 { environmentId, projection },
184 { environmentId: EnvironmentId.make("other-environment"), projection },
185 { environmentId, projection: questionProjection(ThreadId.make("other-thread")) },
186 { environmentId, projection: questionProjection(threadRef.threadId, ["second", "first"]) },
187 ];
188 await using screen = await render(null);
189 const show = (scope: ComponentProps<typeof PendingRequestsProbe>) =>
190 screen.rerender(<PendingRequestsProbe {...scope} />);
191 for (const [index, scope] of scopes.entries()) {
192 await show(scope);
193 expect(requests.activePendingQuestionIndex).toBe(0);
194 expect(requests.activePendingDraftAnswers["question-0"]?.customAnswer).toBeUndefined();
195 await act(() =>
196 requests.onChangeActivePendingUserInputCustomAnswer("question-0", `Answer ${index}`),
197 );
198 await act(() => requests.onAdvanceActivePendingUserInput());
199 }
200​
201 // "first" was answered on another device.
202 await show({
203 environmentId,
204 projection: {
205 ...projection,
206 runtimeRequests: projection.runtimeRequests.map((request) =>
207 request.id === "first"
208 ? { ...request, status: "resolved", resolvedAt: projection.updatedAt }
209 : request,
210 ),
211 },
212 });
213 expect(requests.activePendingUserInput?.requestId).toBe("second");
214 await act(() =>
215 makeThreadRequestsResolvedAnnouncer(
216 environmentId,
217 threadRef.threadId,
218 )([RuntimeRequestId.make("second")]),
219 );
220 for (const [index, scope] of scopes.entries()) {
221 await show(scope);
222 expect(requests.activePendingQuestionIndex).toBe(index === 0 ? 0 : 1);
223 expect(requests.activePendingDraftAnswers["question-0"]?.customAnswer).toBe(
224 index === 0 ? undefined : `Answer ${index}`,
225 );
226 }
227});