Files
nanobot/webui/src/components/thread/ThreadComposer.tsx
T

2537 lines
96 KiB
TypeScript
Raw Normal View History

import type { ModelOptionsControlProps } from "@/components/thread/ModelOptionsControl";
import { pastedFilePath, PastedPathRange, type LocalAttachment } from "../../../../packages/client-events/attachments";
import {
ToolRunIcon,
AttachIcon,
EditIcon,
} from "@/components/icons/product-icons";
import {
useCallback,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
type CSSProperties,
type KeyboardEvent as ReactKeyboardEvent,
2026-08-06 18:29:04 +08:00
type Ref,
} from "react";
2026-05-22 22:25:12 +08:00
import {
CapabilityMentionToken,
2026-05-22 22:25:12 +08:00
cliAppInitials,
mcpPresetInitials,
splitCapabilityMentionSegments,
2026-05-22 22:25:12 +08:00
} from "@/components/CliAppMentionText";
import {
SkillReferenceToken,
withSkillReferences,
type InlineReferenceSegment,
} from "@/components/SkillReferenceText";
import {
composerMentionText,
isCapabilityMentionStart,
type CapabilityMentionSegment,
} from "@/lib/composer-mention-text";
import { INLINE_REFERENCE_HIGHLIGHT_COLOR, InlineTokenHighlight } from "@/components/InlineTokenHighlight";
import { SlashCommandText } from "@/components/SlashCommandText";
import {
CornerDownRight,
Loader2,
Maximize2,
Minimize2,
Quote,
Trash2,
X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { useToast } from "@/components/ui/toast";
import { AttachmentCard, AttachmentTypeFace, attachmentCardActionClassName } from "@/components/AttachmentCard";
import { ComposerActionIcon, type ComposerActionState } from "@/components/thread/ComposerActionIcon";
2026-08-04 15:32:29 +08:00
import {
CliAppMentionPalette,
SkillPalette,
SlashCommandPalette,
skillSourceBucket,
slashCommandI18nKey,
type MentionCandidate,
type SkillPaletteItem,
type SlashPaletteCommand,
type SlashPaletteLayout,
type SlashPalettePlacement,
} from "@/components/thread/ComposerPalette";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import {
WorkspaceAccessMenu,
WorkspaceProjectPicker,
} from "@/components/thread/WorkspaceControls";
import {
ModelPresetBadge,
type ModelPresetOption,
} from "@/components/thread/ModelPresetBadge";
import type { ComposerUsageControl } 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 RestoredReadyImage,
} from "@/hooks/useAttachedImages";
import { useClipboardAndDrop } from "@/hooks/useClipboardAndDrop";
import { useComposerMentionInput } from "@/hooks/useComposerMentionInput";
import { useMediaQuery } from "@/hooks/useMediaQuery";
import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream";
import { useComposerVoiceInput } from "@/hooks/useComposerVoiceInput";
import type {
CliAppInfo,
2026-08-02 22:04:59 +08:00
ChatSummary,
GoalStateWsPayload,
McpPresetInfo,
OutboundCliAppMention,
OutboundMcpPresetMention,
2026-08-02 22:04:59 +08:00
SessionMention,
SlashCommand,
2026-07-01 15:52:34 +08:00
SkillSummary,
WebUIIngressLimits,
WorkspaceScopePayload,
WorkspacesPayload,
ProjectDirectory,
WorkspaceDirectoriesPayload,
} from "@/lib/types";
import { requestSkillsRefresh } from "@/lib/skill-events";
import {
isRegisteredSlashCommand,
isSideChannelLifecycle,
matchingSlashCommand,
slashCommandLifecycle,
} from "@/lib/slash-command";
import {
clearDraggedSession,
hasDraggedSession,
readDraggedSession,
} from "@/lib/session-drag";
import { formatQuotedUserMessage } from "@/lib/user-message-quote";
import { cn } from "@/lib/utils";
import type { ComposerDraft, ComposerDraftStore } from "@/lib/composer-draft";
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
import {
queuedImagesToSendImages,
queuedUploadBytes,
readyImagesToQueuedImages,
useQueuedPrompt,
type QueuedPromptContent,
} from "@/components/thread/useQueuedPrompt";
function formatBytes(n: number): string {
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`;
return `${(n / (1024 * 1024)).toFixed(1)} MiB`;
}
function utf8Bytes(value: string): number {
return new TextEncoder().encode(value).byteLength;
}
interface ThreadComposerProps {
onSend: (
content: string,
images?: SendAttachment[],
options?: SendOptions,
) => boolean | void | Promise<boolean | void>;
disabled?: boolean;
placeholder?: string;
inputAriaLabel?: string;
expandable?: boolean;
compactWhenIdle?: boolean;
isStreaming?: boolean;
activeTurnId?: string | null;
completedTurnIds?: readonly string[];
modelLabel?: string | null;
modelDetail?: string | null;
modelPreset?: string | null;
modelPresets?: ModelPresetOption[];
modelOptionsControl?: ModelOptionsControlProps;
onModelMenuOpenChange?: (open: boolean) => void;
onModelPresetChange?: (name: string) => void;
imageInputBlocked?: boolean;
onInspectImagePreset?: () => void;
modelProvider?: string | null;
modelProviderLabel?: string | null;
modelNeedsSetup?: boolean;
onModelBadgeClick?: () => void;
2026-08-25 19:32:07 +08:00
onManageModels?: () => void;
renderContextUsage?: ComposerUsageControl;
variant?: "thread" | "hero";
2026-05-06 15:54:15 +00:00
slashCommands?: SlashCommand[];
onMentionSearch?: () => void;
2026-05-22 22:25:12 +08:00
cliApps?: CliAppInfo[];
mcpPresets?: McpPresetInfo[];
2026-08-02 22:04:59 +08:00
sessions?: ChatSummary[];
2026-07-01 15:52:34 +08:00
skills?: SkillSummary[];
onStop?: () => void;
2026-08-06 18:29:04 +08:00
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;
2026-08-06 18:29:04 +08:00
workspaceControlsHidden?: boolean;
workspacePickerLayoutAnchor?: HTMLElement | null;
workspaceDefaultScope?: WorkspaceScopePayload | null;
workspaceControls?: WorkspacesPayload["controls"] | null;
workspaceScopeDisabled?: boolean;
workspaceProjectLocked?: boolean;
workspaceError?: string | null;
onFavoriteWorkspaceProject?: (path: string, pinned: boolean) => Promise<ProjectDirectory[]>;
onResolveWorkspaceProject?: (path: string) => Promise<ProjectDirectory>;
onLoadWorkspaceProjects?: () => Promise<WorkspacesPayload>;
onBrowseWorkspaceDirectories?: (path: string, query: string, showHidden: boolean) => Promise<WorkspaceDirectoriesPayload>;
onWorkspaceScopeChange?: (scope: WorkspaceScopePayload) => void;
pendingQueueKey?: string | null;
draftKey?: string;
draftStore?: ComposerDraftStore;
persistDraft?: boolean;
transcriptionProvider?: string | null;
ingressLimits?: WebUIIngressLimits | null;
quotedContext?: string | null;
focusRequest?: number;
onQuotedContextChange?: (text: string | null) => void;
2026-05-06 15:54:15 +00:00
}
const SLASH_PALETTE_GAP_PX = 8;
const SLASH_PALETTE_MAX_HEIGHT_PX = 288;
const SLASH_PALETTE_MIN_HEIGHT_PX = 144;
2026-05-24 20:56:07 +08:00
const SLASH_RECENTS_STORAGE_KEY = "nanobot.webui.slashCommandRecents";
const SLASH_RECENTS_LIMIT = 5;
const SESSION_MENTIONS_LIMIT = 8;
function VoiceRecordingMeter({
ariaLabel,
className,
elapsedLabel,
isHero,
levels,
}: {
ariaLabel: string;
className?: string;
elapsedLabel: string;
isHero: boolean;
levels: number[];
}) {
return (
<div
className={cn(
"flex min-w-0 items-center gap-2 text-neutral-700 dark:text-white",
isHero ? "h-8" : "h-9",
className,
)}
aria-live="polite"
aria-label={ariaLabel}
>
<span className="flex h-5 min-w-0 flex-1 items-center justify-between overflow-hidden" aria-hidden>
{levels.map((height, index) => (
<span
key={index}
className="w-[2px] rounded-full bg-current opacity-85 transition-[height] duration-75 ease-linear motion-reduce:transition-none"
style={{ height }}
/>
))}
</span>
<span className="min-w-[2.1rem] text-right text-[12px] font-medium tabular-nums text-muted-foreground">
{elapsedLabel}
</span>
</div>
);
}
2026-05-22 22:25:12 +08:00
interface CliAppMentionQuery {
query: string;
start: number;
end: number;
}
interface MentionInsertion {
value: string;
cursor: number;
tokenStart: number;
tokenEnd: number;
}
function mentionInsertion(
value: string,
name: string,
start: number,
end: number,
): MentionInsertion {
const from = Math.min(Math.max(start, 0), value.length);
const to = Math.min(Math.max(end, from), value.length);
const prefix = value.slice(0, from);
const suffix = value.slice(to);
const leadingSpace = prefix && !isCapabilityMentionStart(value, from) ? " " : "";
const trailingSpace = /^\s/.test(suffix) ? "" : " ";
const tokenStart = prefix.length + leadingSpace.length;
const tokenEnd = tokenStart + name.length + 1;
return {
2026-08-18 18:28:19 +08:00
value: `${prefix}${leadingSpace}@${name}${trailingSpace}${suffix}`,
cursor: tokenEnd + trailingSpace.length,
tokenStart,
tokenEnd,
};
}
function sessionMentionOptions(sessions: ChatSummary[]): SessionMention[] {
return sessions.flatMap((session) => {
2026-08-18 18:28:19 +08:00
if (!session.handle) return [];
return [{
2026-08-18 18:28:19 +08:00
id: session.handle.id,
name: session.handle.name,
session_key: session.key,
title: session.title?.trim() || session.preview.trim(),
}];
});
}
2026-07-28 11:28:53 +08:00
function skillMatchRank(skill: SkillSummary, query: string): number | null {
if (!query) return 0;
const name = skill.name.toLowerCase();
if (name === query) return 0;
if (name.startsWith(query)) return 1;
if (name.includes(query)) return 2;
if (skill.description.toLowerCase().includes(query)) return 3;
return null;
}
function skillSourceOrder(source: string): number {
const bucket = skillSourceBucket(source);
if (bucket === "workspace") return 0;
if (bucket === "builtin") return 1;
return 2;
}
function slashCommandMatchRank(
command: SlashCommand,
title: string,
description: string,
query: string,
): number | null {
if (!query) return 0;
const name = command.command.replace(/^\//, "").toLowerCase();
if (name === query) return 0;
if (name.startsWith(query)) return 1;
if (name.includes(query)) return 2;
if (title.toLowerCase().includes(query) || command.title.toLowerCase().includes(query)) return 3;
const haystack = [command.command, command.description, command.argHint ?? "", description]
.join(" ")
.toLowerCase();
return haystack.includes(query) ? 4 : null;
}
2026-05-24 20:56:07 +08:00
function readSlashRecents(): string[] {
if (typeof window === "undefined") return [];
try {
const raw = window.localStorage.getItem(SLASH_RECENTS_STORAGE_KEY);
const parsed = raw ? JSON.parse(raw) : [];
return Array.isArray(parsed)
? parsed.filter((item): item is string => typeof item === "string").slice(0, SLASH_RECENTS_LIMIT)
: [];
} catch {
return [];
}
}
function storeSlashRecents(commands: string[]): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(
SLASH_RECENTS_STORAGE_KEY,
JSON.stringify(commands.slice(0, SLASH_RECENTS_LIMIT)),
);
} catch {
// localStorage may be unavailable in private contexts; command insertion still works.
}
}
function queuedPromptLabel(prompt: QueuedPromptContent): string {
const text = prompt.text.trim();
if (text) return text;
return prompt.images?.map((img) => img.name).filter(Boolean).join(", ") || "File attachment";
}
function visualViewportBounds(): { top: number; bottom: number; height: number } {
const viewport = window.visualViewport;
if (!viewport) {
return { top: 0, bottom: window.innerHeight, height: window.innerHeight };
}
const top = Math.max(0, viewport.offsetTop);
const height = Math.max(0, viewport.height);
return { top, bottom: top + height, height };
}
function getVisibleBounds(el: HTMLElement): { top: number; bottom: number } {
// The app already follows the visual viewport on touch browsers. Measure
// its frame in the same coordinates as the composer, not WebKit's pan offset.
// During pinch zoom the app stops fitting, so use the zoomed viewport again.
const fittedRoot = window.visualViewport?.scale === 1
? el.closest("#root.visual-viewport")
: null;
const viewport = fittedRoot?.getBoundingClientRect() ?? visualViewportBounds();
let top = viewport.top;
let bottom = viewport.bottom;
let parent = el.parentElement;
while (parent) {
const style = window.getComputedStyle(parent);
if (/(auto|scroll|hidden|clip)/.test(style.overflowY)) {
const rect = parent.getBoundingClientRect();
top = Math.max(top, rect.top);
bottom = Math.min(bottom, rect.bottom);
}
parent = parent.parentElement;
}
return { top, bottom };
}
2026-05-22 22:25:12 +08:00
function cliAppMentionPayload(app: CliAppInfo): OutboundCliAppMention {
return {
name: app.name,
display_name: app.display_name,
category: app.category,
entry_point: app.entry_point,
logo_url: app.logo_url ?? null,
brand_color: app.brand_color ?? null,
};
}
function mcpPresetMentionPayload(preset: McpPresetInfo): OutboundMcpPresetMention {
return {
name: preset.name,
display_name: preset.display_name,
category: preset.category,
transport: preset.transport,
status: preset.status,
configured: preset.configured,
logo_url: preset.logo_url ?? null,
brand_color: preset.brand_color ?? null,
};
}
function autosizeTextarea(input: HTMLTextAreaElement) {
const container = input.parentElement!;
const previousMinHeight = container.style.minHeight;
const scrollTop = input.scrollTop;
// Measuring the one-row textarea must not expand the sibling transcript and
// clamp its native scroll offset, even temporarily before paint.
container.style.minHeight = `${container.getBoundingClientRect().height}px`;
try {
input.style.height = "auto";
input.style.height = `${input.scrollHeight}px`;
input.scrollTop = scrollTop;
} finally {
container.style.minHeight = previousMinHeight;
}
}
export function ThreadComposer({
onSend,
disabled,
placeholder,
inputAriaLabel,
expandable = true,
compactWhenIdle = false,
isStreaming = false,
activeTurnId = null,
completedTurnIds,
modelLabel = null,
modelDetail = null,
modelPreset = null,
modelPresets = [],
modelOptionsControl,
onModelMenuOpenChange,
onModelPresetChange,
imageInputBlocked = false,
onInspectImagePreset,
modelProvider = null,
modelProviderLabel = null,
modelNeedsSetup = false,
onModelBadgeClick,
2026-08-25 19:32:07 +08:00
onManageModels,
renderContextUsage,
variant = "thread",
2026-05-06 15:54:15 +00:00
slashCommands = [],
onMentionSearch,
2026-05-22 22:25:12 +08:00
cliApps = [],
mcpPresets = [],
2026-08-02 22:04:59 +08:00
sessions = [],
2026-07-01 15:52:34 +08:00
skills = [],
onStop,
2026-08-06 18:29:04 +08:00
surfaceRef,
onTranscribeAudio,
onInspectAttachment,
goalState,
workspaceScope = null,
2026-08-06 18:29:04 +08:00
workspaceControlsHidden = false,
workspacePickerLayoutAnchor,
workspaceDefaultScope = null,
workspaceControls = null,
workspaceScopeDisabled = false,
workspaceProjectLocked = false,
workspaceError = null,
onLoadWorkspaceProjects,
onResolveWorkspaceProject,
onFavoriteWorkspaceProject,
onBrowseWorkspaceDirectories,
onWorkspaceScopeChange,
pendingQueueKey = null,
draftKey,
draftStore,
persistDraft = false,
transcriptionProvider = null,
ingressLimits = null,
quotedContext = null,
focusRequest = 0,
onQuotedContextChange,
}: ThreadComposerProps) {
const { t } = useTranslation();
const [initialDraft] = useState(() => draftKey ? draftStore?.get(draftKey, persistDraft) : undefined);
const [value, setValue] = useState(initialDraft?.text ?? "");
const [composerFocused, setComposerFocused] = useState(false);
const [compactPlaceholder, setCompactPlaceholder] = useState(false);
const blurFrame = useRef<number | null>(null);
const [boundSessionMentions, setBoundSessionMentions] = useState<SessionMention[]>(
initialDraft?.sessionMentions ?? [],
);
const [sessionDragPreview, setSessionDragPreview] = useState<{
mention: SessionMention;
start: number;
end: number;
} | null>(null);
const [inlineError, setInlineError] = useState<string | null>(null);
const showToast = useToast();
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 textareaRef = useRef<HTMLTextAreaElement>(null);
const textareaId = useId();
const [draftExpanded, setDraftExpanded] = useState(false);
const [draftOverflows, setDraftOverflows] = useState(false);
const focusTextarea = useCallback(() => {
requestAnimationFrame(() => textareaRef.current?.focus());
}, []);
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 formatRejection = useCallback(
(reason: Exclude<AttachmentError, "too_large">): string => {
const key = `thread.composer.imageRejected.${reason}`;
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"
: "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),
defaultValue: `Message text is too large (max ${formatBytes(maxTextBytes)})`,
}),
[maxTextBytes, t],
);
const queuedPromptError = useCallback((prompt: QueuedPromptContent): string | null => {
if (utf8Bytes(formatQuotedUserMessage(prompt.text, prompt.quotedContext)) > maxTextBytes) {
return textTooLargeMessage();
}
const attachments = prompt.images ?? [];
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);
}
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, formatUploadTooLarge, ingressLimits, maxAttachments, maxFileBytes, maxTextBytes, t, textTooLargeMessage]);
const validatePrompt = useCallback((prompt: QueuedPromptContent): boolean => {
if (imageInputBlocked && prompt.images?.some(({ kind }) => kind === "image")) {
showToast?.({
message: t("errors.modelRequestFailed.imageInputTitle"),
tone: "error",
action: onInspectImagePreset
? { label: t("settings.models.viewPreset"), run: onInspectImagePreset }
: undefined,
});
return false;
}
const error = queuedPromptError(prompt);
if (error) setInlineError(error);
return error === null;
}, [imageInputBlocked, onInspectImagePreset, queuedPromptError, showToast, t]);
const {
snapshot: queueSnapshot,
collect: collectQueuedPrompt,
enqueue: enqueueQueuedPrompt,
clear: clearQueuedPrompt,
pause: pauseQueue,
send: sendQueuedPrompt,
} = useQueuedPrompt(pendingQueueKey, { isStreaming, activeTurnId, completedTurnIds }, {
disabled: !!disabled || sendPending,
onSend,
validate: validatePrompt,
onSendAttempt: focusTextarea,
});
const queuedPrompt = queueSnapshot.prompt;
const interactionDisabled = !!disabled || sendPending || queueSnapshot.sending;
useEffect(() => {
if (queueSnapshot.error) setInlineError(queueSnapshot.error);
}, [queueSnapshot.error]);
2026-05-06 15:54:15 +00:00
const [slashMenuDismissed, setSlashMenuDismissed] = useState(false);
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);
2026-05-22 22:25:12 +08:00
const [cliAppMenuDismissed, setCliAppMenuDismissed] = useState(false);
const [selectedCliAppIndex, setSelectedCliAppIndex] = useState(0);
const [cursorPosition, setCursorPosition] = useState(0);
2026-05-24 20:56:07 +08:00
const [recentSlashCommands, setRecentSlashCommands] = useState<string[]>(() => readSlashRecents());
const hasTouchPrimaryPointer = useMediaQuery("(hover: none) and (pointer: coarse)");
// Coarser than hasTouchPrimaryPointer on purpose: tablets with a physical
// keyboard still get the newline-on-Enter behavior.
const hasCoarsePointer = useMediaQuery("(pointer: coarse)");
const mobileWorkspaceControls = useMediaQuery("(max-width: 639px)");
const { readingTextSize, customReadingTextSize } = useLocalPreferences();
const placeholderMeasureRef = useRef<HTMLSpanElement>(null);
const mentionOverlayRef = useRef<HTMLDivElement>(null);
const formRef = useRef<HTMLFormElement>(null);
const [compactControls, setCompactControls] = useState(false);
const measureDraft = useCallback(() => {
const input = textareaRef.current;
if (!input) return;
autosizeTextarea(input);
if (expandable) setDraftOverflows(input.scrollHeight > input.clientHeight);
if (mentionOverlayRef.current) mentionOverlayRef.current.scrollTop = input.scrollTop;
}, [expandable]);
useLayoutEffect(() => {
const form = formRef.current;
const input = textareaRef.current;
if (!form || !input) return;
let previousWidth = 0;
const update = () => {
const width = form.getBoundingClientRect().width;
if (width <= 0) return;
if (width !== previousWidth) {
previousWidth = width;
setCompactControls(width <= 512);
measureDraft();
} else if (expandable) {
setDraftOverflows(input.scrollHeight > input.clientHeight);
}
};
update();
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(update);
observer?.observe(form);
if (expandable) observer?.observe(input);
window.addEventListener("resize", update);
return () => {
observer?.disconnect();
window.removeEventListener("resize", update);
};
}, [expandable, measureDraft]);
const fileInputRef = useRef<HTMLInputElement>(null);
const chipRefs = useRef(new Map<string, HTMLButtonElement>());
const previousPendingQueueKeyRef = useRef(pendingQueueKey);
const isHero = variant === "hero";
2026-08-05 19:24:41 +08:00
const projectPickerAvailable =
!workspaceProjectLocked
&& !!workspaceDefaultScope
&& !!onWorkspaceScopeChange
&& !!onLoadWorkspaceProjects
&& !!onBrowseWorkspaceDirectories
&& !!onResolveWorkspaceProject
&& !!onFavoriteWorkspaceProject
&& workspaceControls?.can_change_project !== false;
2026-08-06 18:29:04 +08:00
const showProjectPicker = projectPickerAvailable && !workspaceControlsHidden;
const resolvedPlaceholder = placeholder ?? t("thread.composer.placeholder");
const showCompactPlaceholder = placeholder === undefined && compactPlaceholder;
const displayedPlaceholder = showCompactPlaceholder ? t("thread.composer.placeholderCompact") : resolvedPlaceholder;
useLayoutEffect(() => {
const input = textareaRef.current;
const text = placeholderMeasureRef.current;
if (!input || !text || placeholder !== undefined) return;
const measure = () => {
const style = getComputedStyle(input);
const available = input.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
if (available > 0) setCompactPlaceholder(text.getBoundingClientRect().width > available);
};
measure();
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);
observer?.observe(input);
observer?.observe(text);
window.addEventListener("resize", measure);
let active = true;
void document.fonts?.ready.then(() => { if (active) measure(); });
return () => {
active = false;
observer?.disconnect();
window.removeEventListener("resize", measure);
};
}, [placeholder, resolvedPlaceholder, compactControls, readingTextSize, customReadingTextSize]);
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?.attachments.length);
useLayoutEffect(() => {
if (restoredDraftAttachments.current) return;
restoredDraftAttachments.current = true;
for (const attachment of initialDraft?.attachments ?? []) {
if (attachment instanceof File) enqueue([attachment], { restoringDraft: true });
else addLocal(attachment, { restoringDraft: true });
}
setDraftAttachmentsReady(true);
}, [enqueue, addLocal, initialDraft]);
const addFiles = useCallback(
(files: File[]) => {
if (interactionDisabled || files.length === 0) return;
const { rejected } = enqueue(files);
if (rejected.length > 0) {
const { reason, file } = rejected[0];
if (reason === "empty_file" || reason === "unsupported_type") {
showToast?.({ message: formatRejection(reason), tone: "error", dedupeKey: `attachment:${reason}` });
return;
}
setInlineError(reason === "too_large"
? formatUploadTooLarge(file.size, acceptedAttachmentKind(file) === "video" ? MAX_VIDEO_BYTES : maxFileBytes)
: formatRejection(reason));
} else {
setInlineError(null);
}
},
[enqueue, formatRejection, formatUploadTooLarge, interactionDisabled, maxFileBytes, showToast],
);
const {
isDragging,
onPaste: onAttachmentPaste,
onDragEnter,
onDragOver,
onDragLeave,
onDrop,
} = useClipboardAndDrop(addFiles);
useEffect(() => {
if (compactWhenIdle || interactionDisabled || hasTouchPrimaryPointer || (workspaceError && showProjectPicker)) {
return;
}
const el = textareaRef.current;
if (!el) return;
const id = requestAnimationFrame(() => el.focus());
return () => cancelAnimationFrame(id);
}, [compactWhenIdle, hasTouchPrimaryPointer, interactionDisabled, showProjectPicker, workspaceError]);
useEffect(() => () => {
if (blurFrame.current !== null) cancelAnimationFrame(blurFrame.current);
}, []);
useEffect(() => {
if (!focusRequest || interactionDisabled) return;
const id = requestAnimationFrame(() => textareaRef.current?.focus());
return () => cancelAnimationFrame(id);
}, [focusRequest, interactionDisabled]);
const normalizedQuotedContext = quotedContext?.trim() || null;
const readyImages = useMemo(
() => images.filter((img) =>
img.status === "ready" && (typeof img.dataUrl === "string" || !!img.local),
),
[images],
);
const hasErrors = images.some((img) => img.status === "error");
const isUserShell = value.trimStart().startsWith("!");
const requiresModelSetup = modelNeedsSetup && !isUserShell;
const hasComposerContent = value.trim().length > 0 || readyImages.length > 0;
const canSend =
!interactionDisabled
&& !requiresModelSetup
&& !encoding
&& !hasErrors
&& hasComposerContent;
const canOpenModelSettings = Boolean(
requiresModelSetup && onModelBadgeClick && !interactionDisabled,
);
const canQueueGuidance =
isStreaming
&& !isUserShell
&& !interactionDisabled
&& !modelNeedsSetup
&& !encoding
&& !hasErrors
&& hasComposerContent
// Without command metadata, let the gateway classify slash input immediately.
&& (slashCommands.length > 0
? !isRegisteredSlashCommand(value, slashCommands)
: !value.trimStart().startsWith("/"));
2026-05-06 15:54:15 +00:00
const slashQuery = useMemo(() => {
if (interactionDisabled || slashMenuDismissed || !value.startsWith("/")) return null;
2026-05-06 15:54:15 +00:00
const commandToken = value.slice(1);
if (/\s/.test(commandToken)) return null;
return commandToken.toLowerCase();
}, [interactionDisabled, slashMenuDismissed, value]);
2026-05-06 15:54:15 +00:00
2026-07-01 15:52:34 +08:00
const skillQuery = useMemo(() => {
if (interactionDisabled || isUserShell || slashMenuDismissed) return null;
2026-07-01 15:52:34 +08:00
const caret = Math.min(Math.max(cursorPosition, 0), value.length);
const beforeCaret = value.slice(0, caret);
const match = /\$([A-Za-z0-9_-]*)$/i.exec(beforeCaret);
if (!match) return null;
return {
end: caret,
start: match.index,
text: match[1].toLowerCase(),
};
}, [cursorPosition, interactionDisabled, isUserShell, slashMenuDismissed, value]);
2026-07-01 15:52:34 +08:00
const skillMenuActive = skillQuery !== null;
useEffect(() => {
// Also refresh an empty menu: skills may have been installed by the agent.
if (skillMenuActive) requestSkillsRefresh();
}, [skillMenuActive]);
2026-05-24 20:56:07 +08:00
const visibleSlashCommands = useMemo(() => {
2026-07-07 14:34:18 +08:00
if (!(isStreaming && onStop)) return slashCommands;
const stopCommand = slashCommands.find((command) => command.command === "/stop");
2026-07-07 14:34:18 +08:00
if (!stopCommand) return slashCommands;
return [
stopCommand,
...slashCommands.filter((command) => command.command !== "/stop"),
];
2026-05-24 20:56:07 +08:00
}, [isStreaming, onStop, slashCommands]);
const filteredSkills = useMemo<SkillPaletteItem[]>(() => {
if (skillQuery === null) return [];
const query = skillQuery.text;
return skills
.filter((skill) => skill.enabled !== false && skill.available)
.flatMap((skill) => {
const matchRank = skillMatchRank(skill, query);
return matchRank === null
? []
: [{
command: `$${skill.name}`,
matchRank,
skill,
}];
})
.sort((a, b) => {
if (a.matchRank !== b.matchRank) return a.matchRank - b.matchRank;
if (query !== "") return 0;
const aRecent = recentSlashCommands.indexOf(a.command);
const bRecent = recentSlashCommands.indexOf(b.command);
if (aRecent !== -1 || bRecent !== -1) {
2026-07-28 11:28:53 +08:00
if (aRecent === -1) return 1;
if (bRecent === -1) return -1;
return aRecent - bRecent;
}
return skillSourceOrder(a.skill.source) - skillSourceOrder(b.skill.source);
})
.map(({ command, skill }) => ({
name: skill.name,
command,
description: skill.description || skill.name,
source: skill.source,
recent: recentSlashCommands.includes(command),
}));
}, [recentSlashCommands, skills, skillQuery]);
const filteredSlashCommands = useMemo<SlashPaletteCommand[]>(() => {
if (skillQuery !== null || slashQuery === null) return [];
return visibleSlashCommands
.flatMap((command) => {
2026-07-07 14:34:18 +08:00
if (
slashQuery === ""
&& (
command.command === "/restart"
|| (command.command === "/stop" && !(isStreaming && onStop))
)
) {
return [];
2026-07-07 14:34:18 +08:00
}
2026-05-24 20:56:07 +08:00
const commandKey = slashCommandI18nKey(command.command);
const title = t(`thread.composer.slash.commands.${commandKey}.title`, {
defaultValue: command.title,
});
const description = t(`thread.composer.slash.commands.${commandKey}.description`, {
defaultValue: command.description,
});
const matchRank = slashCommandMatchRank(command, title, description, slashQuery);
if (matchRank === null) return [];
2026-05-24 20:56:07 +08:00
let detail = description;
let badge: string | undefined;
if (command.command === "/model" && modelLabel) {
detail = modelLabel;
badge = t("thread.composer.slash.badges.current");
} else if (command.command === "/goal") {
detail = goalState?.active
? t("thread.composer.slash.details.goalActive")
: t("thread.composer.slash.details.goalReady");
} else if (command.command === "/stop" && isStreaming) {
detail = t("thread.composer.slash.details.stopRunning");
}
return [{
matchRank,
item: {
...command,
detail,
badge,
recent: recentSlashCommands.includes(command.command),
},
}];
2026-05-24 20:56:07 +08:00
})
.sort((a, b) => {
if (isStreaming) {
if (a.item.command === "/stop") return -1;
if (b.item.command === "/stop") return 1;
2026-05-24 20:56:07 +08:00
}
if (a.matchRank !== b.matchRank) return a.matchRank - b.matchRank;
2026-05-24 20:56:07 +08:00
if (slashQuery !== "") return 0;
const aRecent = recentSlashCommands.indexOf(a.item.command);
const bRecent = recentSlashCommands.indexOf(b.item.command);
2026-05-24 20:56:07 +08:00
if (aRecent !== -1 || bRecent !== -1) {
if (aRecent === -1) return 1;
if (bRecent === -1) return -1;
return aRecent - bRecent;
}
return 0;
})
.map(({ item }) => item);
}, [goalState?.active, isStreaming, modelLabel, onStop, recentSlashCommands, skillQuery, slashQuery, t, visibleSlashCommands]);
2026-05-24 20:56:07 +08:00
const showSkillMenu = filteredSkills.length > 0;
const showSlashMenu = !showSkillMenu && filteredSlashCommands.length > 0;
2026-05-22 22:25:12 +08:00
const cliAppMention = useMemo<CliAppMentionQuery | null>(() => {
if (interactionDisabled || isUserShell || cliAppMenuDismissed) return null;
2026-05-22 22:25:12 +08:00
const caret = Math.min(Math.max(cursorPosition, 0), value.length);
const beforeCaret = value.slice(0, caret);
const match = /@([\p{L}\p{N}_-]*)$/iu.exec(beforeCaret);
if (!match || !isCapabilityMentionStart(value, match.index)) return null;
2026-05-22 22:25:12 +08:00
const query = match[1].toLowerCase();
return {
query,
start: match.index,
2026-05-22 22:25:12 +08:00
end: caret,
};
}, [cliAppMenuDismissed, cursorPosition, interactionDisabled, isUserShell, value]);
2026-05-22 22:25:12 +08:00
const mentionSearchActive = cliAppMention !== null;
useEffect(() => {
if (mentionSearchActive) onMentionSearch?.();
}, [mentionSearchActive, onMentionSearch]);
2026-08-02 22:04:59 +08:00
const availableSessionMentions = useMemo(
() => sessionMentionOptions(sessions),
[sessions],
);
const sessionMentionCatalog = useMemo(
() => [...availableSessionMentions, ...boundSessionMentions],
[availableSessionMentions, boundSessionMentions],
);
const mentionSegments = useMemo<CapabilityMentionSegment[]>(
() => isUserShell ? [{ kind: "text", text: value }]
: splitCapabilityMentionSegments(value, cliApps, mcpPresets, sessionMentionCatalog),
[cliApps, isUserShell, mcpPresets, sessionMentionCatalog, value],
);
const editMentionInput = useCallback((next: string, cursor: number) => {
setValue(next);
setSlashMenuDismissed(false);
setCliAppMenuDismissed(false);
setCursorPosition(cursor);
}, []);
const mentionInput = useComposerMentionInput({
segments: mentionSegments,
inputRef: textareaRef,
onEdit: editMentionInput,
resetKey: pendingQueueKey,
});
const { rawSelection, replace: replaceMentionInput } = mentionInput;
const onPaste = useCallback((event: React.ClipboardEvent<HTMLTextAreaElement>) => {
onAttachmentPaste(event);
if (event.defaultPrevented || interactionDisabled || isUserShell || !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(() => {
if (generation !== pathCheckGeneration.current || pathCheckScope.current !== scopeIdentity) return;
// Attachment recognition is optional; the pasted text is already in the draft.
setPathInspection(null);
});
}, [interactionDisabled, isUserShell, onAttachmentPaste, onInspectAttachment, rawSelection, replaceMentionInput, scopeIdentity, value]);
useLayoutEffect(() => {
if (!pathInspection) return;
if (isUserShell || 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 && !addLocal(pathInspection.attachment)) {
replaceMentionInput(edited.value, edited.cursor, { preserveFocus: true });
setInlineError(null);
}
setPathInspection(null);
}, [addLocal, isUserShell, mentionInput.isComposing, pathInspection, rawSelection, replaceMentionInput, scopeIdentity, value]);
const draftText = composerMentionText(mentionInput.segments).raw;
const sessionDragInsertion = sessionDragPreview
? mentionInsertion(
value,
sessionDragPreview.mention.name,
sessionDragPreview.start,
sessionDragPreview.end,
)
: null;
const displayMentionSegments = sessionDragInsertion && sessionDragPreview
2026-08-18 18:28:19 +08:00
? splitCapabilityMentionSegments(
sessionDragInsertion.value,
cliApps,
mcpPresets,
sessionMentionCatalog,
2026-08-18 18:28:19 +08:00
)
: mentionInput.segments;
2026-08-18 18:28:19 +08:00
const activeSessionMentions = useMemo(() => {
const seen = new Set<string>();
return mentionSegments.flatMap((segment) => {
if (segment.kind !== "session" || seen.has(segment.mention.session_key)) return [];
seen.add(segment.mention.session_key);
return [segment.mention];
});
2026-08-18 18:28:19 +08:00
}, [mentionSegments]);
useLayoutEffect(() => {
// Pin resolved identities so a catalog refresh cannot retarget an existing reference.
if (activeSessionMentions.length !== boundSessionMentions.length
|| activeSessionMentions.some((mention, index) => mention !== boundSessionMentions[index])) {
setBoundSessionMentions(activeSessionMentions);
}
}, [activeSessionMentions, boundSessionMentions]);
useLayoutEffect(() => {
if (!draftKey || !draftStore || !draftAttachmentsReady) return;
if (!draftText && images.length === 0 && !quotedContext) {
draftStore.delete(draftKey);
return;
}
draftStore.set(draftKey, {
text: draftText,
attachments: images.flatMap((image): ComposerDraft["attachments"] => (
image.local ? [image.local] : image.file instanceof File ? [image.file] : []
)),
sessionMentions: activeSessionMentions,
quotedContext,
}, persistDraft);
}, [activeSessionMentions, draftAttachmentsReady, draftKey, draftStore, images, persistDraft, quotedContext, draftText]);
const insertableSessionMentions = useMemo(() => availableSessionMentions.filter((mention) => {
const bound = activeSessionMentions.find(
(active) => active.name.toLowerCase() === mention.name.toLowerCase(),
);
return (!bound || bound.session_key === mention.session_key)
&& (activeSessionMentions.length < SESSION_MENTIONS_LIMIT
|| activeSessionMentions.some((active) => active.session_key === mention.session_key));
}), [activeSessionMentions, availableSessionMentions]);
const filteredMentionCandidates = useMemo<MentionCandidate[]>(() => {
2026-05-22 22:25:12 +08:00
if (!cliAppMention) return [];
const sessionCandidates: MentionCandidate[] = insertableSessionMentions
2026-08-18 18:28:19 +08:00
.filter((mention) => [
mention.name,
mention.title,
].join(" ").toLowerCase().includes(cliAppMention.query))
2026-08-02 22:04:59 +08:00
.map((mention) => ({
2026-08-18 18:28:19 +08:00
kind: "session",
2026-08-02 22:04:59 +08:00
name: mention.name,
2026-08-18 18:28:19 +08:00
displayName: mention.title || mention.name,
mention,
2026-08-02 22:04:59 +08:00
}));
2026-08-18 18:28:19 +08:00
const sessionNames = new Set(
sessionMentionCatalog.map((mention) => mention.name.toLowerCase()),
2026-08-18 18:28:19 +08:00
);
const cliCandidates: MentionCandidate[] = cliApps
2026-05-22 22:25:12 +08:00
.filter((app) => app.installed)
2026-08-18 18:28:19 +08:00
.filter((app) => !sessionNames.has(app.name.toLowerCase()))
2026-05-22 22:25:12 +08:00
.filter((app) => {
const haystack = [
app.name,
app.display_name,
app.category,
app.description,
app.entry_point,
].join(" ").toLowerCase();
return haystack.includes(cliAppMention.query);
})
.map((app) => ({
kind: "cli",
name: app.name,
displayName: app.display_name,
brandColor: app.brand_color ?? null,
logoUrl: app.logo_url ?? null,
initials: cliAppInitials(app),
}));
const mcpCandidates: MentionCandidate[] = mcpPresets
.filter((preset) => preset.installed && preset.configured)
2026-08-18 18:28:19 +08:00
.filter((preset) => !sessionNames.has(preset.name.toLowerCase()))
.filter((preset) => {
const haystack = [
preset.name,
preset.display_name,
preset.category,
preset.description,
preset.transport,
].join(" ").toLowerCase();
return haystack.includes(cliAppMention.query);
})
.map((preset) => ({
kind: "mcp",
name: preset.name,
displayName: preset.display_name,
brandColor: preset.brand_color ?? null,
logoUrl: preset.logo_url ?? null,
initials: mcpPresetInitials(preset),
}));
const groups = [
2026-08-18 18:28:19 +08:00
{ candidates: sessionCandidates, reserved: 4 },
{ candidates: cliCandidates, reserved: 2 },
{ candidates: mcpCandidates, reserved: 2 },
];
let remaining = 8;
const counts = groups.map(({ candidates, reserved }) => {
const count = Math.min(candidates.length, reserved);
remaining -= count;
return count;
});
for (const index of [0, 1, 2]) {
const extra = Math.min(remaining, groups[index].candidates.length - counts[index]);
counts[index] += extra;
remaining -= extra;
}
return groups.flatMap(({ candidates }, index) => candidates.slice(0, counts[index]));
}, [cliAppMention, cliApps, insertableSessionMentions, mcpPresets, sessionMentionCatalog]);
2026-05-22 22:25:12 +08:00
const showCliAppMenu = filteredMentionCandidates.length > 0;
const showAnyPalette = showSlashMenu || showSkillMenu || showCliAppMenu;
const inlineSegments = useMemo(
() => isUserShell ? displayMentionSegments : withSkillReferences(displayMentionSegments),
[displayMentionSegments, isUserShell],
2026-05-22 22:25:12 +08:00
);
const slashCommand = matchingSlashCommand(sessionDragInsertion?.value ?? draftText, slashCommands);
const hasInlineDecorations = isUserShell || slashCommand !== null || inlineSegments.some((segment) => segment.kind !== "text");
2026-05-22 22:25:12 +08:00
const activeCliMentionApps = useMemo(() => {
const seen = new Set<string>();
return mentionSegments.flatMap((segment) => {
if (segment.kind !== "cli" || seen.has(segment.app.name)) return [];
seen.add(segment.app.name);
return [segment.app];
});
}, [mentionSegments]);
const activeMcpPresetMentions = useMemo(() => {
const seen = new Set<string>();
return mentionSegments.flatMap((segment) => {
if (segment.kind !== "mcp" || seen.has(segment.preset.name)) return [];
seen.add(segment.preset.name);
return [segment.preset];
});
}, [mentionSegments]);
const [slashPaletteLayout, setSlashPaletteLayout] = useState<SlashPaletteLayout>({
placement: "above",
maxHeight: SLASH_PALETTE_MAX_HEIGHT_PX,
});
2026-05-06 15:54:15 +00:00
const activeCommandCount = showSkillMenu ? filteredSkills.length : filteredSlashCommands.length;
2026-05-06 15:54:15 +00:00
useEffect(() => {
setSelectedCommandIndex(0);
}, [skillQuery?.text, slashQuery]);
2026-05-06 15:54:15 +00:00
2026-05-22 22:25:12 +08:00
useEffect(() => {
setSelectedCliAppIndex(0);
2026-08-18 18:28:19 +08:00
}, [cliAppMention?.query]);
2026-05-22 22:25:12 +08:00
2026-05-06 15:54:15 +00:00
useEffect(() => {
if (selectedCommandIndex >= activeCommandCount) {
2026-05-06 15:54:15 +00:00
setSelectedCommandIndex(0);
}
}, [activeCommandCount, selectedCommandIndex]);
2026-05-06 15:54:15 +00:00
useEffect(() => {
if (selectedCliAppIndex >= filteredMentionCandidates.length) {
2026-05-22 22:25:12 +08:00
setSelectedCliAppIndex(0);
}
}, [filteredMentionCandidates.length, selectedCliAppIndex]);
2026-05-22 22:25:12 +08:00
useEffect(() => {
if (!showAnyPalette) return;
const dismissOnPointerDown = (event: PointerEvent) => {
const target = event.target;
if (target instanceof Node && formRef.current?.contains(target)) return;
setSlashMenuDismissed(true);
2026-05-22 22:25:12 +08:00
setCliAppMenuDismissed(true);
};
document.addEventListener("pointerdown", dismissOnPointerDown, true);
return () => {
document.removeEventListener("pointerdown", dismissOnPointerDown, true);
};
2026-05-22 22:25:12 +08:00
}, [showAnyPalette]);
useLayoutEffect(() => {
2026-05-22 22:25:12 +08:00
if (!showAnyPalette) return;
const updateLayout = () => {
const form = formRef.current;
if (!form) return;
const rect = form.getBoundingClientRect();
if (rect.width === 0 && rect.height === 0) return;
const bounds = getVisibleBounds(form);
const spaceAbove = Math.max(0, rect.top - bounds.top - SLASH_PALETTE_GAP_PX);
const spaceBelow = Math.max(0, bounds.bottom - rect.bottom - SLASH_PALETTE_GAP_PX);
// A landscape keyboard can leave less height than one input and option.
// Use the available width instead of clipping an absolute menu in the
// short viewport's scrollable composer footer.
const beside = rect.width >= 640
&& !!form.closest("#root.short-visual-viewport");
const placement: SlashPalettePlacement =
beside ? "beside" : spaceAbove >= SLASH_PALETTE_MIN_HEIGHT_PX || spaceAbove >= spaceBelow
? "above"
: "below";
const available = beside
? Math.max(0, bounds.bottom - bounds.top)
: placement === "above" ? spaceAbove : spaceBelow;
const maxHeight = Math.min(SLASH_PALETTE_MAX_HEIGHT_PX, available);
setSlashPaletteLayout((current) =>
current.placement === placement && current.maxHeight === maxHeight
? current
: { placement, maxHeight },
);
};
updateLayout();
const viewport = window.visualViewport;
viewport?.addEventListener("resize", updateLayout);
viewport?.addEventListener("scroll", updateLayout);
window.addEventListener("resize", updateLayout);
document.addEventListener("scroll", updateLayout, true);
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(updateLayout);
if (formRef.current) observer?.observe(formRef.current);
return () => {
observer?.disconnect();
viewport?.removeEventListener("resize", updateLayout);
viewport?.removeEventListener("scroll", updateLayout);
window.removeEventListener("resize", updateLayout);
document.removeEventListener("scroll", updateLayout, true);
};
}, [filteredMentionCandidates.length, filteredSkills.length, filteredSlashCommands.length, showAnyPalette]);
useLayoutEffect(() => {
if (mentionInput.isComposing) return;
if (!mentionInput.value) setDraftExpanded(false);
measureDraft();
}, [compactControls, measureDraft, mentionInput.isComposing, mentionInput.value]);
useEffect(() => {
// The parent projects typography tokens in its layout effect; measure after it.
measureDraft();
}, [readingTextSize, customReadingTextSize, measureDraft]);
const appendTranscription = useCallback((text: string) => {
const transcript = text.trim();
if (!transcript) return;
2026-08-18 18:28:19 +08:00
setValue((current) => {
if (!current.trim()) return transcript;
const separator = /[\s\n]$/.test(current) ? "" : " ";
return `${current}${separator}${transcript}`;
});
setSlashMenuDismissed(false);
setCliAppMenuDismissed(false);
focusTextarea();
}, [focusTextarea]);
const {
recorder: voiceRecorder, setupError: voiceSetupError, clearSetupError,
shortcutLabel: voiceShortcutLabel, shortcutAria, canSendQueuedPrompt,
} = useComposerVoiceInput({
disabled: interactionDisabled, onTranscribeAudio, onTranscript: appendTranscription,
wantsWav: transcriptionProvider === "xiaomi_mimo",
});
// Runs before paint so switching sessions never flashes stale draft text.
useLayoutEffect(() => {
if (previousPendingQueueKeyRef.current === pendingQueueKey) return;
previousPendingQueueKeyRef.current = pendingQueueKey;
setValue("");
setInlineError(null);
clearSetupError();
setSlashMenuDismissed(false);
setCliAppMenuDismissed(false);
setCursorPosition(0);
clear();
}, [clear, clearSetupError, pendingQueueKey]);
const handleStop = useCallback(() => {
pauseQueue();
onStop?.();
}, [onStop, pauseQueue]);
const recordSlashRecent = useCallback((command: string) => {
const nextRecents = [
command,
...recentSlashCommands.filter((item) => item !== command),
].slice(0, SLASH_RECENTS_LIMIT);
setRecentSlashCommands(nextRecents);
storeSlashRecents(nextRecents);
}, [recentSlashCommands]);
const chooseSkill = useCallback(
(skill: SkillPaletteItem) => {
if (skillQuery === null) return;
recordSlashRecent(skill.command);
const suffix = value.slice(skillQuery.end);
const inserted = `${skill.command}${suffix.startsWith(" ") ? "" : " "}`;
const next = `${value.slice(0, skillQuery.start)}${inserted}${suffix}`;
const nextCursor = skillQuery.start + inserted.length;
replaceMentionInput(next, nextCursor);
setSlashMenuDismissed(true);
setCliAppMenuDismissed(false);
setInlineError(null);
focusTextarea();
},
[focusTextarea, recordSlashRecent, replaceMentionInput, skillQuery, value],
);
2026-05-06 15:54:15 +00:00
const chooseSlashCommand = useCallback(
2026-07-01 15:52:34 +08:00
(command: SlashPaletteCommand) => {
2026-05-24 20:56:07 +08:00
if (command.command === "/stop" && isStreaming && onStop) {
handleStop();
2026-08-18 18:28:19 +08:00
setValue("");
2026-05-24 20:56:07 +08:00
setSlashMenuDismissed(true);
setCliAppMenuDismissed(false);
setInlineError(null);
focusTextarea();
2026-05-24 20:56:07 +08:00
return;
}
recordSlashRecent(command.command);
setValue(command.argHint ? `${command.command} ` : command.command);
2026-05-06 15:54:15 +00:00
setSlashMenuDismissed(true);
2026-05-22 22:25:12 +08:00
setCliAppMenuDismissed(false);
2026-05-06 15:54:15 +00:00
setInlineError(null);
focusTextarea();
2026-05-06 15:54:15 +00:00
},
[focusTextarea, handleStop, isStreaming, onStop, recordSlashRecent],
2026-05-06 15:54:15 +00:00
);
const insertMention = useCallback(
(name: string, start: number, end: number) => {
const insertion = mentionInsertion(value, name, start, end);
replaceMentionInput(insertion.value, insertion.cursor);
2026-05-22 22:25:12 +08:00
setCliAppMenuDismissed(true);
setSlashMenuDismissed(false);
setInlineError(null);
focusTextarea();
2026-05-22 22:25:12 +08:00
},
[replaceMentionInput, focusTextarea, value],
2026-05-22 22:25:12 +08:00
);
const chooseMentionCandidate = useCallback(
(candidate: MentionCandidate) => {
2026-08-18 18:28:19 +08:00
if (!cliAppMention) return;
insertMention(candidate.name, cliAppMention.start, cliAppMention.end);
},
[cliAppMention, insertMention],
);
const handleSessionDrop = useCallback((event: React.DragEvent) => {
if (!hasDraggedSession(event.dataTransfer)) return false;
event.preventDefault();
clearDraggedSession();
const preview = sessionDragPreview;
setSessionDragPreview(null);
if (interactionDisabled) return true;
const sessionKey = readDraggedSession(event.dataTransfer);
const mention = insertableSessionMentions.find(
(candidate) => candidate.session_key === (sessionKey ?? preview?.mention.session_key),
);
if (!mention) return true;
const caret = preview?.start ?? rawSelection().start;
insertMention(mention.name, caret, preview?.end ?? rawSelection().end);
return true;
}, [insertableSessionMentions, insertMention, interactionDisabled, rawSelection, sessionDragPreview]);
const previewSessionDrop = useCallback((event: React.DragEvent) => {
if (!hasDraggedSession(event.dataTransfer)) return false;
if (interactionDisabled) {
2026-08-06 14:38:50 +08:00
event.dataTransfer.dropEffect = "none";
setSessionDragPreview(null);
return true;
}
const sessionKey = readDraggedSession(event.dataTransfer);
const mention = insertableSessionMentions.find(
(candidate) => candidate.session_key === sessionKey,
);
if (!mention) {
2026-08-06 14:38:50 +08:00
event.dataTransfer.dropEffect = "none";
setSessionDragPreview(null);
return true;
}
2026-08-06 14:38:50 +08:00
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
const { start, end } = rawSelection();
setSessionDragPreview((current) => (
current?.mention.session_key === mention.session_key
&& current.start === start
&& current.end === end
? current
: { mention, start, end }
));
return true;
}, [insertableSessionMentions, interactionDisabled, rawSelection]);
useEffect(() => {
if (!sessionDragPreview) return;
const clearPreview = () => {
clearDraggedSession();
setSessionDragPreview(null);
};
document.addEventListener("dragend", clearPreview);
return () => document.removeEventListener("dragend", clearPreview);
}, [sessionDragPreview]);
const clearComposerText = useCallback((restoreFocus = true) => {
2026-08-18 18:28:19 +08:00
setValue("");
setInlineError(null);
setSlashMenuDismissed(false);
setCliAppMenuDismissed(false);
setCursorPosition(0);
if (restoreFocus) focusTextarea();
}, [focusTextarea]);
const collectGuidancePrompt = useCallback(() => collectQueuedPrompt({
text: value,
images: readyImagesToQueuedImages(readyImages),
...(normalizedQuotedContext ? { quotedContext: normalizedQuotedContext } : {}),
sessionMentions: activeSessionMentions,
}), [activeSessionMentions, collectQueuedPrompt, normalizedQuotedContext, readyImages, value]);
const queueGuidancePrompt = useCallback(() => {
if (!canQueueGuidance) return;
if (!enqueueQueuedPrompt(collectGuidancePrompt())) return;
clear();
clearComposerText();
onQuotedContextChange?.(null);
}, [canQueueGuidance, clear, clearComposerText, collectGuidancePrompt, onQuotedContextChange, enqueueQueuedPrompt]);
const removeQueuedPrompt = useCallback(() => {
clearQueuedPrompt();
requestAnimationFrame(() => textareaRef.current?.focus());
}, [clearQueuedPrompt]);
const editQueuedPrompt = useCallback((pending: QueuedPromptContent) => {
const prompt = hasComposerContent || normalizedQuotedContext ? collectGuidancePrompt() : pending;
clearQueuedPrompt();
replaceMentionInput(prompt.text, prompt.text.length);
setBoundSessionMentions(prompt.sessionMentions ?? []);
setInlineError(null);
setSlashMenuDismissed(false);
setCliAppMenuDismissed(false);
onQuotedContextChange?.(prompt.quotedContext ?? null);
if (prompt.images?.length) {
restoreReadyImages(prompt.images as RestoredReadyImage[]);
} else {
clear();
}
focusTextarea();
}, [clear, collectGuidancePrompt, hasComposerContent, normalizedQuotedContext, onQuotedContextChange, replaceMentionInput, focusTextarea, restoreReadyImages, clearQueuedPrompt]);
const submit = useCallback(() => {
if (requiresModelSetup) {
if (hasComposerContent) {
setModelSetupAttentionRequest((request) => request + 1);
}
return;
}
if (!canSend) return;
if (isUserShell && (images.length > 0 || normalizedQuotedContext)) {
setInlineError(t("thread.composer.shell.removeContext"));
return;
}
const trimmed = value.trim();
const content = trimmed;
if (utf8Bytes(formatQuotedUserMessage(content, normalizedQuotedContext)) > maxTextBytes) {
setInlineError(textTooLargeMessage());
return;
}
// Keep self-contained local previews across drafts and optimistic bubbles.
// The client decodes these to HTTP binary; WS messages contain only refs.
const payload = queuedImagesToSendImages(readyImagesToQueuedImages(readyImages));
2026-05-22 22:25:12 +08:00
const attachedCliApps = activeCliMentionApps.map(cliAppMentionPayload);
const attachedMcpPresets = activeMcpPresetMentions.map(mcpPresetMentionPayload);
const options: SendOptions | undefined = !isUserShell && (
2026-08-02 22:04:59 +08:00
attachedCliApps.length > 0
|| attachedMcpPresets.length > 0
|| activeSessionMentions.length > 0
|| normalizedQuotedContext
)
2026-05-22 22:25:12 +08:00
? {
...(attachedCliApps.length > 0 ? { cliApps: attachedCliApps } : {}),
...(attachedMcpPresets.length > 0 ? { mcpPresets: attachedMcpPresets } : {}),
2026-08-02 22:04:59 +08:00
...(activeSessionMentions.length > 0
? { sessionMentions: activeSessionMentions }
: {}),
...(normalizedQuotedContext ? { quotedContext: normalizedQuotedContext } : {}),
2026-05-22 22:25:12 +08:00
}
: undefined;
const hasPlainTextCommandPayload =
payload === undefined
&& attachedCliApps.length === 0
2026-08-02 22:04:59 +08:00
&& attachedMcpPresets.length === 0
2026-08-18 18:28:19 +08:00
&& activeSessionMentions.length === 0;
const slashLifecycle = hasPlainTextCommandPayload
? slashCommandLifecycle(content, slashCommands)
: null;
if (
slashLifecycle === "stop_active_turn"
&& isStreaming
&& onStop
) {
handleStop();
clear();
clearComposerText();
onQuotedContextChange?.(null);
return;
}
const isSideChannel = isUserShell || isSideChannelLifecycle(slashLifecycle);
const finalizeActiveTurn =
slashLifecycle === "finalize_active_turn";
if (!isUserShell && !slashLifecycle) {
const prompt = collectGuidancePrompt();
if (!validatePrompt(prompt)) return;
if (queuedPrompt) {
sendQueuedPrompt(prompt, options);
if (draftKey) draftStore?.delete(draftKey);
clear();
clearComposerText(!hasTouchPrimaryPointer);
onQuotedContextChange?.(null);
return;
}
}
const submittedDraft = draftKey ? draftStore?.get(draftKey) : undefined;
const finishSend = () => {
// A pending send can finish after this composer unmounts and a newer draft is started.
if (draftKey && draftStore && draftStore.get(draftKey) !== submittedDraft) return;
if (draftKey) draftStore?.delete(draftKey);
if (hasTouchPrimaryPointer) textareaRef.current?.blur();
if ((!isStreaming && !isUserShell) || finalizeActiveTurn) clearQueuedPrompt();
// Bubble owns the data URL copy; safe to revoke every staged blob
// preview here without affecting the rendered message.
clear();
clearComposerText(!hasTouchPrimaryPointer);
onQuotedContextChange?.(null);
};
const result = onSend(
content,
payload,
isSideChannel
? {
...options,
sideChannel: true,
...(isUserShell ? { userShell: true } : {}),
...(finalizeActiveTurn ? { finalizeActiveTurn } : {}),
}
: isStreaming ? { ...options, continueActiveTurn: true } : options,
);
if (result instanceof Promise) {
setSendPending(true);
void result
.then((accepted) => {
if (accepted !== false) finishSend();
})
.catch((error: unknown) => {
setInlineError(error instanceof Error ? error.message : "Failed to send message");
})
.finally(() => setSendPending(false));
return;
}
if (result !== false) finishSend();
}, [
activeCliMentionApps,
activeMcpPresetMentions,
2026-08-02 22:04:59 +08:00
activeSessionMentions,
canSend,
draftKey,
draftStore,
clear,
clearComposerText,
collectGuidancePrompt,
queuedPrompt,
validatePrompt,
sendQueuedPrompt,
clearQueuedPrompt,
hasTouchPrimaryPointer,
hasComposerContent,
handleStop,
images.length,
isStreaming,
isUserShell,
maxTextBytes,
requiresModelSetup,
onSend,
onStop,
onQuotedContextChange,
normalizedQuotedContext,
readyImages,
slashCommands,
t,
textTooLargeMessage,
value,
]);
const onKeyDown = (e: ReactKeyboardEvent<HTMLTextAreaElement>) => {
mentionInput.onKeyDown(e);
if (e.defaultPrevented || e.nativeEvent.isComposing || mentionInput.isComposing) return;
2026-05-22 22:25:12 +08:00
if (showCliAppMenu) {
if (e.key === "ArrowDown") {
e.preventDefault();
setSelectedCliAppIndex((idx) => (idx + 1) % filteredMentionCandidates.length);
2026-05-22 22:25:12 +08:00
return;
}
if (e.key === "ArrowUp") {
e.preventDefault();
setSelectedCliAppIndex(
(idx) => (idx - 1 + filteredMentionCandidates.length) % filteredMentionCandidates.length,
2026-05-22 22:25:12 +08:00
);
return;
}
if (e.key === "Tab" || (e.key === "Enter" && !e.shiftKey)) {
e.preventDefault();
chooseMentionCandidate(filteredMentionCandidates[selectedCliAppIndex]);
2026-05-22 22:25:12 +08:00
return;
}
if (e.key === "Escape") {
e.preventDefault();
setCliAppMenuDismissed(true);
return;
}
}
if (showSkillMenu) {
if (e.key === "ArrowDown") {
e.preventDefault();
setSelectedCommandIndex((idx) => (idx + 1) % filteredSkills.length);
return;
}
if (e.key === "ArrowUp") {
e.preventDefault();
setSelectedCommandIndex(
(idx) => (idx - 1 + filteredSkills.length) % filteredSkills.length,
);
return;
}
if (e.key === "Tab" || (e.key === "Enter" && !e.shiftKey)) {
e.preventDefault();
chooseSkill(filteredSkills[selectedCommandIndex]);
return;
}
if (e.key === "Escape") {
e.preventDefault();
setSlashMenuDismissed(true);
return;
}
}
2026-05-06 15:54:15 +00:00
if (showSlashMenu) {
if (e.key === "ArrowDown") {
e.preventDefault();
setSelectedCommandIndex((idx) => (idx + 1) % filteredSlashCommands.length);
return;
}
if (e.key === "ArrowUp") {
e.preventDefault();
setSelectedCommandIndex(
(idx) => (idx - 1 + filteredSlashCommands.length) % filteredSlashCommands.length,
);
return;
}
if (e.key === "Tab" || (e.key === "Enter" && !e.shiftKey)) {
e.preventDefault();
chooseSlashCommand(filteredSlashCommands[selectedCommandIndex]);
return;
}
if (e.key === "Escape") {
e.preventDefault();
setSlashMenuDismissed(true);
return;
}
}
// Touch keyboards: a plain Enter inserts a newline; sending stays on the
// send button. The select-on-Enter menu branches above take precedence.
if (
e.key === "Enter"
&& !e.shiftKey
&& !e.altKey
&& !e.ctrlKey
&& !e.metaKey
&& !e.nativeEvent.isComposing
&& hasCoarsePointer
) {
return;
}
2026-08-18 18:28:19 +08:00
if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
e.preventDefault();
if (canQueueGuidance) {
if (!e.repeat) queueGuidancePrompt();
return;
}
// Empty Enter explicitly sends the visible pending message, including restored drafts.
if (
queuedPrompt
&& value.length === 0
&& images.length === 0
&& !e.altKey
&& !e.ctrlKey
&& !e.metaKey
) {
if (!e.repeat && canSendQueuedPrompt()) {
sendQueuedPrompt(queuedPrompt);
}
return;
}
submit();
}
};
const onFilePick: React.ChangeEventHandler<HTMLInputElement> = (e) => {
const files = Array.from(e.target.files ?? []);
e.target.value = "";
addFiles(files);
};
const removeChip = useCallback(
(id: string) => {
const { nextFocusId } = remove(id);
setInlineError(null);
requestAnimationFrame(() => {
const el = nextFocusId ? chipRefs.current.get(nextFocusId) : null;
if (el) {
el.focus();
} else {
textareaRef.current?.focus();
}
});
},
[remove],
);
const onChipKey = useCallback(
(id: string) => (e: ReactKeyboardEvent<HTMLButtonElement>) => {
if (
e.key === "Delete" ||
e.key === "Backspace" ||
e.key === "Enter" ||
e.key === " "
) {
e.preventDefault();
removeChip(id);
}
},
[removeChip],
);
const attachButtonDisabled = interactionDisabled || full;
const showVoiceButton = Boolean(onTranscribeAudio) && (
voiceRecorder.state !== "idle"
|| (!hasComposerContent && images.length === 0 && !isStreaming && !modelNeedsSetup)
);
const voiceRecordingStatusLabel = t("thread.composer.voice.recordingStatus", {
time: voiceRecorder.elapsedLabel,
defaultValue: `Recording ${voiceRecorder.elapsedLabel}`,
});
const voiceButtonLabel =
voiceRecorder.state === "recording"
? t("thread.composer.voice.stop")
: voiceRecorder.state === "transcribing"
? t("thread.composer.voice.transcribing")
: t("thread.composer.tools.voice");
const voiceButtonTooltip =
voiceRecorder.state === "recording"
? t("thread.composer.voice.stop")
: voiceRecorder.state === "transcribing"
? t("thread.composer.voice.transcribing")
: t("thread.composer.voice.hint");
// Touch users need an explicit send action; keep Stop while sending is unavailable.
const showStopButton = isStreaming && !!onStop && !canSend;
const actionState: ComposerActionState = showVoiceButton
? voiceRecorder.state === "transcribing" ? "busy" : voiceRecorder.isRecording ? "recording" : "voice"
: showStopButton ? "stop" : requiresModelSetup ? "setup" : canSend || !isStreaming ? "send" : "busy";
const relaxedHeroInput = isHero && images.length === 0 && !isStreaming;
const compactIdle = compactWhenIdle && !compactControls && !isHero && !composerFocused
&& value.length === 0 && images.length === 0 && !inlineError && !(onTranscribeAudio && voiceSetupError)
&& !normalizedQuotedContext && !queuedPrompt
&& !isDragging && !sessionDragPreview && !voiceRecorder.isRecording && !showProjectPicker;
useLayoutEffect(() => {
if (!compactWhenIdle || compactControls) return;
const form = formRef.current;
const primary = form?.querySelector<HTMLElement>(".thread-composer-footer-primary");
const actions = form?.querySelector<HTMLElement>(".thread-composer-footer-actions");
if (!form || !primary || !actions) return;
const controls = Array.from(primary.children).filter((child) => getComputedStyle(child).display !== "none");
// Reserve the real toolbar width, including translated model labels, while
// the footer slides beneath the input. Neither control is remounted.
const measure = () => {
const gap = parseFloat(getComputedStyle(primary).columnGap) || 0;
const width = controls.reduce((sum, child) => sum + child.getBoundingClientRect().width, 0)
+ Math.max(0, controls.length - 1) * gap + actions.getBoundingClientRect().width;
form.style.setProperty("--composer-compact-controls-width", `${width}px`);
};
measure();
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);
controls.forEach((control) => observer?.observe(control));
observer?.observe(actions);
return () => observer?.disconnect();
}, [compactControls, compactWhenIdle, modelLabel, voiceRecorder.isRecording, workspaceScope]);
const accessControl = workspaceScope && !workspaceControlsHidden ? (
<WorkspaceAccessMenu
scope={workspaceScope}
disabled={interactionDisabled || workspaceScopeDisabled}
onChange={onWorkspaceScopeChange}
hintBoundaryRef={formRef}
/>
) : null;
const workspaceControl = showProjectPicker ? (
<WorkspaceProjectPicker
layoutAnchor={workspacePickerLayoutAnchor}
disabled={interactionDisabled || workspaceScopeDisabled}
scope={workspaceScope}
defaultScope={workspaceDefaultScope}
controls={workspaceControls}
error={workspaceError}
onFavoriteProject={onFavoriteWorkspaceProject}
onResolveProject={onResolveWorkspaceProject}
onLoadProjects={onLoadWorkspaceProjects}
onBrowseDirectories={onBrowseWorkspaceDirectories}
onChange={onWorkspaceScopeChange}
/>
) : null;
const modelControl = modelLabel && !voiceRecorder.isRecording ? (
<ModelPresetBadge
label={modelLabel}
modelDetail={modelDetail}
modelPreset={modelPreset}
modelPresets={modelPresets}
modelOptionsControl={modelOptionsControl}
onMenuOpenChange={onModelMenuOpenChange}
onPresetChange={onModelPresetChange}
onManageModels={onManageModels}
onRequestComposerFocus={() => textareaRef.current?.focus()}
provider={modelProvider}
providerLabel={modelProviderLabel}
needsSetup={modelNeedsSetup}
attentionRequest={modelSetupAttentionRequest}
isHero={isHero && !compactControls}
onClick={modelNeedsSetup ? onModelBadgeClick : undefined}
/>
) : null;
const usageInMeta = mobileWorkspaceControls || compactControls;
const usageControl = !voiceRecorder.isRecording
? renderContextUsage?.({ showLabel: usageInMeta, compactLabel: mobileWorkspaceControls }) : null;
2026-05-22 22:25:12 +08:00
const inputTextClasses = cn(
// The native input and its reference overlay must wrap and space text alike.
"inset-scrollbar w-full resize-none bg-transparent text-composer [scrollbar-gutter:stable] [text-autospace:no-autospace]",
compactControls
? "min-h-[52px] px-4 pb-2 pt-3"
: isHero
? cn(
"min-h-[78px] px-4 sm:px-5",
relaxedHeroInput ? "pb-2 pt-[27px]" : "pb-1.5 pt-4",
)
: "min-h-[50px] px-3.5 pb-1.5 pt-3 sm:px-4",
2026-05-22 22:25:12 +08:00
);
const paletteBeside = showAnyPalette && slashPaletteLayout.placement === "beside";
const draftResizeLabel = t(draftExpanded ? "thread.composer.collapseDraft" : "thread.composer.expandDraft");
const toggleDraftSize = () => {
const input = textareaRef.current;
if (!input) return;
const followCaret = draftExpanded && input.selectionStart === input.value.length
&& input.scrollHeight - input.clientHeight - input.scrollTop <= 1;
setDraftExpanded(!draftExpanded);
input.focus({ preventScroll: true });
if (followCaret) requestAnimationFrame(() => { input.scrollTop = input.scrollHeight; });
};
return (
<form
ref={formRef}
data-compact-controls={compactControls ? "true" : undefined}
data-palette-beside={paletteBeside || undefined}
onFocusCapture={() => {
if (!compactWhenIdle) return;
// Portaled model controls belong to this composer too: keep its layout
// stable while moving between the input, toolbar, and model picker.
if (blurFrame.current !== null) cancelAnimationFrame(blurFrame.current);
}}
onBlurCapture={() => {
if (!compactWhenIdle) return;
if (blurFrame.current !== null) cancelAnimationFrame(blurFrame.current);
blurFrame.current = requestAnimationFrame(() => {
blurFrame.current = null;
setComposerFocused(false);
});
}}
onSubmit={(e) => {
e.preventDefault();
submit();
}}
onDragEnter={(event) => {
if (!previewSessionDrop(event)) onDragEnter(event);
}}
onDragOver={(event) => {
if (!previewSessionDrop(event)) onDragOver(event);
}}
onDragLeave={(event) => {
if (!hasDraggedSession(event.dataTransfer)) {
onDragLeave(event);
return;
}
const nextTarget = event.relatedTarget;
if (!(nextTarget instanceof Node) || !event.currentTarget.contains(nextTarget)) {
setSessionDragPreview(null);
}
}}
onDrop={(event) => {
if (!handleSessionDrop(event)) onDrop(event);
}}
className={cn(
"thread-composer-form relative w-full [--composer-action-margin:0px]",
isHero
? "px-0 [--composer-action-size:2rem] [--composer-footer-inset:0.75rem] sm:[--composer-footer-inset:1rem]"
: "px-1 pb-0 pt-1 [--composer-action-size:2.25rem] [--composer-footer-inset:0.625rem] sm:px-0 sm:pb-1.5 sm:[--composer-footer-inset:0.75rem]",
compactWhenIdle && "thread-composer-collapsible-layout",
paletteBeside && "grid grid-cols-2 items-start gap-2 p-0",
)}
>
{showSkillMenu ? (
<SkillPalette
skills={filteredSkills}
query={skillQuery?.text ?? ""}
selectedIndex={selectedCommandIndex}
layout={slashPaletteLayout}
isHero={isHero}
onHover={setSelectedCommandIndex}
onChoose={chooseSkill}
/>
) : showSlashMenu ? (
2026-05-06 15:54:15 +00:00
<SlashCommandPalette
commands={filteredSlashCommands}
query={slashQuery ?? ""}
2026-05-06 15:54:15 +00:00
selectedIndex={selectedCommandIndex}
layout={slashPaletteLayout}
2026-05-06 15:54:15 +00:00
isHero={isHero}
onHover={setSelectedCommandIndex}
onChoose={chooseSlashCommand}
/>
) : null}
2026-05-22 22:25:12 +08:00
{showCliAppMenu ? (
<CliAppMentionPalette
candidates={filteredMentionCandidates}
query={cliAppMention?.query ?? ""}
2026-05-22 22:25:12 +08:00
selectedIndex={selectedCliAppIndex}
layout={slashPaletteLayout}
isHero={isHero}
onHover={setSelectedCliAppIndex}
onChoose={chooseMentionCandidate}
2026-05-22 22:25:12 +08:00
/>
) : null}
<div
2026-08-06 18:29:04 +08:00
ref={surfaceRef}
data-compact={compactIdle || undefined}
style={paletteBeside ? { maxHeight: slashPaletteLayout.maxHeight, overflowY: "auto" } : undefined}
className={cn(
"thread-composer-surface group/composer relative mx-auto flex w-full flex-col overflow-visible bg-card",
paletteBeside && "col-start-1 row-start-1",
isHero
? "max-w-[var(--composer-content-width,58rem)] rounded-prominent"
: "max-w-[var(--composer-content-width,49.5rem)] rounded-panel",
compactWhenIdle && "thread-composer-collapsible transition-colors motion-reduce:transition-none",
interactionDisabled && "opacity-60",
sessionDragPreview && "ring-1 ring-primary/25",
isDragging && "ring-2 ring-primary/40 motion-reduce:ring-0 motion-reduce:border-primary",
)}
>
{queuedPrompt ? (
<QueuedPromptPreview
prompt={queuedPrompt}
disabled={interactionDisabled}
editDisabled={encoding || hasErrors}
label={t("thread.composer.queued.label")}
guideLabel={t("thread.composer.queued.guide")}
deleteLabel={t("thread.composer.queued.delete")}
editLabel={t("thread.composer.queued.edit")}
onGuide={() => sendQueuedPrompt(queuedPrompt)}
onDelete={removeQueuedPrompt}
onEdit={() => editQueuedPrompt(queuedPrompt)}
/>
) : null}
{images.length > 0 ? (
<div
className="flex flex-wrap items-start gap-2 px-3 pt-3"
aria-label={t("thread.composer.attachImage")}
>
{images.map((img) => (
<AttachmentChip
key={img.id}
image={img}
labelRemove={t("thread.composer.remove")}
labelEncoding={t("thread.composer.encoding")}
normalizedHint={(orig, current) =>
t("thread.composer.normalizedSizeHint", {
orig: formatBytes(orig),
current: formatBytes(current),
})
}
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) => {
if (el) chipRefs.current.set(img.id, el);
else chipRefs.current.delete(img.id);
}}
/>
))}
</div>
) : null}
{normalizedQuotedContext ? (
<div
className="mx-3 mt-3 flex min-w-0 items-start gap-2 border-l-2 border-muted-foreground/25 pl-3 pr-1 text-muted-foreground"
aria-label={t("thread.composer.quotedContext")}
>
<Quote className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden />
<p className="line-clamp-2 min-w-0 flex-1 text-reading-small">
{normalizedQuotedContext}
</p>
<button
type="button"
className="touch-target -mr-1 inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label={t("thread.composer.removeQuotedContext")}
onClick={() => {
onQuotedContextChange?.(null);
requestAnimationFrame(() => textareaRef.current?.focus());
}}
>
<X className="h-3.5 w-3.5" aria-hidden />
</button>
</div>
) : null}
<div
className="thread-composer-input relative min-w-0"
data-expandable={expandable || undefined}
data-expanded={draftExpanded || undefined}
data-overflowing={draftOverflows || undefined}
>
{placeholder === undefined ? (
<span className="pointer-events-none invisible absolute h-0 w-0 overflow-hidden">
<span ref={placeholderMeasureRef} aria-hidden className="inline-block whitespace-pre text-composer [text-autospace:no-autospace]">{resolvedPlaceholder}</span>
</span>
) : null}
{hasInlineDecorations ? (
<ComposerInlineReferenceOverlay
overlayRef={mentionOverlayRef}
segments={inlineSegments}
slashCommand={slashCommand?.command ?? null}
2026-05-22 22:25:12 +08:00
isHero={isHero}
isComposing={mentionInput.isComposing}
2026-05-22 22:25:12 +08:00
className={inputTextClasses}
ghostRange={sessionDragInsertion
? { start: sessionDragInsertion.tokenStart, end: sessionDragInsertion.tokenEnd }
: null}
2026-05-22 22:25:12 +08:00
/>
) : null}
<textarea
id={textareaId}
ref={textareaRef}
value={mentionInput.value}
onFocus={() => {
if (compactWhenIdle) setComposerFocused(true);
}}
onChange={mentionInput.onChange}
onCompositionStart={mentionInput.onCompositionStart}
onCompositionEnd={mentionInput.onCompositionEnd}
onKeyDown={onKeyDown}
onKeyUp={() => setCursorPosition(rawSelection().start)}
onSelect={() => setCursorPosition(rawSelection().start)}
onClick={() => setCursorPosition(rawSelection().start)}
onCopy={mentionInput.onCopy}
onCut={mentionInput.onCut}
onScroll={(e) => {
if (mentionOverlayRef.current) mentionOverlayRef.current.scrollTop = e.currentTarget.scrollTop;
}}
onPaste={onPaste}
rows={1}
enterKeyHint={hasCoarsePointer ? "enter" : undefined}
placeholder={sessionDragPreview ? "" : displayedPlaceholder}
disabled={interactionDisabled}
aria-label={inputAriaLabel ?? t("thread.composer.inputAria")}
aria-description={sessionDragPreview ? undefined : resolvedPlaceholder}
className={cn(
inputTextClasses,
"relative z-10 block caret-foreground placeholder:text-muted-foreground",
"focus:outline-none focus-visible:outline-none",
"disabled:cursor-not-allowed",
hasInlineDecorations && "text-transparent selection:bg-primary/20",
)}
/>
2026-05-22 22:25:12 +08:00
</div>
{inlineError || (onTranscribeAudio && voiceSetupError) ? (
<div role="alert" className="mx-3 mb-1 break-words rounded-md border border-destructive/40 bg-destructive/8 px-2.5 py-1 text-[11.5px] font-medium text-destructive">
{inlineError ?? t(`thread.composer.voiceErrors.${voiceSetupError}`)}
</div>
) : null}
<div
className={cn(
"thread-composer-footer flex flex-nowrap items-center px-[var(--composer-footer-inset)] motion-safe:transition-[padding-bottom] motion-safe:[transition-duration:220ms] motion-safe:ease-in-out",
2026-06-14 16:46:34 +08:00
isHero
2026-07-23 18:18:34 +08:00
? cn(
"gap-x-1.5",
showProjectPicker && compactControls ? "pb-1.5" : "pb-3.5",
2026-07-23 18:18:34 +08:00
)
: "gap-x-2 pb-2",
)}
>
2026-07-23 18:18:34 +08:00
<div
className={cn(
"thread-composer-footer-primary flex min-w-0 flex-1 basis-0 items-center",
isHero ? "gap-1.5" : "gap-2",
)}
>
<input
ref={fileInputRef}
type="file"
accept={ACCEPT_ATTR}
multiple
hidden
onChange={onFilePick}
/>
<Button
type="button"
size="icon"
variant="icon"
disabled={attachButtonDisabled}
aria-label={t("thread.composer.attachImage")}
onClick={() => fileInputRef.current?.click()}
className={cn(
"thread-composer-action thread-composer-round-action touch-target shrink-0 rounded-xl text-muted-foreground hover:text-foreground",
"h-[var(--composer-action-size)] w-[var(--composer-action-size)]",
)}
>
<AttachIcon className="h-3.5 w-3.5" />
</Button>
{!mobileWorkspaceControls ? accessControl : null}
{voiceRecorder.isRecording ? (
<VoiceRecordingMeter
ariaLabel={voiceRecordingStatusLabel}
className="mx-1 flex-1"
elapsedLabel={voiceRecorder.elapsedLabel}
isHero={isHero}
levels={voiceRecorder.levels}
/>
) : null}
</div>
2026-07-23 18:18:34 +08:00
<div
className={cn(
"thread-composer-footer-actions ml-auto flex min-w-0 items-center justify-end",
isHero ? "gap-1.5" : "gap-2",
)}
>
{expandable && (draftExpanded || draftOverflows) ? (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
size="icon"
variant="icon"
disabled={interactionDisabled}
aria-label={draftResizeLabel}
aria-expanded={draftExpanded}
aria-controls={textareaId}
onMouseDown={(event) => event.preventDefault()}
onClick={toggleDraftSize}
className="thread-composer-action thread-composer-round-action touch-target h-[var(--composer-action-size)] w-[var(--composer-action-size)] shrink-0 rounded-xl text-muted-foreground hover:text-foreground"
>
{draftExpanded ? <Minimize2 className="h-3.5 w-3.5" /> : <Maximize2 className="h-3.5 w-3.5" />}
</Button>
</TooltipTrigger>
<TooltipContent>{draftResizeLabel}</TooltipContent>
</Tooltip>
</TooltipProvider>
) : null}
{modelControl}
{!usageInMeta ? usageControl : null}
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
type={showVoiceButton || showStopButton || requiresModelSetup ? "button" : "submit"}
size="icon"
disabled={showVoiceButton ? voiceRecorder.buttonDisabled : showStopButton ? interactionDisabled : !canSend && !canOpenModelSettings}
aria-label={
showVoiceButton
? voiceButtonLabel
: showStopButton
? t("thread.composer.stop")
: requiresModelSetup
? t("thread.composer.configureModel", { defaultValue: "Configure model" })
: isUserShell ? t("thread.composer.shell.run") : t("thread.composer.send")
}
aria-keyshortcuts={showVoiceButton ? shortcutAria : undefined}
onPointerDown={showVoiceButton ? voiceRecorder.beginPress : undefined}
onPointerUp={showVoiceButton ? voiceRecorder.endPress : undefined}
onPointerCancel={showVoiceButton ? voiceRecorder.endPress : undefined}
onClickCapture={event => {
if (!voiceRecorder.consumeSuppressedClick()) return;
event.preventDefault();
event.stopPropagation();
}}
onClick={showVoiceButton ? voiceRecorder.handleClick : showStopButton ? handleStop : requiresModelSetup ? onModelBadgeClick : undefined}
className={cn(
"composer-primary-action thread-composer-action thread-composer-round-action touch-target rounded-full bg-clip-padding",
actionState === "stop"
? "border border-transparent bg-foreground/[0.045] text-foreground/85 hover:bg-foreground/[0.08] hover:text-foreground disabled:text-muted-foreground/50"
: actionState === "voice"
? "border border-transparent bg-foreground/75 text-background hover:bg-foreground/[0.85] hover:text-background disabled:bg-foreground/[0.12] disabled:text-muted-foreground"
: "border border-transparent bg-foreground text-background hover:bg-foreground/90 hover:text-background disabled:border-foreground disabled:bg-foreground disabled:text-background",
actionState === "send" && "disabled:border-transparent disabled:bg-foreground/[0.12] disabled:text-muted-foreground",
showVoiceButton && voiceRecorder.isRecording && "border-transparent bg-red-500 text-white hover:bg-red-500 hover:text-white",
isHero ? "h-8 w-8" : "h-9 w-9",
)}
>
{isUserShell && actionState === "send"
? <ToolRunIcon className="h-4 w-4" />
: <ComposerActionIcon state={actionState} />}
</Button>
</TooltipTrigger>
{showVoiceButton ? (
<TooltipContent
side="top"
align="center"
className="flex items-center gap-2 rounded-full border border-border/70 bg-popover px-3 py-1.5 text-[13px] font-medium text-popover-foreground shadow-[0_8px_24px_rgba(15,23,42,0.13)] dark:border-white/10"
>
<span>{voiceButtonTooltip}</span>
{voiceRecorder.state === "idle" ? (
<kbd className="rounded-full bg-muted px-2 py-0.5 font-sans text-[12px] font-semibold leading-none text-muted-foreground dark:bg-white/10">
{voiceShortcutLabel}
</kbd>
) : null}
</TooltipContent>
) : isUserShell ? (
<TooltipContent>{t("thread.composer.shell.run")}</TooltipContent>
) : null}
</Tooltip>
</TooltipProvider>
</div>
</div>
</div>
{workspaceControl || mobileWorkspaceControls && accessControl || usageInMeta && usageControl ? (
<div className={cn(
"thread-composer-meta mx-auto mt-1 flex w-full min-w-0 items-center gap-x-2 pr-2 sm:pr-3",
mobileWorkspaceControls ? "flex-nowrap gap-x-1 pr-0" : "flex-wrap gap-y-1",
isHero ? "max-w-[58rem]" : "max-w-[49.5rem]",
paletteBeside && "col-start-1 row-start-2",
)}>
<div className={cn("thread-composer-workspace-group flex min-w-0 items-center gap-1", mobileWorkspaceControls ? "flex-1" : "flex-auto max-[359px]:flex-wrap")}>
{workspaceControl}
</div>
{usageInMeta && usageControl || mobileWorkspaceControls && accessControl ? (
<div className={cn("ml-auto flex shrink-0 items-center gap-1", mobileWorkspaceControls && "h-11 max-w-[calc(100%-3rem)]")}>
{usageInMeta ? usageControl : null}
{mobileWorkspaceControls ? accessControl : null}
</div>
) : null}
</div>
) : null}
</form>
);
}
function QueuedPromptPreview({
prompt,
disabled,
editDisabled,
label,
guideLabel,
deleteLabel,
editLabel,
onGuide,
onDelete,
onEdit,
}: {
prompt: QueuedPromptContent;
disabled: boolean;
editDisabled: boolean;
label: string;
guideLabel: string;
deleteLabel: string;
editLabel: string;
onGuide: () => void;
onDelete: () => void;
onEdit: () => void;
}) {
return (
<div
role="group"
data-state="enter"
className={cn(
2026-08-14 07:07:09 +09:00
"composer-status-strip relative z-20 mx-3 mt-3 overflow-hidden rounded-floating",
"border border-black/[0.05] bg-popover/90 p-1.5",
"shadow-[0_10px_28px_rgba(15,23,42,0.07)] backdrop-blur-md",
"dark:border-white/[0.08] dark:bg-popover/90 dark:shadow-[0_14px_34px_rgba(0,0,0,0.30)]",
)}
style={{ "--composer-strip-max-height": "224px" } as CSSProperties}
aria-label={label}
>
<div className="flex min-w-0 items-center gap-1 px-1 pb-1">
<span className="min-w-0 flex-1 truncate text-[11.5px] font-semibold text-foreground/75">{label}</span>
<Button
type="button"
variant="ghost"
size="sm"
disabled={disabled}
className="h-7 shrink-0 rounded-full px-2 text-[11.5px] font-medium text-muted-foreground hover:bg-muted/70 hover:text-foreground dark:hover:bg-white/[0.07]"
onClick={onGuide}
>
<CornerDownRight className="mr-1 h-3 w-3" aria-hidden />
{guideLabel}
</Button>
<Button
type="button"
variant="ghost"
size="icon"
disabled={disabled || editDisabled}
aria-label={editLabel}
title={editLabel}
className="h-7 w-7 shrink-0 rounded-full text-muted-foreground hover:text-foreground"
onClick={onEdit}
>
<EditIcon className="h-3.5 w-3.5" aria-hidden />
</Button>
<Button
type="button"
variant="ghost"
size="icon"
disabled={disabled}
aria-label={deleteLabel}
className="h-7 w-7 shrink-0 rounded-full text-muted-foreground hover:text-destructive"
onClick={onDelete}
>
<Trash2 className="h-3 w-3" aria-hidden />
</Button>
</div>
<div className="max-h-40 overflow-y-auto px-2 pb-1 text-[13px]">
<p className="whitespace-pre-wrap break-words font-medium leading-relaxed text-foreground/88">
{queuedPromptLabel(prompt)}
</p>
{prompt.text && prompt.images?.length ? (
<p className="mt-1 break-words text-xs text-muted-foreground">
{prompt.images.map((image) => image.name).filter(Boolean).join(", ")}
</p>
) : null}
</div>
</div>
);
}
function ComposerInlineReferenceOverlay({
overlayRef,
2026-05-22 22:25:12 +08:00
segments,
slashCommand,
2026-05-22 22:25:12 +08:00
isHero,
isComposing,
2026-05-22 22:25:12 +08:00
className,
ghostRange,
2026-05-22 22:25:12 +08:00
}: {
overlayRef: Ref<HTMLDivElement>;
segments: InlineReferenceSegment[];
slashCommand: string | null;
2026-05-22 22:25:12 +08:00
isHero: boolean;
isComposing: boolean;
2026-05-22 22:25:12 +08:00
className: string;
ghostRange?: { start: number; end: number } | null;
2026-05-22 22:25:12 +08:00
}) {
let offset = 0;
const occurrences = new Map<string, number>();
2026-05-22 22:25:12 +08:00
return (
<div
ref={overlayRef}
2026-05-22 22:25:12 +08:00
aria-hidden
className={cn(
className,
"pointer-events-none absolute inset-0 z-0 overflow-hidden whitespace-pre-wrap break-words text-foreground",
// Native IME selection backgrounds can be opaque; keep the mirrored glyphs visible.
isComposing && "z-20",
2026-05-22 22:25:12 +08:00
)}
>
{segments.map((segment, index) => {
const start = offset;
offset += segment.text.length;
2026-05-22 22:25:12 +08:00
if (segment.kind === "text") {
const bangPrefix = index === 0 ? /^(\s*)!/.exec(segment.text) : null;
return <span key={`text-${index}`}>{bangPrefix ? <>
{bangPrefix[1]}
<InlineTokenHighlight testId="composer-shell-prefix" className="font-normal" color={INLINE_REFERENCE_HIGHLIGHT_COLOR}>
<span className="opacity-90">!</span>
</InlineTokenHighlight>
{segment.text.slice(bangPrefix[0].length)}
</> : start === 0 && slashCommand ? <>
<SlashCommandText command={slashCommand} testId="composer-slash-command" />
{segment.text.slice(slashCommand.length)}
</> : segment.text}</span>;
2026-05-22 22:25:12 +08:00
}
if (segment.kind === "skill") {
return <SkillReferenceToken
key={`skill-${segment.name}-${index}`}
name={segment.name}
testId={`composer-skill-reference-${segment.name.toLowerCase()}`}
/>;
}
const isGhost = ghostRange?.start === start && ghostRange.end === offset;
const identity = `${segment.kind}-${segment.kind === "cli"
? segment.app.name : segment.kind === "mcp" ? segment.preset.name : segment.mention.session_key}`;
const occurrence = occurrences.get(identity) ?? 0;
occurrences.set(identity, occurrence + 1);
2026-08-02 22:04:59 +08:00
return (
<span
key={`${identity}-${occurrence}`}
data-testid={isGhost ? "composer-session-drag-preview" : undefined}
className={cn(isGhost && "opacity-45 transition-opacity duration-100")}
>
2026-08-18 18:28:19 +08:00
<CapabilityMentionToken
segment={segment}
variant="composer"
isHero={isHero}
/>
</span>
2026-08-02 22:04:59 +08:00
);
2026-05-22 22:25:12 +08:00
})}
{segments.at(-1)?.text.endsWith("\n") ? "\u200b" : null}
2026-05-22 22:25:12 +08:00
</div>
);
}
2026-05-06 15:54:15 +00:00
interface AttachmentChipProps {
image: AttachedImage;
labelRemove: string;
labelEncoding: string;
normalizedHint: (origBytes: number, currentBytes: number) => string;
formatError: (reason: AttachmentError) => string;
onRemove: () => void;
onKeyDown: (e: ReactKeyboardEvent<HTMLButtonElement>) => void;
registerRef: (el: HTMLButtonElement | null) => void;
}
function AttachmentChip({
image,
labelRemove,
labelEncoding,
normalizedHint,
formatError,
onRemove,
onKeyDown,
registerRef,
}: AttachmentChipProps) {
const sizeLabel =
image.status === "ready" && image.normalized && image.encodedBytes
? normalizedHint(image.file.size, image.encodedBytes)
: formatBytes(image.file.size);
const isThumbnail = image.kind === "image" && image.status !== "error";
const error = image.status === "error" && image.error ? formatError(image.error) : null;
return (
<div className="flex w-24 max-w-full shrink-0 flex-col gap-1" data-testid="composer-chip">
<AttachmentCard name={image.file.name} description={sizeLabel} invalid={!!error}
action={<button type="button" ref={registerRef} onClick={onRemove} onKeyDown={onKeyDown}
aria-label={labelRemove} aria-description={image.file.name} title={labelRemove}
className={cn(attachmentCardActionClassName, "group/remove focus-visible:bg-black/50 focus-visible:ring-white")}>
<span className="grid h-5 w-5 place-items-center rounded-full bg-black/65 text-white group-hover/remove:bg-black/80">
<X className="h-3 w-3" aria-hidden />
</span>
</button>}>
{isThumbnail && image.previewUrl ? <img src={image.previewUrl} alt={image.file.name} loading="eager" draggable={false}
className="h-full w-full object-cover" /> : <AttachmentTypeFace name={image.file.name} kind={image.kind} />}
{image.status === "encoding" ? <span className="absolute inset-0 flex items-center justify-center bg-background/60" aria-label={labelEncoding}>
<Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden />
</span> : null}
</AttachmentCard>
{error ? <span className="break-words text-center text-[11px] leading-4 text-destructive">{error}</span> : null}
</div>
);
}