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

ComposerPendingUserInputPanel.navigation.browser.test.tsx

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