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