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