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

filePreview.test.ts

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