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

filePreview.test.ts

1,495 lines59.6 KB

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