feat(attachments): support local files and video attachments (#6321)

* feat(attachments): support local files and video attachments

Share gateway inspection and send validation for borrowed local paths while preserving binary uploads, original-file ownership, and existing limits.

Related to NAN-284. Native provider video input remains outside this change.

* test: make cross-platform verification fixtures self-contained

* test(webui): align typed fixtures with runtime contracts

* fix(webui): preserve uploaded video playback during history sync

* test(tui): preserve local attachment drafts across resizes

* perf(attachments): preserve upload caches and release video previews

* docs(webui): keep attachment guidance user-focused

* chore: remove redundant dependency comment

* test(providers): make stream idle renewal timing deterministic

* fix(attachments): keep upload byte limits out of local references

Validate common format/count rules separately from upload byte budgets. Keep local inspection and send-time checks metadata-only, and exclude local references from composer and pending-upload totals. Explain upload size rejections with actual size and maximum in all ten locales. Related to NAN-284.

* fix(attachments): retain image references and draft order

* fix(attachments): close local reference UX and authorization gaps

* fix(attachments): preserve focus during asynchronous path confirmation
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-22 18:32:18 +08:00
1 parent 7dfeff9ddf
commit 254f94b068
65 files changed
+1816 -292

No files matched your search

+15 -6
View File
@@ -13,12 +13,14 @@ interface AttachmentTileProps {
className?: string;
inline?: boolean;
variant?: "default" | "compact";
pending?: boolean;
}
export function AttachmentTile({ attachment, className, inline = false, variant = "default" }: AttachmentTileProps) {
export function AttachmentTile({ attachment, className, inline = false, variant = "default", pending = false }: AttachmentTileProps) {
const { t } = useTranslation();
const videoUrl = attachment.url;
const [failedUrl, setFailedUrl] = useState<string | undefined>(undefined);
const failed = !!attachment.url && failedUrl === attachment.url;
const failed = !!videoUrl && failedUrl === videoUrl;
const [imageOpen, setImageOpen] = useState(false);
const hasUrl = typeof attachment.url === "string" && attachment.url.length > 0;
const label = attachmentLabel(attachment, t);
@@ -36,7 +38,7 @@ export function AttachmentTile({ attachment, className, inline = false, variant
);
}
if (attachment.kind === "video" && hasUrl) {
if (attachment.kind === "video" && hasUrl && !failed) {
return (
<AttachmentFrame
attachment={attachment}
@@ -45,9 +47,10 @@ export function AttachmentTile({ attachment, className, inline = false, variant
variant={variant}
>
<video
src={attachment.url}
src={videoUrl}
controls
preload="metadata"
onError={() => setFailedUrl(videoUrl)}
className={cn(
"block w-full bg-black",
variant === "compact" ? "max-h-40" : "max-h-[26rem]",
@@ -100,9 +103,15 @@ export function AttachmentTile({ attachment, className, inline = false, variant
aria-label={label}
>
{body}
<span className="sr-only">
{t("message.attachmentUnavailable", { defaultValue: "Attachment unavailable" })}
<span className="text-xs text-muted-foreground">
{pending ? t("message.delivery.sending") : t("message.attachmentUnavailable", { defaultValue: "Attachment unavailable" })}
</span>
{attachment.kind === "video" && failed && !pending ? (
<button type="button" onClick={() => setFailedUrl(undefined)}
className="shrink-0 rounded-sm px-1 text-foreground underline-offset-2 hover:underline focus-visible:outline focus-visible:outline-2">
{t("common.retry")}
</button>
) : null}
</div>
);
}
+4 -2
View File
@@ -477,7 +477,7 @@ export function MessageBubble({
{!hasText ? contextMenu : null}
{hasImages ? <ImageGallery images={images} align="right" size="compact" /> : null}
{!hasImages && hasMedia ? (
<MessageMedia media={media} align="right" />
<MessageMedia media={media} align="right" pending={message.deliveryStatus === "sending"} />
) : null}
{quotedContext ? (
<UserQuotedContext
@@ -641,9 +641,11 @@ function mergeCliMentionApps(
function MessageMedia({
media,
align,
pending = false,
}: {
media: UIMediaAttachment[];
align: "left" | "right";
pending?: boolean;
}) {
const inlineImages = useInlineImages();
if (media.length === 0) return null;
@@ -673,7 +675,7 @@ function MessageMedia({
<ImageGallery images={images} align={align} size={align === "left" ? "large" : "compact"} />
) : null}
{nonImages.map((item, i) => (
<AttachmentTile key={`${item.url ?? item.name ?? item.kind}-${i}`} attachment={item} />
<AttachmentTile key={`${item.kind}-${i}`} attachment={item} pending={pending} />
))}
</div>
);
+134 -57
View File
@@ -1,3 +1,4 @@
import { pastedFilePath, PastedPathRange, isLocalAttachment, type LocalAttachment } from "../../../../packages/client-events/attachments";
import {
NewChatIcon,
CompactIcon,
@@ -57,6 +58,7 @@ import {
ChevronUp,
CornerDownRight,
FileText,
Video,
ImageIcon,
Loader2,
Quote,
@@ -94,13 +96,15 @@ import {
} from "@/components/thread/ComposerUsagePopover";
import {
ACCEPT_ATTR,
acceptedAttachmentKind,
MAX_ATTACHMENTS_PER_MESSAGE,
MAX_ATTACHMENT_BYTES,
MAX_TOTAL_ATTACHMENT_BYTES,
MAX_VIDEO_BYTES,
MAX_VIDEOS_PER_MESSAGE,
useAttachedImages,
type AttachedImage,
type AttachmentError,
type AttachmentKind,
type RestoredReadyImage,
} from "@/hooks/useAttachedImages";
import { useClipboardAndDrop } from "@/hooks/useClipboardAndDrop";
@@ -142,7 +146,7 @@ import {
} from "@/lib/session-drag";
import { formatQuotedUserMessage } from "@/lib/user-message-quote";
import { cn } from "@/lib/utils";
import type { ComposerDraftStore } from "@/lib/composer-draft";
import type { ComposerDraft, ComposerDraftStore } from "@/lib/composer-draft";
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
const VOICE_SHORTCUT_CODE = "KeyD";
@@ -153,8 +157,8 @@ type VoiceShortcutPlatform = "apple" | "chromeos" | "linux" | "other" | "windows
function formatBytes(n: number): string {
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
return `${(n / (1024 * 1024)).toFixed(1)} MB`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`;
return `${(n / (1024 * 1024)).toFixed(1)} MiB`;
}
function utf8Bytes(value: string): number {
@@ -244,6 +248,7 @@ interface ThreadComposerProps {
onStop?: () => void;
surfaceRef?: Ref<HTMLDivElement>;
onTranscribeAudio?: (dataUrl: string, options?: { durationMs?: number }) => Promise<string>;
onInspectAttachment?: (path: string) => Promise<LocalAttachment>;
/** Sustained objective for this chat (WebSocket ``goal_state``). */
goalState?: GoalStateWsPayload;
workspaceScope?: WorkspaceScopePayload | null;
@@ -398,17 +403,15 @@ function mergeQueuedPrompt(first: QueuedPrompt, next: QueuedPrompt): QueuedPromp
};
}
function queuedAttachmentBytes(image: QueuedPromptImage): number {
const base64 = image.dataUrl.slice(image.dataUrl.indexOf(",") + 1);
function queuedUploadBytes(image: QueuedPromptImage): number {
if (image.local) return 0;
const dataUrl = image.dataUrl ?? "";
const base64 = dataUrl.slice(dataUrl.indexOf(",") + 1);
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
return Math.floor(base64.length * 3 / 4) - padding;
}
interface QueuedPromptImage {
dataUrl: string;
name?: string;
kind?: AttachmentKind;
}
type QueuedPromptImage = RestoredReadyImage;
interface CliAppMentionQuery {
query: string;
@@ -555,13 +558,16 @@ function normalizeQueuedPrompt(item: unknown, index: number): QueuedPrompt | nul
if (typeof record.text !== "string") return null;
const text = record.text.trim();
const images = Array.isArray(record.images)
? record.images.flatMap((image) => {
? record.images.flatMap((image): QueuedPromptImage[] => {
if (!image || typeof image !== "object") return [];
const candidate = image as Partial<QueuedPromptImage>;
if (isLocalAttachment(candidate.local)) {
return [{ local: candidate.local, kind: candidate.local.kind, name: candidate.local.name }];
}
if (typeof candidate.dataUrl !== "string" || !candidate.dataUrl.startsWith("data:")) {
return [];
}
const kind = candidate.kind === "file" || candidate.kind === "image"
const kind = candidate.kind === "file" || candidate.kind === "image" || candidate.kind === "video"
? candidate.kind
: candidate.dataUrl.startsWith("data:image/")
? "image"
@@ -721,10 +727,11 @@ if (typeof window !== "undefined") {
}
function readyImagesToQueuedImages(
images: Array<AttachedImage & { dataUrl: string }>,
images: AttachedImage[],
): QueuedPromptImage[] {
return images.map((img) => ({
dataUrl: img.dataUrl,
local: img.local,
kind: img.kind,
name: img.file.name,
}));
@@ -732,17 +739,20 @@ function readyImagesToQueuedImages(
function queuedImagesToSendImages(images?: QueuedPromptImage[]): SendAttachment[] | undefined {
if (!images?.length) return undefined;
return images.map((img) => ({
media: {
data_url: img.dataUrl,
...(img.name ? { name: img.name } : {}),
},
preview: {
kind: img.kind ?? (img.dataUrl.startsWith("data:image/") ? "image" : "file"),
url: img.dataUrl,
...(img.name ? { name: img.name } : {}),
},
}));
return images.flatMap((img): SendAttachment[] => {
if (img.local) return [{
media: { path: img.local.path, name: img.local.name },
preview: { kind: img.local.kind, url: img.local.url, name: img.local.name },
}];
if (!img.dataUrl) return [];
return [{
media: { data_url: img.dataUrl, ...(img.name ? { name: img.name } : {}) },
preview: {
kind: img.kind ?? (img.dataUrl.startsWith("data:image/") ? "image" : img.dataUrl.startsWith("data:video/") ? "video" : "file"),
url: img.dataUrl, ...(img.name ? { name: img.name } : {}),
},
}];
});
}
function queuedPromptLabel(prompt: QueuedPrompt): string {
@@ -1096,6 +1106,7 @@ export function ThreadComposer({
onStop,
surfaceRef,
onTranscribeAudio,
onInspectAttachment,
goalState,
workspaceScope = null,
workspaceControlsHidden = false,
@@ -1134,6 +1145,14 @@ export function ThreadComposer({
} | null>(null);
const [inlineError, setInlineError] = useState<string | null>(null);
const [sendPending, setSendPending] = useState(false);
const [pathInspection, setPathInspection] = useState<{
generation: number; scope: string; range: PastedPathRange; attachment?: LocalAttachment;
} | null>(null);
const pathCheckGeneration = useRef(0);
const pathCheckScope = useRef("");
const scopeIdentity = `${workspaceScope?.project_path ?? ""}:${workspaceScope?.access_mode ?? ""}`;
pathCheckScope.current = scopeIdentity;
useEffect(() => () => { pathCheckGeneration.current += 1; }, []);
const [modelSetupAttentionRequest, setModelSetupAttentionRequest] = useState(0);
const queuedPromptStorageKey = queuedPromptsStorageKey(pendingQueueKey);
const queuedPromptStore = useMemo(() => queuedPromptStoreFor(queuedPromptStorageKey), [queuedPromptStorageKey]);
@@ -1223,35 +1242,47 @@ export function ThreadComposer({
const maxAttachments = ingressLimits?.attachments.max_count
?? MAX_ATTACHMENTS_PER_MESSAGE;
const maxFileBytes = ingressLimits?.attachments.max_file_bytes ?? MAX_ATTACHMENT_BYTES;
const maxTextBytes = ingressLimits?.message.max_text_bytes ?? 64 * 1024;
const { images, enqueue, remove, clear, restoreReadyImages, encoding, full } =
const { images, enqueue, addLocal, remove, clear, restoreReadyImages, encoding: encodingFiles, full } =
useAttachedImages({ ingressLimits });
const encoding = encodingFiles || pathInspection !== null;
const restoredDraftAttachments = useRef(false);
const [draftAttachmentsReady, setDraftAttachmentsReady] = useState(!initialDraft?.files.length);
const [draftAttachmentsReady, setDraftAttachmentsReady] = useState(!initialDraft?.attachments.length);
useLayoutEffect(() => {
if (restoredDraftAttachments.current) return;
restoredDraftAttachments.current = true;
if (initialDraft?.files.length) enqueue(initialDraft.files, { restoringDraft: true });
for (const attachment of initialDraft?.attachments ?? []) {
if (attachment instanceof File) enqueue([attachment], { restoringDraft: true });
else addLocal(attachment, { restoringDraft: true });
}
setDraftAttachmentsReady(true);
}, [enqueue, initialDraft]);
}, [enqueue, addLocal, initialDraft]);
const formatRejection = useCallback(
(reason: AttachmentError): string => {
(reason: Exclude<AttachmentError, "too_large">): string => {
const key = `thread.composer.imageRejected.${reason}`;
const fallback = reason === "too_many_attachments"
const fallback = reason === "too_many_videos"
? "Max 1 video per message"
: reason === "too_many_attachments"
? `Max ${maxAttachments} attachments per message`
: reason === "empty_file"
? "Empty files cannot be attached"
: reason === "total_too_large"
? "Attachments are too large together — remove some or use smaller files"
: reason === "too_large"
? "File is too large"
: "Unsupported file type";
: "Unsupported file type";
return t(key, { max: maxAttachments, defaultValue: fallback });
},
[maxAttachments, t],
);
const formatUploadTooLarge = useCallback(
(size: number, maximum: number) => t("thread.composer.imageRejected.too_large", {
size: formatBytes(size), max: formatBytes(maximum),
}),
[t],
);
const textTooLargeMessage = useCallback(
() => t("thread.composer.textTooLarge", {
max: formatBytes(maxTextBytes),
@@ -1266,17 +1297,20 @@ export function ThreadComposer({
secondEnterPromptIdRef.current = null;
const { rejected } = enqueue(files);
if (rejected.length > 0) {
setInlineError(formatRejection(rejected[0].reason));
const { reason, file } = rejected[0];
setInlineError(reason === "too_large"
? formatUploadTooLarge(file.size, acceptedAttachmentKind(file) === "video" ? MAX_VIDEO_BYTES : maxFileBytes)
: formatRejection(reason));
} else {
setInlineError(null);
}
},
[enqueue, formatRejection, interactionDisabled],
[enqueue, formatRejection, formatUploadTooLarge, interactionDisabled, maxFileBytes],
);
const {
isDragging,
onPaste,
onPaste: onAttachmentPaste,
onDragEnter,
onDragOver,
onDragLeave,
@@ -1306,8 +1340,8 @@ export function ThreadComposer({
const normalizedQuotedContext = quotedContext?.trim() || null;
const readyImages = useMemo(
() => images.filter((img): img is AttachedImage & { dataUrl: string } =>
img.status === "ready" && typeof img.dataUrl === "string",
() => images.filter((img) =>
img.status === "ready" && (typeof img.dataUrl === "string" || !!img.local),
),
[images],
);
@@ -1531,6 +1565,49 @@ export function ThreadComposer({
resetKey: pendingQueueKey,
});
const { rawSelection, replace: replaceMentionInput } = mentionInput;
const onPaste = useCallback((event: React.ClipboardEvent<HTMLTextAreaElement>) => {
onAttachmentPaste(event);
if (event.defaultPrevented || interactionDisabled || !onInspectAttachment) return;
const raw = event.clipboardData.getData("text/plain");
const path = pastedFilePath(raw);
if (!path) return;
event.preventDefault();
const { start, end } = rawSelection();
const pasted = value.slice(0, start) + raw + value.slice(end);
const generation = ++pathCheckGeneration.current;
replaceMentionInput(pasted, start + raw.length);
setPathInspection({ generation, scope: scopeIdentity, range: new PastedPathRange(pasted, start, start + raw.length) });
void onInspectAttachment(path).then((attachment) => {
if (generation !== pathCheckGeneration.current) return;
setPathInspection((current) => current?.generation === generation ? { ...current, attachment } : current);
}).catch((error: unknown) => {
if (generation !== pathCheckGeneration.current || pathCheckScope.current !== scopeIdentity) return;
setInlineError(error instanceof Error ? error.message : t("message.attachmentUnavailable"));
setPathInspection(null);
});
}, [interactionDisabled, onAttachmentPaste, onInspectAttachment, rawSelection, replaceMentionInput, scopeIdentity, t, value]);
useLayoutEffect(() => {
if (!pathInspection) return;
if (pathInspection.scope !== scopeIdentity || !pathInspection.range.update(value)) {
pathCheckGeneration.current += 1;
setPathInspection(null);
return;
}
// Let the native IME commit before removing the confirmed path from its text.
if (!pathInspection.attachment || mentionInput.isComposing) return;
const edited = pathInspection.range.replace("", rawSelection().start);
if (edited) {
const rejection = addLocal(pathInspection.attachment);
if (rejection) setInlineError(formatRejection(rejection));
else {
replaceMentionInput(edited.value, edited.cursor, { preserveFocus: true });
setInlineError(null);
}
}
setPathInspection(null);
}, [addLocal, formatRejection, mentionInput.isComposing, pathInspection, rawSelection, replaceMentionInput, scopeIdentity, value]);
const draftText = composerMentionText(mentionInput.segments).raw;
const sessionDragInsertion = sessionDragPreview
? mentionInsertion(
@@ -1571,7 +1648,9 @@ export function ThreadComposer({
}
draftStore.set(draftKey, {
text: draftText,
files: images.map((image) => image.file),
attachments: images.flatMap((image): ComposerDraft["attachments"] => (
image.local ? [image.local] : image.file instanceof File ? [image.file] : []
)),
sessionMentions: activeSessionMentions,
quotedContext,
}, persistDraft);
@@ -2017,19 +2096,22 @@ export function ThreadComposer({
return textTooLargeMessage();
}
const attachments = prompt.images ?? [];
if (attachments.length > maxAttachments) return formatRejection("too_many_attachments");
const sizes = attachments.map(queuedAttachmentBytes);
if (sizes.some((size) => size > (ingressLimits?.attachments.max_file_bytes ?? MAX_ATTACHMENT_BYTES))) {
return formatRejection("too_large");
const videos = attachments.filter((item) => item.kind === "video").length;
if (videos > MAX_VIDEOS_PER_MESSAGE) return formatRejection("too_many_videos");
if (attachments.length - videos > maxAttachments) return formatRejection("too_many_attachments");
const oversized = attachments.find((item) => queuedUploadBytes(item) > (item.kind === "video" ? MAX_VIDEO_BYTES : maxFileBytes));
if (oversized) {
return formatUploadTooLarge(queuedUploadBytes(oversized), oversized.kind === "video" ? MAX_VIDEO_BYTES : maxFileBytes);
}
if (sizes.reduce((sum, size) => sum + size, 0) > (ingressLimits?.attachments.max_total_bytes ?? MAX_TOTAL_ATTACHMENT_BYTES)) {
const total = attachments.reduce((sum, item) => sum + (item.kind === "video" ? 0 : queuedUploadBytes(item)), 0);
if (total > (ingressLimits?.attachments.max_total_bytes ?? MAX_TOTAL_ATTACHMENT_BYTES)) {
return formatRejection("total_too_large");
}
if ((prompt.sessionMentions?.length ?? 0) > SESSION_MENTIONS_LIMIT) {
return t("thread.composer.queued.tooManyMentions", { max: SESSION_MENTIONS_LIMIT });
}
return null;
}, [formatRejection, ingressLimits, maxAttachments, maxTextBytes, t, textTooLargeMessage]);
}, [formatRejection, formatUploadTooLarge, ingressLimits, maxAttachments, maxFileBytes, maxTextBytes, t, textTooLargeMessage]);
const collectGuidancePrompt = useCallback((): QueuedPrompt => {
queuedPromptCounterRef.current += 1;
@@ -2146,16 +2228,7 @@ export function ThreadComposer({
}
// Keep self-contained local previews across drafts and optimistic bubbles.
// The client decodes these to HTTP binary; WS messages contain only refs.
const payload: SendAttachment[] | undefined =
readyImages.length > 0
? readyImages.map((img) => ({
media: {
data_url: img.dataUrl,
name: img.file.name,
},
preview: { kind: img.kind, url: img.dataUrl, name: img.file.name },
}))
: undefined;
const payload = queuedImagesToSendImages(readyImagesToQueuedImages(readyImages));
const attachedCliApps = activeCliMentionApps.map(cliAppMentionPayload);
const attachedMcpPresets = activeMcpPresetMentions.map(mcpPresetMentionPayload);
const options: SendOptions | undefined =
@@ -2627,7 +2700,9 @@ export function ThreadComposer({
current: formatBytes(current),
})
}
formatError={formatRejection}
formatError={(reason) => reason === "too_large"
? formatUploadTooLarge(img.file.size, img.kind === "video" ? MAX_VIDEO_BYTES : maxFileBytes)
: formatRejection(reason)}
onRemove={() => removeChip(img.id)}
onKeyDown={onChipKey(img.id)}
registerRef={(el) => {
@@ -3393,6 +3468,8 @@ function AttachmentChip({
<div className="flex h-full w-full items-center justify-center">
{image.kind === "image" ? (
<ImageIcon className="h-4 w-4 text-muted-foreground" aria-hidden />
) : image.kind === "video" ? (
<Video className="h-4 w-4 text-muted-foreground" aria-hidden />
) : (
<FileText className="h-4 w-4 text-muted-foreground" aria-hidden />
)}
+43 -7
View File
@@ -15,7 +15,7 @@ import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
import { RecoveryNotice } from "@/components/thread/RecoveryNotice";
import { SubagentTasksProvider } from "@/components/thread/SubagentTasks";
import { SessionInfoPopover } from "@/components/thread/SessionInfoPopover";
import type { ComposerDraftStore } from "@/lib/composer-draft";
import type { ComposerDraft, ComposerDraftStore } from "@/lib/composer-draft";
import { ThreadComposer } from "@/components/thread/ThreadComposer";
import type {
ComposerContextUsage,
@@ -54,6 +54,7 @@ import {
isMcpPresetsPayload,
} from "@/lib/mcp-preset-events";
import type { StreamError } from "@/lib/nanobot-client";
import { isLocalAttachment } from "../../../../packages/client-events/attachments";
import type {
ChatSummary,
FilePreviewPayload,
@@ -560,7 +561,8 @@ export function ThreadShell({
const filePreviewWidthRef = useRef(FILE_PREVIEW_DEFAULT_WIDTH);
const filePreviewCloseTimerRef = useRef<number | null>(null);
const filePreviewResizeCleanupRef = useRef<(() => void) | null>(null);
const pendingFirstRef = useRef<PendingFirstMessage | null>(null);
const pendingFirstRef = useRef<(PendingFirstMessage & { draft?: ComposerDraft; draftKey: string }) | null>(null);
const [restoredFirstDraft, setRestoredFirstDraft] = useState<{ chatId: string; revision: number; error: string } | null>(null);
const [pendingFirstTargetChatId, setPendingFirstTargetChatId] = useState<string | null>(null);
const consumedPendingFirstMessageIdRef = useRef<string | null>(null);
const viewportRef = useRef<ThreadViewportHandle | null>(null);
@@ -971,10 +973,27 @@ export function ThreadShell({
setSubmittedViewportTurnId(submitted.turnId);
}
if (submitted?.delivery) {
void submitted.delivery.then(() => pending.finish?.(true), () => pending.finish?.(false));
void submitted.delivery.then(() => pending.finish?.(true), (error: unknown) => {
// Topic creation already unmounted the landing composer. A rejected
// local reference must hand its draft to that topic, not strand it on /new.
if (pending.draft && pending.images?.some((image) => image.media.path !== undefined)) {
const targetKey = `websocket:${chatId}`;
const current = draftStore?.get(targetKey, !temporary);
if (!current?.text && !current?.attachments.length
&& !current?.sessionMentions.length && !current?.quotedContext) {
draftStore?.set(targetKey, pending.draft, !temporary);
if (draftStore?.get(pending.draftKey) === pending.draft) draftStore.delete(pending.draftKey);
setRestoredFirstDraft((previous) => ({
chatId, revision: (previous?.revision ?? 0) + 1,
error: error instanceof Error ? error.message : String(error),
}));
}
}
pending.finish?.(false);
});
} else pending.finish?.(submitted !== null);
setBooting(false);
}, [chatId, pendingFirstTargetChatId, send]);
}, [chatId, draftStore, pendingFirstTargetChatId, send, temporary]);
useEffect(() => {
if (
@@ -1022,7 +1041,10 @@ export function ThreadShell({
setBooting(true);
let finish!: (accepted: boolean) => void;
const delivery = new Promise<boolean>((resolve) => { finish = resolve; });
pendingFirstRef.current = { content, images, options: withWorkspaceScope(options), finish };
pendingFirstRef.current = {
content, images, options: withWorkspaceScope(options), finish,
draftKey, draft: draftStore?.get(draftKey, persistDraft),
};
setPendingFirstTargetChatId(null);
const newId = await onCreateChat?.(workspaceScope, content, localModelPreset);
if (!newId) {
@@ -1037,11 +1059,20 @@ export function ThreadShell({
setPendingFirstTargetChatId(newId);
return delivery;
},
[booting, client, localModelPreset, onCreateChat, withWorkspaceScope, workspaceScope],
[booting, client, draftKey, draftStore, localModelPreset, onCreateChat, persistDraft, withWorkspaceScope, workspaceScope],
);
const inspectAttachment = useCallback(async (path: string) => {
const result = await client.requestMutation("attachment.inspect", {
chat_id: chatId, path, ...(workspaceScope ? { workspace_scope: workspaceScope } : {}),
});
if (!isLocalAttachment(result)) throw new Error("Invalid attachment metadata");
return result;
}, [chatId, client, workspaceScope]);
const handleThreadSend = useCallback(
(content: string, images?: SendAttachment[], options?: SendOptions) => {
setRestoredFirstDraft((current) => current?.chatId === chatId ? { ...current, error: "" } : current);
const submitted = send(content, images, withWorkspaceScope(options));
if (
chatId
@@ -1253,9 +1284,12 @@ export function ThreadShell({
onOpenSettings={onOpenModelSettings}
/>
) : null}
{restoredFirstDraft?.chatId === chatId && restoredFirstDraft.error ? (
<p role="alert" className="px-3 text-sm text-destructive">{restoredFirstDraft.error}</p>
) : null}
{session ? (
<ThreadComposer
key={draftKey}
key={`${draftKey}:${restoredFirstDraft?.chatId === chatId ? restoredFirstDraft.revision : 0}`}
draftKey={draftKey}
draftStore={draftStore}
persistDraft={persistDraft}
@@ -1291,6 +1325,7 @@ export function ThreadShell({
sessions={mentionSessions}
skills={skills}
onStop={stop}
onInspectAttachment={inspectAttachment}
onTranscribeAudio={transcribeAudio}
goalState={currentGoalState}
onFavoriteWorkspaceProject={favoriteWorkspaceProject}
@@ -1347,6 +1382,7 @@ export function ThreadShell({
sessions={mentionSessions}
skills={skills}
surfaceRef={composerSurfaceRef}
onInspectAttachment={inspectAttachment}
onTranscribeAudio={transcribeAudio}
goalState={currentGoalState}
onFavoriteWorkspaceProject={favoriteWorkspaceProject}
+74 -34
View File
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useRef, useState } from "react";
import type { LocalAttachment } from "../../../packages/client-events/attachments";
import { encodeImage, type EncodeFailure } from "@/lib/imageEncode";
import type { WebUIIngressLimits } from "@/lib/types";
@@ -10,12 +11,13 @@ import type { WebUIIngressLimits } from "@/lib/types";
* - ``error`` — validation / decode failure; chip shows inline error
*/
type AttachmentStatus = "encoding" | "ready" | "error";
export type AttachmentKind = "image" | "file";
export type AttachmentKind = "image" | "video" | "file";
interface AttachedAttachment {
id: string;
kind: AttachmentKind;
file: File;
file: Pick<File, "name" | "size" | "type">;
local?: LocalAttachment;
/** Optimistic ``blob:`` preview URL; revoked on ``remove`` / ``clear`` /
* unmount. */
previewUrl?: string;
@@ -32,8 +34,9 @@ interface AttachedAttachment {
export type AttachedImage = AttachedAttachment;
interface RestoredReadyAttachment {
dataUrl: string;
export interface RestoredReadyAttachment {
dataUrl?: string;
local?: LocalAttachment;
name?: string;
kind?: AttachmentKind;
}
@@ -46,16 +49,24 @@ export type RestoredReadyImage = RestoredReadyAttachment;
export type AttachmentError =
| "unsupported_type" // server whitelist excludes this MIME
| "empty_file" // attachments must contain bytes
| "too_many_attachments" // per-message cap (4) reached before enqueue
| "too_many_attachments" // non-video per-message cap reached before enqueue
| "too_many_videos" // video slot is already occupied
| "total_too_large" // decoded attachments exceed the business-policy total
| "magic_mismatch" // extension lies about the real content
| "decode_failed" // Worker couldn't decode / re-encode
| "too_large" // even after normalization we exceed the budget
| "io"; // file read failed at the browser layer
type AttachmentCountError = Extract<AttachmentError, "too_many_attachments" | "too_many_videos">;
export const MAX_ATTACHMENTS_PER_MESSAGE = 4;
export const MAX_ATTACHMENT_BYTES = 6 * 1024 * 1024;
export const MAX_TOTAL_ATTACHMENT_BYTES = 24 * 1024 * 1024;
export const MAX_VIDEO_BYTES = 20 * 1024 * 1024;
export const MAX_VIDEOS_PER_MESSAGE = 1;
const VIDEO_MIME_BY_EXTENSION = new Map([
[".mp4", "video/mp4"], [".webm", "video/webm"], [".mov", "video/quicktime"],
]);
/** MIME whitelist — mirrors the server's and the ``<input accept>`` attr. */
const ACCEPTED_IMAGE_MIMES: ReadonlySet<string> = new Set([
@@ -91,6 +102,8 @@ export const ACCEPT_ATTR = [
...ACCEPTED_IMAGE_MIMES,
...ACCEPTED_DOCUMENT_MIMES,
...DOCUMENT_MIME_BY_EXTENSION.keys(),
...VIDEO_MIME_BY_EXTENSION.values(),
...VIDEO_MIME_BY_EXTENSION.keys(),
].join(",");
function extensionOf(name: string): string {
@@ -99,7 +112,8 @@ function extensionOf(name: string): string {
}
function mimeForFile(file: File): string {
const byName = DOCUMENT_MIME_BY_EXTENSION.get(extensionOf(file.name));
const byName = DOCUMENT_MIME_BY_EXTENSION.get(extensionOf(file.name))
?? VIDEO_MIME_BY_EXTENSION.get(extensionOf(file.name));
if (byName) return byName;
if (!file.type || file.type === "application/octet-stream") {
return "application/octet-stream";
@@ -114,6 +128,8 @@ function positiveLimit(value: number | null | undefined, fallback: number): numb
}
export function acceptedAttachmentKind(file: File): AttachmentKind | null {
if (VIDEO_MIME_BY_EXTENSION.has(extensionOf(file.name))
|| [...VIDEO_MIME_BY_EXTENSION.values()].includes(file.type)) return "video";
if (DOCUMENT_MIME_BY_EXTENSION.has(extensionOf(file.name))) return "file";
if (ACCEPTED_IMAGE_MIMES.has(file.type)) return "image";
const mime = mimeForFile(file);
@@ -127,7 +143,8 @@ function dataUrlMime(dataUrl: string): string {
}
function kindFromDataUrl(dataUrl: string): AttachmentKind {
return dataUrlMime(dataUrl).startsWith("image/") ? "image" : "file";
const mime = dataUrlMime(dataUrl);
return mime.startsWith("image/") ? "image" : mime.startsWith("video/") ? "video" : "file";
}
function dataUrlToFile(dataUrl: string, name?: string): File {
@@ -212,6 +229,7 @@ export interface UseAttachedImagesApi {
enqueue: (files: Iterable<File>, options?: { restoringDraft: boolean }) => {
rejected: Array<{ file: File; reason: AttachmentError }>;
};
addLocal: (attachment: LocalAttachment, options?: { restoringDraft: boolean }) => AttachmentCountError | null;
remove: (id: string) => { nextFocusId: string | null };
/** Revoke every staged blob URL and drop all attachments. Called after a
* successful submit — the optimistic bubble holds onto an independent
@@ -272,13 +290,14 @@ export function useAttachedImages({
const enqueue = useCallback(
(files: Iterable<File>, { restoringDraft = false } = {}) => {
const rejected: Array<{ file: File; reason: AttachmentError }> = [];
const toAdd: AttachedAttachment[] = [];
let slot = maxAttachments - imagesRef.current.length;
const toAdd: Array<AttachedAttachment & { file: File }> = [];
let slot = maxAttachments - imagesRef.current.filter((item) => item.kind !== "video").length;
let videoSlot = MAX_VIDEOS_PER_MESSAGE - imagesRef.current.filter((item) => item.kind === "video").length;
let projectedDecodedBytes = imagesRef.current.reduce(
(total, image) => total + (
(total, image) => total + (image.local || image.kind === "video" ? 0 : (
image.encodedBytes
?? (image.kind === "image" ? Math.min(image.file.size, maxFileBytes) : image.file.size)
),
)),
0,
);
@@ -292,20 +311,21 @@ export function useAttachedImages({
rejected.push({ file, reason: "empty_file" });
continue;
}
if (!restoringDraft && kind === "file" && file.size > maxFileBytes) {
if (!restoringDraft && kind !== "image" && file.size > (kind === "video" ? MAX_VIDEO_BYTES : maxFileBytes)) {
rejected.push({ file, reason: "too_large" });
continue;
}
if (!restoringDraft && slot <= 0) {
rejected.push({ file, reason: "too_many_attachments" });
if (!restoringDraft && (kind === "video" ? videoSlot : slot) <= 0) {
rejected.push({ file, reason: kind === "video" ? "too_many_videos" : "too_many_attachments" });
continue;
}
const nextDecodedBytes = kind === "image" ? Math.min(file.size, maxFileBytes) : file.size;
const nextDecodedBytes = kind === "video" ? 0 : kind === "image" ? Math.min(file.size, maxFileBytes) : file.size;
if (!restoringDraft && projectedDecodedBytes + nextDecodedBytes > maxTotalBytes) {
rejected.push({ file, reason: "total_too_large" });
continue;
}
slot -= 1;
if (kind === "video") videoSlot -= 1;
else slot -= 1;
projectedDecodedBytes += nextDecodedBytes;
toAdd.push({
id: uuid(),
@@ -325,7 +345,7 @@ export function useAttachedImages({
queueMicrotask(() => {
const work = entry.kind === "image"
? encodeImage(entry.file)
: encodeFile(entry.file, maxFileBytes);
: encodeFile(entry.file, entry.kind === "video" ? MAX_VIDEO_BYTES : maxFileBytes);
work.then(
(result) => {
if (result.ok) {
@@ -359,6 +379,22 @@ export function useAttachedImages({
[maxAttachments, maxFileBytes, maxTotalBytes, setEntry],
);
const addLocal = useCallback((local: LocalAttachment, { restoringDraft = false } = {}): AttachmentCountError | null => {
const current = imagesRef.current;
const videos = current.filter((item) => item.kind === "video").length;
if (!restoringDraft && (local.kind === "video" ? videos >= MAX_VIDEOS_PER_MESSAGE : current.length - videos >= maxAttachments)) {
return local.kind === "video" ? "too_many_videos" : "too_many_attachments";
}
const next: AttachedAttachment[] = [...current, {
id: uuid(), kind: local.kind, local, status: "ready", encodedBytes: local.size,
file: { name: local.name, size: local.size, type: local.mime },
...(local.kind === "image" ? { previewUrl: local.url } : {}),
}];
imagesRef.current = next;
setImages(next);
return null;
}, [maxAttachments]);
const remove = useCallback((id: string) => {
let nextFocusId: string | null = null;
setImages((prev) => {
@@ -399,21 +435,24 @@ export function useAttachedImages({
}, []);
const restoreReadyImages = useCallback((restored: RestoredReadyAttachment[]) => {
const toRestore = restored
.filter((img) => acceptedAttachmentKind(dataUrlToFile(img.dataUrl, img.name)))
.map((img): AttachedAttachment => {
const file = dataUrlToFile(img.dataUrl, img.name);
const kind = img.kind ?? kindFromDataUrl(img.dataUrl);
return {
id: uuid(),
kind,
file,
...(kind === "image" ? { previewUrl: img.dataUrl } : {}),
status: "ready",
dataUrl: img.dataUrl,
encodedBytes: file.size,
};
});
const toRestore = restored.flatMap((img): AttachedAttachment[] => {
if (img.local) {
const local = img.local;
return [{
id: uuid(), kind: local.kind, local, status: "ready", encodedBytes: local.size,
file: { name: local.name, size: local.size, type: local.mime },
...(local.kind === "image" ? { previewUrl: local.url } : {}),
}];
}
if (!img.dataUrl) return [];
const file = dataUrlToFile(img.dataUrl, img.name);
if (!acceptedAttachmentKind(file)) return [];
const kind = img.kind ?? kindFromDataUrl(img.dataUrl);
return [{
id: uuid(), kind, file, status: "ready", dataUrl: img.dataUrl, encodedBytes: file.size,
...(kind === "image" ? { previewUrl: img.dataUrl } : {}),
}];
});
setImages((prev) => {
for (const img of prev) {
if (img.previewUrl) {
@@ -447,7 +486,8 @@ export function useAttachedImages({
}, []);
const encoding = images.some((img) => img.status === "encoding");
const full = images.length >= maxAttachments;
const videos = images.filter((image) => image.kind === "video").length;
const full = images.length - videos >= maxAttachments && videos >= MAX_VIDEOS_PER_MESSAGE;
return { images, enqueue, remove, clear, restoreReadyImages, encoding, full };
return { images, enqueue, addLocal, remove, clear, restoreReadyImages, encoding, full };
}
+13 -9
View File
@@ -19,7 +19,7 @@ export function useComposerMentionInput({
}) {
const text = useMemo(() => composerMentionText(segments), [segments]);
const textRef = useRef(text);
const pendingSelection = useRef<{ start: number; end: number } | null>(null);
const pendingSelection = useRef<{ start: number; end: number; preserveFocus?: boolean } | null>(null);
const history = useRef<{ undo: Snapshot[]; redo: Snapshot[] }>({ undo: [], redo: [] });
const lastEdit = useRef({ type: "", at: 0, cursor: -1 });
const composing = useRef(false);
@@ -42,10 +42,10 @@ export function useComposerMentionInput({
return selection;
}, [inputRef]);
const selectRaw = useCallback((start: number, end = start) => {
const selectRaw = useCallback((start: number, end = start, preserveFocus = false) => {
const el = inputRef.current;
// Focus first: removing a queued prompt's edit button can reset a blurred selection.
el?.focus();
// Focus first for user actions; passive attachment confirmation keeps the active control.
if (!preserveFocus) el?.focus();
el?.setSelectionRange(
mentionTextOffset(textRef.current, start, "toDisplay", "start"),
mentionTextOffset(textRef.current, end, "toDisplay", "end"),
@@ -74,13 +74,13 @@ export function useComposerMentionInput({
}
textRef.current = text;
if (!composing.current && pendingSelection.current) {
const { start, end } = pendingSelection.current;
selectRaw(start, end);
const { start, end, preserveFocus } = pendingSelection.current;
selectRaw(start, end, preserveFocus);
pendingSelection.current = null;
}
});
const apply = useCallback((value: string, cursor: number, type = "", selection = rawSelection()) => {
const apply = useCallback((value: string, cursor: number, type = "", selection = rawSelection(), preserveFocus = false) => {
const previous = textRef.current;
if (value !== previous.raw) {
const now = Date.now();
@@ -93,10 +93,14 @@ export function useComposerMentionInput({
history.current.redo = [];
lastEdit.current = { type, at: now, cursor };
}
pendingSelection.current = value === previous.raw ? null : { start: cursor, end: cursor };
pendingSelection.current = value === previous.raw ? null : { start: cursor, end: cursor, preserveFocus };
onEdit(value, cursor);
}, [onEdit, rawSelection]);
const replace = useCallback((value: string, cursor: number, { preserveFocus = false } = {}) => {
apply(value, cursor, "", undefined, preserveFocus);
}, [apply]);
const beforeSelection = useRef<{ start: number; end: number; raw: { start: number; end: number } } | null>(null);
const captureSelection = useCallback(() => {
const el = inputRef.current;
@@ -170,7 +174,7 @@ export function useComposerMentionInput({
),
isComposing: compositionValue !== null,
rawSelection,
replace: apply,
replace,
onChange,
onKeyDown,
onCopy: (event: ClipboardEvent<HTMLTextAreaElement>) => copy(event, false),
+20 -3
View File
@@ -688,7 +688,16 @@ export function useNanobotStream(
if (turnId) {
setMessages((prev) => transitionTurnDelivery(prev, turnId, "accepted"));
}
if (ev.event === "message_accepted") return;
if (ev.event === "message_accepted") {
if (ev.media_urls?.length) {
setMessages((prev) => prev.map((message) => (
message.role === "user" && message.turnId === ev.turn_id
? { ...message, media: ev.media_urls }
: message
)));
}
return;
}
if (ev.event === "user_message") {
if (ev.provenance?.session_message) {
flushPendingStreamEvents();
@@ -705,7 +714,11 @@ export function useNanobotStream(
setMessages((prev) => {
if (ev.turn_id && prev.some((message) => (
message.role === "user" && message.turnId === ev.turn_id
))) return prev;
))) return ev.media_urls?.length ? prev.map((message) => (
message.role === "user" && message.turnId === ev.turn_id
? { ...message, media: ev.media_urls }
: message
)) : prev;
const row: UIMessage = {
id: crypto.randomUUID(),
role: "user",
@@ -1021,7 +1034,11 @@ export function useNanobotStream(
const turnId = crypto.randomUUID();
const userMessageId = crypto.randomUUID();
if (sideChannel) transcriptRef.current.sideChannelTurnIds.add(turnId);
const previews = hasAttachments ? images!.map((i) => i.preview) : undefined;
const previews = hasAttachments ? images!.map(({ preview }) => (
preview.kind === "video" && preview.url?.startsWith("data:")
? { kind: preview.kind, name: preview.name }
: preview
)) : undefined;
setMessages((prev) => {
let projection = { ...transcriptRef.current.projection, messages: prev };
if ((!sideChannel && !continueActiveTurn) || finalizeActiveTurn) {
+2 -1
View File
@@ -2307,10 +2307,11 @@
"unsupported_type": "Unsupported file type",
"empty_file": "Empty files cannot be attached",
"too_many_attachments": "Max {{max}} attachments per message",
"too_many_videos": "Max 1 video per message",
"too_many_images": "Max {{max}} images per message",
"magic_mismatch": "File doesn't look like a real image",
"decode_failed": "Couldn't decode this image",
"too_large": "File is too large — try a smaller one",
"too_large": "File is too large to upload ({{size}}; maximum {{max}})",
"total_too_large": "Attachments are too large together — remove some or use smaller files",
"io": "Couldn't read this file"
},
+2 -1
View File
@@ -2087,10 +2087,11 @@
"unsupported_type": "Tipo de archivo no compatible",
"empty_file": "No se pueden adjuntar archivos vacíos",
"too_many_attachments": "Máximo {{max}} adjuntos por mensaje",
"too_many_videos": "Máximo 1 vídeo por mensaje",
"too_many_images": "Máximo {{max}} imágenes por mensaje",
"magic_mismatch": "El archivo no parece una imagen real",
"decode_failed": "No se pudo decodificar esta imagen",
"too_large": "Archivo demasiado grande — prueba uno más pequeño",
"too_large": "El archivo ({{size}}) supera el límite de carga de {{max}}",
"total_too_large": "Los archivos adjuntos son demasiado grandes en conjunto; elimina algunos o usa archivos más pequeños",
"io": "No se pudo leer este archivo"
},
+2 -1
View File
@@ -2086,10 +2086,11 @@
"unsupported_type": "Type de fichier non pris en charge",
"empty_file": "Impossible de joindre des fichiers vides",
"too_many_attachments": "Maximum {{max}} pièces jointes par message",
"too_many_videos": "Une seule vidéo par message",
"too_many_images": "Maximum {{max}} images par message",
"magic_mismatch": "Ce fichier n'est pas une image",
"decode_failed": "Impossible de décoder cette image",
"too_large": "Fichier trop volumineux — essayez-en un plus petit",
"too_large": "Le fichier ({{size}}) dépasse la limite d’envoi de {{max}}",
"total_too_large": "Les pièces jointes sont trop volumineuses ensemble — supprimez-en ou utilisez des fichiers plus petits",
"io": "Impossible de lire ce fichier"
},
+2 -1
View File
@@ -2086,10 +2086,11 @@
"unsupported_type": "Tipe file tidak didukung",
"empty_file": "File kosong tidak dapat dilampirkan",
"too_many_attachments": "Maksimal {{max}} lampiran per pesan",
"too_many_videos": "Maksimal 1 video per pesan",
"too_many_images": "Maksimal {{max}} gambar per pesan",
"magic_mismatch": "File ini tampaknya bukan gambar asli",
"decode_failed": "Tidak dapat mendekode gambar ini",
"too_large": "File terlalu besar — coba yang lebih kecil",
"too_large": "Ukuran file {{size}} melebihi batas unggahan {{max}}",
"total_too_large": "Total lampiran terlalu besar — hapus beberapa atau gunakan file yang lebih kecil",
"io": "Tidak dapat membaca file ini"
},
+2 -1
View File
@@ -2086,10 +2086,11 @@
"unsupported_type": "対応していないファイル形式です",
"empty_file": "空のファイルは添付できません",
"too_many_attachments": "1 メッセージにつき最大 {{max}} 件までです",
"too_many_videos": "1 メッセージにつき動画は 1 件までです",
"too_many_images": "1 メッセージにつき最大 {{max}} 枚です",
"magic_mismatch": "画像ファイルではないようです",
"decode_failed": "この画像をデコードできません",
"too_large": "ファイルが大きすぎます。小さいものを選んでください",
"too_large": "ファイルサイズ {{size}} はアップロード上限 {{max}} を超えています",
"total_too_large": "添付ファイルの合計サイズが大きすぎます。いくつか削除するか、より小さいファイルを使用してください",
"io": "このファイルを読み込めません"
},
+2 -1
View File
@@ -2086,10 +2086,11 @@
"unsupported_type": "지원하지 않는 파일 형식입니다",
"empty_file": "빈 파일은 첨부할 수 없습니다",
"too_many_attachments": "메시지당 최대 {{max}}개까지 가능합니다",
"too_many_videos": "메시지당 동영상은 최대 1개까지 가능합니다",
"too_many_images": "메시지당 최대 {{max}}장까지 가능합니다",
"magic_mismatch": "이미지 파일이 아닌 것 같습니다",
"decode_failed": "이 이미지를 디코딩할 수 없습니다",
"too_large": "파일이 너무 큽니다. 더 작은 파일을 선택해 주세요",
"too_large": "파일 크기 {{size}}가 업로드 한도 {{max}}를 초과합니다",
"total_too_large": "첨부 파일의 전체 크기가 너무 큽니다. 일부를 제거하거나 더 작은 파일을 사용해 주세요",
"io": "이 파일을 읽을 수 없습니다"
},
+2 -1
View File
@@ -2115,10 +2115,11 @@
"unsupported_type": "Tipo de arquivo não compatível",
"empty_file": "Arquivos vazios não podem ser anexados",
"too_many_attachments": "Máx. de {{max}} anexos por mensagem",
"too_many_videos": "Máx. de 1 vídeo por mensagem",
"too_many_images": "Máx. de {{max}} imagens por mensagem",
"magic_mismatch": "O arquivo não parece uma imagem real",
"decode_failed": "Não foi possível decodificar esta imagem",
"too_large": "A imagem é grande demais — tente uma menor",
"too_large": "O arquivo ({{size}}) excede o limite de upload de {{max}}",
"total_too_large": "Os anexos são grandes demais em conjunto — remova alguns ou use arquivos menores",
"io": "Não foi possível ler este arquivo"
},
+2 -1
View File
@@ -2086,10 +2086,11 @@
"unsupported_type": "Loại tệp không được hỗ trợ",
"empty_file": "Không thể đính kèm tệp trống",
"too_many_attachments": "Tối đa {{max}} tệp đính kèm mỗi tin nhắn",
"too_many_videos": "Tối đa 1 video mỗi tin nhắn",
"too_many_images": "Tối đa {{max}} ảnh mỗi tin nhắn",
"magic_mismatch": "Tệp này không phải là một ảnh thực",
"decode_failed": "Không thể giải mã ảnh này",
"too_large": "Tệp quá lớn — hãy thử tệp nhỏ hơn",
"too_large": "Tệp có dung lượng {{size}}, vượt giới hạn tải lên {{max}}",
"total_too_large": "Tổng dung lượng tệp đính kèm quá lớn — hãy xóa bớt hoặc dùng tệp nhỏ hơn",
"io": "Không thể đọc tệp này"
},
+2 -1
View File
@@ -2306,10 +2306,11 @@
"unsupported_type": "不支持的文件类型",
"empty_file": "不能附加空文件",
"too_many_attachments": "每条消息最多 {{max}} 个附件",
"too_many_videos": "每条消息最多 1 个视频",
"too_many_images": "每条消息最多 {{max}} 张图片",
"magic_mismatch": "文件看起来不像真实的图片",
"decode_failed": "无法解码这张图片",
"too_large": "文件太大,请换一个小一点的",
"too_large": "文件为 {{size}},超过上传上限 {{max}}",
"total_too_large": "附件总大小过大,请移除部分文件或使用更小的文件",
"io": "无法读取该文件"
},
+2 -1
View File
@@ -2086,10 +2086,11 @@
"unsupported_type": "不支援的檔案類型",
"empty_file": "無法附加空白檔案",
"too_many_attachments": "每則訊息最多 {{max}} 個附件",
"too_many_videos": "每則訊息最多 1 部影片",
"too_many_images": "每則訊息最多 {{max}} 張圖片",
"magic_mismatch": "檔案內容似乎不是有效的圖片",
"decode_failed": "無法解碼這張圖片",
"too_large": "檔案太大,請改用較小的檔案",
"too_large": "檔案為 {{size}},超過上傳上限 {{max}}",
"total_too_large": "附件總大小過大,請移除部分檔案或改用較小的檔案",
"io": "無法讀取這個檔案"
},
+10 -6
View File
@@ -1,9 +1,10 @@
import type { SessionMention } from "./types";
import { isLocalAttachment, type LocalAttachment } from "../../../packages/client-events/attachments";
/** Files stay in memory, including unfinished attachments. */
/** Ordered attachments retain browser Files in memory and persist local references. */
export interface ComposerDraft {
text: string;
files: File[];
attachments: Array<File | LocalAttachment>;
sessionMentions: SessionMention[];
quotedContext: string | null;
}
@@ -34,7 +35,9 @@ function readDraft(raw: string): ComposerDraft | undefined {
? { id: item.id } : {}),
}];
});
return { text: value.text, quotedContext: value.quotedContext, sessionMentions, files: [] };
const rawAttachments = Array.isArray(value.attachments) ? value.attachments : value.localAttachments;
const attachments = Array.isArray(rawAttachments) ? rawAttachments.filter(isLocalAttachment) : [];
return { text: value.text, quotedContext: value.quotedContext, sessionMentions, attachments };
}
function removeStoredDraft(key: string): void {
@@ -69,14 +72,14 @@ export class ComposerDraftStore extends Map<string, ComposerDraft> {
const unchanged = previous
&& previous.text === draft.text
&& previous.quotedContext === draft.quotedContext
&& previous.files.length === draft.files.length
&& previous.files.every((file, index) => file === draft.files[index])
&& previous.attachments.length === draft.attachments.length
&& previous.attachments.every((attachment, index) => attachment === draft.attachments[index])
&& previous.sessionMentions.length === draft.sessionMentions.length
&& previous.sessionMentions.every((mention, index) => mention === draft.sessionMentions[index]);
// Restoring a composer is not an edit. Pending sends retain this identity across mounts.
super.set(key, unchanged ? previous : draft);
if (!persist) return this;
if (!draft.text && !draft.quotedContext) {
if (!draft.text && !draft.quotedContext && !draft.attachments.some(isLocalAttachment)) {
removeStoredDraft(key);
return this;
}
@@ -85,6 +88,7 @@ export class ComposerDraftStore extends Map<string, ComposerDraft> {
text: draft.text,
quotedContext: draft.quotedContext,
sessionMentions: draft.sessionMentions,
attachments: draft.attachments.filter(isLocalAttachment),
});
if (raw.length <= MAX_STORED_CHARS) localStorage.setItem(STORAGE_PREFIX + key, raw);
else removeStoredDraft(key);
+5 -7
View File
@@ -1488,11 +1488,12 @@ export type InboundEvent =
event: "message_accepted";
chat_id: string;
turn_id: string;
media_urls?: UIMediaAttachment[];
starts_turn?: boolean;
active_turn_id?: string;
started_at?: number;
}
| {
| ({
event: "user_message";
chat_id: string;
text: string;
@@ -1506,14 +1507,14 @@ export type InboundEvent =
mcp_presets?: UIMcpPresetAttachment[];
session_mentions?: SessionMention[];
provenance?: { session_message?: UISessionMessage };
}
} & InboundTurnMetadata)
| ({
event: "message";
chat_id: string;
text: string;
reply_to?: string;
media?: string[];
media_urls?: Array<{ url: string; name?: string }>;
media_urls?: Array<{ url: string; name?: string; kind?: UIMediaKind }>;
tool_events?: ToolProgressEvent[];
/** Oversized persisted activity detail, fetched only when the trace is expanded. */
trace_detail?: UITraceDetail;
@@ -1677,10 +1678,7 @@ export type ThreadProjectionEvent = Extract<
* surface. ``name`` is advisory and is surfaced as the placeholder label when
* the session is replayed.
*/
export interface OutboundMedia {
data_url: string;
name?: string;
}
export type OutboundMedia = import("../../../packages/client-events/attachments").DraftAttachment;
export interface OutboundCliAppMention {
name: string;
+27 -6
View File
@@ -8,7 +8,7 @@ const draft: ComposerDraft = {
text: " Keep this draft\n继续编辑",
quotedContext: "Quoted answer",
sessionMentions: [{ name: "other", title: "Other topic", session_key: "websocket:other" }],
files: [new File(["attachment"], "draft.txt", { type: "text/plain" })],
attachments: [new File(["attachment"], "draft.txt", { type: "text/plain" })],
};
afterEach(() => {
@@ -21,15 +21,15 @@ describe("composer draft storage", () => {
const store = new ComposerDraftStore();
store.set(key, draft, true);
expect(store.get(key)).toBe(draft);
expect(new ComposerDraftStore().get(key, true)).toEqual({ ...draft, files: [] });
expect(new ComposerDraftStore().get(key, true)).toEqual({ ...draft, attachments: [] });
expect(new ComposerDraftStore().get("websocket:other", true)).toBeUndefined();
expect(localStorage.getItem(storageKey)).not.toContain("files");
expect(JSON.parse(localStorage.getItem(storageKey)!).attachments).toEqual([]);
});
it("keeps the identity of an unchanged restored draft but advances it for edits", () => {
const store = new ComposerDraftStore();
store.set(key, draft, true);
store.set(key, { ...draft, files: [...draft.files], sessionMentions: [...draft.sessionMentions] }, true);
store.set(key, { ...draft, attachments: [...draft.attachments], sessionMentions: [...draft.sessionMentions] }, true);
expect(store.get(key)).toBe(draft);
const edited = { ...draft, text: "edited draft" };
store.set(key, edited, true);
@@ -39,6 +39,27 @@ describe("composer draft storage", () => {
expect(store.get(key)).toBe(reverted);
});
it("keeps mixed attachment order in memory and the local subsequence after reload", () => {
const first = { path: "/project/first.png", name: "first.png", size: 8, mime: "image/png", kind: "image" as const, url: "" };
const last = { ...first, path: "/project/last.png", name: "last.png" };
const mixed = { ...draft, attachments: [first, draft.attachments[0], last] };
const store = new ComposerDraftStore();
store.set(key, mixed, true);
store.set(key, { ...mixed, attachments: [...mixed.attachments] }, true);
expect(store.get(key)).toBe(mixed);
expect(new ComposerDraftStore().get(key, true)?.attachments).toEqual([first, last]);
const reordered = { ...mixed, attachments: [last, draft.attachments[0], first] };
store.set(key, reordered, true);
expect(store.get(key)).toBe(reordered);
expect(new ComposerDraftStore().get(key, true)?.attachments).toEqual([last, first]);
});
it("reads local references already saved in v1 drafts", () => {
const local = { path: "/project/previous.png", name: "previous.png", size: 8, mime: "image/png", kind: "image", url: "" };
localStorage.setItem(storageKey, JSON.stringify({ text: "previous draft", quotedContext: null, sessionMentions: [], localAttachments: [local] }));
expect(new ComposerDraftStore().get(key, true)?.attachments).toEqual([local]);
});
it("requires explicit opt-in for both saving and restoring", () => {
const store = new ComposerDraftStore();
store.set(key, draft);
@@ -52,7 +73,7 @@ describe("composer draft storage", () => {
const store = new ComposerDraftStore();
store.set(key, draft, true);
store.set(key, { ...draft, text: "", quotedContext: null, sessionMentions: [] }, true);
expect(store.get(key)?.files).toEqual(draft.files);
expect(store.get(key)?.attachments).toEqual(draft.attachments);
expect(new ComposerDraftStore().get(key, true)).toBeUndefined();
});
@@ -82,7 +103,7 @@ describe("composer draft storage", () => {
localStorage.setItem(storageKey, JSON.stringify({
...draft, sessionMentions: [null, { name: 42 }, ...draft.sessionMentions],
}));
expect(new ComposerDraftStore().get(key, true)).toEqual({ ...draft, files: [] });
expect(new ComposerDraftStore().get(key, true)).toEqual({ ...draft, attachments: [] });
});
it("keeps editing usable when storage is unavailable and removes stale saved text", () => {
+40
View File
@@ -1049,6 +1049,23 @@ describe("MessageBubble", () => {
expect(content.querySelectorAll("li")).toHaveLength(1000);
});
it("retries a failed video locally without replacing a healthy player on history updates", () => {
const message: UIMessage = { id: "retry-video", role: "user", content: "watch", createdAt: 0,
media: [{ kind: "video", name: "clip.webm", url: "/api/media/sig/clip" }] };
const { container, rerender } = render(<MessageBubble message={message} />);
const original = container.querySelector("video")!;
fireEvent.error(original);
expect(container.querySelector("video")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
const retried = container.querySelector("video")!;
expect(retried).toHaveAttribute("src", "/api/media/sig/clip");
expect(retried).not.toBe(original);
rerender(<MessageBubble message={{ ...message, media: [...message.media!] }} />);
expect(container.querySelector("video")).toBe(retried);
fireEvent.error(retried);
expect(screen.getByRole("button", { name: "Retry" })).toBeVisible();
});
it("renders video media as an inline player", () => {
const message: UIMessage = {
id: "a1",
@@ -1076,6 +1093,29 @@ describe("MessageBubble", () => {
expect(screen.queryByText("Code")).not.toBeInTheDocument();
});
it("starts an uploaded player from its accepted URL and preserves it through hydration", () => {
const message: UIMessage = {
id: "optimistic-user", role: "user", content: "Watch this", createdAt: 1,
turnId: "video-turn", turnPhase: "user", deliveryStatus: "sending",
media: [{ kind: "video", name: "clip.webm" }],
};
const accepted: UIMessage = {
...message, deliveryStatus: "accepted",
media: [{ kind: "video", name: "clip.webm", url: "/api/media/sig/clip" }],
};
const { rerender, unmount } = render(<ThreadMessages messages={[message]} />);
expect(screen.queryByLabelText(/video attachment/i)?.tagName).not.toBe("VIDEO");
expect(screen.queryByText(/attachment unavailable/i)).not.toBeInTheDocument();
rerender(<ThreadMessages messages={[accepted]} />);
const video = screen.getByLabelText(/video attachment/i);
rerender(<ThreadMessages messages={[{ ...accepted, id: "history-user" }]} />);
expect(screen.getByLabelText(/video attachment/i)).toBe(video);
expect(video).toHaveAttribute("src", "/api/media/sig/clip");
unmount();
render(<ThreadMessages messages={[accepted]} />);
expect(screen.getByLabelText(/video attachment/i)).toHaveAttribute("src", "/api/media/sig/clip");
});
it("renders streaming reasoning as one compact activity line", () => {
const message: UIMessage = {
id: "a-reasoning-streaming",
+15 -1
View File
@@ -67,6 +67,20 @@ describe("merged waiting messages", () => {
});
});
it.each(["video", "file"] as const)("sends a restored large local %s and a browser upload without spending local bytes", (kind) => {
const local = { path: `C:\\project\\large.${kind === "video" ? "mp4" : "pdf"}`, name: "large reference", kind, size: 64 * 1024 * 1024 + 1, mime: kind === "video" ? "video/mp4" : "application/pdf", url: "/api/media/sig/local" };
window.localStorage.setItem(STORAGE_KEY, JSON.stringify([
{ id: "first", text: "read references", images: [{ local, kind }, DOCUMENT] },
]));
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" ingressLimits={limits({ max_file_bytes: 5, max_total_bytes: 5 })} />);
fireEvent.click(screen.getByRole("button", { name: "Send now" }));
expect(onSend).toHaveBeenCalledWith("read references", [
expect.objectContaining({ media: { path: local.path, name: local.name } }),
expect.objectContaining({ media: { data_url: DOCUMENT.dataUrl, name: DOCUMENT.name } }),
]);
});
it("preserves merged text longer than the former per-entry storage truncation across remounts", () => {
const onSend = vi.fn();
const first = render(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" isStreaming />);
@@ -155,7 +169,7 @@ describe("merged waiting messages", () => {
render(<ThreadComposer {...props} />);
await waitFor(() => expect(screen.queryByLabelText("Encoding…")).not.toBeInTheDocument());
expect(screen.getAllByTestId("composer-chip")).toHaveLength(2);
expect(draftStore.get("chat-a")?.files.map((file) => file.name)).toEqual(["first.png", "second.txt"]);
expect(draftStore.get("chat-a")?.attachments.map((file) => file.name)).toEqual(["first.png", "second.txt"]);
});
it("retains a merged rejected send after leaving the topic during upload", async () => {
+2 -2
View File
@@ -288,7 +288,7 @@ describe("SettingsView Apps catalog", () => {
"Fix connection",
);
await act(() => i18n.changeLanguage("zh-CN"));
await act(async () => { await i18n.changeLanguage("zh-CN"); });
expect(within(row as HTMLElement).getByText("连接失败。")).toBeInTheDocument();
const manage = within(row as HTMLElement).getByRole("button", { name: "管理 Xmind" });
expect(manage).toHaveTextContent("修复连接");
@@ -306,7 +306,7 @@ describe("SettingsView Apps catalog", () => {
{ name: "xmind", reset: true, use_proxy: "false" },
30_000,
));
await act(() => i18n.changeLanguage("en"));
await act(async () => { await i18n.changeLanguage("en"); });
});
it("keeps an OAuth runtime failure visible after credentials are cleared", async () => {
@@ -42,7 +42,7 @@ describe("automation channel identity", () => {
["ja", "メール"],
["es", "Correo electrónico"],
]) {
await act(() => i18n.changeLanguage(locale));
await act(async () => { await i18n.changeLanguage(locale); });
expect(detail.getByText(name)).toBeVisible();
expect(detail.queryByText("Email")).not.toBeInTheDocument();
}
@@ -8,6 +8,7 @@ import {
import { beforeEach, describe, expect, it, vi } from "vitest";
import { ThreadComposer } from "@/components/thread/ThreadComposer";
import { ComposerDraftStore } from "@/lib/composer-draft";
import type { EncodeResponse } from "@/lib/imageEncode";
import type { WebUIIngressLimits } from "@/lib/types";
@@ -425,3 +426,180 @@ describe("ThreadComposer — attachments", () => {
expect(onSend).not.toHaveBeenCalled();
});
});
describe("local attachment paths and video ingress", () => {
const local = { path: "C:\\project\\my clip.mp4", name: "my clip.mp4", size: 12,
mime: "video/mp4", kind: "video" as const, url: "/api/media/sig/local" };
it("confirms a large pasted video path and sends only the borrowed reference", async () => {
const inspect = vi.fn().mockResolvedValue({ ...local, size: 64 * 1024 * 1024 + 1 });
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} onInspectAttachment={inspect} />);
const input = screen.getByLabelText(/message input/i);
fireEvent.change(input, { target: { value: "keep this " } });
(input as HTMLTextAreaElement).setSelectionRange(10, 10);
fireEvent.paste(input, { clipboardData: { items: [], getData: () => '"C:\\project\\my clip.mp4"' } });
await waitFor(() => expect(screen.getByTestId("composer-chip")).toHaveTextContent("my clip.mp4"));
expect(input).toHaveValue("keep this ");
expect(inspect).toHaveBeenCalledWith(local.path);
fireEvent.keyDown(input, { key: "Enter" });
expect(onSend.mock.calls[0][1][0].media).toEqual({ path: local.path, name: local.name });
});
it.each(["append", "prepend"])("keeps %s text written while the pasted path is being checked", async (edit) => {
let complete!: (attachment: typeof local) => void;
const inspect = vi.fn(() => new Promise<typeof local>((resolve) => { complete = resolve; }));
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} onInspectAttachment={inspect} />);
const input = screen.getByLabelText(/message input/i) as HTMLTextAreaElement;
fireEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
const typed = edit === "append" ? `${local.path} describe it` : `请看 ${local.path}`;
fireEvent.change(input, { target: { value: typed, selectionStart: typed.length } });
await act(async () => complete(local));
await screen.findByTestId("composer-chip");
expect(input).toHaveValue(edit === "append" ? " describe it" : "请看 ");
fireEvent.keyDown(input, { key: "Enter" });
expect(onSend.mock.calls[0][0]).toBe(edit === "append" ? "describe it" : "请看");
expect(onSend.mock.calls[0][1][0].media).toEqual({ path: local.path, name: local.name });
});
it.each(["edit", "remove"])("does not attach a path after the user chooses to %s it during inspection", async (edit) => {
let complete!: (attachment: typeof local) => void;
render(<ThreadComposer onSend={vi.fn()} onInspectAttachment={() => new Promise((resolve) => { complete = resolve; })} />);
const input = screen.getByLabelText(/message input/i);
fireEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
const typed = edit === "edit" ? local.path.replace("clip", "other") : "keep my new text";
fireEvent.change(input, { target: { value: typed } });
await act(async () => complete(local));
expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument();
expect(input).toHaveValue(typed);
expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled();
});
it("does not steal toolbar focus when a pending path is confirmed", async () => {
let complete!: (attachment: typeof local) => void;
render(<ThreadComposer onSend={vi.fn()} onInspectAttachment={() => new Promise((resolve) => { complete = resolve; })} />);
const input = screen.getByLabelText(/message input/i);
await waitFor(() => expect(input).toHaveFocus());
fireEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
const attach = screen.getByRole("button", { name: /attach/i });
attach.focus();
expect(attach).toHaveFocus();
await act(async () => complete(local));
await screen.findByTestId("composer-chip");
expect(attach).toHaveFocus();
});
it("lets an IME composition finish before converting its pasted path", async () => {
let complete!: (attachment: typeof local) => void;
render(<ThreadComposer onSend={vi.fn()} onInspectAttachment={() => new Promise((resolve) => { complete = resolve; })} />);
const input = screen.getByLabelText(/message input/i);
fireEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
fireEvent.compositionStart(input);
fireEvent.change(input, { target: { value: `${local.path}你` } });
await act(async () => complete(local));
expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument();
fireEvent.compositionEnd(input);
await screen.findByTestId("composer-chip");
expect(input).toHaveValue("你");
});
it("ignores an inspection reply after the workspace scope changes", async () => {
let complete!: (attachment: typeof local) => void;
const inspect = () => new Promise<typeof local>((resolve) => { complete = resolve; });
const view = render(<ThreadComposer onSend={vi.fn()} onInspectAttachment={inspect} workspaceScope={{ project_path: "C:\\project", access_mode: "full" }} />);
const input = screen.getByLabelText(/message input/i);
fireEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
view.rerender(<ThreadComposer onSend={vi.fn()} onInspectAttachment={inspect} workspaceScope={{ project_path: "C:\\project", access_mode: "restricted" }} />);
await act(async () => complete(local));
expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument();
expect(input).toHaveValue(local.path);
expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled();
});
it("keeps mixed local and uploaded attachment order across draft remounts", async () => {
encodeImage.mockImplementation(async (file) => resolveReady(file));
const firstLocal = { ...local, path: "C:\\project\\first.png", name: "first.png", kind: "image" as const, mime: "image/png" };
const lastLocal = { ...firstLocal, path: "C:\\project\\last.png", name: "last.png" };
const inspect = vi.fn().mockResolvedValueOnce(firstLocal).mockResolvedValueOnce(lastLocal);
const store = new ComposerDraftStore();
const onSend = vi.fn();
const composer = () => <ThreadComposer draftKey="mixed-order" draftStore={store} onSend={onSend} onInspectAttachment={inspect} />;
const view = render(composer());
const input = screen.getByLabelText(/message input/i);
fireEvent.paste(input, { clipboardData: { items: [], getData: () => firstLocal.path } });
await screen.findByText(firstLocal.name);
fireEvent.change(input.closest("form")!.querySelector('input[type="file"]')!, { target: { files: [pngFile("middle.png")] } });
await screen.findByText("middle.png");
fireEvent.paste(input, { clipboardData: { items: [], getData: () => lastLocal.path } });
await screen.findByText(lastLocal.name);
fireEvent.change(input, { target: { value: "compare the first, second and third images" } });
await waitFor(() => expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled());
expect(screen.getAllByTestId("composer-chip").map((chip) => chip.textContent)).toEqual([
expect.stringContaining("first.png"), expect.stringContaining("middle.png"), expect.stringContaining("last.png"),
]);
view.unmount();
render(composer());
await waitFor(() => expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled());
fireEvent.keyDown(screen.getByLabelText(/message input/i), { key: "Enter" });
expect(onSend.mock.calls[0][1].map((item: { media: { name: string } }) => item.media.name)).toEqual([
"first.png", "middle.png", "last.png",
]);
});
it("keeps failed path text and attachment draft, and does not consume prose or URLs", async () => {
const inspect = vi.fn().mockRejectedValue(new Error("file not found"));
render(<ThreadComposer onSend={vi.fn()} onInspectAttachment={inspect} />);
const input = screen.getByLabelText(/message input/i);
fireEvent.paste(input, { clipboardData: { items: [], getData: () => "./missing.mp4" } });
await waitFor(() => expect(screen.getByText("file not found")).toBeInTheDocument());
expect(input).toHaveValue("./missing.mp4");
for (const text of ["look at ./missing.mp4 please", "https://host/clip.mp4", "const path = './clip.mp4'", "line one\n./clip.mp4"]) {
fireEvent.paste(input, { clipboardData: { items: [], getData: () => text } });
}
expect(inspect).toHaveBeenCalledTimes(1);
expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument();
});
it("does not charge large local documents against a picked document's upload budget", async () => {
const onSend = vi.fn();
const document = { ...local, path: "C:\\project\\large.pdf", name: "large.pdf", mime: "application/pdf", kind: "file" as const, size: 64 * 1024 * 1024 + 1 };
render(<ThreadComposer onSend={onSend} onInspectAttachment={vi.fn().mockResolvedValue(document)} ingressLimits={ingressLimits({ maxFileBytes: 8, maxTotalBytes: 8 })} />);
const input = screen.getByLabelText(/message input/i);
fireEvent.paste(input, { clipboardData: { items: [], getData: () => document.path } });
await screen.findByText(document.name);
const picker = input.closest("form")!.querySelector('input[type="file"]')!;
fireEvent.change(picker, { target: { files: [pdfFile("upload.pdf", 8)] } });
await waitFor(() => expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled());
fireEvent.keyDown(input, { key: "Enter" });
expect(onSend).toHaveBeenCalledWith("", [
expect.objectContaining({ media: { path: document.path, name: document.name } }),
expect.objectContaining({ media: expect.objectContaining({ name: "upload.pdf", data_url: expect.any(String) }) }),
], undefined);
});
it("explains the size and limit of a rejected browser video without losing the draft", () => {
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} />);
const input = screen.getByLabelText(/message input/i);
fireEvent.change(input, { target: { value: "keep this text" } });
const file = new File([new Uint8Array(21 * 1024 * 1024)], "large.mp4", { type: "video/mp4" });
fireEvent.change(input.closest("form")!.querySelector('input[type="file"]')!, { target: { files: [file] } });
expect(screen.getByRole("alert")).toHaveTextContent("21.0 MiB");
expect(screen.getByRole("alert")).toHaveTextContent("20.0 MiB");
expect(input).toHaveValue("keep this text");
expect(onSend).not.toHaveBeenCalled();
});
it("uploads picked video bytes with the existing independent video size/count allowance", async () => {
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} ingressLimits={ingressLimits({ maxFileBytes: 3 })} />);
const input = screen.getByLabelText(/message input/i);
const picker = input.closest("form")!.querySelector('input[type="file"]')!;
fireEvent.change(picker, { target: { files: [new File(["movie"], "clip.mov", { type: "" })] } });
await waitFor(() => expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled());
fireEvent.keyDown(input, { key: "Enter" });
expect(onSend.mock.calls[0][1][0].media).toEqual({ data_url: `data:video/quicktime;base64,${btoa("movie")}`, name: "clip.mov" });
});
});
+30 -3
View File
@@ -665,6 +665,33 @@ describe("ThreadShell", () => {
expect(client.sendMessage).not.toHaveBeenCalled();
});
it("restores the landing attachment draft in its created topic after a gateway rejection", async () => {
const client = { ...makeClient(), sendAttachments: vi.fn().mockRejectedValue(new Error("file not found")) };
const store = new ComposerDraftStore();
store.set("new:chat", {
text: "keep the first draft", sessionMentions: [], quotedContext: null,
attachments: [{ path: "/project/video.mp4", name: "video.mp4", size: 8, mime: "video/mp4", kind: "video", url: "" }],
});
const onCreateChat = vi.fn().mockResolvedValue("created");
const shell = (id: string | null) => wrap(client, <ThreadShell session={id ? session(id) : null}
title="First attachment" draftStore={store} onToggleSidebar={() => {}} onCreateChat={onCreateChat} />);
const view = render(shell(null));
await screen.findByTestId("composer-chip");
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
await waitFor(() => expect(onCreateChat).toHaveBeenCalledTimes(1));
view.rerender(shell("created"));
await waitFor(() => expect(screen.getByRole("textbox")).toHaveValue("keep the first draft"));
expect(await screen.findByTestId("composer-chip")).toHaveTextContent("video.mp4");
expect(screen.getByRole("alert")).toHaveTextContent("file not found");
expect(store.get("websocket:created")?.attachments).toHaveLength(1);
expect(store.has("new:chat")).toBe(false);
client.sendAttachments.mockResolvedValue(undefined);
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
await waitFor(() => expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument());
expect(screen.getByRole("textbox")).toHaveValue("");
expect(client.sendAttachments).toHaveBeenCalledTimes(2);
});
it("clears the welcome draft after a delayed new-chat send and an unchanged round-trip", async () => {
const client = makeClient();
const store = new ComposerDraftStore();
@@ -694,7 +721,7 @@ describe("ThreadShell", () => {
const client = makeClient();
let draftStore = new ComposerDraftStore();
draftStore.set("websocket:reload-draft", {
text: "original", files: [], sessionMentions: [], quotedContext: "quoted answer",
text: "original", attachments: [], sessionMentions: [], quotedContext: "quoted answer",
});
const shell = () => wrap(client, (
<ThreadShell session={session("reload-draft")} title="Reload test" temporary={temporary}
@@ -740,8 +767,8 @@ describe("ThreadShell", () => {
it.each([false, true])("keeps text and quote drafts scoped to the session (temporary=%s)", async (temporary) => {
const client = makeClient();
const draftStore: ComposerDraftStore = new Map([
["websocket:draft-a", { text: "draft A", files: [], sessionMentions: [], quotedContext: "quote A" }],
["websocket:draft-b", { text: "draft B", files: [], sessionMentions: [], quotedContext: "quote B" }],
["websocket:draft-a", { text: "draft A", attachments: [], sessionMentions: [], quotedContext: "quote A" }],
["websocket:draft-b", { text: "draft B", attachments: [], sessionMentions: [], quotedContext: "quote B" }],
]);
const shell = (chatId: string) => wrap(client, (
<ThreadShell session={session(chatId)} title="Draft test" temporary={temporary}
+43
View File
@@ -2899,6 +2899,49 @@ describe("useNanobotStream", () => {
);
});
it("uses the accepted upload URL instead of retaining an encoded video in message state", () => {
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("uploaded-video", EMPTY_MESSAGES), {
wrapper: wrap(fake.client),
});
act(() => {
result.current.send("watch", [{
media: { data_url: "data:video/webm;base64,AAAA", name: "clip.webm" },
preview: { kind: "video", url: "data:video/webm;base64,AAAA", name: "clip.webm" },
}]);
});
const optimistic = result.current.messages[0];
expect(optimistic.media).toEqual([{ kind: "video", name: "clip.webm" }]);
const media = [{ kind: "video" as const, url: "/api/media/sig/upload", name: "clip.webm" }];
act(() => fake.emit("uploaded-video", {
event: "message_accepted", chat_id: "uploaded-video",
turn_id: optimistic.turnId!, starts_turn: true, media_urls: media,
}));
expect(result.current.messages).toHaveLength(1);
expect(result.current.messages[0]).toMatchObject({ id: optimistic.id, media, deliveryStatus: "accepted" });
});
it("replaces a local reference's optimistic preview with the gateway's session URL", () => {
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("local-video", EMPTY_MESSAGES), {
wrapper: wrap(fake.client),
});
act(() => {
result.current.send("watch", [{
media: { path: "/project/video.mp4", name: "video.mp4" },
preview: { kind: "video", url: "", name: "video.mp4" },
}]);
});
const optimistic = result.current.messages[0];
const media = [{ kind: "video" as const, url: "/api/media/sig/local-video", name: "video.mp4" }];
act(() => fake.emit("local-video", {
event: "user_message", chat_id: "local-video", text: "watch",
turn_id: optimistic.turnId!, starts_turn: true, media_urls: media,
}));
expect(result.current.messages).toHaveLength(1);
expect(result.current.messages[0]).toMatchObject({ id: optimistic.id, media, deliveryStatus: "accepted" });
});
it("inlines quoted context into the optimistic and outbound user message", () => {
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("chat-quote", EMPTY_MESSAGES), {
+2 -2
View File
@@ -345,7 +345,7 @@ describe("durable run recovery", () => {
it.each(["failed read", "missing activity state"])("leaves %s unresolved", async (failure) => {
const body = completedThread();
delete body.has_pending_tool_calls;
Reflect.deleteProperty(body, "has_pending_tool_calls");
body.events = body.events.slice(0, 2);
const fetchMock = failure === "failed read"
? vi.fn().mockRejectedValue(new Error("offline"))
@@ -390,7 +390,7 @@ describe("durable run recovery", () => {
it("accepts an explicit completed turn when an older host omits activity metadata", async () => {
const body = completedThread();
delete body.has_pending_tool_calls;
Reflect.deleteProperty(body, "has_pending_tool_calls");
body.completed_turn_ids = ["turn-old"];
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(body)));
const { client, running, reopen, close } = setup();