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