Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

51.2 KB
Raw Blame
import { directMessageSent, roomMessageSent } from "@/lib/product-events";
import { TeamAudienceLabel } from "./TeamSideSwitch";
import { useComposerDictation } from "@/lib/use-composer-dictation"; import { DismissWarning } from "./DismissWarning"; import { composerOrderStyle, useComposerLayout } from "@/lib/composer-layout"; import { isPlaceId } from "@/lib/place-chat";
import { ComposerForkError, useComposerFork } from "./ComposerFork";
import { isNewChatThread, newChatThreadId } from "@/state/new-chat";
import { useCallback, useEffect, useMemo, useRef, useState, type SetStateAction } from "react";
import { Mic, Square } from "lucide-react";
import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { useStoreRef } from "@/state/store-ref"; import { sameDrawnBots } from "@/lib/drawn-bots";
import { visibleMessages, currentTaskBot, type Action, type Bot, type Group, type InstanceInfo, type Message } from "@/state/store";
import { cn } from "@/lib/cn"; import { useComposerFocusHandlers } from "@/lib/composer-focus"; import { tapHaptic } from "@/lib/haptics";
import { PHONE_LAYOUT, useMediaQuery } from "@/lib/use-media-query";
import { useMenuMotion } from "./MenuMotion";
import { ELEVATED_CARD, ELEVATED_COMPOSER, ELEVATED_FLOAT } from "./elevated";
import { uploadDraftImage } from "@/lib/composer-uploads";
import { intakeFilesWithNotice } from "@/lib/attach-notice";
import { activeLocale, t } from "@/lib/i18n";
import { useAdvancedMode } from "@/lib/interface-mode";
import { isDictationToggle, isMacPlatform } from "@/lib/keyboard-shortcuts";
import { imeComposing, sendKeyLabel, sendsMessage, useSendKey } from "@/lib/send-key";
import { alternateSend, alternateSendLabel, useFollowUpDefault } from "@/lib/follow-up"; import { followUpChoices, resolveFollowUp, type FollowUp } from "../../shared/follow-up";
import {
  draftRevision,
  appendDraftAttachments,
  changeDraftAttachmentPending,
  forgetFailedComposerSend,
  markDraftEdited,
  prependComposerDraft,
  recoverFailedComposerSend,
  rememberFailedComposerSend,
  restoredSendId,
  restoredRequestText,
  useComposerDraft,
  useComposerChannelMode,
  useDraftAttachmentPending,
  useFailedComposerSends,
  type ComposerSendSnapshot,
  type FailedComposerSend,
} from "@/lib/drafts";
import { DEVS_CHOICE, MentionMenu, teammateChoices, type MentionChoice } from "./MentionMenu"; import { useTeammates } from "@/state/team-people"; import { hiddenFromSidebar, useViewerEmail } from "@/lib/default-bot"; import { useMayAct } from "./SharedQueueLine";
import { SlashCommandMenu } from "./SlashCommandMenu"; import { ComposerFailedSends } from "./ComposerFailedSends";
import { MentionTextarea } from "./MentionTextarea"; import { useSuggestedReply } from "./use-suggested-reply"; import { SUGGESTION_HINT_ID, SuggestedReplyGhost } from "./SuggestedReplyGhost";
import { ComposerAttachments, localPathForFile, pathForFile } from "./ComposerAttachments";
import { PointedChips } from "./app/PointedChips"; import { SetupRequestChip, setupRequestPlaceholder } from "./SetupOffer";
import { takePointedChips } from "@/lib/pointed-chips";
import { openPageFor } from "@/lib/open-page";
import { splitTranscriptCitations, type CitationAttachment } from "@/lib/citations";
import { ComposerAdvancedTools } from "./ComposerAdvancedTools";
import { approvalModeFor } from "../../shared/approval-mode";
import { useOnCall } from "@/lib/call";
import { isLiveCallRunning, useLiveMedia } from "@/lib/live-call-media";
import {
  appendPastedText,
  clipboardFilesToAttach,
  clipboardHasImages,
  clipboardImageFiles,
  composeMessage,
  dataContextFor,
  discardUnsentUpload,
  composerShouldRefocus,
  composerTakesFocusOnOpen,
  imageBytesLeft,
  imageSlotsLeft,
  imagesThatFit,
  replyTargetTakesFocus,
  isLongPaste,
  pasteAttachment,
  releaseAttachmentImagePreview,
  type Attachment,
  type PasteAttachment,
} from "@/lib/composer-attachments";
import { goalCoordinatorForComposer, jevRoomRoutingOn, openTaskWorking, roomRouteForComposer } from "@/lib/group-routing";
import { composerForkOwner, composerPlaceholder, sendLabels, SIMPLE_COMPOSER, SIMPLE_CONTROL, slotColors } from "./composer-simple"; import { ComposerSendButton } from "./ComposerSendButton"; import { ComposerContextMenu } from "./ComposerContextMenu";
import { PendingApprovalActions, PendingApprovalPanel, pendingApprovals } from "./PendingApproval";
import { CallButton } from "./CallView";
import { GroupCallButton } from "./GroupCallView";
import { ApprovalChip, ComposerPlusMenu, GoalToggle } from "./ComposerPlusMenu";
import { PlaceMark } from "./PlaceChip";
import type { Place } from "@/lib/place";
import { PhonePlus } from "./PhonePlus";
import { useThreadApproval } from "./thread-approval";
import { useTallPill } from "./composer-wrap";
import { ComposerReplyStrip } from "./ReplyQuote";
import { escapeCancelsReply } from "@/lib/replies";
import { useThreadRefs } from "./ThreadRefs";
import {
  QueuedComposerMessages,
  composerCanSteerQueuedMessages,
  doubleEnterSteerWindowExpiresAt,
  doubleEnterSteersQueue,
  roomSteersQueued,
} from "./ComposerQueuedMessages";
import { skillAuthoringEnabled } from "@/lib/feature-flags";
import { departmentChoices, mentionChoicesForQuery, mentionQueryAt } from "@/lib/mentions"; import { mentionPicksFor, restoreMentionPicks } from "@/lib/mention-picks";
import { serializeThreadRefs, threadTokenFromPaste, threadTokenSpacing } from "@/lib/thread-refs";
import {
  composerSlashTrigger,
  goalTextFromComposer,
  builtInCommandText,
  replaceComposerSlashTrigger,
  skillSlashCommands,
  slashCommandMatches,
  type ComposerSlashCommand,
} from "@/lib/composer-commands";
import { useSlashSkills } from "@/lib/use-slash-skills";
import { randomUuid } from "@/lib/random-uuid";
import { conversationCommands, useComposerThreadCommand } from "./use-composer-thread-command";

const supportsAgents = (instances: InstanceInfo[], candidate?: Bot) =>
  Boolean(candidate && instances.find((instance) => instance.instanceId === candidate.modelSelection.instanceId)?.capabilities?.agentsMcp);

interface ComposerDraftSnapshot extends ComposerSendSnapshot {
  reply: Message | null;
}

export function Composer({
  bot: profile,
  group,
  members,
  onEditLast,
  replyTo,
  onClearReply,
  onConsumeReply,
  onRestoreReply,
  onSendGroup,
}: {
  bot?: Bot;
  group?: Group;
  members?: Bot[];
  onEditLast?: () => void;
  replyTo?: Message | null;
  onClearReply?: () => void;
  onConsumeReply?: () => void;
  onRestoreReply?: (message: Message, threadId: string) => void;
  /** Takes a room's send instead of the store: the room feed starts a new thread with it. */
  onSendGroup?: (action: Extract<Action, { type: "sendGroup" }>) => void;
}) {
  const bot = profile ? currentTaskBot(profile) : undefined;
  const locked = Boolean(bot?.awaitingThreadSnapshot);
  const state = useStoreSelector((s) => ({ instances: s.instances, config: s.config, queued: s.pendingQueued[group?.threadId ?? bot?.threadId ?? ""] }), sameFields), dispatch = useStoreDispatch(), store = useStoreRef(), bots = useStoreSelector((s) => s.bots, sameDrawnBots);
  const { threads, currentBotId } = useThreadRefs();
  const advanced = useAdvancedMode();
  // On a phone the composer is a dock: a round + (attach and every other tool), then one pill with the field, the mic and the voice button.
  const singleRow = useMediaQuery(PHONE_LAYOUT);
  // Simple mode on a wider screen: one pill holding a round +, the field, the mic and one round button in the bot's colour.
  const simpleDock = !advanced && !singleRow;
  // Advanced mode on a wider screen: the field on its own line, with one quiet footer row of tools under it.
  const stacked = advanced && !singleRow;
  const sendKey = useSendKey(); const followUpDefault = useFollowUpDefault();
  const sendLabel = sendKeyLabel(sendKey);
  const remoteClient = window.ogb?.remoteClient?.active === true;
  const threadId = group?.threadId ?? bot?.threadId ?? "";
  const currentGroupTask = group?.tasks?.find((task) => task.threadId === threadId);
  const groupBusyBotId = currentGroupTask?.busyBotId ?? (currentGroupTask?.working ? group?.busyBotId : (group?.threadId === threadId ? group?.busyBotId : null));
  const groupWorking = group ? openTaskWorking(group) : false;
  const busy = group ? Boolean(groupWorking || groupBusyBotId) : Boolean(bot?.busy);
  const steerInstanceId = group
    ? members?.find((member) => member.id === groupBusyBotId)?.modelSelection.instanceId
    : bot?.modelSelection.instanceId;
  const canSteer =
    state.instances.find((i) => i.instanceId === steerInstanceId)?.capabilities?.queueing === true;
  const composerTask = profile?.tasks?.find((task) => task.threadId === threadId);
  // Visible branch only: an approval left on an abandoned branch must not block the composer.
  const approvals = pendingApprovals(group ? group.messages : bot ? visibleMessages(bot) : []);
  const approval = approvals[0];
  // A Turn on card can wait while the person walks to their computer: they can still write meanwhile.
  const blocking = Boolean(approval && !approval.message.card?.computerAsk);
  const asker = useStoreSelector((s) => s.bots.find((one) => one.id === approval?.message.inbox?.from.botId)), approvalBot = group
    ? members?.find((member) => member.id === approval?.message.from?.botId) ??
      members?.find((member) => member.id === groupBusyBotId)
    : asker ?? bot;
  const busyName = group
    ? (members?.find((b) => b.id === groupBusyBotId)?.name ??
      (groupWorking ? t("composer.busy.team") : t("composer.busy.aBot")))
    : (bot?.name ?? t("composer.busy.theBot"));
  const draftId = group
    ? `group:${group.id}:${group.threadId}`
    : `bot:${bot?.id ?? ""}:${bot?.threadId ?? ""}`;
  const [text, setText, attachments, setAttachments] = useComposerDraft(
    draftId,
    !group && bot && !state.config?.team ? `bot:${bot.id}` : undefined,
  );
  const forkOwnerId = composerForkOwner({ phone: singleRow, group, botId: bot?.id, threadId: threadId && !isNewChatThread(threadId) ? threadId : undefined, startsThread: Boolean(onSendGroup) });
  const attachmentPending = useDraftAttachmentPending(draftId);
  const failedSends = useFailedComposerSends(draftId); const picks = mentionPicksFor(draftId);
  const [channelMode, setChannelMode] = useComposerChannelMode(draftId);
  const editText = useCallback(
    (next: string) => {
      markDraftEdited(draftId);
      setText(next);
    },
    [draftId, setText],
  );
  const editAttachments = useCallback(
    (next: SetStateAction<Attachment[]>) => {
      markDraftEdited(draftId);
      setAttachments(next);
    },
    [draftId, setAttachments],
  );
  const restoreDraft = useCallback(
    (sent: ComposerDraftSnapshot) => {
      if (recoverFailedComposerSend(sent) === "restored") {
        restoreMentionPicks(sent.draftId, sent.mentions); if (sent.reply) onRestoreReply?.(sent.reply, sent.threadId);
      }
    },
    [onRestoreReply],
  );
  const addAttachments = useCallback(
    (next: Attachment[]) => appendDraftAttachments(draftId, next),
    [draftId],
  );
  const removeAttachment = useCallback(
    (id: string) => {
      const removed = attachments.find((attachment) => attachment.id === id);
      if (removed?.kind === "image") releaseAttachmentImagePreview(removed);
      if (removed) discardUnsentUpload(removed);
      editAttachments((prev) => prev.filter((attachment) => attachment.id !== id));
    },
    [attachments, editAttachments],
  );
  const displayPasteInChatBox = useCallback(
    function displayPasteInChatBox(attachment: PasteAttachment) {
      const nextText = appendPastedText(text, attachment.text);
      editText(nextText);
      editAttachments((prev) => prev.filter((a) => a.id !== attachment.id));
      setCaret(nextText.length);
      setDismissedAt(null);
      requestAnimationFrame(() => {
        const input = inputRef.current;
        if (!input) return;
        input.focus();
        input.setSelectionRange(nextText.length, nextText.length);
      });
    },
    [text, editText, editAttachments],
  );
  const composerLayout = useComposerLayout(), { recording, ready: micReady, speechError, dismissSpeechError, toggle: toggleMic, stop: stopDictation } = useComposerDictation({ draftId, text, onText: editText });
  const fork = useComposerFork({ ownerId: forkOwnerId, kind: group ? "group" : "bot", threadId,
    branchLeafId: group ? undefined : bot?.activeLeafId ?? undefined, draftId, text, editText, stopDictation });
  const micShown = !locked && !busy && micReady;
  const [caret, setCaret] = useState(0);
  const shellRef = useRef<HTMLDivElement>(null); const composerFocus = useComposerFocusHandlers(threadId);
  const tall = useTallPill(shellRef, simpleDock);
  const multiline = simpleDock && (tall || text.includes("\n"));
  const [highlight, setHighlight] = useState(0);
  const [dismissedAt, setDismissedAt] = useState<number | null>(null);
  const [dismissedSlashAt, setDismissedSlashAt] = useState<number | null>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);
  const draftIdRef = useRef(draftId);
  draftIdRef.current = draftId;
  const caretRef = useRef(0);
  caretRef.current = caret;
  const escapeBlurs = useRef(0);
  const refocusInput = useCallback((escapesBefore: number) => {
    requestAnimationFrame(() => {
      const input = inputRef.current;
      if (escapeBlurs.current !== escapesBefore || !input || input.disabled || !composerShouldRefocus(document.activeElement, input)) return;
      const at = Math.min(caretRef.current, input.value.length);
      input.focus();
      input.setSelectionRange(at, at);
    });
  }, []);
  // Touch screens are skipped: focusing there pops the on-screen keyboard over the conversation.
  useEffect(() => {
    if (window.matchMedia?.("(hover: none) and (pointer: coarse)").matches) return;
    const frame = requestAnimationFrame(() => {
      const input = inputRef.current;
      if (!input || input.disabled || !composerTakesFocusOnOpen(document.activeElement, input)) return;
      input.focus();
      input.setSelectionRange(input.value.length, input.value.length);
    });
    return () => cancelAnimationFrame(frame);
  }, []);
  const replyToId = replyTo?.id ?? null;
  const focusedReplyRef = useRef(replyToId);
  useEffect(() => {
    const previous = focusedReplyRef.current;
    focusedReplyRef.current = replyToId;
    if (!replyTargetTakesFocus(previous, replyToId)) return;
    if (window.matchMedia?.("(hover: none) and (pointer: coarse)").matches) return;
    const frame = requestAnimationFrame(() => {
      const input = inputRef.current;
      if (!input || input.disabled || !composerTakesFocusOnOpen(document.activeElement, input)) return;
      input.focus();
      input.setSelectionRange(input.value.length, input.value.length);
    });
    return () => cancelAnimationFrame(frame);
  }, [replyToId]);
  const mentionListRef = useRef<HTMLDivElement>(null);
  const commandListRef = useRef<HTMLDivElement>(null);

  const botSupportsImages = (candidate?: Bot) =>
    Boolean(
      candidate &&
        state.instances.find((i) => i.instanceId === candidate.modelSelection.instanceId)?.capabilities?.images,
    );
  const imageTargetsSupport = (message: string, mode: "chat" | "goal") => {
    if (!group) return botSupportsImages(bot);
    if (mode === "goal") {
      return botSupportsImages(goalCoordinatorForComposer(message, members ?? [], group, picks.ids(message)) ?? undefined);
    }
    const route = roomRouteForComposer(message, members ?? [], group, picks.ids(message));
    return route.ambiguous || (route.responders.length > 0 && route.responders.every(botSupportsImages));
  };
  const typedGoalText = !group?.dm ? goalTextFromComposer(text) : null;
  const effectiveText = typedGoalText ?? text;
  const threadCommandAvailable = !group && Boolean(composerTask);
  const startedThread = Boolean(bot && threadCommandAvailable && !isNewChatThread(threadId) && visibleMessages(bot).length > 0);
  const { command: threadCommand, freshPrompt, run: runThreadCommand, dialog: threadCommandDialog, contextMenu } = useComposerThreadCommand({
    text, bot: !group ? bot : undefined, threadId, mainThreadId: profile?.mainThreadId, threads: profile?.tasks, threadActions: threadCommandAvailable, started: startedThread,
    title: composerTask?.title, busy, dispatch, returnFocusRef: inputRef,
    clearText: () => { stopDictation(); editText(""); picks.clear(); setCaret(0); },
    onCleared: () => { editText(""); setAttachments([]); picks.clear(); setCaret(0); setDismissedSlashAt(null); onConsumeReply?.(); setChannelMode("chat"); },
  });
  const effectiveChannelMode = typedGoalText !== null ? "goal" : channelMode;
  const engineSupportsImages = imageTargetsSupport(effectiveText, effectiveChannelMode);

  const slash = composerSlashTrigger(text, caret);
  const locale = activeLocale();
  const slashSkills = useSlashSkills(group || isPlaceId(bot?.id) ? undefined : bot?.id, threadId, Boolean(slash) && slash?.start !== dismissedSlashAt);
  const canLearn = skillAuthoringEnabled(state.config) && !isPlaceId(bot?.id) &&
    (group ? (members ?? []).some((member) => supportsAgents(state.instances, member)) : supportsAgents(state.instances, bot));
  const commandCandidates = useMemo(() => {
    if (!slash || slash.start === dismissedSlashAt) return [];
    const available: ComposerSlashCommand[] = [];
    const builtIns = slash.start === 0; // Built-in commands only work at the start of a message; skills can be named anywhere.
    if (builtIns && !group?.dm) available.push({
      kind: "command",
      id: "goal",
      label: "/goal",
      description: t(group ? "composer.command.goalDesc" : "composer.command.goalBotDesc"),
    });
    if (builtIns && canLearn) {
      available.push({
        kind: "command",
        id: "learn",
        label: "/learn",
        description: t("composer.command.learnDesc"),
      });
    }
    if (builtIns && !group && supportsAgents(state.instances, bot)) available.push({
      kind: "command",
      id: "setup",
      label: "/setup",
      description: t("composer.command.setupDesc"),
    }, { kind: "command", id: "burst", label: "/burst", description: t("composer.command.burstDesc") });
    if (builtIns && forkOwnerId) available.push({ kind: "command", id: "fork", label: "/fork", description: t("composer.command.forkDesc") });
    if (builtIns && threadCommandAvailable && bot) available.push(...conversationCommands(startedThread));
    available.push(...skillSlashCommands(slashSkills).filter((command) => !available.some((builtIn) => builtIn.id === command.id)));
    return available.filter((command) => slashCommandMatches(command, slash.query))
      .sort((a, b) => Number(b.id === slash.query.toLowerCase()) - Number(a.id === slash.query.toLowerCase()));
  }, [slash, dismissedSlashAt, group, bot, threadCommandAvailable, startedThread, canLearn, state.instances, locale, slashSkills, forkOwnerId]);
  const commandPickerOpen = commandCandidates.length > 0;

  const mention = mentionQueryAt(text, caret); const teammates = useTeammates(); const viewer = useViewerEmail();
  const candidates = useMemo(() => {
    if (!mention || mention.start === dismissedAt || isPlaceId(bot?.id)) return []; // a My Cloud bot's chat names none of this computer's
    const pool: MentionChoice[] = group
      ? [
          ...(!group.dm ? [{ id: "__everyone__", name: "everyone" }, ...departmentChoices(members ?? [])] : []),
          ...(members ?? []).map((member) => ({ id: member.id, name: member.name, bot: member })),
        ]
      : bots
          .filter((member) => member.id !== bot?.id && !member.hidden && !isPlaceId(member.id) && !hiddenFromSidebar(member, viewer))
          .map((member) => ({ id: member.id, name: member.name, bot: member }));
    return mentionChoicesForQuery([...pool, ...teammateChoices(teammates.people), DEVS_CHOICE], mention.query);
  }, [mention, dismissedAt, bots, bot?.id, group, members, teammates, viewer]);
  const mentionEveryoneCount = (members ?? []).filter((member) => !member.hidden).length;
  const mentionPickerOpen = candidates.length > 0;
  const commandMotion = useMenuMotion(commandPickerOpen);
  const mentionMotion = useMenuMotion(mentionPickerOpen);

  useEffect(
    () => setHighlight(0),
    [mention?.start, mention?.query, slash?.start, slash?.query],
  );

  useEffect(() => {
    if (!commandPickerOpen) return;
    setHighlight((current) => Math.min(current, commandCandidates.length - 1));
  }, [commandCandidates.length, commandPickerOpen]);

  useEffect(() => {
    if (!commandPickerOpen) return;
    commandListRef.current
      ?.querySelector<HTMLElement>(`[data-command-index="${highlight}"]`)
      ?.scrollIntoView({ block: "nearest" });
  }, [highlight, commandPickerOpen]);

  useEffect(() => {
    if (!mentionPickerOpen) return;
    mentionListRef.current
      ?.querySelector<HTMLElement>(`[data-mention-index="${highlight}"]`)
      ?.scrollIntoView({ block: "nearest" });
  }, [highlight, mentionPickerOpen]);

  const pickMention = (peer: MentionChoice) => {
    if (!mention) return;
    const after = text.slice(caret);
    const next = `${text.slice(0, mention.start)}@${peer.name} ${after}`;
    picks.pick(peer); editText(next);
    const newCaret = mention.start + peer.name.length + 2;
    setCaret(newCaret);
    setDismissedAt(mention.start);
    requestAnimationFrame(() => {
      inputRef.current?.focus();
      inputRef.current?.setSelectionRange(newCaret, newCaret);
    });
  };

  const pickCommand = (command: ComposerSlashCommand | undefined) => {
    if (!slash || !command) return;
    const spaceAfter = /^\s/.test(text.slice(slash.end)) ? "" : " ";
    const replacement = command.kind === "skill" ? `${command.label}${spaceAfter}`
      : builtInCommandText(command.id);
    const next = replaceComposerSlashTrigger(text, slash, replacement);
    editText(next.text);
    setCaret(next.caret);
    setDismissedSlashAt(slash.start);
    setChannelMode(command.kind === "command" && command.id === "goal" ? "goal" : "chat");
    requestAnimationFrame(() => {
      inputRef.current?.focus();
      inputRef.current?.setSelectionRange(next.caret, next.caret);
    });
  };
  const teachTask = () => {
    const learn = "/learn ";
    editText(learn + text.replace(/^\/learn\s*/, "").trimStart());
    setCaret(learn.length);
    setChannelMode("chat");
    requestAnimationFrame(() => { inputRef.current?.focus(); inputRef.current?.setSelectionRange(learn.length, learn.length); });
  };

  const sharedChat = Boolean(state.config?.team && !group && profile?.tasks?.some((task) => task.threadId === threadId && !task.private));
  const queuedMessages = sharedChat ? [] : state.queued ?? [];
  const pendingCount = queuedMessages.length;
  const canSteerQueued = composerCanSteerQueuedMessages(
    busy,
    locked,
    pendingCount,
    blocking,
  );
  const roomSteers = Boolean(group) && roomSteersQueued(canSteer, groupBusyBotId);
  const [steering, setSteering] = useState(false);
  const interruptTurn = () => {
    if (group) dispatch({ type: "interruptGroup", groupId: group.id, threadId });
    else if (bot) dispatch({ type: "interrupt", botId: bot.id, threadId });
  };
  const queueHeadId = queuedMessages[0]?.queueId;
  const steerQueued = () => {
    if (!queueHeadId) return;
    setSteering(true);
    const settle = () => setSteering(false);
    if (group) {
      if (roomSteers) dispatch({ type: "steerGroupQueued", groupId: group.id, threadId, queueId: queueHeadId, onError: settle, onSettled: settle });
      else settle();
    } else if (bot && canSteer) {
      dispatch({ type: "steerQueued", botId: bot.id, threadId, queueId: queueHeadId, onError: settle, onSettled: settle });
    } else if (bot) {
      dispatch({ type: "interrupt", botId: bot.id, threadId, onError: settle });
    }
  };
  useEffect(() => setSteering(false), [threadId, queueHeadId]);
  // Only a confirmed removal hands the words back, so a message that already drained into a turn is never resent.
  const editQueued = (queueId: string) => {
    const queued = queuedMessages.find((item) => item.queueId === queueId);
    if (!queued) return;
    const targetDraftId = draftId;
    const onCancelled = () => {
      const cited = splitTranscriptCitations(queued.text);
      if (cited.display) prependComposerDraft(targetDraftId, cited.display);
      appendDraftAttachments(targetDraftId, cited.citations);
      if (targetDraftId !== draftIdRef.current) return;
      requestAnimationFrame(() => {
        const input = inputRef.current;
        if (!input) return;
        input.focus();
        input.setSelectionRange(cited.display.length, cited.display.length);
      });
    };
    if (group) dispatch({ type: "cancelGroupQueued", groupId: group.id, threadId, queueId, onCancelled });
    else if (bot) dispatch({ type: "cancelQueued", botId: bot.id, threadId, queueId, onCancelled });
  };
  const steerAgainUntilRef = useRef(0);
  const prevPendingCountRef = useRef(pendingCount);
  useEffect(() => {
    const expiresAt = doubleEnterSteerWindowExpiresAt(
      prevPendingCountRef.current,
      pendingCount,
      busy,
      group ? roomSteers : canSteer,
    );
    if (expiresAt !== null) steerAgainUntilRef.current = expiresAt;
    prevPendingCountRef.current = pendingCount;
  }, [pendingCount, busy, canSteer, group, roomSteers]);
  useEffect(() => {
    if (!busy || pendingCount === 0) {
      setSteering(false);
      return;
    }
    if (!steering) return;
    const timeout = window.setTimeout(() => setSteering(false), 20_000);
    return () => window.clearTimeout(timeout);
  }, [busy, pendingCount, steering]);
  const fileInput = useRef<HTMLInputElement>(null);
  const [attachmentNotice, setAttachmentNotice] = useState<string | null>(null), placed = isPlaceId(bot?.id), filesThere = () => setAttachmentNotice(t("together.inPlace.files")); // a My Cloud bot open in place takes no files here
  const modeBot = group ? undefined : bot;
  const pinPlace = (surface: Place | null) => modeBot && dispatch({ type: "updateTask", botId: modeBot.id, threadId: modeBot.threadId, patch: { surface } });
  const place = modeBot && !remoteClient && advanced ? { bot: modeBot, task: composerTask, disabled: Boolean(modeBot.busy), onPin: pinPlace } : undefined;
  const { choice: approvalChoice, dialogs: approvalDialogs } = useThreadApproval(modeBot);
  const uploadImage = useCallback((file: File) => (placed ? Promise.resolve(null) : uploadDraftImage(draftId, file)), [draftId, placed]);
  const pickFiles = async (picked: FileList | readonly File[] | null) => {
    if (!picked?.length) return; if (placed) return filesThere();
    const escapesBefore = escapeBlurs.current;
    changeDraftAttachmentPending(draftId, true);
    try {
      const { attachments: added, notice } = await intakeFilesWithNotice(Array.from(picked), {
        allowImages: engineSupportsImages,
        getPath: pathForFile,
        localPath: localPathForFile,
        uploadImage,
        imageSlots: imageSlotsLeft(attachments),
        imageBytes: imageBytesLeft(attachments),
      });
      if (added.length) addAttachments(added);
      if (notice) setAttachmentNotice(notice);
    } finally {
      changeDraftAttachmentPending(draftId, false);
    }
    refocusInput(escapesBefore);
  };

  const hasContent = Boolean(effectiveText.trim()) || attachments.length > 0;
  const suggestion = useSuggestedReply({ botId: group ? undefined : bot?.id, threadId, messages: !group && bot ? visibleMessages(bot) : [], working: busy || Boolean(bot?.waitingForTeammates), held: locked || blocking || pendingCount > 0 || Boolean(replyTo) || recording, draft: text, attached: attachments.length > 0, inputRef, fill: (value) => { editText(value); setCaret(value.length); } });
  const onCall = useOnCall();
  const media = useLiveMedia();
  const callTarget = group?.id ?? bot?.id;
  const calling = callTarget !== undefined && (onCall === callTarget || (isLiveCallRunning(media.phase) && media.botId === callTarget));
  const mayAct = useMayAct(), mayStop = !sharedChat || mayAct(profile?.tasks?.find((task) => task.threadId === threadId)?.askedBy);
  const stoppable = (busy || Boolean(!group && bot?.waitingForTeammates)) && mayStop;
  const stopInSlot = simpleDock && stoppable && !locked && !hasContent && !calling;
  const callShown = singleRow || !hasContent || busy || Boolean(!group && bot?.waitingForTeammates) || calling;
  const slot = slotColors(bot?.color, Boolean(group));
  // A bot at work: Enter does the chosen follow-up and Ctrl/⌘ with it the other one. A room joins in when its speaking engine can steer,
  // without the send menu: a room's turn has no restart.
  const followUpFor = (alternate: boolean) => resolveFollowUp({ running: busy && (group ? roomSteers : Boolean(bot)), alternate, preferred: followUpDefault, canSteer }) ?? undefined;
  const steersNow = followUpFor(false) === "steer";
  const sendNames = fork.command ? { label: t("composer.command.forkDesc"), title: t("composer.command.forkDesc") }
    : sendLabels({ simple: !advanced, busy, canSteer: steersNow, name: busyName, sendLabel });
  const retryFailedSend = (failed: FailedComposerSend) => {
    const failedMode = failed.channelMode ?? "chat";
    if (failed.requestText.includes("<attached-image ") && !imageTargetsSupport(failed.requestText, failedMode)) {
      dispatch({ type: "error", message: t("composer.error.noImages") });
      return;
    }
    forgetFailedComposerSend(draftId, failed.id);
    const retry = {
      sendId: failed.sendId,
      text: failed.requestText,
      replyToId: failed.replyToId,
      threadId: failed.threadId, mentions: failed.mentions,
      onError: () => {
        rememberFailedComposerSend(draftId, {
          sendId: failed.sendId,
          text: failed.text,
          requestText: failed.requestText,
          replyToId: failed.replyToId,
          threadId: failed.threadId, mentions: failed.mentions,
          channelMode: failed.channelMode,
          followUp: failed.followUp,
        });
      },
    };
    if (group) {
      (onSendGroup ?? dispatch)({ type: "sendGroup", groupId: group.id, mode: failedMode, ...(failed.followUp ? { followUp: failed.followUp } : {}), ...retry });
    } else if (bot) {
      dispatch({ type: "send", botId: bot.id, mode: failedMode, followUp: failed.followUp, ...retry });
    }
  };
  const send = (followUp: FollowUp | undefined = followUpFor(false)) => {
    if (locked || attachmentPending) return;
    if (threadCommand && !freshPrompt) { setDismissedSlashAt(slash?.start ?? 0); runThreadCommand(); return; }
    if (fork.command) {
      setDismissedSlashAt(slash?.start ?? 0);
      fork.submit();
      return;
    }
    if (
      attachments.some((attachment) => attachment.kind === "image") &&
      !imageTargetsSupport(effectiveText, effectiveChannelMode)
    ) {
      dispatch({ type: "error", message: t("composer.error.noImages") });
      return;
    }
    const composed = composeMessage(serializeThreadRefs(freshPrompt || effectiveText, threads, currentBotId), attachments);
    if (!composed) return;
    stopDictation();
    const body = restoredRequestText(draftId) ?? composed;
    const sentThread = freshPrompt && startedThread && bot ? newChatThreadId(bot.id) : threadId, sentDraftId = sentThread === threadId ? draftId : `bot:${bot?.id ?? ""}:${sentThread}`;
    const dataContext = dataContextFor(body, store.state().computerOpen ? store.state().dataView : null, !group && bot ? { botId: bot.id, threadId: sentThread } : undefined);
    const sentDraft: ComposerDraftSnapshot = {
      draftId: sentDraftId,
      revision: draftRevision(sentDraftId),
      sendId: restoredSendId(sentDraftId) ?? randomUuid(),
      text: freshPrompt || text,
      requestText: body,
      attachments: [...attachments],
      reply: sentThread === threadId ? replyTo ?? null : null,
      replyToId: sentThread === threadId ? replyTo?.id : undefined,
      threadId: sentThread,
      channelMode: effectiveChannelMode, mentions: picks.ids(body), followUp,
    };
    if (group) {
      const points = effectiveChannelMode === "goal" ? null : takePointedChips(threadId);
      (onSendGroup ?? dispatch)({
        type: "sendGroup",
        groupId: group.id,
        text: body,
        sendId: sentDraft.sendId,
        replyToId: replyTo?.id,
        threadId,
        mode: effectiveChannelMode, mentions: sentDraft.mentions,
        ...(points ? { pointed: points.pointed } : {}), ...(followUp ? { followUp } : {}),
        onError: () => { points?.restore(); restoreDraft(sentDraft); },
      });
      roomMessageSent(effectiveChannelMode, busy);
    } else if (bot) {
      if (freshPrompt && startedThread) dispatch({ type: "newTask", botId: bot.id });
      const points = effectiveChannelMode === "goal" ? null : takePointedChips(sentThread); const page = effectiveChannelMode === "goal" ? undefined : openPageFor(sentThread);
      dispatch({
        type: "send", botId: bot.id, text: body, sendId: sentDraft.sendId, replyToId: sentThread === threadId ? replyTo?.id : undefined, threadId: sentThread, dataContext, mode: effectiveChannelMode, mentions: sentDraft.mentions,
        ...(points ? { pointed: points.pointed } : {}), ...(page ? { openPage: page } : {}), ...(followUp ? { followUp } : {}),
        onError: () => { points?.restore(); restoreDraft(sentDraft); },
      });
      directMessageSent(state.instances, bot.modelSelection?.instanceId, busy && followUp !== "steer");
    }
    setText("");
    setAttachments([]); picks.clear();
    onConsumeReply?.();
    setChannelMode("chat");
  };

  const handlePaste = (e: React.ClipboardEvent<HTMLTextAreaElement>) => {
    const pastedFiles = clipboardFilesToAttach(e.clipboardData); if (placed && (pastedFiles.length || clipboardHasImages(e.clipboardData))) { e.preventDefault(); filesThere(); return; }
    if (pastedFiles.length > 0) {
      e.preventDefault();
      void pickFiles(pastedFiles);
      return;
    }
    const imageFiles = clipboardImageFiles(e.clipboardData);
    if (imageFiles.length > 0 || clipboardHasImages(e.clipboardData)) {
      e.preventDefault();
      if (!engineSupportsImages) {
        dispatch({
          type: "error",
          message: t("composer.error.noImages"),
        });
        return;
      }
      if (!imageFiles.length) {
        dispatch({ type: "error", message: t("composer.error.clipboardImage") });
        return;
      }
      const kept = imagesThatFit(imageFiles, imageSlotsLeft(attachments), setAttachmentNotice, imageBytesLeft(attachments));
      changeDraftAttachmentPending(draftId, true);
      void (async () => {
        try {
          const results = await Promise.allSettled(kept.map(uploadImage));
          for (const result of results) {
            if (result.status === "rejected") {
              dispatch({
                type: "error",
                message: result.reason instanceof Error ? result.reason.message : "image upload failed",
              });
            }
          }
        } finally {
          changeDraftAttachmentPending(draftId, false);
        }
      })();
      return;
    }
    const pasted = e.clipboardData.getData("text/plain");
    const reference = threadTokenFromPaste(pasted, threads, currentBotId);
    if (reference) {
      e.preventDefault();
      const start = e.currentTarget.selectionStart ?? text.length;
      const end = e.currentTarget.selectionEnd ?? start;
      const { lead, trail } = threadTokenSpacing(text, start, end);
      const token = lead + reference.token + trail;
      editText(text.slice(0, start) + token + text.slice(end));
      const at = start + token.length;
      setCaret(at);
      requestAnimationFrame(() => {
        inputRef.current?.focus();
        inputRef.current?.setSelectionRange(at, at);
      });
      return;
    }
    if (!isLongPaste(pasted)) return;
    e.preventDefault();
    const start = e.currentTarget.selectionStart;
    const end = e.currentTarget.selectionEnd;
    if (start !== end) {
      editText(`${text.slice(0, start)}${text.slice(end)}`);
      setCaret(start);
    }
    editAttachments((prev) => [...prev, pasteAttachment(pasted)]);
  };

  const toggleGoal = () => {
    markDraftEdited(draftId);
    if (typedGoalText !== null) {
      const nextCaret = Math.max(0, caret - (text.length - typedGoalText.length));
      editText(typedGoalText);
      setCaret(nextCaret);
      setChannelMode("chat");
      requestAnimationFrame(() => {
        inputRef.current?.focus();
        inputRef.current?.setSelectionRange(nextCaret, nextCaret);
      });
      return;
    }
    setChannelMode((current) => current === "goal" ? "chat" : "goal");
  };
  const goal = !group?.dm ? { on: effectiveChannelMode === "goal", onToggle: toggleGoal, solo: !group } : undefined;

  return (
    <div className={cn("pointer-events-none relative px-4", simpleDock ? "pb-4" : "pb-3")}>
      {speechError && <div className="pointer-events-auto mb-2 flex w-full items-start gap-2 rounded-lg border border-warning/30 bg-warning/10 px-3 py-2 text-[12px] text-warning">
        <span role="status" className="min-w-0 flex-1 break-words">{speechError}</span><DismissWarning onDismiss={() => { dismissSpeechError(); inputRef.current?.focus(); }} /></div>}
      <div className="pointer-events-auto relative w-full">
        {fork.error && <ComposerForkError message={fork.error} onRetry={() => { inputRef.current?.focus(); send(); }} />}
        <ComposerFailedSends draftId={draftId} failedSends={failedSends} onRetry={retryFailedSend} />
        <SlashCommandMenu listRef={commandListRef} motion={commandMotion} commands={commandCandidates} highlight={highlight}
          onPick={pickCommand} onHighlight={setHighlight} />
        <MentionMenu listRef={mentionListRef} motion={mentionMotion} choices={candidates} highlight={highlight}
          everyoneCount={mentionEveryoneCount} onPick={pickMention} onHighlight={setHighlight} />
        {approval && (
          <div className={cn("mb-2 overflow-hidden rounded-[18px]", ELEVATED_CARD)}>
            <PendingApprovalPanel
              key={approval.requestId}
              pending={approval}
              botName={approvalBot?.name} asker={approvalBot}
              count={approvals.length}
              index={0}
              locale={activeLocale()}
              actions={<PendingApprovalActions part="primary" pending={approval} threadId={threadId} bot={approvalBot} onCancelTurn={interruptTurn} />}
              more={approval.message.inbox ? undefined : <PendingApprovalActions part="more" pending={approval} threadId={threadId} bot={approvalBot} onCancelTurn={interruptTurn} />}
            />
          </div>
        )}
        <PointedChips threadId={threadId} />{!group && bot && <SetupRequestChip bot={bot} threadId={threadId} />}
        <ComposerAttachments
          items={attachments}
          onAdd={placed ? filesThere : addAttachments}
          onRemove={removeAttachment}
          onChangeCitation={(citation: CitationAttachment) => editAttachments((current) => current.map((attachment) => attachment.id === citation.id ? citation : attachment))}
          onDisplayInChatBox={displayPasteInChatBox}
          allowImages={engineSupportsImages}
          notice={attachmentNotice}
          onNotice={setAttachmentNotice}
          onPendingChange={(pending) => changeDraftAttachmentPending(draftId, pending)}
          uploadImage={uploadImage}
        />
        <QueuedComposerMessages
          items={queuedMessages}
          oneThreadPerBot={state.config?.cloudStarter === true}
          onSeePlans={() => dispatch({ type: "toggleAppSettings", open: true, section: "cloudAccount" })}
          onSteer={canSteerQueued && (!group || roomSteers) ? steerQueued : undefined}
          steerInterrupts={!group && !canSteer}
          held={Boolean(group) && busy && !roomSteers}
          steerMode={group ? "next" : "all"}
          steering={steering}
          onCancel={(queueId) => {
            if (group) dispatch({ type: "cancelGroupQueued", groupId: group.id, threadId, queueId });
            else if (bot) dispatch({ type: "cancelQueued", botId: bot.id, threadId, queueId });
          }}
          onEdit={locked ? undefined : editQueued}
        /><TeamAudienceLabel bot={bot} group={group} />
        <div className="relative">
          {/* Plain canvas behind the composer and the strip below it, so the transcript ends at the composer
              with no fade. Simple mode starts it at the composer's top edge, Advanced at its middle. */}
          <div
            aria-hidden
            data-composer-backdrop
            className={cn("pointer-events-none absolute -left-4 -right-4 bg-app", advanced ? "-bottom-3 top-1/2" : cn("top-0", simpleDock ? "-bottom-4" : "-bottom-3"))}
          />
        <div ref={shellRef} data-tour="composer" data-look="composer" data-multiline={multiline ? "" : undefined} className={cn("@container/composer relative z-[1]", singleRow ? "flex items-end gap-2" : simpleDock ? cn(SIMPLE_COMPOSER, multiline ? "rounded-[18px]" : "rounded-[22px]") : cn("rounded-[18px] px-2 pb-2 pt-2.5", ELEVATED_COMPOSER))}>
        {singleRow && !locked && (
          <div className="flex shrink-0 items-center">
            <PhonePlus
              onAttach={() => fileInput.current?.click()}
              goal={goal}
              teach={canLearn ? teachTask : undefined}
              approval={approvalChoice && modeBot && { name: modeBot.name, choice: approvalChoice }}
              callBotId={bot && !group ? bot.id : undefined}
              place={place}
            />
          </div>
        )}
        <div className={singleRow ? cn("min-w-0 flex-1 rounded-[26px] px-3 py-1.5", ELEVATED_FLOAT) : "contents"}>
        {replyTo && <ComposerReplyStrip message={replyTo} fallbackName={bot?.name} onClear={onClearReply} />}
        <div data-composer-row className={cn("flex items-end", simpleDock ? "gap-1.5" : stacked ? "flex-wrap gap-x-1 gap-y-1.5" : "gap-1")}>
          <input
            ref={fileInput}
            type="file"
            multiple
            className="hidden"
            onChange={(e) => {
              void pickFiles(e.target.files);
              // Reset so picking the same file again still fires onChange.
              e.target.value = "";
            }}
          />
          {!locked && simpleDock && (
            <div className="flex items-center gap-1 shrink-0">
              <ComposerPlusMenu onAttach={() => fileInput.current?.click()} goal={goal} teach={canLearn ? teachTask : undefined} />
              {/* Simple mode shows a mode's chip only while it is on, so a choice made in the + menu or the bot panel stays in view. */}
              {goal?.on && <GoalToggle {...goal} />}
              {approvalChoice && profile && bot && approvalModeFor(bot) !== approvalModeFor(profile) && <ApprovalChip choice={approvalChoice} />}
              {modeBot && <PlaceMark bot={modeBot} task={composerTask} />}
            </div>
          )}
          <MentionTextarea
          wrapperClassName={stacked ? "basis-full" : undefined} ghost={suggestion.text ? <SuggestedReplyGhost text={suggestion.text} onUse={suggestion.accept} /> : undefined}
          inputRef={inputRef} {...composerFocus}
          peers={[...(group ? [...(members ?? []), ...(group.dm ? [] : departmentChoices(members ?? []))] : bots.filter((member) => member.id !== bot?.id)), ...teammates.peers]}
          everyone={Boolean(group && !group.dm)}
          dir="auto"
          rows={1}
          value={text}
          onChange={(e) => {
            if (recording) stopDictation();
            editText(e.target.value);
            setCaret(e.target.selectionStart ?? e.target.value.length);
            setDismissedAt(null);
            setDismissedSlashAt(null);
          }}
          onPaste={handlePaste}
          onKeyUp={(e) => setCaret((e.target as HTMLTextAreaElement).selectionStart ?? 0)}
          onClick={(e) => setCaret((e.target as HTMLTextAreaElement).selectionStart ?? 0)}
          onKeyDown={(e) => {
            // An input method's confirming Enter and arrows pick its own candidates, not a mention or command.
            if (imeComposing(e.nativeEvent) || suggestion.onKeyDown(e)) return;
            const submitsFork = fork.command && commandCandidates[highlight]?.id === "fork" && sendsMessage(e.nativeEvent, sendKey);
            const submitsThreadCommand = Boolean(threadCommand) && commandCandidates[highlight]?.id === threadCommand && sendsMessage(e.nativeEvent, sendKey);
            if (commandPickerOpen && !submitsFork && !submitsThreadCommand) {
              if (e.key === "ArrowDown" || e.key === "ArrowUp") {
                e.preventDefault();
                const delta = e.key === "ArrowDown" ? 1 : -1;
                setHighlight((current) =>
                  (current + delta + commandCandidates.length) % commandCandidates.length,
                );
                return;
              }
              if (e.key === "Enter" || e.key === "Tab") {
                e.preventDefault();
                pickCommand(commandCandidates[highlight]);
                return;
              }
              if (e.key === "Escape") {
                e.preventDefault();
                setDismissedSlashAt(slash?.start ?? null);
                return;
              }
            }
            if (mentionPickerOpen) {
              if (e.key === "ArrowDown" || e.key === "ArrowUp") {
                e.preventDefault();
                const delta = e.key === "ArrowDown" ? 1 : -1;
                setHighlight((h) => (h + delta + candidates.length) % candidates.length);
                return;
              }
              if (e.key === "Enter" || e.key === "Tab") {
                e.preventDefault();
                pickMention(candidates[highlight]);
                return;
              }
              if (e.key === "Escape") {
                e.preventDefault();
                setDismissedAt(mention?.start ?? null);
                return;
              }
            }
            if (micShown && isDictationToggle(e.nativeEvent)) {
              e.preventDefault();
              if (!e.nativeEvent.repeat) toggleMic();
              return;
            }
            if (onClearReply && escapeCancelsReply(e.nativeEvent, { replying: Boolean(replyTo), recording })) {
              e.preventDefault();
              onClearReply();
              return;
            }
            if (e.key === "ArrowUp" && !hasContent && onEditLast) {
              e.preventDefault();
              onEditLast();
              return;
            }
            if (sendsMessage(e.nativeEvent, sendKey)) {
              e.preventDefault();
              if (
                (group ? roomSteers : canSteer) &&
                doubleEnterSteersQueue(steerAgainUntilRef.current, Date.now(), pendingCount, hasContent)
              ) {
                steerAgainUntilRef.current = 0;
                steerQueued();
                return;
              }
              send(followUpFor(alternateSend(e.nativeEvent, sendKey)));
            }
            if (e.key !== "Escape") return;
            if (recording) stopDictation();
            else if (!e.defaultPrevented) {
              escapeBlurs.current += 1;
              e.currentTarget.blur();
            }
          }}
          // Not disabled during an upload: a disabled element drops keyboard focus for good. send() refuses while one
          // is pending.
          disabled={blocking || locked}
          aria-busy={bot?.awaitingThreadSnapshot || undefined} aria-describedby={suggestion.text ? SUGGESTION_HINT_ID : undefined}
          placeholder={suggestion.text ?? composerPlaceholder({
            simple: !advanced, approval: blocking, attaching: attachmentPending, listening: recording,
            replying: Boolean(replyTo), busy, canSteer: steersNow, queued: pendingCount > 0, busyName, sendLabel, group, members: members ?? [],
            jevOn: jevRoomRoutingOn(state.config), goal: channelMode === "goal", botName: bot?.name ?? "",
            setupHint: group ? null : setupRequestPlaceholder(bot, threadId), startsThread: Boolean(onSendGroup),
          })}
          aria-label={t("composer.placeholder.bot", { name: group ? group.name : (bot?.name ?? "") })}
            className={cn(
              "block max-h-[9rem] w-full resize-none overflow-y-auto bg-transparent placeholder:text-ink-tertiary focus:outline-none",
              !simpleDock && cn(stacked ? "px-2" : "px-1", "text-[15px]"),
              simpleDock ? "min-h-7 px-0.5 py-1 text-[14px] leading-5" : "min-h-6 py-1 leading-6",
            )}
          />
          {stacked && (
            <ComposerAdvancedTools profile={profile} bot={modeBot} task={composerTask} locked={locked} remoteClient={remoteClient}
              onAttach={() => fileInput.current?.click()} goal={goal} teach={canLearn ? teachTask : undefined} approval={approvalChoice}
              callBotId={callShown && bot && !group && !placed ? bot.id : undefined}
              onPin={pinPlace} />
          )}
          <div data-composer-actions style={composerOrderStyle(composerLayout.order)} className={cn("flex items-center", simpleDock ? "gap-2" : "gap-1", stacked && "ms-auto")}>
          {(simpleDock ? stoppable : busy && mayStop) && !locked && (
          <button
            onClick={() => { tapHaptic(); interruptTurn(); }} data-composer-end="stop"
            aria-label={t("chat.stopTurn")}
            data-composer-stop={simpleDock ? (stopInSlot ? "slot" : "beside") : undefined}
            className={cn(
              "flex shrink-0 items-center justify-center rounded-full",
              !simpleDock ? "size-8 text-ink-secondary hover:bg-raised hover:text-ink"
                : stopInSlot ? cn("size-7", slot.button.className)
                : SIMPLE_CONTROL,
            )}
            style={stopInSlot ? slot.button.style : undefined}
            title={t("chat.stop")}
          >
            <Square size={simpleDock ? 10 : 14} className="fill-current" />
          </button>
        )}
        {!locked && <ComposerContextMenu bot={bot} group={group} members={members} handle={contextMenu} className={cn(simpleDock ? "size-7" : "size-8", advanced || singleRow ? "text-ink-secondary hover:bg-raised hover:text-ink" : SIMPLE_CONTROL)} />}
        {micShown && (
          <button
            onClick={toggleMic} data-composer-end="mic"
            aria-label={recording ? t("composer.dictation.stop") : t("composer.dictation.start")}
            className={cn(
              "flex shrink-0 items-center justify-center rounded-full",
              simpleDock ? "size-7" : "size-8",
              recording
                ? "animate-pulse bg-danger/20 text-danger"
                : advanced || singleRow ? "text-ink-secondary hover:bg-raised hover:text-ink" : SIMPLE_CONTROL,
            )}
            title={recording ? t("composer.dictation.stopHint") : t("composer.dictation.hintKey", { keys: isMacPlatform() ? "⌘D" : "Ctrl+D" })}
          >
            <Mic size={16} className="[&_rect]:fill-current" />
          </button>
        )}
        {callShown && bot && !group && !placed && <CallButton bot={bot} placement="composer" fill={advanced || singleRow ? undefined : slot.fill} ink={slot.ink} inverse={singleRow} modeMenu={!stacked} />}
        {callShown && group && !advanced && <GroupCallButton group={group} members={members ?? []} placement="composer" fill={slot.fill} ink={slot.ink} />}
        {hasContent && !locked && (
          <ComposerSendButton compact={simpleDock} waits={!fork.command && busy && !steersNow} label={sendNames.label} title={sendNames.title} look={slot.button}
            disabled={attachmentPending} onSend={(alternate) => send(followUpFor(alternate))} onChoose={send}
            menu={!fork.command && !group && followUpFor(false) ? { choices: followUpChoices(followUpDefault, canSteer), name: busyName, sendKey: sendLabel, alternateKey: alternateSendLabel(sendKey) } : undefined} />
          )}
          </div>
        </div>
        </div>
        </div>
        </div>
      </div>
      <div className="pointer-events-auto">
      {approvalDialogs}
      </div>
      {threadCommandDialog}
    </div>
  );
}