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

filePreview.test.ts

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