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