Skip to content
TypeScript

feat(web): play video attachments in chat (#8688)

Bilal Bakrac4aae101d06
diff --git a/apps/desktop/src/electron/ElectronProtocol.test.ts b/apps/desktop/src/electron/ElectronProtocol.test.ts
index 2db85dafc4d..585dd7e7ea1 100644
--- a/apps/desktop/src/electron/ElectronProtocol.test.ts
+++ b/apps/desktop/src/electron/ElectronProtocol.test.ts
@@ -225,6 +225,7 @@ describe("ElectronProtocol", () => {
"http:",
"https:",
]);
+ assert.deepEqual(directives["media-src"], ["'self'", "t3code:", "blob:"]);
assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]);
});
});
diff --git a/apps/desktop/src/electron/ElectronProtocol.ts b/apps/desktop/src/electron/ElectronProtocol.ts
index 11459c9ef7a..845f03dba5d 100644
--- a/apps/desktop/src/electron/ElectronProtocol.ts
+++ b/apps/desktop/src/electron/ElectronProtocol.ts
@@ -87,6 +87,7 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
`script-src ${scriptSources.join(" ")}`,
`connect-src ${connectSources.join(" ")}`,
`img-src 'self' ${input.scheme}: blob: data: http: https:`,
+ `media-src 'self' ${input.scheme}: blob:`,
"style-src 'self' 'unsafe-inline'",
`font-src 'self' ${input.scheme}: data:`,
"worker-src 'self' blob:",
diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts
index aa47a78238b..8cf9c642384 100644
--- a/apps/server/src/assets/AssetAccess.test.ts
+++ b/apps/server/src/assets/AssetAccess.test.ts
@@ -208,6 +208,37 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(testLayer)),
);
+ it.effect("serves video attachments inline", () =>
+ Effect.gen(function* () {
+ const config = yield* ServerConfig.ServerConfig;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001-mp4";
+ const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.mp4`);
+ yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
+ yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
+
+ const result = yield* issueAssetUrl({
+ resource: {
+ _tag: "attachment",
+ attachmentId,
+ fileName: "demo.mp4",
+ mimeType: 'video/mp4; codecs="avc1.42E01E"',
+ },
+ });
+ const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
+ const separatorIndex = suffix.indexOf("/");
+
+ expect(
+ yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
+ ).toEqual({
+ kind: "file",
+ path: attachmentPath,
+ fileName: "demo.mp4",
+ mimeType: "video/mp4",
+ });
+ }).pipe(Effect.provide(testLayer)),
+ );
it.effect("issues project favicon capabilities with a signed fallback", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts
index dff11524ed2..d064ec07529 100644
--- a/apps/server/src/assets/AssetAccess.ts
+++ b/apps/server/src/assets/AssetAccess.ts
@@ -48,6 +48,7 @@ const SIGNING_SECRET_NAME = "asset-access-signing-key";
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;
const PROJECT_FAVICON_VERSION_PREFIX = "v";
+const INLINE_VIDEO_MIME_TYPE_PATTERN = /^video\/[\w!#$&^.+-]+$/i;
const PREVIEW_ASSET_EXTENSIONS = new Set([
...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
@@ -300,16 +301,20 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
});
}
// Generic files carry their extension inside the attachment id (that
- // shape resolves the on-disk path); images do not. Only generic files
- // download, images render inline in chat.
+ // shape resolves the on-disk path); images do not. Videos and images
+ // render inline; other generic files download.
const isGenericFile = parseAttachmentFileExtension(input.resource.attachmentId) !== null;
+ const videoMimeType = input.resource.mimeType?.split(";", 1)[0]?.trim() ?? "";
+ const isVideo = INLINE_VIDEO_MIME_TYPE_PATTERN.test(videoMimeType);
claims = {
version: 1,
kind: "attachment",
attachmentId: input.resource.attachmentId,
- ...(isGenericFile ? { download: true } : {}),
+ ...(isGenericFile && !isVideo ? { download: true } : {}),
...(input.resource.fileName !== undefined ? { fileName: input.resource.fileName } : {}),
- ...(input.resource.mimeType !== undefined ? { mimeType: input.resource.mimeType } : {}),
+ ...(input.resource.mimeType !== undefined
+ ? { mimeType: isVideo ? videoMimeType : input.resource.mimeType }
+ : {}),
expiresAt,
};
fileName = input.resource.fileName ?? path.basename(attachmentPath);
diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.ts
index edb3967a078..9ee36ffebdd 100644
--- a/apps/server/src/http.test.ts
+++ b/apps/server/src/http.test.ts
@@ -50,6 +50,17 @@ describe("assetResponseHeaders", () => {
});
});
+ it("serves inline videos with their declared mime type", () => {
+ expect(
+ assetResponseHeaders("/attachments/demo.bin", {
+ mimeType: 'video/mp4; codecs="avc1.42E01E"',
+ }),
+ ).toEqual({
+ "Cache-Control": "private, max-age=3600",
+ "Content-Type": "video/mp4",
+ "X-Content-Type-Options": "nosniff",
+ });
+ });
it("declares utf-8 for HTML assets so non-ASCII content renders correctly", () => {
expect(assetResponseHeaders("/workspace/page.html")).toHaveProperty(
"Content-Type",
diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts
index 26214c9ddda..5e3f46711b1 100644
--- a/apps/server/src/http.ts
+++ b/apps/server/src/http.ts
@@ -57,6 +57,8 @@ const DOWNLOAD_MIME_TYPE_PATTERN = /^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/;
const isSafeDownloadMimeType = (mimeType: string): boolean =>
DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) &&
!/(?:^text\/html$|\/xml(?:$|-)|\+xml$)/i.test(mimeType.trim().toLowerCase());
+const isSafeInlineVideoMimeType = (mimeType: string): boolean =>
+ DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) && mimeType.toLowerCase().startsWith("video/");
/** RFC 6266 disposition with an ASCII fallback name plus a UTF-8 `filename*`. */
export function downloadContentDisposition(fileName?: string): string {
@@ -86,6 +88,7 @@ export function assetResponseHeaders(
},
): Record<string, string> {
const lowerPath = filePath.toLowerCase();
+ const inlineVideoMimeType = options?.mimeType?.split(";", 1)[0]?.trim();
return {
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
@@ -98,9 +101,11 @@ export function assetResponseHeaders(
? options.mimeType
: "application/octet-stream",
}
- : lowerPath.endsWith(".html") || lowerPath.endsWith(".htm")
- ? { "Content-Type": "text/html; charset=utf-8" }
- : {}),
+ : inlineVideoMimeType !== undefined && isSafeInlineVideoMimeType(inlineVideoMimeType)
+ ? { "Content-Type": inlineVideoMimeType }
+ : lowerPath.endsWith(".html") || lowerPath.endsWith(".htm")
+ ? { "Content-Type": "text/html; charset=utf-8" }
+ : {}),
...(!options?.download && lowerPath.endsWith(".svg")
? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY }
: {}),
@@ -276,9 +281,9 @@ export const assetRouteLayer = HttpRouter.add(
status: 200,
headers: assetResponseHeaders(
asset.path,
- asset.download
+ asset.download || asset.mimeType !== undefined
? {
- download: true,
+ ...(asset.download ? { download: true } : {}),
...(asset.fileName !== undefined ? { fileName: asset.fileName } : {}),
...(asset.mimeType !== undefined ? { mimeType: asset.mimeType } : {}),
}
diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts
index 5ff86bb2381..d4a5bfe74c0 100644
--- a/apps/web/src/components/ChatView.logic.test.ts
+++ b/apps/web/src/components/ChatView.logic.test.ts
@@ -21,6 +21,8 @@ import {
dismissBranchMismatchForSession,
ENVIRONMENT_RECONNECT_WARNING_GRACE_MS,
getStartedThreadModelChangeBlockReason,
+ loadVideoPreviewUrl,
+ isVideoPreviewRequestCurrent,
hasEnvironmentReconnectWarningGraceElapsed,
hasServerAcknowledgedLocalDispatch,
isBranchMismatchDismissedForSession,
@@ -41,6 +43,31 @@ import {
shouldWriteThreadErrorToCurrentServerThread,
} from "./ChatView.logic";
+describe("loadVideoPreviewUrl", () => {
+ it("loads video bytes into an object URL", async () => {
+ const objectUrl = await loadVideoPreviewUrl("data:video/mp4;base64,AA==");
+ expect(objectUrl).toMatch(/^blob:/);
+ URL.revokeObjectURL(objectUrl);
+ });
+
+ it("stops loading when the preview request is cancelled", async () => {
+ const controller = new AbortController();
+ controller.abort();
+
+ await expect(
+ loadVideoPreviewUrl("data:video/mp4;base64,AA==", controller.signal),
+ ).rejects.toMatchObject({ name: "AbortError" });
+ });
+});
+
+describe("isVideoPreviewRequestCurrent", () => {
+ it("rejects changed threads and replaced previews", () => {
+ expect(isVideoPreviewRequestCurrent("thread-1", "thread-2", 1, 1)).toBe(false);
+ expect(isVideoPreviewRequestCurrent("thread-1", "thread-1", 1, 2)).toBe(false);
+ expect(isVideoPreviewRequestCurrent("thread-1", "thread-1", 2, 2)).toBe(true);
+ });
+});
+
const environmentId = EnvironmentId.make("environment-local");
const projectId = ProjectId.make("project-1");
const threadId = ThreadId.make("thread-1");
diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts
index 25a49f3efa2..b0f5dacc078 100644
--- a/apps/web/src/components/ChatView.logic.ts
+++ b/apps/web/src/components/ChatView.logic.ts
@@ -290,6 +290,21 @@ export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
URL.revokeObjectURL(previewUrl);
}
+export async function loadVideoPreviewUrl(url: string, signal?: AbortSignal): Promise<string> {
+ const response = await fetch(url, signal ? { signal } : {});
+ if (!response.ok) throw new Error(`Could not load video (${response.status}).`);
+ return URL.createObjectURL(await response.blob());
+}
+
+export function isVideoPreviewRequestCurrent(
+ requestThreadKey: string,
+ currentThreadKey: string,
+ requestId: number,
+ currentRequestId: number,
+): boolean {
+ return requestThreadKey === currentThreadKey && requestId === currentRequestId;
+}
+
export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
if (message.role !== "user" || !message.attachments) {
return;
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index a027a1848b3..df6e5cc1024 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -129,6 +129,7 @@ import {
MAX_TERMINALS_PER_GROUP,
type ChatMessage,
isImageAttachment,
+ videoMimeType,
type SessionPhase,
type Thread,
type TurnDiffSummary,
@@ -360,6 +361,8 @@ import {
cloneComposerImageForRetry,
deriveLockedProvider,
readFileAsDataUrl,
+ loadVideoPreviewUrl,
+ isVideoPreviewRequestCurrent,
reconcileMountedTerminalThreadIds,
resolveBackgroundDraftWorkspaceOptions,
resolveDraftHeroState,
@@ -1438,8 +1441,23 @@ function ChatViewContent(props: ChatViewProps) {
const localComposerRef = useRef<ChatComposerHandle | null>(null);
const composerRef = useComposerHandleContext() ?? localComposerRef;
const [isWorkspaceFileDragActive, setIsWorkspaceFileDragActive] = useState(false);
+ const routeThreadKeyRef = useRef(routeThreadKey);
+ routeThreadKeyRef.current = routeThreadKey;
+ const videoPreviewRequestIdRef = useRef(0);
+ const videoPreviewAbortControllerRef = useRef<AbortController | null>(null);
+ const cancelVideoPreviewRequest = useCallback(() => {
+ videoPreviewRequestIdRef.current += 1;
+ videoPreviewAbortControllerRef.current?.abort();
+ videoPreviewAbortControllerRef.current = null;
+ }, []);
+ const [openingVideoAttachmentId, setOpeningVideoAttachmentId] = useState<string | null>(null);
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
+ useEffect(() => {
+ const item = expandedImage?.images[expandedImage.index];
+ if (item?.type !== "video" || !item.src.startsWith("blob:")) return;
+ return () => revokeBlobPreviewUrl(item.src);
+ }, [expandedImage]);
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState<
Record<string, ReadonlyArray<CodexFeedbackSubmission>>
@@ -2479,11 +2497,12 @@ function ChatViewContent(props: ChatViewProps) {
useEffect(() => {
return () => {
clearAttachmentPreviewHandoffs();
+ cancelVideoPreviewRequest();
for (const message of optimisticUserMessagesRef.current) {
revokeUserMessagePreviewUrls(message);
}
};
- }, [clearAttachmentPreviewHandoffs]);
+ }, [cancelVideoPreviewRequest, clearAttachmentPreviewHandoffs]);
const handoffAttachmentPreviews = useCallback((messageId: MessageId, previewUrls: string[]) => {
if (previewUrls.length === 0) return;
@@ -2504,17 +2523,40 @@ function ChatViewContent(props: ChatViewProps) {
});
}, []);
const serverMessages = activeThread?.messages;
- const downloadFileAttachment = useCallback(
+ const openFileAttachment = useCallback(
async (attachment: ChatFileAttachment) => {
const connection = readPreparedConnection(environmentId);
if (!connection) {
toastManager.add({ type: "error", title: "The environment is not connected." });
return;
}
+ const videoMime = videoMimeType(attachment);
+ const isVideo = videoMime !== null;
+ const action = isVideo ? "play" : "download";
+ const videoPreviewAbortController = isVideo ? new AbortController() : null;
+ if (isVideo) {
+ videoPreviewAbortControllerRef.current?.abort();
+ videoPreviewAbortControllerRef.current = videoPreviewAbortController;
+ }
+ const videoPreviewRequestId = isVideo ? ++videoPreviewRequestIdRef.current : 0;
+ const isCurrentRequest = () =>
+ !isVideo ||
+ isVideoPreviewRequestCurrent(
+ routeThreadKey,
+ routeThreadKeyRef.current,
+ videoPreviewRequestId,
+ videoPreviewRequestIdRef.current,
+ );
+ const finishVideoPreviewRequest = () => {
+ if (videoPreviewRequestIdRef.current === videoPreviewRequestId) {
+ setOpeningVideoAttachmentId(null);
+ videoPreviewAbortControllerRef.current = null;
+ }
+ };
+ if (isVideo) setOpeningVideoAttachmentId(attachment.id);
- // fileName and mimeType ride in the signed claims so the download gets
- // a real filename and Content-Type even when the anchor's `download`
- // attribute is ignored (cross-origin environment servers).
+ // fileName and mimeType ride in the signed claims so videos render
+ // inline while other files keep their real download name and type.
const result = await createAttachmentAssetUrl({
environmentId,
input: {
@@ -2522,15 +2564,20 @@ function ChatViewContent(props: ChatViewProps) {
_tag: "attachment",
attachmentId: attachment.id,
fileName: attachment.name,
- mimeType: attachment.mimeType,
+ mimeType: videoMime ?? attachment.mimeType,
},
},
});
+ if (!isCurrentRequest()) {
+ finishVideoPreviewRequest();
+ return;
+ }
if (result._tag === "Failure") {
+ finishVideoPreviewRequest();
const error = squashAtomCommandFailure(result);
toastManager.add({
type: "error",
- title: `Could not download ${attachment.name}`,
+ title: "Could not " + action + " " + attachment.name,
description: error instanceof Error ? error.message : "The attachment is unavailable.",
});
return;
@@ -2538,7 +2585,31 @@ function ChatViewContent(props: ChatViewProps) {
const url = resolveAssetUrl(connection.httpBaseUrl, result.value.relativeUrl);
if (!url) {
- toastManager.add({ type: "error", title: `Could not download ${attachment.name}` });
+ finishVideoPreviewRequest();
+ toastManager.add({ type: "error", title: "Could not " + action + " " + attachment.name });
+ return;
+ }
+ if (isVideo) {
+ try {
+ const previewUrl = await loadVideoPreviewUrl(url, videoPreviewAbortController?.signal);
+ if (!isCurrentRequest()) {
+ revokeBlobPreviewUrl(previewUrl);
+ return;
+ }
+ setExpandedImage({
+ images: [{ src: previewUrl, name: attachment.name, type: "video" }],
+ index: 0,
+ });
+ } catch (error) {
+ if (!isCurrentRequest()) return;
+ toastManager.add({
+ type: "error",
+ title: "Could not play " + attachment.name,
+ description: error instanceof Error ? error.message : "The attachment is unavailable.",
+ });
+ } finally {
+ finishVideoPreviewRequest();
+ }
return;
}
const anchor = document.createElement("a");
@@ -2546,7 +2617,7 @@ function ChatViewContent(props: ChatViewProps) {
anchor.download = attachment.name;
anchor.click();
},
- [createAttachmentAssetUrl, environmentId],
+ [createAttachmentAssetUrl, environmentId, routeThreadKey],
);
const serverAttachmentIds = useMemo(() => {
const attachmentIds = new Set<string>();
@@ -4389,8 +4460,10 @@ function ChatViewContent(props: ChatViewProps) {
return [];
});
resetLocalDispatch();
+ cancelVideoPreviewRequest();
+ setOpeningVideoAttachmentId(null);
setExpandedImage(null);
- }, [draftId, resetLocalDispatch, threadId]);
+ }, [cancelVideoPreviewRequest, draftId, resetLocalDispatch, threadId]);
const closeExpandedImage = useCallback(() => {
setExpandedImage(null);
@@ -6843,9 +6916,14 @@ function ChatViewContent(props: ChatViewProps) {
}
};
- const onExpandTimelineImage = useCallback((preview: ExpandedImagePreview) => {
- setExpandedImage(preview);
- }, []);
+ const onExpandTimelineImage = useCallback(
+ (preview: ExpandedImagePreview) => {
+ cancelVideoPreviewRequest();
+ setOpeningVideoAttachmentId(null);
+ setExpandedImage(preview);
+ },
+ [cancelVideoPreviewRequest],
+ );
const onOpenTurnDiff = useCallback(
(turnId: TurnId, filePath?: string) => {
if (!isServerThread || !activeThreadRef) return;
@@ -7139,7 +7217,8 @@ function ChatViewContent(props: ChatViewProps) {
onRevertUserMessage={onRevertUserMessage}
isRevertingCheckpoint={isRevertingCheckpoint}
onImageExpand={onExpandTimelineImage}
- onFileDownload={downloadFileAttachment}
+ onFileOpen={openFileAttachment}
+ openingVideoAttachmentId={openingVideoAttachmentId}
markdownCwd={gitCwd ?? undefined}
resolvedTheme={resolvedTheme}
timestampFormat={timestampFormat}
@@ -7320,6 +7399,8 @@ function ChatViewContent(props: ChatViewProps) {
scheduleComposerFocus={scheduleComposerFocus}
setThreadError={setThreadError}
onExpandImage={onExpandTimelineImage}
+ onFileOpen={openFileAttachment}
+ openingVideoAttachmentId={openingVideoAttachmentId}
/>
</div>
</div>
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index 9a8908bb139..68d1a9eb2e3 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -1,5 +1,6 @@
import type {
ApprovalRequestId,
+ ChatFileAttachment,
EnvironmentId,
ModelSelection,
PreviewAnnotationPayload,
@@ -55,6 +56,8 @@ import {
type DraftId,
type PersistedComposerFileAttachment,
type PersistedComposerImageAttachment,
+ composerFileDedupKey,
+ composerFileMatchesReattachMarker,
composerFileNeedsReattach,
composerTargetKey,
hydrateImagesFromPersisted,
@@ -86,6 +89,7 @@ import {
classifyComposerAttachmentFile,
fileAttachmentCapabilityBlockReason,
fileAttachmentStagingLimit,
+ isPreviewableComposerVideo,
normalizeComposerImageFileMimeType,
shouldHandleComposerAttachmentPaste,
} from "./composerAttachmentFiles";
@@ -142,7 +146,11 @@ import {
} from "./composerProviderState";
import { ContextWindowMeter } from "./ContextWindowMeter";
import { resolveContextWindowModelDisplayName } from "./ContextWindowMeter.logic";
-import { buildExpandedImagePreview, type ExpandedImagePreview } from "./ExpandedImagePreview";
+import {
+ attachVideoThumbnail,
+ buildExpandedImagePreview,
+ type ExpandedImagePreview,
+} from "./ExpandedImagePreview";
import { basenameOfPath } from "../../pierre-icons";
import { cn, randomUUID } from "~/lib/utils";
import { Separator } from "../ui/separator";
@@ -153,6 +161,30 @@ import {
} from "./composerSubmission";
import { ComposerPromptLengthValidation } from "./ComposerPromptLengthValidation";
+function ComposerVideoThumbnail({ file }: { file: File }) {
+ const setVideo = useCallback(
+ (video: HTMLVideoElement | null) => {
+ if (!video) return;
+ return attachVideoThumbnail(video, file);
+ },
+ [file],
+ );
+
+ return (
+ <video
+ ref={setVideo}
+ muted
+ playsInline
+ preload="metadata"
+ aria-hidden="true"
+ onLoadedMetadata={(event) => {
+ event.currentTarget.currentTime = Math.min(0.1, event.currentTarget.duration || 0);
+ }}
+ className="pointer-events-none absolute inset-0 size-full object-cover"
+ />
+ );
+}
+
type ComposerCommandMenuPosition = {
bottom: number;
left: number;
@@ -259,6 +291,7 @@ import {
FileIcon,
PaperclipIcon,
PencilRulerIcon,
+ PlayIcon,
type LucideIcon,
LockIcon,
LockOpenIcon,
@@ -280,7 +313,7 @@ import {
} from "../../providerInstances";
import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection";
import type { UnifiedSettings } from "@t3tools/contracts/settings";
-import type { SessionPhase, Thread } from "../../types";
+import { type SessionPhase, type Thread, videoMimeType } from "../../types";
import type { PendingUserInputDraftAnswer } from "../../pendingUserInput";
import type { PendingApproval, PendingUserInput } from "../../session-logic";
import type { ContextWindowSnapshot } from "../../lib/contextWindow";
@@ -683,6 +716,8 @@ export interface ChatComposerProps {
scheduleComposerFocus: () => void;
setThreadError: (threadId: ThreadId | null, error: string | null) => void;
onExpandImage: (preview: ExpandedImagePreview) => void;
+ onFileOpen: (attachment: ChatFileAttachment) => void;
+ openingVideoAttachmentId: string | null;
}
// --------------------------------------------------------------------------
@@ -762,6 +797,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
scheduleComposerFocus,
setThreadError,
onExpandImage,
+ onFileOpen,
+ openingVideoAttachmentId,
} = props;
// ------------------------------------------------------------------
// Store subscriptions (prompt / images / terminal contexts)
@@ -774,6 +811,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const prompt = composerDraft.prompt;
const composerImages = composerDraft.images;
const composerFiles = composerDraft.files;
+ const composerVideos = composerFiles.filter((file) =>
+ isPreviewableComposerVideo(file, environmentId),
+ );
+ const composerOtherFiles = composerFiles.filter(
+ (file) => !isPreviewableComposerVideo(file, environmentId),
+ );
const composerTerminalContexts = composerDraft.terminalContexts;
const composerElementContexts = composerDraft.elementContexts;
const composerPreviewAnnotations = composerDraft.previewAnnotations;
@@ -2363,11 +2406,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
let restoredFileCount = 0;
const stashedFiles = entry.files ?? [];
if (stashedFiles.length > 0) {
- const fileDedupKey = (file: {
- readonly mimeType: string;
- readonly sizeBytes: number;
- readonly name: string;
- }) => `${file.mimeType}\u0000${file.sizeBytes}\u0000${file.name}`;
const composerFilesNow = composerFilesRef.current;
const existingFileIds = new Set(composerFilesNow.map((file) => file.id));
const retainedUploadIds = new Set(
@@ -2375,16 +2413,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
file.uploadedAttachmentId ? [file.uploadedAttachmentId] : [],
),
);
- const existingFileKeys = new Set(composerFilesNow.map(fileDedupKey));
- const reattachMarkerKeys = new Set(
- composerFilesNow.filter(composerFileNeedsReattach).map(fileDedupKey),
- );
+ const existingFileKeys = new Set(composerFilesNow.map(composerFileDedupKey));
+ const reattachMarkers = composerFilesNow.filter(composerFileNeedsReattach);
+ const restoredMarkerIds = new Set<string>();
const duplicateFiles: PersistedComposerFileAttachment[] = [];
const markerReplacements: ComposerFileAttachment[] = [];
const appendedFiles: ComposerFileAttachment[] = [];
for (const file of stashedFiles) {
const expired = expiredAttachmentIds.has(file.attachmentId);
- const key = fileDedupKey(file);
+ const key = composerFileDedupKey(file);
const restored: ComposerFileAttachment = {
type: "file",
id: file.id,
@@ -2404,23 +2441,23 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}
continue;
}
- if (existingFileKeys.has(key)) {
- if (reattachMarkerKeys.has(key)) {
- // The draft row with this identity is a needs-reattach marker,
- // not a real duplicate. Replace it (addFiles swaps a matching
- // marker in place) instead of deleting the only uploaded copy.
- reattachMarkerKeys.delete(key);
- existingFileIds.add(file.id);
- if (expired) {
- // The draft's marker already says "attach again"; nothing to
- // restore or release, but say why the stash copy is gone.
- expiredFileNames.push(file.name);
- } else {
- retainedUploadIds.add(file.attachmentId);
- markerReplacements.push(restored);
- }
- continue;
+ const reattachMarker = reattachMarkers.find(
+ (marker) =>
+ !restoredMarkerIds.has(marker.id) && composerFileMatchesReattachMarker(marker, file),
+ );
+ if (reattachMarker) {
+ restoredMarkerIds.add(reattachMarker.id);
+ existingFileIds.add(file.id);
+ existingFileKeys.add(key);
+ if (expired) {
+ expiredFileNames.push(file.name);
+ } else {
+ retainedUploadIds.add(file.attachmentId);
+ markerReplacements.push(restored);
}
+ continue;
+ }
+ if (existingFileKeys.has(key)) {
if (!expired && !retainedUploadIds.has(file.attachmentId)) {
duplicateFiles.push(file);
}
@@ -2956,22 +2993,34 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// A pick that matches a needs-reattach marker replaces it in the draft, so
// it must not consume a slot; a draft full of markers would otherwise hit
// the capacity error before the replacement path could run.
- const reattachKeys = new Set(
- composerFilesRef.current
- .filter(composerFileNeedsReattach)
- .map((file) => `${file.mimeType}\u0000${file.sizeBytes}\u0000${file.name}`),
- );
+ const reattachMarkers = composerFilesRef.current.filter(composerFileNeedsReattach);
+ const replacedReattachMarkerIds = new Set<string>();
const acceptedImages: File[] = [];
const acceptedFiles: ComposerFileAttachment[] = [];
let error: string | null = null;
for (const file of files) {
const attachmentKind = classifyComposerAttachmentFile(file);
- const replacesReattachMarker =
- attachmentKind === "file" &&
- reattachKeys.delete(
- `${file.type || "application/octet-stream"}\u0000${file.size}\u0000${file.name || "file"}`,
- );
- if (!replacesReattachMarker && reservedCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
+ const fileMimeType =
+ attachmentKind === "file"
+ ? (videoMimeType({ name: file.name, mimeType: file.type }) ??
+ (file.type || "application/octet-stream"))
+ : file.type;
+ const matchingReattachMarker =
+ attachmentKind === "file"
+ ? reattachMarkers.find(
+ (marker) =>
+ !replacedReattachMarkerIds.has(marker.id) &&
+ composerFileMatchesReattachMarker(marker, {
+ name: file.name || "file",
+ mimeType: fileMimeType,
+ sizeBytes: file.size,
+ }),
+ )
+ : undefined;
+ if (matchingReattachMarker) {
+ replacedReattachMarkerIds.add(matchingReattachMarker.id);
+ }
+ if (!matchingReattachMarker && reservedCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`;
// Keep scanning: a later file in this batch can still replace a
// needs-reattach marker without needing a free slot.
@@ -2996,16 +3045,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
error = fileAttachmentTooLargeMessage(file.name, fileStagingLimit);
continue;
}
+ const attachmentFile =
+ file.type === fileMimeType
+ ? file
+ : new File([file], file.name, { type: fileMimeType, lastModified: file.lastModified });
acceptedFiles.push({
type: "file",
id: randomUUID(),
- name: file.name || "file",
- mimeType: file.type || "application/octet-stream",
- sizeBytes: file.size,
- file,
+ name: attachmentFile.name || "file",
+ mimeType: fileMimeType,
+ sizeBytes: attachmentFile.size,
+ file: attachmentFile,
});
}
- if (!replacesReattachMarker) {
+ if (!matchingReattachMarker) {
reservedCount += 1;
}
}
@@ -3686,10 +3739,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
{!isComposerCollapsedMobile &&
!isComposerApprovalState &&
pendingUserInputs.length === 0 &&
- composerImages.some(
- (image) =>
- !composerPreviewAnnotations.some((annotation) => annotation.id === image.id),
- ) && (
+ (composerVideos.length > 0 ||
+ composerImages.some(
+ (image) =>
+ !composerPreviewAnnotations.some((annotation) => annotation.id === image.id),
+ )) && (
<div className="mb-3 flex flex-wrap gap-2">
{composerImages
.filter(
@@ -3800,15 +3854,102 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
</div>
);
})}
+ {composerVideos.map((file) => {
+ const fileCanUpload =
+ supportsAttachmentUploads &&
+ maxFileAttachmentBytes !== null &&
+ file.sizeBytes <= maxFileAttachmentBytes;
+ const upload = fileCanUpload ? uploadsByImageId[file.id] : undefined;
+ const isOpening = file.uploadedAttachmentId === openingVideoAttachmentId;
+ return (
+ <div
+ key={file.id}
+ className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-black"
+ >
+ <button
+ type="button"
+ className="flex h-full w-full cursor-zoom-in flex-col items-center justify-center gap-1 px-1 text-white aria-disabled:cursor-default aria-disabled:opacity-50"
+ aria-busy={isOpening || undefined}
+ aria-disabled={isOpening || undefined}
+ aria-label={`${isOpening ? "Loading" : "Play"} ${file.name}`}
+ onClick={() => {
+ if (isOpening) return;
+ if (file.file !== null) {
+ const preview = buildExpandedImagePreview([file], file.id);
+ if (preview) onExpandImage(preview);
+ return;
+ }
+ if (!file.uploadedAttachmentId) return;
+ onFileOpen({ ...file, id: file.uploadedAttachmentId });
+ }}
+ >
+ {file.file && (
+ <>
+ <ComposerVideoThumbnail file={file.file} />
+ <span className="pointer-events-none absolute inset-0 bg-gradient-to-t from-black/70 via-black/10 to-black/10" />
+ </>
+ )}
+ {isOpening ? (
+ <span className="relative z-10 text-[10px]">Loading…</span>
+ ) : (
+ <PlayIcon className="relative z-10 size-4 fill-current drop-shadow-md" />
+ )}
+ </button>
+ {upload?.status === "uploading" && (
+ <span className="pointer-events-none absolute inset-x-0 bottom-0 bg-background/85 px-1 text-center text-[10px] text-foreground">
+ {formatAttachmentUploadProgress(upload.progress)}
+ </span>
+ )}
+ {upload?.status === "failed" && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ className="absolute bottom-1 left-1 bg-background/85 hover:bg-background/95"
+ onClick={() =>
+ retryAttachmentUpload({
+ environmentId,
+ image: file,
+ draftTarget: composerDraftTarget,
+ })
+ }
+ aria-label={`Retry upload for ${file.name}`}
+ />
+ }
+ >
+ <RotateCcwIcon />
+ </TooltipTrigger>
+ <TooltipPopup
+ side="top"
+ className="max-w-64 whitespace-normal leading-tight"
+ >
+ {upload.reason}
+ </TooltipPopup>
+ </Tooltip>
+ )}
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ className="absolute right-1 top-1 bg-background/80 hover:bg-background/90"
+ onClick={() => removeComposerFileFromDraft(file.id)}
+ aria-label={`Remove ${file.name}`}
+ >
+ <XIcon />
+ </Button>
+ </div>
+ );
+ })}
</div>
)}
{!isComposerCollapsedMobile &&
!isComposerApprovalState &&
pendingUserInputs.length === 0 &&
- composerFiles.length > 0 && (
+ composerOtherFiles.length > 0 && (
<div className="mb-3 flex flex-col gap-1">
- {composerFiles.map((file) => {
+ {composerOtherFiles.map((file) => {
const fileCanUpload =
supportsAttachmentUploads &&
maxFileAttachmentBytes !== null &&
diff --git a/apps/web/src/components/chat/ExpandedImageDialog.test.tsx b/apps/web/src/components/chat/ExpandedImageDialog.test.tsx
new file mode 100644
index 00000000000..c2a63f34ecd
--- /dev/null
+++ b/apps/web/src/components/chat/ExpandedImageDialog.test.tsx
@@ -0,0 +1,28 @@
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it } from "vite-plus/test";
+
+import { ExpandedImageDialog } from "./ExpandedImageDialog";
+import type { ExpandedImagePreview } from "./ExpandedImagePreview";
+
+describe("ExpandedImageDialog", () => {
+ it("renders video previews with native controls", () => {
+ const preview: ExpandedImagePreview = {
+ images: [
+ {
+ src: "https://environment.test/api/assets/demo.mp4",
+ name: "demo.mp4",
+ type: "video",
+ },
+ ],
+ index: 0,
+ };
+
+ const markup = renderToStaticMarkup(
+ <ExpandedImageDialog preview={preview} onClose={() => {}} />,
+ );
+
+ expect(markup).toContain("<video");
+ expect(markup).toContain('controls=""');
+ expect(markup).toContain('aria-label="demo.mp4"');
+ });
+});
diff --git a/apps/web/src/components/chat/ExpandedImageDialog.tsx b/apps/web/src/components/chat/ExpandedImageDialog.tsx
index fd14c68b0c4..ffae6471651 100644
--- a/apps/web/src/components/chat/ExpandedImageDialog.tsx
+++ b/apps/web/src/components/chat/ExpandedImageDialog.tsx
@@ -1,7 +1,7 @@
import { memo, useCallback, useEffect, useState } from "react";
-import { ChevronLeftIcon, ChevronRightIcon, XIcon } from "lucide-react";
+import { ChevronLeftIcon, ChevronRightIcon, DownloadIcon, XIcon } from "lucide-react";
import { Button } from "../ui/button";
-import type { ExpandedImagePreview } from "./ExpandedImagePreview";
+import { downloadVideoPreview, type ExpandedImagePreview } from "./ExpandedImagePreview";
interface ExpandedImageDialogProps {
preview: ExpandedImagePreview;
@@ -13,12 +13,27 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
onClose,
}: ExpandedImageDialogProps) {
const [imageOffset, setImageOffset] = useState(0);
+ const [failedVideoSrc, setFailedVideoSrc] = useState<string | null>(null);
+ const [downloadingVideoSrc, setDownloadingVideoSrc] = useState<string | null>(null);
+ const [downloadFailedVideoSrc, setDownloadFailedVideoSrc] = useState<string | null>(null);
const index = (preview.index + imageOffset + preview.images.length) % preview.images.length;
const navigateImage = useCallback((direction: -1 | 1) => {
setImageOffset((current) => current + direction);
}, []);
+ const downloadVideo = async (src: string, name: string) => {
+ setDownloadFailedVideoSrc(null);
+ setDownloadingVideoSrc(src);
+ try {
+ await downloadVideoPreview(src, name);
+ } catch {
+ setDownloadFailedVideoSrc(src);
+ } finally {
+ setDownloadingVideoSrc((current) => (current === src ? null : current));
+ }
+ };
+
useEffect(() => {
const onKeyDown = (event: globalThis.KeyboardEvent) => {
if (event.key === "Escape") {
@@ -45,18 +60,21 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
const item = preview.images[index];
if (!item) return null;
+ const mediaLabel = item.type === "video" ? "video" : "image";
+ const isDownloadingVideo = downloadingVideoSrc === item.src;
+ const videoDownloadFailed = downloadFailedVideoSrc === item.src;
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 px-4 py-6 [-webkit-app-region:no-drag]"
role="dialog"
aria-modal="true"
- aria-label="Expanded image preview"
+ aria-label={`Expanded ${mediaLabel} preview`}
>
<button
type="button"
className="absolute inset-0 z-0 cursor-zoom-out"
- aria-label="Close image preview"
+ aria-label={`Close ${mediaLabel} preview`}
onClick={onClose}
/>
{preview.images.length > 1 && (
@@ -78,16 +96,49 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
variant="ghost"
className="absolute right-2 top-2"
onClick={onClose}
- aria-label="Close image preview"
+ aria-label={`Close ${mediaLabel} preview`}
>
<XIcon />
</Button>
- <img
- src={item.src}
- alt={item.name}
- className="max-h-[86vh] max-w-[92vw] select-none rounded-lg border border-border/70 bg-background object-contain shadow-2xl"
- draggable={false}
- />
+ {item.type === "video" && failedVideoSrc === item.src ? (
+ <div className="flex h-48 w-[min(92vw,32rem)] flex-col items-center justify-center gap-3 rounded-lg border border-border/70 bg-black px-6 text-center text-white shadow-2xl">
+ <p className="text-sm">
+ {videoDownloadFailed
+ ? "Could not download this video."
+ : "This video format cannot be played here."}
+ </p>
+ <Button
+ size="sm"
+ variant="secondary"
+ aria-busy={isDownloadingVideo || undefined}
+ aria-disabled={isDownloadingVideo || undefined}
+ onClick={() => {
+ if (isDownloadingVideo) return;
+ void downloadVideo(item.src, item.name);
+ }}
+ >
+ <DownloadIcon />
+ {isDownloadingVideo ? "Downloading…" : "Download video"}
+ </Button>
+ </div>
+ ) : item.type === "video" ? (
+ <video
+ src={item.src}
+ aria-label={item.name}
+ autoPlay
+ controls
+ playsInline
+ onError={() => setFailedVideoSrc(item.src)}
+ className="max-h-[86vh] max-w-[92vw] rounded-lg border border-border/70 bg-black object-contain shadow-2xl"
+ />
+ ) : (
+ <img
+ src={item.src}
+ alt={item.name}
+ className="max-h-[86vh] max-w-[92vw] select-none rounded-lg border border-border/70 bg-background object-contain shadow-2xl"
+ draggable={false}
+ />
+ )}
<p className="mt-2 max-w-[92vw] truncate text-center text-xs text-muted-foreground/80">
{item.name}
{preview.images.length > 1 ? ` (${index + 1}/${preview.images.length})` : ""}
diff --git a/apps/web/src/components/chat/ExpandedImagePreview.test.ts b/apps/web/src/components/chat/ExpandedImagePreview.test.ts
new file mode 100644
index 00000000000..71979a3cb01
--- /dev/null
+++ b/apps/web/src/components/chat/ExpandedImagePreview.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import type { ComposerFileAttachment } from "../../composerDraftStore";
+import {
+ attachVideoThumbnail,
+ buildExpandedImagePreview,
+ downloadVideoPreview,
+} from "./ExpandedImagePreview";
+
+describe("buildExpandedImagePreview", () => {
+ it("builds a video preview for a local video attachment", () => {
+ const file = new File([new Uint8Array([1, 2, 3])], "demo.mp4", { type: "video/mp4" });
+ const attachment: ComposerFileAttachment = {
+ type: "file",
+ id: "video-1",
+ name: file.name,
+ mimeType: file.type,
+ sizeBytes: file.size,
+ file,
+ };
+
+ const preview = buildExpandedImagePreview([attachment], attachment.id);
+
+ expect(preview).toMatchObject({
+ images: [{ name: "demo.mp4", type: "video" }],
+ index: 0,
+ });
+ expect(preview?.images[0]?.src).toMatch(/^blob:/);
+ URL.revokeObjectURL(preview?.images[0]?.src ?? "");
+ });
+
+ it("releases a video thumbnail URL when detached", async () => {
+ const video = { src: "" } as HTMLVideoElement;
+ const file = new File([new Uint8Array([1, 2, 3])], "demo.mp4", { type: "video/mp4" });
+
+ const detach = attachVideoThumbnail(video, file);
+ const url = video.src;
+
+ expect((await fetch(url)).ok).toBe(true);
+ detach();
+ await expect(fetch(url)).rejects.toThrow();
+ });
+
+ it("downloads a video through a local blob URL", async () => {
+ vi.useFakeTimers();
+ const source = URL.createObjectURL(new Blob([new Uint8Array([1, 2, 3])]));
+ const click = vi.fn();
+ const anchor = { href: "", download: "", click };
+ vi.stubGlobal("document", { createElement: () => anchor });
+
+ try {
+ await downloadVideoPreview(source, "demo.mp4");
+
+ expect(anchor.download).toBe("demo.mp4");
+ expect(anchor.href).toMatch(/^blob:/);
+ expect(anchor.href).not.toBe(source);
+ expect(click).toHaveBeenCalledOnce();
+ expect((await fetch(anchor.href)).ok).toBe(true);
+
+ await vi.runAllTimersAsync();
+ await expect(fetch(anchor.href)).rejects.toThrow();
+ } finally {
+ URL.revokeObjectURL(source);
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ }
+ });
+});
diff --git a/apps/web/src/components/chat/ExpandedImagePreview.tsx b/apps/web/src/components/chat/ExpandedImagePreview.tsx
index db5803d4908..b57a292e0bf 100644
--- a/apps/web/src/components/chat/ExpandedImagePreview.tsx
+++ b/apps/web/src/components/chat/ExpandedImagePreview.tsx
@@ -1,6 +1,10 @@
+import type { ComposerFileAttachment } from "../../composerDraftStore";
+import { type ChatImageAttachment, isVideoAttachment } from "../../types";
+
export interface ExpandedImageItem {
src: string;
name: string;
+ type?: "video";
}
export interface ExpandedImagePreview {
@@ -8,12 +12,38 @@ export interface ExpandedImagePreview {
index: number;
}
+export function attachVideoThumbnail(video: HTMLVideoElement, file: File): () => void {
+ const url = URL.createObjectURL(file);
+ video.src = url;
+ return () => URL.revokeObjectURL(url);
+}
+
+export async function downloadVideoPreview(src: string, name: string): Promise<void> {
+ const response = await fetch(src);
+ if (!response.ok) throw new Error(`Could not download video (${response.status}).`);
+ const url = URL.createObjectURL(await response.blob());
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ anchor.download = name;
+ anchor.click();
+ setTimeout(() => URL.revokeObjectURL(url), 30_000);
+}
+
export function buildExpandedImagePreview(
- images: ReadonlyArray<{ id: string; name: string; previewUrl?: string }>,
+ images: ReadonlyArray<ChatImageAttachment | ComposerFileAttachment>,
selectedImageId: string,
): ExpandedImagePreview | null {
+ const selected = images.find((image) => image.id === selectedImageId);
+ if (selected?.type === "file" && selected.file && isVideoAttachment(selected)) {
+ return {
+ images: [{ src: URL.createObjectURL(selected.file), name: selected.name, type: "video" }],
+ index: 0,
+ };
+ }
const previewableImages = images.flatMap((image) =>
- image.previewUrl ? [{ id: image.id, src: image.previewUrl, name: image.name }] : [],
+ image.type === "image" && image.previewUrl
+ ? [{ id: image.id, src: image.previewUrl, name: image.name }]
+ : [],
);
if (previewableImages.length === 0) {
return null;
diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx
index 4c7cf29969d..5b7584fb6e4 100644
--- a/apps/web/src/components/chat/MessagesTimeline.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx
@@ -187,6 +187,7 @@ function buildProps() {
revertTurnCountByUserMessageId: new Map(),
onRevertUserMessage: () => {},
isRevertingCheckpoint: false,
+ openingVideoAttachmentId: null,
onImageExpand: () => {},
activeThreadEnvironmentId: ACTIVE_THREAD_ENVIRONMENT_ID,
markdownCwd: undefined,
@@ -586,6 +587,43 @@ describe("MessagesTimeline", () => {
expect(markup).not.toContain('alt="report.pdf"');
});
+ it("renders video attachments as play buttons", () => {
+ const entry = {
+ ...buildUserTimelineEntry("Watch the demo."),
+ message: {
+ ...buildUserTimelineEntry("Watch the demo.").message,
+ attachments: [
+ {
+ type: "file" as const,
+ id: "attachment-demo-mp4",
+ name: "demo.mp4",
+ mimeType: "video/mp4",
+ sizeBytes: 42,
+ },
+ ],
+ },
+ };
+
+ const markup = renderToStaticMarkup(
+ <MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
+ );
+ const busyMarkup = renderToStaticMarkup(
+ <MessagesTimeline
+ {...buildProps()}
+ timelineEntries={[entry]}
+ openingVideoAttachmentId="attachment-demo-mp4"
+ />,
+ );
+
+ expect(markup).toContain('aria-label="Play demo.mp4"');
+ expect(markup).toContain("min-h-[72px]");
+ expect(markup).toContain(">demo.mp4</span>");
+ expect(markup).not.toContain('aria-label="Download demo.mp4"');
+ expect(busyMarkup).toContain('aria-busy="true"');
+ expect(busyMarkup).toContain('aria-disabled="true"');
+ expect(busyMarkup).not.toContain('disabled=""');
+ expect(busyMarkup).toContain(">Loading…</span>");
+ });
it("renders a file download button without creating its URL in advance", () => {
const entry = {
...buildUserTimelineEntry("Read the report."),
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index 0b9acdf3347..e2232cdd9b9 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -16,7 +16,7 @@ import {
const EMPTY_AGENT_PANEL_MODEL = emptyAgentPanelModel();
const NOOP_OPEN_AGENTS = () => {};
-const NOOP_DOWNLOAD_ATTACHMENT = (_attachment: ChatFileAttachment) => {};
+const NOOP_OPEN_ATTACHMENT = (_attachment: ChatFileAttachment) => {};
import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import {
createContext,
@@ -45,6 +45,7 @@ import {
type ChatImageAttachment,
isFileAttachment,
isImageAttachment,
+ isVideoAttachment,
type TurnDiffSummary,
} from "../../types";
import {
@@ -67,6 +68,7 @@ import {
MessageCircleIcon,
MousePointerClickIcon,
PaintbrushIcon,
+ PlayIcon,
SearchIcon,
SquarePenIcon,
TerminalIcon,
@@ -153,7 +155,8 @@ interface TimelineRowSharedState {
activeThreadEnvironmentId: EnvironmentId;
onRevertUserMessage: (messageId: MessageId) => void;
onImageExpand: (preview: ExpandedImagePreview) => void;
- onFileDownload: (attachment: ChatFileAttachment) => void;
+ onFileOpen: (attachment: ChatFileAttachment) => void;
+ openingVideoAttachmentId: string | null;
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
onToggleTurnFold: (turnId: TurnId) => void;
onToggleWorkGroup: (groupId: string, anchorKey: string) => void;
@@ -232,7 +235,8 @@ interface MessagesTimelineProps {
onRevertUserMessage: (messageId: MessageId) => void;
isRevertingCheckpoint: boolean;
onImageExpand: (preview: ExpandedImagePreview) => void;
- onFileDownload?: (attachment: ChatFileAttachment) => void;
+ onFileOpen?: (attachment: ChatFileAttachment) => void;
+ openingVideoAttachmentId: string | null;
activeThreadEnvironmentId: EnvironmentId;
markdownCwd: string | undefined;
resolvedTheme: "light" | "dark";
@@ -278,7 +282,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onRevertUserMessage,
isRevertingCheckpoint,
onImageExpand,
- onFileDownload = NOOP_DOWNLOAD_ATTACHMENT,
+ onFileOpen = NOOP_OPEN_ATTACHMENT,
+ openingVideoAttachmentId,
activeThreadEnvironmentId,
markdownCwd,
resolvedTheme,
@@ -537,7 +542,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
activeThreadEnvironmentId,
onRevertUserMessage,
onImageExpand,
- onFileDownload,
+ onFileOpen,
+ openingVideoAttachmentId,
onOpenTurnDiff,
onToggleTurnFold,
onToggleWorkGroup,
@@ -554,7 +560,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
activeThreadEnvironmentId,
onRevertUserMessage,
onImageExpand,
- onFileDownload,
+ onFileOpen,
+ openingVideoAttachmentId,
onOpenTurnDiff,
onToggleTurnFold,
onToggleWorkGroup,
@@ -1005,6 +1012,8 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
// comparisons) split it. Unknown types render as inert rows below the files.
const userImages = (row.message.attachments ?? []).filter(isImageAttachment);
const userFiles = (row.message.attachments ?? []).filter(isFileAttachment);
+ const userVideos = userFiles.filter(isVideoAttachment);
+ const otherUserFiles = userFiles.filter((file) => !isVideoAttachment(file));
const unknownAttachments = (row.message.attachments ?? []).filter(
(attachment) => !isImageAttachment(attachment) && !isFileAttachment(attachment),
);
@@ -1030,7 +1039,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
return (
<div className="group flex flex-col items-end gap-1">
<div className="relative max-w-[80%] rounded-2xl bg-message p-3 text-message-foreground">
- {regularImages.length > 0 && (
+ {(regularImages.length > 0 || userVideos.length > 0) && (
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
{regularImages.map((image) => (
<div
@@ -1061,6 +1070,35 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
)}
</div>
))}
+ {userVideos.map((file) => {
+ const isOpening = ctx.openingVideoAttachmentId === file.id;
+ return (
+ <div
+ key={file.id}
+ className="overflow-hidden rounded-lg border border-border/80 bg-black"
+ >
+ <button
+ type="button"
+ disabled={file.downloadable === false}
+ className="flex min-h-[72px] w-full cursor-zoom-in flex-col items-center justify-center gap-1 px-2 py-2 text-white disabled:cursor-default disabled:opacity-50 aria-disabled:cursor-default aria-disabled:opacity-50"
+ aria-busy={isOpening || undefined}
+ aria-disabled={isOpening || undefined}
+ aria-label={`${isOpening ? "Loading" : "Play"} ${file.name}`}
+ onClick={() => {
+ if (isOpening) return;
+ ctx.onFileOpen(file);
+ }}
+ >
+ {isOpening ? (
+ <span className="text-[11px]">Loading…</span>
+ ) : (
+ <PlayIcon className="size-8 fill-current" />
+ )}
+ <span className="max-w-full truncate text-[11px]">{file.name}</span>
+ </button>
+ </div>
+ );
+ })}
</div>
)}
{previewAnnotations.map((annotation, index) => (
@@ -1070,9 +1108,9 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
image={previewImages[index] ?? null}
/>
))}
- {userFiles.length > 0 || unknownAttachments.length > 0 ? (
+ {otherUserFiles.length > 0 || unknownAttachments.length > 0 ? (
<div className="mb-2 flex flex-col gap-1">
- {userFiles.map((file) => {
+ {otherUserFiles.map((file) => {
const content = (
<>
<FileIcon className="size-4 shrink-0 text-secondary-label" />
@@ -1100,7 +1138,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
key={file.id}
type="button"
aria-label={`Download ${file.name}`}
- onClick={() => ctx.onFileDownload(file)}
+ onClick={() => ctx.onFileOpen(file)}
className="flex min-w-0 cursor-pointer items-center gap-2 rounded-md py-1 text-left text-sm hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
>
{content}
diff --git a/apps/web/src/components/chat/composerAttachmentFiles.test.ts b/apps/web/src/components/chat/composerAttachmentFiles.test.ts
index d650e0b1070..2269dcf4489 100644
--- a/apps/web/src/components/chat/composerAttachmentFiles.test.ts
+++ b/apps/web/src/components/chat/composerAttachmentFiles.test.ts
@@ -2,12 +2,14 @@ import { EnvironmentId, PROVIDER_SEND_TURN_MAX_FILE_BYTES } from "@t3tools/contr
import { describe, expect, it } from "vite-plus/test";
import type { ComposerFileAttachment, ComposerImageAttachment } from "../../composerDraftStore";
+import { isVideoAttachment, videoMimeType } from "../../types";
import {
attachmentsToReleaseOnUploadCapabilityLoss,
classifyComposerAttachmentFile,
fileAttachmentCapabilityBlockReason,
fileAttachmentStagingLimit,
inferImageMimeTypeFromName,
+ isPreviewableComposerVideo,
normalizeComposerImageFileMimeType,
shouldHandleComposerAttachmentPaste,
} from "./composerAttachmentFiles";
@@ -267,6 +269,48 @@ describe("composer attachment files", () => {
expect(released.map((attachment) => attachment.id)).toEqual(["image-1", "file-uploading"]);
});
+ it("keeps restored videos on the preview path in their upload environment", () => {
+ const environmentId = EnvironmentId.make("environment-1");
+ const video: ComposerFileAttachment = {
+ type: "file",
+ id: "video-1",
+ name: "clip.mp4",
+ mimeType: "video/mp4",
+ sizeBytes: 3,
+ file: null,
+ uploadedAttachmentId: "uploaded-video-1",
+ uploadEnvironmentId: environmentId,
+ };
+
+ expect(isPreviewableComposerVideo(video, environmentId)).toBe(true);
+ expect(isPreviewableComposerVideo(video, EnvironmentId.make("environment-2"))).toBe(false);
+ });
+
+ it("recognizes common video extensions when the browser omits the MIME type", () => {
+ const formats = [
+ ["clip.mp4", "video/mp4"],
+ ["clip.mov", "video/quicktime"],
+ ["clip.webm", "video/webm"],
+ ["clip.m4v", "video/mp4"],
+ ["clip.mkv", "video/x-matroska"],
+ ["clip.avi", "video/x-msvideo"],
+ ["clip.ogv", "video/ogg"],
+ ] as const;
+
+ for (const [name, expectedMimeType] of formats) {
+ expect(
+ isVideoAttachment({
+ type: "file",
+ id: name,
+ name,
+ mimeType: "application/octet-stream",
+ sizeBytes: 1,
+ }),
+ ).toBe(true);
+ expect(videoMimeType({ name, mimeType: "application/octet-stream" })).toBe(expectedMimeType);
+ }
+ });
+
it("claims image pastes even when clipboard text is present", () => {
const image = new File(["image"], "photo.heic", { type: "image/heic" });
diff --git a/apps/web/src/components/chat/composerAttachmentFiles.ts b/apps/web/src/components/chat/composerAttachmentFiles.ts
index 58ca40508b4..f9991e732c5 100644
--- a/apps/web/src/components/chat/composerAttachmentFiles.ts
+++ b/apps/web/src/components/chat/composerAttachmentFiles.ts
@@ -1,4 +1,5 @@
import {
+ type EnvironmentId,
isProviderSendTurnSupportedImageMimeType,
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
} from "@t3tools/contracts";
@@ -9,6 +10,7 @@ import {
import type { ComposerFileAttachment, ComposerImageAttachment } from "../../composerDraftStore";
import { isHeicImageFile } from "../../lib/imageCompression";
+import { isVideoAttachment } from "../../types";
type ComposerAttachmentFileKind = "image" | "file" | "unsupported-image";
@@ -75,6 +77,17 @@ export function classifyComposerAttachmentFile(
return isProviderSendTurnSupportedImageMimeType(file.type) ? "image" : "unsupported-image";
}
+export function isPreviewableComposerVideo(
+ file: ComposerFileAttachment,
+ environmentId: EnvironmentId,
+): boolean {
+ return (
+ isVideoAttachment(file) &&
+ (file.file !== null ||
+ (file.uploadedAttachmentId !== undefined && file.uploadEnvironmentId === environmentId))
+ );
+}
+
/** Byte limit for adding a generic file to the local composer draft. */
export function fileAttachmentStagingLimit(input: FileAttachmentCapabilityState): number | null {
if (!input.attachmentUploadsCapabilityKnown) {
diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
index 3e8cdcd6b5d..f782e5be113 100644
--- a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
@@ -10,12 +10,10 @@ import { splitPullRequestBody } from "./pullRequestMarkdown.logic";
* A pull request body, rendered with the app's markdown renderer plus a card for each upload
* embedded in it, which that renderer drops on the floor.
*
- * The card links out instead of playing in place, because nothing here can play. A
- * `github.com/user-attachments/assets/…` link is a 302 to a signed S3 URL that serves the file
- * as uploaded — `video/quicktime` for anything recorded on a Mac, which no Chromium decodes —
- * and the desktop window's content policy declares no `media-src`, so media falls back to
- * `default-src 'self'` and every remote source is refused before a byte is fetched. A player
- * here can only be the box that never fills in; a card that opens the host is a real answer.
+ * The card links out instead of playing in place. GitHub serves the file as uploaded — Mac
+ * recordings are `video/quicktime`, which no Chromium decodes — and the desktop window's
+ * `media-src` allows only `'self'`, the app scheme and `blob:`, so a remote source is refused
+ * before a byte is fetched. Opening the host works for every format.
*/
export function PullRequestMarkdown({
text,
diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts
index 329167e2927..ac797529308 100644
--- a/apps/web/src/composerDraftStore.test.ts
+++ b/apps/web/src/composerDraftStore.test.ts
@@ -517,6 +517,34 @@ describe("composerDraftStore file attachments", () => {
expect(files?.some(composerFileNeedsReattach)).toBe(false);
});
+ it("replaces a legacy video marker after its MIME type is normalized", () => {
+ const store = useComposerDraftStore.getState();
+ const marker: ComposerFileAttachment = {
+ type: "file",
+ id: "file-marker",
+ name: "clip.mkv",
+ mimeType: "application/octet-stream",
+ sizeBytes: 6,
+ file: null,
+ };
+ store.addFiles(threadRef, [marker]);
+
+ const file = new File(["report"], marker.name, { type: "video/x-matroska" });
+ const repicked: ComposerFileAttachment = {
+ type: "file",
+ id: "file-repicked",
+ name: file.name,
+ mimeType: file.type,
+ sizeBytes: file.size,
+ file,
+ };
+ store.addFiles(threadRef, [repicked, { ...repicked, id: "file-repicked-duplicate" }]);
+
+ const files = store.getComposerDraft(threadRef)?.files;
+ expect(files?.map((entry) => entry.id)).toEqual(["file-repicked"]);
+ expect(files?.some(composerFileNeedsReattach)).toBe(false);
+ });
+
it("replaces a needs-reattach marker with a stash-restored uploaded file", () => {
const store = useComposerDraftStore.getState();
const marker: ComposerFileAttachment = { ...makeFile("file-marker"), file: null };
@@ -553,6 +581,36 @@ describe("composerDraftStore file attachments", () => {
]);
});
+ it("keeps same-name videos with different MIME types", () => {
+ const store = useComposerDraftStore.getState();
+ const mp4 = new File(["report"], "clip", { type: "video/mp4" });
+ const webm = new File(["report"], "clip", { type: "video/webm" });
+
+ store.addFiles(threadRef, [
+ {
+ type: "file",
+ id: "video-mp4",
+ name: mp4.name,
+ mimeType: mp4.type,
+ sizeBytes: mp4.size,
+ file: mp4,
+ },
+ {
+ type: "file",
+ id: "video-webm",
+ name: webm.name,
+ mimeType: webm.type,
+ sizeBytes: webm.size,
+ file: webm,
+ },
+ ]);
+
+ expect(store.getComposerDraft(threadRef)?.files.map((file) => file.id)).toEqual([
+ "video-mp4",
+ "video-webm",
+ ]);
+ });
+
it("keeps the remaining file slot available after a duplicate is skipped", () => {
const store = useComposerDraftStore.getState();
store.addImages(
diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts
index c32415b222c..886c89071d1 100644
--- a/apps/web/src/composerDraftStore.ts
+++ b/apps/web/src/composerDraftStore.ts
@@ -39,6 +39,7 @@ import {
DEFAULT_RUNTIME_MODE,
type ChatFileAttachment,
type ChatImageAttachment,
+ videoMimeType,
} from "./types";
import {
type TerminalContextDraft,
@@ -745,6 +746,26 @@ function composerImageDedupKey(image: ComposerImageAttachment): string {
return `${image.mimeType}\u0000${image.sizeBytes}\u0000${image.name}`;
}
+export function composerFileDedupKey(
+ file: Pick<ComposerFileAttachment, "mimeType" | "sizeBytes" | "name">,
+): string {
+ return `${file.mimeType}\u0000${file.sizeBytes}\u0000${file.name}`;
+}
+
+export function composerFileMatchesReattachMarker(
+ marker: Pick<ComposerFileAttachment, "mimeType" | "sizeBytes" | "name">,
+ file: Pick<ComposerFileAttachment, "mimeType" | "sizeBytes" | "name">,
+): boolean {
+ if (marker.name !== file.name || marker.sizeBytes !== file.sizeBytes) return false;
+ if (marker.mimeType === file.mimeType) return true;
+ const markerMimeType = marker.mimeType.toLowerCase();
+ return (
+ (markerMimeType === "" || markerMimeType === "application/octet-stream") &&
+ videoMimeType(marker) !== null &&
+ videoMimeType(file) !== null
+ );
+}
+
function terminalContextDedupKey(context: TerminalContextDraft): string {
return `${context.terminalId}\u0000${context.lineStart}\u0000${context.lineEnd}`;
}
@@ -3189,29 +3210,32 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
const knownIds = new Set(existing.files.map((file) => file.id));
const knownFiles = new Map<string, ComposerFileAttachment>(
- existing.files.map((file) => [
- `${file.mimeType}\u0000${file.sizeBytes}\u0000${file.name}`,
- file,
- ]),
+ existing.files.map((file) => [composerFileDedupKey(file), file]),
);
const accepted: ComposerFileAttachment[] = [];
// Needs-reattach markers replaced in place by a re-pick, keyed by
// the marker's id.
const replacements = new Map<string, ComposerFileAttachment>();
for (const file of files) {
- const key = `${file.mimeType}\u0000${file.sizeBytes}\u0000${file.name}`;
+ const key = composerFileDedupKey(file);
if (knownIds.has(file.id)) {
continue;
}
- const duplicate = knownFiles.get(key);
+ const duplicate =
+ knownFiles.get(key) ??
+ existing.files.find(
+ (candidate) =>
+ composerFileNeedsReattach(candidate) &&
+ !replacements.has(candidate.id) &&
+ composerFileMatchesReattachMarker(candidate, file),
+ );
if (duplicate) {
- // A needs-reattach marker persists exactly the metadata this
- // key hashes, so re-picking the same file matches its marker.
- // Dropping the pick as a duplicate would leave the draft
- // blocked forever; replace the marker so the upload restarts.
+ // A needs-reattach marker is not a usable duplicate. Replace
+ // it so the upload restarts.
if (composerFileNeedsReattach(duplicate) && !replacements.has(duplicate.id)) {
replacements.set(duplicate.id, file);
knownIds.add(file.id);
+ knownFiles.set(key, file);
}
continue;
}
@@ -3802,18 +3826,12 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
// A file the destination already holds (same id, or same
// metadata key) stays behind instead of duplicating there.
const destinationFileIds = new Set(destination.files.map((file) => file.id));
- const destinationFileKeys = new Set(
- destination.files.map(
- (file) => `${file.mimeType}\u0000${file.sizeBytes}\u0000${file.name}`,
- ),
- );
+ const destinationFileKeys = new Set(destination.files.map(composerFileDedupKey));
const transferableFiles = source.files.filter(
(file) =>
(file.file !== null || file.uploadEnvironmentId === destinationEnvironmentId) &&
!destinationFileIds.has(file.id) &&
- !destinationFileKeys.has(
- `${file.mimeType}\u0000${file.sizeBytes}\u0000${file.name}`,
- ),
+ !destinationFileKeys.has(composerFileDedupKey(file)),
);
const remainingAttachmentSlots = Math.max(
0,
diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts
index 776631428d2..f5727980a25 100644
--- a/apps/web/src/types.ts
+++ b/apps/web/src/types.ts
@@ -59,6 +59,31 @@ export function isFileAttachment(attachment: ChatAttachment): attachment is Chat
return attachment.type === "file";
}
+const VIDEO_MIME_TYPE_BY_EXTENSION: Readonly<Record<string, string>> = {
+ avi: "video/x-msvideo",
+ m4v: "video/mp4",
+ mkv: "video/x-matroska",
+ mov: "video/quicktime",
+ mp4: "video/mp4",
+ ogv: "video/ogg",
+ webm: "video/webm",
+};
+
+export function videoMimeType(
+ attachment: Pick<ChatFileAttachment, "name" | "mimeType">,
+): string | null {
+ const mimeType = attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
+ if (mimeType.startsWith("video/")) return mimeType;
+ const dotIndex = attachment.name.lastIndexOf(".");
+ return dotIndex < 0
+ ? null
+ : (VIDEO_MIME_TYPE_BY_EXTENSION[attachment.name.slice(dotIndex + 1).toLowerCase()] ?? null);
+}
+
+export function isVideoAttachment(attachment: ChatFileAttachment): boolean {
+ return videoMimeType(attachment) !== null;
+}
+
export interface ChatMessage extends Omit<OrchestrationMessage, "attachments"> {
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
}
diff --git a/docs/user/composer.md b/docs/user/composer.md
index 357616d8ed3..6b99cf113c3 100644
--- a/docs/user/composer.md
+++ b/docs/user/composer.md
@@ -13,6 +13,9 @@ On web and desktop, attachments upload as soon as you add them. The send button
after every upload finishes. Failed uploads can be retried or removed. On mobile, attachments are
currently limited to images.
+Select a video attachment before or after sending to play it with the browser's built-in controls.
+Playback depends on the video formats and codecs that the browser supports.
+
If you reload before a file finishes uploading, the draft keeps the file's name and shows **Attach
again** next to it. Attach the file again or remove it, then send.