Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { AiSpeechIcon, BookmarkIcon, FileSearchIcon, TrashIcon } from "@/lib/hugeicons-derived";
import { createPortal } from "react-dom";
import {
canQueueTextAttachment,
normalizeQueuedPrompt,
prepareQueuedPromptFiles,
queuedPromptHasContent,
queuedPromptMessage,
snapshotQueuedTextPrompt,
type QueuedPrompt,
} from "@/features/chat/utils/queued-text-attachments";
import { getAuthSessionEpoch } from "@/features/auth";
import { useMarkChatWelcome } from "@/features/chat-background";
import {
ComposerAttachments,
UserMessageAttachments,
} from "@/components/assistant-ui/attachment";
import {
GeneratedImageOverlayProvider,
useGeneratedImageOverlay,
} from "@/components/assistant-ui/generated-image-overlay-context";
import { AutoReadAloud } from "@/components/assistant-ui/auto-read-aloud";
import { CompactionDivider } from "@/components/assistant-ui/compaction-divider";
import {
compactionDividerRows,
compactionToolCallDividers,
memoOnArrayByKey,
} from "@/components/assistant-ui/message-derived";
import { downloadImagePart } from "@/components/assistant-ui/image";
import {
MarkdownText,
highlightFenceSource,
} from "@/components/assistant-ui/markdown-text";
import { grammarWarmed } from "@/components/assistant-ui/code-fence-defer";
import {
createGrammarPrewarm,
type GrammarPrewarm,
} from "@/components/assistant-ui/grammar-prewarm";
import { streamActive } from "@/components/assistant-ui/use-reasoning-highlight";
import { scheduleQuietIdleTask } from "@/lib/schedule-idle-task";
import { inputPointerHeld } from "@/lib/input-pointer-state";
import { MessageHtmlArtifacts } from "@/components/assistant-ui/message-html-artifacts";
import {
MessageResponseDetailsSheet,
MessageResponseModelBadge,
} from "@/components/assistant-ui/message-response-details-sheet";
import { ComposerDraftPreview } from "@/components/assistant-ui/composer-draft-preview";
import { PromptQueueList } from "@/components/assistant-ui/lazy-prompt-queue-list";
import { QueueResumeIcon } from "@/components/assistant-ui/queue-resume-icon";
import { observeReplyPaint } from "@/components/assistant-ui/reply-paint";
import { observeDistantRow } from "@/components/assistant-ui/distant-rows";
import { WindowedMessageBody } from "@/components/assistant-ui/windowed-message-body";
import { ProgressiveMessages } from "@/components/assistant-ui/progressive-messages";
import { MessageMenuTime } from "@/components/assistant-ui/message-menu-time";
import { AssistantMessageTime } from "@/components/assistant-ui/assistant-message-time";
import { LiveGenerationLine } from "@/components/assistant-ui/live-generation-line";
import { UserMessageActionBar, UserMessageFooter } from "@/components/assistant-ui/user-message-actions";
import { useActionBarFocusReveal } from "@/components/assistant-ui/use-action-bar-focus-reveal";
import {
composerColumnInset,
composerInsetFromColumn,
readViewportBox,
} from "@/components/assistant-ui/composer-column-inset";
import { MessageTiming } from "@/components/assistant-ui/message-timing";
import { attachThreadFastCopy } from "@/components/assistant-ui/thread-fast-copy";
import { attachWheelHoverSuppression } from "@/components/assistant-ui/thread-wheel-hover";
import { threadHasResearchMessage } from "@/components/assistant-ui/thread-research-presence";
import {
THREAD_GUTTER_CHANGE_EVENT,
syncThreadGutter,
watchThreadGutter,
} from "@/components/assistant-ui/thread-gutter";
import { observeThreadWidthSteps } from "@/components/assistant-ui/thread-width-steps";
import { Reasoning, ReasoningGroup } from "@/components/assistant-ui/reasoning";
import { researchReplyOwners } from "@/components/assistant-ui/research-reply-owners";
import { Sources, SourcesGroup } from "@/components/assistant-ui/sources";
import {
proplessSlot,
threadMessageKind,
} from "@/components/assistant-ui/thread-message-slot";
import {
thinkEffortAriaLabel,
thinkToggleAriaLabel,
} from "@/components/assistant-ui/think-aria-label";
import { withToolConfirmation } from "@/components/assistant-ui/tool-confirmation-controls";
import { ToolFallback } from "@/components/assistant-ui/tool-fallback";
import { ToolGroup } from "@/components/assistant-ui/tool-group";
import { CodeExecutionToolUI } from "@/components/assistant-ui/tool-ui-code-execution";
import {
ImageGenerationToolUI,
VideoGenerationToolUI,
} from "@/components/assistant-ui/tool-ui-image-generation";
import { KnowledgeBaseToolUI } from "@/components/assistant-ui/tool-ui-knowledge-base";
import { ReadSkillToolUI } from "@/components/assistant-ui/tool-ui-read-skill";
import { SkillMentionPopover } from "@/components/assistant-ui/skill-mentions";
import { isRewindCommand, useRewindDialogStore } from "@/features/chat";
import { RenderHtmlToolUI } from "@/components/assistant-ui/tool-ui-render-html";
import { PythonToolUI } from "@/components/assistant-ui/tool-ui-python";
import { TerminalToolUI } from "@/components/assistant-ui/tool-ui-terminal";
import { WebSearchToolUI } from "@/components/assistant-ui/tool-ui-web-search";
import { ChatDictationBar } from "@/components/assistant-ui/chat-dictation-bar";
import {
ChatAudioUploadMount,
composerSubmitIntent,
composerFollowUpBehavior,
composerShortcutLabels,
composerKeyEventForImeSubmit,
effectiveSendShortcut,
imeKeydownBlocksComposerSubmit,
followUpSubmitIntent,
steeringInsertionIndex,
parkedSendSteer,
cancelPreStreamRunForThreadIds,
type ComposerSendShortcut,
type ParkedSendSteerState,
type ComposerSubmitIntent,
type ComposerFollowUpBehavior,
type ContextTruncation,
attachmentsPastedText,
hasPendingPromptQueueStart,
isCompactCommand,
isThreadIncognito,
requestThreadCompaction,
useCompactRequestStore,
isPastedTextFile,
pastedTextQueueKey,
promptQueueActiveItemChanged,
reorderPromptQueueItems,
pasteClipboardFiles,
extractYoutubeVideoUrlFromClipboard,
pasteLongTextAsFile,
isPlainPasteChord,
plainPasteStillCounts,
insertAtCaret,
richPasteMarkdown,
currentDictationEntryMode,
isStudioDictationAvailable,
micRecordsForModel,
notifyStudioDictationUnavailable,
setMicAudioClipTarget,
YoutubeTranscriptPrompt,
stripSearchImageTokens,
ChatComposerFocusableContext,
useChatActive,
useChatAudioUpload,
useInComparePane,
refreshSkillsCatalog,
stopRecoveredRun,
pythonToolRunsInStudio,
withAttachmentOriginal,
priorPassTiming,
} from "@/features/chat";
import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";
import {
BookmarkTurnMenuItem,
TurnNavigator,
} from "@/components/assistant-ui/turn-navigation";
import {
IntentAwareScrollProvider,
useAdjustForContentInsertedAbove,
useDetachThreadFromBottom,
useIntentAwareAutoScroll,
useIsThreadAtBottom,
useScrollThreadToBottom,
} from "@/components/assistant-ui/use-intent-aware-autoscroll";
import { Button } from "@/components/ui/button";
import { MascotImg } from "@/components/mascot-img";
import { Spinner } from "@/components/ui/spinner";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { forkChatThread } from "@/features/chat/api/chat-api";
import {
findLatestUserAudioBase64,
resolveProjectId,
sentAudioNames,
} from "@/features/chat/api/chat-adapter";
import {
PromptStorageDialog,
exportConversationShareGPT,
exportConversationRawJsonl,
exportConversationMessagesJsonl,
exportConversationCsv,
exportConversationMarkdown,
exportConversationHtml,
exportConversationPdf,
} from "@/features/chat/prompt-storage/prompt-storage-dialog";
import { ExportFormatItems } from "@/features/chat/components/export-format-items";
import {
listPromptEntries,
listPromptLists,
type PromptEntry,
type PromptListEntry,
} from "@/features/chat/api/prompts-api";
import { PromptCountBadge } from "@/features/chat/prompt-storage/prompt-count-badge";
import { insertSavedPrompt } from "@/features/chat/prompt-storage/insert-prompt";
import {
COMPOSER_POSITION_BOTTOM,
COMPOSER_POSITION_MIDDLE,
useChatPreferencesStore,
} from "@/features/chat/stores/chat-preferences-store";
import {
sortProjectsByActivity,
useChatProjects,
} from "@/features/chat/hooks/use-chat-projects";
import { NewProjectDialog } from "@/features/chat/components/new-project-dialog";
import { ResearchMessage } from "@/features/chat/components/research-message";
import {
DeepResearchComposerButton,
DeepResearchWebsiteAccessDialog,
} from "@/features/chat/components/deep-research-composer-button";
import {
NativeAttachmentDragContext,
type NativeIntent,
useNativeAttachmentTargetKey,
useNativeAttachmentOwnerScope,
useNativeIntentStore,
} from "@/features/native-intents";
import { nativeAttachmentIntentToFile } from "@/features/native-intents/native-attachment-file";
import { wasAttachmentAddCancelled } from "@/features/chat/draft-attachment-adapter";
import {
attachLibraryChatFiles,
useLibraryChatHandoffStore,
} from "@/features/library/chat-handoff-store";
import { resumesThought } from "@/features/model-picker";
import { cancelResearchRun } from "@/features/chat/api/research-api";
import {
ingestResearchUpdate,
useResearchRunStore,
} from "@/features/chat/stores/research-run-store";
import { researchReplyOwnsRun } from "@/features/chat/utils/research-run-binding";
import {
isExternalModelId,
parseExternalModelId,
providerModelSupportsStudioTools,
} from "@/features/chat/external-providers";
import { toolStatusKind } from "@/features/chat/utils/tool-status";
import {
formatPrefillDetails,
formatPrefillTimeLeft,
prefillPercent,
runningReplyTail,
} from "@/features/chat";
import { replySourceMarkdown } from "@/features/chat/utils/reply-source-markdown";
import { toolResultModelText } from "@/features/chat/api/chat-adapter";
import {
collectGeminiAnswerReplayParts,
collectGeminiThoughtReplayParts,
continuationGeminiReplayTurns,
} from "@/features/chat/gemini-thought-replay";
import {
CONTINUATION_RUN_CONFIG_KEY,
type ContinuationRequest,
carriedThought,
incompleteLabel,
incompleteRemedy,
isContinuableContent,
isProviderReportedReason,
modeAllowsContinuation,
providerCompactionContinuationFields,
readContinuationSource,
readIncompleteInfo,
readTextThoughtSignature,
claimAutoContinue,
forgetAutoContinue,
recordAutoContinue,
shouldAutoContinueMessage,
} from "@/features/chat/utils/continuation";
import {
holdAutoContinueRun,
watchAutoContinueRun,
} from "@/features/chat/utils/auto-continue-run-keeper";
import { McpComposerButton } from "@/features/chat/mcp-composer-button";
import {
SkillsComposerButton,
useSkillsSwitch,
} from "@/features/chat/skills-composer-button";
import { pickerAcceptForTextBasenames } from "@/features/chat/text-attachment-accept";
import {
COMPOSER_INPUT_SELECTOR,
isModEnter,
isSurfaceInForeground,
shortcutMatchingEvent,
useKeyboardShortcutsStore,
useShortcut,
useShortcutAvailable,
useSettingsDialogStore,
isMacPlatform,
resolveBindings,
} from "@/features/settings";
import { FIND_SKIP_ATTRIBUTE } from "@/features/find-in-page";
import { translate, useLocale, useT } from "@/i18n";
import type { TranslationKey } from "@/i18n";
import {
clampReasoningEffortToLevels,
getExternalReasoningCapabilities,
kimiSearchExcludesThinking,
modelCatalogVersion,
subscribeModelCatalog,
} from "@/features/chat/provider-capabilities";
import { useRagToolDisabled } from "@/features/chat/hooks/use-rag-tool-disabled";
import { BypassPermissionsMenuItem } from "@/features/chat/bypass-permissions-menu-item";
import { PermissionModeComposerPill } from "@/features/chat/permission-mode-select";
import {
codeToolsOn,
imageToolAvailable,
localImagePillCount,
settleThreadScopedSettingsForCopy,
useChatRuntimeStore,
} from "@/features/chat/stores/chat-runtime-store";
import {
forkBoundaryAnchor,
setForkBoundaryAnchor,
useForkBoundaryStore,
} from "@/features/chat/stores/fork-boundary-store";
import {
PROMPT_QUEUE_RUN_FAILED_EVENT,
PROMPT_QUEUE_STOP_EVENT,
} from "@/features/chat/utils/prompt-queue-events";
import { useExternalProvidersStore } from "@/features/chat/stores/external-providers-store";
import { saveMarkdownAsProjectSource } from "@/features/rag";
import {
splitPlusMenuItems,
CONVERSATION_MARKDOWN_LABEL,
CONVERSATION_HTML_LABEL,
CONVERSATION_PDF_LABEL,
addQueuedChatRunSettingsThreadIds,
adoptPreStreamRunReservation,
chatHistoryClearBoundary,
deleteStoredChatThreads,
discardQueuedChatRunSettings,
discardQueuedChatRunSettingsForThread,
hasPreStreamRunReservation,
localPromptQueueModelBoundary,
notifyPromptQueueRunFailed,
planLocalPromptQueueStop,
planUserPromptQueueStop,
userStopTargetCancelMode,
registerQueuedChatRunSettings,
releasePreStreamRunReservation,
reservePreStreamRun,
subscribePreStreamRunReservations,
claimThreadCreation,
useChatProjectScope,
shouldAbortPendingQueueForModelBoundary,
shouldAbortPendingQueueForSettingsChange,
resolveDeferredQueuedModelSettings,
snapshotQueuedChatRunSettings,
flushComposerDraft,
latestDraft,
NEW_CHAT_DRAFT_ID,
stageComposerDraft,
latestPasteDraft,
publishDraft,
subscribeDraft,
composerDraftKey,
composerPasteDraftKey,
createPastedTextFile,
pastedTextOf,
writePasteDraft,
markThreadIncognito,
markChatThreadDeleted,
type PromptQueueRunFailedEventDetail,
type PromptQueueStopEventDetail,
dictationFailed,
dictationProducedClip,
dictationProducedTranscript,
type PromptQueueUIEntry,
type PromptQueueUIItem,
type PromptQueueUIItemStatus,
type PromptQueueUIState,
usePromptQueueUI,
forkCountFor,
subscribeForkCounts,
useForkInFlight,
showForkCreatedToast,
showForkFailedToast,
type PlusMenuItemId,
usePlusMenuPrefsStore,
useBookmarkedTurnsStore,
writeComposerDraft,
normalizeChatImage,
} from "@/features/chat";
import {
applySentTextGuard,
armSentTextGuard,
isGuardRetiringKey,
markSentTextGuardUserInput,
sentTextGuardBlocksDraft,
type SentTextGuard,
} from "@/features/chat/utils/composer-send-guard";
import { deleteThreadMessage } from "@/features/chat/utils/delete-thread-message";
import {
readBackendChatThread,
getStoredChatThread,
updateStoredChatThread,
} from "@/features/chat/utils/chat-history-storage";
import {
clipStillAttached,
dictationSendBlocked,
shouldSubmitDictation,
} from "@/features/chat/utils/dictation-send";
import {
micSendsAudioToModel,
pickAudioForModel,
} from "@/features/chat/utils/mic-target";
import {
isRagClientError,
listProjectDocuments,
listThreadDocuments,
projectWorkCount,
} from "@/features/rag/api/rag-api";
import { useRagAvailabilityStore } from "@/features/rag/api/rag-availability";
import { ThreadDocumentsBar } from "@/features/rag/components/thread-documents-bar";
import { KnowledgeBaseComposerButton } from "@/features/rag/components/knowledge-base-composer-button";
import { useUserProfileStore } from "@/features/profile/stores/user-profile-store";
import { resolveGreeting } from "@/features/profile/greeting";
import { usePublishedFrame } from "@/features/settings/hooks/use-published-frame";
import { useVoiceSettingsStore } from "@/features/settings/stores/voice-settings-store";
import { applyQwenThinkingParams } from "@/features/chat/utils/qwen-params";
import { isTauri } from "@/lib/api-base";
import { openFilePicker } from "@/lib/open-file-picker";
import { InternetGlyph } from "@/lib/internet-icon";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { MenuDismissGuard } from "@/lib/menu-dismiss-guard";
import { useWindowChromeCollisionPadding } from "@/lib/window-chrome";
import { NonModalDropdownMenu } from "@/components/ui/non-modal-dropdown-menu";
import { MicIcon } from "@/lib/mic-icon";
import { downloadFile, isDownloadCancelled } from "@/lib/native-files";
import { toast } from "@/lib/toast";
import { Tick02Icon } from "@/lib/tick-icon";
import { BrowserAgentMenuItem, BrowserAgentPill } from "@/features/browser/agent/lazy-composer-toggle";
import {
BranchNextIcon,
BranchPrevIcon,
ContinueArrowIcon,
ReadAloudIcon,
} from "@/lib/action-bar-icons";
import { ForkIcon } from "@/lib/fork-icon";
import { markComposerScrollable, markComposerScrollEdges } from "@/lib/composer-scroll-fade";
import { useSurfaceRef } from "@/lib/surface-registry";
import { cn } from "@/lib/utils";
import {
ActionBarMorePrimitive,
ActionBarPrimitive,
AuiIf,
BranchPickerPrimitive,
ComposerPrimitive,
ErrorPrimitive,
MessagePrimitive,
TextMessagePartProvider,
ThreadPrimitive,
useAui,
useAuiEvent,
useAuiState,
} from "@assistant-ui/react";
import { flushResourcesSync } from "@assistant-ui/tap";
import {
Attachment01Icon,
CodeIcon,
Download01Icon,
Edit03Icon,
ImageIcon,
LayoutTwoColumnIcon,
McpServerIcon,
Refresh01Icon,
Scroll01Icon,
Telescope02Icon,
UndoIcon,
VolumeMute02Icon,
WorkflowCircle05Icon,
Clock01Icon,
SlidersHorizontalIcon,
MoreHorizontalIcon,
PlusSignIcon,
Cancel01Icon,
} from "@hugeicons/core-free-icons";
import { FolderAddIcon, FolderAttachmentIcon } from "@/lib/folder-icons";
import { Copy01Icon } from "@/lib/copy-icon";
import { StopIcon } from "@/lib/media-control-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { ProjectIcon } from "@/lib/project-icon";
import { RefreshGlyph } from "@/lib/refresh-icon";
import { useNavigate } from "@tanstack/react-router";
import {
ArrowDownIcon,
ArrowUpIcon,
Loader2Icon,
TerminalIcon,
} from "lucide-react";
import {
type ChangeEvent,
type CompositionEvent,
type ClipboardEvent,
type CSSProperties,
type FC,
type KeyboardEvent,
type DragEvent as ReactDragEvent,
type PropsWithChildren,
type ReactNode,
type RefObject,
Fragment,
Suspense,
createContext,
lazy,
memo,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
} from "react";
import { extractTaggedText, updateThreadMessage } from "@/features/chat/utils/update-thread-message";
import { useComposerPillFit } from "@/hooks/use-composer-pill-fit";
import { useIsMobile } from "@/hooks/use-mobile";
import { useUiSpaceScale } from "@/hooks/use-ui-space-scale";
import { useExpandedComposerFill } from "./use-expanded-composer-fill";
import { watchComposerClearance } from "@/lib/toast-offset";
const PageDragContext = createContext(false);
const FOLLOW_UP_SHORTCUTS = {
queueMessage: "queue",
steerMessage: "steer",
} as const satisfies Record<string, ComposerFollowUpBehavior>;
const FOLLOW_UP_SHORTCUT_IDS = Object.keys(
FOLLOW_UP_SHORTCUTS,
) as (keyof typeof FOLLOW_UP_SHORTCUTS)[];
function followUpShortcutBehavior(event: {
code: string;
key?: string;
metaKey: boolean;
ctrlKey: boolean;
shiftKey: boolean;
altKey: boolean;
}): ComposerFollowUpBehavior | null {
const id = shortcutMatchingEvent(
useKeyboardShortcutsStore.getState().overrides,
FOLLOW_UP_SHORTCUT_IDS,
event,
);
return id ? FOLLOW_UP_SHORTCUTS[id] : null;
}
// module scope and runningByThreadId let queues survive Composer remounts and advance off-screen.
type PromptQueueTarget = {
getDocumentThreadId: () => string | null;
/** project captured when a new chat has no persisted row to read. */
getQueueProjectId: () => string | null;
getRunningThreadIds: () => string[];
isRunning: () => boolean;
append: (prompt: QueuedPrompt) => void | Promise<void>;
complete: () => void;
cancel: () => void;
cancelActiveRun: () => void;
/** Forget the captured local model so a held prompt resolves the one loaded when it is sent. */
releaseModel: () => void;
isIndexing: () => boolean;
usesThreadDocuments: boolean;
usesLocalModel: boolean;
usesDeepResearch: boolean;
/** whether a research run now holds this queue's thread. */
researchStarted: () => boolean;
temporary: boolean;
consumeDeepResearch: () => void;
};
type PromptQueueItem = QueuedPrompt & {
id: string;
target: PromptQueueTarget;
dispatched: boolean;
dispatchRetries: number;
blockedByModelFailure?: boolean;
};
type PromptQueueRun = {
id: string;
items: PromptQueueItem[];
index: number;
generation: number;
prevStoreRunning: boolean;
waitingForTargetIdle: boolean;
paused: boolean;
retryTimer: ReturnType<typeof setTimeout> | null;
deepResearchConsumed: boolean;
};
const PROMPT_QUEUE_INDEXING_RETRY_MS = 500;
const PROMPT_QUEUE_DISPATCH_RETRY_MS = 500;
const PROMPT_QUEUE_TARGET_STATE_POLL_MS = 50;
const PROMPT_QUEUE_MAX_DISPATCH_RETRIES = 5;
const promptQueueRuns = new Map<string, PromptQueueRun>();
const promptQueueActiveRunIds = new Set<string>();
const promptQueueDispatchingRunIds = new Set<string>();
const promptQueueRunOrder: string[] = [];
let promptQueueStoreUnsub: (() => void) | null = null;
let promptQueuePumpTimer: ReturnType<typeof setTimeout> | null = null;
let promptQueueRoundRobinCursor = 0;
function compactIds(ids: Array<string | null | undefined>) {
return Array.from(new Set(ids.filter((id): id is string => Boolean(id))));
}
function createPromptQueueItemId() {
return `prompt-queue-${crypto.randomUUID()}`;
}
function createPromptQueueRunId() {
return `prompt-queue-run-${crypto.randomUUID()}`;
}
function stopPromptQueueSubscription() {
if (promptQueueStoreUnsub) {
promptQueueStoreUnsub();
promptQueueStoreUnsub = null;
}
}
function clearPromptQueuePumpTimer() {
if (!promptQueuePumpTimer) {
return;
}
clearTimeout(promptQueuePumpTimer);
promptQueuePumpTimer = null;
}
function clearPromptQueueRetryTimer(run: PromptQueueRun) {
if (!run.retryTimer) {
return;
}
clearTimeout(run.retryTimer);
run.retryTimer = null;
}
function deletePromptQueueRun(run: PromptQueueRun) {
run.generation += 1;
clearPromptQueueRetryTimer(run);
promptQueueActiveRunIds.delete(run.id);
promptQueueDispatchingRunIds.delete(run.id);
promptQueueRuns.delete(run.id);
const orderIndex = promptQueueRunOrder.indexOf(run.id);
if (orderIndex >= 0) {
promptQueueRunOrder.splice(orderIndex, 1);
if (promptQueueRoundRobinCursor > orderIndex) {
promptQueueRoundRobinCursor -= 1;
}
if (promptQueueRunOrder.length > 0) {
promptQueueRoundRobinCursor %= promptQueueRunOrder.length;
} else {
promptQueueRoundRobinCursor = 0;
}
}
if (promptQueueRuns.size === 0) {
clearPromptQueuePumpTimer();
stopPromptQueueSubscription();
}
syncPromptQueueUI();
}
function resetPromptQueues() {
for (const run of promptQueueRuns.values()) {
run.generation += 1;
clearPromptQueueRetryTimer(run);
}
promptQueueRuns.clear();
promptQueueActiveRunIds.clear();
promptQueueDispatchingRunIds.clear();
promptQueueRunOrder.length = 0;
promptQueueRoundRobinCursor = 0;
clearPromptQueuePumpTimer();
stopPromptQueueSubscription();
syncPromptQueueUI();
}
function requestPromptQueuePumpIfReady(delay = 0) {
if (hasReadyPromptQueueRun()) {
requestPromptQueuePump(delay);
}
}
function handleQueuedPromptAppendFailure(
run: PromptQueueRun,
item: PromptQueueItem,
error: unknown,
) {
if (!isActivePromptQueueItem(run, item, run.generation)) {
return;
}
item.dispatched = false;
promptQueueActiveRunIds.delete(run.id);
syncPromptQueueUI();
item.dispatchRetries += 1;
if (item.dispatchRetries > PROMPT_QUEUE_MAX_DISPATCH_RETRIES) {
console.error("Prompt queue dispatch failed permanently:", error);
try {
item.target.cancel();
} catch (cleanupError) {
console.error("Prompt queue cleanup failed:", cleanupError);
}
deletePromptQueueRun(run);
requestPromptQueuePumpIfReady();
return;
}
item.target.complete();
scheduleQueuedPromptDispatch(run, item, PROMPT_QUEUE_DISPATCH_RETRY_MS);
}
function consumePromptQueueDeepResearch(
run: PromptQueueRun,
item: PromptQueueItem,
) {
// The queue's one research is spent only once a run actually started, not when merely armed.
if (
run.deepResearchConsumed ||
!item.target.usesDeepResearch ||
!item.target.researchStarted()
) {
return;
}
run.deepResearchConsumed = true;
for (const item of run.items) {
item.target.consumeDeepResearch();
}
}
function appendQueuedPrompt(run: PromptQueueRun, item: PromptQueueItem) {
item.dispatched = true;
promptQueueActiveRunIds.add(run.id);
syncPromptQueueUI();
try {
const result = item.target.append(item);
if (result && typeof result.catch === "function") {
void result
.then(() => consumePromptQueueDeepResearch(run, item))
.catch((error) => {
handleQueuedPromptAppendFailure(run, item, error);
});
} else {
consumePromptQueueDeepResearch(run, item);
}
} catch (error) {
handleQueuedPromptAppendFailure(run, item, error);
}
schedulePromptQueueTargetStatePoll(run);
}
const indexingDocument = (doc: { status: string }) =>
doc.status === "pending" || doc.status === "running";
async function targetHasIndexingDocuments(item: PromptQueueItem) {
if (item.target.isIndexing()) {
return true;
}
const threadId = item.target.getDocumentThreadId();
try {
if (threadId && item.target.usesThreadDocuments) {
const documents = await listThreadDocuments(threadId);
if (documents.some(indexingDocument)) {
return true;
}
}
// Project sources are retrieved whatever the Docs pill says (chat-adapter's
// rag_scope), and isIndexing() above only answers while the bar that watches
// them is mounted, which a background queue has not. So ask directly, and
// for a chat with no row yet use the project the queue was started in.
// Rethrowing: a row this probe could not read is not a chat with no project,
// and the catch below is what holds the prompt and asks again. The queue's
// own project is the fallback wherever the row is still missing, so a poll
// landing mid-navigation cannot probe the project the user moved to.
const queueProjectId = item.target.getQueueProjectId();
const projectId = threadId
? await resolveProjectId(threadId, undefined, {
rethrowReadFailure: true,
composerProjectId: queueProjectId,
})
: queueProjectId;
if (!projectId) {
return false;
}
if (projectWorkCount(projectId) > 0) {
return true;
}
try {
const projectDocuments = await listProjectDocuments(projectId);
return projectDocuments.some(indexingDocument);
} catch (error) {
// A project the server will not list is not one to wait for: the retry would never end.
if (isRagClientError(error)) {
return false;
}
throw error;
}
} catch {
// A failed status probe cannot prove documents are ready, so retry, unless RAG is unavailable
// on this host, where waiting would never send the prompt.
return !useRagAvailabilityStore.getState().isUnavailable();
}
}
function getActivePromptQueueItem(run: PromptQueueRun) {
return run.items[Math.max(run.index, 0)];
}
function isActivePromptQueueItem(
run: PromptQueueRun,
item: PromptQueueItem,
generation: number,
) {
if (promptQueueRuns.get(run.id) !== run || generation !== run.generation) {
return false;
}
return getActivePromptQueueItem(run) === item && !item.blockedByModelFailure;
}
function scheduleQueuedPromptDispatch(
run: PromptQueueRun,
item: PromptQueueItem,
delay: number,
generation = run.generation,
) {
clearPromptQueueRetryTimer(run);
run.retryTimer = setTimeout(() => {
run.retryTimer = null;
if (isActivePromptQueueItem(run, item, generation)) {
requestPromptQueuePump();
}
}, delay);
}
function isPromptQueueRunReadyToDispatch(run: PromptQueueRun) {
const item = getActivePromptQueueItem(run);
return Boolean(
item &&
run.index >= 0 &&
!item.dispatched &&
!item.blockedByModelFailure &&
!run.waitingForTargetIdle &&
!run.paused &&
!run.retryTimer &&
!promptQueueActiveRunIds.has(run.id) &&
!promptQueueDispatchingRunIds.has(run.id),
);
}
function getNextReadyPromptQueueRun() {
if (promptQueueRunOrder.length === 0) {
return null;
}
const size = promptQueueRunOrder.length;
for (let offset = 0; offset < size; offset += 1) {
const orderIndex = (promptQueueRoundRobinCursor + offset) % size;
const runId = promptQueueRunOrder[orderIndex];
const run = promptQueueRuns.get(runId);
if (!run || !isPromptQueueRunReadyToDispatch(run)) {
continue;
}
promptQueueRoundRobinCursor = (orderIndex + 1) % size;
return run;
}
return null;
}
function requestPromptQueuePump(delay = 0) {
if (promptQueuePumpTimer) {
return;
}
promptQueuePumpTimer = setTimeout(() => {
promptQueuePumpTimer = null;
pumpPromptQueues();
}, delay);
}
function pumpPromptQueues() {
ensurePromptQueueSubscription();
// Sequential within a thread; independent threads may dispatch together (backend caps concurrency).
while (true) {
const run = getNextReadyPromptQueueRun();
if (!run) {
return;
}
const item = getActivePromptQueueItem(run);
if (!item) {
deletePromptQueueRun(run);
continue;
}
const dispatchGeneration = run.generation;
promptQueueDispatchingRunIds.add(run.id);
dispatchQueuedPrompt(run, item, run.generation)
.catch(() => undefined)
.finally(() => {
// Releasing a live attempt's flag makes Stop then Resume append twice.
if (
promptQueueRuns.get(run.id) === run &&
dispatchGeneration !== run.generation
) {
return;
}
promptQueueDispatchingRunIds.delete(run.id);
syncPromptQueueUI();
if (!promptQueueActiveRunIds.has(run.id)) {
requestPromptQueuePump();
}
});
}
}
async function dispatchQueuedPrompt(
run: PromptQueueRun,
item: PromptQueueItem,
generation = run.generation,
) {
if (!isActivePromptQueueItem(run, item, generation)) {
return;
}
// Keep prompts editable until the local model finishes loading.
if (item.target.usesLocalModel && useChatRuntimeStore.getState().modelLoading) {
scheduleQueuedPromptDispatch(run, item, PROMPT_QUEUE_DISPATCH_RETRY_MS);
return;
}
if (
isPromptQueueTargetRunning(
item.target,
useChatRuntimeStore.getState().runningByThreadId,
)
) {
run.waitingForTargetIdle = true;
run.prevStoreRunning = true;
promptQueueActiveRunIds.delete(run.id);
syncPromptQueueUI();
ensurePromptQueueSubscription();
handlePromptQueueRunState(
run,
useChatRuntimeStore.getState().runningByThreadId,
);
schedulePromptQueueTargetStatePoll(run);
return;
}
const hasIndexingDocuments = await targetHasIndexingDocuments(item);
if (!isActivePromptQueueItem(run, item, generation)) {
return;
}
// recheck loading after the document probe.
if (
hasIndexingDocuments ||
(item.target.usesLocalModel && useChatRuntimeStore.getState().modelLoading)
) {
promptQueueActiveRunIds.delete(run.id);
scheduleQueuedPromptDispatch(run, item, PROMPT_QUEUE_INDEXING_RETRY_MS);
return;
}
if (!isActivePromptQueueItem(run, item, generation)) {
return;
}
appendQueuedPrompt(run, item);
}
function createQueuedPrompt(prompt: QueuedPrompt, target: PromptQueueTarget) {
return {
id: createPromptQueueItemId(),
...prompt,
target,
dispatched: false,
dispatchRetries: 0,
};
}
function getPromptQueueTargetIds(target: PromptQueueTarget) {
return compactIds([
...target.getRunningThreadIds(),
target.getDocumentThreadId(),
]);
}
function getPromptQueueRunTargetIds(run: PromptQueueRun) {
return compactIds(
run.items.flatMap((item) => getPromptQueueTargetIds(item.target)),
);
}
function promptQueueRunUsesLocalModel(run: PromptQueueRun) {
return run.items
.slice(Math.max(run.index, 0))
.some((item) => item.target.usesLocalModel);
}
function promptQueueRunIsTemporary(run: PromptQueueRun) {
return run.items
.slice(Math.max(run.index, 0))
.some((item) => item.target.temporary);
}
function promptQueueRunMatchesThreadIds(
run: PromptQueueRun,
threadIds: string[],
) {
return getPromptQueueRunTargetIds(run).some((id) => threadIds.includes(id));
}
function findPromptQueueRunByTarget(target: PromptQueueTarget) {
const targetIds = getPromptQueueTargetIds(target);
if (targetIds.length === 0) {
return null;
}
for (const run of promptQueueRuns.values()) {
if (promptQueueRunMatchesThreadIds(run, targetIds)) {
return run;
}
}
return null;
}
function findPromptQueueRunByItemId(itemId: string) {
for (const run of promptQueueRuns.values()) {
const itemIndex = run.items.findIndex((item) => item.id === itemId);
if (itemIndex >= 0) {
return { run, itemIndex, item: run.items[itemIndex] };
}
}
return null;
}
function findPromptQueueRunByThreadIds(threadIds: string[]) {
if (threadIds.length === 0) {
return null;
}
for (const run of promptQueueRuns.values()) {
if (promptQueueRunMatchesThreadIds(run, threadIds)) {
return run;
}
}
return null;
}
function findPromptQueueEntry(
state: PromptQueueUIState,
threadIds: string[],
) {
for (const threadId of threadIds) {
const entry = state.byThreadId[threadId];
if (entry) {
return entry;
}
}
return null;
}
function canEditPromptQueueItem(item: PromptQueueItem) {
return !item.dispatched;
}
function canRemovePromptQueueItem(item: PromptQueueItem) {
return !item.dispatched;
}
function getPromptQueueRunProgress(run: PromptQueueRun) {
const activeItemIndex = Math.max(run.index, 0);
const total = run.items.length;
const current = run.index >= 0 ? Math.min(activeItemIndex + 1, total) : 0;
return { activeItemIndex, current, total };
}
function getPromptQueueItemStatus(
run: PromptQueueRun,
index: number,
activeItemIndex: number,
): PromptQueueUIItemStatus {
if (run.items[index]?.blockedByModelFailure) return "paused";
if (run.paused && run.index >= 0 && index === activeItemIndex) {
return "paused";
}
if (run.index >= 0 && index === activeItemIndex) {
return run.waitingForTargetIdle ? "waiting" : "next";
}
return "queued";
}
function getPromptQueueUIItemsForRun(run: PromptQueueRun) {
const { activeItemIndex, total } = getPromptQueueRunProgress(run);
const items: PromptQueueUIItem[] = [];
for (const [index, item] of run.items.entries()) {
if (index < activeItemIndex || item.dispatched) {
continue;
}
items.push({
id: item.id,
runId: run.id,
prompt: item.prompt,
attachmentNames: item.attachments?.map((attachment) => attachment.name),
position: index + 1,
total,
status: getPromptQueueItemStatus(run, index, activeItemIndex),
threadIds: getPromptQueueTargetIds(item.target),
canEdit: canEditPromptQueueItem(item),
canRemove: canRemovePromptQueueItem(item),
});
}
return items;
}
function syncPromptQueueUI() {
if (promptQueueRuns.size === 0) {
usePromptQueueUI.setState({
byThreadId: {},
current: 0,
total: 0,
items: [],
isRunning: false,
});
return;
}
const items: PromptQueueUIItem[] = [];
const byThreadId: Record<string, PromptQueueUIEntry> = {};
let current = 0;
let total = 0;
for (const run of promptQueueRuns.values()) {
const { current: runCurrent, total: runTotal } =
getPromptQueueRunProgress(run);
current += runCurrent;
total += runTotal;
items.push(...getPromptQueueUIItemsForRun(run));
const ids = getPromptQueueRunTargetIds(run);
if (ids.length === 0) {
continue;
}
const entry = {
runId: run.id,
current: runCurrent,
total: runTotal,
local: promptQueueRunUsesLocalModel(run),
temporary: promptQueueRunIsTemporary(run),
dispatched: Boolean(getActivePromptQueueItem(run)?.dispatched),
paused: run.paused || run.items.some((item) => item.blockedByModelFailure),
};
for (const id of ids) {
byThreadId[id] = entry;
}
}
usePromptQueueUI.setState({
byThreadId,
current,
total,
items,
isRunning: true,
});
}
function editPromptQueueItem(itemId: string, prompt: string) {
const nextPrompt = prompt.trim();
const match = findPromptQueueRunByItemId(itemId);
if (!match) {
return false;
}
const { item } = match;
if (!canEditPromptQueueItem(item) || !queuedPromptHasContent({ ...item, prompt: nextPrompt })) {
return false;
}
item.prompt = nextPrompt;
syncPromptQueueUI();
return true;
}
function removePromptQueueItem(itemId: string) {
const match = findPromptQueueRunByItemId(itemId);
if (!match) {
return false;
}
const { run, itemIndex, item } = match;
if (!canRemovePromptQueueItem(item)) {
return false;
}
const wasActive = itemIndex === Math.max(run.index, 0);
run.items.splice(itemIndex, 1);
if (run.items.length === 0) {
deletePromptQueueRun(run);
return true;
}
if (itemIndex < run.index) {
run.index -= 1;
}
if (wasActive && run.index >= run.items.length) {
deletePromptQueueRun(run);
return true;
}
syncPromptQueueUI();
if (wasActive) {
clearPromptQueueRetryTimer(run);
if (run.index < 0 || run.waitingForTargetIdle) {
return true;
}
run.prevStoreRunning = false;
const next = run.items[run.index];
if (next) {
scheduleQueuedPromptDispatch(run, next, 50);
}
}
return true;
}
/** Both must still be pending; the insert index is read off the pre-splice array. */
function movePromptQueueItem(itemId: string, targetItemId: string) {
if (itemId === targetItemId) {
return false;
}
const match = findPromptQueueRunByItemId(itemId);
const target = findPromptQueueRunByItemId(targetItemId);
if (!match || !target || match.run !== target.run) {
return false;
}
const { run, itemIndex, item } = match;
if (item.dispatched || target.item.dispatched) {
return false;
}
if (promptQueueDispatchingRunIds.has(run.id)) {
return false;
}
const activeIndex = Math.max(run.index, 0);
const before = run.items;
const after = reorderPromptQueueItems(
before,
itemIndex,
target.itemIndex,
activeIndex,
);
if (!after) {
return false;
}
const activeChanged = promptQueueActiveItemChanged(before, after, run.index);
run.items = after;
syncPromptQueueUI();
// A move across the active slot changes what dispatches next, so retarget like a removal.
const nowActive = run.items[run.index];
if (run.index >= 0 && !run.waitingForTargetIdle && nowActive && activeChanged) {
clearPromptQueueRetryTimer(run);
run.prevStoreRunning = false;
scheduleQueuedPromptDispatch(run, nowActive, 50);
}
return true;
}
function isPromptQueueTargetRunning(
target: PromptQueueTarget,
runningByThreadId: Record<string, boolean>,
) {
// assistant-ui marks a run synchronously while the shared store is set later; reading the target
// closes the rapid-submit window where another append would cancel the new run.
try {
if (target.isRunning()) {
return true;
}
} catch {
// Fall back to the shared store if the thread runtime is remounting.
}
const runningIds = Object.keys(runningByThreadId);
if (runningIds.length === 0) {
return false;
}
const targetIds = target.getRunningThreadIds();
if (targetIds.length === 0) {
// Never borrow another chat's running state; retry this queue's own dispatch instead.
return false;
}
return runningIds.some((threadId) => targetIds.includes(threadId));
}
function isPromptQueueRunTargetRunning(
run: PromptQueueRun,
runningByThreadId: Record<string, boolean>,
) {
const activeItem = getActivePromptQueueItem(run);
if (!activeItem) {
return false;
}
return isPromptQueueTargetRunning(activeItem.target, runningByThreadId);
}
function advancePromptQueue(run: PromptQueueRun) {
clearPromptQueueRetryTimer(run);
promptQueueActiveRunIds.delete(run.id);
getActivePromptQueueItem(run)?.target.complete();
const nextIndex = run.index + 1;
if (nextIndex >= run.items.length) {
deletePromptQueueRun(run);
return;
}
run.index = nextIndex;
run.waitingForTargetIdle = false;
run.prevStoreRunning = false;
syncPromptQueueUI();
requestPromptQueuePump(100);
}
function shouldPollPromptQueueTargetState(run: PromptQueueRun) {
return (
run.waitingForTargetIdle ||
run.index < 0 ||
Boolean(getActivePromptQueueItem(run)?.dispatched)
);
}
function schedulePromptQueueTargetStatePoll(run: PromptQueueRun) {
const isWaitingForTargetState = shouldPollPromptQueueTargetState(run);
if (run.retryTimer || !isWaitingForTargetState) {
return;
}
const generation = run.generation;
run.retryTimer = setTimeout(() => {
run.retryTimer = null;
if (
promptQueueRuns.get(run.id) !== run ||
generation !== run.generation ||
!shouldPollPromptQueueTargetState(run)
) {
return;
}
handlePromptQueueRunState(
run,
useChatRuntimeStore.getState().runningByThreadId,
);
if (
promptQueueRuns.get(run.id) === run &&
shouldPollPromptQueueTargetState(run)
) {
schedulePromptQueueTargetStatePoll(run);
}
}, PROMPT_QUEUE_TARGET_STATE_POLL_MS);
}
function getRunningThreadCount(runningByThreadId: Record<string, boolean>) {
return Object.values(runningByThreadId).filter(Boolean).length;
}
function hasReadyPromptQueueRun() {
return Array.from(promptQueueRuns.values()).some(
isPromptQueueRunReadyToDispatch,
);
}
function handlePromptQueueRunState(
run: PromptQueueRun,
runningByThreadId: Record<string, boolean>,
) {
if (!promptQueueRuns.has(run.id)) {
return;
}
const isRunning = isPromptQueueRunTargetRunning(run, runningByThreadId);
const wasRunning = run.prevStoreRunning;
run.prevStoreRunning = isRunning;
if (!wasRunning || isRunning) {
return;
}
if (run.paused) {
return;
}
// An idle edge before an unsent prompt dispatches belongs to the cancelled response (steering
// race with the dispatch timer); index -1 is the normal wait for the current response.
if (
run.waitingForTargetIdle ||
(run.index >= 0 && !getActivePromptQueueItem(run)?.dispatched)
) {
clearPromptQueueRetryTimer(run);
run.waitingForTargetIdle = false;
const activeItem = run.items[run.index];
if (activeItem) {
requestPromptQueuePump(50);
}
return;
}
advancePromptQueue(run);
requestPromptQueuePump();
}
function ensurePromptQueueSubscription() {
if (promptQueueStoreUnsub) {
return;
}
let previousRunningCount = getRunningThreadCount(
useChatRuntimeStore.getState().runningByThreadId,
);
promptQueueStoreUnsub = useChatRuntimeStore.subscribe((state) => {
if (promptQueueRuns.size === 0) {
stopPromptQueueSubscription();
return;
}
const nextRunningCount = getRunningThreadCount(state.runningByThreadId);
for (const run of Array.from(promptQueueRuns.values())) {
handlePromptQueueRunState(run, state.runningByThreadId);
}
if (nextRunningCount < previousRunningCount && hasReadyPromptQueueRun()) {
requestPromptQueuePump();
}
previousRunningCount = nextRunningCount;
});
}
function steerPromptQueueTarget(target: PromptQueueTarget) {
const targetIds = getPromptQueueTargetIds(target);
const run = findPromptQueueRunByTarget(target);
const active = run && run.index >= 0 ? getActivePromptQueueItem(run) : null;
const cancelledTarget = active?.dispatched ? active.target : null;
pausePromptQueueRun(targetIds);
cancelPreStreamRunForThreadIds(targetIds);
try {
// Pausing already cancels the dispatched target once.
if (cancelledTarget !== target) target.cancelActiveRun();
} catch {
toast.info("Your follow-up is queued next", {
description: "The current response could not be interrupted.",
});
}
resumePromptQueueRun(targetIds);
}
function steerPromptQueueItem(itemId: string) {
const match = findPromptQueueRunByItemId(itemId);
if (!match) return false;
const { run, itemIndex, item } = match;
if (
item.dispatched ||
itemIndex < Math.max(run.index, 0) ||
getPromptQueueTargetIds(item.target).length === 0
) {
return false;
}
if (item.target.researchStarted()) {
toast.info("Research is still running", {
description: "Stop research before steering with a queued prompt.",
});
return false;
}
// move the item so its captured settings and identity stay intact.
run.items.splice(itemIndex, 1);
run.items.splice(steeringInsertionIndex(run.items, run.index), 0, item);
steerPromptQueueTarget(item.target);
return true;
}
function startPromptQueue(
items: Array<string | QueuedPrompt>,
target: PromptQueueTarget,
waitForCurrentRun = false,
behavior: ComposerFollowUpBehavior = "queue",
) {
const filtered = items.map(normalizeQueuedPrompt).filter(queuedPromptHasContent);
if (filtered.length === 0) {
return;
}
const steering = behavior === "steer";
const targetIds = getPromptQueueTargetIds(target);
if (steering && targetIds.length === 0) {
throw new Error("The chat is no longer available for steering.");
}
const existingRun = findPromptQueueRunByTarget(target);
if (existingRun) {
if (existingRun.deepResearchConsumed) {
target.consumeDeepResearch();
}
const newItems = filtered.map((prompt) => createQueuedPrompt(prompt, target));
if (steering) {
existingRun.items.splice(
steeringInsertionIndex(existingRun.items, existingRun.index),
0,
...newItems,
);
steerPromptQueueTarget(target);
return;
}
existingRun.items.push(...newItems);
syncPromptQueueUI();
requestPromptQueuePump();
return;
}
const runningByThreadId = useChatRuntimeStore.getState().runningByThreadId;
const shouldWaitForCurrentRun =
(waitForCurrentRun || steering) &&
isPromptQueueTargetRunning(target, runningByThreadId);
const run: PromptQueueRun = {
id: createPromptQueueRunId(),
items: filtered.map((prompt) => createQueuedPrompt(prompt, target)),
index: shouldWaitForCurrentRun ? -1 : 0,
generation: 0,
prevStoreRunning: shouldWaitForCurrentRun,
waitingForTargetIdle: false,
paused: false,
retryTimer: null,
deepResearchConsumed: false,
};
promptQueueRuns.set(run.id, run);
promptQueueRunOrder.push(run.id);
syncPromptQueueUI();
ensurePromptQueueSubscription();
if (steering) {
steerPromptQueueTarget(target);
return;
}
if (shouldWaitForCurrentRun) {
handlePromptQueueRunState(
run,
useChatRuntimeStore.getState().runningByThreadId,
);
schedulePromptQueueTargetStatePoll(run);
} else {
requestPromptQueuePump(50);
}
}
function getPromptQueueRunsForThreadIds(threadIds?: string[]) {
if (!threadIds || threadIds.length === 0) {
return Array.from(promptQueueRuns.values());
}
const runs = new Set<PromptQueueRun>();
for (const id of compactIds(threadIds)) {
const run = findPromptQueueRunByThreadIds([id]);
if (run) {
runs.add(run);
}
}
return Array.from(runs);
}
function pausePromptQueueRun(threadIds?: string[]) {
for (const run of getPromptQueueRunsForThreadIds(threadIds)) {
const activeItem = getActivePromptQueueItem(run);
const plan = planUserPromptQueueStop(
run.items.map((item) => ({ dispatched: item.dispatched })),
run.index,
);
const cancelMode = userStopTargetCancelMode(plan);
if (plan.retainedItemIndexes.length === 0) {
deletePromptQueueRun(run);
} else {
run.items = plan.retainedItemIndexes.map((index) => run.items[index]);
// From 0 this rewinds onto an item already passed, replaying it out of order.
const resumeFrom = plan.retainedItemIndexes.findIndex(
(index) => index >= Math.max(run.index, 0),
);
const searchFrom = resumeFrom < 0 ? 0 : resumeFrom;
const nextIndex = run.items.findIndex(
(item, index) => index >= searchFrom && !item.dispatched,
);
if (nextIndex < 0) {
deletePromptQueueRun(run);
} else {
run.generation += 1;
run.index = nextIndex;
run.paused = plan.pause;
run.waitingForTargetIdle = false;
run.prevStoreRunning = false;
clearPromptQueueRetryTimer(run);
promptQueueActiveRunIds.delete(run.id);
promptQueueDispatchingRunIds.delete(run.id);
syncPromptQueueUI();
}
}
if (cancelMode === "none") {
continue;
}
try {
if (cancelMode === "permanent") {
activeItem?.target.cancel();
} else {
activeItem?.target.cancelActiveRun();
}
} catch {
// The active run may have already ended.
}
}
requestPromptQueuePumpIfReady();
}
function resumePromptQueueRun(threadIds?: string[]) {
for (const run of getPromptQueueRunsForThreadIds(threadIds)) {
if (run.items.some((item) => item.blockedByModelFailure)) {
for (const item of run.items) item.blockedByModelFailure = false;
syncPromptQueueUI();
}
if (!run.paused) {
continue;
}
run.paused = false;
// prevStoreRunning outlives the paused early-return; a stale edge skips a prompt.
run.waitingForTargetIdle = false;
run.prevStoreRunning = false;
clearPromptQueueRetryTimer(run);
syncPromptQueueUI();
}
requestPromptQueuePumpIfReady();
}
function stopPromptQueueRun(threadIds?: string[]) {
for (const run of getPromptQueueRunsForThreadIds(threadIds)) {
const activeItem = getActivePromptQueueItem(run);
const activeTarget = activeItem?.target;
const shouldCancelActiveRun = Boolean(activeItem?.dispatched);
deletePromptQueueRun(run);
if (!shouldCancelActiveRun) {
continue;
}
try {
activeTarget?.cancel();
} catch {
// The active run may have already ended.
}
}
requestPromptQueuePumpIfReady();
}
function stopPromptQueueRunForThreadIds(threadIds: string[]) {
stopPromptQueueRun(threadIds);
}
function waitForPromptQueueTargetIdle(run: PromptQueueRun) {
clearPromptQueueRetryTimer(run);
promptQueueActiveRunIds.delete(run.id);
run.waitingForTargetIdle = true;
run.prevStoreRunning = true;
syncPromptQueueUI();
ensurePromptQueueSubscription();
}
function refreshPromptQueueTargetIdleWait(run: PromptQueueRun) {
handlePromptQueueRunState(
run,
useChatRuntimeStore.getState().runningByThreadId,
);
schedulePromptQueueTargetStatePoll(run);
}
function stopLocalPromptQueueRun(run: PromptQueueRun) {
const activeItem = getActivePromptQueueItem(run);
const plan = planLocalPromptQueueStop(
run.items.map((item) => ({
usesLocalModel: item.target.usesLocalModel,
dispatched: item.dispatched,
})),
run.index,
);
if (!plan.cancelActiveItem && plan.heldItemIndexes.length === 0) {
return;
}
const heldItems = plan.heldItemIndexes.map((index) => run.items[index]);
run.items = plan.retainedItemIndexes.map((index) => run.items[index]);
for (const item of heldItems) {
// Held like a failed load: the row stays editable and Resume sends it to the model loaded then.
item.blockedByModelFailure = true;
item.target.releaseModel();
}
if (!getActivePromptQueueItem(run)) {
deletePromptQueueRun(run);
try {
activeItem?.target.cancel();
} catch {
// The active local run may have already ended.
}
return;
}
if (plan.cancelActiveItem) {
waitForPromptQueueTargetIdle(run);
try {
// A permanent cancel would also void the held prompts that share this target.
if (run.items.some((item) => item.target === activeItem?.target)) {
activeItem?.target.cancelActiveRun();
} else {
activeItem?.target.cancel();
}
} catch {
// The active local run may have already ended.
}
refreshPromptQueueTargetIdleWait(run);
return;
}
if (getActivePromptQueueItem(run)?.blockedByModelFailure) {
// Invalidate an attempt already underway for the now-held item.
run.generation += 1;
clearPromptQueueRetryTimer(run);
promptQueueDispatchingRunIds.delete(run.id);
promptQueueActiveRunIds.delete(run.id);
// The cleared timer may be the poll that sees the run this queue waits behind end.
if (shouldPollPromptQueueTargetState(run)) {
refreshPromptQueueTargetIdleWait(run);
}
}
syncPromptQueueUI();
}
function stopLocalPromptQueueRunsForThreadIds(threadIds: string[]) {
if (threadIds.length === 0) {
return;
}
for (const run of getPromptQueueRunsForThreadIds(threadIds)) {
stopLocalPromptQueueRun(run);
}
requestPromptQueuePumpIfReady();
}
function retainPendingPromptQueueItemsAfterFailure(run: PromptQueueRun) {
if (run.paused) {
return true;
}
const activeIndex = Math.max(run.index, 0);
const activeItem = run.items[activeIndex];
if (run.index < 0 || !activeItem?.dispatched) {
return false;
}
activeItem.target.complete();
run.items.splice(activeIndex, 1);
if (!getActivePromptQueueItem(run)) {
deletePromptQueueRun(run);
return true;
}
waitForPromptQueueTargetIdle(run);
refreshPromptQueueTargetIdleWait(run);
return true;
}
function cancelPendingPromptQueueFactoriesForStop<
T extends { temporary: boolean; cancelled: boolean },
>(
pendingFactories: Map<string, T>,
aliases: string[],
detail: PromptQueueStopEventDetail,
) {
const { threadIds, temporaryOnly, localOnly } = detail;
if (localOnly) {
// Hydrated local factories are invalidated by the boundary advance; keep external ones.
return;
}
if (
threadIds &&
threadIds.length > 0 &&
!threadIds.some((threadId) => aliases.includes(threadId))
) {
return;
}
for (const [key, reservation] of pendingFactories) {
if (temporaryOnly && !reservation.temporary) {
continue;
}
reservation.cancelled = true;
pendingFactories.delete(key);
}
}
function stopAllPromptQueueRuns() {
const activeRuns = Array.from(promptQueueRuns.values()).map((run) => ({
activeItem: getActivePromptQueueItem(run),
}));
resetPromptQueues();
for (const { activeItem } of activeRuns) {
const activeTarget = activeItem?.target;
const shouldCancelActiveRun = Boolean(activeItem?.dispatched);
if (!shouldCancelActiveRun) {
continue;
}
try {
activeTarget?.cancel();
} catch {
// The active run may have already ended.
}
}
}
function handlePromptQueueRunFailed(threadId?: string | null, localOnly = false) {
if (localOnly) {
for (const run of promptQueueRuns.values()) {
for (const item of run.items.slice(Math.max(run.index, 0))) {
if (item.target.usesLocalModel && !item.dispatched) {
item.blockedByModelFailure = true;
}
}
if (getActivePromptQueueItem(run)?.blockedByModelFailure) {
run.generation += 1;
clearPromptQueueRetryTimer(run);
promptQueueDispatchingRunIds.delete(run.id);
promptQueueActiveRunIds.delete(run.id);
}
}
syncPromptQueueUI();
return;
}
if (threadId) {
const failedRun = findPromptQueueRunByThreadIds([threadId]);
if (failedRun) {
if (!retainPendingPromptQueueItemsAfterFailure(failedRun)) {
// Keep accepted follow-ups editable after a failed load or preflight.
discardQueuedChatRunSettingsForThread(threadId);
pausePromptQueueRun([threadId]);
}
} else {
discardQueuedChatRunSettingsForThread(threadId);
}
}
// A queued adapter can fail before running is set, so pump other ready queues regardless.
requestPromptQueuePumpIfReady();
}
if (typeof window !== "undefined") {
window.addEventListener(PROMPT_QUEUE_STOP_EVENT, (event) => {
const { threadIds, temporaryOnly, localOnly } =
(event as CustomEvent<PromptQueueStopEventDetail>).detail ?? {};
if (localOnly) {
stopLocalPromptQueueRunsForThreadIds(threadIds ?? []);
return;
}
if (threadIds && threadIds.length > 0) {
stopPromptQueueRunForThreadIds(threadIds);
return;
}
if (temporaryOnly) {
return;
}
stopAllPromptQueueRuns();
});
window.addEventListener(PROMPT_QUEUE_RUN_FAILED_EVENT, (event) => {
const { threadId, localOnly } =
(event as CustomEvent<PromptQueueRunFailedEventDetail>).detail ?? {};
handlePromptQueueRunFailed(threadId, localOnly);
});
}
interface PromptQueueCallbacks {
startQueue: (
items: string[],
waitForCurrentRun?: boolean,
onAborted?: () => void,
) => boolean;
stopQueue: () => void;
}
const noopStartPromptQueue: PromptQueueCallbacks["startQueue"] = () =>
false;
const noopStopPromptQueue: PromptQueueCallbacks["stopQueue"] = () => undefined;
const PromptQueueContext = createContext<PromptQueueCallbacks>({
startQueue: noopStartPromptQueue,
stopQueue: noopStopPromptQueue,
});
// Gap between last message and floating composer, added to the bottom spacer height.
const COMPOSER_SCROLL_GAP_PX = 24;
const FOOTER_GAP_BELOW_SPACER_PX = 10;
// After a run start, composer shrinks apply immediately: the run-start pin owns the bottom.
const RUN_SHRINK_WINDOW_MS = 1000;
// Picked from role and edit state, not a `components` map; see thread-message-slot.ts.
const ThreadMessage: FC = () => {
const role = useAuiState(({ message }) => message.role);
const isEditing = useAuiState(({ message }) => message.composer.isEditing);
let body: ReactNode = null;
switch (threadMessageKind(role, isEditing)) {
case "edit":
body = <EditComposer />;
break;
case "user":
body = <UserMessage />;
break;
case "assistant":
body = <AssistantMessage />;
break;
default:
return null;
}
return (
<>
<CompactionRowDivider />
{body}
<ForkContinuationRule />
<PendingCompactionRule />
</>
);
};
const PendingCompactionRule: FC = () => {
const threadId = useChatRuntimeStore((s) => s.activeThreadId);
const pending = useCompactRequestStore((s) =>
threadId === null ? false : s.requested[threadId] === true,
);
const endsWithReply = useAuiState(
({ message }) => message.isLast && message.role === "assistant",
);
if (!pending || !endsWithReply) return null;
return <CompactionDivider pending={true} className="mt-6" />;
};
// The selector returns the persisted record, which keeps its identity between renders, so a
// row re-renders only when a divider arrives or leaves above it.
const CompactionRowDivider: FC = () => {
const truncation = useAuiState(
({ thread, message }) =>
compactionDividerRows(thread.messages).get(message.id) ?? null,
);
if (!truncation) return null;
return <CompactionDivider truncation={truncation} />;
};
/**
* Resolves the divider against the branch on screen, once for the thread.
*
* Which inherited message closes the history depends on the branch: editing an inherited turn
* starts a sibling and leaves the fork's anchor off screen with earlier inherited messages
* still above it. Selecting the message array in each ROW is what the delete render budget
* forbids, so it is selected here, in one component, and the rows read the id it publishes.
* The walk stops at the first message the fork did not inherit, so it costs the inherited
* count rather than the thread length.
*/
const FORK_BOUNDARY_NONE: readonly string[] = [];
const useTrackForkBoundaryAnchor = (threadId: string | null): void => {
const inherited = useForkBoundaryStore((s) =>
threadId === null
? undefined
: s.boundaryByThreadId[threadId]?.messageIds,
);
const anchor = useAuiState(({ thread }) =>
memoOnArrayByKey(thread.messages, inherited ?? FORK_BOUNDARY_NONE, () =>
forkBoundaryAnchor(thread.messages, inherited),
),
);
useEffect(() => {
setForkBoundaryAnchor(threadId, anchor);
}, [threadId, anchor]);
};
// One read per source chat for the divider's label; a failed read is dropped so a later mount retries.
const forkSourceTitles = new Map<string, Promise<string | null>>();
function forkSourceTitle(sourceThreadId: string): Promise<string | null> {
let title = forkSourceTitles.get(sourceThreadId);
if (!title) {
title = readBackendChatThread(sourceThreadId).then((source) => {
if (source === undefined) forkSourceTitles.delete(sourceThreadId);
return source?.title?.trim() || null;
});
forkSourceTitles.set(sourceThreadId, title);
}
return title;
}
// Closes the history a fork inherited. Rendered by the message it follows, since the row slot
// is propless and the boundary arrives through the store.
const ForkContinuationRule: FC = () => {
const threadId = useChatRuntimeStore((s) => s.activeThreadId);
const messageId = useAuiState(({ message }) => message.id);
// Two plain values so rows do not re-render when an unrelated thread publishes.
const anchor = useForkBoundaryStore((s) =>
threadId === null ? undefined : s.anchorByThreadId[threadId],
);
const sourceThreadId = useForkBoundaryStore((s) =>
threadId === null
? null
: (s.boundaryByThreadId[threadId]?.sourceThreadId ?? null),
);
const navigate = useNavigate();
const isAnchor = anchor !== undefined && anchor === messageId;
const [source, setSource] = useState<{ id: string; title: string | null } | null>(null);
useEffect(() => {
if (!isAnchor || !sourceThreadId) return;
let live = true;
void forkSourceTitle(sourceThreadId).then((title) => {
if (live) setSource({ id: sourceThreadId, title });
});
return () => {
live = false;
};
}, [isAnchor, sourceThreadId]);
if (anchor === undefined || anchor !== messageId) return null;
const sourceTitle = source?.id === sourceThreadId ? source.title : null;
const label = (
<>
<HugeiconsIcon icon={WorkflowCircle05Icon} strokeWidth={1.75} className="size-3.5" />
{sourceTitle ? (
<span className="max-w-80 truncate">Forked from {sourceTitle}</span>
) : (
"Continued from chat"
)}
</>
);
const labelClass =
"inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap leading-none";
return (
<div
data-slot="fork-continuation-rule"
className="mx-auto mt-6 mb-2 flex w-full max-w-(--thread-content-max-width) items-center gap-3 text-muted-foreground text-sm"
>
<span aria-hidden={true} className="h-px flex-1 bg-border" />
{sourceThreadId ? (
<button
type="button"
data-slot="fork-continuation-link"
title="Open the chat this was forked from"
// Checked on click (tombstones are per tab); only a definite "no" stops it.
onClick={async () => {
const source = await readBackendChatThread(sourceThreadId);
if (source === null) {
toast.info("That chat has been deleted.");
return;
}
navigate({
to: "/chat",
// A paired source opens as its comparison, matching the sidebar.
search: source?.pairId
? { compare: source.pairId }
: { thread: sourceThreadId },
replace: false,
});
}}
className={cn(
labelClass,
"cursor-pointer rounded-sm text-foreground underline decoration-foreground/40 underline-offset-2 transition-colors hover:decoration-foreground focus-visible:outline-2 focus-visible:outline-ring focus-visible:outline-offset-2",
)}
>
{label}
</button>
) : (
<span className={labelClass}>{label}</span>
)}
<span aria-hidden={true} className="h-px flex-1 bg-border" />
</div>
);
};
const PREWARM_INPUT_QUIET_MS = 1000;
const PREWARM_INPUT_EVENTS = [
"scroll",
"wheel",
"pointerdown",
"keydown",
"touchmove",
] as const;
let grammarPrewarm: GrammarPrewarm | null = null;
const startGrammarPrewarm = (): void => {
if (grammarPrewarm !== null) return;
let lastInputAt = Number.NEGATIVE_INFINITY;
const noteInput = () => {
lastInputAt = performance.now();
};
for (const type of PREWARM_INPUT_EVENTS) {
document.addEventListener(type, noteInput, { capture: true, passive: true });
}
grammarPrewarm = createGrammarPrewarm(
(code, language, late) => highlightFenceSource(code, language, late),
{
idle: scheduleQuietIdleTask,
wait: (callback, ms) => {
const timer = setTimeout(callback, ms);
return () => clearTimeout(timer);
},
quiet: () =>
!streamActive()
&& !inputPointerHeld()
&& performance.now() - lastInputAt >= PREWARM_INPUT_QUIET_MS,
skip: grammarWarmed,
},
);
grammarPrewarm.start();
};
// Hoisted, so ThreadPrimitive.Messages sees the same children function on every Thread render. An
// inline arrow changes identity each time, invalidating the memo that keeps the message array from
// being rebuilt, and the bail-out below it would never get to run.
const renderThreadMessage = proplessSlot(ThreadMessage);
// Memoized: chat-page renders this inside a store-subscribing component.
export const Thread: FC<{
hideComposer?: boolean;
hideWelcome?: boolean;
targetThreadId?: string;
}> = memo(({ hideComposer, hideWelcome, targetThreadId }) => {
useEffect(() => {
startGrammarPrewarm();
}, []);
const composerAtBottom = useChatPreferencesStore(
(s) => s.newChatComposerPosition >= COMPOSER_POSITION_BOTTOM,
);
// Intent-aware autoscroll replaces assistant-ui's built-in autoscroll to
// prevent the streaming-mutation race that snaps the viewport back to the
// bottom while the user scrolls up (see the hook for the full explanation).
const {
ref: viewportRef,
context: autoScrollContext,
} = useIntentAwareAutoScroll();
const isComposerAttachPending = useAuiState(({ threads }) =>
targetThreadId ? threads.mainThreadId !== targetThreadId : false,
);
const runtimeThreadId = useAuiState(
({ threadListItem }) => threadListItem.id,
);
const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
const threadId = targetThreadId ?? activeThreadId ?? null;
const aui = useAui();
useThreadForkCounts();
useTrackForkBoundaryAnchor(threadId);
const [composerHeight, setComposerHeight] = useState<number | null>(null);
const footerBottomPx =
composerHeight == null
? null
: composerHeight + COMPOSER_SCROLL_GAP_PX - FOOTER_GAP_BELOW_SPACER_PX;
// Viewport element is owned by the autoscroll hook; mirror it locally for
// the spacer clamp math. State, not a ref: the keyed provider remounts the
// viewport on thread switches and the scroll listener must re-attach.
const [viewportSlot, setViewportSlot] = useState<{
el: HTMLElement;
threadId: string;
} | null>(null);
const viewportEl =
viewportSlot !== null && viewportSlot.threadId === runtimeThreadId
? viewportSlot.el
: null;
// Same element in an identity-stable ref, so ProgressiveMessages can read the viewport without a
// prop that would rebuild its row array on thread switch. A ref rather than a document-wide query
// because the Compare panes each mount their own Thread.
const viewportElRef = useRef<HTMLElement | null>(null);
const composedViewportRef = useCallback(
(node: HTMLElement | null) => {
viewportElRef.current = node;
setViewportSlot(node ? { el: node, threadId: runtimeThreadId } : null);
viewportRef(node);
},
[viewportRef, runtimeThreadId],
);
// plain-text copy skips styled data that consumes over 99% of long-thread copy time.
// thread-fast-copy.ts falls back to browser copying unless the substitution is invisible.
useEffect(() => {
if (!viewportEl) return;
return attachThreadFastCopy(viewportEl);
}, [viewportEl]);
useEffect(() => {
if (!viewportEl) return;
return attachWheelHoverSuppression(viewportEl);
}, [viewportEl]);
// Layout effect: shift a remounted viewport before its first paint.
useLayoutEffect(() => {
if (!viewportEl) return;
return watchThreadGutter(viewportEl);
}, [viewportEl]);
// composer growth applies immediately because content below the scroll position is invisible.
// composer shrink waits until clamping scrollTop is safe or a bottom pin owns the motion.
// imperative sizing restores remounted spacers even when composerHeight is unchanged.
const spacerElRef = useRef<HTMLDivElement | null>(null);
const desiredSpacerPxRef = useRef<number | null>(null);
const appliedSpacerPxRef = useRef<number | null>(null);
const applySpacerPx = useCallback((px: number) => {
appliedSpacerPxRef.current = px;
const node = spacerElRef.current;
if (node) {
node.style.height = `${px}px`;
}
}, []);
// Release any deferred shrink, used where the view pins to the bottom anyway.
const releaseSpacerExcess = useCallback(() => {
const desired = desiredSpacerPxRef.current;
const applied = appliedSpacerPxRef.current;
if (desired != null && applied != null && applied > desired) {
applySpacerPx(desired);
}
}, [applySpacerPx]);
const spacerRef = useCallback(
(node: HTMLDivElement | null) => {
spacerElRef.current = node;
const desired = desiredSpacerPxRef.current;
if (node && desired != null) {
applySpacerPx(desired);
}
},
[applySpacerPx],
);
const prevComposerHeightRef = useRef<number | null>(null);
const runStartAtRef = useRef(0);
useLayoutEffect(() => {
const prev = prevComposerHeightRef.current;
prevComposerHeightRef.current = composerHeight;
if (composerHeight == null || hideComposer) {
desiredSpacerPxRef.current = null;
appliedSpacerPxRef.current = null;
spacerElRef.current?.style.removeProperty("height");
autoScrollContext.notifyContentResized();
return;
}
const desired = composerHeight + COMPOSER_SCROLL_GAP_PX;
desiredSpacerPxRef.current = desired;
const applied = appliedSpacerPxRef.current;
if (applied == null || desired >= applied) {
applySpacerPx(desired);
} else {
const distance = viewportEl
? viewportEl.scrollHeight - viewportEl.scrollTop - viewportEl.clientHeight
: Number.POSITIVE_INFINITY;
const runOwnsBottom =
aui.thread().getState().isRunning ||
performance.now() - runStartAtRef.current < RUN_SHRINK_WINDOW_MS;
// At the bottom the shrink only drops blank spacer, so apply it now.
if (
runOwnsBottom ||
distance >= applied - desired ||
autoScrollContext.getIsAtBottom()
) {
applySpacerPx(desired);
}
}
if (prev != null && composerHeight > prev) {
// Detach as if the user scrolled up so nothing re-pins; not mid-run, where growth is tool rows.
if (!aui.thread().getState().isRunning) {
autoScrollContext.detachFromBottom();
}
}
autoScrollContext.notifyContentResized();
}, [composerHeight, hideComposer, autoScrollContext, aui, applySpacerPx, viewportEl]);
// Drop deferred excess once far enough above the bottom that the shrink cannot clamp.
useEffect(() => {
const el = viewportEl;
if (!el) {
return;
}
const onScroll = () => {
const desired = desiredSpacerPxRef.current;
const applied = appliedSpacerPxRef.current;
if (desired == null || applied == null || applied <= desired) {
return;
}
const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
if (distance >= applied - desired) {
applySpacerPx(desired);
}
};
el.addEventListener("scroll", onScroll, { passive: true });
return () => el.removeEventListener("scroll", onScroll);
}, [viewportEl, applySpacerPx]);
// These pin to the bottom; runStart also opens the shrink window for send-clears-chips.
useAuiEvent("thread.runStart", () => {
runStartAtRef.current = performance.now();
releaseSpacerExcess();
});
useAuiEvent("thread.initialize", releaseSpacerExcess);
useAuiEvent("threadListItem.switchedTo", releaseSpacerExcess);
// Page-wide drop; the composer's own dropzone calls preventDefault, so those are skipped here.
const [pageDragging, setPageDragging] = useState(false);
const dragDepth = useRef(0);
const hasFiles = (e: ReactDragEvent) =>
Array.from(e.dataTransfer?.types ?? []).includes("Files");
const onDragEnter = (e: ReactDragEvent) => {
if (isTauri || !hasFiles(e)) return;
dragDepth.current += 1;
setPageDragging(true);
};
const onDragOver = (e: ReactDragEvent) => {
if (isTauri || !hasFiles(e)) return;
e.preventDefault();
};
const onDragLeave = (e: ReactDragEvent) => {
if (isTauri || !hasFiles(e)) return;
dragDepth.current = Math.max(0, dragDepth.current - 1);
if (dragDepth.current === 0) setPageDragging(false);
};
const onDrop = (e: ReactDragEvent) => {
if (isTauri) return;
dragDepth.current = 0;
setPageDragging(false);
// Compare panes hide this composer and use the shared composer's dropzone.
if (hideComposer) return;
if (e.defaultPrevented) return;
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
e.preventDefault();
for (const file of files) {
aui
.composer()
.addAttachment(file)
.catch(() => {
// Adapter shows its own toast (e.g. "Load a model before adding images").
});
}
};
const watchWidthSteps = useCallback(
(root: HTMLDivElement | null) =>
root ? observeThreadWidthSteps(root) : undefined,
[],
);
return (
<GeneratedImageOverlayProvider key={runtimeThreadId} threadId={threadId}>
<PageDragContext.Provider value={pageDragging}>
<IntentAwareScrollProvider value={autoScrollContext}>
<ThreadPrimitive.Viewport
autoScroll={false}
scrollToBottomOnRunStart={false}
scrollToBottomOnInitialize={false}
scrollToBottomOnThreadSwitch={false}
className="aui-thread-host hidden"
onDragEnter={onDragEnter}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
aria-hidden={true}
>
{viewportEl !== null &&
createPortal(
<>
{!hideWelcome && (
<AuiIf
condition={({ thread }) => thread.isEmpty && !thread.isLoading}
>
<ThreadWelcome hideComposer={hideComposer} threadId={threadId} />
</AuiIf>
)}
<TurnNavigator viewportRef={viewportElRef} />
{/* Drop-in for ThreadPrimitive.Messages that mounts only the rows near the reader, with a
spacer for the rows on either side, so a thread costs what is on screen and not its
length. Readers of the whole document (find, print, select all) call
completeProgressiveMounts. It takes the propless slot #9042 introduced: React's bail-out
needs one shared element per row. See thread-window.ts. */}
<ProgressiveMessages
renderMessage={renderThreadMessage}
resetKey={runtimeThreadId}
viewportRef={viewportElRef}
/>
<ForkChatShortcut />
{/* Bottom slack so the last message has room above the sticky
scroll-to-bottom button (and floating composer in single mode),
instead of butting against the footer. */}
<AuiIf condition={({ thread }) => hideWelcome || !thread.isEmpty}>
<div
ref={spacerRef}
className={cn(
"shrink-0",
hideComposer
? "h-16"
: composerHeight == null
? "h-40"
: undefined,
)}
aria-hidden={true}
/>
</AuiIf>
<AuiIf condition={({ thread }) => hideWelcome || !thread.isEmpty}>
<ThreadPrimitive.ViewportFooter
className={cn(
"aui-thread-viewport-footer pointer-events-none sticky z-20 flex w-full justify-center bg-transparent",
hideComposer
? "bottom-3"
: footerBottomPx == null
? "bottom-[calc(150px*var(--ui-space-scale,1))]"
: undefined,
)}
style={
!hideComposer && footerBottomPx != null
? { bottom: footerBottomPx }
: undefined
}
>
<ThreadScrollToBottom />
</ThreadPrimitive.ViewportFooter>
</AuiIf>
</>,
viewportEl,
)}
</ThreadPrimitive.Viewport>
</IntentAwareScrollProvider>
<ThreadPrimitive.Root
ref={watchWidthSteps}
className="aui-root aui-thread-root relative flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden [contain:style]"
style={{
["--thread-max-width" as string]: "var(--custom-chat-max-width, 48rem)",
["--thread-content-max-width" as string]:
"calc(var(--thread-max-width) - 1.5rem)",
}}
onDragEnter={onDragEnter}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
>
{!hideComposer && <AutoReadAloud />}
<IntentAwareScrollProvider value={autoScrollContext}>
<div
ref={composedViewportRef}
className={cn(
"aui-thread-viewport aui-stream-viewport relative flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-x-auto overflow-y-auto scroll-smooth px-5",
hideComposer
? "pt-4"
: "[--thread-header-offset:calc(var(--studio-content-top-inset,0px)-var(--studio-chat-scroller-top,0px)+var(--studio-chat-header-height,48px))] mt-[var(--studio-chat-scroller-top,0px)] pt-[var(--thread-header-offset)]",
)}
/>
<GeneratedImageViewportOverlay
hideComposer={hideComposer}
bottomOffsetPx={footerBottomPx}
/>
{!hideComposer && (
<AuiIf
condition={({ thread }) =>
hideWelcome || !thread.isEmpty || composerAtBottom
}
>
<ThreadComposerDock
disabled={isComposerAttachPending}
threadId={threadId}
onHeightChange={setComposerHeight}
/>
</AuiIf>
)}
</IntentAwareScrollProvider>
</ThreadPrimitive.Root>
<RewindDialogMount />
</PageDragContext.Provider>
</GeneratedImageOverlayProvider>
);
});
Thread.displayName = "Thread";
const GeneratedImageViewportOverlay: FC<{
hideComposer?: boolean;
bottomOffsetPx?: number | null;
}> = ({ hideComposer, bottomOffsetPx }) => {
const { overlay, closeOverlay } = useGeneratedImageOverlay();
useEffect(() => {
if (!overlay) {
return;
}
document
.querySelector<HTMLTextAreaElement>(COMPOSER_INPUT_SELECTOR)
?.focus();
}, [overlay]);
if (!overlay) {
return null;
}
return (
<div className="pointer-events-none absolute inset-0 z-30">
<button
type="button"
className="pointer-events-auto absolute inset-0 bg-background/65 dark:bg-background/55"
onClick={closeOverlay}
aria-label="Close generated image preview"
/>
<section
className={cn(
"pointer-events-none absolute inset-x-5 top-[calc(48px*var(--ui-space-scale,1))] flex flex-col items-center",
hideComposer
? "bottom-4"
: bottomOffsetPx == null
? "bottom-[calc(150px*var(--ui-space-scale,1))]"
: undefined,
)}
style={
!hideComposer && bottomOffsetPx != null
? { bottom: bottomOffsetPx }
: undefined
}
aria-label="Generated image preview"
>
<div className="pointer-events-auto relative flex min-h-0 w-full max-w-[calc(1100px*var(--ui-space-scale,1))] flex-1 flex-col items-center justify-center gap-3 rounded-3xl bg-muted/10 p-3 ring-1 ring-border/20">
<div className="absolute inset-x-3 top-3 z-10 flex justify-end">
<div className="flex shrink-0 items-center gap-1 rounded-full bg-background/70 p-1 ring-1 ring-border/20 backdrop-blur-sm">
<Button
type="button"
variant="ghost"
size="icon-sm"
className="size-7 rounded-full"
onClick={() =>
downloadImagePart({
image: overlay.image,
filename: overlay.filename,
})
}
aria-label="Download generated image"
>
<HugeiconsIcon icon={Download01Icon} className="size-3.5" />
</Button>
<Button
type="button"
variant="ghost"
size="icon-sm"
className="size-7 rounded-full"
onClick={closeOverlay}
aria-label="Close generated image preview"
>
<HugeiconsIcon icon={Cancel01Icon} className="size-3.5" />
</Button>
</div>
</div>
<div className="flex min-h-0 flex-1 items-center justify-center pt-1">
<img
src={overlay.image}
alt={overlay.title}
className="max-h-full max-w-full object-contain"
/>
</div>
<div
className="w-full max-w-[min(100%,46rem)] shrink-0 text-center"
title={overlay.title}
>
<p className="truncate text-xs font-semibold text-foreground/80">
Generated image
</p>
{overlay.metadata ? (
<p className="truncate text-ui-11 font-medium text-muted-foreground">
{overlay.metadata}
</p>
) : null}
{hideComposer ? null : (
<p className="mx-auto mt-2 inline-flex rounded-full bg-primary/10 px-3 py-1 text-xs font-medium text-primary">
Type edits below, then send
</p>
)}
</div>
</div>
</section>
</div>
);
};
// From the end: the footer follows every message row, and a forward walk costs O(rows) where Chromium's `:scope >` is O(1).
const childWithClass = (
parent: Element | null | undefined,
className: string,
): HTMLElement | null => {
for (
let child = parent?.lastElementChild ?? null;
child;
child = child.previousElementSibling
) {
if (child instanceof HTMLElement && child.classList.contains(className)) {
return child;
}
}
return null;
};
const ThreadComposerDock: FC<{
disabled?: boolean;
threadId?: string | null;
onHeightChange?: (height: number | null) => void;
}> = ({ disabled, threadId, onHeightChange }) => {
const { overlay } = useGeneratedImageOverlay();
const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
const threadListItemId = useAuiState(
({ threadListItem }) => threadListItem.id,
);
const threadListItemRemoteId = useAuiState(
({ threadListItem }) => threadListItem.remoteId,
);
const promptQueueThreadIds = compactIds([
threadListItemId,
threadListItemRemoteId,
threadId,
activeThreadId,
]);
const queueVisible = usePromptQueueUI(
(s) => {
const entry = findPromptQueueEntry(s, promptQueueThreadIds);
return Boolean(
entry && s.items.some((item) => item.runId === entry.runId),
);
},
);
const dockRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const el = dockRef.current;
if (!el || !onHeightChange) return;
const measure = () => onHeightChange(el.offsetHeight);
measure();
const resizeObserver = new ResizeObserver(measure);
resizeObserver.observe(el);
return () => {
resizeObserver.disconnect();
onHeightChange(null);
};
}, [onHeightChange]);
const composerColumnRef = useRef<HTMLDivElement | null>(null);
const uiSpaceScale = useUiSpaceScale();
useEffect(() => {
const column = composerColumnRef.current;
return column ? watchComposerClearance(column, uiSpaceScale) : undefined;
}, [uiSpaceScale]);
const dockInnerRef = useRef<HTMLDivElement | null>(null);
useLayoutEffect(() => {
const dock = dockRef.current;
const inner = dockInnerRef.current;
const viewport = childWithClass(dock?.parentElement, "aui-thread-viewport");
if (!dock || !inner || !viewport) return;
const resizeObserver = new ResizeObserver(() => apply());
let observedFooter: Element | null = null;
const apply = () => {
// May fire before the gutter's observer, which would leave the composer a scrollbar off-centre.
syncThreadGutter(viewport);
// The footer is the real column box: WebKit's both-edges gutter reserves 2x the scrollbar on the right, clientWidth 1x.
const footer = childWithClass(viewport, "aui-thread-viewport-footer");
if (footer && footer !== observedFooter) {
if (observedFooter) resizeObserver.unobserve(observedFooter);
resizeObserver.observe(footer);
observedFooter = footer;
}
const dockRect = dock.getBoundingClientRect();
const footerRect = footer?.getBoundingClientRect();
// The footer scrolls sideways with the content; the composer does not.
const inset = footerRect
? composerInsetFromColumn(
{
left: footerRect.left + viewport.scrollLeft,
right: footerRect.right + viewport.scrollLeft,
},
dockRect,
)
: composerColumnInset(readViewportBox(viewport), dockRect);
inner.style.setProperty("--composer-dock-inset-left", `${inset.left}px`);
inner.style.setProperty("--composer-dock-inset-right", `${inset.right}px`);
};
apply();
resizeObserver.observe(viewport);
resizeObserver.observe(dock);
viewport.addEventListener(THREAD_GUTTER_CHANGE_EVENT, apply);
return () => {
resizeObserver.disconnect();
viewport.removeEventListener(THREAD_GUTTER_CHANGE_EVENT, apply);
};
}, []);
return (
<div
ref={dockRef}
className={cn(
// Inset both sides: keeps the bottom fade off the scrollbar without shifting the centre.
"aui-thread-composer-dock pointer-events-none absolute bottom-0 left-0 right-0 md:left-[var(--thread-scrollbar-gutter,10px)] md:right-[var(--thread-scrollbar-gutter,10px)]",
overlay ? "z-40" : "z-20",
)}
>
{/* Column width only: across empty gutters the gradient rounds to a visible seam. */}
<div
aria-hidden={true}
className={cn(
"thread-bottom-fade absolute bottom-0 left-1/2 w-full max-w-(--thread-max-width) -translate-x-1/2 bg-gradient-to-t from-background from-[calc(100%_-_28px)] to-[rgb(from_var(--background)_r_g_b/0)]",
queueVisible
? "h-32 backdrop-blur-[1px] [mask-image:linear-gradient(to_top,black_0%,black_58%,transparent_100%)]"
: "top-[calc(10px*var(--ui-space-scale,1))]",
)}
/>
<div ref={dockInnerRef} className="unsloth-composer-dock-inner relative pb-2">
<div
ref={composerColumnRef}
className="pointer-events-auto mx-auto w-full max-w-(--thread-max-width)"
>
<ComposerAnimated
disabled={disabled}
threadId={threadId}
menuSide="top"
/>
</div>
</div>
</div>
);
};
const ThreadScrollToBottom: FC = () => {
// Our own scroll provider, not ThreadPrimitive.ScrollToBottom. The button toggles via CSS:
// unmounting would trip the hook's MutationObserver as a content change.
const isAtBottom = useIsThreadAtBottom();
const scrollToBottom = useScrollThreadToBottom();
return (
<TooltipIconButton
tooltip="Scroll to bottom"
variant="outline"
onClick={() => scrollToBottom("auto")}
className={cn(
"aui-thread-scroll-to-bottom pointer-events-auto rounded-full p-0 size-[calc(28px*var(--ui-space-scale,1))] bg-background shadow-[0_0_0_0.5px_rgb(0_0_0/0.15)] hover:bg-accent dark:shadow-[0_0_0_0.5px_rgb(255_255_255/0.2)] dark:bg-muted dark:hover:bg-accent",
isAtBottom && "invisible pointer-events-none",
)}
>
<ArrowDownIcon
strokeWidth={1.75}
className="size-[calc(var(--ui-icon-size)*1.125)]"
/>
</TooltipIconButton>
);
};
const pickRandom = <T,>(arr: T[]): T =>
arr[Math.floor(Math.random() * arr.length)];
// Each greeting carries its matching sloth picture so a line always shows the
// same mascot. Greeting varies by local time; name-bearing lines drop the
// name when none is set. Text is a message key, translated at render so a
// language switch updates the open greeting.
type Welcome = { key: TranslationKey; name?: string; sloth: string };
const DEFAULT_WELCOME: Welcome = {
key: "welcome.onYourMind",
sloth: "sloth magnify final.png",
};
function buildWelcome(hour: number, name: string): Welcome {
const g = (key: TranslationKey, sloth: string): Welcome => ({ key, sloth });
const named = (
key: TranslationKey,
namedKey: TranslationKey,
sloth: string,
): Welcome => (name ? { key: namedKey, name, sloth } : { key, sloth });
// Use the name on ~a third of lines (only direct salutations where it reads
// naturally); the rest stay name-free so greetings don't feel repetitive.
const base: Welcome[] = [
named("welcome.goodToSeeYou", "welcome.goodToSeeYouName", "large sloth wave.png"),
g("welcome.readyWhenYouAre", "large sloth thumbs.png"),
DEFAULT_WELCOME,
g("welcome.howCanIHelp", "sloth sir large.png"),
];
if (hour >= 4 && hour < 9) {
const morning = named("welcome.goodMorning", "welcome.goodMorningName", "large sloth drink.png");
return pickRandom([...base, morning]);
}
if (hour >= 17 && hour < 23) {
const evening: Welcome[] = [
named("welcome.goodEvening", "welcome.goodEveningName", "sloth shy large.png"),
g("welcome.tonight", "large sloth glasses.png"),
];
return pickRandom(Math.random() < 0.75 ? evening : base);
}
if (hour >= 23 || hour < 4) {
return pickRandom([
g("welcome.nightOwl", "large sloth glasses.png"),
g("welcome.lateNightIdeas", "large sloth yay.png"),
g("welcome.upLate", "large sloth heart.png"),
named("welcome.nightShift", "welcome.nightShiftName", "large sloth drink.png"),
]);
}
return pickRandom(base);
}
const ThreadWelcome: FC<{
hideComposer?: boolean;
threadId?: string | null;
}> = ({ hideComposer, threadId }) => {
const incognito = useChatRuntimeStore((s) => s.incognito);
const displayName = useUserProfileStore((s) => s.displayName);
const nickname = useUserProfileStore((s) => s.nickname);
const showGreetingSloth = useUserProfileStore((s) => s.showGreetingSloth);
const greetingStyle = useUserProfileStore((s) => s.greetingStyle);
const greetingIcon = useUserProfileStore((s) => s.greetingIcon);
const greetingIconDataUrl = useUserProfileStore((s) => s.greetingIconDataUrl);
const greetingText = useUserProfileStore((s) => s.greetingText);
const greetingImageDataUrl = useUserProfileStore(
(s) => s.greetingImageDataUrl,
);
const greeting = resolveGreeting({
showGreetingSloth,
greetingStyle,
greetingIcon,
greetingIconDataUrl,
greetingText,
greetingImageDataUrl,
});
const customText = greeting.kind === "text" ? greeting.text : null;
// At the bottom, Thread docks the composer and the greeting centres in the space above it.
const composerPosition = useChatPreferencesStore(
(s) => s.newChatComposerPosition,
);
const composerAtBottom = composerPosition >= COMPOSER_POSITION_BOTTOM;
// Below 50 the top padding shrinks; above it, spacers split the leftover height.
const lift =
Math.min(composerPosition, COMPOSER_POSITION_MIDDLE) /
COMPOSER_POSITION_MIDDLE;
const sink = Math.max(0, composerPosition - COMPOSER_POSITION_MIDDLE);
useMarkChatWelcome();
const [welcome, setWelcome] = useState<Welcome>(DEFAULT_WELCOME);
const t = useT();
useEffect(() => {
const raw = nickname.trim() || (displayName.trim().split(/\s+/)[0] ?? "");
const name = raw.length > 20 ? `${raw.slice(0, 20)}…` : raw;
setWelcome(buildWelcome(new Date().getHours(), name));
}, [displayName, nickname]);
const currentEmojiSrc = `Sloth emojis/${welcome.sloth}`;
return (
<div className="aui-thread-welcome-root mx-auto my-auto flex w-full max-w-(--thread-max-width) grow flex-col">
{/* With a files panel showing (chat with files, or project sources), center the whole block. */}
<div
className={cn(
"aui-thread-welcome-center flex w-full grow flex-col items-center",
composerAtBottom
? "justify-center pb-[calc(160px*var(--ui-space-scale,1))]"
: "justify-start has-[.unsloth-files-panel]:justify-center has-[.unsloth-files-panel]:pt-0 has-[.unsloth-files-panel]:pb-[6dvh]",
// Without the greeting, its row and gap become padding, so the composer stays where it was.
// The image row's -76px margin needs at least that much padding.
!composerAtBottom &&
(greeting.kind === "image" && !incognito
? "pt-[max(calc(76px*var(--ui-space-scale,1)),calc(27.5dvh*var(--welcome-lift,1)))]"
: greeting.kind !== "off" || incognito
? "pt-[calc(27.5dvh*var(--welcome-lift,1))]"
: "pt-[calc(27.5dvh*var(--welcome-lift,1)_+_44px*var(--ui-space-scale,1)_+_2.25rem)]"),
)}
style={{ "--welcome-lift": lift } as CSSProperties}
>
{!composerAtBottom && (
<div
aria-hidden="true"
className="[:has(.unsloth-files-panel)>&]:hidden"
style={{ flexGrow: sink }}
/>
)}
{/* No padding, so the composer here is as wide as once it docks. */}
<div className="aui-thread-welcome-message flex w-full flex-col justify-center gap-9">
{/* The setting hides the whole greeting; the incognito title is a status, so it stays. */}
{greeting.kind === "image" && !incognito && (
<div
className={cn(
"unsloth-welcome-greeting flex flex-row items-end justify-center",
!composerAtBottom &&
"h-[calc(120px*var(--ui-space-scale,1))] -mt-[calc(76px*var(--ui-space-scale,1))]",
)}
>
<h1 className="sr-only">{t(welcome.key, welcome.name ? { name: welcome.name } : undefined)}</h1>
<img
src={greeting.src}
alt=""
draggable={false}
className="unsloth-welcome-image fade-in slide-in-from-bottom-1 animate-in max-h-[calc(120px*var(--ui-space-scale,1))] max-w-full object-contain duration-200"
/>
</div>
)}
{(greeting.kind === "text" || incognito) && (
<div
className={cn(
"unsloth-welcome-greeting flex flex-row items-center justify-center gap-[calc(15px*var(--ui-space-scale,1))]",
!incognito &&
greeting.kind === "text" &&
greeting.icon.kind === "none" &&
"min-h-[calc(44px*var(--ui-space-scale,1))]",
)}
>
{!incognito && greeting.kind === "text" && greeting.icon.kind === "sloth" && (
<MascotImg
src={currentEmojiSrc}
className="unsloth-welcome-sloth size-[calc(44px*var(--ui-space-scale,1))] -translate-y-[2px]"
/>
)}
{!incognito && greeting.kind === "text" && greeting.icon.kind === "custom" && (
<img
src={greeting.icon.src}
alt=""
draggable={false}
className="unsloth-welcome-sloth unsloth-welcome-icon size-[calc(44px*var(--ui-space-scale,1))] shrink-0 -translate-y-[2px] object-contain"
/>
)}
<h1
className={cn(
"aui-thread-welcome-message-inner unsloth-welcome-title fade-in slide-in-from-bottom-1 animate-in text-3xl tracking-[-0.02em] duration-200",
customText && "min-w-0 text-balance text-center [overflow-wrap:anywhere]",
)}
>
{incognito
? t("welcome.temporaryChat")
: customText
? customText
: t(welcome.key, welcome.name ? { name: welcome.name } : undefined)}
</h1>
</div>
)}
{incognito && (
<p className="aui-thread-welcome-message-inner fade-in -mt-2 animate-in text-center font-heading font-normal text-muted-foreground text-sm duration-200">
{t("welcome.temporaryChatDescription")}
</p>
)}
{!hideComposer && !composerAtBottom && (
<ComposerAnimated threadId={threadId} />
)}
</div>
{!composerAtBottom && (
<div
aria-hidden="true"
className="[:has(.unsloth-files-panel)>&]:hidden"
style={{ flexGrow: COMPOSER_POSITION_MIDDLE - sink }}
/>
)}
</div>
</div>
);
};
export const ProjectComposer: FC<{
disabled?: boolean;
placeholder?: string;
}> = ({ disabled, placeholder }) => {
return (
<GeneratedImageOverlayProvider>
{/* Queuing in a new project chat misbinds the thread, so the queue waits for a session. */}
<ComposerAnimated
disabled={disabled}
placeholder={placeholder}
disableQueue
/>
{/* Its file cards open previews; the thread's mount is not on this page. */}
</GeneratedImageOverlayProvider>
);
};
const ComposerAnimated: FC<{
disabled?: boolean;
placeholder?: string;
threadId?: string | null;
menuSide?: "top" | "bottom";
disableQueue?: boolean;
}> = ({ disabled, threadId, menuSide, disableQueue }) => {
return (
<div className="unsloth-composer-shell relative mx-auto min-w-0 w-full max-w-[var(--custom-chat-shell-max-width,var(--thread-content-max-width,46rem))]">
<div className="relative z-10 w-full">
<Composer
disabled={disabled}
threadId={threadId}
menuSide={menuSide}
disableQueue={disableQueue}
/>
</div>
</div>
);
};
const PendingAudioChip: FC = () => {
const audioName = useChatRuntimeStore((s) => s.pendingAudioName);
const clearPendingAudio = useChatRuntimeStore((s) => s.clearPendingAudio);
if (!audioName) {
return null;
}
return (
<div className="mb-2 flex w-full flex-row items-center gap-2 px-1.5 pt-0.5 pb-1">
<div className="flex items-center gap-2 rounded-full border border-[color-mix(in_oklab,var(--foreground)_calc(20%*var(--contrast-edge-gain,1)),transparent)] bg-muted px-3 py-1.5 text-xs">
<HugeiconsIcon icon={AiSpeechIcon} className="size-3.5 text-muted-foreground" />
<span className="max-w-48 truncate">{audioName}</span>
<button
type="button"
onClick={clearPendingAudio}
className="flex size-4 items-center justify-center rounded-full hover:bg-destructive hover:text-destructive-foreground"
aria-label="Remove audio"
>
<HugeiconsIcon icon={Cancel01Icon} className="size-3" />
</button>
</div>
</div>
);
};
/** React routes portal events through the composer, whose dropzone captures them first. */
function claimPortaledDrop(event: ReactDragEvent): void {
const target = event.target as Element | null;
if (!target?.closest?.(".aui-composer-attachment-dropzone")) {
event.preventDefault();
}
}
// Never a thread id, so entering or leaving a temporary chat counts as a chat switch.
const INCOGNITO_DRAFT_SCOPE = "\u0000incognito";
const Composer: FC<{
disabled?: boolean;
placeholder?: string;
threadId?: string | null;
menuSide?: "top" | "bottom";
disableQueue?: boolean;
}> = ({ disabled, threadId, menuSide, disableQueue }) => {
const aui = useAui();
const isDictating = useAuiState((s) => s.composer.dictation != null);
const pageDragging = useContext(PageDragContext);
const nativeDragging = useContext(NativeAttachmentDragContext);
const { overlay, closeOverlay } = useGeneratedImageOverlay();
const setImageToolsEnabled = useChatRuntimeStore(
(s) => s.setImageToolsEnabled,
);
const toolsEnabled = useChatRuntimeStore((s) => s.toolsEnabled);
const supportsTools = useChatRuntimeStore((s) => s.supportsTools);
const codeToolsEnabled = useChatRuntimeStore((s) => s.codeToolsEnabled);
const imageToolsEnabled = useChatRuntimeStore((s) => s.imageToolsEnabled);
const supportsBuiltinImageGeneration = useChatRuntimeStore(
(s) => s.supportsBuiltinImageGeneration,
);
// The local Images pill counts only while it is on, like RAG.
const localImagePills = useChatRuntimeStore(localImagePillCount);
const mcpEnabledForChat = useChatRuntimeStore((s) => s.mcpEnabledForChat);
const ragEnabled = useChatRuntimeStore((s) => s.ragEnabled);
const deepResearchEnabled = useChatRuntimeStore(
(s) => s.deepResearchEnabled,
);
const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
const researchThreadId = threadId ?? activeThreadId ?? null;
const researchThreadClaimed = useResearchRunStore((state) =>
researchThreadId ? Boolean(state.claimedThreadIds[researchThreadId]) : false,
);
const liveResearchRunId = useResearchRunStore((state) =>
researchThreadId ? state.latestRunByThreadId[researchThreadId] : undefined,
);
// Derive in the selector: a bare run selector re-renders on every streamed research delta.
const isResearchActive = useResearchRunStore((state) => {
const runId = researchThreadId
? state.latestRunByThreadId[researchThreadId]
: undefined;
const run = runId ? state.sessions[runId]?.run : undefined;
return Boolean(
run && !["completed", "failed", "cancelled"].includes(run.status),
);
});
const hasResearchMessage = useAuiState(({ thread }) =>
threadHasResearchMessage(thread.messages, liveResearchRunId),
);
const researchUsed = researchThreadClaimed || hasResearchMessage;
const effectiveDeepResearchEnabled = deepResearchEnabled && !researchUsed;
const [researchWebsiteAccessOpen, setResearchWebsiteAccessOpen] =
useState(false);
useEffect(() => {
if (!researchUsed) return;
if (hasResearchMessage && researchThreadId) {
useResearchRunStore.getState().setThreadClaimed(researchThreadId, true);
}
if (deepResearchEnabled) {
useChatRuntimeStore.getState().setDeepResearchEnabled(false);
}
}, [deepResearchEnabled, hasResearchMessage, researchThreadId, researchUsed]);
// More than 4 pills: collapse to icons only. Search, Tools, and permissions
// always show; Images, RAG, MCP and Deep Research are conditional.
// Narrow viewports collapse too: the labelled row is wider than a phone composer.
const isMobile = useIsMobile();
const pillCount =
3 +
(ragEnabled ? 1 : 0) +
(supportsBuiltinImageGeneration ? 1 : 0) +
localImagePills +
(mcpEnabledForChat ? 1 : 0) +
(effectiveDeepResearchEnabled ? 1 : 0);
// Long labels can still overflow under the count threshold; measuring collapses just enough.
const { pillRowRef, pillCompact } = useComposerPillFit(
isMobile || pillCount > 4,
);
const setPendingImageEditReference = useChatRuntimeStore(
(s) => s.setPendingImageEditReference,
);
const pastedTextMinChars = useChatPreferencesStore(
(state) => state.pastedTextMinChars,
);
const richTextPaste = useChatPreferencesStore((s) => s.richTextPaste);
const sendShortcut = useChatPreferencesStore((s) => s.sendShortcut);
const submitIntentRef = useRef<ComposerSubmitIntent>("default");
const submitOnKey = useCallback(
(event: KeyboardEvent<HTMLTextAreaElement>, intent: ComposerSubmitIntent) => {
const form = event.currentTarget.form;
if (typeof form?.requestSubmit !== "function") return;
// preventDefault here keeps a queue/steer chord bound to Enter from reaching useShortcut.
const named = followUpShortcutBehavior(event);
submitIntentRef.current = named
? followUpSubmitIntent(
useChatPreferencesStore.getState().followUpBehavior,
named,
)
: intent;
try {
form.requestSubmit();
} finally {
submitIntentRef.current = "default";
}
},
[],
);
// Read by both writers that could put sent text back; armed by every path that clears the composer.
const justSentRef = useRef<SentTextGuard | null>(null);
const draftKeyRef = useRef<string | null>(null);
// True while the @skill picker has a row to pick, so Enter selects it instead of sending.
const mentionConsumesEnterRef = useRef(false);
const setMentionConsumesEnter = useCallback((consumesEnter: boolean) => {
mentionConsumesEnterRef.current = consumesEnter;
}, []);
// True while the @skill picker is open, so Escape closes it without collapsing the composer.
const mentionOpenRef = useRef(false);
const setMentionOpen = useCallback((open: boolean) => {
mentionOpenRef.current = open;
}, []);
const { inputProps, isComposing, isComposingRef, imeSessionOpenRef } =
useImeComposerInputHandlers({
submitOnEnter: true,
skipEnterRef: mentionConsumesEnterRef,
sendShortcut,
onSubmitKey: submitOnKey,
justSentRef,
draftKeyRef,
});
const [youtubeLink, setYoutubeLink] = useState<string | null>(null);
// Plain paste: a paste event carries no modifiers, so the chord is read from the keydown before it.
const plainPasteAtRef = useRef(0);
const notePlainPasteChord = useCallback(
(event: KeyboardEvent<HTMLTextAreaElement>) => {
plainPasteAtRef.current = isPlainPasteChord(event)
? performance.now()
: 0;
if (event.key === "@") refreshSkillsCatalog();
},
[],
);
// Any key release or blur ends it; the time cap covers a release that never lands.
const endPlainPasteChord = useCallback(() => {
plainPasteAtRef.current = 0;
}, []);
const handleFilePaste = useCallback(
(event: ClipboardEvent<HTMLTextAreaElement>) => {
// Read once and cleared, so a menu or scripted paste is never taken for the plain one.
const plainPaste = plainPasteStillCounts(
plainPasteAtRef.current,
performance.now(),
);
plainPasteAtRef.current = 0;
const pastedText = event.clipboardData?.getData("text/plain") ?? "";
const pastedYoutubeUrl = extractYoutubeVideoUrlFromClipboard(
event.clipboardData,
);
// Bulk pastes attach as a file, except image-edit mode, which takes inline text only.
const input = event.currentTarget;
const { selectionStart, selectionEnd, value } = input;
// Attachments serialise after all inline text, so only an end-of-text paste can become one.
const pasteGoesLast = input.selectionEnd === input.value.length;
// Apply the replacement once the attachment lands, same composer only, or a failed paste eats text.
const dropReplacedSelection = () => {
if (selectionStart === selectionEnd) return;
const composer = aui.composer();
if (composer.getState().text !== value) return;
composer.setText(value.slice(0, selectionStart) + value.slice(selectionEnd));
};
const attachedPastedText =
!overlay &&
!plainPaste &&
pasteGoesLast &&
pasteLongTextAsFile(
event,
async (file) => {
await aui.composer().addAttachment(file);
if (wasAttachmentAddCancelled(file)) return;
dropReplacedSelection();
},
() =>
toast.error("Could not attach the pasted text.", {
description: "Paste it again, or paste it in smaller pieces.",
}),
pastedTextMinChars,
);
if (attachedPastedText) return;
pasteClipboardFiles(
event,
async (files) => {
await Promise.all(
files.map((file) => aui.composer().addAttachment(file)),
);
},
() =>
toast.error("Could not paste files.", {
description: "The clipboard item is unsupported, unreadable, or exceeds its size limit.",
}),
);
if (event.defaultPrevented) return;
const markdown =
richTextPaste && !plainPaste ? richPasteMarkdown(event.clipboardData) : null;
if (markdown !== null) {
event.preventDefault();
if (pastedYoutubeUrl) setYoutubeLink(pastedYoutubeUrl);
// Before inserting: execCommand's input event is not a paste, so the guard would refuse a resend.
if (justSentRef.current?.draftKey === draftKeyRef.current) {
justSentRef.current = null;
}
insertAtCaret(input, markdown, (next, caret) => {
aui.composer().setText(next);
requestAnimationFrame(() => input.setSelectionRange(caret, caret));
});
return;
}
if (pastedYoutubeUrl) {
setYoutubeLink(pastedYoutubeUrl);
if (!pastedText.includes(pastedYoutubeUrl)) {
event.preventDefault();
const youtubePasteText =
pastedText.length === 0
? pastedYoutubeUrl
: `${pastedText}${pastedText.endsWith("\n") ? "" : "\n"}${pastedYoutubeUrl}`;
const caret = selectionStart + youtubePasteText.length;
aui
.composer()
.setText(
value.slice(0, selectionStart) +
youtubePasteText +
value.slice(selectionEnd),
);
requestAnimationFrame(() => input.setSelectionRange(caret, caret));
if (justSentRef.current?.draftKey === draftKeyRef.current) {
justSentRef.current = null;
}
return;
}
}
// A paste retires the sent-text guard, but only when the browser will really insert the text.
if (
pastedText.length > 0 &&
!event.defaultPrevented &&
justSentRef.current?.draftKey === draftKeyRef.current
) {
justSentRef.current = null;
}
},
[aui, overlay, pastedTextMinChars, richTextPaste],
);
const composerText = useAuiState(({ composer }) => composer.text);
// Derived, not cleared in an effect: the offer retracts when the link leaves the draft.
const youtubeOfferUrl =
youtubeLink !== null && composerText.includes(youtubeLink)
? youtubeLink
: null;
// Expand only once the input wraps, latched so it cannot flip-flop at the wrap boundary.
const inputRef = useRef<HTMLTextAreaElement>(null);
const composerSurfaceRef = useSurfaceRef(COMPOSER_INPUT_SELECTOR, inputRef);
const editorRef = useRef<HTMLDivElement>(null);
const inputId = useId();
const uiSpaceScale = useUiSpaceScale();
const oneRowHeight = Math.round(40 * uiSpaceScale);
const [editorHeight, setEditorHeight] = useState(40);
const [isWritingExpanded, setIsWritingExpanded] = useState(false);
const detachFromBottom = useDetachThreadFromBottom();
const scrollThreadToBottom = useScrollThreadToBottom();
const threadEmpty = useAuiState(({ thread }) => thread.isEmpty);
const toggleWritingExpanded = () => {
setIsWritingExpanded((expanded) => !expanded);
inputRef.current?.focus({ preventScroll: true });
};
// Welcome page: the bottom pin's stabilizer padding shifted the expanded frame up. On every
// transition (button, Escape, send), so collapsing always re-pins the toolbar into view.
const wasExpandedRef = useRef(false);
useLayoutEffect(() => {
const was = wasExpandedRef.current;
wasExpandedRef.current = isWritingExpanded;
if (!threadEmpty || was === isWritingExpanded) {
return;
}
if (isWritingExpanded) {
detachFromBottom();
} else {
window.requestAnimationFrame(() => scrollThreadToBottom("instant"));
}
}, [isWritingExpanded, threadEmpty, detachFromBottom, scrollThreadToBottom]);
useExpandedComposerFill(editorRef, isWritingExpanded && !isDictating);
// Cache line metrics so getComputedStyle runs once, not per keystroke.
const lineMetricsRef = useRef<{ lineHeight: number; padding: number } | null>(
null,
);
const [isMultiline, setIsMultiline] = useState(false);
useEffect(() => {
if (composerText.length === 0) {
setIsMultiline(false);
lineMetricsRef.current = null;
return;
}
if (isMultiline) return;
const el = inputRef.current;
if (!el) {
return;
}
if (!lineMetricsRef.current) {
const cs = getComputedStyle(el);
const lineHeight = Number.parseFloat(cs.lineHeight) || 24;
const padTop = Number.parseFloat(cs.paddingTop) || 0;
const padBottom = Number.parseFloat(cs.paddingBottom) || 0;
lineMetricsRef.current = { lineHeight, padding: padTop + padBottom };
}
const { lineHeight, padding } = lineMetricsRef.current;
const contentHeight = el.scrollHeight - padding;
if (contentHeight > lineHeight * 1.5) setIsMultiline(true);
}, [composerText, isMultiline]);
// Autosize measures a detached clone, so the expanded editor's min/max-height cannot inflate it.
const [editorRows, setEditorRows] = useState(1);
const handleEditorHeightChange = useCallback(
(height: number, meta: { rowHeight: number }) => {
setEditorHeight(height);
const el = inputRef.current;
// Drafts set without typing change only the height.
if (el) {
markComposerScrollable(el);
markComposerScrollEdges(el);
}
if (meta.rowHeight <= 0) return;
if (el && !lineMetricsRef.current) {
const cs = getComputedStyle(el);
const lineHeight = Number.parseFloat(cs.lineHeight) || 24;
const padTop = Number.parseFloat(cs.paddingTop) || 0;
const padBottom = Number.parseFloat(cs.paddingBottom) || 0;
lineMetricsRef.current = { lineHeight, padding: padTop + padBottom };
}
const padding = lineMetricsRef.current?.padding ?? 0;
setEditorRows(Math.round((height - padding) / meta.rowHeight));
},
[],
);
const showWritingToggle = composerText.includes("\n") || editorRows > 3;
const hasAttachments = useAuiState(
({ composer }) => composer.attachments.length > 0,
);
const hasPendingAttachments = useAuiState(({ composer }) =>
composer.attachments.some(
(attachment) => attachment.status.type === "running",
),
);
const attachmentsAreQueueableText = useAuiState(
({ composer }) =>
composer.attachments.length > 0 &&
composer.attachments.every((attachment) =>
canQueueTextAttachment(attachment) ||
isPastedTextFile((attachment as { file?: File }).file),
),
);
// track every attachment id so removing any file releases paste restore without hashing bodies
const composerAttachmentSignature = useAuiState(({ composer }) =>
composer.attachments.map((attachment) => attachment.id).join(","),
);
const hasPendingAudio = useChatRuntimeStore((s) =>
Boolean(s.pendingAudioName),
);
const threadListItemId = useAuiState(
({ threadListItem }) => threadListItem.id,
);
const nativeAttachmentTargetKey = useNativeAttachmentTargetKey();
const nativeAttachmentOwnerScope = useNativeAttachmentOwnerScope();
const nativeAttachmentTargetKeyRef = useRef(nativeAttachmentTargetKey);
nativeAttachmentTargetKeyRef.current = nativeAttachmentTargetKey;
useEffect(() => {
if (!nativeAttachmentTargetKey) return;
const targetKey = nativeAttachmentTargetKey;
let disposed = false;
// aui.composer() is whichever chat is open now: a switch mid-batch must not take the rest.
const add = async (file: File) => {
if (disposed || nativeAttachmentTargetKeyRef.current !== targetKey) {
throw new Error("The chat changed before this file was attached.");
}
await aui.composer().addAttachment(file);
// The draft-scoped adapter resolves a cancelled add; throwing keeps the file held.
if (wasAttachmentAddCancelled(file)) {
throw new Error("The chat changed before this file was attached.");
}
};
const drain = async () => {
const held = await attachLibraryChatFiles(targetKey, add);
if (held > 0) toast(translate("library.toast.chatFilesWaiting", { count: held }));
};
void drain();
const offers = useLibraryChatHandoffStore.subscribe((state) => {
if (state.pending?.targetKey === targetKey) void drain();
});
let retrying = false;
let again = false;
const retry = async () => {
if (retrying) {
again = true;
return;
}
retrying = true;
do {
again = false;
await attachLibraryChatFiles(targetKey, add, true);
} while (again);
retrying = false;
};
const loads = useChatRuntimeStore.subscribe((state, prev) => {
if (state.modelLoading) return;
if (
prev.modelLoading ||
state.params.checkpoint !== prev.params.checkpoint ||
state.residentCheckpoint !== prev.residentCheckpoint ||
state.loadedIsMultimodal !== prev.loadedIsMultimodal ||
state.codeToolsEnabled !== prev.codeToolsEnabled ||
state.supportsTools !== prev.supportsTools
) {
void retry();
}
});
return () => {
disposed = true;
offers();
loads();
};
}, [nativeAttachmentTargetKey, aui]);
const hasPendingImageAttachments = useNativeIntentStore((s) =>
Boolean(
nativeAttachmentTargetKey &&
(s.pendingImageAttachments[nativeAttachmentTargetKey]?.length ?? 0) > 0,
),
);
const hasPendingOpenDocumentAttachments = useNativeIntentStore((s) =>
Boolean(
nativeAttachmentTargetKey &&
(s.pendingOpenDocumentAttachments[nativeAttachmentTargetKey]?.length ??
0) > 0,
),
);
const registeringImageDrops = useNativeIntentStore(
(s) => s.registeringImageDrops > 0,
);
const [materializingDroppedImages, setMaterializingDroppedImages] =
useState(false);
const [
materializingDroppedOpenDocuments,
setMaterializingDroppedOpenDocuments,
] = useState(false);
const hasPendingAudioAttachments = useNativeIntentStore((s) =>
Boolean(
nativeAttachmentTargetKey &&
(s.pendingAudioAttachments[nativeAttachmentTargetKey]?.length ?? 0) > 0,
),
);
const registeringAudioDrops = useNativeIntentStore(
(s) => s.registeringAudioDrops > 0,
);
const [materializingDroppedAudio, setMaterializingDroppedAudio] =
useState(false);
const hasPendingVideoAttachments = useNativeIntentStore((s) =>
Boolean(
nativeAttachmentTargetKey &&
(s.pendingVideoAttachments[nativeAttachmentTargetKey]?.length ?? 0) > 0,
),
);
const registeringVideoDrops = useNativeIntentStore(
(s) => s.registeringVideoDrops > 0,
);
const [materializingDroppedVideo, setMaterializingDroppedVideo] =
useState(false);
// A parked send must not fire on a failed drop. Assigned below once the callback exists.
const cancelQueuedSendRef = useRef<(() => void) | null>(null);
const composerIdentityRef = useRef("");
const nativeAttachmentOwner = nativeAttachmentOwnerScope
? JSON.stringify([nativeAttachmentOwnerScope, threadListItemId ?? ""])
: threadListItemId ?? "";
const nativeAttachmentOwnerRef = useRef(nativeAttachmentOwner);
nativeAttachmentOwnerRef.current = nativeAttachmentOwner;
const imageDropFailures = useNativeIntentStore(
(s) => (nativeAttachmentTargetKey ? s.imageDropFailures[nativeAttachmentTargetKey] : 0) ?? 0,
);
const seenImageDropFailuresRef = useRef(imageDropFailures);
// Registration fails before an intent exists, so cancel the parked send here.
useEffect(() => {
if (seenImageDropFailuresRef.current === imageDropFailures) return;
seenImageDropFailuresRef.current = imageDropFailures;
cancelQueuedSendRef.current?.();
}, [imageDropFailures]);
const audioDropFailures = useNativeIntentStore(
(s) => (nativeAttachmentTargetKey ? s.audioDropFailures[nativeAttachmentTargetKey] : 0) ?? 0,
);
const seenAudioDropFailuresRef = useRef(audioDropFailures);
// Cancel the parked send before `endAudioDropRegistration` reopens the gate.
useEffect(() => {
if (seenAudioDropFailuresRef.current === audioDropFailures) return;
seenAudioDropFailuresRef.current = audioDropFailures;
cancelQueuedSendRef.current?.();
}, [audioDropFailures]);
const videoDropFailures = useNativeIntentStore(
(s) => (nativeAttachmentTargetKey ? s.videoDropFailures[nativeAttachmentTargetKey] : 0) ?? 0,
);
const seenVideoDropFailuresRef = useRef(videoDropFailures);
// Cancel the parked send before `endVideoDropRegistration` reopens the gate.
useEffect(() => {
if (seenVideoDropFailuresRef.current === videoDropFailures) return;
seenVideoDropFailuresRef.current = videoDropFailures;
cancelQueuedSendRef.current?.();
}, [videoDropFailures]);
// Hold the send gate while the dropped clip is registered and read.
useEffect(() => {
// aui.composer() is still the previous chat until the runtime reaches this route's thread.
if (!nativeAttachmentTargetKey || disabled) {
return;
}
const targetKey = nativeAttachmentTargetKey;
const identityAtSetup = nativeAttachmentOwnerRef.current;
useNativeIntentStore
.getState()
.claimAudioAttachments(identityAtSetup, targetKey);
let disposed = false;
let draining = false;
const cancelledOnce = new Set<string>();
// A re-key follows the same composer; a thread switch parks the clip back.
const stillThisComposer = () =>
nativeAttachmentOwnerRef.current === identityAtSetup;
// A remount hides the new key, so tag the batch; the next instance claims it.
const requeue = (intents: NativeIntent[]) => {
const key = stillThisComposer()
? (nativeAttachmentTargetKeyRef.current ?? targetKey)
: targetKey;
const store = useNativeIntentStore.getState();
store.addAudioAttachments(key, intents);
store.noteAudioDropOwner(key, identityAtSetup);
};
const drainPendingAudio = async () => {
if (disposed || draining) return;
draining = true;
setMaterializingDroppedAudio(true);
try {
while (!disposed) {
const intents = useNativeIntentStore
.getState()
.takeAudioAttachments(targetKey);
if (intents.length === 0) break;
for (const [index, intent] of intents.entries()) {
if (disposed) {
requeue(intents.slice(index));
return;
}
let file: File;
try {
file = await nativeAttachmentIntentToFile(intent);
} catch (error) {
toast.error("Could not attach dropped audio", {
description:
error instanceof Error ? error.message : String(error),
});
if (stillThisComposer()) cancelQueuedSendRef.current?.();
continue;
}
// The read is async; a chat switch in that window must not steal the clip.
if (
disposed ||
nativeAttachmentTargetKeyRef.current !== targetKey
) {
requeue(intents.slice(index));
return;
}
try {
await aui.composer().addAttachment(file);
if (wasAttachmentAddCancelled(file)) {
// Same owner and key means the destination refused it: retry once, never spin.
const sameDestination =
stillThisComposer() &&
nativeAttachmentTargetKeyRef.current === targetKey;
if (!sameDestination || !cancelledOnce.has(intent.id)) {
if (sameDestination) cancelledOnce.add(intent.id);
requeue(intents.slice(index));
return;
}
cancelledOnce.delete(intent.id);
cancelQueuedSendRef.current?.();
continue;
}
} catch {
// The adapter toasted. Keep going: a later, smaller clip may still fit.
if (stillThisComposer()) cancelQueuedSendRef.current?.();
continue;
}
}
}
} finally {
draining = false;
// A drain for an abandoned target must not touch the flag; the live target may own it.
if (!disposed) {
// Early returns requeue mid-batch, and drops can land while `draining` gated the subscription.
const pending =
useNativeIntentStore.getState().pendingAudioAttachments[targetKey]
?.length ?? 0;
// Only the owning instance re-drains; otherwise the batch stays parked instead of looping.
if (pending > 0 && stillThisComposer()) {
void drainPendingAudio();
} else {
setMaterializingDroppedAudio(false);
}
}
}
};
const unsubscribe = useNativeIntentStore.subscribe((state) => {
// A predecessor's requeue can land after setup, so keep watching.
const orphaned = Object.entries(state.audioDropOwners).some(
([key, owner]) => owner === identityAtSetup && key !== targetKey,
);
if (orphaned) {
useNativeIntentStore
.getState()
.claimAudioAttachments(identityAtSetup, targetKey);
return;
}
if ((state.pendingAudioAttachments[targetKey]?.length ?? 0) > 0) {
void drainPendingAudio();
}
});
void drainPendingAudio();
return () => {
disposed = true;
setMaterializingDroppedAudio(false);
unsubscribe();
};
}, [nativeAttachmentTargetKey, nativeAttachmentOwner, aui, disabled]);
// Same drain as audio: one clip per message, and the send gate holds across the read.
useEffect(() => {
if (!nativeAttachmentTargetKey || disabled) {
return;
}
const targetKey = nativeAttachmentTargetKey;
const identityAtSetup = nativeAttachmentOwnerRef.current;
useNativeIntentStore
.getState()
.claimVideoAttachments(identityAtSetup, targetKey);
let disposed = false;
let draining = false;
const cancelledOnce = new Set<string>();
const stillThisComposer = () =>
nativeAttachmentOwnerRef.current === identityAtSetup;
const requeue = (intents: NativeIntent[]) => {
const key = stillThisComposer()
? (nativeAttachmentTargetKeyRef.current ?? targetKey)
: targetKey;
const store = useNativeIntentStore.getState();
store.addVideoAttachments(key, intents);
store.noteVideoDropOwner(key, identityAtSetup);
};
const drainPendingVideo = async () => {
if (disposed || draining) return;
draining = true;
setMaterializingDroppedVideo(true);
try {
while (!disposed) {
const intents = useNativeIntentStore
.getState()
.takeVideoAttachments(targetKey);
if (intents.length === 0) break;
for (const [index, intent] of intents.entries()) {
if (disposed) {
requeue(intents.slice(index));
return;
}
let file: File;
try {
file = await nativeAttachmentIntentToFile(intent);
} catch (error) {
toast.error("Could not attach dropped video", {
description:
error instanceof Error ? error.message : String(error),
});
if (stillThisComposer()) cancelQueuedSendRef.current?.();
continue;
}
if (
disposed ||
nativeAttachmentTargetKeyRef.current !== targetKey
) {
requeue(intents.slice(index));
return;
}
try {
await aui.composer().addAttachment(file);
if (wasAttachmentAddCancelled(file)) {
// Same owner and key means the destination refused it: retry once, never spin.
const sameDestination =
stillThisComposer() &&
nativeAttachmentTargetKeyRef.current === targetKey;
if (!sameDestination || !cancelledOnce.has(intent.id)) {
if (sameDestination) cancelledOnce.add(intent.id);
requeue(intents.slice(index));
return;
}
cancelledOnce.delete(intent.id);
cancelQueuedSendRef.current?.();
continue;
}
} catch {
// Chat-wide failure and the adapter already toasted: stop quietly.
if (stillThisComposer()) cancelQueuedSendRef.current?.();
return;
}
}
}
} finally {
draining = false;
if (!disposed) {
const pending =
useNativeIntentStore.getState().pendingVideoAttachments[targetKey]
?.length ?? 0;
if (pending > 0 && stillThisComposer()) {
void drainPendingVideo();
} else {
setMaterializingDroppedVideo(false);
}
}
}
};
const unsubscribe = useNativeIntentStore.subscribe((state) => {
const orphaned = Object.entries(state.videoDropOwners).some(
([key, owner]) => owner === identityAtSetup && key !== targetKey,
);
if (orphaned) {
useNativeIntentStore
.getState()
.claimVideoAttachments(identityAtSetup, targetKey);
return;
}
if ((state.pendingVideoAttachments[targetKey]?.length ?? 0) > 0) {
void drainPendingVideo();
}
});
void drainPendingVideo();
return () => {
disposed = true;
setMaterializingDroppedVideo(false);
unsubscribe();
};
}, [nativeAttachmentTargetKey, nativeAttachmentOwner, aui, disabled]);
useEffect(() => {
if (!nativeAttachmentTargetKey || disabled) {
return;
}
const targetKey = nativeAttachmentTargetKey;
const identityAtSetup = nativeAttachmentOwnerRef.current;
useNativeIntentStore
.getState()
.claimImageAttachments(identityAtSetup, targetKey);
let disposed = false;
let draining = false;
const cancelledOnce = new Set<string>();
// A fresh chat re-keys from "single:new" to its thread id under the same composer, so follow it.
const stillThisComposer = () =>
nativeAttachmentOwnerRef.current === identityAtSetup;
const requeueKey = () =>
stillThisComposer()
? (nativeAttachmentTargetKeyRef.current ?? targetKey)
: targetKey;
// Persisting remounts this composer, so tag the batch; the next instance claims it.
const requeue = (intents: NativeIntent[]) => {
const key = requeueKey();
const store = useNativeIntentStore.getState();
store.addImageAttachments(key, intents);
store.noteImageDropOwner(key, identityAtSetup);
};
const drainPendingImages = async () => {
if (disposed || draining) {
return;
}
draining = true;
setMaterializingDroppedImages(true);
let readFailures = 0;
let lastReadError: unknown;
try {
while (!disposed) {
const intents = useNativeIntentStore
.getState()
.takeImageAttachments(targetKey);
if (intents.length === 0) {
break;
}
for (let index = 0; index < intents.length; index += 1) {
if (disposed) {
requeue(intents.slice(index));
return;
}
const intent = intents[index]!;
let file: File;
try {
file = await normalizeChatImage(
await nativeAttachmentIntentToFile(intent),
);
} catch (error) {
// Report once below rather than one toast per file: a whole batch
// can go unreadable at once (volume ejected, tokens expired).
readFailures += 1;
lastReadError = error;
continue;
}
if (
disposed ||
nativeAttachmentTargetKeyRef.current !== targetKey
) {
requeue(intents.slice(index));
return;
}
try {
await aui.composer().addAttachment(file);
if (wasAttachmentAddCancelled(file)) {
// Same owner and key means the destination refused it: retry once, never spin.
const sameDestination =
stillThisComposer() &&
nativeAttachmentTargetKeyRef.current === targetKey;
if (!sameDestination || !cancelledOnce.has(intent.id)) {
if (sameDestination) cancelledOnce.add(intent.id);
requeue(intents.slice(index));
return;
}
cancelledOnce.delete(intent.id);
cancelQueuedSendRef.current?.();
continue;
}
} catch {
// Chat-wide failure and the adapter already toasted: stop quietly.
if (stillThisComposer()) cancelQueuedSendRef.current?.();
return;
}
}
}
} finally {
draining = false;
if (readFailures > 0) {
toast.error("Could not attach dropped images", {
description:
lastReadError instanceof Error
? lastReadError.message
: String(lastReadError),
});
if (stillThisComposer()) cancelQueuedSendRef.current?.();
}
if (disposed) {
return;
}
const pending =
useNativeIntentStore.getState().pendingImageAttachments[targetKey]
?.length ?? 0;
if (pending > 0 && stillThisComposer()) {
void drainPendingImages();
} else {
setMaterializingDroppedImages(false);
}
}
};
const unsubscribe = useNativeIntentStore.subscribe((state) => {
// The predecessor's requeue can land after the setup claim, so keep watching.
const orphaned = Object.entries(state.imageDropOwners).some(
([key, owner]) => owner === identityAtSetup && key !== targetKey,
);
if (orphaned) {
useNativeIntentStore
.getState()
.claimImageAttachments(identityAtSetup, targetKey);
return;
}
const pending =
state.pendingImageAttachments[targetKey]?.length ?? 0;
if (pending > 0) {
void drainPendingImages();
}
});
void drainPendingImages();
return () => {
disposed = true;
setMaterializingDroppedImages(false);
unsubscribe();
};
}, [nativeAttachmentTargetKey, nativeAttachmentOwner, aui, disabled]);
useEffect(() => {
if (!nativeAttachmentTargetKey || disabled) {
return;
}
const targetKey = nativeAttachmentTargetKey;
const identityAtSetup = nativeAttachmentOwnerRef.current;
useNativeIntentStore
.getState()
.claimImageAttachments(identityAtSetup, targetKey);
let disposed = false;
let draining = false;
const cancelledOnce = new Set<string>();
const stillThisComposer = () =>
nativeAttachmentOwnerRef.current === identityAtSetup;
const requeue = (intents: NativeIntent[]) => {
const key = stillThisComposer()
? (nativeAttachmentTargetKeyRef.current ?? targetKey)
: targetKey;
const store = useNativeIntentStore.getState();
store.addOpenDocumentAttachments(key, intents);
store.noteImageDropOwner(key, identityAtSetup);
};
const drainPendingOpenDocuments = async () => {
if (disposed || draining) return;
draining = true;
setMaterializingDroppedOpenDocuments(true);
try {
while (!disposed) {
const intents = useNativeIntentStore
.getState()
.takeOpenDocumentAttachments(targetKey);
if (intents.length === 0) break;
for (const [index, intent] of intents.entries()) {
if (disposed) {
requeue(intents.slice(index));
return;
}
let file: File;
try {
file = await nativeAttachmentIntentToFile(intent);
} catch (error) {
toast.error("Could not attach dropped document", {
description:
error instanceof Error ? error.message : String(error),
});
if (stillThisComposer()) cancelQueuedSendRef.current?.();
continue;
}
if (
disposed ||
nativeAttachmentTargetKeyRef.current !== targetKey
) {
requeue(intents.slice(index));
return;
}
try {
await aui.composer().addAttachment(file);
if (wasAttachmentAddCancelled(file)) {
// Same owner and key means the destination refused it: retry once, never spin.
const sameDestination =
stillThisComposer() &&
nativeAttachmentTargetKeyRef.current === targetKey;
if (!sameDestination || !cancelledOnce.has(intent.id)) {
if (sameDestination) cancelledOnce.add(intent.id);
requeue(intents.slice(index));
return;
}
cancelledOnce.delete(intent.id);
cancelQueuedSendRef.current?.();
continue;
}
} catch {
if (stillThisComposer()) cancelQueuedSendRef.current?.();
}
}
}
} finally {
draining = false;
if (!disposed) {
const pending =
useNativeIntentStore.getState().pendingOpenDocumentAttachments[
targetKey
]?.length ?? 0;
if (pending > 0 && stillThisComposer()) {
void drainPendingOpenDocuments();
} else {
setMaterializingDroppedOpenDocuments(false);
}
}
}
};
const unsubscribe = useNativeIntentStore.subscribe((state) => {
const orphaned = Object.entries(state.imageDropOwners).some(
([key, owner]) => owner === identityAtSetup && key !== targetKey,
);
if (orphaned) {
useNativeIntentStore
.getState()
.claimImageAttachments(identityAtSetup, targetKey);
return;
}
if (
(state.pendingOpenDocumentAttachments[targetKey]?.length ?? 0) > 0
) {
void drainPendingOpenDocuments();
}
});
void drainPendingOpenDocuments();
return () => {
disposed = true;
setMaterializingDroppedOpenDocuments(false);
unsubscribe();
};
}, [nativeAttachmentTargetKey, nativeAttachmentOwner, aui, disabled]);
const hasMaterializingImageAttachments =
registeringImageDrops ||
hasPendingImageAttachments ||
materializingDroppedImages ||
hasPendingOpenDocumentAttachments ||
materializingDroppedOpenDocuments;
const hasMaterializingAudioAttachments =
registeringAudioDrops ||
hasPendingAudioAttachments ||
materializingDroppedAudio;
const hasMaterializingVideoAttachments =
registeringVideoDrops ||
hasPendingVideoAttachments ||
materializingDroppedVideo;
const threadIsRunning = useAuiState(({ thread }) => thread.isRunning);
const threadListItemRemoteId = useAuiState(
({ threadListItem }) => threadListItem.remoteId,
);
const referenceThreadId = threadId ?? activeThreadId ?? null;
// Not referenceThreadId: it moves null -> remote id on first persist of the same composer.
const composerIdentity = threadListItemId ?? "";
composerIdentityRef.current = composerIdentity;
const chatActive = useChatActive();
// assistant-ui's Escape cancels the run and prevents the key, which would block declining a tool request.
// Only when decline would take that Escape: its card is keyboard-ready on this screen (not parked in a
// background chat, where Escape would then stop nothing), and not once rebound.
const declineMounted = useShortcutAvailable("declineToolRequest", true);
const declineOwnsEscape = useKeyboardShortcutsStore((s) => {
const bindings = resolveBindings(s.overrides, "declineToolRequest");
return bindings.primary === "Escape" || bindings.alternate === "Escape";
});
const composerFocusable = useContext(ChatComposerFocusableContext);
// While a Run handoff owns the model picker the input ignores focus(), so its autofocus cannot
// dismiss the picker. Gating autoFocus would focus it when the gate lifts; inert would also block
// a press and read as Chat being covered.
useLayoutEffect(() => {
const input = inputRef.current;
if (composerFocusable || !input) return;
input.focus = () => {};
return () => {
Reflect.deleteProperty(input, "focus");
};
}, [composerFocusable, isDictating]);
const readAudioUploadDraft = useCallback(
() => aui.composer().getState().text,
[aui],
);
const writeAudioUploadDraft = useCallback(
(value: string) => aui.composer().setText(value),
[aui],
);
const focusAudioUploadDraft = useCallback(() => {
inputRef.current?.focus({ preventScroll: true });
}, []);
const dictationEntryDisabled = !chatActive;
const audioUpload = useChatAudioUpload({
owner: composerIdentity,
chatId: referenceThreadId,
disabled: dictationEntryDisabled || isDictating,
readDraft: readAudioUploadDraft,
writeDraft: writeAudioUploadDraft,
focusDraft: focusAudioUploadDraft,
});
const cancelAudioUpload = audioUpload.cancel;
// Read at Send time so a send materializing after a project switch is filed where made.
const projectScope = useChatProjectScope();
// One array per set of ids, not per render: the queue callbacks and the context they feed are
// keyed on these, and the composer renders on every keystroke.
const promptQueueThreadIds = useMemo(
() => compactIds([threadListItemId, threadListItemRemoteId, threadId]),
[threadListItemId, threadListItemRemoteId, threadId],
);
const preStreamThreadIds = useMemo(
() => compactIds([...promptQueueThreadIds, referenceThreadId]),
[promptQueueThreadIds, referenceThreadId],
);
const preStreamRunReservationRef = useRef<symbol | null>(null);
// Wakes a parked attachment when a preflight releases without ever streaming.
const preStreamRunActive = useSyncExternalStore(
subscribePreStreamRunReservations,
() => hasPreStreamRunReservation(preStreamThreadIds),
() => false,
);
useEffect(() => {
const token = preStreamRunReservationRef.current;
if (!token) {
return;
}
adoptPreStreamRunReservation(token, preStreamThreadIds);
// Keep the reservation until the adapter consumes or fails it: isRunning can show before
// preflight finishes, and releasing early hides the send from a model-change gate.
}, [preStreamThreadIds]);
const promptQueueActive = usePromptQueueUI((s) =>
Boolean(findPromptQueueEntry(s, promptQueueThreadIds)),
);
const hasSendableContent =
composerText.trim().length > 0 || hasAttachments || hasPendingAudio;
const composerAcceptsQueueing =
!hasPendingAudio &&
!isComposing &&
!hasPendingAttachments &&
!hasMaterializingImageAttachments &&
!hasMaterializingAudioAttachments &&
!hasMaterializingVideoAttachments &&
!disabled &&
!overlay;
const canQueueCurrentPrompt =
composerText.trim().length > 0 && !hasAttachments && composerAcceptsQueueing;
// validated text uploads and long pastes can join the per-chat queue
const canQueueTextAttachmentsPrompt =
attachmentsAreQueueableText && composerAcceptsQueueing;
// attachments without prepared text stay parked until the run and queue are idle
const canQueueAttachmentPrompt =
hasAttachments && !attachmentsAreQueueableText && composerAcceptsQueueing;
const incognito = useChatRuntimeStore((s) => s.incognito);
const shareDraft = useChatPreferencesStore((s) => s.shareComposerDraft);
// Route and active IDs can lead the runtime switch; drafts belong to the composer on screen.
const draftThreadId = threadListItemRemoteId ?? NEW_CHAT_DRAFT_ID;
const restoredDraftScopeRef = useRef<string | undefined>(undefined);
const previousDraftIdentityRef = useRef({
draftThreadId,
threadListItemId,
incognito,
});
const draftKey = composerDraftKey(draftThreadId, shareDraft);
const draftScope = incognito
? INCOGNITO_DRAFT_SCOPE
: `${draftKey}:${threadListItemId}`;
// Text that came from Compare, so saving it back can't overwrite a newer write.
const remoteDraftRef = useRef<string | null>(null);
const [draftSource] = useState(() => Symbol("chat composer"));
// Whose pastes are on screen: a temporary chat's never cross into the saved draft, nor back.
const pasteKeyShownRef = useRef<string | null>(incognito ? null : draftKey);
// unsent pasted File objects need a separate slot because they exist only in memory
const pasteDraftKey = composerPasteDraftKey(draftThreadId, shareDraft);
const lastDraftScopeRef = useRef(draftScope);
// save only after this chat's paste restore finishes to avoid premature clearing
const restoredPasteScopeRef = useRef<string | null | undefined>(undefined);
const restoringPasteScopeRef = useRef<string | null | undefined>(undefined);
const draftSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const pendingDraftRef = useRef<{ key: string; text: string } | null>(null);
// The key flips before the runtime swaps threads: until the restore shows, the text is the last chat's.
const awaitingRestoreRef = useRef<{ scope: string; stale: string; text: string } | null>(null);
useEffect(() => {
const previous = previousDraftIdentityRef.current;
previousDraftIdentityRef.current = {
draftThreadId,
threadListItemId,
incognito,
};
const composer = aui.composer();
if (!composer.getState().isEditing) return;
if (
restoredDraftScopeRef.current === draftScope &&
previous.threadListItemId === threadListItemId
) return;
restoredDraftScopeRef.current = draftScope;
// First persistence names the same conversation; navigation must still restore its own draft.
if (
!incognito &&
!previous.incognito &&
!shareDraft &&
previous.draftThreadId === NEW_CHAT_DRAFT_ID &&
aui.threadListItem().getState().remoteId === draftThreadId &&
previous.threadListItemId === threadListItemId &&
previous.draftThreadId !== draftThreadId
) {
const previousKey = composerDraftKey(previous.draftThreadId);
const previousPasteKey = composerPasteDraftKey(previous.draftThreadId);
if (justSentRef.current?.draftKey === previousKey) {
justSentRef.current = { ...justSentRef.current, draftKey };
}
const text = latestDraft(previousKey);
writeComposerDraft(draftKey, text);
stageComposerDraft(draftKey, text);
writePasteDraft(pasteDraftKey, latestPasteDraft(previousPasteKey));
writeComposerDraft(previousKey, "");
writePasteDraft(previousPasteKey, []);
pasteKeyShownRef.current = draftKey;
}
if (draftScope === INCOGNITO_DRAFT_SCOPE) {
composer.setText("");
return;
}
remoteDraftRef.current = null;
const draft = latestDraft(draftKey);
// A save that raced the send still holds the sent text, so restoring it
// would undo the clear. Clear rather than return early, which would leave
// the previous thread's text on screen under this one.
if (sentTextGuardBlocksDraft(justSentRef.current, draft, draftKey)) {
// Inline because clearStoredDraft is declared below; cancel the pending save too.
if (draftSaveTimerRef.current !== null) {
clearTimeout(draftSaveTimerRef.current);
draftSaveTimerRef.current = null;
}
writeComposerDraft(draftKey, "");
awaitingRestoreRef.current = { scope: draftScope, stale: composer.getState().text, text: "" };
composer.setText("");
return;
}
awaitingRestoreRef.current = { scope: draftScope, stale: composer.getState().text, text: draft };
composer.setText(draft);
}, [
draftScope,
draftKey,
pasteDraftKey,
shareDraft,
draftThreadId,
threadListItemId,
incognito,
aui,
]);
// Compare's composer, so whichever is on screen shows the latest draft.
useEffect(() => {
if (!shareDraft || draftScope === INCOGNITO_DRAFT_SCOPE) return;
return subscribeDraft(draftSource, (text) => {
const composer = aui.composer();
if (!composer.getState().isEditing) return;
remoteDraftRef.current = text;
composer.setText(text);
});
}, [draftScope, draftSource, shareDraft, aui]);
// The saved-prompt menu and the prompt storage dialog fill the composer
// directly, bypassing the guard. Text appearing after the send was put there
// deliberately, so retire. Read live, or a
// pending render retires it on stale text. Must stay after the restore
// above, which clears the raced draft this would otherwise retire on.
useEffect(() => {
const guard = justSentRef.current;
if (guard === null || guard.draftKey !== draftKey) return;
if (aui.composer().getState().text.length === 0) return;
justSentRef.current = null;
}, [composerText, draftKey, aui]);
// Separate from the text restore, which must stay keyed on the draft alone.
useEffect(() => {
const composer = aui.composer();
if (!composer.getState().isEditing) return;
if (restoredPasteScopeRef.current === draftScope) return;
if (pasteKeyShownRef.current !== (incognito ? null : draftKey)) {
const pasted = composer
.getState()
.attachments.filter(
(attachment) =>
pastedTextOf((attachment as { file?: File }).file) !== undefined,
);
if (pasted.length > 0) {
// Removing them changes the attachments, which runs this again.
for (const attachment of pasted) {
void composer.attachment({ id: attachment.id }).remove();
}
return;
}
}
pasteKeyShownRef.current = incognito ? null : draftKey;
if (draftScope === INCOGNITO_DRAFT_SCOPE) {
restoredPasteScopeRef.current = draftScope;
return;
}
// Only the saved pastes not on screen: the composer can outlive a switch holding
// them, and another attachment (a handoff's image) is no sign they were restored.
const shown = composer
.getState()
.attachments.flatMap((attachment) => {
const text = pastedTextOf((attachment as { file?: File }).file);
return text === undefined ? [] : [text];
});
const missing = latestPasteDraft(pasteDraftKey).filter((text) => {
const at = shown.indexOf(text);
if (at === -1) return true;
shown.splice(at, 1);
return false;
});
if (missing.length === 0) {
restoredPasteScopeRef.current = draftScope;
return;
}
// Its own additions re-run this; one pass per scope, or they double up.
if (restoringPasteScopeRef.current === draftScope) return;
restoringPasteScopeRef.current = draftScope;
// Claim the chat only once the attachments are in, so the save effect
// cannot write an empty composer over the draft still being restored.
const restoredFiles = missing.map(createPastedTextFile);
void Promise.all(
restoredFiles.map((file) => composer.addAttachment(file)),
).finally(() => {
restoringPasteScopeRef.current = undefined;
// A switch while these were added re-runs the restore for the new scope instead.
if (draftScopeRef.current === draftScope) {
restoredPasteScopeRef.current = draftScope;
} else {
// An adapter finishing after navigation reinserts its file; drop only this restore's files.
for (const attachment of composer.getState().attachments) {
const file = (attachment as { file?: File }).file;
if (file && restoredFiles.includes(file)) {
void composer.attachment({ id: attachment.id }).remove();
}
}
}
});
}, [draftScope, draftKey, incognito, pasteDraftKey, composerAttachmentSignature, aui]);
// Keyed on the paste identities, never their bodies, so typing beside a
// megabyte paste does not rewrite it to localStorage every 300ms.
useEffect(() => {
if (
draftScope === INCOGNITO_DRAFT_SCOPE ||
restoredPasteScopeRef.current !== draftScope
) {
return;
}
const pastes = aui
.composer()
.getState()
.attachments.flatMap((attachment) => {
const text = pastedTextOf((attachment as { file?: File }).file);
return text === undefined ? [] : [text];
});
writePasteDraft(pasteDraftKey, pastes);
}, [composerAttachmentSignature, draftScope, pasteDraftKey, aui]);
useEffect(() => {
// After a thread switch composerText can still hold what was on screen
// before the restore; skip that cycle so it can't overwrite the draft.
if (lastDraftScopeRef.current !== draftScope) {
lastDraftScopeRef.current = draftScope;
return;
}
if (draftScope === INCOGNITO_DRAFT_SCOPE) return;
if (composerText !== aui.composer().getState().text) return;
const awaiting = awaitingRestoreRef.current;
if (awaiting?.scope === draftScope) {
if (composerText === awaiting.stale && composerText !== awaiting.text) return;
awaitingRestoreRef.current = null;
}
if (composerText === remoteDraftRef.current) return;
remoteDraftRef.current = null;
if (shareDraft) publishDraft(composerText, draftSource);
if (!shareDraft) {
pendingDraftRef.current = { key: draftKey, text: composerText };
stageComposerDraft(draftKey, composerText);
}
const t = setTimeout(() => {
writeComposerDraft(draftKey, composerText);
pendingDraftRef.current = null;
}, 300);
draftSaveTimerRef.current = t;
return () => clearTimeout(t);
}, [composerText, draftScope, draftKey, draftSource, shareDraft, aui]);
useEffect(() => () => {
const pending = pendingDraftRef.current;
if (pending && !sentTextGuardBlocksDraft(justSentRef.current, pending.text, pending.key)) {
flushComposerDraft(pending.key, pending.text);
}
pendingDraftRef.current = null;
}, [draftScope]);
const draftScopeRef = useRef(draftScope);
const pasteDraftKeyRef = useRef(pasteDraftKey);
const shareDraftRef = useRef(shareDraft);
useEffect(() => {
draftKeyRef.current = draftKey;
draftScopeRef.current = draftScope;
pasteDraftKeyRef.current = pasteDraftKey;
shareDraftRef.current = shareDraft;
}, [draftKey, draftScope, pasteDraftKey, shareDraft]);
// Call wherever the composer is emptied because its text left as a message.
const armJustSent = useCallback((...texts: string[]) => {
justSentRef.current = armSentTextGuard(
texts,
draftKeyRef.current,
imeSessionOpenRef.current,
);
// Here, not beside send(): handleSubmit returns early on the three queueing
// paths, which empty the composer too.
setIsWritingExpanded(false);
}, [imeSessionOpenRef]);
const clearStoredDraft = useCallback(() => {
pendingDraftRef.current = null;
if (draftSaveTimerRef.current !== null) {
clearTimeout(draftSaveTimerRef.current);
draftSaveTimerRef.current = null;
}
// A temporary chat's send was never the stored draft.
if (draftScopeRef.current === INCOGNITO_DRAFT_SCOPE) return;
if (shareDraftRef.current) publishDraft("", draftSource);
if (draftKeyRef.current) writeComposerDraft(draftKeyRef.current, "");
writePasteDraft(pasteDraftKeyRef.current, []);
}, [draftSource]);
// react-textarea-autosize re-measures only on value change or window resize,
// not on the width swap from expanding, so it keeps the taller height and
// leaves a stray blank row. Nudge a resize whenever input width changes.
useEffect(() => {
const el = inputRef.current;
if (!el || typeof ResizeObserver === "undefined") {
return;
}
let lastWidth = -1;
const pending: Array<ReturnType<typeof setTimeout>> = [];
const observer = new ResizeObserver((entries) => {
const width = Math.round(entries[0]?.contentRect.width ?? 0);
// Width changes only; reacting to autosize's height change would loop.
if (width === lastWidth) {
return;
}
lastWidth = width;
// An immediate dispatch races autosize's own measurement; 0ms + 64ms wins.
while (pending.length) {
clearTimeout(pending.pop());
}
for (const delay of [0, 64]) {
pending.push(
setTimeout(() => {
window.dispatchEvent(new Event("resize"));
}, delay),
);
}
});
observer.observe(el);
return () => {
while (pending.length) {
clearTimeout(pending.pop());
}
observer.disconnect();
};
}, []);
const effectiveMenuSide = menuSide ?? "bottom";
// While this thread's docs index, hold the send so retrieval covers all of them.
const [indexingActive, setIndexingActive] = useState(false);
const indexingActiveRef = useRef(false);
const promptQueueTargetMountedRef = useRef(true);
const promptQueueStartPendingRef = useRef(
new Map<
string,
{
temporary: boolean;
cancelled: boolean;
threadId: string | null;
localModelBoundaryGeneration: number;
queuedSettingsEpoch: number;
waitForCurrentRun: boolean;
behavior: ComposerFollowUpBehavior;
}
>(),
);
// The pasted-text read precedes queue registration, so record the intent here, keyed like a
// reservation so a second submit cannot start a second read.
const pastedTextQueuePendingRef = useRef(
new Map<
string,
{
temporary: boolean;
cancelled: boolean;
threadId: string | null;
localModelBoundaryGeneration: number;
queuedSettingsEpoch: number;
historyClearGeneration: number;
}
>(),
);
// Starts not yet in the queue store.
const hasPendingQueueStart = useCallback(
() =>
hasPendingPromptQueueStart(
promptQueueStartPendingRef.current.values(),
referenceThreadId,
) ||
hasPendingPromptQueueStart(
pastedTextQueuePendingRef.current.values(),
referenceThreadId,
),
[referenceThreadId],
);
useEffect(() => {
promptQueueTargetMountedRef.current = true;
return () => {
promptQueueTargetMountedRef.current = false;
};
}, []);
useEffect(() => {
const cancelPendingQueueFactories = (event: Event) => {
const detail =
(event as CustomEvent<PromptQueueStopEventDetail>).detail ?? {};
const state = aui.threadListItem().getState();
const aliases = compactIds([state.id, state.remoteId, referenceThreadId]);
cancelPendingPromptQueueFactoriesForStop(
promptQueueStartPendingRef.current,
aliases,
detail,
);
// A read in flight has no reservation yet; cancel it or Clear all lets it recreate the chat.
cancelPendingPromptQueueFactoriesForStop(
pastedTextQueuePendingRef.current,
aliases,
detail,
);
};
window.addEventListener(
PROMPT_QUEUE_STOP_EVENT,
cancelPendingQueueFactories,
);
return () => {
window.removeEventListener(
PROMPT_QUEUE_STOP_EVENT,
cancelPendingQueueFactories,
);
};
}, [aui, referenceThreadId]);
const [pendingSend, setPendingSend] = useState(false);
const pendingSendRef = useRef(false);
const pendingFollowUpBehaviorRef = useRef<ComposerFollowUpBehavior>("queue");
const waitToastRef = useRef<string | number | null>(null);
// This chat's settings have not arrived; a send now would use installation defaults.
const threadScopedSettingsPending = useChatRuntimeStore(
(s) => s.threadScopedSettingsPending,
);
const handleIndexingChange = useCallback((active: boolean) => {
indexingActiveRef.current = active;
setIndexingActive(active);
}, []);
const createPromptQueueTarget = useCallback(async (): Promise<PromptQueueTarget | null> => {
const assistantRuntime = aui.threads().__internal_getAssistantRuntime?.();
const initialState = aui.threadListItem().getState();
const initialRunningThreadIds = [
initialState.id,
initialState.remoteId,
referenceThreadId,
].filter((id): id is string => Boolean(id));
const initialDocumentThreadId =
initialState.remoteId ?? referenceThreadId ?? null;
const historyClearGeneration = chatHistoryClearBoundary.capture();
await useChatRuntimeStore.getState().hydratePersistedSettings();
if (
!promptQueueTargetMountedRef.current ||
chatHistoryClearBoundary.capture() !== historyClearGeneration
) {
return null;
}
const currentState = aui.threadListItem().getState();
if (
!compactIds([currentState.id, currentState.remoteId]).some((id) =>
initialRunningThreadIds.includes(id),
)
) {
return null;
}
const chatStateAtQueueStart = useChatRuntimeStore.getState();
const incognitoAtQueueStart = chatStateAtQueueStart.incognito;
// A chat with no row has no project yet, and the store tracks the on-screen one; read it now.
const projectIdAtQueueStart = incognitoAtQueueStart
? null
: (chatStateAtQueueStart.activeProjectId ?? null);
const usesThreadDocumentsAtQueueStart =
chatStateAtQueueStart.ragEnabled &&
chatStateAtQueueStart.ragSource.type === "thread";
let deferModelResolution =
chatStateAtQueueStart.modelLoading &&
parseExternalModelId(
chatStateAtQueueStart.loadingModelPick &&
!chatStateAtQueueStart.loadingModelPick.selectionSuperseded
? chatStateAtQueueStart.loadingModelPick.id
: chatStateAtQueueStart.params.checkpoint,
) === null;
const runSettingsAtQueueStart = snapshotQueuedChatRunSettings(
chatStateAtQueueStart,
{ deferModelResolution },
);
const getThreadListItemState = () => {
const runtime =
assistantRuntime ?? aui.threads().__internal_getAssistantRuntime?.();
if (!runtime) {
return null;
}
for (const id of initialRunningThreadIds) {
try {
return runtime.threads.getItemById(id).getState();
} catch {
// Try the next captured id.
}
}
return null;
};
const getQueueThreadIds = () => {
const state = getThreadListItemState();
return compactIds([
...initialRunningThreadIds,
state?.id,
state?.remoteId,
]);
};
const getThreadRuntime = () => {
const runtime =
assistantRuntime ?? aui.threads().__internal_getAssistantRuntime?.();
if (!runtime) {
return null;
}
for (const id of getQueueThreadIds()) {
try {
const thread = runtime.threads.getById(id);
thread.getState();
return thread;
} catch {
// Try the next captured id.
}
}
return null;
};
const isTargetCurrentThread = () => {
const state = aui.threadListItem().getState();
return compactIds([state.id, state.remoteId]).some((id) =>
initialRunningThreadIds.includes(id),
);
};
const pendingSettingsIds = new Set<number>();
let cancelled = false;
let appendEpoch = 0;
let shouldCorrectPersistedModel: boolean | null = null;
let initializedFreshThreadId: string | null = null;
let freshThreadAppendAccepted = false;
const removeFreshThreadPersistedAfterAbort = () => {
const historyWasCleared =
chatHistoryClearBoundary.capture() !== historyClearGeneration;
if (
!initializedFreshThreadId ||
freshThreadAppendAccepted ||
(!cancelled && !historyWasCleared)
) {
return false;
}
// Tombstone synchronously so a late initializer cannot show an empty record during cleanup.
markChatThreadDeleted(initializedFreshThreadId);
// Never roll the tombstone back: a failed DELETE may have committed, leaving the id 410.
void deleteStoredChatThreads([initializedFreshThreadId]).catch(
() => undefined,
);
if (!historyWasCleared && isTargetCurrentThread()) {
void Promise.resolve(aui.threads().switchToNewThread()).catch(
() => undefined,
);
}
return true;
};
const discardOldestPendingSettings = () => {
const settingsId = pendingSettingsIds.values().next().value;
if (settingsId === undefined) {
return;
}
pendingSettingsIds.delete(settingsId);
discardQueuedChatRunSettings(settingsId);
};
return {
getDocumentThreadId: () => {
const state = getThreadListItemState();
return state?.remoteId ?? referenceThreadId ?? initialDocumentThreadId;
},
getRunningThreadIds: () => {
return getQueueThreadIds();
},
isRunning: () =>
hasPreStreamRunReservation(getQueueThreadIds()) ||
Boolean(getThreadRuntime()?.getState().isRunning),
append: async (prompt) => {
const epoch = appendEpoch;
const thread = getThreadRuntime();
if (!thread) {
throw new Error("Prompt queue thread runtime is unavailable");
}
if (incognitoAtQueueStart) {
for (const id of getQueueThreadIds()) {
markThreadIncognito(id);
}
}
const settingsId = registerQueuedChatRunSettings(
getQueueThreadIds(),
{
...runSettingsAtQueueStart,
params: { ...runSettingsAtQueueStart.params },
},
);
pendingSettingsIds.add(settingsId);
try {
const runtime =
assistantRuntime ?? aui.threads().__internal_getAssistantRuntime?.();
const state = getThreadListItemState();
if (!runtime || !state) {
throw new Error("Prompt queue thread item is unavailable");
}
if (chatHistoryClearBoundary.capture() !== historyClearGeneration) {
return;
}
shouldCorrectPersistedModel ??= !state.remoteId;
const initializingFreshThread = !state.remoteId;
// Stamp with the project the queue was started under; the adapter may show another by now.
if (initializingFreshThread) {
claimThreadCreation([state.id, state.remoteId], {
projectId: projectIdAtQueueStart,
incognito: incognitoAtQueueStart,
modelId: runSettingsAtQueueStart.params.checkpoint ?? "",
modelGgufVariant: runSettingsAtQueueStart.activeGgufVariant,
createdAt: Date.now(),
});
}
// Await the remote id so the adapter matches the queued settings on its first invocation.
const { remoteId } = await runtime.threads
.getItemById(state.id)
.initialize();
if (initializingFreshThread) {
initializedFreshThreadId = remoteId;
}
if (
removeFreshThreadPersistedAfterAbort() ||
cancelled ||
epoch !== appendEpoch ||
!pendingSettingsIds.has(settingsId)
) {
return;
}
addQueuedChatRunSettingsThreadIds(settingsId, [
...getQueueThreadIds(),
remoteId,
]);
if (shouldCorrectPersistedModel) {
// initialize() persisted the live global model; correct it to this run's captured model.
await updateStoredChatThread(remoteId, {
modelId: runSettingsAtQueueStart.params.checkpoint ?? "",
modelGgufVariant: runSettingsAtQueueStart.activeGgufVariant,
});
shouldCorrectPersistedModel = false;
if (
removeFreshThreadPersistedAfterAbort() ||
cancelled ||
epoch !== appendEpoch ||
!pendingSettingsIds.has(settingsId)
) {
return;
}
}
// refresh aliases after initialization replaces a local id so stop dialogs deduplicate it
syncPromptQueueUI();
const resolvedRunSettings = deferModelResolution
? resolveDeferredQueuedModelSettings(
runSettingsAtQueueStart,
useChatRuntimeStore.getState(),
)
: runSettingsAtQueueStart;
const keepQueuedFilesForPython = pythonToolRunsInStudio(
resolvedRunSettings,
);
const authSessionEpoch = getAuthSessionEpoch();
const readyPrompt = await prepareQueuedPromptFiles(
prompt,
(file, attachment) =>
withAttachmentOriginal(
{ file },
attachment,
incognitoAtQueueStart,
authSessionEpoch,
keepQueuedFilesForPython,
),
);
prompt.attachments = readyPrompt.attachments;
prompt.attachmentFiles = readyPrompt.attachmentFiles;
if (
removeFreshThreadPersistedAfterAbort() ||
cancelled ||
epoch !== appendEpoch ||
!pendingSettingsIds.has(settingsId)
) {
return;
}
const appendResult = thread.append(
queuedPromptMessage(readyPrompt),
) as unknown;
freshThreadAppendAccepted = true;
// thread.append accepts synchronously; later provider failures must not dispatch a duplicate
if (
appendResult &&
typeof (appendResult as Promise<void>).catch === "function"
) {
void (appendResult as Promise<void>).catch(() => undefined);
}
} catch (error) {
// retry setup failures unless stop or Clear all invalidated this queue
removeFreshThreadPersistedAfterAbort();
pendingSettingsIds.delete(settingsId);
discardQueuedChatRunSettings(settingsId);
throw error;
}
},
complete: discardOldestPendingSettings,
cancel: () => {
cancelled = true;
removeFreshThreadPersistedAfterAbort();
for (const settingsId of pendingSettingsIds) {
discardQueuedChatRunSettings(settingsId);
}
pendingSettingsIds.clear();
getThreadRuntime()?.cancelRun();
},
cancelActiveRun: () => {
appendEpoch += 1;
discardOldestPendingSettings();
getThreadRuntime()?.cancelRun();
},
releaseModel: () => {
// The same snapshot a queue started during a model load takes.
deferModelResolution = true;
runSettingsAtQueueStart.params.checkpoint = "";
runSettingsAtQueueStart.activeGgufVariant = null;
},
isIndexing: () =>
promptQueueTargetMountedRef.current &&
isTargetCurrentThread() &&
indexingActiveRef.current,
getQueueProjectId: () => projectIdAtQueueStart,
usesThreadDocuments: usesThreadDocumentsAtQueueStart,
usesLocalModel:
parseExternalModelId(runSettingsAtQueueStart.params.checkpoint) === null,
usesDeepResearch: runSettingsAtQueueStart.deepResearchEnabled,
researchStarted: () => {
const claimed = useResearchRunStore.getState().claimedThreadIds;
return getQueueThreadIds().some((id) => Boolean(claimed[id]));
},
temporary: incognitoAtQueueStart,
consumeDeepResearch: () => {
runSettingsAtQueueStart.deepResearchEnabled = false;
},
};
}, [aui, referenceThreadId]);
// Whether a pending start will be refused, so a retry replaces it instead of being deduped.
// Never stricter than the reservation, or the same prompt queues twice.
const pendingQueueStartIsStale = useCallback(
(pending: {
cancelled: boolean;
temporary: boolean;
queuedSettingsEpoch: number;
historyClearGeneration?: number;
}): boolean => {
if (pending.cancelled) return true;
if (
pending.historyClearGeneration !== undefined &&
chatHistoryClearBoundary.capture() !== pending.historyClearGeneration
) {
return true;
}
const chatState = useChatRuntimeStore.getState();
return shouldAbortPendingQueueForSettingsChange({
capturedEpoch: pending.queuedSettingsEpoch,
currentEpoch: chatState.queuedSettingsEpoch,
capturedTemporary: pending.temporary,
currentTemporary: chatState.incognito,
});
},
[],
);
const startHydratedPromptQueue = useCallback(
(
items: Array<string | QueuedPrompt>,
waitForCurrentRun = false,
onStarted?: () => void,
onAborted?: () => void,
// capture before awaiting so intervening boundary or setting changes invalidate the queue
capturedAt?: {
localModelBoundaryGeneration: number;
queuedSettingsEpoch: number;
temporary: boolean;
},
behavior: ComposerFollowUpBehavior = "queue",
) => {
const reservationKey = JSON.stringify([referenceThreadId, items]);
// replace only invalid reservations so one attempt owns each prompt
const existing = promptQueueStartPendingRef.current.get(reservationKey);
if (existing && !pendingQueueStartIsStale(existing)) {
// A new shortcut updates the pending draft instead of sending it twice.
existing.waitForCurrentRun = waitForCurrentRun;
existing.behavior = behavior;
return false;
}
const reservation = {
temporary:
capturedAt?.temporary ?? useChatRuntimeStore.getState().incognito,
cancelled: false,
threadId: referenceThreadId,
localModelBoundaryGeneration:
capturedAt?.localModelBoundaryGeneration ??
localPromptQueueModelBoundary.capture(),
queuedSettingsEpoch:
capturedAt?.queuedSettingsEpoch ??
useChatRuntimeStore.getState().queuedSettingsEpoch,
waitForCurrentRun,
behavior,
};
promptQueueStartPendingRef.current.set(reservationKey, reservation);
void createPromptQueueTarget()
.then((target) => {
const currentQueueSettings = useChatRuntimeStore.getState();
const modelBoundaryInvalidated = target
? shouldAbortPendingQueueForModelBoundary({
capturedGeneration:
reservation.localModelBoundaryGeneration,
usesLocalModel: target.usesLocalModel,
})
: false;
const settingsInvalidated =
shouldAbortPendingQueueForSettingsChange({
capturedEpoch: reservation.queuedSettingsEpoch,
currentEpoch: currentQueueSettings.queuedSettingsEpoch,
capturedTemporary: reservation.temporary,
currentTemporary: currentQueueSettings.incognito,
});
if (
target &&
!reservation.cancelled &&
!modelBoundaryInvalidated &&
!settingsInvalidated &&
promptQueueStartPendingRef.current.get(reservationKey) ===
reservation
) {
cancelAudioUpload();
startPromptQueue(
items,
target,
reservation.waitForCurrentRun,
reservation.behavior,
);
onStarted?.();
} else if (
promptQueueStartPendingRef.current.get(reservationKey) ===
reservation
) {
// Superseded reservations stay quiet: their replacement is still going.
onAborted?.();
}
})
.catch((error) => {
toast.error("Could not start prompt queue", {
description:
error instanceof Error ? error.message : "Please try again.",
});
onAborted?.();
})
.finally(() => {
if (
promptQueueStartPendingRef.current.get(reservationKey) ===
reservation
) {
promptQueueStartPendingRef.current.delete(reservationKey);
}
});
return true;
},
[
cancelAudioUpload,
createPromptQueueTarget,
pendingQueueStartIsStale,
referenceThreadId,
],
);
// preserve pure pastes as editable text while snapshotting uploaded text files
const queueTextAttachmentsPrompt = useCallback(
(
waitForCurrentRun: boolean,
behavior: ComposerFollowUpBehavior = "queue",
): boolean => {
const composer = aui.composer();
const attachments = composer.getState().attachments;
// keep validated decoded file payloads separate from the editable prompt
if (!attachments.every((attachment) => isPastedTextFile(attachment.file))) {
const text = composer.getState().text;
const prepared = snapshotQueuedTextPrompt(text, attachments);
if (!prepared) return false;
const ids = attachments.map((attachment) => attachment.id);
startHydratedPromptQueue(
[prepared],
waitForCurrentRun,
() => {
const state = composer.getState();
if (
state.text !== text ||
state.attachments.length !== ids.length ||
!state.attachments.every((attachment, index) => attachment.id === ids[index])
) {
return;
}
void composer.clearAttachments();
flushResourcesSync(() => composer.setText(""));
clearStoredDraft();
armJustSent(text);
},
() => {
toast.info("Text attachments were not queued", {
description: "The chat or settings changed. Send them again.",
});
},
undefined,
behavior,
);
return true;
}
const files: File[] = [];
for (const attachment of attachments) {
const file = (attachment as { file?: File }).file;
if (file === undefined || !isPastedTextFile(file)) return false;
files.push(file);
}
if (files.length === 0) return false;
const attachmentIds = attachments.map((attachment) => attachment.id);
const textAtQueue = composer.getState().text.trim();
const queueTexts = (
texts: string[],
capturedAt?: {
localModelBoundaryGeneration: number;
queuedSettingsEpoch: number;
temporary: boolean;
},
) => {
const queuedPrompt = [textAtQueue, ...texts]
.filter((part) => part.trim().length > 0)
.join("\n\n");
if (queuedPrompt.length === 0) return;
startHydratedPromptQueue(
[queuedPrompt],
waitForCurrentRun,
() => {
const state = composer.getState();
if (
state.text.trim() !== textAtQueue ||
state.attachments.length !== attachmentIds.length ||
!state.attachments.every(
(attachment, index) => attachment.id === attachmentIds[index],
)
) {
return;
}
void composer.clearAttachments();
flushResourcesSync(() => {
composer.setText("");
});
clearStoredDraft();
armJustSent(state.text);
},
() => {
toast.info("Pasted text was not queued", {
description: "The chat settings changed. Send it again.",
});
},
capturedAt,
behavior,
);
};
// Read the cached body: awaiting the File would reorder this behind a later gesture.
const cachedTexts: string[] = [];
for (const file of files) {
const text = pastedTextOf(file);
if (text === undefined) break;
cachedTexts.push(text);
}
if (cachedTexts.length === files.length) {
queueTexts(cachedTexts);
return true;
}
// Register before the read, or a submit during it would queue the same text twice.
const pendingKey = pastedTextQueueKey(
referenceThreadId,
textAtQueue,
attachmentIds,
);
// Same intent as a running read: report handled. A stale read will abort, so not that one.
const inFlight = pastedTextQueuePendingRef.current.get(pendingKey);
if (inFlight && !pendingQueueStartIsStale(inFlight)) return true;
const chatState = useChatRuntimeStore.getState();
const pendingRead = {
temporary: chatState.incognito,
cancelled: false,
threadId: referenceThreadId,
// The chat the read began in, so a mid-read switch cannot dispatch into the new chat.
composerIdentity: composerIdentityRef.current,
localModelBoundaryGeneration: localPromptQueueModelBoundary.capture(),
queuedSettingsEpoch: chatState.queuedSettingsEpoch,
historyClearGeneration: chatHistoryClearBoundary.capture(),
};
// Replaces a stale read; it still resolves but no longer owns the key, so it skips its start.
pastedTextQueuePendingRef.current.set(pendingKey, pendingRead);
void Promise.all(files.map((file) => file.text()))
.then((texts) => {
if (
pendingQueueStartIsStale(pendingRead) ||
composerIdentityRef.current !== pendingRead.composerIdentity ||
pastedTextQueuePendingRef.current.get(pendingKey) !== pendingRead
) {
return;
}
queueTexts(texts, pendingRead);
})
.catch(() => {
toast.error("Could not queue the pasted text.", {
description: "Show it in the text field, then send it again.",
});
})
.finally(() => {
if (pastedTextQueuePendingRef.current.get(pendingKey) === pendingRead) {
pastedTextQueuePendingRef.current.delete(pendingKey);
}
});
return true;
},
[
armJustSent,
aui,
clearStoredDraft,
pendingQueueStartIsStale,
referenceThreadId,
startHydratedPromptQueue,
],
);
// Hoisted so the parked-send release can use it; reads the live composer, not rendered text.
const queueComposerText = useCallback(
(waitForCurrentRun: boolean, behavior: ComposerFollowUpBehavior = "queue") => {
const queuedPrompt = aui.composer().getState().text.trim();
if (!queuedPrompt) {
return;
}
startHydratedPromptQueue(
[queuedPrompt],
waitForCurrentRun,
() => {
// Guard the untrimmed text too: that is what a late write carries.
const cleared = aui.composer().getState().text;
if (cleared.trim() !== queuedPrompt) {
return;
}
flushResourcesSync(() => {
aui.composer().setText("");
});
clearStoredDraft();
armJustSent(queuedPrompt, cleared);
},
undefined,
undefined,
behavior,
);
},
[armJustSent, aui, clearStoredDraft, startHydratedPromptQueue],
);
const dismissWaitToast = useCallback(() => {
if (waitToastRef.current !== null) {
toast.dismiss(waitToastRef.current);
waitToastRef.current = null;
}
}, []);
// Declared here because cancelQueuedSend has to clear the dictation hold too.
const sendAfterDictationRef = useRef(false);
const heldTextRef = useRef<string | null>(null);
const cancelQueuedSend = useCallback(() => {
pendingSendRef.current = false;
pendingFollowUpBehaviorRef.current = "queue";
setPendingSend(false);
sendAfterDictationRef.current = false;
heldTextRef.current = null;
dismissWaitToast();
}, [dismissWaitToast]);
cancelQueuedSendRef.current = cancelQueuedSend;
const enqueueSend = useCallback(
(
waitingOn:
| "indexing"
| "images"
| "audio"
| "video"
| "running"
| "settings" = "indexing",
) => {
if (pendingSendRef.current) return;
pendingSendRef.current = true;
setPendingSend(true);
const title =
waitingOn === "running"
? "Waiting for the current response to finish"
: waitingOn === "images"
? "Waiting for dropped images"
: waitingOn === "audio"
? "Waiting for dropped audio"
: waitingOn === "video"
? "Waiting for dropped video"
: waitingOn === "settings"
? "Loading this chat's settings"
: "Waiting for documents to finish indexing";
waitToastRef.current = toast(title, {
description: "Your message will send automatically once it is ready.",
duration: Infinity,
cancel: { label: "Cancel", onClick: cancelQueuedSend },
});
},
[cancelQueuedSend],
);
// Consuming the intent makes one press cancel once.
const steerParkedSend = useCallback(
(state: Omit<ParkedSendSteerState, "behavior">) => {
const steer = parkedSendSteer({
...state,
behavior: pendingFollowUpBehaviorRef.current,
});
if (!steer) return;
pendingFollowUpBehaviorRef.current = "queue";
cancelPreStreamRunForThreadIds(preStreamThreadIds);
if (!steer.cancelRun) return;
try {
aui.thread().cancelRun();
} catch {
// Already ended.
}
},
[aui, preStreamThreadIds],
);
// A materializing image or clip parks the send; both gates share this to agree.
const parkIfWaitingOnAttachments = useCallback(() => {
if (
disabled ||
overlay ||
(!hasMaterializingImageAttachments &&
!hasMaterializingAudioAttachments &&
!hasMaterializingVideoAttachments) ||
!hasSendableContent ||
isComposingRef.current ||
hasPendingAttachments
) {
return;
}
// Name what is awaited, or a parked video drop reports itself as audio.
enqueueSend(
hasMaterializingImageAttachments
? "images"
: hasMaterializingAudioAttachments
? "audio"
: "video",
);
}, [
disabled,
overlay,
hasMaterializingImageAttachments,
hasMaterializingAudioAttachments,
hasMaterializingVideoAttachments,
hasSendableContent,
hasPendingAttachments,
isComposingRef,
enqueueSend,
]);
const shouldBlockSend = useCallback(
() =>
!hasSendableContent ||
isComposingRef.current ||
hasPendingAttachments ||
hasMaterializingImageAttachments ||
hasMaterializingAudioAttachments ||
hasMaterializingVideoAttachments,
[
hasMaterializingAudioAttachments,
hasMaterializingVideoAttachments,
hasMaterializingImageAttachments,
hasPendingAttachments,
hasSendableContent,
isComposingRef,
],
);
// alsoGuard: prior composer text, so a late write of what the user typed is refused too.
const sendReservedComposer = useCallback((...alsoGuard: string[]) => {
const assistantRuntime =
aui.threads().__internal_getAssistantRuntime?.();
let reservationToken: symbol | null = null;
reservationToken = reservePreStreamRun(preStreamThreadIds, {
usesLocalModel:
parseExternalModelId(
useChatRuntimeStore.getState().params.checkpoint,
) === null,
cancel: (reservedThreadIds) => {
if (preStreamRunReservationRef.current === reservationToken) {
preStreamRunReservationRef.current = null;
}
for (const reservedThreadId of reservedThreadIds) {
try {
assistantRuntime?.threads.getById(reservedThreadId).cancelRun();
return;
} catch {
// Thread hydration can retire an alias; try the next captured id.
}
}
},
});
if (!reservationToken) {
toast.error("Wait for the current response to finish");
return;
}
preStreamRunReservationRef.current = reservationToken;
try {
// Only after reservation succeeds: a refused send keeps the in-flight transcript.
cancelAudioUpload();
const sentText = aui.composer().getState().text;
// Stamp before send() awaits attachments; see utils/chat-thread-creation-claim.ts.
const chatStateAtSend = useChatRuntimeStore.getState();
claimThreadCreation(preStreamThreadIds, {
projectId: projectScope,
incognito: chatStateAtSend.incognito,
modelId: chatStateAtSend.params.checkpoint ?? "",
modelGgufVariant: chatStateAtSend.activeGgufVariant,
createdAt: Date.now(),
});
aui.composer().send();
// Empty texts are dropped, so an attachment-only send still clears.
armJustSent(sentText, ...alsoGuard);
} catch (error) {
if (releasePreStreamRunReservation(reservationToken)) {
notifyPromptQueueRunFailed(referenceThreadId);
}
preStreamRunReservationRef.current = null;
toast.error("Could not prepare attachments", {
description:
error instanceof Error ? error.message : "Please retry the send.",
});
}
}, [
aui,
armJustSent,
cancelAudioUpload,
preStreamThreadIds,
projectScope,
referenceThreadId,
]);
const interceptSend = useCallback(
(event: { preventDefault: () => void }) => {
if (disabled || shouldBlockSend()) {
event.preventDefault();
parkIfWaitingOnAttachments();
return true;
}
if (indexingActive && !overlay) {
event.preventDefault();
enqueueSend();
return true;
}
// Settings still loading means installation defaults would be captured (a chat stored as
// "ask" could run tools without asking); park the send until the snapshot lands.
if (threadScopedSettingsPending && !overlay) {
event.preventDefault();
enqueueSend("settings");
return true;
}
return false;
},
[
disabled,
shouldBlockSend,
indexingActive,
overlay,
threadScopedSettingsPending,
enqueueSend,
parkIfWaitingOnAttachments,
],
);
// Fire the parked send once all waits clear, unless the composer was emptied. A late-dropped
// image must land first or it attaches to the next draft.
useEffect(() => {
const liveThreadIsRunning =
threadIsRunning || aui.thread().getState().isRunning;
const livePromptQueueActive = Boolean(
findPromptQueueEntry(usePromptQueueUI.getState(), promptQueueThreadIds),
);
const livePreStreamRunActive =
hasPreStreamRunReservation(preStreamThreadIds);
const parkedBehindResponse =
hasAttachments &&
!attachmentsAreQueueableText &&
(liveThreadIsRunning || livePromptQueueActive || livePreStreamRunActive);
// pendingSendRef is authoritative because pendingSend still reflects the pre-cancel render.
if (
!pendingSend ||
!pendingSendRef.current ||
indexingActive ||
threadScopedSettingsPending ||
parkedBehindResponse ||
hasMaterializingImageAttachments ||
hasMaterializingAudioAttachments ||
hasMaterializingVideoAttachments
) {
// Keeps its steer until an upload or settings hold clears.
if (pendingSend && pendingSendRef.current) {
steerParkedSend({
parkedBehindResponse,
otherHoldActive:
threadScopedSettingsPending ||
hasMaterializingImageAttachments ||
hasMaterializingAudioAttachments ||
hasMaterializingVideoAttachments,
promptQueueActive: livePromptQueueActive || hasPendingQueueStart(),
researchActive: isResearchActive,
threadRunning: liveThreadIsRunning,
});
}
return;
}
const { text, attachments } = aui.composer().getState();
const behavior = pendingFollowUpBehaviorRef.current;
pendingSendRef.current = false;
pendingFollowUpBehaviorRef.current = "queue";
setPendingSend(false);
dismissWaitToast();
if (text.trim().length > 0 || attachments.length > 0) {
// Read wait mode now: a run may start while settings load, and must not be dispatched over.
const waitForCurrentRun =
aui.thread().getState().isRunning ||
hasPreStreamRunReservation(preStreamThreadIds);
// A parked send is a late submit, so mirror handleSubmit's branches; sending regardless while
// a turn streams is refused silently. Research disables input, so never release here.
if (isResearchActive) {
return;
}
const queueAlreadyActive = Boolean(
findPromptQueueEntry(usePromptQueueUI.getState(), preStreamThreadIds),
);
if (waitForCurrentRun || queueAlreadyActive) {
// queueing here would bind the follow-up to a nonexistent project new-chat thread.
if (disableQueue) {
toast.error("Wait for the current response to finish");
return;
}
// queueComposerText preserves the draft until the queue starts.
if (canQueueCurrentPrompt) {
queueComposerText(waitForCurrentRun, behavior);
return;
}
// a long paste has no separate prompt text to queue.
if (
canQueueTextAttachmentsPrompt &&
queueTextAttachmentsPrompt(waitForCurrentRun, behavior)
) {
return;
}
// sending here would add the attachment to the active thread.
if (overlay || hasAttachments || hasPendingAudio) {
toast.error("Wait for the current response to finish", {
description:
"Only text prompts can be queued while a response is running or the prompt queue is active.",
});
}
return;
}
clearStoredDraft();
// keep this synchronous so stale run state cannot drop the send after dismissing the toast.
// eslint-disable-next-line react-hooks/set-state-in-effect -- see above
sendReservedComposer();
}
}, [
pendingSend,
indexingActive,
threadScopedSettingsPending,
preStreamRunActive,
threadIsRunning,
promptQueueActive,
promptQueueThreadIds,
attachmentsAreQueueableText,
hasMaterializingImageAttachments,
hasMaterializingAudioAttachments,
hasMaterializingVideoAttachments,
aui,
canQueueCurrentPrompt,
canQueueTextAttachmentsPrompt,
clearStoredDraft,
dismissWaitToast,
queueComposerText,
queueTextAttachmentsPrompt,
sendReservedComposer,
steerParkedSend,
hasPendingQueueStart,
preStreamThreadIds,
disableQueue,
isResearchActive,
overlay,
hasAttachments,
hasPendingAudio,
]);
useEffect(
() => () => {
pendingSendRef.current = false;
pendingFollowUpBehaviorRef.current = "queue";
if (waitToastRef.current !== null) toast.dismiss(waitToastRef.current);
},
[],
);
// Submitting through the form keeps queueing, indexing holds and draft clearing identical.
const formRef = useRef<HTMLFormElement | null>(null);
// Mirrored into state so the publish effect re-runs on mount; see usePublishedFrame.
const [composerEl, setComposerEl] = useState<HTMLFormElement | null>(null);
const attachComposer = useCallback((node: HTMLFormElement | null) => {
formRef.current = node;
setComposerEl(node);
}, []);
// Published so the API monitor panel opens clear of Send.
usePublishedFrame(composerEl);
const dictationBaseTextRef = useRef("");
const dictationComposerRef = useRef("");
useEffect(() => {
setIsWritingExpanded(false);
}, [composerIdentity]);
// Window capture runs before the document listeners, where cancelOnEscape preventDefaults
// every Escape, so defaultPrevented cannot tell them apart.
useEffect(() => {
const collapseOnEscape = (event: globalThis.KeyboardEvent) => {
if (
event.key === "Escape" &&
!event.isComposing &&
!mentionOpenRef.current &&
event.target instanceof Node &&
editorRef.current?.contains(event.target)
) {
setIsWritingExpanded(false);
}
};
window.addEventListener("keydown", collapseOnEscape, true);
return () => window.removeEventListener("keydown", collapseOnEscape, true);
}, []);
// Keep the mic clickable: if the engine cannot run, explain and point to the local model.
const startDictation = useCallback(() => {
if (audioUpload.busy || dictationEntryDisabled) return;
if (currentDictationEntryMode() === "recording-file") {
if (micRecordsForModel()) {
pickAudioForModel((file) => aui.composer().addAttachment(file));
} else {
audioUpload.openDialog();
}
return;
}
if (!micRecordsForModel() && !isStudioDictationAvailable()) {
notifyStudioDictationUnavailable();
return;
}
try {
aui.composer().startDictation();
} catch {
notifyStudioDictationUnavailable();
}
}, [aui, audioUpload, dictationEntryDisabled]);
useEffect(
() =>
setMicAudioClipTarget({
add: (file) => aui.composer().addAttachment(file),
attached: () =>
aui
.composer()
.getState()
.attachments.flatMap((attachment) =>
attachment.file ? [attachment.file] : [],
),
}),
// Per chat: the old chat's unregister discards its unfinished clip.
[aui, composerIdentity],
);
const sendAfterDictation = useCallback(() => {
sendAfterDictationRef.current = true;
dictationComposerRef.current = composerIdentity;
aui.composer().stopDictation();
}, [aui, composerIdentity]);
// One gate: greys the bar's send and holds a pending send if the composer changes after.
const dictationBlocked = dictationSendBlocked({
composerDisabled: Boolean(disabled),
uploading:
hasPendingAttachments ||
hasMaterializingImageAttachments ||
hasMaterializingAudioAttachments ||
hasMaterializingVideoAttachments,
researchActive: isResearchActive,
runActive: threadIsRunning || promptQueueActive,
queueDisabled: Boolean(disableQueue),
hasOverlay: Boolean(overlay),
hasAttachments,
hasPendingAudio,
});
// Both chords live here: the recording bar replaces the controls below, so one registered there
// could start dictation and never stop it.
useShortcut(
"startDictation",
() => {
// Stop first and ungated: the gate's selector is gone while recording.
if (isDictating) {
aui.composer().stopDictation();
return;
}
// A dialog over Chat keeps this registered; a hidden microphone could not be stopped.
if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return;
startDictation();
},
{ enabled: chatActive },
);
useShortcut(
"sendMessage",
() => {
// While recording, stop dictation first so the final transcript lands before sending.
if (isDictating) {
if (!dictationBlocked) sendAfterDictation();
return;
}
// A dialog over Chat keeps this registered, and sending is not undoable.
if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return;
// requestSubmit, not the runtime's send: handleSubmit parks, queues or refuses first.
formRef.current?.requestSubmit();
},
{
enabled: chatActive && !disabled,
// The model picker popover keeps the composer foreground; other text fields keep this chord.
skipInTextFields: true,
textFieldException: COMPOSER_INPUT_SELECTOR,
},
);
// handleSubmit reads the intent ref, so request the opposite when the preference differs.
const submitWithFollowUp = useCallback(
(behavior: ComposerFollowUpBehavior) => {
// No dictation branch: the bar replaces the composer, so the foreground gate no-ops it.
if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return;
submitIntentRef.current = followUpSubmitIntent(
useChatPreferencesStore.getState().followUpBehavior,
behavior,
);
try {
formRef.current?.requestSubmit();
} finally {
submitIntentRef.current = "default";
}
},
[],
);
const followUpShortcutOptions = {
enabled: chatActive && !disabled,
skipInTextFields: true,
textFieldException: COMPOSER_INPUT_SELECTOR,
};
useShortcut(
"queueMessage",
() => submitWithFollowUp("queue"),
followUpShortcutOptions,
);
useShortcut(
"steerMessage",
() => submitWithFollowUp("steer"),
followUpShortcutOptions,
);
const wasDictatingRef = useRef(false);
useEffect(() => {
if (isDictating) {
if (wasDictatingRef.current) return;
wasDictatingRef.current = true;
// A new recording supersedes a send still held for an upload.
sendAfterDictationRef.current = false;
heldTextRef.current = null;
// Anchor on the text at session start: interim results stream into the composer.
dictationBaseTextRef.current = aui.composer().getState().text;
return;
}
wasDictatingRef.current = false;
if (!sendAfterDictationRef.current) return;
// A partial transcript stays in the composer but must not send half a message. Settled before
// the hold below.
const text = composerText;
const sendable =
!dictationFailed() &&
shouldSubmitDictation({
originComposer: dictationComposerRef.current,
currentComposer: composerIdentity,
producedTranscript: dictationProducedTranscript(),
producedClip: clipStillAttached(
dictationProducedClip(),
aui.composer().getState().attachments,
),
baseText: dictationBaseTextRef.current,
text,
});
if (!sendable) {
sendAfterDictationRef.current = false;
heldTextRef.current = null;
return;
}
// Uploads can appear after the press; keep the intent until the composer accepts a submit.
if (dictationBlocked) {
// The hold lasts only for the transcript it was pressed for; an edit hands control back.
if (heldTextRef.current === null) {
heldTextRef.current = text;
} else if (heldTextRef.current !== text) {
sendAfterDictationRef.current = false;
heldTextRef.current = null;
}
return;
}
sendAfterDictationRef.current = false;
heldTextRef.current = null;
formRef.current?.requestSubmit();
}, [isDictating, aui, composerIdentity, dictationBlocked, composerText]);
const handleSubmit = useCallback(
(event: {
preventDefault: () => void;
stopPropagation?: () => void;
}) => {
const behavior = composerFollowUpBehavior(
useChatPreferencesStore.getState().followUpBehavior,
submitIntentRef.current,
);
submitIntentRef.current = "default";
pendingFollowUpBehaviorRef.current = behavior;
if (isResearchActive) {
event.preventDefault();
return;
}
// A command, not a prompt: ahead of the model and queue gates, so it works with no model loaded.
if (!overlay && !hasAttachments && isRewindCommand(composerText)) {
event.preventDefault();
if (threadIsRunning || aui.thread().getState().isRunning) {
toast.error(translate("rewind.waitForResponse"));
return;
}
aui.composer().setText("");
useRewindDialogStore.getState().openRewind({
threadKey: aui.threadListItem().getState().id,
messageId: null,
});
return;
}
if (
!overlay &&
!hasAttachments &&
!hasPendingAudio &&
isCompactCommand(composerText)
) {
event.preventDefault();
const runtime = useChatRuntimeStore.getState();
if (!referenceThreadId || aui.thread().getState().messages.length === 0) {
toast.info("Nothing to compact yet");
return;
}
if (runtime.incognito || isThreadIncognito(referenceThreadId)) {
toast.info("Temporary chats are not saved, so they cannot be compacted");
return;
}
// The compacted turns stay reachable only through search_conversation, so no tools, no reset.
if (
!runtime.supportsTools ||
!resumesThought({
loadedIsGguf: runtime.loadedIsGguf,
loadedIsMlx: runtime.loadedIsMlx,
activeGgufVariant: runtime.activeGgufVariant,
activeNativePathToken: runtime.activeNativePathToken,
checkpoint: runtime.params.checkpoint,
})
) {
toast.info("/compact works with GGUF and MLX models that support tools");
return;
}
requestThreadCompaction(referenceThreadId);
clearStoredDraft();
aui.composer().setText("");
return;
}
if (disabled || shouldBlockSend()) {
event.preventDefault();
parkIfWaitingOnAttachments();
return;
}
// Before the queue branch: a prompt queued now would snapshot installation defaults.
if (threadScopedSettingsPending && !overlay) {
event.preventDefault();
enqueueSend("settings");
return;
}
// React may lag several rapid submits; the imperative runtime and queue store are current.
const liveThreadIsRunning =
threadIsRunning || aui.thread().getState().isRunning;
const livePromptQueueActive =
promptQueueActive ||
hasPendingQueueStart() ||
Boolean(
findPromptQueueEntry(
usePromptQueueUI.getState(),
promptQueueThreadIds,
),
);
const livePreStreamRunActive =
hasPreStreamRunReservation(preStreamThreadIds);
if (
liveThreadIsRunning ||
livePromptQueueActive ||
livePreStreamRunActive
) {
event.preventDefault();
// the project new-chat composer has no thread to bind a queue to.
if (disableQueue) {
toast.error("Wait for the current response to finish");
return;
}
if (!canQueueCurrentPrompt) {
if (
canQueueTextAttachmentsPrompt &&
queueTextAttachmentsPrompt(
liveThreadIsRunning || livePreStreamRunActive,
behavior,
)
) {
return;
}
if (canQueueAttachmentPrompt) {
enqueueSend("running");
// A repeat press does not re-run the release effect.
steerParkedSend({
parkedBehindResponse: true,
otherHoldActive: false,
promptQueueActive: livePromptQueueActive,
researchActive: isResearchActive,
threadRunning: liveThreadIsRunning,
});
return;
}
if (overlay || hasAttachments || hasPendingAudio) {
toast.error(
liveThreadIsRunning
? "Wait for the current response to finish"
: "Wait for the prompt queue to finish",
{
description:
"Only text prompts and ready attachments can be queued while a response is running or the prompt queue is active.",
},
);
}
return;
}
queueComposerText(
liveThreadIsRunning || livePreStreamRunActive,
behavior,
);
return;
}
if (interceptSend(event)) return;
if (overlay) {
const trimmed = composerText.trim();
if (!trimmed) {
event.preventDefault();
return;
}
if (!overlay.openaiImageGenerationCallId) {
event.preventDefault();
toast.error("This generated image cannot be edited", {
description:
"The original image reference is missing. Generate the image again, then retry the edit.",
});
closeOverlay();
return;
}
if ((overlay.threadId ?? null) !== referenceThreadId) {
event.preventDefault();
toast.error("This generated image belongs to another chat", {
description: "Open the original chat and retry the edit.",
});
closeOverlay();
return;
}
clearStoredDraft();
setImageToolsEnabled(true);
setPendingImageEditReference({
threadId: overlay.threadId ?? referenceThreadId,
openaiImageGenerationCallId: overlay.openaiImageGenerationCallId,
...(overlay.openaiResponseId
? { openaiResponseId: overlay.openaiResponseId }
: {}),
openaiReasoningItem: overlay.openaiReasoningItem,
});
// Live text, not composerText: a late DOM write carries exactly what the textarea held.
const visibleBeforeWrap = aui.composer().getState().text;
flushResourcesSync(() => {
aui
.composer()
.setText(
`Use the selected generated image as the reference and apply this edit: ${trimmed}. Preserve everything else exactly.`,
);
});
closeOverlay();
event.preventDefault();
// The wrapper replaced what the user typed, so guard that text as well.
sendReservedComposer(visibleBeforeWrap, trimmed);
return;
}
if (hasAttachments || hasPendingAudio) {
event.preventDefault();
clearStoredDraft();
sendReservedComposer();
return;
}
event.preventDefault();
clearStoredDraft();
sendReservedComposer();
},
[
aui,
canQueueAttachmentPrompt,
canQueueCurrentPrompt,
canQueueTextAttachmentsPrompt,
queueComposerText,
queueTextAttachmentsPrompt,
clearStoredDraft,
closeOverlay,
composerText,
disabled,
disableQueue,
hasAttachments,
hasPendingAudio,
enqueueSend,
interceptSend,
isResearchActive,
overlay,
parkIfWaitingOnAttachments,
threadScopedSettingsPending,
promptQueueActive,
promptQueueThreadIds,
preStreamThreadIds,
referenceThreadId,
setImageToolsEnabled,
setPendingImageEditReference,
sendReservedComposer,
shouldBlockSend,
steerParkedSend,
hasPendingQueueStart,
threadIsRunning,
],
);
const stopQueue = useCallback(() => {
pausePromptQueueRun(promptQueueThreadIds);
}, [promptQueueThreadIds]);
const resumeQueue = useCallback(() => {
resumePromptQueueRun(promptQueueThreadIds);
}, [promptQueueThreadIds]);
const startQueue = useCallback(
(
items: Array<string | QueuedPrompt>,
waitForCurrentRun =
threadIsRunning || aui.thread().getState().isRunning,
onAborted?: () => void,
) => {
// saved-prompt calls bypass the button, so project new-chat must still refuse queues.
if (disableQueue) return false;
// false means an identical start is pending, not refused.
startHydratedPromptQueue(items, waitForCurrentRun, undefined, onAborted);
return true;
},
[aui, startHydratedPromptQueue, threadIsRunning, disableQueue],
);
const queueContextValue: PromptQueueCallbacks = useMemo(
() => ({ startQueue, stopQueue }),
[startQueue, stopQueue],
);
// Skills off sends no read_skill, so a mention would load nothing.
const [skillsSwitchOn] = useSkillsSwitch();
// The composer renders on every keystroke, since it owns the draft. Nothing in these controls
// reads the text, so their elements are kept from one render to the next: React skips a subtree
// whose element is the one it rendered last. Measured on a keystroke: 297 component renders
// under the composer without this, 68 with it.
const toolsMenu = useMemo(
() => (
<ComposerToolsMenu
inputRef={inputRef}
side={effectiveMenuSide}
researchAvailable={!researchUsed}
audioUploadBusy={audioUpload.busy}
/>
),
[effectiveMenuSide, researchUsed, audioUpload.busy],
);
const pills = useMemo(
() => (
<>
<PermissionModeComposerPill side={effectiveMenuSide} />
{effectiveDeepResearchEnabled ? (
<DeepResearchComposerButton
onConfigure={() => setResearchWebsiteAccessOpen(true)}
/>
) : null}
<WebSearchToggle />
<CodeToolsToggle />
<BrowserAgentPill glyph={(icon) => <PillGlyph>{icon}</PillGlyph>} />
<ImagesToggle />
<KnowledgeBaseComposerButton side={effectiveMenuSide} />
{mcpEnabledForChat ? (
<McpComposerButton side={effectiveMenuSide} />
) : null}
<SkillsComposerButton side={effectiveMenuSide} />
</>
),
[effectiveMenuSide, effectiveDeepResearchEnabled, mcpEnabledForChat],
);
const attachments = useMemo(
() => (
<>
<ComposerAttachments oneRowInChat={true} />
<PendingAudioChip />
</>
),
[],
);
const toolStatus = useMemo(() => <ToolStatusDisplay />, []);
const documentsBar = useMemo(
() => (
<ThreadDocumentsBar
threadId={referenceThreadId}
onIndexingChange={handleIndexingChange}
/>
),
[referenceThreadId, handleIndexingChange],
);
const researchWebsiteAccessDialog = useMemo(
() => (
<DeepResearchWebsiteAccessDialog
open={researchWebsiteAccessOpen && effectiveDeepResearchEnabled}
onOpenChange={setResearchWebsiteAccessOpen}
/>
),
[researchWebsiteAccessOpen, effectiveDeepResearchEnabled],
);
const composerContent = (
<>
{!isDictating ? attachments : null}
{!isDictating ? <ComposerDraftPreview text={composerText} /> : null}
{!isDictating ? toolStatus : null}
<div
className="unsloth-composer-line"
// The permission pill is always visible, so stay two-row unless dictating.
data-expanded={!isDictating ? "true" : "false"}
data-dictating={isDictating ? "true" : undefined}
>
<div
ref={pillRowRef}
className="unsloth-composer-left"
data-pill-compact={pillCompact}
>
{toolsMenu}
{!isDictating ? pills : null}
</div>
{isDictating ? (
<ChatDictationBar
onSend={sendAfterDictation}
// Every state handleSubmit would reject after transcription; text comes from the transcript.
sendDisabled={dictationBlocked}
/>
) : (
<>
<div
ref={editorRef}
className="unsloth-composer-editor"
style={
{
"--composer-editor-height": `${composerText.length === 0 ? oneRowHeight : Math.max(oneRowHeight, editorHeight)}px`,
} as CSSProperties
}
>
<ComposerPrimitive.Input
id={inputId}
submitMode="none"
placeholder={
overlay ? "Type your edits for your image" : "Ask anything"
}
ref={composerSurfaceRef}
data-type-to-activate="composer"
className="aui-composer-input unsloth-composer-input"
minRows={1}
maxRows={12}
onHeightChange={handleEditorHeightChange}
autoFocus={!disabled}
disabled={disabled}
aria-label={overlay ? "Image edit instructions" : "Message input"}
dir="auto"
{...inputProps}
cancelOnEscape={!(declineMounted && declineOwnsEscape)}
onScrollCapture={(event) =>
markComposerScrollEdges(event.currentTarget)
}
onInputCapture={(event) =>
markComposerScrollEdges(event.currentTarget)
}
onFocusCapture={(event) =>
markComposerScrollEdges(event.currentTarget)
}
// Capture, so inputProps keeps the handlers it already owns.
onKeyDownCapture={notePlainPasteChord}
onKeyUpCapture={endPlainPasteChord}
onBlurCapture={endPlainPasteChord}
addAttachmentOnPaste={false}
onPaste={handleFilePaste}
/>
{(showWritingToggle || isWritingExpanded) && (
<TooltipIconButton
type="button"
tooltip={
isWritingExpanded ? "Collapse composer" : "Expand composer"
}
aria-expanded={isWritingExpanded}
aria-controls={inputId}
disabled={disabled}
className="unsloth-composer-expand absolute -right-1 top-0 size-8 rounded-full bg-transparent text-muted-foreground hover:bg-transparent hover:text-muted-foreground dark:hover:bg-transparent aria-expanded:bg-transparent aria-expanded:text-muted-foreground"
onMouseDown={(event) => event.preventDefault()}
onClick={toggleWritingExpanded}
>
<svg
viewBox="0 0 20 20"
fill="none"
stroke="currentColor"
strokeWidth={2.25}
strokeLinecap="round"
strokeLinejoin="round"
className="size-4"
aria-hidden={true}
>
<path
d={
isWritingExpanded
? "M13 2v5h5M2 13h5v5"
: "M11 4h5v5M4 11v5h5"
}
/>
</svg>
</TooltipIconButton>
)}
</div>
<ComposerRightControls
disabled={
disabled ||
!hasSendableContent ||
isComposing ||
hasPendingAttachments
}
dictationDisabled={dictationEntryDisabled}
// disableQueue makes running threads show Stop instead of Queue.
queueDisabled={
disableQueue ||
!(
canQueueCurrentPrompt ||
canQueueTextAttachmentsPrompt ||
canQueueAttachmentPrompt
)
}
onQueueClick={() => formRef.current?.requestSubmit()}
// ComposerPrimitive.Send skips form submit, so run the full queue and capacity path.
onSendClick={handleSubmit}
onStopClick={stopQueue}
onResumeClick={resumeQueue}
onDictateClick={startDictation}
audioUpload={audioUpload}
pendingSend={pendingSend}
menuSide={effectiveMenuSide}
queueThreadIds={promptQueueThreadIds}
/>
</>
)}
</div>
{researchWebsiteAccessDialog}
<ChatAudioUploadMount audioUpload={audioUpload} />
</>
);
// The blur is only on while the overlay shows: WebKitGTK stops drawing the composer's own Glass
// blur while a hidden (opacity 0) child still carries a backdrop-filter.
const dropOverlay = (
<div
className={cn(
"aui-composer-drop-overlay pointer-events-none absolute inset-0 z-20 flex flex-col items-center justify-center gap-1 overflow-hidden rounded-[inherit] bg-background/90 opacity-0 transition-opacity duration-150 group-data-[dragging=true]/dropzone:opacity-100 group-data-[dragging=true]/dropzone:backdrop-blur-sm dark:bg-card/90",
(pageDragging || nativeDragging) && "opacity-100 backdrop-blur-sm",
)}
>
<HugeiconsIcon
icon={Attachment01Icon}
strokeWidth={2}
className="size-6 text-primary"
/>
<span className="text-sm font-medium text-primary">
Drop files here
</span>
</div>
);
return (
<PromptQueueContext.Provider value={queueContextValue}>
<ComposerPrimitive.Unstable_TriggerPopoverRoot>
<SkillMentionPopover
// mentions remain available without Code because each one offers read_skill.
enabled={supportsTools && skillsSwitchOn}
composerRef={editorRef}
onConsumesEnterChange={setMentionConsumesEnter}
onOpenChange={setMentionOpen}
/>
<ComposerPrimitive.Root
ref={attachComposer}
// skip find-in-page because it cannot index the textarea and would match toolbar pills.
{...{ [FIND_SKIP_ATTRIBUTE]: "" }}
className="aui-composer-root relative flex w-full flex-col"
data-writing-expanded={
isWritingExpanded && !isDictating ? "true" : undefined
}
aria-disabled={disabled}
onSubmit={handleSubmit}
>
<PromptQueueStack queueThreadIds={promptQueueThreadIds} />
{/* Chat with files card. Stays mounted while dictating to keep indexing state. */}
<div className={isDictating ? "hidden" : "contents"}>
{documentsBar}
</div>
{youtubeOfferUrl && !isDictating && !disabled ? (
// Keyed by URL so a second paste remounts and aborts the stale request.
<YoutubeTranscriptPrompt
key={youtubeOfferUrl}
url={youtubeOfferUrl}
onClose={() => setYoutubeLink(null)}
/>
) : null}
{isTauri ? (
<div className="aui-composer-attachment-dropzone unsloth-composer-surface relative z-10">
{composerContent}
{dropOverlay}
</div>
) : (
<ComposerPrimitive.AttachmentDropzone
className="group/dropzone aui-composer-attachment-dropzone unsloth-composer-surface relative z-10"
onDragEnterCapture={claimPortaledDrop}
onDragOverCapture={claimPortaledDrop}
onDropCapture={claimPortaledDrop}
>
{composerContent}
{dropOverlay}
</ComposerPrimitive.AttachmentDropzone>
)}
</ComposerPrimitive.Root>
</ComposerPrimitive.Unstable_TriggerPopoverRoot>
</PromptQueueContext.Provider>
);
};
function isNativeComposing(event: Event) {
return "isComposing" in event && (event as InputEvent).isComposing === true;
}
// An autocorrect commit; its value can differ from what was sent, so equality is not enough.
function isTextReplacement(event: Event | undefined) {
return inputTypeOf(event) === "insertReplacementText";
}
// An IME composition write: stale only when the composition began before the send.
// compositionend counts: onCompositionEnd applies its value and no input event follows.
function isCompositionWrite(event: Event | undefined) {
return (
inputTypeOf(event) === "insertCompositionText" ||
event?.type === "compositionend" ||
(event !== undefined && isNativeComposing(event))
);
}
// Gesture-only input types apply even with the sent text; drag-drop and yank have no hook.
const DELIBERATE_INPUT_TYPES = new Set([
"historyUndo",
"historyRedo",
"insertFromPaste",
"insertFromDrop",
"insertFromYank",
]);
function isDeliberateWrite(event: Event | undefined) {
return DELIBERATE_INPUT_TYPES.has(inputTypeOf(event) ?? "");
}
function inputTypeOf(event: Event | undefined): string | undefined {
if (event === undefined || !("inputType" in event)) return undefined;
return (event as InputEvent).inputType;
}
// Stuck IME fallback: Chrome on Windows against WSL never fires compositionend (#5546). Every
// compositionupdate or input resets the timer.
const IME_STUCK_TIMEOUT_MS = 2500;
function useImeComposerInputHandlers({
submitOnEnter = false,
skipEnterRef,
onSubmitKey,
sendShortcut = "enter",
justSentRef,
draftKeyRef,
}: {
submitOnEnter?: boolean;
/** Set while a composer popover will consume plain Enter itself. */
skipEnterRef?: RefObject<boolean>;
onSubmitKey?: (
event: KeyboardEvent<HTMLTextAreaElement>,
intent: ComposerSubmitIntent,
) => void;
sendShortcut?: ComposerSendShortcut;
// Guard armed by the last send or queue. See setComposerText below.
justSentRef?: RefObject<SentTextGuard | null>;
// The composer outlives a thread switch; this says whether the guard belongs to this thread.
draftKeyRef?: RefObject<string | null>;
} = {}) {
const aui = useAui();
const composingRef = useRef(false);
const imeSessionOpenRef = useRef(false);
const compositionEndedAtRef = useRef(-Infinity);
const [isComposing, setIsComposing] = useState(false);
const stuckTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const clearStuckTimer = useCallback(() => {
if (stuckTimerRef.current) {
clearTimeout(stuckTimerRef.current);
stuckTimerRef.current = null;
}
}, []);
const setCompositionState = useCallback(
(next: boolean) => {
composingRef.current = next;
setIsComposing(next);
clearStuckTimer();
if (next) {
stuckTimerRef.current = setTimeout(() => {
stuckTimerRef.current = null;
composingRef.current = false;
setIsComposing(false);
}, IME_STUCK_TIMEOUT_MS);
}
},
[clearStuckTimer],
);
const refreshStuckTimer = useCallback(() => {
if (!composingRef.current) {
return;
}
clearStuckTimer();
stuckTimerRef.current = setTimeout(() => {
stuckTimerRef.current = null;
composingRef.current = false;
setIsComposing(false);
}, IME_STUCK_TIMEOUT_MS);
}, [clearStuckTimer]);
useEffect(() => clearStuckTimer, [clearStuckTimer]);
// False when refused, so the caller can preventDefault the Input's own handler.
const setComposerText = useCallback(
(value: string, nativeEvent?: Event): boolean => {
const composer = aui.composer();
if (!composer.getState().isEditing) {
return false;
}
// Refuse the sent message coming back, but only in the thread that sent it.
const guardOwnsThread =
justSentRef?.current == null ||
draftKeyRef === undefined ||
justSentRef.current.draftKey === draftKeyRef.current;
if (justSentRef && guardOwnsThread) {
const result = applySentTextGuard(justSentRef.current, {
value,
replacesText: isTextReplacement(nativeEvent),
isDeliberate: isDeliberateWrite(nativeEvent),
isComposition: isCompositionWrite(nativeEvent),
composerIsEmpty: composer.getState().text.length === 0,
});
justSentRef.current = result.guard;
if (!result.accept) {
return false;
}
}
flushResourcesSync(() => {
composer.setText(value);
});
return true;
},
[aui, draftKeyRef, justSentRef],
);
const onCompositionStart = useCallback(() => {
// Dictation and handwriting insert without keydown; a post-send composition is not queued.
if (justSentRef) {
justSentRef.current = markSentTextGuardUserInput(justSentRef.current);
}
imeSessionOpenRef.current = true;
setCompositionState(true);
}, [justSentRef, setCompositionState]);
const onCompositionUpdate = useCallback(() => {
refreshStuckTimer();
}, [refreshStuckTimer]);
const onCompositionEnd = useCallback(
(e: CompositionEvent<HTMLTextAreaElement>) => {
imeSessionOpenRef.current = false;
compositionEndedAtRef.current = e.timeStamp;
setCompositionState(false);
if (!setComposerText(e.currentTarget.value, e.nativeEvent)) {
e.preventDefault();
}
},
[setComposerText, setCompositionState],
);
const onChange = useCallback(
(e: ChangeEvent<HTMLTextAreaElement>) => {
setCompositionState(isNativeComposing(e.nativeEvent));
if (!setComposerText(e.target.value, e.nativeEvent)) {
e.preventDefault();
}
},
[setComposerText, setCompositionState],
);
// Re-arm composingRef from the native event (isComposing / keyCode 229) so a cleared watchdog
// cannot let preedit text submit; re-arm the watchdog too or it pins true forever.
const onKeyDown = useCallback(
(e: KeyboardEvent<HTMLTextAreaElement>) => {
const msSinceCompositionEnd = e.timeStamp - compositionEndedAtRef.current;
compositionEndedAtRef.current = -Infinity;
const imeKey = e.nativeEvent.isComposing || e.keyCode === 229;
if (imeKey) {
if (
imeKeydownBlocksComposerSubmit(
e,
imeSessionOpenRef.current,
msSinceCompositionEnd,
)
) {
// Not user input: a candidate pick continues a composition the send left open.
composingRef.current = true;
refreshStuckTimer();
return;
}
setCompositionState(false);
}
if (justSentRef && isGuardRetiringKey(e)) {
justSentRef.current = markSentTextGuardUserInput(justSentRef.current);
}
if (composingRef.current) {
// Candidate-confirming Enter can arrive as non-composing; keep it gated.
if (e.key === "Enter") {
if (!e.shiftKey) {
e.preventDefault();
}
refreshStuckTimer();
return;
}
// A non-IME key while composingRef is stuck (macOS input-method switch): clear immediately.
setCompositionState(false);
}
if (submitOnEnter && !skipEnterRef?.current) {
const intent = composerSubmitIntent(
imeKey ? composerKeyEventForImeSubmit(e) : e,
sendShortcut,
e.currentTarget?.value,
);
if (intent) {
e.preventDefault();
if (onSubmitKey) onSubmitKey(e, intent);
else e.currentTarget.form?.requestSubmit();
}
}
},
[
justSentRef,
onSubmitKey,
sendShortcut,
refreshStuckTimer,
setCompositionState,
skipEnterRef,
submitOnEnter,
],
);
// macOS input-method switches can leave composition open; the OS commits it before blur.
const onBlur = useCallback(() => {
imeSessionOpenRef.current = false;
setCompositionState(false);
}, [setCompositionState]);
return {
inputProps: {
onCompositionStart,
onCompositionUpdate,
onCompositionEnd,
onChange,
onKeyDown,
onBlur,
},
isComposing,
isComposingRef: composingRef,
imeSessionOpenRef,
};
}
const BulbIcon: FC<{ className?: string }> = ({ className }) => (
<svg
className={className}
viewBox="-10.24 -10.24 1044.48 1044.48"
fill="currentColor"
stroke="currentColor"
strokeWidth={16.384}
xmlns="http://www.w3.org/2000/svg"
aria-hidden={true}
>
<path d="M511.984 0c-198.032 0-353.12 161.104-353.12 359.136 0 149.2 73.28 220.256 131.185 272.128 37.28 33.424 62.368 53.552 62.368 78.352v54.255c0 1.392.193 2.752.368 4.128h-.72v92.624c.016 97.712 63.2 163.376 161.072 163.376 94.464 0 158.944-65.664 158.944-163.376V768h-.928c.176-1.376.416-2.736.416-4.128v-54.255c0-37.76 28.032-60.592 70.528-97.696 57.504-50.208 123.023-112.688 123.023-252.784C865.136 161.104 710.016 0 511.983 0zm-1.215 960c-59.904 0-94.689-37.152-94.689-99.376l-.463-42.672C438.64 825.824 470 832 512 832c41.424 0 72.848-6.624 96.08-14.768v43.392c0 63.152-35.247 99.376-97.312 99.376zm189.248-396.288c-43.472 37.968-92.433 77.216-92.433 145.904v40.432c-15.183 8.48-43.183 18.56-96.127 18.56-55.569 0-81.92-9.856-95.024-17.473V709.6c0-54.608-42.688-89.297-83.68-126.017-54.32-48.672-109.873-103.84-109.873-224.464-.015-162.72 126.385-295.12 289.104-295.12 162.752 0 289.152 132.4 289.152 295.137 0 111.024-48.463 158.576-101.12 204.576z" />
</svg>
);
const ThinkIcon: FC = () => <BulbIcon className="size-[calc(15.5px*var(--ui-space-scale,1))]" />;
const ReasoningToggle: FC<{ side?: "top" | "bottom" }> = ({
side = "bottom",
}) => {
const modelLoaded = useChatRuntimeStore(
(s) => !!s.params.checkpoint && !s.modelLoading,
);
const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);
const supportsReasoning = useChatRuntimeStore((s) => s.supportsReasoning);
const reasoningAlwaysOn = useChatRuntimeStore((s) => s.reasoningAlwaysOn);
const reasoningEnabled = useChatRuntimeStore((s) => s.reasoningEnabled);
const setReasoningEnabled = useChatRuntimeStore((s) => s.setReasoningEnabled);
const reasoningStyle = useChatRuntimeStore((s) => s.reasoningStyle);
const reasoningEffort = useChatRuntimeStore((s) => s.reasoningEffort);
const supportsReasoningOff = useChatRuntimeStore(
(s) => s.supportsReasoningOff,
);
const reasoningEffortLevels = useChatRuntimeStore(
(s) => s.reasoningEffortLevels,
);
const setReasoningEffort = useChatRuntimeStore((s) => s.setReasoningEffort);
const connectionsEnabled = useExternalProvidersStore(
(s) => s.connectionsEnabled,
);
const externalProvidersAll = useExternalProvidersStore((s) => s.providers);
const externalProviders = connectionsEnabled ? externalProvidersAll : [];
const externalSelection = parseExternalModelId(checkpoint);
const selectedExternalProvider =
externalSelection != null
? externalProviders.find((p) => p.id === externalSelection.providerId)
: undefined;
const isKimiExternal = kimiSearchExcludesThinking(
selectedExternalProvider?.providerType,
externalSelection?.modelId,
);
const toolsEnabled = useChatRuntimeStore((s) => s.toolsEnabled);
const setToolsEnabled = useChatRuntimeStore((s) => s.setToolsEnabled);
const supportsPreserveThinking = useChatRuntimeStore(
(s) => s.supportsPreserveThinking,
);
const preserveThinking = useChatRuntimeStore((s) => s.preserveThinking);
const setPreserveThinking = useChatRuntimeStore((s) => s.setPreserveThinking);
useSyncExternalStore(subscribeModelCatalog, modelCatalogVersion);
const externalReasoningCaps =
externalSelection != null
? getExternalReasoningCapabilities(
selectedExternalProvider?.providerType,
// The adapter resolves reasoning for the selected id; openrouter/free can route each turn elsewhere.
externalSelection?.modelId,
{
isReasoningProvider:
selectedExternalProvider?.isReasoningModel === true,
// Lets the resolver detect custom Gemini OAI-compat gateways.
baseUrl: selectedExternalProvider?.baseUrl ?? null,
apiType: selectedExternalProvider?.apiType,
reasoningConfig: selectedExternalProvider?.reasoningConfig,
},
)
: null;
const effectiveReasoningStyle =
externalReasoningCaps?.reasoningStyle ?? reasoningStyle;
const effectiveReasoningAlwaysOn =
externalReasoningCaps?.reasoningAlwaysOn ?? reasoningAlwaysOn;
const effectiveSupportsReasoningOff =
externalReasoningCaps?.supportsReasoningOff ?? supportsReasoningOff;
const effectiveReasoningEffortLevels =
externalReasoningCaps?.reasoningEffortLevels ?? reasoningEffortLevels;
const effectiveSupportsReasoning =
externalReasoningCaps?.supportsReasoning ?? supportsReasoning;
const reasoningLockedOn =
effectiveSupportsReasoning &&
(effectiveReasoningAlwaysOn || !effectiveSupportsReasoningOff);
const effectiveReasoningEnabled = reasoningLockedOn ? true : reasoningEnabled;
// Show the stored effort clamped to the current ladder without overwriting the choice.
const displayedEffort =
effectiveReasoningEffortLevels.length > 0
? clampReasoningEffortToLevels(reasoningEffort, effectiveReasoningEffortLevels)
: reasoningEffort;
const effectiveReasoningVisualEnabled =
effectiveReasoningEnabled && displayedEffort !== "none";
const disabled =
!modelLoaded || !(effectiveSupportsReasoning || supportsPreserveThinking);
const formatEffortLabel = (level: typeof reasoningEffort): string => {
if (level !== "xhigh")
return level.charAt(0).toUpperCase() + level.slice(1);
const normalized = externalSelection?.modelId?.trim().toLowerCase() ?? "";
if (
normalized.startsWith("claude-opus-4-6") ||
normalized.startsWith("claude-sonnet-4-6")
) {
return "Max";
}
return "Extra High";
};
const effortLabel = formatEffortLabel(displayedEffort);
// A connection may support history preservation without a generation toggle.
if (!effectiveSupportsReasoning && !supportsPreserveThinking) {
return null;
}
// enable_thinking_effort reuses the effort dropdown, adding an Off row.
const isEffort =
effectiveReasoningStyle === "reasoning_effort" ||
effectiveReasoningStyle === "enable_thinking_effort";
const useDropdown = isEffort || supportsPreserveThinking;
const activeLook = !effectiveSupportsReasoning
? preserveThinking && !disabled
: isEffort
? reasoningLockedOn || (effectiveReasoningVisualEnabled && !disabled)
: reasoningLockedOn || (effectiveReasoningEnabled && !disabled);
if (useDropdown) {
return (
<NonModalDropdownMenu
side={side}
align="end"
avoidCollisions={true}
className="unsloth-plus-menu unsloth-thinking-menu min-w-0 w-[calc(176px*var(--ui-space-scale,1))]"
trigger={(triggerRef) => (
<button
ref={triggerRef}
type="button"
disabled={disabled}
className="unsloth-thinking-pill"
data-pill-label="Thinking settings"
data-active={activeLook ? "true" : "false"}
aria-label={thinkEffortAriaLabel({
modelLoaded,
reasoningDisabled: disabled,
reasoningEffort: displayedEffort,
})}
>
<ThinkIcon />
{activeLook ? (
<span className="unsloth-thinking-label">
{isEffort ? `Thinking · ${effortLabel}` : "Thinking"}
</span>
) : null}
<HugeiconsIcon icon={ChevronDownStandardIcon} strokeWidth={1.5} className="unsloth-thinking-caret size-[calc(15px*var(--ui-space-scale,1))]" />
</button>
)}
>
{isEffort ? (
<>
{effectiveSupportsReasoningOff && (
<DropdownMenuItem
onSelect={() => {
setReasoningEnabled(false);
applyQwenThinkingParams(false);
// Preserve thinking needs thinking on, so turn it off too.
setPreserveThinking(false);
}}
>
None
<HugeiconsIcon
icon={Tick02Icon}
strokeWidth={2}
className={cn(
"unsloth-tick ms-auto size-4",
effectiveReasoningVisualEnabled && "opacity-0",
)}
/>
</DropdownMenuItem>
)}
{effectiveReasoningEffortLevels
// 'none' is a real template level for some models; skip it only if the off item covers it.
.filter(
(level) =>
level !== "none" || !effectiveSupportsReasoningOff,
)
.map((level) => (
<DropdownMenuItem
key={level}
onSelect={() => {
setReasoningEffort(level);
setReasoningEnabled(true);
applyQwenThinkingParams(true);
// Kimi's $web_search forbids thinking, so enabling thinking turns Search off.
if (isKimiExternal && toolsEnabled) {
setToolsEnabled(false, { persist: false });
}
}}
>
{formatEffortLabel(level)}
<HugeiconsIcon
icon={Tick02Icon}
strokeWidth={2}
className={cn(
"unsloth-tick ms-auto size-4",
!(
effectiveReasoningVisualEnabled &&
displayedEffort === level
) && "opacity-0",
)}
/>
</DropdownMenuItem>
))}
</>
) : (
effectiveSupportsReasoning &&
effectiveSupportsReasoningOff &&
!reasoningLockedOn && (
<DropdownMenuItem
onSelect={() => {
const next = !reasoningEnabled;
setReasoningEnabled(next);
applyQwenThinkingParams(next);
if (!next) setPreserveThinking(false);
if (isKimiExternal && next && toolsEnabled) {
setToolsEnabled(false, { persist: false });
}
}}
>
Thinking
<HugeiconsIcon
icon={Tick02Icon}
strokeWidth={2}
className={cn(
"unsloth-tick ms-auto size-4",
!effectiveReasoningEnabled && "opacity-0",
)}
/>
</DropdownMenuItem>
)
)}
{supportsPreserveThinking && (
<DropdownMenuItem
disabled={disabled}
onSelect={(e) => {
e.preventDefault();
const next = !preserveThinking;
setPreserveThinking(next);
// Only local models couple this setting to generation controls.
if (next && externalSelection === null) {
setReasoningEnabled(true);
applyQwenThinkingParams(true);
}
}}
>
Preserve thinking
<HugeiconsIcon
icon={Tick02Icon}
strokeWidth={2}
className={cn(
"unsloth-tick ms-auto size-4",
!preserveThinking && "opacity-0",
)}
/>
</DropdownMenuItem>
)}
</NonModalDropdownMenu>
);
}
return (
<button
type="button"
disabled={disabled || reasoningLockedOn}
aria-disabled={disabled || reasoningLockedOn}
title={
reasoningLockedOn
? "This model requires reasoning to stay on."
: undefined
}
onClick={() => {
if (reasoningLockedOn) return;
const next = !reasoningEnabled;
setReasoningEnabled(next);
applyQwenThinkingParams(next);
// Mutually exclusive with Search on Kimi (see dropdown branch).
if (isKimiExternal && next && toolsEnabled) {
setToolsEnabled(false, { persist: false });
}
}}
className="unsloth-thinking-pill"
data-pill-label="Thinking"
data-active={activeLook ? "true" : "false"}
aria-label={thinkToggleAriaLabel({
reasoningLockedOn,
modelLoaded,
reasoningDisabled: disabled,
effectiveReasoningEnabled,
})}
>
<PillGlyph>
<ThinkIcon />
</PillGlyph>
{activeLook ? (
<span className="unsloth-thinking-label">Thinking</span>
) : null}
</button>
);
};
const PillGlyph: FC<{ children: ReactNode }> = ({ children }) => (
<span className="composer-pill-glyph">
{children}
<HugeiconsIcon icon={Cancel01Icon} className="composer-pill-x" />
</span>
);
const WebSearchToggle: FC = () => {
const modelLoaded = useChatRuntimeStore(
(s) => !!s.params.checkpoint && !s.modelLoading,
);
const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);
const supportsTools = useChatRuntimeStore((s) => s.supportsTools);
// External providers can expose a server-side web_search tool; mirrors shared-composer.
const supportsBuiltinWebSearch = useChatRuntimeStore(
(s) => s.supportsBuiltinWebSearch,
);
const toolsEnabled = useChatRuntimeStore((s) => s.toolsEnabled);
const setToolsEnabled = useChatRuntimeStore((s) => s.setToolsEnabled);
const setReasoningEnabled = useChatRuntimeStore((s) => s.setReasoningEnabled);
const connectionsEnabled = useExternalProvidersStore(
(s) => s.connectionsEnabled,
);
const externalProvidersAll = useExternalProvidersStore((s) => s.providers);
const externalProviders = connectionsEnabled ? externalProvidersAll : [];
const externalSelection = parseExternalModelId(checkpoint);
const selectedExternalProvider =
externalSelection != null
? externalProviders.find((p) => p.id === externalSelection.providerId)
: undefined;
const isKimiExternal = kimiSearchExcludesThinking(
selectedExternalProvider?.providerType,
externalSelection?.modelId,
);
// Disable only when a loaded model lacks the capability; with no model the
// tool can still be pre-selected, matching the + menu.
const disabled = modelLoaded && !(supportsTools || supportsBuiltinWebSearch);
return (
<button
type="button"
disabled={disabled}
onClick={() => {
const next = !toolsEnabled;
setToolsEnabled(next);
// Kimi's $web_search requires thinking disabled; keep the pills mutually exclusive.
if (isKimiExternal) {
setReasoningEnabled(!next, { persist: false });
applyQwenThinkingParams(!next);
}
}}
className="composer-pill-btn"
data-pill-label="Search"
data-active={toolsEnabled && !disabled ? "true" : "false"}
aria-label={toolsEnabled ? "Disable web search" : "Enable web search"}
>
<PillGlyph>
<InternetGlyph className="size-[calc(15px*var(--ui-space-scale,1))]" />
</PillGlyph>
<span>Search</span>
</button>
);
};
const CodeToolsToggle: FC = () => {
const modelLoaded = useChatRuntimeStore(
(s) => !!s.params.checkpoint && !s.modelLoading,
);
const supportsTools = useChatRuntimeStore((s) => s.supportsTools);
// Claude 4.x runs code_execution server-side; mirrors shared-composer's codeDisabled.
const supportsBuiltinCodeExecution = useChatRuntimeStore(
(s) => s.supportsBuiltinCodeExecution,
);
const codeToolsEnabled = useChatRuntimeStore(codeToolsOn);
const setCodeToolsEnabled = useChatRuntimeStore((s) => s.setCodeToolsEnabled);
const disabled = modelLoaded && !(supportsTools || supportsBuiltinCodeExecution);
return (
<button
type="button"
disabled={disabled}
onClick={() => setCodeToolsEnabled(!codeToolsEnabled)}
className="composer-pill-btn"
data-pill-label="Tools"
data-active={codeToolsEnabled && !disabled ? "true" : "false"}
aria-label={
codeToolsEnabled ? "Disable tools" : "Enable tools"
}
>
<PillGlyph>
<HugeiconsIcon
icon={CodeIcon}
className="size-[calc(18.5px*var(--ui-space-scale,1))]"
strokeWidth={2}
/>
</PillGlyph>
<span>Tools</span>
</button>
);
};
const ImagesToggle: FC = () => {
const modelLoaded = useChatRuntimeStore(
(s) => !!s.params.checkpoint && !s.modelLoading,
);
// The provider's own image_generation, or the image or video model loaded in
// Unsloth for a model that calls Unsloth tools. Mirror of
// shared-composer's imageDisabled / showImagePill so this composer matches the empty state.
const imageToolShown = useChatRuntimeStore(imageToolAvailable);
const imageToolsEnabled = useChatRuntimeStore((s) => s.imageToolsEnabled);
const setImageToolsEnabled = useChatRuntimeStore(
(s) => s.setImageToolsEnabled,
);
if (!imageToolShown) {
return null;
}
const disabled = !modelLoaded;
return (
<button
type="button"
disabled={disabled}
onClick={() => setImageToolsEnabled(!imageToolsEnabled)}
className="composer-pill-btn"
data-pill-label="Images"
data-active={imageToolsEnabled && !disabled ? "true" : "false"}
aria-label={
imageToolsEnabled
? "Disable image generation"
: "Enable image generation"
}
>
<PillGlyph>
<HugeiconsIcon icon={ImageIcon} className="size-3.5" strokeWidth={2} />
</PillGlyph>
<span>Images</span>
</button>
);
};
const ToolStatusDisplay: FC = () => {
// This conversation's status only. remoteId, not id: the adapter keys the map by unstable_threadId.
const threadListItemId = useAuiState(
({ threadListItem }) => threadListItem.remoteId,
);
const isThreadRunning = useAuiState(({ thread }) => thread.isRunning);
const entry = useChatRuntimeStore((s) => {
// A first turn files under "__default" before its id persists; claim it only when it holds one run.
const unresolved = s.toolStatusByThreadId.__default;
const own =
s.toolStatusByThreadId[threadListItemId ?? ""] ??
(isThreadRunning && unresolved?.length === 1 ? unresolved : undefined);
// Newest run for this key, so one finishing cannot blank a sibling still running a tool.
return own?.[own.length - 1];
});
const toolStatus = entry?.status ?? null;
const startedAt = entry?.startedAt ?? null;
const [now, setNow] = useState(() => Date.now());
const [visible, setVisible] = useState(false);
const visibleRef = useRef(false);
useEffect(() => {
visibleRef.current = visible;
}, [visible]);
useEffect(() => {
if (!startedAt) {
if (!isThreadRunning) {
setVisible(false);
}
return;
}
setNow(Date.now());
// 300ms debounce unless already visible, so short tool calls never flash the badge.
let showTimer: ReturnType<typeof setTimeout> | undefined;
if (!visibleRef.current) {
showTimer = setTimeout(() => setVisible(true), 300);
}
const interval = setInterval(() => setNow(Date.now()), 1000);
return () => {
clearInterval(interval);
if (showTimer) {
clearTimeout(showTimer);
}
};
}, [startedAt, isThreadRunning]);
if (!(toolStatus && startedAt && visible)) {
return null;
}
// From the store's start time, so returning to the conversation resumes rather than restarting.
const elapsed = Math.max(0, Math.floor((now - startedAt) / 1000));
const kind = toolStatusKind(toolStatus);
const isNudging = kind === "nudge";
const StatusIcon = kind === "terminal" ? TerminalIcon : InternetGlyph;
return (
<div
data-testid="composer-tool-status"
className="mb-2 flex w-full flex-row items-center gap-2 px-1.5 pt-0.5 pb-1"
>
<div
className={cn(
"flex items-center gap-2 rounded-full border border-primary/20 bg-primary/5 px-3 py-1.5 text-xs text-primary",
// The spinner is its own motion cue; pulsing too just fades it mid-spin.
!isNudging && "animate-pulse",
)}
>
{isNudging ? (
// The spinner is the only role="status" region, so its label is what gets announced.
<Spinner className="size-3.5" label={toolStatus} />
) : (
<StatusIcon className="size-3.5" />
)}
<span>{toolStatus}</span>
<span className="tabular-nums opacity-60">{elapsed}s</span>
</div>
</div>
);
};
const AUDIO_ACCEPT_TOKEN_RE =
/^(audio\/|\.(?:wav|mp3|mp2|m4a|ogg|oga|opus|flac|aac|aiff|aif|aifc|caf|wma|amr|m4b|weba|mka)$)/i;
function attachmentAcceptForPicker(accept: string, audioEnabled: boolean): string {
const enabledAccept =
audioEnabled || accept === "*"
? accept
: accept
.split(",")
.map((token) => token.trim())
.filter((token) => token && !AUDIO_ACCEPT_TOKEN_RE.test(token))
.join(",") || accept;
return pickerAcceptForTextBasenames(enabledAccept);
}
function usePickComposerAttachment(): () => void {
const aui = useAui();
const audioAttachmentsEnabled = useChatRuntimeStore((s) => {
const activeCheckpoint = s.params.checkpoint;
// No model yet: offer audio too, since files attached now wait for the model loaded next.
if (!activeCheckpoint || s.modelLoading) {
return true;
}
const activeModel = s.models.find((m) => m.id === activeCheckpoint);
return Boolean(activeModel?.hasAudioInput);
});
return useCallback(() => {
const attachmentAccept = attachmentAcceptForPicker(
aui.composer().getState().attachmentAccept,
audioAttachmentsEnabled,
);
openFilePicker(attachmentAccept, (files) => {
for (const file of files) {
void aui.composer().addAttachment(file);
}
});
}, [aui, audioAttachmentsEnabled]);
}
const LazyLibraryAttachmentPicker = lazy(() =>
import("@/components/assistant-ui/library-attachment-picker").then((module) => ({
default: module.LibraryAttachmentPicker,
})),
);
const ComposerToolsMenu: FC<{
inputRef: RefObject<HTMLTextAreaElement | null>;
side?: "top" | "bottom";
researchAvailable: boolean;
audioUploadBusy: boolean;
}> = ({ inputRef, side = "bottom", researchAvailable, audioUploadBusy }) => {
const t = useT();
const navigate = useNavigate();
const toolsEnabled = useChatRuntimeStore((s) => s.toolsEnabled);
const setToolsEnabled = useChatRuntimeStore((s) => s.setToolsEnabled);
const codeToolsEnabled = useChatRuntimeStore(codeToolsOn);
const setCodeToolsEnabled = useChatRuntimeStore((s) => s.setCodeToolsEnabled);
const mcpEnabledForChat = useChatRuntimeStore((s) => s.mcpEnabledForChat);
const setMcpEnabledForChat = useChatRuntimeStore(
(s) => s.setMcpEnabledForChat,
);
const deepResearchEnabled = useChatRuntimeStore((s) => s.deepResearchEnabled);
const setDeepResearchEnabled = useChatRuntimeStore((s) => s.setDeepResearchEnabled);
const incognito = useChatRuntimeStore((s) => s.incognito);
const ragEnabled = useChatRuntimeStore((s) => s.ragEnabled);
const setRagEnabled = useChatRuntimeStore((s) => s.setRagEnabled);
// Shared gate so the menu row agrees with the RAG pill.
const ragDisabled = useRagToolDisabled();
// The permission pill is hidden while recording, so the menu carries it then.
const isDictating = useAuiState((s) => s.composer.dictation != null);
// Gate like the visible pills so menu and pills agree on what the loaded model supports.
const modelLoaded = useChatRuntimeStore(
(s) => !!s.params.checkpoint && !s.modelLoading,
);
const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);
const supportsTools = useChatRuntimeStore((s) => s.supportsTools);
const supportsBuiltinWebSearch = useChatRuntimeStore(
(s) => s.supportsBuiltinWebSearch,
);
const supportsBuiltinCodeExecution = useChatRuntimeStore(
(s) => s.supportsBuiltinCodeExecution,
);
const imageToolShown = useChatRuntimeStore(imageToolAvailable);
const imageToolsEnabled = useChatRuntimeStore((s) => s.imageToolsEnabled);
const setImageToolsEnabled = useChatRuntimeStore(
(s) => s.setImageToolsEnabled,
);
const setReasoningEnabled = useChatRuntimeStore((s) => s.setReasoningEnabled);
const connectionsEnabled = useExternalProvidersStore(
(s) => s.connectionsEnabled,
);
const externalProvidersAll = useExternalProvidersStore((s) => s.providers);
const externalProviders = connectionsEnabled ? externalProvidersAll : [];
const externalSelection = parseExternalModelId(checkpoint);
const selectedExternalProvider =
externalSelection != null
? externalProviders.find((p) => p.id === externalSelection.providerId)
: undefined;
const isKimiExternal = kimiSearchExcludesThinking(
selectedExternalProvider?.providerType,
externalSelection?.modelId,
);
// Disable only when a loaded model lacks the capability; with no model the
// tool can still be pre-selected, matching the pill logic above.
const searchDisabled =
modelLoaded && !(supportsTools || supportsBuiltinWebSearch);
const codeDisabled =
modelLoaded && !(supportsTools || supportsBuiltinCodeExecution);
const imageDisabled = !modelLoaded;
const mcpDisabled = modelLoaded && !supportsTools;
const researchDisabled =
!researchAvailable ||
(modelLoaded && !externalSelection && !supportsTools) ||
(Boolean(externalSelection) &&
providerModelSupportsStudioTools(
selectedExternalProvider?.providerType,
externalSelection?.modelId,
) !== true) ||
incognito;
const { projects } = useChatProjects();
const recentProjects = sortProjectsByActivity(projects).slice(0, 3);
const openProject = (projectId: string) => {
useChatRuntimeStore.getState().setActiveProjectId(projectId);
navigate({ to: "/chat", search: { project: projectId } });
};
const startCompare = useCallback(() => {
const store = useChatRuntimeStore.getState();
store.setActiveThreadId(null);
store.setContextUsage(null);
// crypto.randomUUID is undefined in non-secure contexts (HTTP over a LAN IP).
const compareId =
typeof globalThis.crypto?.randomUUID === "function"
? globalThis.crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
navigate({ to: "/chat", search: { compare: compareId } });
}, [navigate]);
const [newProjectOpen, setNewProjectOpen] = useState(false);
const [skillsOn, setSkillsOn] = useSkillsSwitch();
const [promptStorageOpen, setPromptStorageOpen] = useState(false);
const [libraryPickerOpen, setLibraryPickerOpen] = useState(false);
const libraryPickerRequested = useRef(false);
const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
const aui = useAui();
const composerCanAddAttachments = useAuiState(
({ composer }) => composer.isEditing,
);
const pickAttachment = usePickComposerAttachment();
// Straight to the picker, skipping the "+" menu the item lives in. Off-route
// the chat pane is hidden rather than unmounted, so the chords gate on it
// being the visible tab; a window listener does not care about `inert`.
const chatActive = useChatActive();
useShortcut(
"attachFiles",
() => {
// A dialog over Chat leaves this live, and the OS file chooser is hard to dismiss.
if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return;
pickAttachment();
},
{ enabled: chatActive && composerCanAddAttachments },
);
// Exports are storage-backed; temporary chats intentionally never write there.
const messageCount = useAuiState(({ thread }) => thread.messages.length);
const exportDisabled = incognito || !activeThreadId || messageCount === 0;
const { startQueue } = useContext(PromptQueueContext);
const { overlay: generatedImageOverlay } = useGeneratedImageOverlay();
const menuIsDictating = useAuiState((s) => s.composer.dictation != null);
const plusPins = usePlusMenuPrefsStore((s) => s.pins);
const plusOrder = usePlusMenuPrefsStore((s) => s.order);
const [recentPrompts, setRecentPrompts] = useState<PromptEntry[]>([]);
const [recentLists, setRecentLists] = useState<PromptListEntry[]>([]);
const recentSeqRef = useRef(0);
const refreshRecentPrompts = useCallback(async () => {
recentSeqRef.current += 1;
const seq = recentSeqRef.current;
try {
const rows = await listPromptEntries();
if (seq !== recentSeqRef.current) return;
const byRecent = [...rows].sort((a, b) => b.updatedAt - a.updatedAt);
const pinnedIds = usePlusMenuPrefsStore.getState().pinnedPromptIds;
const pinned = byRecent.filter((p) => pinnedIds.includes(p.id));
setRecentPrompts(pinned.length > 0 ? pinned : byRecent.slice(0, 3));
} catch {
// Clear, don't keep: a stale list row would run its cached items.
if (seq === recentSeqRef.current) setRecentPrompts([]);
}
try {
const rows = await listPromptLists();
if (seq !== recentSeqRef.current) return;
const pinnedIds = usePlusMenuPrefsStore.getState().pinnedListIds;
setRecentLists(rows.filter((l) => pinnedIds.includes(l.id)));
} catch {
if (seq === recentSeqRef.current) setRecentLists([]);
}
}, []);
const [plusOpen, setPlusOpen] = useState(false);
const setPlusMenuOpen = (open: boolean) => {
setPlusOpen(open);
if (open) void refreshRecentPrompts();
};
useShortcut(
"openComposerMenu",
() => {
// The open menu inerts the composer, so closing skips the gate.
if (plusOpen) return setPlusMenuOpen(false);
if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return;
setPlusMenuOpen(true);
},
{ enabled: chatActive },
);
const runPromptList = useCallback(
(items: string[], fromDialog = false) => {
// A queue started while recording would swallow the held transcript send.
if (menuIsDictating) {
toast.error("Finish dictating before running a list");
return;
}
// Starting the queue cancels an in-flight transcription, which would discard it.
if (audioUploadBusy) {
toast.error("Wait for the transcription to finish before running a list");
return;
}
// Mid image edit, startQueue would bypass the overlay's prompt rewrite.
if (generatedImageOverlay) {
toast.error("Close the image editor before running a list", {
description: "Saved lists cannot be applied to a generated image.",
});
return;
}
const started = startQueue(items, undefined, () => {
if (fromDialog) setPromptStorageOpen(true);
toast.info("Saved list was not queued", {
description: "The chat changed before the queue was ready. Try again.",
});
});
if (started) {
setPromptStorageOpen(false);
return;
}
// startQueue refuses synchronously without calling onAborted.
toast.error("Couldn't queue that list here", {
description: "Open a chat first, then run the list.",
});
},
[startQueue, generatedImageOverlay, menuIsDictating, audioUploadBusy, setPromptStorageOpen],
);
// Adjustable "+" menu items: pinned ones render top level, the rest go under "More".
const plusMenuNodes: Record<PlusMenuItemId, ReactNode> = {
deepResearch: researchAvailable ? (
<DropdownMenuItem
disabled={researchDisabled && !deepResearchEnabled}
className={
deepResearchEnabled && !researchDisabled
? "text-primary font-medium"
: undefined
}
onSelect={() => setDeepResearchEnabled(!deepResearchEnabled)}
>
<HugeiconsIcon icon={Telescope02Icon} strokeWidth={2} />
Deep research
{deepResearchEnabled && !researchDisabled ? (
<HugeiconsIcon
icon={Tick02Icon}
strokeWidth={2}
className="ml-auto"
/>
) : null}
</DropdownMenuItem>
) : null,
browserUse: <BrowserAgentMenuItem />,
chatWithFiles: (
<DropdownMenuItem
disabled={ragDisabled}
className={
ragEnabled && !ragDisabled ? "text-primary font-medium" : undefined
}
onSelect={() => {
// With the files panel hidden, the item brings it back rather than turning RAG off.
const { ragPanelHidden, setRagPanelHidden } = useChatRuntimeStore.getState();
if (ragEnabled && ragPanelHidden) {
setRagPanelHidden(false);
return;
}
setRagEnabled(!ragEnabled);
}}
>
<HugeiconsIcon icon={FileSearchIcon} strokeWidth={2} />
Chat with files
{ragEnabled && !ragDisabled ? (
<HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="ml-auto" />
) : null}
</DropdownMenuItem>
),
mcp: (
<DropdownMenuItem
disabled={mcpDisabled}
className={
mcpEnabledForChat && !mcpDisabled
? "text-primary font-medium"
: undefined
}
onSelect={() => setMcpEnabledForChat(!mcpEnabledForChat)}
>
<HugeiconsIcon icon={McpServerIcon} strokeWidth={2} />
MCP
{mcpEnabledForChat && !mcpDisabled ? (
<HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="ml-auto" />
) : null}
</DropdownMenuItem>
),
skills: (
<DropdownMenuItem
className={skillsOn ? "text-primary font-medium" : undefined}
onSelect={() => setSkillsOn(!skillsOn)}
>
<HugeiconsIcon icon={Scroll01Icon} strokeWidth={2} />
Skills
{skillsOn ? (
<HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="ml-auto" />
) : null}
</DropdownMenuItem>
),
savedPrompts: (
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<HugeiconsIcon icon={BookmarkIcon} strokeWidth={2} />
Saved prompts
</DropdownMenuSubTrigger>
<DropdownMenuSubContent
collisionPadding={16}
className="unsloth-plus-menu w-[calc(208px*var(--ui-space-scale,1))]"
>
{recentPrompts.map((p) => (
<DropdownMenuItem
key={`prompt:${p.id}`}
onSelect={() => insertSavedPrompt(inputRef.current, p.text, (next) => aui.composer().setText(next))}
>
<span className="truncate">{p.name}</span>
</DropdownMenuItem>
))}
{recentLists.map((l) => (
<DropdownMenuItem key={`list:${l.id}`} onSelect={() => runPromptList(l.items)}>
<span className="truncate">{l.name}</span>
<PromptCountBadge count={l.items.length} />
</DropdownMenuItem>
))}
{recentPrompts.length > 0 || recentLists.length > 0 ? (
<DropdownMenuSeparator />
) : null}
<DropdownMenuItem onSelect={() => setPromptStorageOpen(true)}>
All saved prompts…
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
),
compareChat: (
<DropdownMenuItem onSelect={() => startCompare()}>
<HugeiconsIcon icon={LayoutTwoColumnIcon} strokeWidth={2} />
Compare chat
</DropdownMenuItem>
),
exportChat: (
<DropdownMenuSub>
<DropdownMenuSubTrigger disabled={exportDisabled}>
<HugeiconsIcon icon={Download01Icon} strokeWidth={2} />
Export chat
</DropdownMenuSubTrigger>
<DropdownMenuSubContent
collisionPadding={16}
className="unsloth-plus-menu w-[calc(208px*var(--ui-space-scale,1))]"
>
<ExportFormatItems
options={[
{ key: "raw", label: "Training JSONL" },
{ key: "messages", label: "Message JSONL" },
{ key: "csv", label: "CSV" },
{ key: "sharegpt", label: "ShareGPT JSONL" },
{ key: "markdown", label: CONVERSATION_MARKDOWN_LABEL },
{ key: "html", label: CONVERSATION_HTML_LABEL },
{ key: "pdf", label: CONVERSATION_PDF_LABEL },
]}
subContentClassName="unsloth-plus-menu w-[calc(176px*var(--ui-space-scale,1))]"
onSelect={(key) => {
if (!activeThreadId) return;
const exporters = {
raw: exportConversationRawJsonl,
messages: exportConversationMessagesJsonl,
csv: exportConversationCsv,
sharegpt: exportConversationShareGPT,
markdown: exportConversationMarkdown,
html: exportConversationHtml,
pdf: exportConversationPdf,
};
exporters[key](activeThreadId).catch((error) => {
if (!isDownloadCancelled(error)) toast.error("Export failed.");
});
}}
/>
</DropdownMenuSubContent>
</DropdownMenuSub>
),
projects: (
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<HugeiconsIcon icon={ProjectIcon} strokeWidth={2} />
Projects
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="unsloth-plus-menu w-[calc(232px*var(--ui-space-scale,1))]">
<DropdownMenuItem onSelect={() => setNewProjectOpen(true)}>
<HugeiconsIcon icon={FolderAddIcon} strokeWidth={2} />
New project
</DropdownMenuItem>
<DropdownMenuLabel>Recents</DropdownMenuLabel>
{recentProjects.length > 0 ? (
recentProjects.map((project) => (
<DropdownMenuItem
key={project.id}
onSelect={() => openProject(project.id)}
>
<HugeiconsIcon icon={ProjectIcon} strokeWidth={2} />
<span className="truncate">{project.name}</span>
</DropdownMenuItem>
))
) : (
<DropdownMenuItem disabled={true}>
No recent projects
</DropdownMenuItem>
)}
</DropdownMenuSubContent>
</DropdownMenuSub>
),
};
const { pinned: pinnedPlusItems, overflow: overflowPlusItems } =
splitPlusMenuItems(plusOrder, plusPins);
const deepResearchWithTools = pinnedPlusItems.includes("deepResearch");
return (
<>
{libraryPickerOpen ? (
<Suspense fallback={null}>
<LazyLibraryAttachmentPicker onClose={() => setLibraryPickerOpen(false)} />
</Suspense>
) : null}
<PromptStorageDialog
open={promptStorageOpen}
onOpenChange={setPromptStorageOpen}
onUse={(text) => insertSavedPrompt(inputRef.current, text, (next) => aui.composer().setText(next))}
onRunList={(items) => runPromptList(items, true)}
/>
<DropdownMenu open={plusOpen} onOpenChange={setPlusMenuOpen}>
<DropdownMenuTrigger asChild={true}>
<button
type="button"
aria-label="Tools and attachments"
data-pill-label="Add files and more"
className="unsloth-composer-plus"
data-tour="chat-plus-menu"
>
<HugeiconsIcon icon={PlusSignIcon} className="size-[calc(22px*var(--ui-space-scale,1))] stroke-[1.75px]" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent
side={side}
align="start"
sideOffset={0}
avoidCollisions={true}
className="unsloth-plus-menu w-[calc(244px*var(--ui-space-scale,1))]"
// Don't refocus the + on close; restored focus showed a stray ring.
onCloseAutoFocus={(event) => {
event.preventDefault();
if (libraryPickerRequested.current) {
libraryPickerRequested.current = false;
if (chatActive) setLibraryPickerOpen(true);
}
}}
>
<DropdownMenuItem
disabled={!composerCanAddAttachments}
onSelect={() => pickAttachment()}
>
<HugeiconsIcon icon={Attachment01Icon} strokeWidth={2} />
Add photos & files
</DropdownMenuItem>
<DropdownMenuItem
disabled={searchDisabled}
className={
toolsEnabled && !searchDisabled
? "text-primary font-medium"
: undefined
}
onSelect={() => {
const next = !toolsEnabled;
setToolsEnabled(next);
// Mirror the Search pill: Kimi forbids search + thinking together.
if (isKimiExternal) {
setReasoningEnabled(!next, { persist: false });
applyQwenThinkingParams(!next);
}
}}
>
<InternetGlyph />
Web search
{toolsEnabled && !searchDisabled ? (
<HugeiconsIcon
icon={Tick02Icon}
strokeWidth={2}
className="ml-auto"
/>
) : null}
</DropdownMenuItem>
<DropdownMenuItem
disabled={codeDisabled}
className={
codeToolsEnabled && !codeDisabled
? "text-primary font-medium"
: undefined
}
onSelect={() => setCodeToolsEnabled(!codeToolsEnabled)}
>
{/* Scale, not width: an oversized box pushed the label out of line. */}
<HugeiconsIcon
icon={CodeIcon}
strokeWidth={2}
className="scale-[1.12]"
/>
Tools
{codeToolsEnabled && !codeDisabled ? (
<HugeiconsIcon
icon={Tick02Icon}
strokeWidth={2}
className="ml-auto"
/>
) : null}
</DropdownMenuItem>
{deepResearchWithTools ? plusMenuNodes.deepResearch : null}
{imageToolShown && (
<DropdownMenuItem
disabled={imageDisabled}
className={
imageToolsEnabled && !imageDisabled
? "text-primary font-medium"
: undefined
}
onSelect={() => setImageToolsEnabled(!imageToolsEnabled)}
>
<HugeiconsIcon icon={ImageIcon} strokeWidth={2} />
Images
{imageToolsEnabled && !imageDisabled ? (
<HugeiconsIcon
icon={Tick02Icon}
strokeWidth={2}
className="ml-auto"
/>
) : null}
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
{isDictating ? <BypassPermissionsMenuItem /> : null}
{pinnedPlusItems
.filter((id) => id !== "deepResearch")
.map((id) => (
<Fragment key={id}>{plusMenuNodes[id]}</Fragment>
))}
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />
More
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="unsloth-plus-menu w-[calc(248px*var(--ui-space-scale,1))]">
<DropdownMenuItem
disabled={!composerCanAddAttachments}
onSelect={() => { libraryPickerRequested.current = true; }}
>
<HugeiconsIcon icon={Attachment01Icon} strokeWidth={2} />
Attach from Library
</DropdownMenuItem>
<DropdownMenuSeparator />
{overflowPlusItems.map((id) => (
<Fragment key={id}>{plusMenuNodes[id]}</Fragment>
))}
{overflowPlusItems.length > 0 && <DropdownMenuSeparator />}
<DropdownMenuItem
onSelect={() => useSettingsDialogStore.getState().openDialog("chat", {
scrollTarget: "chat-composer",
})}
>
<HugeiconsIcon icon={SlidersHorizontalIcon} className="size-4" />
{t("composerSettings.settings")}
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
</DropdownMenuContent>
</DropdownMenu>
<NewProjectDialog
open={newProjectOpen}
onOpenChange={setNewProjectOpen}
/>
</>
);
};
const PromptQueueStack: FC<{ queueThreadIds: string[] }> = ({
queueThreadIds,
}) => {
const queueEntry = usePromptQueueUI((s) =>
findPromptQueueEntry(s, queueThreadIds),
);
const items = usePromptQueueUI((s) => s.items);
const visibleItems = queueEntry
? items.filter((item) => item.runId === queueEntry.runId)
: [];
if (!queueEntry || visibleItems.length === 0) return null;
return (
<PromptQueueList
key={queueEntry.runId}
entry={queueEntry}
items={visibleItems}
onEdit={editPromptQueueItem}
onRemove={removePromptQueueItem}
onMove={movePromptQueueItem}
onSteer={steerPromptQueueItem}
onResume={() => resumePromptQueueRun(queueThreadIds)}
/>
);
};
const ComposerRightControls: FC<{
disabled?: boolean;
dictationDisabled?: boolean;
queueDisabled?: boolean;
onQueueClick?: () => void;
onSendClick?: (event: { preventDefault: () => void }) => void;
onStopClick?: () => void;
onResumeClick?: () => void;
onDictateClick?: () => void;
audioUpload: ReturnType<typeof useChatAudioUpload>;
pendingSend?: boolean;
menuSide?: "top" | "bottom";
queueThreadIds: string[];
}> = ({
disabled,
dictationDisabled,
queueDisabled,
onQueueClick,
onSendClick,
onStopClick,
onResumeClick,
onDictateClick,
audioUpload,
pendingSend,
menuSide,
queueThreadIds,
}) => {
const t = useT();
const followUpBehavior = useChatPreferencesStore((s) => s.followUpBehavior);
const sendShortcut = useChatPreferencesStore((s) => s.sendShortcut);
const micTarget = useVoiceSettingsStore((s) => s.micTarget);
const modelHearsAudio = useChatRuntimeStore(
(s) =>
!s.modelLoading &&
s.models.find((model) => model.id === s.params.checkpoint)
?.hasAudioInput === true,
);
const micLabel = micSendsAudioToModel(micTarget, modelHearsAudio)
? t("settings.voice.dictation.micRecordForModel")
: "Dictate";
// A boolean, so typing re-renders this only when a line break comes or goes.
const multiline = useAuiState(({ composer }) => composer.text.includes("\n"));
const shortcutLabels = composerShortcutLabels(
sendShortcut,
isMacPlatform(),
multiline ? "\n" : "",
);
const followUpLabel = t(
followUpBehavior === "queue"
? "promptQueue.queueButton"
: "promptQueue.steerButton",
);
const followUpTooltip = t("promptQueue.followUpTooltip", {
action: followUpLabel,
send: shortcutLabels.send,
opposite: shortcutLabels.opposite,
});
const queueEntry = usePromptQueueUI((s) =>
findPromptQueueEntry(s, queueThreadIds),
);
const isQueueRunning = Boolean(queueEntry);
const activeThreadId = useChatRuntimeStore((state) => state.activeThreadId);
const threadRemoteId = useAuiState(
({ threadListItem }) => threadListItem.remoteId,
);
// Id and status, not the run: run identity changes on every streamed research delta.
const activeResearchRunId = useResearchRunStore((state) =>
activeThreadId ? state.latestRunByThreadId[activeThreadId] : undefined,
);
const activeResearchRunStatus = useResearchRunStore((state) => {
const runId = activeThreadId
? state.latestRunByThreadId[activeThreadId]
: undefined;
return runId ? state.sessions[runId]?.run.status : undefined;
});
const isResearchActive = Boolean(
activeResearchRunStatus &&
!["completed", "failed", "cancelled"].includes(activeResearchRunStatus),
);
const [stoppingResearchRunId, setStoppingResearchRunId] = useState<
string | null
>(null);
const stoppingResearchRunIdRef = useRef<string | null>(null);
const researchStopping = Boolean(
activeResearchRunStatus &&
(activeResearchRunStatus === "cancelling" ||
(activeResearchRunId !== undefined &&
stoppingResearchRunId === activeResearchRunId)),
);
useEffect(() => {
if (
!isResearchActive ||
(stoppingResearchRunIdRef.current &&
stoppingResearchRunIdRef.current !== activeResearchRunId)
) {
stoppingResearchRunIdRef.current = null;
setStoppingResearchRunId(null);
}
}, [activeResearchRunId, isResearchActive]);
const stop = () => {
if (isResearchActive && activeResearchRunId) {
if (
activeResearchRunStatus === "cancelling" ||
stoppingResearchRunIdRef.current === activeResearchRunId
) {
return;
}
if (isQueueRunning) onStopClick?.();
stoppingResearchRunIdRef.current = activeResearchRunId;
setStoppingResearchRunId(activeResearchRunId);
void cancelResearchRun(activeResearchRunId)
.then((run) => ingestResearchUpdate(run))
.catch((error) => {
stoppingResearchRunIdRef.current = null;
setStoppingResearchRunId(null);
toast.error("Could not stop research", {
description: error instanceof Error ? error.message : undefined,
});
});
return;
}
if (isQueueRunning) onStopClick?.();
// A reply replayed after a reload has no adapter run for Cancel to abort.
stopRecoveredRun(threadRemoteId);
};
const aui = useAui();
const chatActive = useChatActive();
const threadRunning = useAuiState(({ thread }) => thread.isRunning);
const controlsRef = useRef<HTMLDivElement>(null);
// Claimed only while foreground: Compare keeps this composer mounted and inert behind its own.
useShortcut(
"stopGeneration",
() => {
const research = isResearchActive;
stop();
if (research) return;
const composer = aui.composer();
if (composer.getState().canCancel) composer.cancel();
},
{
enabled: chatActive && (threadRunning || isResearchActive),
claims: () =>
controlsRef.current !== null &&
!controlsRef.current.closest('[aria-hidden="true"], [inert]'),
},
);
return (
<div
ref={controlsRef}
className="aui-composer-action-wrapper flex shrink-0 items-center gap-1.5"
>
<ReasoningToggle side={menuSide} />
<ComposerPrimitive.If dictation={false}>
{audioUpload.busy ? (
<Button
type="button"
variant="ghost"
size="sm"
className="h-9 gap-1.5 rounded-full px-2.5 text-muted-foreground"
aria-label={t("settings.voice.dictation.audioUploadCancel")}
title={t("settings.voice.dictation.audioUploadCancel")}
onClick={audioUpload.cancel}
>
<Spinner className="size-4" />
<span>{t("settings.voice.dictation.audioUploadTranscribing")}</span>
<HugeiconsIcon icon={Cancel01Icon} className="size-3.5" aria-hidden="true" />
</Button>
) : (
<TooltipIconButton
tooltip={micLabel}
aria-label={micLabel}
type="button"
variant="ghost"
className="size-9 rounded-full text-foreground"
disabled={dictationDisabled}
onClick={onDictateClick}
>
<MicIcon className="unsloth-dictate-icon size-6" />
</TooltipIconButton>
)}
</ComposerPrimitive.If>
<AuiIf
condition={({ thread }) =>
!thread.isRunning && !isQueueRunning && !isResearchActive
}
>
<ComposerPrimitive.Send asChild={true}>
<TooltipIconButton
tooltip={
pendingSend
? "Waiting for documents…"
: t("promptQueue.sendTooltip", { shortcut: shortcutLabels.send })
}
side="bottom"
type="submit"
variant="primary"
size="icon"
// Stay clickable while docs index so a click can queue; disable once a send is parked.
disabled={disabled || pendingSend}
onClick={(event) => onSendClick?.(event)}
className="aui-composer-send ml-1.5 size-9 rounded-full"
aria-label={t("promptQueue.sendLabel")}
>
{pendingSend ? (
<Spinner className="size-[calc(18px*var(--ui-space-scale,1))]" />
) : (
<ArrowUpIcon className="unsloth-send-icon aui-composer-send-icon size-[calc(21px*var(--ui-space-scale,1))] stroke-2" />
)}
</TooltipIconButton>
</ComposerPrimitive.Send>
</AuiIf>
{isQueueRunning && !isResearchActive ? (
<AuiIf condition={({ thread }) => !thread.isRunning}>
{queueEntry?.paused && queueDisabled ? (
<TooltipIconButton
tooltip="Resume queue"
side="bottom"
type="button"
variant="primary"
size="icon"
onClick={onResumeClick}
className="aui-composer-send ml-1.5 size-9 rounded-full"
aria-label="Resume queue"
>
<QueueResumeIcon className="composer-resume-glyph size-4" />
</TooltipIconButton>
) : queueEntry?.dispatched && !queueEntry.paused ? (
<Button
type="button"
variant="primary"
size="icon"
className="aui-composer-cancel ml-1.5 size-9 rounded-full"
aria-label="Stop queued message"
onClick={stop}
>
<HugeiconsIcon icon={StopIcon} className="composer-glyph-snap size-3.5 fill-current" />
</Button>
) : (
<TooltipIconButton
tooltip={followUpTooltip}
side="bottom"
type="button"
variant="primary"
size="icon"
disabled={disabled || queueDisabled}
onClick={onQueueClick}
className="aui-composer-send ml-1.5 size-9 rounded-full"
aria-label={followUpLabel}
>
<ArrowUpIcon className="unsloth-send-icon aui-composer-send-icon size-[calc(21px*var(--ui-space-scale,1))] stroke-2" />
</TooltipIconButton>
)}
</AuiIf>
) : null}
{isResearchActive ? (
<Button
type="button"
variant="primary"
size="icon"
className="aui-composer-cancel ml-1.5 size-9 rounded-full"
aria-label={researchStopping ? "Stopping research" : "Stop research"}
disabled={researchStopping}
onClick={stop}
>
{researchStopping ? (
<Spinner className="size-3.5" />
) : (
<HugeiconsIcon icon={StopIcon} className="composer-glyph-snap size-3.5 fill-current" />
)}
</Button>
) : (
<AuiIf condition={({ thread }) => thread.isRunning}>
{/* Classed so the narrow-screen rules can treat this like the
sibling send/stop buttons; it is the flex item, not the button. */}
{/* With a draft only the stop shortcut stops the reply. */}
<div className="aui-composer-run-controls ml-1.5 flex items-center gap-1.5">
{queueDisabled ? (
<ComposerPrimitive.Cancel asChild={true}>
<Button
type="button"
variant="primary"
size="icon"
className="aui-composer-cancel size-9 rounded-full"
aria-label="Stop generating"
// Cancel only ends the reply; handlePromptQueueRunState then
// dispatches the next queued prompt. stop() ends the run.
onClick={stop}
>
<HugeiconsIcon icon={StopIcon} className="composer-glyph-snap size-3.5 fill-current" />
</Button>
</ComposerPrimitive.Cancel>
) : (
<TooltipIconButton
tooltip={followUpTooltip}
side="bottom"
type="button"
variant="primary"
size="icon"
onClick={onQueueClick}
className="aui-composer-send size-9 rounded-full"
aria-label={followUpLabel}
>
<ArrowUpIcon className="unsloth-send-icon aui-composer-send-icon size-[calc(21px*var(--ui-space-scale,1))] stroke-2" />
</TooltipIconButton>
)}
</div>
</AuiIf>
)}
</div>
);
};
const MessageError: FC = () => {
const researchRunId = useResearchMessageRunId();
const researchActive = useThreadResearchActive();
return (
<MessagePrimitive.Error>
<ErrorPrimitive.Root className="aui-message-error-root mt-2 flex flex-wrap items-center gap-x-3 gap-y-2 rounded-lg bg-destructive/10 p-3 text-destructive text-sm dark:bg-destructive/5 dark:text-red-200">
<ErrorPrimitive.Message className="aui-message-error-message min-w-0 flex-1 whitespace-pre-wrap break-words" />
{!researchRunId && !researchActive && (
<ActionBarPrimitive.Reload asChild={true}>
<button
type="button"
className="btn-fill aui-message-error-retry inline-flex shrink-0 items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium transition-colors "
>
<HugeiconsIcon icon={Refresh01Icon} strokeWidth={1.75} className="size-3.5" />
Retry
</button>
</ActionBarPrimitive.Reload>
)}
</ErrorPrimitive.Root>
</MessagePrimitive.Error>
);
};
const GeneratingIndicator: FC = () => {
const show = useAuiState(
({ message }) =>
message.content.length === 0 && message.status?.type === "running",
);
if (!show) {
return null;
}
return <GeneratingStatus />;
};
// assistant-ui's empty text part (fallback off) and the next-round status, in a box owned here so React removes
// it before appending the next part: a mid-list removal restyles the whole reply (MathML UA :nth-child rules).
const PartsWithRoundTail: FC<{ children: ReactNode }> = ({ children }) => {
const tail = useAuiState(({ message }) =>
runningReplyTail(message.status?.type === "running", message.content),
);
return (
<>
{children}
{tail !== 0 && (
<div data-slot="round-tail" className="contents">
<TextMessagePartProvider text="" isRunning={true}>
<MarkdownText />
</TextMessagePartProvider>
{tail === 2 && (
<div data-slot="next-round-indicator" className="mt-2">
<GeneratingStatus />
</div>
)}
</div>
)}
</>
);
};
// Mounted only under a running reply waiting on the model, so the thread's other messages subscribe to nothing new.
const GeneratingStatus: FC = () => {
// Keyed like DiffusionCanvas: a first turn reads "__default" until the thread persists.
const threadKey =
useAuiState(({ threadListItem }) => threadListItem.remoteId) ?? "__default";
const prefill = useChatRuntimeStore(
(s) => s.liveGenerationByThreadId[threadKey]?.prefill ?? null,
);
const labelShown = useChatRuntimeStore(
(s) => s.liveGenerationByThreadId[threadKey]?.prefillShown === true,
);
// A reply can decode with nothing to show yet (a tool call being written): past the prompt, back to Working.
const decoding = useChatRuntimeStore(
(s) => s.liveGenerationByThreadId[threadKey]?.decode != null,
);
const compacting = useChatRuntimeStore(
(s) => s.liveGenerationByThreadId[threadKey]?.compacting === true,
);
const showDetails = useChatPreferencesStore((s) => s.showGenerationDetails);
const locale = useLocale();
const t = useT();
if (compacting) {
return (
<span
data-slot="compacting-progress"
className="generating-glint text-sm text-muted-foreground"
>
{t("generationStats.compactingContext")}
</span>
);
}
const percent = prefill ? prefillPercent(prefill) : null;
// Held at 100% until the first token: going back to Working... for that moment would flash too.
if (prefill === null || !labelShown || percent === null || decoding) {
return (
<span className="generating-glint text-sm text-muted-foreground">
{t("generationStats.working")}
</span>
);
}
const timeLeft = formatPrefillTimeLeft(prefill, t);
return (
<span
data-slot="prefill-progress"
className="generating-glint text-sm text-muted-foreground tabular-nums whitespace-normal!"
>
{t("generationStats.processingPrompt", { percent })}
{timeLeft ? ` · ${timeLeft}` : null}
{showDetails ? ` · ${formatPrefillDetails(prefill, t, locale)}` : null}
</span>
);
};
// Placeholder when stop fires before any visible content (e.g. mid-think).
const CancelledIndicator: FC = () => {
const show = useAuiState(
({ message }) =>
message.content.length === 0 &&
message.status?.type === "incomplete" &&
message.status?.reason === "cancelled",
);
if (!show) {
return null;
}
return (
<span className="aui-cancelled-indicator text-sm italic text-muted-foreground">
Cancelled.
</span>
);
};
function readThoughtDuration(metadata: unknown): number | undefined {
const custom = (metadata as { custom?: Record<string, unknown> } | undefined)
?.custom;
const durations = custom?.reasoningDurations;
const value = Array.isArray(durations) ? durations[0] : custom?.reasoningDuration;
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function useContinuation() {
const aui = useAui();
const messageId = useAuiState(({ message }) => message.id);
const isLast = useAuiState(({ message }) => message.isLast);
const isRunning = useAuiState(({ thread }) => thread.isRunning);
const researchRunId = useResearchMessageRunId();
const researchActive = useThreadResearchActive();
const status = useAuiState(({ message }) => message.status);
const metadata = useAuiState(({ message }) => message.metadata);
const thoughtResumable = useChatRuntimeStore((s) =>
resumesThought({
loadedIsGguf: s.loadedIsGguf,
loadedIsMlx: s.loadedIsMlx,
activeGgufVariant: s.activeGgufVariant,
activeNativePathToken: s.activeNativePathToken,
checkpoint: s.params.checkpoint,
}),
);
const managedEngine = useChatRuntimeStore(
(s) => !isExternalModelId(s.params.checkpoint) && s.loadedEngine !== "auto",
);
const partial = useAuiState(
({ message }) => readContinuationSource(message.content).partial,
);
const reasoning = useAuiState(({ message }) =>
"status" in message && message.status?.type === "running"
? ""
: readContinuationSource(message.content).reasoning,
);
// Gemini signs answer and thought parts. A continuation runs from a sibling branch,
// so both kinds of replay metadata travel with the partial.
const thoughtSignature = useAuiState(({ message }) =>
readTextThoughtSignature(message.content),
);
const messageContent = useAuiState(({ message }) =>
"status" in message && message.status?.type === "running"
? undefined
: message.content,
);
const thoughtParts = useMemo(
() => collectGeminiThoughtReplayParts(messageContent),
[messageContent],
);
const answerParts = useMemo(
() => collectGeminiAnswerReplayParts(messageContent),
[messageContent],
);
const geminiReplayTurns = useMemo(
() =>
continuationGeminiReplayTurns(metadata, {
text: partial,
...(thoughtSignature ? { thoughtSignature } : {}),
...(thoughtParts.length > 0 ? { thoughtParts } : {}),
...(answerParts.length > 0 ? { answerParts } : {}),
}),
[metadata, partial, thoughtSignature, thoughtParts, answerParts],
);
// A tool-calling turn cannot be resumed: the continuation runs as a sibling, so the
// call and its result would be missing from the outbound history. A Gemini ledger is
// independently replayable even when its signed thought produced no visible text.
const continuable = useMemo(
() =>
isContinuableContent(messageContent, {
thought: thoughtResumable,
replay: geminiReplayTurns.length > 0,
}),
[messageContent, thoughtResumable, geminiReplayTurns],
);
// Audio input re-listens to the recording and answers afresh rather than resuming,
// so continuing there would append a second answer.
const fromAudioInput = useAuiState(({ thread }) =>
Boolean(findLatestUserAudioBase64(thread.messages, false)),
);
// An audio-output model regenerates the whole clip and never reads the request.
const audioOutputModel = useChatRuntimeStore((s) => {
const activeModel = s.models.find((m) => m.id === s.params.checkpoint);
return Boolean(activeModel?.isAudio && !activeModel.hasAudioInput);
});
// Cancelled comes through status; other reasons are on metadata (survive reload) and outrank it.
const stamped = readIncompleteInfo(metadata);
const cancelled =
status?.type === "incomplete" && status?.reason === "cancelled";
const reason =
cancelled && !isProviderReportedReason(stamped?.reason)
? ("cancelled" as const)
: stamped?.reason;
const carriedReasoning = carriedThought(
{ partial, reasoning },
{ resumesThought: thoughtResumable, managedEngine },
);
const canResume =
isLast &&
!isRunning &&
!researchRunId &&
!researchActive &&
continuable &&
modeAllowsContinuation({
fromAudioInput,
audioOutputModel,
}) &&
Boolean(
partial.trim() ||
carriedReasoning.trim() ||
geminiReplayTurns.length > 0,
);
const reasoningDuration = readThoughtDuration(metadata);
// Hands the started run back, untyped: the only handle identified with THIS run.
const startContinuation = useCallback((): unknown => {
const messages = aui.thread().getState().messages;
const index = messages.findIndex((message) => message.id === messageId);
if (index < 0) {
return undefined;
}
// Sibling of the resumed turn, so the branch picker can still reach the original.
const parent = index > 0 ? messages[index - 1].id : null;
const request: ContinuationRequest = {
partial,
...(carriedReasoning ? { reasoning: carriedReasoning, reasoningDuration } : {}),
...(thoughtSignature ? { thoughtSignature } : {}),
...(thoughtParts.length > 0 ? { thoughtParts } : {}),
...(answerParts.length > 0 ? { answerParts } : {}),
...(geminiReplayTurns.length > 0 ? { geminiReplayTurns } : {}),
...providerCompactionContinuationFields(metadata),
};
const priorTiming = priorPassTiming(metadata);
if (priorTiming) request.priorTiming = priorTiming;
return aui.thread().startRun({
parentId: parent,
runConfig: {
custom: { [CONTINUATION_RUN_CONFIG_KEY]: request },
},
});
}, [
aui,
messageId,
partial,
carriedReasoning,
reasoningDuration,
thoughtSignature,
thoughtParts,
answerParts,
geminiReplayTurns,
metadata,
]);
return {
messageId,
reason,
completed: status?.type === "complete",
canResume,
resumedChars: partial.length + carriedReasoning.length,
startContinuation,
};
}
const ContinueMessageBar: FC = () => {
// Mount the full subscriptions only for the newest message to keep typing responsive.
const isLast = useAuiState(({ message }) => message.isLast);
if (!isLast) {
return null;
}
return <ContinueMessageBarForLastMessage />;
};
const ContinueMessageBarForLastMessage: FC = () => {
const aui = useAui();
const { messageId, reason, canResume, resumedChars, startContinuation } =
useContinuation();
const resumable = Boolean(reason) && canResume;
// A cut with a remedy is one resuming cannot undo, so the way out replaces the button.
const remedy = reason ? incompleteRemedy(reason) : null;
// The parent is shared by every round of one logical turn; continuations are siblings.
const parentId = useAuiState(({ thread, message }) => {
const index = thread.messages.findIndex((m) => m.id === message.id);
return index > 0 ? thread.messages[index - 1].id : null;
});
// A partial too big to fit beside the system turn makes every further round fail identically.
const truncation = useAuiState(({ message }) => {
const custom = (message.metadata as { custom?: Record<string, unknown> } | undefined)
?.custom;
return (custom?.contextTruncation ?? null) as ContextTruncation | null;
});
// Max Tokens auto-continues (bounded; see `shouldAutoContinue`). Remember WHICH message another
// tab claimed: rows mount by index, so a boolean would leak across branches at the same index.
const [heldElsewhereFor, setHeldElsewhereFor] = useState<string | null>(null);
const claimHeldElsewhere = heldElsewhereFor === messageId;
// `remoteId`, not `id`: the key the run appears under in `runningByThreadId`.
const runThreadId = useAuiState(({ threadListItem }) => threadListItem.remoteId);
const autoContinuing =
!claimHeldElsewhere &&
resumable &&
shouldAutoContinueMessage(messageId, reason, parentId, {
fits: truncation?.fits,
// Same chars/4 estimator as the backend fit, enough to spot a partial that ate the budget.
partialTokens: Math.ceil(resumedChars / 4),
promptTarget: truncation?.prompt_target,
});
useEffect(() => {
if (!autoContinuing || !parentId) {
return;
}
let mounted = true;
// Claimed in module scope under a cross-tab lock: a ref survives StrictMode replay but not a
// remount, and module scope alone does not cover a second tab.
void claimAutoContinue(messageId, runThreadId ?? "").then((claim) => {
if (claim === "started") {
// `aui.thread()` follows the selection, so check the message still exists BEFORE holding:
// a hold whose run never appears renews forever and blocks other tabs.
const stillThere = aui
.thread()
.getState()
.messages.some((message) => message.id === messageId);
if (!stillThere) {
// Give the claim back in this tab only; the lease runs out its own TTL.
forgetAutoContinue(messageId);
return;
}
// Held for as long as this thread's run generates; the bar unmounts almost at once.
holdAutoContinueRun(messageId, runThreadId);
// Started even if unmounted, and recorded BEFORE the run so an empty round spends its budget.
recordAutoContinue(parentId);
// The run's own promise is what ends the hold if this preflight is stopped.
watchAutoContinueRun(messageId, runThreadId, startContinuation());
return;
}
// `skipped` is this tab's duplicate call; the run comes from the other tab.
if (claim === "held-elsewhere" && mounted) {
setHeldElsewhereFor(messageId);
}
});
return () => {
mounted = false;
};
}, [
aui,
autoContinuing,
parentId,
messageId,
startContinuation,
runThreadId,
]);
// Newest turn only. `reason` is repeated because `resumable` is a boolean and narrows nothing.
// A remedy is owed even when nothing can be resumed.
if (!reason || (!remedy && !resumable)) {
return null;
}
if (autoContinuing) {
// The run starts this tick; showing the bar would flash an already-answered question.
return (
<div className="aui-continue-bar mt-2 flex items-center gap-2 rounded-lg border border-border/70 bg-muted/50 p-2.5 text-sm text-muted-foreground">
<Loader2Icon className="size-3.5 animate-spin" strokeWidth={1.75} />
Continuing automatically.
</div>
);
}
return (
<div className="aui-continue-bar mt-2 flex flex-wrap items-center gap-x-3 gap-y-2 rounded-lg border border-border/70 bg-muted/50 p-2.5 text-sm">
<span className="min-w-0 flex-1 text-muted-foreground">
{incompleteLabel(reason)}.{remedy ? ` ${remedy}.` : ""}
</span>
{remedy ? null : (
<Button
type="button"
size="sm"
variant="secondary"
className="shrink-0 gap-1.5 text-xs"
onClick={() => {
startContinuation();
}}
>
<QueueResumeIcon className="size-3.5" />
{/* Not bare text: as the last element the icon lost its margin to the message's reset. */}
<span>Resume</span>
</Button>
)}
</div>
);
};
const ToolGroupThenCompaction = memo<
PropsWithChildren<{ startIndex: number; endIndex: number }>
>(({ startIndex, endIndex, children }) => {
const truncation = useAuiState(({ thread, message }) => {
const marker = compactionToolCallDividers(thread.messages).get(message.id);
if (!marker) return null;
for (let index = startIndex; index <= endIndex; index += 1) {
const part = message.parts[index];
if (part?.type === "tool-call" && part.toolCallId === marker.afterToolCallId) {
return marker.truncation;
}
}
return null;
});
return (
<>
<ToolGroup startIndex={startIndex} endIndex={endIndex}>
{children}
</ToolGroup>
{truncation && (
<CompactionDivider truncation={truncation} className="my-6" />
)}
</>
);
});
ToolGroupThenCompaction.displayName = "ToolGroupThenCompaction";
const WebSearchToolUIConfirmable = withToolConfirmation(WebSearchToolUI);
const KnowledgeBaseToolUIConfirmable =
withToolConfirmation(KnowledgeBaseToolUI);
const PythonToolUIConfirmable = withToolConfirmation(PythonToolUI);
const TerminalToolUIConfirmable = withToolConfirmation(TerminalToolUI);
const CodeExecutionToolUIConfirmable =
withToolConfirmation(CodeExecutionToolUI);
const ImageGenerationToolUIConfirmable = withToolConfirmation(
ImageGenerationToolUI,
);
const VideoGenerationToolUIConfirmable = withToolConfirmation(
VideoGenerationToolUI,
);
const RenderHtmlToolUIConfirmable = withToolConfirmation(RenderHtmlToolUI);
// Read at render time, not module scope: the skill modules reach the chat barrel.
const ReadSkillToolUIConfirmable = withToolConfirmation((props) => (
<ReadSkillToolUI {...props} />
));
const ToolFallbackConfirmable = withToolConfirmation(ToolFallback);
/**
* Module scope on purpose: `MessagePrimitivePartByIndex` compares `components.tools` by
* identity, so entries here must stay referentially stable.
*/
const ASSISTANT_PART_COMPONENTS = {
Text: MarkdownText,
Reasoning: Reasoning,
ReasoningGroup: ReasoningGroup,
Source: Sources,
ToolGroup: ToolGroupThenCompaction,
tools: {
by_name: {
web_search: WebSearchToolUIConfirmable,
search_knowledge_base: KnowledgeBaseToolUIConfirmable,
read_skill: ReadSkillToolUIConfirmable,
studio_load_skill: ReadSkillToolUIConfirmable,
python: PythonToolUIConfirmable,
terminal: TerminalToolUIConfirmable,
code_execution: CodeExecutionToolUIConfirmable,
image_generation: ImageGenerationToolUIConfirmable,
generate_image: ImageGenerationToolUIConfirmable,
generate_video: VideoGenerationToolUIConfirmable,
render_html: RenderHtmlToolUIConfirmable,
},
Fallback: ToolFallbackConfirmable,
},
} as const;
// DiffusionGemma's live canvas; store-only, so the finished message keeps only the markdown.
const DiffusionCanvas: FC = () => {
const isRunning = useAuiState(
({ message }) => message.status?.type === "running",
);
// A first turn has no id, so it reads "__default", where its run files frames until persisted.
const threadKey =
useAuiState(({ threadListItem }) => threadListItem.remoteId) ?? "__default";
// Canvas exists only after diffusion_frame events; loadedIsDiffusion can lag the first frame.
const canvas = useChatRuntimeStore(
(s) => s.activeDiffusionCanvasByThreadId[threadKey],
);
if (!isRunning || !canvas) {
return null;
}
const stepLabel =
canvas.total > 0 ? `step ${canvas.step + 1}/${canvas.total}` : "denoising";
return (
<div className="aui-diffusion-canvas my-1.5 overflow-hidden rounded-lg border border-wash-20 bg-wash-3">
<div className="flex items-center gap-2 border-b border-wash-10 px-3 py-1.5 text-ui-11 font-medium text-foreground/80">
<span className="inline-block size-1.5 animate-pulse rounded-full bg-primary" />
<span>Denoising</span>
<span className="opacity-60">
block {canvas.block + 1} - {stepLabel}
</span>
</div>
<pre className="max-h-[60dvh] overflow-auto whitespace-pre-wrap px-3 py-2 font-mono text-ui-12p5 leading-relaxed text-foreground/90">
{canvas.text}
</pre>
</div>
);
};
const ResearchMessageRunIdContext = createContext<string | null>(null);
/** Edits use <THINK> and <TOOL> tags in a plain textarea while preserving tool-call metadata. */
const AssistantMessage: FC = () => {
const aui = useAui();
const focusReveal = useActionBarFocusReveal();
const replyRef = focusReveal.ref;
useEffect(() => {
if (replyRef.current) return observeReplyPaint(replyRef.current);
}, [replyRef]);
const adjustAbove = useAdjustForContentInsertedAbove();
useEffect(() => {
if (replyRef.current) return observeDistantRow(replyRef.current, adjustAbove);
}, [replyRef, adjustAbove]);
const messageId = useAuiState(({ message }) => message.id);
const messageContent = useAuiState(({ message }) =>
"status" in message && message.status?.type === "running"
? null
: message.content,
);
const metadataResearchRunId = useAuiState(({ message }) =>
getResearchRunId(message.metadata),
);
const boundResearchAssistantMessageId = useResearchRunStore((state) =>
metadataResearchRunId
? state.sessions[metadataResearchRunId]?.run?.assistantMessageId
: undefined,
);
const researchRunId =
metadataResearchRunId &&
researchReplyOwnsRun(boundResearchAssistantMessageId, messageId)
? metadataResearchRunId
: null;
const incognito = useChatRuntimeStore((s) => s.incognito);
const editingId = useChatRuntimeStore((s) => s.editingMessageId);
const setEditingId = useChatRuntimeStore((s) => s.setEditingMessageId);
const isEditing = editingId === messageId;
const textareaRef = useRef<HTMLTextAreaElement>(null);
const adjustHeight = () => {
const el = textareaRef.current;
if (el) {
el.style.height = "auto";
el.style.height = `${el.scrollHeight}px`;
}
};
useEffect(() => {
if (isEditing) setTimeout(adjustHeight, 0);
}, [isEditing]);
const handleSave = async () => {
const finalText = textareaRef.current?.value || "";
const remoteId = aui.threadListItem().getState().remoteId
|| useChatRuntimeStore.getState().activeThreadId;
if (!remoteId || remoteId === "" || remoteId === "/") {
toast.error("Save failed: No thread ID found.");
setEditingId(null);
return;
}
try {
await updateThreadMessage({
thread: {
export: () => aui.thread().export(),
import: (data) => aui.thread().import(data)
},
messageId,
remoteId,
newText: finalText,
isIncognito: incognito,
});
} catch (error) {
console.error("UI: Error during save:", error);
toast.error("Failed to save message edits.");
} finally {
setEditingId(null);
}
};
return (
<ResearchMessageRunIdContext.Provider value={researchRunId}>
<MessagePrimitive.Root
className="group/assistant-message aui-assistant-message-root relative mx-auto min-w-0 w-full max-w-(--thread-content-max-width) pt-0.5 pb-4 text-ui-15p5 [font-weight:410] tracking-[0.01em] dark:tracking-[0.02em]"
data-role="assistant"
// The message is the tab stop that lets the action bar reveal fire; a tabIndex adds no DOM node,
// and :focus-visible keeps mouse clicks unringed.
tabIndex={0}
ref={focusReveal.ref}
onFocus={focusReveal.onFocus}
onBlur={focusReveal.onBlur}
>
<WindowedMessageBody enabled={!isEditing && messageContent !== null && !researchRunId}>
<div className="aui-assistant-message-content wrap-break-word min-w-0 text-[#0f1114] dark:text-foreground leading-relaxed">
{isEditing ? (
// Same surface as a prompt's EditComposer, at the reply's full width. Bottom gap is padding:
// index.css zeroes the margin-bottom of the reply's last descendants.
<div className="aui-assistant-edit-root flex w-full flex-col overflow-hidden rounded-3xl bg-muted pb-3">
<textarea
ref={textareaRef}
defaultValue={extractTaggedText(messageContent ?? [])}
className="block min-h-14 w-full max-h-[70dvh] resize-none overflow-y-auto bg-transparent p-4 text-foreground text-sm font-[450] outline-none"
autoFocus
onInput={adjustHeight}
onKeyDown={(e) => {
e.stopPropagation();
if (isModEnter(e)) {
handleSave();
}
if (e.key === 'Escape') {
setEditingId(null); // UX: Close editor on Escape
}
}}
/>
<div className="mx-3 flex items-center gap-2 self-end">
<Button type="button" size="sm" variant="ghost" onClick={() => setEditingId(null)}>Cancel</Button>
<Button type="button" size="sm" onClick={handleSave}>Save</Button>
</div>
</div>
) : (
<>
<div className="pointer-events-none relative h-0 min-w-0">
<MessageResponseModelBadge className="absolute -top-6 left-0 max-w-[min(22rem,100%)]" />
</div>
{researchRunId ? (
<ResearchMessage />
) : (
<>
<GeneratingIndicator />
<CancelledIndicator />
<DiffusionCanvas />
<PartsWithRoundTail>
<MessagePrimitive.Parts
components={ASSISTANT_PART_COMPONENTS}
unstable_showEmptyOnNonTextEnd={false}
/>
</PartsWithRoundTail>
<SourcesGroup />
<MessageHtmlArtifacts />
<ContinueMessageBar />
</>
)}
<MessageError />
</>
)}
</div>
<div className="aui-assistant-message-footer mt-1.5 -ml-[var(--icon-btn-inset)] flex min-h-8 min-w-0 flex-wrap items-center gap-y-1">
{/* First, so the action bar mounting on hover never moves it. */}
<AssistantMessageTime />
{/* Match the row height so wrapping live text cannot move the picker. */}
<BranchPicker className="mr-0.5 h-8" />
<LiveGenerationLine />
<AssistantActionBar />
</div>
</WindowedMessageBody>
{/* Trailing stop so Shift+Tab enters the action bar; the root's onFocus mounts it. */}
<span
className="aui-assistant-reveal-sentinel"
tabIndex={0}
aria-label="Message actions"
/>
</MessagePrimitive.Root>
</ResearchMessageRunIdContext.Provider>
);
};
const COPY_RESET_MS = 2000;
/** One subscription per thread: the autohiding badges would otherwise refetch on every hover. */
const useThreadForkCounts = (): void => {
const remoteId =
useAuiState(({ threadListItem }) => threadListItem.remoteId) ?? null;
useEffect(() => {
if (!remoteId) return;
return subscribeForkCounts(remoteId, () => {});
}, [remoteId]);
};
const ForkCountBadge: FC = () => {
const remoteId =
useAuiState(({ threadListItem }) => threadListItem.remoteId) ?? null;
const messageId = useAuiState(({ message }) => message.id);
const subscribe = useCallback(
(onChange: () => void) =>
remoteId ? subscribeForkCounts(remoteId, onChange) : () => {},
[remoteId],
);
const getSnapshot = useCallback(
() => (remoteId ? forkCountFor(remoteId, messageId) : 0),
[remoteId, messageId],
);
const count = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
if (count <= 0) return null;
return (
<span
className="mx-1 inline-flex items-center gap-1 rounded-full bg-primary/10 px-1.5 py-0.5 text-ui-10 font-medium text-primary"
title={`${count} fork${count === 1 ? "" : "s"} from this message`}
>
<HugeiconsIcon icon={ForkIcon} strokeWidth={1.75} className="size-3" />
{count}
</span>
);
};
const useForkMessageAction = (messageId: string | undefined) => {
const aui = useAui();
const navigate = useNavigate();
const isRunning = useAuiState(({ thread }) => thread.isRunning);
const pending = useForkInFlight((s) => s.forking);
const setPending = useForkInFlight((s) => s.setForking);
const handleFork = async () => {
// Read the store, not the render: two handlers can run in one tick.
if (useForkInFlight.getState().forking) return;
if (!messageId) return;
const remoteId = aui.threadListItem().getState().remoteId;
if (!remoteId) {
toast.error("Cannot fork an unsaved chat");
return;
}
setPending(true);
try {
// The fork copies settings_json from the row, so flush pending setting saves first.
try {
await settleThreadScopedSettingsForCopy(remoteId);
} catch {
// The row lacks on-screen edits, so a fork now would drop them; say so instead.
toast.error("Could not fork this chat", {
description:
"Its settings could not be saved, so the fork would not match. Please retry.",
});
return;
}
const result = await forkChatThread(remoteId, {
messageId,
newThreadId: crypto.randomUUID(),
createdAt: Date.now(),
});
useChatRuntimeStore.getState().setActiveThreadId(result.thread.id);
navigate({
to: "/chat",
search: { thread: result.thread.id },
replace: false,
});
showForkCreatedToast(result.containerSnapshotWarning, result.thread.title);
} catch (error) {
console.error("Failed to fork", error);
showForkFailedToast(error);
} finally {
setPending(false);
}
};
return {
forkMessage: handleFork,
forkDisabled: isRunning || pending,
};
};
/** The fork chord's registration, mounted once per thread outside the rows: the window unmounts
* the last row when the reader scrolls away, and autohidden action bars drop theirs. */
const ForkChatShortcut: FC = () => {
const lastId = useAuiState(({ thread }) => thread.messages.at(-1)?.id);
const { forkMessage, forkDisabled } = useForkMessageAction(lastId);
const chatActive = useChatActive();
// Compare mounts a thread per pane and the chord goes to whichever registered first.
const inComparePane = useInComparePane();
useShortcut(
"forkChat",
() => {
// `chatActive` is the visible tab, not the foreground; a dialog over Chat must not fork.
if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return;
void forkMessage();
},
{ enabled: lastId !== undefined && chatActive && !inComparePane && !forkDisabled },
);
return null;
};
const ForkMessageButton: FC = () => {
const messageId = useAuiState(({ message }) => message.id);
const { forkMessage, forkDisabled } = useForkMessageAction(messageId);
return (
<TooltipIconButton
tooltip="Fork from here"
disabled={forkDisabled}
onClick={forkMessage}
>
<HugeiconsIcon icon={ForkIcon} strokeWidth={1.75} className="size-[calc(var(--icon-size)*0.97)]" />
</TooltipIconButton>
);
};
const getResearchRunId = (metadata: unknown): string | null => {
const custom = (
metadata as
| {
custom?: {
researchRunId?: unknown;
researchRun?: { id?: unknown };
};
}
| undefined
)?.custom;
const runId = custom?.researchRunId ?? custom?.researchRun?.id;
return typeof runId === "string" ? runId : null;
};
const useResearchMessageRunId = () => {
return useContext(ResearchMessageRunIdContext);
};
// Boolean(), not `!== null`: an empty id must not hide a message's edit and delete controls.
const hasResearchRunId = (metadata: unknown): boolean =>
Boolean(getResearchRunId(metadata));
const useOwnsResearchMessage = () => {
const aui = useAui();
const messageId = useAuiState(({ message }) => message.id);
// Select the ANSWER, not the message array, or every action bar re-renders on each change.
return useAuiState(({ thread }) => {
if (thread.messages.length === 0) {
return false;
}
return researchReplyOwners(
thread.messages,
() => aui.thread().export().messages,
hasResearchRunId,
).has(messageId);
});
};
// After a reload `thread.isRunning` is false while durable research runs; gate on this too.
const useThreadResearchActive = (): boolean => {
const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
return useResearchRunStore((state) => {
const runId = activeThreadId
? state.latestRunByThreadId[activeThreadId]
: undefined;
const run = runId ? state.sessions[runId]?.run : undefined;
return Boolean(
run && !["completed", "failed", "cancelled"].includes(run.status),
);
});
};
function useDeleteMessage() {
const aui = useAui();
const messageId = useAuiState(({ message }) => message.id);
const isRunning = useAuiState(({ thread }) => thread.isRunning);
const researchRunId = useResearchMessageRunId();
const ownsResearchMessage = useOwnsResearchMessage();
const handleDelete = async () => {
const thread = aui.thread();
// Deleting unmounts the only Stop reading control; stop read-aloud first (guarded, it may throw).
const speakingId = thread.getState().speech?.messageId;
if (speakingId) {
const { messages } = thread.export();
const target = messages.find(({ message }) => message.id === messageId);
const removed = new Set<string>([messageId]);
if (target?.message.role === "user") {
for (const { parentId, message } of messages) {
if (parentId === messageId && message.role === "assistant") {
removed.add(message.id);
}
}
}
if (removed.has(speakingId)) {
try {
thread.stopSpeaking();
} catch {
// Playback ended between reading the state and stopping it.
}
}
}
const remoteId = aui.threadListItem().getState().remoteId;
try {
await deleteThreadMessage({
thread: {
export: () => thread.export(),
import: (data) => thread.import(data),
},
messageId,
remoteId,
});
if (remoteId) {
useBookmarkedTurnsStore.getState().forgetTurns(remoteId, [messageId]);
}
} catch (error) {
console.error("Failed to delete message", error);
toast.error("Failed to delete message");
}
};
return { handleDelete, isRunning, hidden: Boolean(researchRunId || ownsResearchMessage) };
}
const DeleteMessageButton: FC = () => {
const { handleDelete, isRunning, hidden } = useDeleteMessage();
if (hidden) {
return null;
}
return (
<TooltipIconButton
tooltip="Delete"
disabled={isRunning}
onClick={() => void handleDelete()}
className="hover:!text-destructive"
>
<HugeiconsIcon icon={TrashIcon} strokeWidth={1.75} className="size-icon" />
</TooltipIconButton>
);
};
// A thin diagonal reads small at the shared size.
const EDIT_GLYPH = "size-[calc(var(--icon-size)*1.049)]";
const MORE_MENU_CONTENT_CLASS =
"aui-action-bar-more-content dropdown-surface z-50 min-w-32 max-h-(--radix-dropdown-menu-content-available-height) flex flex-col overflow-hidden rounded-xl bg-popover px-[calc(8px*var(--ui-space-scale,1))] py-2 text-popover-foreground shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)]";
const MORE_MENU_ITEM_CLASS =
"aui-action-bar-more-item flex cursor-pointer select-none items-center gap-2 rounded-md px-3 py-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50";
// Loaded on first use: the dialog is not part of the first screen.
const LazyRewindDialog = lazy(() =>
import("@/components/assistant-ui/rewind-dialog").then((module) => ({
default: module.RewindDialog,
})),
);
const RewindDialogMount: FC = () => {
const requested = useRewindDialogStore((s) => s.request !== null);
const [loaded, setLoaded] = useState(false);
useEffect(() => {
if (requested) setLoaded(true);
}, [requested]);
// Stays mounted once loaded so closing keeps its animation.
return requested || loaded ? (
<Suspense fallback={null}>
<LazyRewindDialog />
</Suspense>
) : null;
};
const RewindMessageButton: FC = () => {
const aui = useAui();
const t = useT();
const messageId = useAuiState(({ message }) => message.id);
const isRunning = useAuiState(({ thread }) => thread.isRunning);
return (
<TooltipIconButton
tooltip={t("rewind.title")}
disabled={isRunning}
onClick={() =>
useRewindDialogStore.getState().openRewind({
threadKey: aui.threadListItem().getState().id,
messageId,
})
}
>
<HugeiconsIcon icon={UndoIcon} strokeWidth={1.75} className="size-icon" />
</TooltipIconButton>
);
};
const CopyButton: FC = () => {
const aui = useAui();
const [copied, setCopied] = useState(false);
const resetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const handleCopy = async () => {
// getCopyText reads content only, and a long paste sits in an attachment.
const pasted = attachmentsPastedText(aui.message().getState().attachments);
// Strip image tokens or the clipboard gets `[[img:0123456789ab]]` where the picture was.
const text = [stripSearchImageTokens(aui.message().getCopyText()), pasted]
.filter((part) => part.length > 0)
.join("\n\n");
if (await copyToClipboard(text)) {
setCopied(true);
if (resetTimeoutRef.current) {
clearTimeout(resetTimeoutRef.current);
}
resetTimeoutRef.current = setTimeout(() => {
setCopied(false);
resetTimeoutRef.current = null;
}, COPY_RESET_MS);
}
};
return (
<TooltipIconButton tooltip="Copy" onClick={handleCopy}>
<HugeiconsIcon
icon={copied ? Tick02Icon : Copy01Icon}
strokeWidth={1.75}
className="size-icon"
/>
</TooltipIconButton>
);
};
const EditAssistantMessageButton: FC = () => {
const messageId = useAuiState(({ message }) => message.id);
const researchRunId = useResearchMessageRunId();
const isRunning = useAuiState(({ thread }) => thread.isRunning);
const researchActive = useThreadResearchActive();
const setEditingId = useChatRuntimeStore((s) => s.setEditingMessageId);
if (researchRunId) return null;
return (
<TooltipIconButton
tooltip="Edit response"
disabled={isRunning || researchActive}
onClick={() => setEditingId(messageId)}
>
<HugeiconsIcon
icon={Edit03Icon}
strokeWidth={1.75}
className={EDIT_GLYPH}
/>
</TooltipIconButton>
);
};
const ContinueResponseMenuItem: FC = () => {
const isLast = useAuiState(({ message }) => message.isLast);
if (!isLast) {
return null;
}
return <ContinueResponseMenuItemForLastMessage />;
};
const ContinueResponseMenuItemForLastMessage: FC = () => {
const { messageId, reason, completed, canResume, startContinuation } =
useContinuation();
const editing = useChatRuntimeStore((s) => s.editingMessageId === messageId);
// The sibling carries no citations, and a continuation restarts their [N] numbering.
const cited = useAuiState(({ message }) =>
message.content.some((part) => part.type === "source"),
);
if (!completed || reason || !canResume || editing || cited) {
return null;
}
return (
<ActionBarMorePrimitive.Item
onSelect={() => {
startContinuation();
}}
className="aui-action-bar-more-item flex cursor-pointer select-none items-center gap-2 rounded-md px-3 py-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
>
<HugeiconsIcon icon={ContinueArrowIcon} strokeWidth={1.75} className="size-icon" />
Continue response
</ActionBarMorePrimitive.Item>
);
};
const EditAssistantMessageMenuItem: FC = () => {
const messageId = useAuiState(({ message }) => message.id);
const researchRunId = useResearchMessageRunId();
const isRunning = useAuiState(({ thread }) => thread.isRunning);
const researchActive = useThreadResearchActive();
const setEditingId = useChatRuntimeStore((s) => s.setEditingMessageId);
if (researchRunId) return null;
return (
<ActionBarMorePrimitive.Item
disabled={isRunning || researchActive}
onSelect={() => setEditingId(messageId)}
className="aui-action-bar-more-item flex cursor-pointer select-none items-center gap-2 rounded-md px-3 py-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
>
<HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />
Edit response
</ActionBarMorePrimitive.Item>
);
};
async function exportMessageMarkdown(content: string): Promise<void> {
try {
await downloadFile(
// The tokens are renderer markup, so a saved answer must not carry them (as copy/export).
stripSearchImageTokens(content),
`message-${Date.now()}.md`,
"text/markdown",
);
} catch (error) {
if (!isDownloadCancelled(error)) {
toast.error("Could not save Markdown export.", {
description: error instanceof Error ? error.message : String(error),
});
}
}
}
const AssistantActionBar: FC = () => {
const aui = useAui();
const moreMenuTriggerRef = useRef<HTMLButtonElement>(null);
// Not built on DropdownMenuContent, so clear the titlebar and cap the height here.
const moreMenuCollisionPadding = useWindowChromeCollisionPadding(undefined);
const researchRunId = useResearchMessageRunId();
const researchActive = useThreadResearchActive();
const activeProjectId = useChatRuntimeStore((s) => s.activeProjectId);
const [detailsOpen, setDetailsOpen] = useState(false);
const ttsEnabled = useVoiceSettingsStore((s) => s.ttsEnabled);
// On by default; off moves Edit response into the More menu.
const inlineEdit = useChatPreferencesStore((s) => s.showInlineEditResponse);
// hideWhenRunning is thread-level; keep the bar while speaking, it holds the only Stop control.
const speaking = useAuiState(({ message }) => message.speech != null);
return (
<>
<ActionBarPrimitive.Root
hideWhenRunning={!speaking}
// Autohide drops each bar's ~8 tooltip subscriptions; "not-last" keeps the newest reply's bar
// tabbable, useActionBarFocusReveal remounts others on focus, "never" while speaking.
autohide={speaking ? "never" : "not-last"}
className="aui-assistant-action-bar-root col-start-3 row-start-2 flex min-w-0 flex-wrap items-center gap-1 text-chat-icon-fg [&_button:not([data-slot=message-timing-trigger])]:size-8 [&_button]:!rounded-full [&_button:hover]:bg-chat-icon-bg-hover [&_button:hover]:text-chat-icon-fg-hover"
>
<CopyButton />
{inlineEdit && <EditAssistantMessageButton />}
{!researchRunId && !researchActive && (
<ActionBarPrimitive.Reload asChild={true}>
<TooltipIconButton tooltip="Refresh">
<RefreshGlyph strokeWidth={1.75} className="size-icon" />
</TooltipIconButton>
</ActionBarPrimitive.Reload>
)}
{ttsEnabled && (
<MessagePrimitive.If speaking={false}>
<ActionBarPrimitive.Speak asChild={true}>
<TooltipIconButton tooltip="Read aloud" aria-label="Read aloud">
<HugeiconsIcon icon={ReadAloudIcon} strokeWidth={1.75} className="size-icon" />
</TooltipIconButton>
</ActionBarPrimitive.Speak>
</MessagePrimitive.If>
)}
{/* Not gated on ttsEnabled: disabling it mid-read must not remove the only stop control. */}
<MessagePrimitive.If speaking={true}>
<ActionBarPrimitive.StopSpeaking asChild={true}>
<TooltipIconButton
tooltip="Stop reading"
aria-label="Stop reading"
className="text-destructive"
>
<HugeiconsIcon icon={VolumeMute02Icon} strokeWidth={1.75} className="size-icon" />
</TooltipIconButton>
</ActionBarPrimitive.StopSpeaking>
</MessagePrimitive.If>
<ForkCountBadge />
<ForkMessageButton />
<DeleteMessageButton />
{/* Non-modal: a modal Radix menu writes `pointer-events: none` on <body>, and
that is an INHERITED property, so every open invalidates style for the whole
document. On a long thread that recalc is the bulk of the open+close cost. */}
<ActionBarMorePrimitive.Root modal={false}>
<ActionBarMorePrimitive.Trigger asChild={true}>
<TooltipIconButton
ref={moreMenuTriggerRef}
tooltip="More"
className="data-[state=open]:bg-accent"
>
<HugeiconsIcon icon={MoreHorizontalIcon} strokeWidth={1.75} className="size-icon" />
</TooltipIconButton>
</ActionBarMorePrimitive.Trigger>
<ActionBarMorePrimitive.Content
side="bottom"
align="start"
collisionPadding={moreMenuCollisionPadding}
onCloseAutoFocus={(e) => e.preventDefault()}
className={MORE_MENU_CONTENT_CLASS}
>
{/* Scroll an inner viewport: a scrollbar on the rounded surface squares its corners. */}
<div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto">
{/* Keep the click that dismisses the menu off the bar's buttons. */}
<MenuDismissGuard triggerRef={moreMenuTriggerRef} />
<MessageMenuTime onShowDetails={() => setDetailsOpen(true)} />
<ContinueResponseMenuItem />
{!inlineEdit && <EditAssistantMessageMenuItem />}
<ActionBarPrimitive.ExportMarkdown
asChild={true}
onExport={exportMessageMarkdown}
>
<ActionBarMorePrimitive.Item className="aui-action-bar-more-item flex cursor-pointer select-none items-center gap-2 rounded-md px-3 py-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground">
<HugeiconsIcon
icon={Download01Icon}
strokeWidth={1.75}
className="size-icon"
/>
Export as markdown
</ActionBarMorePrimitive.Item>
</ActionBarPrimitive.ExportMarkdown>
{activeProjectId && (
<ActionBarMorePrimitive.Item
onSelect={() => {
// Not getCopyText, which drops reasoning, tools and citations. Stripped: saved
// tokens would teach the model ids that resolve to nothing.
const text = stripSearchImageTokens(
replySourceMarkdown(
aui.message().getState().content,
toolResultModelText,
),
);
if (!text.trim()) {
toast.info("No content to save.");
return;
}
const state = aui.threadListItem().getState();
// The title is the whole chat's, so mark the reply apart.
const title = state.title ? `${state.title} - reply` : "reply";
// activeProjectId can lag a thread switch; resolve the destination from this thread.
const remoteId =
state.remoteId ||
useChatRuntimeStore.getState().activeThreadId;
void (async () => {
const thread = remoteId
? await getStoredChatThread(remoteId).catch(() => null)
: null;
if (!thread?.projectId) {
toast.info("This chat isn't in a project.");
return;
}
await saveMarkdownAsProjectSource(
thread.projectId,
text,
title,
);
})();
}}
className="aui-action-bar-more-item flex cursor-pointer select-none items-center gap-2 rounded-md px-3 py-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground"
>
<HugeiconsIcon
icon={FolderAttachmentIcon}
strokeWidth={1.75}
className="size-icon"
/>
Save to project sources
</ActionBarMorePrimitive.Item>
)}
<BookmarkTurnMenuItem className="aui-action-bar-more-item flex cursor-pointer select-none items-center gap-2 rounded-md px-3 py-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground" />
</div>
</ActionBarMorePrimitive.Content>
</ActionBarMorePrimitive.Root>
<MessageTiming side="top" className="h-8 px-2" />
</ActionBarPrimitive.Root>
<MessageResponseDetailsSheet
open={detailsOpen}
onOpenChange={setDetailsOpen}
/>
</>
);
};
const UserMessageAudio: FC = () => {
const audioName = useAuiState(({ message }) =>
sentAudioNames.get(message.id),
);
if (!audioName) {
return null;
}
return (
<div className="col-start-2 flex justify-end">
<div className="flex items-center gap-2 rounded-full border border-[color-mix(in_oklab,var(--foreground)_calc(20%*var(--contrast-edge-gain,1)),transparent)] bg-muted px-3 py-1.5 text-xs">
<HugeiconsIcon icon={AiSpeechIcon} className="size-3.5 text-muted-foreground" />
<span className="max-w-48 truncate">{audioName}</span>
</div>
</div>
);
};
const SCHEDULED_REPLY_KEY = "scheduled-task-replies";
function scheduledTaskIdOf(custom: unknown): string | null {
const source = (custom as { scheduledTask?: { taskId?: unknown } } | undefined)?.scheduledTask;
return typeof source?.taskId === "string" ? source.taskId : null;
}
/** "Sent by scheduled task" over a task run's prompt; the reply carries the mark too, surviving rewrites. */
const ScheduledTaskSource: FC = () => {
const t = useT();
const navigate = useNavigate();
const taskId = useAuiState(({ thread, message }) => {
const own = scheduledTaskIdOf(message.metadata?.custom);
if (own) return own;
// One pass per messages snapshot, not a search per prompt per streamed token.
const byPrompt = memoOnArrayByKey(thread.messages, SCHEDULED_REPLY_KEY, () => {
const map = new Map<string, string>();
thread.messages.forEach((entry, index) => {
const reply = thread.messages[index + 1];
const replyTask =
reply?.role === "assistant" ? scheduledTaskIdOf(reply.metadata?.custom) : null;
if (replyTask) map.set(entry.id, replyTask);
});
return map;
});
return byPrompt.get(message.id) ?? null;
});
if (!taskId) return null;
return (
<button
type="button"
onClick={() => void navigate({ to: "/tasks", search: { edit: taskId } })}
className="inline-flex cursor-pointer items-center gap-1.5 rounded-md text-ui-13 text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
>
<HugeiconsIcon icon={Clock01Icon} strokeWidth={1.75} className="size-3.5" />
{t("scheduledTasks.sentBy")}
</button>
);
};
/** Prompts already shown: the thread window remounts rows, and a remount must not replay the arrival. */
const shownPrompts = new Set<string>();
const UserMessage: FC = () => {
const focusReveal = useActionBarFocusReveal();
const id = useAuiState(({ message }) => message.id);
const [arriving] = useState(() => !shownPrompts.has(id));
useEffect(() => {
shownPrompts.add(id);
}, [id]);
const promptRef = focusReveal.ref;
const adjustAbove = useAdjustForContentInsertedAbove();
useEffect(() => {
if (promptRef.current) return observeDistantRow(promptRef.current, adjustAbove);
}, [promptRef, adjustAbove]);
// Attachments alone (annotations, images) get no empty bubble under them.
const hasContent = useAuiState(({ message }) =>
message.content.some((part) => part.type !== "text" || part.text.trim() !== ""),
);
return (
<MessagePrimitive.Root
className={cn(
"aui-user-message-root mx-auto flex w-full max-w-(--thread-content-max-width) flex-col items-end gap-y-2 pt-6 pb-4 text-ui-15p5 [font-weight:410] tracking-[0.01em] dark:tracking-[0.02em]",
arriving && "fade-in slide-in-from-bottom-1 animate-in duration-150",
)}
data-role="user"
tabIndex={0}
{...focusReveal}
>
<WindowedMessageBody>
<ScheduledTaskSource />
<UserMessageAttachments />
<UserMessageAudio />
<div className="aui-user-message-content-wrapper flex w-full min-w-0 flex-col items-end">
{hasContent ? (
<div
dir="auto"
className="aui-user-message-content wrap-break-word [&_p]:whitespace-pre-wrap! w-fit max-w-[80%] rounded-xl bg-[#f5f5f5] px-4 py-2.5 text-[#0f1114] dark:text-foreground dark:bg-card">
<MessagePrimitive.Parts />
</div>
) : null}
<UserMessageFooter>
<UserActionBar />
<BranchPicker className="aui-user-branch-picker ml-[calc(6px*var(--ui-space-scale,1))] shrink-0" />
</UserMessageFooter>
</div>
</WindowedMessageBody>
{/* Reverse traversal reaches a trailing stop before the root. Focusing it
mounts the autohidden controls, so the next Shift+Tab enters its controls
instead of skipping the action bar and leaving the message. */}
<span
className="aui-user-reveal-sentinel"
tabIndex={0}
aria-label="Message actions"
/>
</MessagePrimitive.Root>
);
};
const UserActionBar: FC = () => {
const ownsResearchMessage = useOwnsResearchMessage();
const researchActive = useThreadResearchActive();
return (
<UserMessageActionBar>
<CopyButton />
{!ownsResearchMessage && !researchActive && (
<ActionBarPrimitive.Edit asChild={true}>
<TooltipIconButton tooltip="Edit" className="aui-user-action-edit">
<HugeiconsIcon
icon={Edit03Icon}
strokeWidth={1.75}
className={EDIT_GLYPH}
/>
</TooltipIconButton>
</ActionBarPrimitive.Edit>
)}
<RewindMessageButton />
<ForkCountBadge />
<DeleteMessageButton />
<UserMoreMenu />
</UserMessageActionBar>
);
};
const UserMoreMenu: FC = () => {
const triggerRef = useRef<HTMLButtonElement>(null);
const collisionPadding = useWindowChromeCollisionPadding(undefined);
const messageId = useAuiState(({ message }) => message.id);
const { forkMessage, forkDisabled } = useForkMessageAction(messageId);
return (
// Non-modal: see AssistantActionBar.
<ActionBarMorePrimitive.Root modal={false}>
<ActionBarMorePrimitive.Trigger asChild={true}>
<TooltipIconButton
ref={triggerRef}
tooltip="More"
className="data-[state=open]:bg-accent"
>
<HugeiconsIcon icon={MoreHorizontalIcon} strokeWidth={1.75} className="size-icon" />
</TooltipIconButton>
</ActionBarMorePrimitive.Trigger>
<ActionBarMorePrimitive.Content
side="bottom"
align="end"
collisionPadding={collisionPadding}
onCloseAutoFocus={(e) => e.preventDefault()}
className={MORE_MENU_CONTENT_CLASS}
>
<div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto">
<MenuDismissGuard triggerRef={triggerRef} />
<ActionBarMorePrimitive.Item
disabled={forkDisabled}
onSelect={() => void forkMessage()}
className={MORE_MENU_ITEM_CLASS}
>
<HugeiconsIcon icon={ForkIcon} strokeWidth={1.75} className="size-[calc(var(--icon-size)*0.97)]" />
Fork from here
</ActionBarMorePrimitive.Item>
<BookmarkTurnMenuItem ownTurn={true} className={MORE_MENU_ITEM_CLASS} />
</div>
</ActionBarMorePrimitive.Content>
</ActionBarMorePrimitive.Root>
);
};
const EditComposer: FC = () => {
const aui = useAui();
const sendShortcut = useChatPreferencesStore((s) => s.sendShortcut);
const editMultiline = useAuiState(({ composer }) => composer.text.includes("\n"));
const { inputProps, isComposingRef } = useImeComposerInputHandlers();
const resendAfterCancelRef = useRef(false);
const researchActive = useThreadResearchActive();
// send() drops an empty composer, e.g. a paste-only message whose chip was removed.
const editEmpty = useAuiState(({ composer }) => composer.isEmpty);
useAuiEvent("thread.runEnd", () => {
if (!resendAfterCancelRef.current) {
return;
}
resendAfterCancelRef.current = false;
aui.composer().send({ startRun: true });
});
// ComposerPrimitive.Root's Enter handler sends without startRun, dropping an unchanged edit.
const submitEdit = useCallback(() => {
if (isComposingRef.current) return;
if (aui.thread().getState().isRunning) {
resendAfterCancelRef.current = true;
aui.thread().cancelRun();
return;
}
aui.composer().send({ startRun: true });
}, [aui, isComposingRef]);
return (
// Top gap and type match UserMessage, so the text stays near the prompt's line.
<MessagePrimitive.Root className="aui-edit-composer-wrapper mx-auto flex w-full max-w-(--thread-content-max-width) flex-col pt-6 pb-4 text-ui-15p5 [font-weight:410] tracking-[0.01em] dark:tracking-[0.02em]">
<ComposerPrimitive.Root
className="aui-edit-composer-root flex w-full flex-col rounded-xl bg-muted"
onSubmit={(event) => {
event.preventDefault();
submitEdit();
}}
>
<ComposerAttachments className="mb-0 px-4 pt-4" />
<ComposerPrimitive.Input
submitMode={
effectiveSendShortcut(sendShortcut, editMultiline ? "\n" : "") === "mod-enter"
? "ctrlEnter"
: "enter"
}
minRows={2}
className="aui-edit-composer-input w-full resize-none bg-transparent px-5 py-3.5 text-foreground outline-none"
autoFocus={true}
dir="auto"
{...inputProps}
/>
<div className="aui-edit-composer-footer mx-4 mb-4 flex items-center gap-2 self-end">
<ComposerPrimitive.Cancel asChild={true}>
<Button type="button" variant="outline">
Cancel
</Button>
</ComposerPrimitive.Cancel>
<Button
type="submit"
variant="dark"
disabled={researchActive || editEmpty}
>
Send
</Button>
</div>
</ComposerPrimitive.Root>
</MessagePrimitive.Root>
);
};
const BranchPicker: FC<BranchPickerPrimitive.Root.Props> = ({
className,
...rest
}) => {
return (
<BranchPickerPrimitive.Root
hideWhenSingleBranch={true}
className={cn(
"aui-branch-picker-root inline-flex items-center text-chat-icon-fg text-ui-13",
className,
)}
{...rest}
>
<BranchPickerPrimitive.Previous asChild={true}>
<button
type="button"
aria-label="Previous"
className="aui-branch-chevron-btn"
>
<HugeiconsIcon icon={BranchPrevIcon} strokeWidth={1.75} className="size-4" />
</button>
</BranchPickerPrimitive.Previous>
<span className="aui-branch-picker-state text-ui-13 leading-none tabular-nums">
<BranchPickerPrimitive.Number />/<BranchPickerPrimitive.Count />
</span>
<BranchPickerPrimitive.Next asChild={true}>
<button
type="button"
aria-label="Next"
className="aui-branch-chevron-btn"
>
<HugeiconsIcon icon={BranchNextIcon} strokeWidth={1.75} className="size-4" />
</button>
</BranchPickerPrimitive.Next>
</BranchPickerPrimitive.Root>
);
};