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

filePreview.test.ts

1,422 lines56.4 KB

1import {
2 act,
3 createElement,
4 Fragment,
5 useEffect,
6 useLayoutEffect,
7 useMemo,
8 type ReactNode,
9} from "react";
10import { createRoot } from "react-dom/client";
11import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
12​
13import { inlineFilePreviewKind, isPdfFile } from "./filePreview";
14import { ThreadInlineFilePreview } from "../features/threads/ThreadInlineFilePreview";
15import { AudioFilePreview } from "../features/files/AudioFilePreview";
16import { MediaVideoPlayer } from "../components/MediaVideoPlayer";
17import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
18import { acquireAudioSession, activateAudioSession, releaseAudioSession } from "./audioSession";
19import { ThreadFeed } from "../features/threads/ThreadFeed";
20import type { ThreadFeedEntry } from "./threadActivity";
21import type { MarkdownImageRenderer } from "../native/SelectableMarkdownText";
22​
23const audio = vi.hoisted(() => ({
24 status: {
25 playing: false,
26 isLoaded: false,
27 error: null,
28 didJustFinish: false,
29 currentTime: 0,
30 duration: 10,
31 isBuffering: false,
32 },
33 player: {
34 play: vi.fn(),
35 pause: vi.fn((_deactivateSession?: boolean) => {}),
36 release: vi.fn(),
37 replace: vi.fn(),
38 seekTo: vi.fn(async () => {}),
39 },
40 refresh: vi.fn<() => Promise<string | null>>(),
41 setAudioMode: vi.fn(async (_mode: unknown) => {}),
42 setActive: vi.fn(async (_active: boolean) => {}),
43 setSessionOwner: vi.fn((_owned: boolean) => {}),
44 sessionOwned: false,
45 enabled: true,
46 played: vi.fn(),
47 video: {
48 playing: false,
49 playbackRequested: false,
50 status: "readyToPlay",
51 play: vi.fn(),
52 pause: vi.fn(),
53 replaceAsync: vi.fn(async (_source: unknown) => {}),
54 addListener: vi.fn(),
55 },
56 videoListeners: new Set<(event: { isPlaying: boolean }) => void>(),
57 videoStatusListeners: new Set<(event: { status: string }) => void>(),
58 videoEndListeners: new Set<() => void>(),
59 videoRequestListeners: new Set<(event: { isPlaybackRequested: boolean }) => void>(),
60 navigate: vi.fn(),
61 query: vi.fn(),
62}));
63vi.mock("expo-audio", () => ({
64 AudioModule: { setAudioSessionOwner: audio.setSessionOwner },
65 useAudioPlayer: () => audio.player,
66 createAudioPlayer: () => audio.player,
67 useAudioPlayerStatus: () => audio.status,
68 setAudioModeAsync: audio.setAudioMode,
69 setIsAudioActiveAsync: audio.setActive,
70}));
71vi.mock("@react-navigation/native", () => ({
72 useIsFocused: () => true,
73 useNavigation: () => ({ navigate: audio.navigate }),
74 useRoute: () => ({ name: "Thread", params: {} }),
75 useFocusEffect: (callback: () => (() => void) | undefined) => useEffect(callback, [callback]),
76}));
77vi.mock("react-native", () => ({
78 Platform: { OS: "android", select: (values: { android?: unknown }) => values.android },
79 StyleSheet: { create: (styles: unknown) => styles },
80 useWindowDimensions: () => ({ width: 390, height: 844, fontScale: 1 }),
81 Text: ({ children }: { children?: ReactNode }) => createElement("span", null, children),
82 AppState: { currentState: "active", addEventListener: () => ({ remove() {} }) },
83 View: ({ children }: { children?: ReactNode }) => createElement("div", null, children),
84 Pressable: (props: {
85 children?: ReactNode;
86 onPress: () => void;
87 disabled?: boolean;
88 accessibilityLabel?: string;
89 accessibilityState?: { busy: boolean };
90 }) =>
91 createElement(
92 "button",
93 {
94 onClick: props.onPress,
95 disabled: props.disabled,
96 "aria-label": props.accessibilityLabel,
97 "aria-busy": props.accessibilityState?.busy,
98 },
99 props.children,
100 ),
101}));
102vi.mock("../components/PierreEntryIcon", () => ({ PierreEntryIcon: () => null }));
103vi.mock("../components/ui/AppText", () => ({
104 AppText: ({ children }: { children?: ReactNode }) => createElement("span", null, children),
105}));
106vi.mock("../components/ui/AppSymbol", () => ({ SymbolView: () => null }));
107vi.mock("../components/ui/Button", () => ({
108 Button: (props: { label: string; onPress(): void; disabled?: boolean }) =>
109 createElement("button", { onClick: props.onPress, disabled: props.disabled }, props.label),
110}));
111vi.mock("expo", () => ({
112 useEvent: (_player: unknown, _event: unknown, initial: unknown) => initial,
113 useReleasingSharedObjectWithLifecycle: (
114 lifecycle: {
115 factory: () => typeof audio.player;
116 release: (player: typeof audio.player) => void;
117 },
118 dependencies: ReadonlyArray<unknown>,
119 ) => {
120 const player = useMemo(lifecycle.factory, dependencies);
121 useEffect(() => () => lifecycle.release(player), [player]);
122 return player;
123 },
124}));
125vi.mock("expo-video", () => ({
126 useVideoPlayer: () => audio.video,
127 VideoView: () => null,
128}));
129vi.mock("../components/VideoThumbnailImage", () => ({ VideoThumbnailImage: () => null }));
130vi.mock("../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null }));
131vi.mock("../components/MediaActionsMenu", () => ({
132 MediaActionsMenu: ({ children }: { children?: ReactNode }) => children,
133}));
134vi.mock("../state/mediaActions", () => ({
135 useMediaActions: () => ({ sharing: false, actions: [] }),
136}));
137vi.mock("./videoAudioSession", () => ({
138 useMediaAudioSessionHold() {},
139 useFullscreenVideoOpen: () => false,
140}));
141vi.mock("../state/assets", () => ({
142 useRefreshAssetUrl: () => audio.refresh,
143 useAssetUrlState: () => ({ _tag: "Success", url: "https://example.com/clip.mp4" }),
144 assetEnvironment: {},
145}));
146vi.mock("../features/threads/ThreadMarkdownVideo", async (importOriginal) => {
147 const { createContext } = await import("react");
148 const actual = await importOriginal<typeof import("../features/threads/ThreadMarkdownVideo")>();
149 return {
150 ...actual,
151 ThreadMediaVisibleContext: createContext(true),
152 ThreadMarkdownVideo: (props: Parameters<typeof actual.ThreadMarkdownVideo>[0]) =>
153 createElement(actual.ThreadMarkdownVideo, { ...props, thumbnailVisible: true }),
154 };
155});
156​
157vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
158 ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
159 executeAtomQuery: (...args: unknown[]) => audio.query(...args),
160}));
161vi.mock("../state/projects", () => ({
162 projectEnvironment: {
163 searchEntries: (input: unknown) => input,
164 fileMetadata: (input: unknown) => input,
165 },
166}));
167vi.mock("../state/server", () => ({ serverEnvironment: {} }));
168vi.mock("../state/session", () => ({
169 readEnvironmentScope: () => true,
170 usePreparedConnection: () => ({ _tag: "Some", value: { httpBaseUrl: "https://example.com" } }),
171}));
172vi.mock("../state/atom-registry", () => ({ appAtomRegistry: {} }));
173vi.mock("../state/threads", () => ({ environmentThreadShells: {}, threadEnvironment: {} }));
174vi.mock("../state/entities", () => ({
175 useLiveThreadLinkLabels: (text: string) => text,
176 useThreadChipIcons: () => new Map(),
177}));
178vi.mock("../state/use-thread-selection", () => ({
179 useThreadSelection: () => ({ selectedThread: null }),
180}));
181vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
182vi.mock("../state/use-atom-command", () => ({}));
183vi.mock("../state/v2-item-support", () => ({}));
184vi.mock("../native/SelectableMarkdownText", () => ({
185 SelectableMarkdownText: (props: {
186 markdown: string;
187 onLinkPress(href: string): void;
188 renderImage?: MarkdownImageRenderer;
189 }) => {
190 const embed = props.markdown.match(/!\[([^\]]*)\]\(([^)]+)\)/);
191 return createElement(
192 "div",
193 null,
194 createElement("button", { onClick: () => props.onLinkPress("target.ts") }, props.markdown),
195 embed && props.renderImage?.({ href: embed[2]!, alt: embed[1]!, title: null }),
196 );
197 },
198}));
199vi.mock("@legendapp/list/keyboard", () => ({
200 KeyboardAwareLegendList: (props: {
201 data: ThreadFeedEntry[];
202 renderItem(info: { item: ThreadFeedEntry; index: number }): ReactNode;
203 }) =>
204 props.data.map((item, index) =>
205 createElement("div", { key: item.id }, props.renderItem({ item, index })),
206 ),
207}));
208vi.mock("@legendapp/list/react-native", () => ({
209 useViewabilityAmount: (callback: (token: { sizeVisible: number }) => void) =>
210 useEffect(() => callback({ sizeVisible: 1 }), [callback]),
211}));
212vi.mock("react-native-reanimated", () => {
213 const transition = { delay: () => transition, duration: () => transition };
214 return {
215 default: { View: ({ children }: { children?: ReactNode }) => children },
216 FadeIn: transition,
217 FadeInDown: transition,
218 FadeInUp: transition,
219 };
220});
221vi.mock("react-native-safe-area-context", () => ({
222 useSafeAreaInsets: () => ({ top: 0, bottom: 0 }),
223}));
224vi.mock("expo-haptics", () => ({ selectionAsync: async () => {} }));
225vi.mock("expo-image", () => ({}));
226vi.mock("uniwind", () => ({}));
227vi.mock("../components/ui/Dialog", () => ({}));
228vi.mock("../components/ui/NativePresentation", () => ({
229 PresentationSource: ({ children }: { children?: ReactNode }) => children,
230}));
231vi.mock("../components/ui/Menu", () => ({
232 Menu: ({ children }: { children?: ReactNode }) => children,
233}));
234vi.mock("../components/FilePreviewGallery", () => ({
235 FilePreviewGallery: ({ children }: { children?: ReactNode }) => children,
236}));
237vi.mock("../components/FilePreviewModal", () => ({
238 FilePreviewModal: (props: { source: { name: string } | null }) =>
239 props.source ? createElement("div", { "data-file-preview": props.source.name }) : null,
240}));
241vi.mock("../components/VideoPreviewModal", () => ({ VideoPreviewModal: () => null }));
242vi.mock("../components/ComposerContextSheet", () => ({}));
243vi.mock("../native/useOpenPullRequest", () => ({ useOpenPullRequest: () => vi.fn() }));
244vi.mock("../native/useMarkdownImageSource", () => ({ useMarkdownImageSource: () => vi.fn() }));
245vi.mock("../native/useEnrichedLinkVariants", () => ({
246 enrichedThreadLinkCustomization: () => undefined,
247 enrichedContextLinkCustomization: () => undefined,
248 withChipIcon: (value: unknown) => value,
249}));
250vi.mock("../native/NativeScrollViewMarker", () => ({
251 NativeScrollViewMarker: ({ children }: { children?: ReactNode }) => children,
252}));
253vi.mock("../native/NativeWorkspaceColumns", () => ({
254 useNativeWorkspaceColumnsSupported: () => false,
255}));
256vi.mock("../native/native-layout-metrics", () => ({ useDeviceType: () => "phone" }));
257vi.mock("../features/layout/workspace-content-width", () => ({
258 useWorkspaceSettledContentWidth: () => null,
259}));
260vi.mock("../features/settings/appearance/AppearancePreferencesProvider", () => ({
261 useAppearancePreferences: () => ({ appearance: { baseFontSize: 14 }, themeAppearance: "dark" }),
262}));
263vi.mock("./useUniwindTheme", () => ({
264 useUniwindTheme: () => new Proxy({}, { get: () => "#000000" }),
265}));
266vi.mock("./composerContextClipboard", () => ({}));
267vi.mock("./copyTextWithHaptic", () => ({}));
268vi.mock("./openExternalUrl", () => ({}));
269vi.mock("./attachmentDownload", () => ({}));
270vi.mock("./uuid", () => ({}));
271vi.mock("../features/threads/thread-context-divider", () => ({}));
272vi.mock("../features/threads/thread-handoff-row", () => ({}));
273vi.mock("../features/threads/ThreadGuestShareBar", () => ({ useThreadGuestShare: () => null }));
274vi.mock("../features/threads/SecretRequestCard", () => ({}));
275vi.mock("../features/threads/LinkRequestCard", () => ({ LinkRequestCard: () => null }));
276vi.mock("../features/threads/worktree-setup-card", () => ({}));
277vi.mock("../features/threads/CopyTextButton", () => ({ CopyTextButton: () => null }));
278vi.mock("../features/threads/thread-work-log", () => ({ THREAD_DISCLOSURE_TRANSITION_MS: 100 }));
279vi.mock("../features/threads/HtmlRenderWebView", () => ({}));
280vi.mock("../features/threads/McpAppWebView", () => ({}));
281vi.mock("../features/layout/AdaptiveWorkspaceLayout", () => ({
282 useAdaptiveWorkspaceLayout: () => ({ fileInspector: { supported: false } }),
283}));
284vi.mock("../features/threads/thread-workflow-opening", () => ({ useWorkflowOpening: () => null }));
285vi.mock("../features/threads/useFileChipShare", () => ({ useFileChipShare: () => vi.fn() }));
286vi.mock("../features/threads/ThreadMarkdownImage", async () => {
287 const { createContext } = await import("react");
288 return { MarkdownImageAvailableWidthContext: createContext(390) };
289});
290vi.mock("../features/review/ReviewCommentCard", () => ({ useReviewCommentColors: () => ({}) }));
291vi.mock("../features/prompt-links/prompt-link-actions", () => ({}));
292vi.mock("@react-navigation/elements", async () => {
293 const { createContext } = await import("react");
294 return { HeaderHeightContext: createContext(0) };
295});
296​
297describe("ThreadInlineFilePreview playback", () => {
298 let root: ReturnType<typeof createRoot> | undefined;
299 beforeEach(() => {
300 audio.sessionOwned = false;
301 audio.setSessionOwner.mockImplementation((owned) => {
302 audio.sessionOwned = owned;
303 });
304 audio.player.pause.mockReset();
305 audio.enabled = true;
306 audio.setActive.mockImplementation(async (enabled) => {
307 audio.enabled = enabled;
308 });
309 // Expo's play() silently does nothing while its global gate is disabled.
310 audio.player.play.mockImplementation(() => {
311 if (audio.enabled) audio.played();
312 });
313 audio.video.addListener.mockImplementation(
314 (event: string, listener: (event: { isPlaying: boolean }) => void) => {
315 if (event === "playbackRequestedChange") {
316 const requestListener = listener as unknown as (event: {
317 isPlaybackRequested: boolean;
318 }) => void;
319 audio.videoRequestListeners.add(requestListener);
320 return { remove: () => audio.videoRequestListeners.delete(requestListener) };
321 }
322 if (event === "statusChange") {
323 const statusListener = listener as unknown as (event: { status: string }) => void;
324 audio.videoStatusListeners.add(statusListener);
325 return { remove: () => audio.videoStatusListeners.delete(statusListener) };
326 }
327 if (event === "playToEnd") {
328 const endListener = listener as unknown as () => void;
329 audio.videoEndListeners.add(endListener);
330 return { remove: () => audio.videoEndListeners.delete(endListener) };
331 }
332 audio.videoListeners.add(listener);
333 return { remove: () => audio.videoListeners.delete(listener) };
334 },
335 );
336 audio.video.play.mockImplementation(() => {
337 audio.video.playing = true;
338 audio.video.playbackRequested = true;
339 for (const listener of audio.videoRequestListeners) listener({ isPlaybackRequested: true });
340 for (const listener of audio.videoListeners) listener({ isPlaying: audio.video.playing });
341 });
342 audio.video.pause.mockImplementation(() => {
343 const wasRequested = audio.video.playbackRequested;
344 const wasPlaying = audio.video.playing;
345 audio.video.playbackRequested = false;
346 audio.video.playing = false;
347 if (wasRequested) {
348 for (const listener of audio.videoRequestListeners)
349 listener({ isPlaybackRequested: false });
350 }
351 if (wasPlaying) {
352 for (const listener of audio.videoListeners) listener({ isPlaying: false });
353 }
354 });
355 });
356 afterEach(async () => {
357 await act(async () => root?.unmount());
358 root = undefined;
359 vi.clearAllMocks();
360 audio.refresh.mockReset();
361 audio.setAudioMode.mockReset();
362 audio.setActive.mockReset();
363 audio.video.status = "readyToPlay";
364 audio.status = {
365 playing: false,
366 isLoaded: false,
367 error: null,
368 didJustFinish: false,
369 currentTime: 0,
370 duration: 10,
371 isBuffering: false,
372 };
373 });
374​
375 it.each(
376 (["user", "assistant"] as const).flatMap((role) =>
377 (["attachment", "markdown"] as const).flatMap((origin) =>
378 (["audio", "video"] as const).flatMap((kind) =>
379 (kind === "video"
380 ? ["initial play", "native resume", "continued playback"]
381 : ["initial play"]
382 ).map((playback) => ({
383 role,
384 origin,
385 kind,
386 playback,
387 outcome: playback === "continued playback" ? "preserves" : "cancels",
388 })),
389 ),
390 ),
391 ),
392 )(
393 "$outcome a pending file lookup on $role $origin $kind $playback",
394 async ({ role, origin, kind, playback }) => {
395 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
396 const environmentId = EnvironmentId.make("environment-1");
397 const threadId = ThreadId.make("thread-1");
398 const messageId = MessageId.make("message-1");
399 const timestamp = "2026-10-20T00:00:00.000Z";
400 const name = kind === "audio" ? "clip.mp3" : "clip.mp4";
401 const mimeType = kind === "audio" ? "audio/mpeg" : "video/mp4";
402 const uri = `https://example.com/${name}`;
403 const feed: ThreadFeedEntry[] = [
404 {
405 type: "message",
406 id: messageId,
407 createdAt: timestamp,
408 message: {
409 id: messageId,
410 role,
411 text: `open target.ts${origin === "markdown" ? `\n\n![${name}](${uri})` : ""}`,
412 attachments:
413 origin === "attachment"
414 ? [{ type: "file", id: "clip", name, mimeType, sizeBytes: 12 }]
415 : [],
416 createdAt: timestamp,
417 updatedAt: timestamp,
418 runId: null,
419 streaming: false,
420 visibility: "local",
421 sourceThreadId: threadId,
422 },
423 },
424 ];
425 let finishLookup!: (value: unknown) => void;
426 const lookup = new Promise((resolve) => {
427 finishLookup = resolve;
428 });
429 audio.query
430 .mockResolvedValue({ _tag: "Success", value: { kind: "file" } })
431 .mockReturnValueOnce(lookup);
432 audio.refresh.mockResolvedValue(uri);
433 const container = document.createElement("div");
434 root = createRoot(container);
435 await act(async () =>
436 root!.render(
437 createElement(ThreadFeed, {
438 environmentId,
439 threadId,
440 detailRef: null,
441 threadTitle: "preview",
442 workspaceRoot: "/repo",
443 feed,
444 queuedMessages: [],
445 dispatchingMessageId: null,
446 onEditPendingMessage: null,
447 contentPresentation: { kind: "ready" },
448 latestRun: null,
449 activeWorkStartedAt: null,
450 listRef: { current: null },
451 freeze: { value: false } as Parameters<typeof ThreadFeed>[0]["freeze"],
452 contentInsetEndAdjustment: { value: 0 } as Parameters<
453 typeof ThreadFeed
454 >[0]["contentInsetEndAdjustment"],
455 anchorMessageId: null,
456 keyboardOffset: 0,
457 }),
458 ),
459 );
460 const link = Array.from(container.querySelectorAll("button")).find((button) =>
461 button.textContent?.startsWith("open target.ts"),
462 )!;
463 const playLabel = kind === "audio" ? "Play audio" : `Play ${name}`;
464 const play = () =>
465 container.querySelector<HTMLButtonElement>(`[aria-label="${playLabel}"]`)!.click();
466 if (playback !== "initial play") {
467 await act(async () => play());
468 expect(audio.video.playing).toBe(true);
469 if (playback === "native resume") {
470 await act(async () => audio.video.pause());
471 expect(audio.video.playing).toBe(false);
472 } else {
473 await act(async () => {
474 for (const listener of audio.videoRequestListeners)
475 listener({ isPlaybackRequested: true });
476 });
477 }
478 }
479 await act(async () => link.click());
480 const signal: AbortSignal = audio.query.mock.calls[0]![2].signal;
481 expect(signal.aborted).toBe(false);
482 expect(audio.navigate).not.toHaveBeenCalled();
483 await act(async () => {
484 if (playback === "native resume") {
485 // Native resume requests playback before buffering advances the clock.
486 audio.video.playbackRequested = true;
487 for (const listener of audio.videoRequestListeners)
488 listener({ isPlaybackRequested: true });
489 expect(audio.video.playing).toBe(false);
490 } else if (playback === "continued playback") {
491 for (const isPlaying of [false, true, false, true]) {
492 audio.video.playing = isPlaying;
493 for (const listener of audio.videoListeners) listener({ isPlaying });
494 for (const listener of audio.videoRequestListeners)
495 listener({ isPlaybackRequested: true });
496 }
497 expect(signal.aborted).toBe(false);
498 } else play();
499 });
500 expect(kind === "audio" ? audio.played : audio.video.play).toHaveBeenCalled();
501 expect(audio.sessionOwned).toBe(true);
502 await act(async () =>
503 finishLookup({
504 _tag: "Success",
505 value: { entries: [{ path: "src/target.ts", kind: "file" }] },
506 }),
507 );
508 if (playback === "continued playback") {
509 expect(audio.navigate).toHaveBeenCalledExactlyOnceWith("ThreadFile", {
510 environmentId,
511 threadId,
512 path: ["src", "target.ts"],
513 });
514 expect(signal.aborted).toBe(false);
515 } else {
516 expect(audio.navigate).not.toHaveBeenCalled();
517 expect(signal.aborted).toBe(true);
518 }
519 expect(container.querySelector(`[aria-label="${playLabel}"]`)).toBeNull();
520 if (kind === "audio")
521 expect(container.querySelector('[aria-label="Pause audio"]')).not.toBeNull();
522 else {
523 if (playback === "native resume") {
524 audio.video.playing = true;
525 for (const listener of audio.videoListeners) listener({ isPlaying: true });
526 }
527 expect(audio.video.playing).toBe(true);
528 }
529 },
530 );
531​
532 it.each(
533 ["takeover", "pause", "finish"].flatMap((release) => [
534 ["inline", "video", release],
535 ["viewer", "video", release],
536 ["inline", "native video controls", release],
537 ["viewer", "native video controls", release],
538 ["inline", "recording", release],
539 ["viewer", "recording", release],
540 ]),
541 )(
542 "keeps the shared session active when %s audio yields to %s after %s",
543 async (source, successor, release) => {
544 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
545 audio.status = { ...audio.status, isLoaded: true };
546 const container = document.createElement("div");
547 root = createRoot(container);
548 const render = (playVideo = false, showAudio = true) =>
549 root!.render(
550 createElement(
551 "div",
552 null,
553 showAudio
554 ? source === "inline"
555 ? createElement(ThreadInlineFilePreview, {
556 source: {
557 kind: "document",
558 name: "sound.mp3",
559 uri: "https://example.com/sound.mp3",
560 },
561 onOpen() {},
562 })
563 : createElement(AudioFilePreview, {
564 uri: "https://example.com/sound.mp3",
565 onRetry() {},
566 })
567 : null,
568 createElement(MediaVideoPlayer, {
569 uri: "https://example.com/clip.mp4",
570 name: "clip.mp4",
571 thumbnailKey: "clip",
572 expanded: true,
573 autoPlay: playVideo,
574 }),
575 ),
576 );
577 await act(async () => render());
578 await act(async () =>
579 [...container.querySelectorAll("button")]
580 .find(
581 (button) =>
582 button.getAttribute("aria-label") === "Play audio" || button.textContent === "Play",
583 )!
584 .click(),
585 );
586 expect(audio.played).toHaveBeenCalledOnce();
587 let sessionActive = true;
588 const deactivated = vi.fn();
589 // Match expo-audio iOS: the queued callback checks ownership at execution time.
590 const queueDeactivation = () =>
591 setTimeout(() => {
592 if (audio.sessionOwned) return;
593 sessionActive = false;
594 audio.video.playing = false;
595 deactivated();
596 }, 100);
597 audio.setSessionOwner.mockImplementation((owned) => {
598 audio.sessionOwned = owned;
599 if (!owned) queueDeactivation();
600 });
601 audio.player.pause.mockImplementation((deactivateSession) => {
602 if (deactivateSession !== false) queueDeactivation();
603 });
604 vi.useFakeTimers();
605 let recording: ReturnType<typeof acquireAudioSession> | undefined;
606 try {
607 if (release === "pause") {
608 await act(async () =>
609 [...container.querySelectorAll("button")]
610 .find(
611 (button) =>
612 button.getAttribute("aria-label") === "Pause audio" ||
613 button.textContent === "Pause",
614 )!
615 .click(),
616 );
617 } else if (release === "finish") {
618 // Native completion queues deactivation before JS receives didJustFinish.
619 queueDeactivation();
620 audio.status = { ...audio.status, playing: false, didJustFinish: true };
621 await act(async () => render());
622 }
623 if (release !== "takeover") {
624 expect(vi.getTimerCount()).toBeGreaterThan(0);
625 await vi.advanceTimersByTimeAsync(50);
626 }
627 await act(async () => {
628 if (successor === "recording") {
629 recording = acquireAudioSession("recording");
630 await activateAudioSession(recording);
631 } else if (successor === "native video controls") audio.video.play();
632 else render(true);
633 });
634 if (successor !== "recording") expect(audio.video.playing).toBe(true);
635 expect(audio.player.pause).toHaveBeenCalled();
636 // Cleanup of the old native ref must not interrupt the successor either.
637 await act(async () => render(successor === "video", false));
638 await vi.advanceTimersByTimeAsync(200);
639 expect(sessionActive).toBe(true);
640 expect(deactivated).not.toHaveBeenCalled();
641 expect(audio.setActive).not.toHaveBeenCalledWith(false);
642 if (successor !== "recording") expect(audio.video.playing).toBe(true);
643 else
644 expect(audio.setAudioMode).toHaveBeenLastCalledWith(
645 expect.objectContaining({ allowsRecording: true }),
646 );
647 await act(async () => root!.unmount());
648 root = undefined;
649 if (recording) await releaseAudioSession(recording);
650 recording = undefined;
651 await vi.advanceTimersByTimeAsync(200);
652 expect(sessionActive).toBe(false);
653 } finally {
654 if (recording) await releaseAudioSession(recording);
655 vi.clearAllTimers();
656 vi.useRealTimers();
657 audio.player.pause.mockReset();
658 }
659 },
660 );
661​
662 it.each(["inline", "viewer"])("stops video before starting %s audio", async (source) => {
663 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
664 audio.status = { ...audio.status, isLoaded: true };
665 const container = document.createElement("div");
666 root = createRoot(container);
667 await act(async () =>
668 root!.render(
669 createElement(
670 "div",
671 null,
672 createElement(MediaVideoPlayer, {
673 uri: "https://example.com/clip.mp4",
674 name: "clip.mp4",
675 thumbnailKey: "clip",
676 expanded: true,
677 autoPlay: true,
678 }),
679 source === "inline"
680 ? createElement(ThreadInlineFilePreview, {
681 source: {
682 kind: "document",
683 name: "sound.mp3",
684 uri: "https://example.com/sound.mp3",
685 },
686 onOpen() {},
687 })
688 : createElement(AudioFilePreview, {
689 uri: "https://example.com/sound.mp3",
690 onRetry() {},
691 }),
692 ),
693 ),
694 );
695 expect(audio.video.playing).toBe(true);
696 audio.video.pause.mockClear();
697 await act(async () =>
698 [...container.querySelectorAll("button")]
699 .find(
700 (button) =>
701 button.getAttribute("aria-label") === "Play audio" || button.textContent === "Play",
702 )!
703 .click(),
704 );
705 expect(audio.video.playing).toBe(false);
706 expect(audio.video.pause.mock.invocationCallOrder[0]).toBeLessThan(
707 audio.player.play.mock.invocationCallOrder[0]!,
708 );
709 expect(audio.played).toHaveBeenCalledOnce();
710 expect(audio.setActive).toHaveBeenLastCalledWith(true);
711 });
712​
713 it("plays inline, opens the file viewer, and yields viewer playback to recording", async () => {
714 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
715 audio.status = { ...audio.status, isLoaded: true };
716 const container = document.createElement("div");
717 root = createRoot(container);
718 const openViewer = () =>
719 root!.render(
720 createElement(AudioFilePreview, { uri: "https://example.com/sound.mp3", onRetry() {} }),
721 );
722 await act(async () =>
723 root!.render(
724 createElement(ThreadInlineFilePreview, {
725 source: { kind: "document", name: "sound.mp3", uri: "https://example.com/sound.mp3" },
726 onOpen: openViewer,
727 }),
728 ),
729 );
730 await act(async () =>
731 container.querySelector<HTMLButtonElement>('button[aria-label="Play audio"]')!.click(),
732 );
733 expect(audio.played).toHaveBeenCalledOnce();
734 await act(async () =>
735 container.querySelector<HTMLButtonElement>('button[aria-label="Open sound.mp3"]')!.click(),
736 );
737 expect(audio.enabled).toBe(true);
738 const play = [...container.querySelectorAll("button")].find(
739 (button) => button.textContent === "Play",
740 )!;
741 await act(async () => play.click());
742 expect(audio.played).toHaveBeenCalledTimes(2);
743 audio.player.pause.mockClear();
744 let recording!: ReturnType<typeof acquireAudioSession>;
745 await act(async () => {
746 recording = acquireAudioSession("recording");
747 });
748 expect(audio.player.pause).toHaveBeenCalledOnce();
749 await activateAudioSession(recording);
750 await act(async () => play.click());
751 expect(audio.played).toHaveBeenCalledTimes(2);
752 await releaseAudioSession(recording);
753 await act(async () => play.click());
754 expect(audio.played).toHaveBeenCalledTimes(3);
755 expect(audio.enabled).toBe(true);
756 });
757​
758 it.each(["pause", "unmount", "recording"])(
759 "does not restart the file viewer after %s during replay seeking",
760 async (action) => {
761 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
762 audio.status = { ...audio.status, isLoaded: true, didJustFinish: true, currentTime: 10 };
763 const seek = Promise.withResolvers<void>();
764 audio.player.seekTo.mockReturnValueOnce(seek.promise);
765 const container = document.createElement("div");
766 root = createRoot(container);
767 await act(async () =>
768 root!.render(
769 createElement(AudioFilePreview, { uri: "https://example.com/sound.mp3", onRetry() {} }),
770 ),
771 );
772 const play = [...container.querySelectorAll("button")].find(
773 (button) => button.textContent === "Play",
774 )!;
775 await act(async () => play.click());
776 expect(play.textContent).toBe("Pause");
777 let recording: ReturnType<typeof acquireAudioSession> | undefined;
778 if (action === "pause") await act(async () => play.click());
779 else if (action === "recording") {
780 await act(async () => {
781 recording = acquireAudioSession("recording");
782 });
783 expect(play.textContent).toBe("Play");
784 await activateAudioSession(recording!);
785 } else {
786 await act(async () => root!.unmount());
787 root = undefined;
788 }
789 await act(async () => seek.resolve());
790 expect(audio.played).not.toHaveBeenCalled();
791 if (recording) await releaseAudioSession(recording);
792 },
793 );
794​
795 it.each(["buffering", "seek"])(
796 "keeps file viewer ownership through %s and native resume",
797 async (transition) => {
798 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
799 audio.status = { ...audio.status, isLoaded: true };
800 const container = document.createElement("div");
801 root = createRoot(container);
802 const render = () =>
803 root!.render(
804 createElement(AudioFilePreview, {
805 uri: "https://example.com/sound.mp3",
806 onRetry() {},
807 }),
808 );
809 await act(async () => render());
810 await act(async () =>
811 [...container.querySelectorAll("button")]
812 .find((button) => button.textContent === "Play")!
813 .click(),
814 );
815 audio.status = { ...audio.status, playing: true };
816 await act(async () => render());
817 audio.player.pause.mockClear();
818 if (transition === "seek") {
819 await act(async () =>
820 [...container.querySelectorAll("button")]
821 .find((button) => button.textContent === "+15s")!
822 .click(),
823 );
824 expect(audio.player.seekTo).toHaveBeenCalledWith(10);
825 }
826 audio.status = { ...audio.status, playing: false, isBuffering: transition === "buffering" };
827 await act(async () => render());
828 expect(audio.player.pause).not.toHaveBeenCalled();
829 expect(
830 [...container.querySelectorAll("button")].map((button) => button.textContent),
831 ).toContain("Pause");
832 audio.status = { ...audio.status, playing: true, isBuffering: false };
833 await act(async () => render());
834 expect(audio.played).toHaveBeenCalledOnce();
835 let recording!: ReturnType<typeof acquireAudioSession>;
836 await act(async () => {
837 recording = acquireAudioSession("recording");
838 });
839 expect(audio.player.pause).toHaveBeenCalledOnce();
840 await releaseAudioSession(recording);
841 },
842 );
843​
844 it.each(["pause", "pause while buffering", "pause while loading", "end", "error"])(
845 "releases file viewer ownership on %s",
846 async (action) => {
847 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
848 audio.status = { ...audio.status, isLoaded: true };
849 const container = document.createElement("div");
850 root = createRoot(container);
851 const render = () =>
852 root!.render(
853 createElement(AudioFilePreview, {
854 uri: "https://example.com/sound.mp3",
855 onRetry() {},
856 }),
857 );
858 await act(async () => render());
859 await act(async () =>
860 [...container.querySelectorAll("button")]
861 .find((button) => button.textContent === "Play")!
862 .click(),
863 );
864 audio.status = { ...audio.status, playing: true };
865 await act(async () => render());
866 if (action.startsWith("pause")) {
867 if (action !== "pause") {
868 audio.status = {
869 ...audio.status,
870 playing: false,
871 isBuffering: true,
872 isLoaded: action !== "pause while loading",
873 };
874 await act(async () => render());
875 }
876 await act(async () =>
877 [...container.querySelectorAll("button")]
878 .find((button) => button.textContent === "Pause")!
879 .click(),
880 );
881 } else {
882 audio.status = { ...audio.status, playing: false, didJustFinish: action === "end" };
883 if (action === "error") Object.assign(audio.status, { error: "Playback failed" });
884 await act(async () => render());
885 }
886 expect(audio.player.pause).toHaveBeenLastCalledWith();
887 audio.status = { ...audio.status, playing: false, isBuffering: false, isLoaded: true };
888 await act(async () => render());
889 expect(
890 [...container.querySelectorAll("button")].map((button) => button.textContent),
891 ).toContain("Play");
892 audio.player.pause.mockClear();
893 const recording = acquireAudioSession("recording");
894 expect(audio.player.pause).not.toHaveBeenCalled();
895 expect(audio.setActive).not.toHaveBeenCalledWith(false);
896 await releaseAudioSession(recording);
897 },
898 );
899​
900 it.each(["buffering", "seek"])(
901 "keeps video ownership through %s and resume, including recording takeover during the next wait",
902 async (transition) => {
903 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
904 root = createRoot(document.createElement("div"));
905 await act(async () =>
906 root!.render(
907 createElement(MediaVideoPlayer, {
908 uri: "https://example.com/clip.mp4",
909 name: "clip.mp4",
910 thumbnailKey: "clip",
911 expanded: true,
912 autoPlay: true,
913 }),
914 ),
915 );
916 audio.video.pause.mockClear();
917 // iOS can keep readyToPlay during a seek's evaluatingBufferingRate wait.
918 if (transition === "buffering") {
919 audio.video.status = "loading";
920 for (const listener of audio.videoStatusListeners) listener({ status: "loading" });
921 }
922 audio.video.playing = false;
923 for (const listener of audio.videoListeners) listener({ isPlaying: false });
924 expect(audio.video.pause).not.toHaveBeenCalled();
925 // Buffer readiness can precede the native playing=true event.
926 audio.video.status = "readyToPlay";
927 for (const listener of audio.videoStatusListeners) listener({ status: "readyToPlay" });
928 expect(audio.video.pause).not.toHaveBeenCalled();
929 audio.video.playing = true;
930 for (const listener of audio.videoListeners) listener({ isPlaying: true });
931 expect(audio.video.play).toHaveBeenCalledOnce();
932 audio.video.playing = false;
933 for (const listener of audio.videoListeners) listener({ isPlaying: false });
934 const recording = acquireAudioSession("recording");
935 expect(audio.video.pause).toHaveBeenCalledOnce();
936 audio.video.play();
937 expect(audio.video.playing).toBe(false);
938 await releaseAudioSession(recording);
939 audio.video.play();
940 expect(audio.video.playing).toBe(true);
941 },
942 );
943​
944 it.each(["pause", "pause while buffering", "end", "error"])(
945 "releases video ownership on %s",
946 async (action) => {
947 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
948 root = createRoot(document.createElement("div"));
949 await act(async () =>
950 root!.render(
951 createElement(MediaVideoPlayer, {
952 uri: "https://example.com/clip.mp4",
953 name: "clip.mp4",
954 thumbnailKey: "clip",
955 expanded: true,
956 autoPlay: true,
957 }),
958 ),
959 );
960 await act(async () => {
961 if (action.startsWith("pause")) {
962 if (action === "pause while buffering") {
963 audio.video.status = "loading";
964 audio.video.playing = false;
965 for (const listener of audio.videoListeners) listener({ isPlaying: false });
966 }
967 audio.video.pause();
968 } else if (action === "end") {
969 for (const listener of audio.videoEndListeners) listener();
970 } else {
971 audio.video.status = "error";
972 for (const listener of audio.videoStatusListeners) listener({ status: "error" });
973 }
974 });
975 audio.video.pause.mockClear();
976 const recording = acquireAudioSession("recording");
977 expect(audio.video.pause).not.toHaveBeenCalled();
978 await releaseAudioSession(recording);
979 },
980 );
981​
982 it("keeps thread video playback and native controls working after audio releases", async () => {
983 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
984 const recording = acquireAudioSession("recording");
985 await activateAudioSession(recording);
986 await releaseAudioSession(recording);
987 const modes = audio.setAudioMode.mock.calls.length;
988 const activations = audio.setActive.mock.calls.length;
989 const container = document.createElement("div");
990 root = createRoot(container);
991 await act(async () =>
992 root!.render(
993 createElement(MediaVideoPlayer, {
994 uri: "https://example.com/clip.mp4",
995 name: "clip.mp4",
996 thumbnailKey: "clip",
997 expanded: true,
998 autoPlay: true,
999 }),
1000 ),
1001 );
1002 expect(audio.video.playing).toBe(true);
1003 expect(audio.setAudioMode).toHaveBeenCalledTimes(modes);
1004 expect(audio.setActive).toHaveBeenCalledTimes(activations);
1005 audio.video.pause();
1006 audio.video.play();
1007 expect(audio.video.playing).toBe(true);
1008 const takeover = acquireAudioSession("recording");
1009 expect(audio.video.playing).toBe(false);
1010 await activateAudioSession(takeover);
1011 audio.video.play();
1012 expect(audio.video.playing).toBe(false);
1013 await releaseAudioSession(takeover);
1014 audio.video.play();
1015 expect(audio.video.playing).toBe(true);
1016 await act(async () => root!.unmount());
1017 root = undefined;
1018 expect(audio.video.playing).toBe(false);
1019 });
1020​
1021 it.each(["play", "cancel", "unmount", "mode failure", "activation failure"])(
1022 "reactivates audio after voice release and honors %s during activation",
1023 async (intent) => {
1024 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
1025 const recording = acquireAudioSession("recording");
1026 await activateAudioSession(recording);
1027 await releaseAudioSession(recording);
1028 vi.clearAllMocks();
1029 let activate: () => void = () => {};
1030 if (intent === "mode failure") {
1031 audio.setAudioMode.mockRejectedValueOnce(new Error("Playback mode unavailable"));
1032 } else if (intent === "activation failure") {
1033 audio.setActive.mockRejectedValueOnce(new Error("Audio session unavailable"));
1034 } else {
1035 audio.setActive.mockImplementationOnce(
1036 () => new Promise((resolve) => (activate = resolve)),
1037 );
1039 audio.status = { ...audio.status, isLoaded: true };
1040 const container = document.createElement("div");
1041 root = createRoot(container);
1042 act(() =>
1043 root!.render(
1044 createElement(ThreadInlineFilePreview, {
1045 source: { kind: "document", name: "sound.mp3", uri: "https://example.com/sound.mp3" },
1046 onOpen() {},
1047 }),
1048 ),
1049 );
1050 const button = container.querySelector<HTMLButtonElement>('button[aria-label="Play audio"]')!;
1051 await act(async () => button.click());
1052 expect(audio.setAudioMode).toHaveBeenLastCalledWith({
1053 allowsRecording: false,
1054 playsInSilentMode: true,
1055 interruptionMode: "doNotMix",
1056 shouldPlayInBackground: false,
1057 });
1058 expect(audio.player.play).not.toHaveBeenCalled();
1059 if (intent.endsWith("failure")) {
1060 expect(container.textContent).toContain("Unavailable · tap play to retry");
1061 expect(button.getAttribute("aria-label")).toBe("Retry audio");
1062 expect(audio.setActive).not.toHaveBeenCalledWith(false);
1063 return;
1065 expect(audio.setActive).toHaveBeenLastCalledWith(true);
1066 expect(audio.setAudioMode.mock.invocationCallOrder[0]).toBeLessThan(
1067 audio.setActive.mock.invocationCallOrder[0]!,
1068 );
1069 if (intent === "cancel") await act(async () => button.click());
1070 else if (intent === "unmount") {
1071 act(() => root!.unmount());
1072 root = undefined;
1073 expect(audio.player.release).not.toHaveBeenCalled();
1075 await act(async () => activate());
1076 if (intent === "play") {
1077 expect(audio.player.play).toHaveBeenCalledOnce();
1078 expect(button.getAttribute("aria-label")).toBe("Pause audio");
1079 } else {
1080 expect(audio.player.play).not.toHaveBeenCalled();
1081 expect(audio.setActive).toHaveBeenLastCalledWith(true);
1082 expect(audio.player.pause).toHaveBeenCalled();
1083 if (intent === "unmount") {
1084 expect(audio.player.release).toHaveBeenCalledOnce();
1085 expect(audio.player.pause.mock.invocationCallOrder[0]).toBeLessThan(
1086 audio.player.release.mock.invocationCallOrder[0]!,
1087 );
1089 if (intent === "cancel") expect(button.getAttribute("aria-label")).toBe("Play audio");
1091 },
1092 );
1093​
1094 it.each(["playing", "URL pending", "mode pending", "activation pending"])(
1095 "yields to recording while %s and plays again after recording stops",
1096 async (phase) => {
1097 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
1098 const url = Promise.withResolvers<string>();
1099 const native = Promise.withResolvers<void>();
1100 audio.refresh.mockReturnValueOnce(url.promise);
1101 audio.status = { ...audio.status, isLoaded: phase !== "URL pending" };
1102 if (phase === "mode pending") audio.setAudioMode.mockReturnValueOnce(native.promise);
1103 if (phase === "activation pending") audio.setActive.mockReturnValueOnce(native.promise);
1104 const container = document.createElement("div");
1105 root = createRoot(container);
1106 act(() =>
1107 root!.render(
1108 createElement(ThreadInlineFilePreview, {
1109 source: {
1110 kind: "document",
1111 name: "sound.mp3",
1112 environmentId: EnvironmentId.make("environment-1"),
1113 resource: {
1114 _tag: "workspace-file",
1115 threadId: ThreadId.make("thread-1"),
1116 path: "/repo/sound.mp3",
1117 },
1118 },
1119 onOpen() {},
1120 }),
1121 ),
1122 );
1123 const button = container.querySelector<HTMLButtonElement>('button[aria-label="Play audio"]')!;
1124 await act(async () => button.click());
1125 expect(audio.player.play).toHaveBeenCalledTimes(phase === "playing" ? 1 : 0);
1126 expect(audio.refresh).toHaveBeenCalledTimes(phase === "URL pending" ? 1 : 0);
1127 let recording!: ReturnType<typeof acquireAudioSession>;
1128 await act(async () => {
1129 recording = acquireAudioSession("recording");
1130 });
1131 expect(audio.player.pause).toHaveBeenCalled();
1132 expect(button.getAttribute("aria-label")).toBe("Play audio");
1133 native.resolve();
1134 await activateAudioSession(recording);
1135 expect(audio.setAudioMode).toHaveBeenLastCalledWith({
1136 allowsRecording: true,
1137 interruptionMode: "doNotMix",
1138 playsInSilentMode: true,
1139 shouldPlayInBackground: false,
1140 });
1141 const modeCalls = audio.setAudioMode.mock.calls.length;
1142 const activationCalls = audio.setActive.mock.calls.length;
1143 await act(async () => url.resolve("https://example.com/sound.mp3"));
1144 await act(async () => button.click());
1145 expect(audio.setAudioMode).toHaveBeenCalledTimes(modeCalls);
1146 expect(audio.setActive).toHaveBeenCalledTimes(activationCalls);
1147 expect(audio.setActive).not.toHaveBeenCalledWith(false);
1148 expect(audio.player.play).toHaveBeenCalledTimes(phase === "playing" ? 1 : 0);
1149 await releaseAudioSession(recording);
1150 audio.status = { ...audio.status, isLoaded: true };
1151 // Refresh the native status before the next tap.
1152 await act(async () =>
1153 root!.render(
1154 createElement(ThreadInlineFilePreview, {
1155 source: { kind: "document", name: "sound.mp3", uri: "https://example.com/sound.mp3" },
1156 onOpen() {},
1157 }),
1158 ),
1159 );
1160 const replay = container.querySelector<HTMLButtonElement>('button[aria-label="Play audio"]')!;
1161 await act(async () => replay.click());
1162 expect(audio.player.play).toHaveBeenCalledTimes(phase === "playing" ? 2 : 1);
1163 expect(audio.setAudioMode).toHaveBeenLastCalledWith({
1164 allowsRecording: false,
1165 interruptionMode: "doNotMix",
1166 playsInSilentMode: true,
1167 shouldPlayInBackground: false,
1168 });
1169 expect(audio.setActive).toHaveBeenLastCalledWith(true);
1170 },
1171 );
1172​
1173 it.each(["cancel", "unmount", "replay, stale first", "replay, latest first"])(
1174 "honors the latest audio intent after %s during URL resolution",
1175 async (intent) => {
1176 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
1177 const container = document.createElement("div");
1178 root = createRoot(container);
1179 const resolutions: Array<(uri: string) => void> = [];
1180 audio.refresh.mockImplementation(() => new Promise((resolve) => resolutions.push(resolve)));
1181 act(() =>
1182 root!.render(
1183 createElement(ThreadInlineFilePreview, {
1184 source: {
1185 kind: "document",
1186 name: "sound.mp3",
1187 environmentId: EnvironmentId.make("environment-1"),
1188 resource: {
1189 _tag: "workspace-file",
1190 threadId: ThreadId.make("thread-1"),
1191 path: "/repo/sound.mp3",
1192 },
1193 },
1194 onOpen() {},
1195 }),
1196 ),
1197 );
1198 const button = container.querySelector<HTMLButtonElement>('button[aria-label="Play audio"]')!;
1199 await act(async () => button.click());
1200 if (intent !== "unmount") {
1201 await act(async () => button.click());
1202 expect(button.getAttribute("aria-label")).toBe("Play audio");
1204 const replay = intent.startsWith("replay");
1205 if (replay) {
1206 await act(async () => button.click());
1207 expect(button.getAttribute("aria-label")).toBe("Pause audio");
1208 expect(audio.refresh).toHaveBeenCalledTimes(2);
1209 } else if (intent === "unmount") {
1210 act(() => root!.unmount());
1211 root = undefined;
1213 const latestFirst = intent === "replay, latest first";
1214 if (latestFirst) await act(async () => resolutions[1]!("https://example.com/latest.mp3"));
1215 await act(async () => resolutions[0]!("https://example.com/stale.mp3"));
1216 expect(audio.player.play).toHaveBeenCalledTimes(latestFirst ? 1 : 0);
1217 expect(audio.player.replace).toHaveBeenCalledTimes(latestFirst ? 1 : 0);
1218 if (replay) {
1219 expect(button.getAttribute("aria-label")).toBe("Pause audio");
1220 if (!latestFirst) {
1221 expect(container.textContent).toContain("Loading…");
1222 await act(async () => resolutions[1]!("https://example.com/latest.mp3"));
1224 expect(audio.player.replace).toHaveBeenCalledExactlyOnceWith({
1225 uri: "https://example.com/latest.mp3",
1226 });
1227 expect(audio.player.play).toHaveBeenCalledOnce();
1229 },
1230 );
1231​
1232 it.each([false, true])(
1233 "cancels a second tap while buffering with isLoaded=%s",
1234 async (isLoaded) => {
1235 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
1236 const container = document.createElement("div");
1237 root = createRoot(container);
1238 audio.status = { ...audio.status, isLoaded, isBuffering: isLoaded };
1239 let resolve: (uri: string) => void = () => {};
1240 audio.refresh.mockImplementation(
1241 () =>
1242 new Promise((done) => {
1243 resolve = done;
1244 }),
1245 );
1246 const preview = createElement(ThreadInlineFilePreview, {
1247 source: {
1248 kind: "document",
1249 name: "sound.mp3",
1250 environmentId: EnvironmentId.make("environment-1"),
1251 resource: {
1252 _tag: "workspace-file",
1253 threadId: ThreadId.make("thread-1"),
1254 path: "/repo/sound.mp3",
1255 },
1256 },
1257 onOpen() {},
1258 });
1259 act(() => root!.render(preview));
1260 const button = container.querySelector<HTMLButtonElement>('button[aria-label="Play audio"]')!;
1261 await act(async () => button.click());
1262 expect(audio.player.play).toHaveBeenCalledTimes(isLoaded ? 1 : 0);
1263 expect(button.disabled).toBe(false);
1264 expect(button.getAttribute("aria-label")).toBe("Pause audio");
1265 expect(button.getAttribute("aria-busy")).toBe("true");
1266 await act(async () => button.click());
1267 expect(audio.player.pause).toHaveBeenCalled();
1268 expect(button.getAttribute("aria-label")).toBe("Play audio");
1269 expect(button.getAttribute("aria-busy")).toBe("false");
1270 if (!isLoaded) await act(async () => resolve("https://example.com/sound.mp3"));
1271 expect(audio.player.play).toHaveBeenCalledTimes(isLoaded ? 1 : 0);
1272 if (!isLoaded) {
1273 expect(audio.player.replace).not.toHaveBeenCalled();
1274 audio.refresh.mockResolvedValue("https://example.com/sound.mp3");
1276 await act(async () => button.click());
1277 expect(audio.player.play).toHaveBeenCalledTimes(isLoaded ? 2 : 1);
1278 audio.status = { ...audio.status, isLoaded: true, didJustFinish: true, currentTime: 10 };
1279 await act(async () =>
1280 root!.render(createElement(ThreadInlineFilePreview, { ...preview.props })),
1281 );
1282 expect(button.getAttribute("aria-label")).toBe("Play audio");
1283 await act(async () => button.click());
1284 expect(audio.player.seekTo).toHaveBeenCalledWith(0);
1285 expect(audio.player.play).toHaveBeenCalledTimes(isLoaded ? 3 : 2);
1286 },
1287 );
1288});
1289​
1290describe("PDF preview detection", () => {
1291 it.each([
1292 [{ name: "download", mimeType: "APPLICATION/PDF; charset=binary" }, true],
1293 [{ name: "https://example.com/report.pdf?signature=abc#page=2" }, true],
1294 [{ name: "report.pdf", mimeType: "text/plain" }, false],
1295 [{ name: "https://example.com/page?download=report.pdf" }, false],
1296 ])("classifies %j as %s", (file, expected) => {
1297 expect(isPdfFile(file)).toBe(expected);
1298 });
1299});
1300​
1301describe("inline file previews", () => {
1302 it.each([
1303 [{ name: "sound.MP3" }, "audio"],
1304 [{ name: "sound", mimeType: "audio/wav" }, "audio"],
1305 [{ name: "report.PDF", mimeType: "text/plain" }, null],
1306 [{ name: "report.csv" }, null],
1307 [{ name: "report.tsv" }, null],
1308 [{ name: "report", mimeType: "text/csv; charset=utf-8" }, null],
1309 [{ name: "report.csv", mimeType: "image/png" }, null],
1310 [{ name: "image.png" }, null],
1311 [{ name: "clip.mp4" }, null],
1312 [{ name: "file.zip" }, null],
1313 [{ name: "report.docx" }, null],
1314 [{ name: "report.xlsx" }, null],
1315 [{ name: "report.pptx" }, null],
1316 [{ name: "download", mimeType: "application/pdf" }, null],
1317 [{ name: "sound.mp3", mimeType: "application/pdf" }, null],
1318 ])("classifies %j as %s", (file, expected) => {
1319 expect(inlineFilePreviewKind(file)).toBe(expected);
1320 });
1321});
1322​
1323describe("ThreadFeed previews", () => {
1324 it("does not commit an open preview over a different thread", async () => {
1325 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
1326 const environmentId = EnvironmentId.make("environment-1");
1327 const messageId = MessageId.make("message-1");
1328 const timestamp = "2026-10-20T00:00:00.000Z";
1329 const feedFor = (threadId: ThreadId): ThreadFeedEntry[] => [
1331 type: "message",
1332 id: messageId,
1333 createdAt: timestamp,
1334 message: {
1335 id: messageId,
1336 role: "user",
1337 text: "report",
1338 attachments: [
1340 type: "file",
1341 id: "report",
1342 name: "report.pdf",
1343 mimeType: "application/pdf",
1344 sizeBytes: 12,
1345 },
1346 ],
1347 createdAt: timestamp,
1348 updatedAt: timestamp,
1349 runId: null,
1350 streaming: false,
1351 visibility: "local",
1352 sourceThreadId: threadId,
1353 },
1354 },
1355 ];
1356 const container = document.createElement("div");
1357 // Records what each commit shows before passive effects get a chance to run.
1358 const committedPreviews: Array<string | null> = [];
1359 function CommitProbe() {
1360 useLayoutEffect(() => {
1361 committedPreviews.push(
1362 container.querySelector("[data-file-preview]")?.getAttribute("data-file-preview") ?? null,
1363 );
1364 });
1365 return null;
1367 const element = (
1368 threadId: ThreadId,
1369 contentPresentation: Parameters<typeof ThreadFeed>[0]["contentPresentation"] = {
1370 kind: "ready",
1371 },
1372 ) =>
1373 createElement(
1374 Fragment,
1375 null,
1376 createElement(ThreadFeed, {
1377 environmentId,
1378 threadId,
1379 detailRef: null,
1380 threadTitle: "preview",
1381 workspaceRoot: "/repo",
1382 feed: feedFor(threadId),
1383 queuedMessages: [],
1384 dispatchingMessageId: null,
1385 onEditPendingMessage: null,
1386 contentPresentation,
1387 latestRun: null,
1388 activeWorkStartedAt: null,
1389 listRef: { current: null },
1390 freeze: { value: false } as Parameters<typeof ThreadFeed>[0]["freeze"],
1391 contentInsetEndAdjustment: { value: 0 } as Parameters<
1392 typeof ThreadFeed
1393 >[0]["contentInsetEndAdjustment"],
1394 anchorMessageId: null,
1395 keyboardOffset: 0,
1396 }),
1397 createElement(CommitProbe),
1398 );
1399 const root = createRoot(container);
1400 try {
1401 await act(async () => root.render(element(ThreadId.make("thread-1"))));
1402 await act(async () =>
1403 container.querySelector<HTMLButtonElement>('[aria-label="Open report.pdf"]')!.click(),
1404 );
1405 expect(container.querySelector('[data-file-preview="report.pdf"]')).not.toBeNull();
1406 committedPreviews.length = 0;
1407 await act(async () => root.render(element(ThreadId.make("thread-2"))));
1408 expect(committedPreviews[0]).toBeNull();
1409​
1410 // A preview hidden by a presentation change stays closed when the content comes back.
1411 await act(async () =>
1412 container.querySelector<HTMLButtonElement>('[aria-label="Open report.pdf"]')!.click(),
1413 );
1414 expect(container.querySelector('[data-file-preview="report.pdf"]')).not.toBeNull();
1415 await act(async () => root.render(element(ThreadId.make("thread-2"), { kind: "loading" })));
1416 await act(async () => root.render(element(ThreadId.make("thread-2"))));
1417 expect(container.querySelector("[data-file-preview]")).toBeNull();
1418 } finally {
1419 await act(async () => root.unmount());
1421 });
1422});