Skip to content

Commit 57bf042

Browse files
committed
test(web): cover pending question draft switching
1 parent 9a946ce commit 57bf042

1 file changed

Lines changed: 280 additions & 0 deletions

File tree

Lines changed: 280 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,280 @@
1+
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2+
import {
3+
ApprovalRequestId,
4+
DEFAULT_CLIENT_SETTINGS,
5+
DEFAULT_UNIFIED_SETTINGS,
6+
EnvironmentId,
7+
ThreadId,
8+
} from "@t3tools/contracts";
9+
import { act, type ComponentProps } from "react";
10+
import { create, type ReactTestRenderer } from "react-test-renderer";
11+
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
12+
13+
import { useComposerDraftStore } from "../../composerDraftStore";
14+
import { derivePendingUserInputProgress } from "../../pendingUserInput";
15+
import { questionAttachmentDraftId } from "../../questionAttachments";
16+
import type { ComposerPromptEditor } from "../ComposerPromptEditor";
17+
import { ChatComposer, type ChatComposerProps } from "./ChatComposer";
18+
19+
// Keep composer state and draft storage real; omit the DOM editor and unrelated RPCs.
20+
vi.mock("../ComposerPromptEditor", () => ({
21+
ComposerPromptEditor: (props: ComponentProps<typeof ComposerPromptEditor>) => {
22+
editor = props;
23+
return null;
24+
},
25+
}));
26+
vi.mock("../../hooks/useSettings", () => ({
27+
useClientSettings: (select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>
28+
select(DEFAULT_CLIENT_SETTINGS),
29+
useEnvironmentIdentificationMode: () => "none",
30+
}));
31+
vi.mock("./PierreEntryIcon", () => ({ PierreEntryIcon: () => null }));
32+
vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
33+
vi.mock("../../lib/composerPathSearchState", () => ({
34+
useComposerPathSearch: () => ({ entries: [], error: null, isPending: false }),
35+
}));
36+
vi.mock("./ProviderModelPicker", () => ({ ProviderModelPicker: () => null }));
37+
vi.mock("../SidebarStageBackdrop", () => ({
38+
StageBackdropButtonArt: () => null,
39+
useSidebarStageBackdropVariant: () => null,
40+
}));
41+
42+
const threadRef = scopeThreadRef(EnvironmentId.make("test-env"), ThreadId.make("test-thread"));
43+
const pendingInput = {
44+
requestId: ApprovalRequestId.make("test-request"),
45+
createdAt: "2026-08-15T00:00:00.000Z",
46+
questions: [{ id: "approach", header: "Approach", question: "Which approach?", options: [] }],
47+
dismissible: true,
48+
};
49+
50+
let renderer: ReactTestRenderer | undefined;
51+
let props: ChatComposerProps;
52+
let editor: ComponentProps<typeof ComposerPromptEditor>;
53+
54+
function renderComposer() {
55+
return act(() => {
56+
if (renderer) renderer.update(<ChatComposer {...props} />);
57+
else renderer = create(<ChatComposer {...props} />);
58+
});
59+
}
60+
61+
function toggle(label: string) {
62+
return renderer!.root.find((node) => node.type === "button" && node.children.includes(label));
63+
}
64+
65+
beforeEach(() => {
66+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
67+
vi.stubGlobal("Element", EventTarget);
68+
vi.stubGlobal("document", Object.assign(new EventTarget(), { activeElement: null }));
69+
vi.stubGlobal(
70+
"window",
71+
Object.assign(new EventTarget(), {
72+
Element,
73+
performance,
74+
matchMedia: () => Object.assign(new EventTarget(), { matches: false }),
75+
setTimeout,
76+
clearTimeout,
77+
requestAnimationFrame: () => 0,
78+
cancelAnimationFrame: () => {},
79+
}),
80+
);
81+
useComposerDraftStore.setState({ draftsByThreadKey: {} });
82+
props = {
83+
composerDraftTarget: threadRef,
84+
environmentId: threadRef.environmentId,
85+
attachmentUploadsCapabilityKnown: false,
86+
supportsAttachmentUploads: false,
87+
supportsQuestionAttachments: true,
88+
maxFileAttachmentBytes: null,
89+
routeKind: "server",
90+
routeThreadRef: threadRef,
91+
draftId: null,
92+
activeThreadId: threadRef.threadId,
93+
activeThreadEnvironmentId: threadRef.environmentId,
94+
activeThread: undefined,
95+
activeThreadShell: null,
96+
promptHistoryMessages: [],
97+
isServerThread: true,
98+
isLocalDraftThread: false,
99+
forceExpandedOnMobile: false,
100+
projectSelectionRequired: false,
101+
phase: "ready",
102+
isConnecting: false,
103+
isSendBusy: false,
104+
sendDisabledReason: null,
105+
isPreparingWorktree: false,
106+
bannerItems: [],
107+
environmentUnavailable: null,
108+
activePendingApproval: null,
109+
pendingApprovals: [],
110+
pendingUserInputs: [],
111+
activePendingProgress: null,
112+
activePendingResolvedAnswers: null,
113+
activePendingIsResponding: false,
114+
activePendingDraftAnswers: {},
115+
activePendingQuestionIndex: 0,
116+
respondingRequestIds: [],
117+
showPlanFollowUpPrompt: false,
118+
activeProposedPlan: null,
119+
activeTasksProgress: null,
120+
activeTaskSteps: null,
121+
threadSyncPhase: null,
122+
runtimeMode: "full-access",
123+
interactionMode: "default",
124+
lockedProvider: null,
125+
providerStatuses: [],
126+
providerCatalogKnown: false,
127+
activeProjectDefaultModelSelection: null,
128+
activeThreadModelSelection: null,
129+
activeContextWindow: null,
130+
compactThreadUnavailable: true,
131+
compactDisabled: true,
132+
compactDisabledReason: null,
133+
resolvedTheme: "dark",
134+
settings: DEFAULT_UNIFIED_SETTINGS,
135+
keybindings: [],
136+
terminalOpen: false,
137+
gitCwd: null,
138+
restingControlsHost: null,
139+
restingControlsHaveLeadingContext: false,
140+
onRestingControlsVisibilityChange: () => {},
141+
getTimelineScrollableNode: () => null,
142+
isTimelineAtLogicalEnd: () => true,
143+
timelineOverflows: false,
144+
onComposerOverlayHeightChange: () => {},
145+
onRestingChange: () => {},
146+
promptRef: { current: "" },
147+
composerImagesRef: { current: [] },
148+
composerFilesRef: { current: [] },
149+
composerTerminalContextsRef: { current: [] },
150+
composerElementContextsRef: { current: [] },
151+
composerRef: { current: null },
152+
onPageScrollKeyDown: () => {},
153+
onPageScrollKeyUp: () => {},
154+
onPageScrollRelease: () => {},
155+
onSend: () => {},
156+
onInterrupt: () => {},
157+
onImplementPlanInNewThread: () => {},
158+
onRespondToApproval: async () => {},
159+
onSelectActivePendingUserInputOption: () => {},
160+
onAdvanceActivePendingUserInput: () => {},
161+
onDismissActivePendingUserInput: () => {},
162+
onPreviousActivePendingUserInputQuestion: () => {},
163+
onChangeActivePendingUserInputCustomAnswer: (questionId, customAnswer) => {
164+
props.activePendingDraftAnswers[questionId] = { selectedOptionValues: [], customAnswer };
165+
props.activePendingProgress = derivePendingUserInputProgress(
166+
pendingInput.questions,
167+
props.activePendingDraftAnswers,
168+
0,
169+
);
170+
renderer!.update(<ChatComposer {...props} />);
171+
},
172+
onToggleAnsweringPendingUserInput: () => {
173+
props.activePendingProgress = props.activePendingProgress
174+
? null
175+
: derivePendingUserInputProgress(
176+
pendingInput.questions,
177+
props.activePendingDraftAnswers,
178+
0,
179+
);
180+
renderer!.update(<ChatComposer {...props} />);
181+
},
182+
onProviderModelSelect: () => {},
183+
onOpenProviderSetup: () => {},
184+
getModelDisabledReason: () => null,
185+
toggleInteractionMode: () => {},
186+
handleRuntimeModeChange: () => {},
187+
handleInteractionModeChange: () => {},
188+
focusComposer: () => {},
189+
scheduleComposerFocus: () => {},
190+
setThreadError: () => {},
191+
onExpandImage: () => {},
192+
onFileOpen: () => {},
193+
};
194+
});
195+
196+
afterEach(async () => {
197+
await act(() => renderer?.unmount());
198+
renderer = undefined;
199+
useComposerDraftStore.setState({ draftsByThreadKey: {} });
200+
vi.unstubAllGlobals();
201+
});
202+
203+
it("keeps typing in the message until answering, and restores each draft and its attachments", async () => {
204+
const store = useComposerDraftStore.getState();
205+
store.setPrompt(threadRef, "Use the existing migration and ");
206+
const file = new File(["notes"], "message.txt", { type: "text/plain" });
207+
const attachment = {
208+
type: "file" as const,
209+
id: "message-file",
210+
name: file.name,
211+
mimeType: file.type,
212+
sizeBytes: file.size,
213+
file,
214+
};
215+
store.addFiles(threadRef, [attachment]);
216+
await renderComposer();
217+
218+
props.pendingUserInputs = [pendingInput];
219+
await renderComposer();
220+
expect(editor.value).toBe("Use the existing migration and ");
221+
expect(props.composerFilesRef.current).toEqual([attachment]);
222+
props.respondingRequestIds = [pendingInput.requestId];
223+
await renderComposer();
224+
expect(toggle("Answer question").props.disabled).toBe(true);
225+
expect(editor.disabled).toBe(false);
226+
props.respondingRequestIds = [];
227+
await renderComposer();
228+
229+
const message = "Use the existing migration and keep the API unchanged.";
230+
await act(() => editor.onChange(message, message.length, message.length, false, []));
231+
expect(props.composerRef.current?.getSendContext()).toMatchObject({
232+
prompt: message,
233+
files: [attachment],
234+
});
235+
236+
await act(() => toggle("Answer question").props.onClick());
237+
expect(editor.value).toBe("");
238+
expect(props.composerFilesRef.current).toEqual([]);
239+
await act(() => editor.onChange("Incrementally", 13, 13, false, []));
240+
const answerAttachment = { ...attachment, id: "answer-file", name: "answer.txt" };
241+
await act(() =>
242+
store.addFiles(
243+
questionAttachmentDraftId(
244+
threadRef.environmentId,
245+
threadRef.threadId,
246+
pendingInput.requestId,
247+
"approach",
248+
),
249+
[answerAttachment],
250+
),
251+
);
252+
253+
await act(() => toggle("Back to message").props.onClick());
254+
expect(editor.value).toBe(message);
255+
expect(props.composerRef.current?.getSendContext()).toMatchObject({
256+
prompt: message,
257+
files: [attachment],
258+
});
259+
260+
await act(() => toggle("Answer question").props.onClick());
261+
expect(editor.value).toBe("Incrementally");
262+
expect(props.composerRef.current?.getSendContext()).toMatchObject({
263+
prompt: "Incrementally",
264+
files: [answerAttachment],
265+
});
266+
props.activePendingIsResponding = true;
267+
await renderComposer();
268+
expect(toggle("Back to message").props.disabled).toBe(true);
269+
expect(editor.disabled).toBe(true);
270+
271+
props.pendingUserInputs = [];
272+
props.activePendingProgress = null;
273+
props.activePendingIsResponding = false;
274+
await renderComposer();
275+
expect(editor.value).toBe(message);
276+
expect(props.composerRef.current?.getSendContext()).toMatchObject({
277+
prompt: message,
278+
files: [attachment],
279+
});
280+
});

0 commit comments

Comments
 (0)