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