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

ChatView.previewAttach.browser.test.tsx

323 lines12.4 KB

1import { createMemoryHistory } from "@tanstack/react-router";
2import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
4import type * as Context from "effect/Context";
5import { expect, it, vi } from "vite-plus/test";
6import { page, userEvent } from "vite-plus/test/browser";
7​
8import { AppRoot } from "~/AppRoot";
9// The route loads ChatView lazily; importing it here keeps its first transform out of the timeout.
10import "~/components/ChatView";
11import { useComposerDraftStore } from "~/composerDraftStore";
12import { __setClientSettingsForTests } from "~/hooks/useSettings";
13import { useRightPanelStore } from "~/rightPanelStore";
14import { getRouter } from "~/router";
15import {
16 ENVIRONMENT_ID,
17 installFakeEnvironment,
18 threadWithHistory,
19 type FakeDriver,
20} from "../../test/fakeEnvironment";
21import { render } from "../../test/render";
22​
23// A 1x1 PNG: screenshots go through image intake, which decodes them.
24const PNG_BYTES = Uint8Array.from(
25 atob(
26 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
27 ),
28 (char) => char.charCodeAt(0),
29);
30​
31const desktop = vi.hoisted(() => {
32 // Any bridge call the panel makes that this test does not care about resolves to a stub.
33 const stub = (): unknown =>
34 new Proxy(() => stub(), { get: (_target, key) => (key === "then" ? undefined : stub()) });
35 const preview = {
36 captureScreenshot: vi.fn(),
37 readArtifact: vi.fn<(id: string, maxBytes: number) => Promise<Uint8Array>>(),
38 revealArtifact: vi.fn(async () => undefined),
39 recording: stub(),
40 };
41 const bridge = new Proxy(preview, {
42 get: (target, key) => (key in target ? target[key as keyof typeof target] : stub()),
43 });
44 return {
45 bridge,
46 preview,
47 recordingRuntimeTabId: null as string | null,
48 stopBrowserRecording: vi.fn(),
49 // While set, image compression waits on it, as a large screenshot would.
50 compression: null as { started: boolean; gate: Promise<void> } | null,
51 };
52});
53​
54// The socket is the only fake layer of the app; the desktop preview host is stubbed above.
55vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => {
56 const [actual, { fakeDriver }, Layer] = await Promise.all([
57 importOriginal<{ readonly ConnectionDriver: Context.Key<unknown, FakeDriver> }>(),
58 import("../../test/fakeEnvironment"),
59 import("effect/Layer"),
60 ]);
61 return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) };
62});
63vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({
64 ...(await original()),
65 trackRpcRequestSent: () => {},
66}));
67// Only the Electron preview host is stubbed; the rest of the app runs as on the web.
68vi.mock(import("~/components/preview/previewBridge"), async (original) => ({
69 ...(await original()),
70 previewBridge: desktop.bridge as never,
71}));
72// The desktop host owns tab state; every thread here shows one loaded desktop tab.
73vi.mock(import("~/previewStateStore"), async (original) => {
74 const actual = await original();
75 return {
76 ...actual,
77 isPreviewSupportedInRuntime: () => true,
78 useThreadPreviewState: ((ref: { threadId: string }) => ({
79 ...actual.useThreadPreviewState(ref as never),
80 activeTabId: "tab-1",
81 desktopByTabId: {
82 "tab-1": {
83 hasWebContents: true,
84 navStatus: { _tag: "Success", url: "http://example.com/", title: "Example" },
85 canGoBack: false,
86 canGoForward: false,
87 loading: false,
88 zoomFactor: 1,
89 pictureInPicture: false,
90 colorScheme: "system",
91 audioMuted: false,
92 audible: false,
93 controller: "none",
94 },
95 },
96 sessions: {
97 "tab-1": {
98 threadId: ref.threadId,
99 tabId: "tab-1",
100 runtime: "desktop",
101 navStatus: { _tag: "Success", url: "http://example.com/", title: "Example" },
102 canGoBack: false,
103 canGoForward: false,
104 updatedAt: "2026-07-13T00:00:00.000Z",
105 },
106 },
107 })) as never,
108 };
109});
110vi.mock(import("~/components/preview/usePreviewSession"), async (original) => ({
111 ...(await original()),
112 usePreviewSession: () => {},
113}));
114vi.mock(import("~/lib/imageCompression"), async (original) => {
115 const actual = await original();
116 return {
117 ...actual,
118 prepareImageForAttachment: async (
119 ...args: Parameters<typeof actual.prepareImageForAttachment>
120 ) => {
121 const held = desktop.compression;
122 if (held) {
123 held.started = true;
124 await held.gate;
125 }
126 return actual.prepareImageForAttachment(...args);
127 },
128 };
129});
130vi.mock(import("~/browser/browserRecording"), async (original) => ({
131 ...(await original()),
132 findActiveBrowserRecordingRuntimeTabId: () => desktop.recordingRuntimeTabId,
133 stopBrowserRecording: desktop.stopBrowserRecording,
134}));
135​
136// The vi.mock factories read this shared state, so each test starts from a clean copy.
137function setup(recordingRuntimeTabId: string | null = null) {
138 desktop.preview.captureScreenshot.mockReset();
139 desktop.preview.readArtifact.mockReset();
140 desktop.preview.revealArtifact.mockClear();
141 desktop.stopBrowserRecording.mockReset();
142 desktop.recordingRuntimeTabId = recordingRuntimeTabId;
143 desktop.compression = null;
145​
146async function openThreadWithBrowser(threadIds: ReadonlyArray<string>) {
147 // Wide enough for the docked right panel, as on a desktop window.
148 await page.viewport(1600, 1000);
149 await using stack = new AsyncDisposableStack();
150 const threads = threadIds.map((id) => threadWithHistory(id, 1));
151 stack.use(installFakeEnvironment(threads, { acceptCommands: true }));
152 __setClientSettingsForTests({
153 ...DEFAULT_CLIENT_SETTINGS,
154 onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
155 });
156 const router = getRouter(
157 createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${threads[0]!.id}`] }),
158 );
159 await router.load();
160 stack.use(await render(<AppRoot router={router} />, { router: false }));
161 await expect.element(page.getByText(`Answer 0 for ${threadIds[0]}.`)).toBeVisible();
162 useRightPanelStore
163 .getState()
164 .openBrowser(scopeThreadRef(ENVIRONMENT_ID, threads[0]!.id), "tab-1");
165 // Unmounts the app, then the fake environment, as the tests' own bindings did.
166 return { app: stack.move(), router, threads };
168​
169const draftOf = (threadId: string) =>
170 useComposerDraftStore
171 .getState()
172 .getComposerDraft(scopeThreadRef(ENVIRONMENT_ID, threadId as never));
173​
174const saved = (kind: "screenshot" | "recording") =>
175 kind === "screenshot"
176 ? {
177 id: "shot",
178 path: "/artifacts/shot.png",
179 mimeType: "image/png",
180 sizeBytes: PNG_BYTES.length,
181 }
182 : { id: "clip", path: "/artifacts/clip.webm", mimeType: "video/webm", sizeBytes: 3 };
183​
184async function saveCapture(kind: "screenshot" | "recording") {
185 const artifact = saved(kind);
186 if (kind === "recording") {
187 desktop.stopBrowserRecording.mockResolvedValue(artifact);
188 desktop.preview.readArtifact.mockResolvedValue(new Uint8Array([1, 2, 3]));
189 await userEvent.click(page.getByRole("button", { name: "Stop recording" }));
190 } else {
191 desktop.preview.captureScreenshot.mockResolvedValue(artifact);
192 desktop.preview.readArtifact.mockResolvedValue(PNG_BYTES);
193 await userEvent.click(page.getByRole("button", { name: "Capture screenshot" }));
194 }
195 await expect
196 .element(page.getByText(kind === "screenshot" ? "Screenshot saved" : "Recording saved"))
197 .toBeVisible();
198 return artifact;
200​
201it.each(["screenshot", "recording"] as const)(
202 "Attach to chat stages a saved %s in the open thread's composer",
203 async (kind) => {
204 setup(kind === "recording" ? "recording" : null);
205 const { app, threads } = await openThreadWithBrowser([`thread-attach-${kind}`]);
206 await using _app = app;
207 const artifact = await saveCapture(kind);
208​
209 await userEvent.click(page.getByRole("button", { name: "Attach to chat" }));
210​
211 await vi.waitFor(() => {
212 const draft = draftOf(threads[0]!.id);
213 const staged = kind === "screenshot" ? draft?.images : draft?.files;
214 expect(staged?.map((attachment) => attachment.name)).toEqual([
215 artifact.path.slice(artifact.path.lastIndexOf("/") + 1),
216 ]);
217 });
218 expect(desktop.preview.readArtifact).toHaveBeenLastCalledWith(artifact.id, expect.any(Number));
219 await expect.element(page.getByText("Unable to add to chat")).not.toBeInTheDocument();
220 },
221);
222​
223it("Attach to chat leaves another thread's composer alone when the chat changes mid-read", async () => {
224 setup();
225 const { router, app, threads } = await openThreadWithBrowser([
226 "thread-capture-origin",
227 "thread-capture-elsewhere",
228 ]);
229 await using _app = app;
230 await saveCapture("screenshot");
231 let finishRead!: (bytes: Uint8Array) => void;
232 desktop.preview.readArtifact.mockImplementationOnce(
233 () => new Promise((resolve) => (finishRead = resolve)),
234 );
235​
236 await userEvent.click(page.getByRole("button", { name: "Attach to chat" }));
237 await vi.waitFor(() => expect(finishRead).toBeDefined());
238 await router.navigate({ href: `/${ENVIRONMENT_ID}/${threads[1]!.id}` });
239 await expect.element(page.getByText("Answer 0 for thread-capture-elsewhere.")).toBeVisible();
240 finishRead(PNG_BYTES);
241​
242 await router.navigate({ href: `/${ENVIRONMENT_ID}/${threads[0]!.id}` });
243 await expect
244 .element(page.getByText("Open the chat this capture came from and try again."))
245 .toBeVisible();
246 expect(draftOf(threads[1]!.id)?.images ?? []).toEqual([]);
247 expect(draftOf(threads[0]!.id)?.images ?? []).toEqual([]);
248});
249​
250it("a screenshot whose intake finishes after a chat switch leaves that chat's caret alone", async () => {
251 setup();
252 const { router, app, threads } = await openThreadWithBrowser([
253 "thread-focus-origin",
254 "thread-focus-elsewhere",
255 ]);
256 await using _app = app;
257 await saveCapture("screenshot");
258 let releaseCompression!: () => void;
259 const held = {
260 started: false,
261 gate: new Promise<void>((resolve) => (releaseCompression = resolve)),
262 };
263 desktop.compression = held;
264 try {
265 await userEvent.click(page.getByRole("button", { name: "Attach to chat" }));
266 await vi.waitFor(() => expect(held.started).toBe(true));
267​
268 await router.navigate({ href: `/${ENVIRONMENT_ID}/${threads[1]!.id}` });
269 await expect.element(page.getByText("Answer 0 for thread-focus-elsewhere.")).toBeVisible();
270 const editor = page.getByTestId("composer-editor");
271 await userEvent.click(editor);
272 await userEvent.keyboard("hello");
273 await expect.element(editor).toHaveTextContent("hello");
274 await userEvent.keyboard("{Home}");
275​
276 releaseCompression();
277 // The image still lands in the chat it was captured in.
278 await vi.waitFor(() => expect(draftOf(threads[0]!.id)?.images).toHaveLength(1));
279 await userEvent.keyboard("X");
280 await expect.element(editor).toHaveTextContent("Xhello");
281 expect(draftOf(threads[1]!.id)?.images ?? []).toEqual([]);
282 } finally {
283 // An early failure must not leave intake waiting on the gate.
284 releaseCompression();
285 desktop.compression = null;
286 }
287});
288​
289it("a saved recording that restores an interrupted attachment counts as attached", async () => {
290 setup("recording");
291 const { app, threads } = await openThreadWithBrowser(["thread-reattach"]);
292 await using _app = app;
293 // An interrupted upload left a marker with this recording's name, type and size.
294 useComposerDraftStore.getState().addFiles(scopeThreadRef(ENVIRONMENT_ID, threads[0]!.id), [
295 {
296 type: "file",
297 id: "marker-clip",
298 name: "clip.webm",
299 mimeType: "video/webm",
300 sizeBytes: 3,
301 file: null,
302 },
303 ]);
304 await saveCapture("recording");
305​
306 await userEvent.click(page.getByRole("button", { name: "Attach to chat" }));
307 await vi.waitFor(() => {
308 const files = draftOf(threads[0]!.id)?.files ?? [];
309 expect(files).toHaveLength(1);
310 expect(files[0]).toMatchObject({ name: "clip.webm", mimeType: "video/webm" });
311 expect(files[0]!.file).not.toBeNull();
312 // The store gives the restored slot the new attachment's id and rewrites its references.
313 expect(files[0]!.id).not.toBe("marker-clip");
314 });
315 await expect.element(page.getByText("Unable to add to chat")).not.toBeInTheDocument();
316​
317 // The same recording again duplicates the restored file, which the draft drops.
318 await userEvent.click(page.getByRole("button", { name: "Attach to chat" }));
319 await expect
320 .element(page.getByText("The chat isn't ready to accept input right now."))
321 .toBeVisible();
322 expect(draftOf(threads[0]!.id)?.files).toHaveLength(1);
323});