The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 301 lines 11.5 KB
Raw
1 import {
2 EnvironmentId,
3 NodeId,
4 RuntimeRequestId,
5 ThreadId,
6 TurnItemId,
7 type OrchestrationV2ThreadProjection,
8 } from "@t3tools/contracts";
9 import { makeThreadRequestsResolvedAnnouncer } from "@t3tools/client-runtime/state/thread-requests";
10 import { useLayoutEffect, useRef, type ComponentProps } from "react";
11 import { expect, it, vi } from "vite-plus/test";
12 import { userEvent } from "vite-plus/test/browser";
13
14 vi.mock(import("../ChatMarkdown"), async (importOriginal) => ({
15 ...(await importOriginal()),
16 default: (({ text }: { text: string }) => <p>{text}</p>) as never,
17 }));
18
19 import { act, fakeTimers, render } from "../../../test/render";
20 import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
21 import { makeThreadProjectionFixture } from "../../test-fixtures";
22 import { toastManager } from "../ui/toast";
23 import { usePendingThreadRequests, usePendingUserInputDraft } from "./usePendingThreadRequests";
24
25 const threadRef = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") };
26
27 const 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
41 function 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
79 interface ProbeProps {
80 environmentId: EnvironmentId;
81 projection: OrchestrationV2ThreadProjection;
82 loading?: boolean;
83 draftTarget?: DraftId;
84 }
85
86 function useProbeRequests({ environmentId, projection, loading = false, draftTarget }: ProbeProps) {
87 const promptRef = useRef("");
88 const composerRef = useRef(null);
89 const requests = 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 });
101 const draft = usePendingUserInputDraft({
102 environmentId,
103 activeThreadId: projection.thread.id,
104 activePendingUserInput: requests.activePendingUserInput,
105 supportsQuestionAttachments: false,
106 });
107 return { ...requests, ...draft };
108 }
109
110 let requests: ReturnType<typeof useProbeRequests>;
111
112 function PendingRequestsProbe(props: ProbeProps) {
113 const state = useProbeRequests(props);
114 useLayoutEffect(() => {
115 requests = state;
116 });
117 return null;
118 }
119
120 it("retains answers, selections and question position after leaving chat, including while the projection reloads", async () => {
121 using _timers = fakeTimers();
122 const environmentId = EnvironmentId.make("remount-environment");
123 const projection = questionProjection(threadRef.threadId);
124 const probe = (loading = false) => (
125 <PendingRequestsProbe environmentId={environmentId} projection={projection} loading={loading} />
126 );
127 await using screen = await render(probe());
128 await act(() =>
129 requests.onChangeActivePendingUserInputCustomAnswer("question-0", "Keep my text"),
130 );
131 await act(() => requests.onAdvanceActivePendingUserInput());
132 await act(() => requests.onSelectActivePendingUserInputOption("question-1", "Incremental"));
133 await act(() => requests.onAdvanceActivePendingUserInput());
134 const expected = {
135 activePendingQuestionIndex: 2,
136 activePendingDraftAnswers: {
137 "question-0": { customAnswer: "Keep my text" },
138 "question-1": { selectedOptionValues: ["Incremental"] },
139 },
140 };
141 expect(requests).toMatchObject(expected);
142
143 // New thread and Settings both unmount the chat that owns this hook.
144 await screen.rerender(null);
145 await screen.rerender(probe());
146 expect(requests).toMatchObject(expected);
147
148 await screen.rerender(null);
149 await screen.rerender(probe(true));
150 expect(requests.activePendingUserInput).toBeNull();
151 await screen.rerender(probe());
152 expect(requests).toMatchObject(expected);
153 });
154
155 it("tells the user when an option click moves their typed answer into the hidden composer draft", async () => {
156 using _timers = fakeTimers();
157 const environmentId = EnvironmentId.make("displaced-environment");
158 const draftTarget = { environmentId, threadId: threadRef.threadId };
159 const draftPrompt = () => useComposerDraftStore.getState().getComposerDraft(draftTarget)?.prompt;
160 using toast = vi.spyOn(toastManager, "add");
161 const probe = (threadId: ThreadId) => (
162 <PendingRequestsProbe environmentId={environmentId} projection={questionProjection(threadId)} />
163 );
164 await using screen = await render(probe(threadRef.threadId));
165
166 await act(() => requests.onSelectActivePendingUserInputOption("question-0", "Incremental"));
167 expect(toast).not.toHaveBeenCalled();
168
169 await act(() => requests.onChangeActivePendingUserInputCustomAnswer("question-0", "first try"));
170 await act(() => requests.onSelectActivePendingUserInputOption("question-0", "Incremental"));
171 expect(draftPrompt()).toBe("first try");
172 expect(toast).toHaveBeenCalledTimes(1);
173 expect(toast).toHaveBeenCalledWith(
174 expect.objectContaining({
175 type: "info",
176 title: "Your typed text was set aside",
177 description: "It will be back in the composer once the question is answered.",
178 data: { threadRef: draftTarget },
179 }),
180 );
181
182 await act(() => requests.onChangeActivePendingUserInputCustomAnswer("question-0", "second try"));
183 expect(draftPrompt()).toBe("first try");
184 expect(requests.activePendingDraftAnswers["question-0"]).toMatchObject({
185 customAnswer: "second try",
186 });
187 expect(toast).toHaveBeenCalledTimes(1);
188
189 // The hook outlives a thread switch; text set aside in another thread is in another draft.
190 await screen.rerender(probe(ThreadId.make("other-thread")));
191 await act(() => requests.onChangeActivePendingUserInputCustomAnswer("question-0", "elsewhere"));
192 await act(() => requests.onSelectActivePendingUserInputOption("question-0", "Incremental"));
193 await screen.rerender(probe(threadRef.threadId));
194
195 // regression: #35205 undo puts the set-aside text back, so the draft must not keep a copy to resend
196 await act(() => requests.onChangeActivePendingUserInputCustomAnswer("question-0", "first try"));
197 expect(draftPrompt() ?? "").toBe("");
198
199 // Text set aside into a queued-message edit draft never withdraws from the thread draft.
200 await screen.rerender(
201 <PendingRequestsProbe
202 environmentId={environmentId}
203 projection={questionProjection(threadRef.threadId)}
204 draftTarget={DraftId.make("queued-edit")}
205 />,
206 );
207 await act(() => requests.onChangeActivePendingUserInputCustomAnswer("question-0", "foo"));
208 await act(() => requests.onSelectActivePendingUserInputOption("question-0", "Incremental"));
209 await screen.rerender(probe(threadRef.threadId));
210 useComposerDraftStore.getState().setPrompt(draftTarget, "foo");
211 await act(() => requests.onChangeActivePendingUserInputCustomAnswer("question-0", "foo"));
212 expect(draftPrompt()).toBe("foo");
213 });
214
215 function QuestionPositionProbe(props: ProbeProps) {
216 const state = useProbeRequests(props);
217 return (
218 <>
219 <output>Question {state.activePendingQuestionIndex + 1}</output>
220 <button
221 type="button"
222 onClick={() => state.onSelectActivePendingUserInputOption("question-0", "Incremental")}
223 >
224 Choose Incremental
225 </button>
226 <button type="button" onClick={() => state.onAdvanceActivePendingUserInput()}>
227 Submit
228 </button>
229 </>
230 );
231 }
232
233 it("stays on an unanswered question when the composer submits", async () => {
234 await using screen = await render(
235 <QuestionPositionProbe
236 environmentId={EnvironmentId.make("unanswered-environment")}
237 projection={questionProjection(threadRef.threadId)}
238 />,
239 );
240 const submit = screen.getByRole("button", { name: "Submit" });
241 await userEvent.click(submit);
242 await expect.element(screen.getByRole("status")).toHaveTextContent("Question 1");
243
244 await userEvent.click(screen.getByRole("button", { name: "Choose Incremental" }));
245 await userEvent.click(submit);
246 await expect.element(screen.getByRole("status")).toHaveTextContent("Question 2");
247 });
248
249 it("isolates drafts by environment, thread and request and discards only resolved requests", async () => {
250 using _timers = fakeTimers();
251 const environmentId = EnvironmentId.make("scope-environment");
252 const projection = questionProjection(threadRef.threadId);
253 const scopes = [
254 { environmentId, projection },
255 { environmentId: EnvironmentId.make("other-environment"), projection },
256 { environmentId, projection: questionProjection(ThreadId.make("other-thread")) },
257 { environmentId, projection: questionProjection(threadRef.threadId, ["second", "first"]) },
258 ];
259 await using screen = await render(null);
260 const show = (scope: ComponentProps<typeof PendingRequestsProbe>) =>
261 screen.rerender(<PendingRequestsProbe {...scope} />);
262 for (const [index, scope] of scopes.entries()) {
263 await show(scope);
264 expect(requests.activePendingQuestionIndex).toBe(0);
265 expect(requests.activePendingDraftAnswers["question-0"]?.customAnswer).toBeUndefined();
266 await act(() =>
267 requests.onChangeActivePendingUserInputCustomAnswer("question-0", `Answer ${index}`),
268 );
269 await act(() => requests.onAdvanceActivePendingUserInput());
270 }
271
272 // "first" was answered on another device.
273 await show({
274 environmentId,
275 projection: {
276 ...projection,
277 runtimeRequests: projection.runtimeRequests.map((request) =>
278 request.id === "first"
279 ? { ...request, status: "resolved", resolvedAt: projection.updatedAt }
280 : request,
281 ),
282 },
283 });
284 expect(requests.activePendingUserInput?.requestId).toBe("second");
285 await act(() =>
286 makeThreadRequestsResolvedAnnouncer(
287 environmentId,
288 threadRef.threadId,
289 )([
290 { id: RuntimeRequestId.make("first"), status: "resolved" },
291 { id: RuntimeRequestId.make("second"), status: "pending" },
292 ]),
293 );
294 for (const [index, scope] of scopes.entries()) {
295 await show(scope);
296 expect(requests.activePendingQuestionIndex).toBe(index === 0 ? 0 : 1);
297 expect(requests.activePendingDraftAnswers["question-0"]?.customAnswer).toBe(
298 index === 0 ? undefined : `Answer ${index}`,
299 );
300 }
301 });