Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

75.6 KB
Raw Blame
import { PairConversationBoundary } from "@/components/agentchat/PairConversation";
import {
  AgentMessageActivity,
  ChatActivity,
  CodingThreadActivity,
  DelegationActivity,
  RoutineActivity,
  assignmentOf,
  routineTask, TeamEventLine } from "./ChatActivity";
import { MemoryNoticeViewer, MemoryUpdateNotice, memoryNoticePath, memoryNoticeTitle } from "./MemoryUpdateNotice";
import { TeamReportNotice } from "./TeamReportNotice";
import { foldMemoryNotices } from "./memoryNotices";
import { foldRepeatedThreadStatus } from "@/components/agentic/threads/openCodingThread";
import { mergeOutgoingMessages, useOutgoingMessages } from "@/components/agentchat/useOutgoingMessages";
/**
 * The model card's chat column, kept deliberately plain (maintainer,
 * 2026-09-02): bubbles, a time stamp, one pill-shaped composer with a "+"
 * for files and voice, the model and the thinking effort — and nothing else.
 *
 * For Jarvis the column speaks to the SAME store the front page and the
 * voice stage use (`useAgentChatStore`, the "jarvis" surface): one history,
 * whatever a person said or typed anywhere. "@Name" hands the task to that
 * agent; "@gmail" (and the other catalog tags) pins that plugin, MCP server
 * or tool for the turn. The shared work trace preserves the order of thoughts, tools and replies.
 *
 * Jarvis' card alone also has a `Voice | Chat` switch (maintainer,
 * 2026-09-02): Jarvis is the one agent a person talks to by voice, so the
 * column can show the front page's voice stage in place — the Jarvis bar,
 * the wake word, the realtime brain — instead of a typed chat. The two run
 * on different brains on purpose: the typed chat is Jarvis' own harness on
 * a provider API behind a key with a per-chat model pick (runner_brain),
 * the voice runs on the realtime tier (`[brain.realtime]`), which no text
 * runner can drive. The header says so while voice is showing.
 */
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useRoutineNavigation } from "./routineNavigation";
import { notifyRoutineChanged } from "../cardData";
import { routineTaskId } from "./routineExecution";
import { RoutineChatHost } from "./RoutineChatHost";
import { AgentConversationsBar } from "./AgentConversations";
import { Plus, RotateCcw, Send, Square } from "lucide-react";
import { ChatMarkdown, MediaPreview, mediaKind } from "@/components/agentchat/ChatMarkdown";

import { AgentChatStoreProvider, useAgentChat, useAgentChatApi } from "@/components/agentchat/AgentChatStoreContext";
import { ChatAttachmentStrip } from "@/components/agentchat/ChatAttachmentStrip";
import { ScrollToEndButton } from "@/components/ui/scroll-to-end-button";
import { useStickToBottom } from "@/hooks/useStickToBottom";
import { ComposerChipField, type ComposerChipFieldHandle, type ComposerDraft } from "@/components/agentchat/ComposerChipField";
import { captureComposerDraftTarget, readComposerDraft, useComposerDraft, writeComposerDraft } from "@/components/agentchat/composerDrafts";
import { MessageWithChips } from "@/components/agentchat/ToolChoiceChips";
import { choiceToken } from "@/components/agentchat/composerChips";
import { releaseHeldFiles, restoreHeldFiles, useChatAttachments } from "@/components/agentchat/useChatAttachments";
import { DictationButton } from "@/components/agentchat/DictationButton";
import { useComposerDictation } from "@/components/agentchat/useComposerDictation";
import { useEventStore } from "@/store/events";
import { useHomeStore } from "@/store/home";
import {
  runningTurn,
  type NoticeItem,
  type TimelineItem,
  type TurnItem,
  type UserItem,
} from "@/components/agentchat/reduce";
import { AwaitingTurn, MessengerTurn, type MemoryLink } from "@/components/agentchat/MessengerTurn";
import { ActionCard, type ActionSpec } from "@/components/agentchat/actionCard/ActionCard";
import { WandSparkles as ProposalIcon } from "lucide-react";
import { openQuestionOf } from "@/components/agentchat/questions/questionModel";
import { VoiceStage } from "@/components/home/VoiceStage";
import { ProviderLogo } from "@/components/providers/ProviderLogo";
import { fill, useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { societyDisplayName } from "@/lib/societyDisplayName";
import { createAgentChatStore, useAgentChatStore, type AgentChatStoreHook } from "@/store/agentChat";
import { warmAgentChatSession, type AgentChatSurface, type ApprovalDecision } from "@/lib/agentChatApi";
import { offeredModels, useSavedHiddenModels } from "@/lib/agentProviderPrefs";

import { AgentSwatch, agentColor } from "../AgentSwatch";
import { bubbleTint, type BubbleTint } from "@/lib/bubbleTint";
import {
  useResolveProposal,
  useSocietyCapabilities,
  type SocietyAgent,
} from "../data";
import { fetchIdeAgents, type AgentStatus } from "@/lib/agenticIdeApi";
import { CodingProjectChoice } from "./CodingProjectChoice";
import { MentionPicker } from "./MentionPicker";
import { AgentModelPicker } from "./AgentModelPicker";
import { mentionChoice, messageChoices } from "./mentionChoices";
import { ChatCommandPanel, useChatCommands } from "@/components/agentchat/ChatCommands";
import { useTranscriptView } from "./useTranscriptView";
import { useHeaderModelSlot } from "../card/headerModelSlot";
import { societyResultHeadline, societyResultText } from "@/lib/skipReasons";
import {
  buildMentionCatalog,
  codingMentionsInText,
  codingAssignmentHint,
  filterMentions,
  mentionToken,
  mentionsInText,
  type MentionItem,
} from "./mentionItems";
import { stampPlan, type StampEntry } from "@/components/agentchat/activity/transcriptTime";
import { CatchUpPill, RunAnnouncer, SettleBox, TranscriptStamp, useFarFromEnd, useUnseen } from "@/components/agentchat/activity/TranscriptAids";
import { WorkInspector } from "@/components/agentchat/inspector/WorkInspector";
import { inspectorDocked, readInspectorWidth, writeInspectorWidth } from "@/components/agentchat/inspector/inspectorWidth";
import { useInspectedTurn } from "@/components/agentchat/inspector/inspectedTurn";
import { markAnswered } from "../attention/attentionStore";

/** Who spoke an item, for time stamps that never split one speaker's run. */
function stampEntry(item: TimelineItem): StampEntry {
  const ts = item.type === "turn" ? item.startedMs : item.tsMs;
  const author = item.type === "turn" ? "agent" : item.type === "user" ? "person" : item.type;
  const end = item.type === "turn" && item.durationMs ? item.startedMs + item.durationMs : undefined;
  return { id: item.id, ts, end, author };
}

/**
 * Messages use the full conversation lane; each bubble limits its own prose
 * width. The composer follows the lane so replies read left to right.
 */
/**
 * The conversation's reading column. The scroller around it spans the whole
 * pane, so a wide window keeps the words in one comfortable, centred column
 * while the scroll area (and its edge) reaches the window's side.
 */
export const CHAT_MEASURE = "mx-auto w-full min-w-0 max-w-[52rem]";

/** The line appended to a message that names an agent; Jarvis delegates on it. */
const DELEGATE_MARK = "[to jarvis]";

/** Specialist mentions identify teammates; they do not change the chat's recipient. */
const MENTION_MARK = "[agent mentions]";

/** The line a message adds when it names a capability: pin those tools for the turn. */
const TOOL_PIN_MARK = "[tools:";

/** The team offer is asked for once per app load; the backend decides the rest. */
let onboardingAsked = false;

export interface AgentChatPanelProps {
  agent: SocietyAgent;
  roster: SocietyAgent[];
  /** An isolated store lets two canonical agent sessions remain open side by side. */
  chatStore?: AgentChatStoreHook;
  /** Shown directly above the composer of an agent's own chat (a team lead's actions). */
  composerExtras?: ReactNode;
}

/**
 * Every other agent speaks in its OWN canonical chat (`society:<agent_id>`,
 * surface `society`): the backend binds the session to the roster row on
 * request, and this store — one socket for the society surface — opens it.
 * The brain is the roster's choice, so the column shows it instead of the
 * front page's pickers.
 */
export const useSocietyChatStore = createAgentChatStore("society");

type JarvisCardMode = "chat" | "voice";

/** The lead card and its history share the voice lifecycle, even while closed. */
export function getJarvisCardMode(): JarvisCardMode {
  return useHomeStore.getState().jarvisCardMode;
}

export function setJarvisCardMode(next: JarvisCardMode): void {
  useHomeStore.getState().setJarvisCardMode(next);
}

export function useJarvisCardMode(): JarvisCardMode {
  return useHomeStore((s) => s.jarvisCardMode);
}
/**
 * The transcript a specialist column may paint. One store serves every
 * specialist, so the chrome (name, rail, composer) can already show the
 * agent you clicked while the socket is still on the previous session —
 * those items must not appear under the new name.
 */
export function itemsForOpenSession(
  sessionId: string | null,
  activeSessionId: string | null,
  items: TimelineItem[],
): TimelineItem[] {
  return sessionId !== null && sessionId === activeSessionId ? items : [];
}

/** Roster id → the name a person sees (the lead follows the wake word). */
function useRosterDisplayName(roster: SocietyAgent[]): (id: string, fallback: string) => string {
  const assistantName = useEventStore((state) => state.assistantName);
  return useCallback((id: string, fallback: string) => {
    const member = roster.find((a) => a.agentId === id);
    return member ? societyDisplayName(member, assistantName) : fallback;
  }, [roster, assistantName]);
}

export function AgentChatPanel(props: AgentChatPanelProps) {
  const disconnect = useCallback(() => {
    (props.agent.tier === "lead" ? useAgentChatStore : props.chatStore ?? useSocietyChatStore).getState().disconnect();
  }, [props.agent.tier, props.chatStore]);
  const assistantName = useEventStore((state) => state.assistantName);
  return <PairConversationBoundary key={props.agent.agentId} recipient={{ id: props.agent.agentId, name: societyDisplayName(props.agent, assistantName) }}>
    <RoutineChatHost agentId={props.agent.agentId} onOpen={disconnect}><AgentChatPanelContent {...props} /></RoutineChatHost>
  </PairConversationBoundary>;
}

function AgentChatPanelContent({ agent, roster, chatStore, composerExtras }: AgentChatPanelProps) {
  if (agent.tier === "lead") {
    return (
      <AgentChatStoreProvider store={useAgentChatStore}>
        <JarvisChat agent={agent} roster={roster} />
      </AgentChatStoreProvider>
    );
  }
  if (!agent.chatSessionId) return <NotBoundYet />;
  return (
    <AgentChatStoreProvider store={chatStore ?? useSocietyChatStore}>
      <SpecialistChat agent={agent} roster={roster} composerExtras={composerExtras} />
    </AgentChatStoreProvider>
  );
}

function NotBoundYet({ detail }: { detail?: string | null }) {
  const t = useT();
  return (
    <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">
      <p className="text-sm font-medium text-foreground">{t("society.card.chat_empty_title")}</p>
      <p className="max-w-[30ch] text-xs text-muted-foreground">{detail ?? t("society.card.chat_empty_hint")}</p>
    </div>
  );
}

async function bindAgentChat(agentId: string): Promise<void> {
  const res = await fetch(`/api/society/agents/${encodeURIComponent(agentId)}/chat`, { method: "POST" });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
}

function SpecialistChat({ agent, roster, composerExtras }: AgentChatPanelProps) {
  const t = useT();
  const items = useAgentChat((s) => s.timeline.items);
  const activeSessionId = useAgentChat((s) => s.activeSessionId);
  const busy = useAgentChat((s) => s.busy);
  const lastError = useAgentChat((s) => s.lastError);
  const socketState = useAgentChat((s) => s.socketState);
  const loadCatalog = useAgentChat((s) => s.loadCatalog);
  const loadSessions = useAgentChat((s) => s.loadSessions);
  const openSession = useAgentChat((s) => s.openSession);
  const send = useAgentChat((s) => s.send);
  const cancel = useAgentChat((s) => s.cancel);
  const decide = useAgentChat((s) => s.decide);
  const [bindError, setBindError] = useState<string | null>(null);
  const sessionId = agent.chatSessionId;
  const sessionReady = Boolean(sessionId) && activeSessionId === sessionId;
  const visibleItems = itemsForOpenSession(sessionId, activeSessionId, items);
  const refreshedRoutineReceipts = useRef(new Set<string>());
  useEffect(() => {
    for (const item of visibleItems) {
      if (item.type === "turn") {
        for (const block of item.blocks) {
          if (block.kind !== "tool" || block.name !== "society_propose_change" || block.output === null || block.isError) continue;
          const input = block.input as { kind?: string; mode?: string } | null;
          if (input?.kind !== "routine" || input.mode !== "apply") continue;
          const key = `tool:${block.callId}`;
          if (refreshedRoutineReceipts.current.has(key)) continue;
          refreshedRoutineReceipts.current.add(key);
          notifyRoutineChanged(agent.agentId);
        }
      } else if (item.type === "notice" && item.kind === "proposal" && item.resolved === "applied" && item.data.proposal_kind === "routine") {
        const key = `proposal:${item.id}`;
        if (refreshedRoutineReceipts.current.has(key)) continue;
        refreshedRoutineReceipts.current.add(key);
        notifyRoutineChanged(agent.agentId);
      }
    }
  }, [visibleItems, agent.agentId]);
  const outgoing = useOutgoingMessages(sessionReady ? agent.agentId : null, sessionId);
  const allItems = useMemo(() => mergeOutgoingMessages(
    visibleItems, outgoing, agent.agentId, agent.name,
    new Map(roster.map((member) => [member.agentId, member.name])),
  ), [visibleItems, outgoing, agent.agentId, agent.name, roster]);
  const view = useTranscriptView(sessionReady ? sessionId : null, allItems);

  // Open the agent's own session before the browser paints. Waiting on bind /
  // catalog / sessions left the previous specialist's transcript on screen
  // under the new name.
  useLayoutEffect(() => {
    if (!sessionId) return;
    openSession(sessionId);
    // An agent on Hermes or OpenClaw starts its runtime while its chat is
    // read, not after the first message is sent.
    warmAgentChatSession(sessionId);
  }, [sessionId, openSession]);

  useEffect(() => {
    void loadCatalog();
    void loadSessions();
  }, [loadCatalog, loadSessions]);

  // Bind is idempotent and the session id is already on the roster row; a
  // failure must not replace a chat that is already open.
  useEffect(() => {
    let alive = true;
    setBindError(null);
    void bindAgentChat(agent.agentId).catch((err) => {
      if (alive) setBindError(err instanceof Error ? err.message : String(err));
    });
    return () => {
      alive = false;
    };
  }, [agent.agentId]);

  const mentionable = useMemo(
    () => roster.filter((a) => a.agentId !== agent.agentId && a.tier !== "lead"),
    [roster, agent.agentId],
  );
  const displayName = useRosterDisplayName(roster);

  return (
    <div
      className="flex h-full min-h-0 flex-col bg-background"
      data-testid="society-chat"
      data-session-id={sessionId ?? ""}
      data-session-ready={sessionReady ? "true" : "false"}
    >
      <AgentConversationsBar agentId={agent.agentId} agentName={agent.name} displayName={displayName} />
      <Transcript key={`${sessionId ?? agent.agentId}:${view.boundaryId}`} items={view.items} agent={agent} roster={roster} onDecide={decide}
        onRetry={sessionReady && !busy ? (text) => void send(text) : undefined} />
      {sessionReady && socketState !== "open" && socketState !== "idle" ? (
        <p role="status" className="px-4 pb-1 text-xs text-muted-foreground">
          {t(socketState === "closed" ? "society.chat.reconnecting" : "society.chat.connecting")}
        </p>
      ) : null}
      {lastError && sessionReady ? (
        <p role="alert" className="px-4 pb-1 text-xs text-destructive">
          {lastError}
        </p>
      ) : null}
      {bindError ? (
        <p role="alert" className="px-4 pb-1 text-xs text-destructive">
          {`${t("society.card.chat_bind_failed")} (${bindError})`}
        </p>
      ) : null}
      {composerExtras}
      <Composer
        key={agent.agentId}
        agent={agent}
        mentionable={mentionable}
        busy={busy || !sessionReady}
        sessionId={sessionReady ? activeSessionId : sessionId}
        cwd=""
        provider={agent.provider}
        surface="society"
        onClear={view.clear}
        onSend={send}
        onCancel={cancel}
      />
    </div>
  );
}

// ---------------------------------------------------------------------------
// the chat
// ---------------------------------------------------------------------------

function JarvisChat({ agent, roster }: AgentChatPanelProps) {
  const t = useT();
  const items = useAgentChat((s) => s.timeline.items);
  const activeSessionId = useAgentChat((s) => s.activeSessionId);
  const busy = useAgentChat((s) => s.busy);
  const lastError = useAgentChat((s) => s.lastError);
  const socketState = useAgentChat((s) => s.socketState);
  const draft = useAgentChat((s) => s.draft);
  const loadCatalog = useAgentChat((s) => s.loadCatalog);
  const loadSessions = useAgentChat((s) => s.loadSessions);
  const newChat = useAgentChat((s) => s.newChat);
  const send = useAgentChat((s) => s.send);
  const cancel = useAgentChat((s) => s.cancel);
  const decide = useAgentChat((s) => s.decide);
  const view = useTranscriptView(activeSessionId, items);

  useEffect(() => {
    void loadCatalog();
    void loadSessions();
  }, [loadCatalog, loadSessions]);

  // First time the lead's card opens on a fresh society: it offers a team.
  // The backend decides whether anything is offered and remembers that it
  // asked, so this may fire as often as it likes.
  useEffect(() => {
    if (onboardingAsked) return;
    onboardingAsked = true;
    void fetch("/api/society/onboarding/start", { method: "POST" })
      .then(() => loadSessions())
      .catch(() => undefined);
  }, [loadSessions]);

  const setActiveConversation = useEventStore((s) => s.setActiveConversation);
  const setMessages = useEventStore((s) => s.setMessages);
  // A null session is an intentional fresh chat. Only an explicit history
  // selection may open an older session; polling must not undo New chat.

  const mentionable = useMemo(() => roster.filter((a) => a.tier !== "lead"), [roster]);
  const displayName = useRosterDisplayName(roster);

  // Voice or typed — Jarvis' card only. The other agents have no voice: the
  // wake word, the realtime brain and the microphone belong to the lead.
  const mode = useJarvisCardMode();
  const pickMode = setJarvisCardMode;

  // A fresh page: no chat, no spoken thread — the composer below starts it.
  const startFresh = useCallback(() => {
    setActiveConversation("text", null);
    setMessages([]);
    newChat();
  }, [newChat, setActiveConversation, setMessages]);


  if (mode === "voice") {
    return (
      <div className="flex h-full min-h-0 flex-col" data-testid="society-chat" data-mode="voice">
        {/* A flex row, not the chat header's grid: the screen-reader note is
            absolutely positioned, so in a grid the switch fell into the first
            1fr track and stretched across it. */}
        <div className="flex shrink-0 justify-center px-4 pb-2">
          <span className="sr-only">{t("society.chat.voice_note")}</span>
          <JarvisModeSwitch mode={mode} onPick={pickMode} />
        </div>
        <VoiceStage />
      </div>
    );
  }

  const header = (
    <div className="grid shrink-0 grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-2 px-4 pb-2">
      <div className="flex min-w-0 items-center gap-1">
        <ModelPicker />
        <EffortPicker />
      </div>
      <JarvisModeSwitch mode={mode} onPick={pickMode} />
      <div className="flex items-center justify-end">
        <button
          type="button"
          onClick={startFresh}
          title={t("society.chat.new_chat")}
          aria-label={t("society.chat.new_chat")}
          className="as-round-button"
        >
          <RotateCcw className="h-3.5 w-3.5" aria-hidden />
        </button>
      </div>
    </div>
  );

  return (
    <div className="flex h-full min-h-0 flex-col bg-background" data-testid="society-chat" data-mode="chat">
      {header}
      <AgentConversationsBar agentId={agent.agentId} agentName={displayName(agent.agentId, agent.name)} displayName={displayName} />
      <Transcript key={`${activeSessionId ?? ""}:${view.boundaryId}`} items={view.items} agent={agent} roster={roster} onDecide={decide}
        onRetry={busy ? undefined : (text) => void send(text)} />
      {activeSessionId && socketState !== "open" && socketState !== "idle" ? (
        <p role="status" className="px-4 pb-1 text-xs text-muted-foreground">
          {t(socketState === "closed" ? "society.chat.reconnecting" : "society.chat.connecting")}
        </p>
      ) : null}
      {lastError ? (
        <p role="alert" className="px-4 pb-1 text-xs text-destructive">
          {lastError}
        </p>
      ) : null}
      <Composer
        agent={agent}
        mentionable={mentionable}
        busy={busy}
        sessionId={activeSessionId}
        cwd={draft.cwd}
        provider={draft.provider}
        onClear={view.clear}
        onSend={send}
        onCancel={cancel}
      />
    </div>
  );
}

// ---------------------------------------------------------------------------
// voice | chat — the lead's card only
// ---------------------------------------------------------------------------

/**
 * The same `Voice | Chat` idea as the sidebar's switch, scoped to the card:
 * it changes what THIS column shows and leaves the front page's own choice
 * alone. Voice is the front page's voice stage itself (the Jarvis bar, the
 * wake word, the realtime brain) — one voice, shown in a second place, never
 * a second microphone.
 */
function JarvisModeSwitch({ mode, onPick }: { mode: JarvisCardMode; onPick: (m: JarvisCardMode) => void }) {
  const t = useT();
  const tab = (value: JarvisCardMode, label: string) => (
    <button
      type="button"
      role="tab"
      aria-selected={mode === value}
      data-testid={`society-jarvis-mode-${value}`}
      onClick={() => onPick(value)}
      className="as-seg-pill"
    >
      {label}
    </button>
  );
  return (
    <div
      role="tablist"
      aria-label={t("society.chat.mode_hint")}
      className="as-seg-pills"
    >
      {tab("voice", t("society.chat.mode_voice"))}
      {tab("chat", t("society.chat.mode_chat"))}
    </div>
  );
}

// ---------------------------------------------------------------------------
// pickers
// ---------------------------------------------------------------------------

function ModelPicker() {
  const t = useT();
  const draft = useAgentChat((s) => s.draft);
  const providerOptions = useAgentChat((s) => s.providerOptions);
  const providerById = useAgentChat((s) => s.providerById);
  const liveModels = useAgentChat((s) => s.liveModels);
  const savedHidden = useSavedHiddenModels((s) => s.hidden);
  const loadModels = useAgentChat((s) => s.loadModels);
  const setDraft = useAgentChat((s) => s.setDraft);
  const locks = useAgentChat((s) => s.locks);
  const [open, setOpen] = useState(false);
  const [providerId, setProviderId] = useState<string | null>(null);
  const ref = useRef<HTMLDivElement>(null);

  const current = providerById(draft.provider);
  const chosen = providerId ? providerById(providerId) : current;
  const providers = providerOptions();
  const models = useMemo(() => {
    if (!chosen) return [];
    const seen = new Set<string>();
    const listed = [...(liveModels[chosen.id] ?? []), ...chosen.curated_models].filter((m) => {
      if (seen.has(m.id)) return false;
      seen.add(m.id);
      return true;
    });
    // Models switched off on the API Keys page stay out; the current pick stays.
    return offeredModels(chosen, listed, chosen.id === draft.provider ? draft.model : "", savedHidden);
  }, [chosen, liveModels, draft.provider, draft.model, savedHidden]);

  useEffect(() => {
    if (open && chosen && chosen.models_source === "live") void loadModels(chosen.id);
  }, [open, chosen, loadModels]);

  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", onDown);
    return () => document.removeEventListener("mousedown", onDown);
  }, [open]);

  const label = current ? current.label : t("society.chat.model_default");
  const modelLabel = draft.model || t("society.chat.model_provider_default");
  const locked = locks?.provider ?? locks?.model;

  return (
    <div ref={ref} className="relative">
      <button
        type="button"
        disabled={Boolean(locked)}
        title={locked ?? t("society.chat.model")}
        onClick={() => {
          setProviderId(current?.id ?? providers[0]?.id ?? null);
          setOpen((v) => !v);
        }}
        className="as-pill-button max-w-[320px] bg-transparent px-3 font-normal text-muted-foreground hover:text-foreground disabled:opacity-60"
      >
        <span className="truncate">{label}</span>
        <span className="truncate">{modelLabel}</span>
      </button>
      {open ? (
        <div className="as-menu absolute left-0 top-full z-20 mt-2 flex w-[460px] max-w-[80vw] overflow-hidden p-1.5">
          <ul className="max-h-72 w-1/2 overflow-y-auto border-r border-border py-1">
            {providers.map((p) => (
              <li key={p.id}>
                <button
                  type="button"
                  onClick={() => setProviderId(p.id)}
                  className={cn(
                    "flex w-full items-center gap-2 rounded-[10px] px-2.5 py-1.5 text-left text-[13px] hover:bg-secondary",
                    chosen?.id === p.id && "bg-secondary",
                    !p.connected && "opacity-50",
                  )}
                  title={p.connected ? p.label : t("society.card.not_connected")}
                >
                  <ProviderLogo providerId={p.id} label={p.label} size="sm" />
                  <span className="truncate">{p.label}</span>
                </button>
              </li>
            ))}
          </ul>
          <ul className="max-h-72 w-1/2 overflow-y-auto py-1">
            {chosen ? (
              <li>
                <button
                  type="button"
                  onClick={() => {
                    void setDraft({ provider: chosen.id, model: "" });
                    setOpen(false);
                  }}
                  className={cn(
                    "w-full rounded-[10px] px-2.5 py-1.5 text-left text-[13px] hover:bg-secondary",
                    draft.provider === chosen.id && !draft.model && "bg-secondary",
                  )}
                >
                  {t("society.chat.model_provider_default")}
                </button>
              </li>
            ) : null}
            {models.map((m) => (
              <li key={m.id}>
                <button
                  type="button"
                  onClick={() => {
                    void setDraft({ provider: chosen?.id ?? draft.provider, model: m.id });
                    setOpen(false);
                  }}
                  title={m.note}
                  className={cn(
                    "w-full rounded-[10px] px-2.5 py-1.5 text-left text-[13px] hover:bg-secondary",
                    draft.provider === chosen?.id && draft.model === m.id && "bg-secondary",
                  )}
                >
                  <span className="block truncate">{m.label}</span>
                  {m.note ? <span className="block truncate text-xs text-muted-foreground">{m.note}</span> : null}
                </button>
              </li>
            ))}
            {chosen && models.length === 0 ? (
              <li className="px-2.5 py-1.5 text-xs text-muted-foreground">{t("society.chat.models_loading")}</li>
            ) : null}
          </ul>
        </div>
      ) : null}
    </div>
  );
}

/** How hard the lead thinks: one quiet word that opens the levels. */
function EffortPicker() {
  const t = useT();
  const draft = useAgentChat((s) => s.draft);
  const providerById = useAgentChat((s) => s.providerById);
  const setDraft = useAgentChat((s) => s.setDraft);
  const locks = useAgentChat((s) => s.locks);
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const provider = providerById(draft.provider);
  const levels = provider?.effort_levels ?? [];
  useEffect(() => {
    if (!open) return;
    const onDown = (event: PointerEvent) => {
      if (!ref.current?.contains(event.target as Node)) setOpen(false);
    };
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") setOpen(false);
    };
    document.addEventListener("pointerdown", onDown, true);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("pointerdown", onDown, true);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);
  if (levels.length === 0) return null;
  const current = draft.effort || "";
  return (
    <div ref={ref} className="relative">
      <button type="button" aria-haspopup="menu" aria-expanded={open} disabled={Boolean(locks?.effort)}
        aria-label={`${t("society.chat.effort")}: ${current || t("society.chat.effort_default")}`}
        onClick={() => setOpen((value) => !value)}
        className="as-pill-button bg-transparent px-3 font-normal capitalize text-muted-foreground hover:text-foreground disabled:opacity-60">
        {current || t("society.chat.effort_default")}
      </button>
      {open ? (
        <div role="radiogroup" aria-label={t("society.chat.effort")} className="as-menu absolute left-0 top-full z-20 mt-2 w-44">
          {levels.map((level) => {
            const value = level || "";
            const on = current === value;
            return (
              <button
                key={level || "default"}
                type="button"
                role="radio"
                aria-checked={on}
                onClick={() => {
                  setOpen(false);
                  void setDraft({ effort: value });
                }}
                className={cn("as-menu-row capitalize", on && "bg-secondary")}
              >
                {level || t("society.chat.effort_default")}
              </button>
            );
          })}
        </div>
      ) : null}
    </div>
  );
}

// ---------------------------------------------------------------------------
// transcript
// ---------------------------------------------------------------------------

export function Transcript({
  items: rawItems,
  agent,
  roster,
  onDecide,
  onRetry,
}: {
  items: TimelineItem[];
  agent: SocietyAgent;
  roster: SocietyAgent[];
  onDecide: (approvalId: string, decision: ApprovalDecision) => Promise<void>;
  /** Sends a message of the person's again (a failed turn's "Retry"). */
  onRetry?: (text: string) => void;
}) {
  const t = useT();
  const sessionId = useAgentChat((state) => state.activeSessionId);
  // Memory receipts are drawn inside the turn they follow, above its reply.
  // A coding thread's unchanged status is one row, however often it arrived.
  // Applied identity changes stay in history without chat rows or timestamps.
  const { items, memoryByTurn } = useMemo(
    () => foldMemoryNotices(foldRepeatedThreadStatus(rawItems.filter((item) => !(
      item.type === "notice" && item.data.proposal_kind === "identity" && (
        item.kind === "proposal" && item.resolved === "applied"
        || item.kind === "proposal_resolved" && (!item.status || item.status === "applied")
      )
    )))),
    [rawItems],
  );
  // Follow the newest while the view sits at the end — the rule every
  // conversation surface shares (hooks/useStickToBottom). This used to scroll
  // a bottom sentinel into view on `[items.length, busy]` only, so a
  // reasoning trace or answer that STREAMS — growing in place, no new item —
  // never pulled the view along and the reader scrolled by hand. The hook
  // watches the content's own size too, so growth follows; scrolled up, the
  // reader keeps their place and gets a button back.
  const { rootRef, contentRef, atEnd, jumpToEnd, follow } = useStickToBottom();
  // The scroller itself too: past 80 px from the end it offers the way back.
  const [scroller, setScroller] = useState<HTMLElement | null>(null);
  const setRoot = useCallback((node: HTMLDivElement | null) => {
    rootRef(node);
    setScroller(node);
  }, [rootRef]);
  const far = useFarFromEnd(scroller);
  const unseen = useUnseen(items, atEnd);
  // A stamp marks a pause of 15 minutes or a new day, before a speaker's run.
  const stamps = useMemo(() => stampPlan(items.map(stampEntry)), [items]);
  const assistantName = useEventStore((state) => state.assistantName);
  // "Writing to Scout": a teammate by the name and face a person knows.
  const memberOf = useCallback((value: string) => {
    const key = value.trim().toLowerCase();
    return roster.find((a) => a.agentId === value || a.name.toLowerCase() === key);
  }, [roster]);
  const nameOf = useCallback((value: string) => {
    const member = memberOf(value);
    return member ? societyDisplayName(member, assistantName) : value;
  }, [memberOf, assistantName]);
  const peerFace = useCallback((value: string) => {
    const member = memberOf(value);
    return member ? <AgentSwatch agent={{ ...member, state: undefined }} size={16} /> : null;
  }, [memberOf]);
  // The work inspector: one turn's whole trace beside the conversation.
  // Opened on the newest turn it follows each new one; opened on an older turn it stays there.
  const { inspecting, open: setInspecting, close: closeInspector } = useInspectedTurn(items);
  const inspectedAt = inspecting ? items.findIndex((item) => item.type === "turn" && item.id === inspecting) : -1;
  const inspected = inspectedAt >= 0 ? items[inspectedAt] as TurnItem : null;
  const inspectedPrompt = useMemo(() => {
    for (let i = inspectedAt - 1; i >= 0; i--) {
      const item = items[i];
      if (item.type === "user") return visibleUserText(item.text);
      if (item.type === "turn") break;
    }
    return undefined;
  }, [items, inspectedAt]);
  const [inspectorWidth, setInspectorWidth] = useState(readInspectorWidth);
  const onInspectorWidth = useCallback((width: number) => {
    setInspectorWidth(width);
    writeInspectorWidth(width);
  }, []);
  const [frame, setFrame] = useState<HTMLDivElement | null>(null);
  const [frameWidth, setFrameWidth] = useState(0);
  // Measured only while the inspector is open: a closed one costs nothing.
  const inspectorOpen = inspected !== null;
  useEffect(() => {
    if (!frame || !inspectorOpen) return;
    setFrameWidth(frame.clientWidth);
    if (typeof ResizeObserver === "undefined") return;
    const ro = new ResizeObserver(() => setFrameWidth(frame.clientWidth));
    ro.observe(frame);
    return () => ro.disconnect();
  }, [frame, inspectorOpen]);
  const docked = frameWidth > 0 && inspectorDocked(frameWidth, inspectorWidth);
  // The person's bubbles wear the colour of the agent they talk to.
  const tint = useMemo(() => bubbleTint(agentColor(agent)), [agent]);
  // `items` itself, not its length: a reasoning trace or tool row grows
  // the same turn in place, so the length does not change. Pin in this
  // layout pass — waiting for ResizeObserver is one frame too late, and
  // that frame is when overflow anchoring would unstick the view.
  useLayoutEffect(follow, [follow, items]);
  // A message of the person's with no turn after it yet: the agent is reading it.
  const lastItem = items[items.length - 1];
  const awaiting = lastItem?.type === "user" && lastItem.origin !== "control" && !assignmentOf(lastItem.text) ? lastItem : null;

  if (items.length === 0) {
    return (
      <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 p-6 text-center">
        <AgentSwatch agent={agent} size={56} />
        <p className="text-sm font-medium text-foreground">{t("society.chat.empty_title").replace("{0}", agent.name)}</p>
        <p className="max-w-[32ch] text-xs text-muted-foreground">{t("society.chat.empty_hint")}</p>
      </div>
    );
  }

  const displayName = societyDisplayName(agent, assistantName);
  const retry = onRetry ? retryOf(items, onRetry) : null;
  return (
    <div ref={setFrame} className="relative flex min-h-0 flex-1">
      <div className="relative flex min-h-0 min-w-0 flex-1 flex-col">
        <div ref={setRoot} className="chat-scroller min-h-0 flex-1 overflow-y-auto px-4 py-5 sm:px-6" data-testid="society-transcript">
          <div ref={contentRef} className={cn(CHAT_MEASURE, "flex flex-col gap-3")}>
          {items.map((item, index) => {
            const stamp = stamps.has(item.id) ? (item.type === "turn" ? item.startedMs : item.tsMs) : 0;
            // The live turn glides to its new height as it grows.
            const live = index === items.length - 1 && item.type === "turn" && item.status === "running";
            const body = item.type === "internal" ? (
              <AgentMessageActivity item={item} roster={roster} />
            ) : item.type === "user" && assignmentOf(item.text) ? (
              <DelegationActivity {...assignmentOf(item.text)!} roster={roster} />
            ) : item.type === "user" && item.teamEvent ? (
              <TeamEventLine event={item.teamEvent} text={item.text} />
            ) : item.type === "user" ? (
              <UserBubble item={item} agentId={agent.agentId} sessionId={sessionId ?? agent.chatSessionId ?? undefined} tint={tint} />
            ) : item.type === "turn" ? (
              <TurnBubble item={item} agent={agent} memory={memoryByTurn.get(item.id)} onDecide={onDecide}
                nameOf={nameOf} peerFace={peerFace} workOpen={inspecting === item.id} onShowWork={setInspecting}
                onRetry={retry?.turnId === item.id ? retry.run : undefined} />
            ) : item.type === "notice" ? (
              item.kind === "proposal" ? (
                <ProposalCard item={item} />
              ) : (
                <NoticeLine item={item} />
              )
            ) : (
              <p className="self-start rounded-2xl bg-destructive/10 px-3 py-2 text-xs text-destructive">{item.text}</p>
            );
            return (
              <div key={item.id} data-chat-item={item.id} className="flex flex-col gap-2">
                {stamp ? <TranscriptStamp ms={stamp} /> : null}
                {/* A turn always sits in its settle box, so finishing (or a
                    notice arriving after it) never remounts it mid-flight. */}
                {item.type === "turn" ? <SettleBox active={live}>{body}</SettleBox> : body}
              </div>
            );
          })}
          {awaiting ? <AwaitingTurn since={awaiting.tsMs} seed={awaiting.id}
            avatar={<AgentSwatch agent={{ ...agent, state: undefined }} size={28} expressive />} color={agentColor(agent)} /> : null}
          </div>
        </div>
        {/* Scrolled up: what arrived meanwhile, else simply the way back. */}
        {!atEnd && unseen.count > 0
          ? <CatchUpPill count={unseen.count} onJump={jumpToEnd} onDismiss={unseen.dismiss} />
          : !atEnd && far ? <ScrollToEndButton onClick={jumpToEnd} testId="society-scroll-end" className="top-auto bottom-3" /> : null}
        <RunAnnouncer items={items} agentName={displayName} />
      </div>
      {inspected ? <WorkInspector turn={inspected} prompt={inspectedPrompt} agentName={displayName}
        color={agentColor(agent)} avatar={<AgentSwatch agent={{ ...agent, state: undefined }} size={24} />}
        width={docked || frameWidth === 0 ? inspectorWidth : Math.min(inspectorWidth, Math.max(280, frameWidth - 24))}
        onWidth={onInspectorWidth} floating={!docked} onClose={closeInspector} /> : null}
    </div>
  );
}

/**
 * A delegated task coming back: the agent's name as the headline, its
 * summary underneath, muted — it is the society reporting, not Jarvis
 * speaking, so it never wears an assistant bubble.
 */
export function NoticeLine({ item }: { item: NoticeItem }) {
  const t = useT();
  if (item.kind === "memory_updated") return <MemoryUpdateNotice item={item} />;
  if (item.kind === "team_report") return <TeamReportNotice item={item} />;
  if (item.kind === "message_queued") {
    return <p className="self-end py-1 text-xs text-muted-foreground" data-testid="message-queued">
      {t("society.chat.message_waiting")} · {item.text}
    </p>;
  }
  if (item.kind === "message_dequeued") {
    return <p role="alert" className="self-end py-1 text-xs text-destructive">
      {t("society.chat.message_not_sent").replace("{0}", item.text)}
    </p>;
  }
  if (item.kind === "context_rollover") {
    return <p className="py-1 text-center text-[12px] text-muted-foreground">{t("society.chat.context_rollover")}</p>;
  }
  if (item.kind === "runtime_setup") {
    const runtime = String(item.data.runtime ?? "");
    return <p className="py-1 text-center text-[12px] text-muted-foreground" data-testid="runtime-setup-notice">
      {runtime ? t("society.runtime.setting_up_chat").replace("{0}", t(`society.runtime.${runtime}`)) : item.text}
    </p>;
  }
  if (item.kind === "stop_reason") {
    // A runtime turn that ended early: the answer above stands, but is cut off.
    const reason = String(item.data.stop_reason ?? "");
    const known = ["max_tokens", "max_turn_requests", "cancelled"].includes(reason);
    return <p role="note" className="py-1 text-xs italic text-muted-foreground" data-testid="stop-reason-notice">
      {known ? t(`society.chat.stop_reason_${reason}`) : item.text}
    </p>;
  }
  if (item.kind === "routine_runtime_fallback") {
    const runtime = String(item.data.runtime ?? "");
    return <p className="py-1 text-center text-[12px] text-muted-foreground" data-testid="routine-runtime-fallback">
      {runtime ? t("society.runtime.routine_fallback").replace(/\{0\}/g, t(`society.runtime.${runtime}`)) : item.text}
    </p>;
  }
  if (item.kind === "routine_run") {
    const sessionId = String(item.data.session_id ?? "");
    const agentId = item.agentId || String(item.data.agent_id ?? "");
    // The routine's own name labels the run; older notices fall back to its first line.
    const name = String(item.data.title ?? "").trim() || item.text;
    return <RoutineActivity task={name} original={item.text}
      onOpen={sessionId && agentId ? () => useRoutineNavigation.getState().open({
        agentId, sessionId, title: name, timestamp: item.tsMs,
      }) : undefined} />;
  }
  if (item.kind === "coding_thread") {
    const label = t("society.chat.coding_thread_started").replace("{0}", String(item.data.agent ?? ""));
    return <CodingThreadActivity label={`${label} · ${String(item.data.title ?? "")}`} threadId={String(item.data.thread_id ?? "")} />;
  }
  if (item.kind === "native_goal_verdict") return <p className="py-1 text-xs text-muted-foreground">{t("slash.verifying")}</p>;
  const headline =
    item.kind === "society_result"
      ? societyResultHeadline(t, item)
      : item.agentName;
  return (
    <ChatActivity label={headline || item.text.split("\n")[0]} failed={item.status === "blocked" || item.resolved === "failed"}>
      {item.text ? <ChatMarkdown text={item.kind === "society_result" ? societyResultText(t, item) : item.text} className="leading-relaxed" /> : null}
    </ChatActivity>
  );
}

/** One human-readable line per proposal kind, read off the typed payload. */
function proposalDetail(kind: string, payload: Record<string, unknown>, t: (key: string) => string): string {
  const list = (v: unknown): string => (Array.isArray(v) ? v.map(String).join(", ") : "");
  switch (kind) {
    case "rule":
      return String(payload.text ?? "");
    case "skill":
      return `${String(payload.name ?? "")}: ${String(payload.goal ?? "")}`;
    case "routine": {
      const schedule = (payload.schedule ?? {}) as Record<string, unknown>;
      const when = Object.entries(schedule)
        .map(([k, v]) => `${k}=${String(v)}`)
        .join(" ");
      return `${String(payload.title ?? "")} — ${when}`;
    }
    case "approval_rule": {
      const parts: string[] = [];
      if (list(payload.require_approval)) parts.push(fill(t("society.chat.proposal_ask_first"), { tools: list(payload.require_approval) }));
      if (list(payload.always_allow)) parts.push(fill(t("society.chat.proposal_always_allow"), { tools: list(payload.always_allow) }));
      return parts.join(" · ");
    }
    case "focus":
      return list(payload.focus);
    case "team":
      return list(payload.names);
    case "identity":
      return [payload.name, payload.title, payload.description]
        .filter((part) => typeof part === "string" && part)
        .map(String)
        .join(" — ");
    default:
      return "";
  }
}

/**
 * The agent proposed a change to itself (a standing rule, a skill, a routine,
 * approval rules, its focus). Nothing has changed yet: the person decides here,
 * and the outcome patches this same card.
 */
function ProposalCard({ item }: { item: NoticeItem }) {
  const t = useT();
  const resolve = useResolveProposal();
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const kind = String(item.data.proposal_kind ?? "");
  const proposalId = String(item.data.proposal_id ?? "");
  const summary = String(item.data.summary ?? item.text);
  const reason = String(item.data.reason ?? "");
  const payload = (item.data.payload ?? {}) as Record<string, unknown>;
  const detail = proposalDetail(kind, payload, t);
  const outcome = item.text.includes("\n") ? item.text.slice(item.text.indexOf("\n") + 1) : "";
  // A team offer is a pick list: everyone is proposed, the person keeps the
  // ones they want and the picked names ride along in the decision's note.
  const offered = useMemo(() => {
    const rows = (payload.proposals ?? []) as { name?: string; title?: string }[];
    if (rows.length > 0) return rows.map((r) => ({ name: String(r.name ?? ""), title: String(r.title ?? "") }));
    return ((payload.names ?? []) as string[]).map((n) => ({ name: String(n), title: "" }));
  }, [payload]);
  const [picked, setPicked] = useState<string[] | null>(null);
  const chosen = picked ?? offered.map((o) => o.name);
  const decide = async (approve: boolean) => {
    setBusy(true);
    setError("");
    try {
      await resolve(proposalId, approve, kind === "team" && approve ? chosen.join(", ") : "");
      markAnswered(proposalId);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setBusy(false);
    }
  };
  const resolvedLabel =
    item.resolved === "applied"
      ? t("society.chat.proposal_applied")
      : item.resolved === "rejected"
        ? t("society.chat.proposal_rejected")
        : item.resolved
          ? t("society.chat.proposal_failed")
          : "";
  const kindLabel = kind ? t(`society.chat.proposal_kind_${kind}`) : "";
  const title = t("society.chat.proposal_title").replace("{0}", item.agentName || t("society.chat.result_agent"));
  const source = { icon: <ProposalIcon strokeWidth={1.75} />, label: kindLabel || t("action_card.source.proposal") };
  if (item.resolved) {
    // Decided: one line that says what happened, the proposal itself one click away.
    return <ActionCard
      id={`proposal:${proposalId || item.id}`}
      testId="proposal-card"
      state={item.resolved}
      source={source}
      title={title}
      ariaLabel={`${resolvedLabel}: ${summary}`}
      settled={{
        tone: item.resolved === "applied" ? "success" : item.resolved === "rejected" ? "muted" : "danger",
        label: resolvedLabel,
        detail: summary,
        body: <>
          <p className="m-0 whitespace-pre-wrap text-xs leading-5 text-foreground-secondary">{detail || summary}</p>
          {reason ? <p className="m-0 text-xs leading-5 text-muted-foreground">{reason}</p> : null}
          {outcome ? <p className={cn("m-0 text-xs leading-5", item.resolved === "failed" ? "text-destructive" : "text-muted-foreground")}>{outcome}</p> : null}
        </>,
      }}
    />;
  }
  const actions: ActionSpec[] = [
    { id: "confirm", label: t("society.chat.proposal_confirm"), tone: "primary", onSelect: () => void decide(true), disabled: busy || (kind === "team" && chosen.length === 0) },
    { id: "reject", label: t("society.chat.proposal_reject"), tone: "tertiary", onSelect: () => void decide(false), disabled: busy },
  ];
  return (
    <ActionCard
      id={`proposal:${proposalId || item.id}`}
      testId="proposal-card"
      source={source}
      title={title}
      ariaLabel={`${t("society.chat.proposal_pending")}: ${title}`}
      lines={reason ? [<><span className="font-medium text-foreground-secondary">{t("society.chat.proposal_reason")}: </span>{reason}</>] : undefined}
      actions={actions}
      failure={error || null}
      note={t("society.chat.proposal_pending")}
      className="self-start"
    >
      {kind === "team" ? (
        <ul className="m-0 flex list-none flex-col gap-1 p-0">
          {offered.map((row) => (
            <li key={row.name} className="flex items-center gap-2 text-sm">
              <input
                type="checkbox"
                id={`${proposalId}-${row.name}`}
                checked={chosen.includes(row.name)}
                disabled={busy}
                onChange={(e) =>
                  setPicked(
                    e.target.checked
                      ? [...chosen, row.name]
                      : chosen.filter((name) => name !== row.name),
                  )
                }
                className="h-3.5 w-3.5 accent-[hsl(var(--primary))]"
              />
              <label htmlFor={`${proposalId}-${row.name}`} className="cursor-pointer text-foreground">
                <span className="font-medium">{row.name}</span>
                {row.title ? <span className="text-muted-foreground"> — {row.title}</span> : null}
              </label>
            </li>
          ))}
        </ul>
      ) : (
        <p className="m-0 whitespace-pre-wrap text-sm leading-relaxed text-foreground">{detail || summary}</p>
      )}
    </ActionCard>
  );
}

/** What the person typed, without the routing hints the composer added. */
function visibleUserText(text: string): string {
  return text
    .split("\n")
    .filter((line) => !line.trimStart().startsWith(DELEGATE_MARK))
    .filter((line) => !line.trimStart().startsWith(MENTION_MARK))
    .filter((line) => !line.trimStart().startsWith(TOOL_PIN_MARK))
    .filter((line) => !line.trimStart().startsWith("[coding-agent]"))
    .join("\n")
    .trimEnd();
}

/**
 * The person's message: a bubble on the right in the agent's colour, with ink
 * chosen for that colour (`bubbleTint`). Without an agent colour (a meeting
 * of several agents) it wears the app's accent.
 */
export function UserBubble({ item, agentId, sessionId, tint }: { item: UserItem; agentId?: string; sessionId?: string; tint?: BubbleTint | null }) {
  const t = useT();
  const choices = messageChoices(item);
  const text = visibleUserText(item.text);
  if (item.origin === "control") return <div className="self-start px-1 py-2 text-xs text-muted-foreground">{t("slash.control_turn")}{item.attachments.map((file) => <span key={file.name} className="ml-2">{file.name}</span>)}</div>;
  const task = routineTask(item.text);
  if (task !== null && item.attachments.length === 0) return <RoutineActivity task={task} original={item.text}
    onOpen={agentId && sessionId ? () => useRoutineNavigation.getState().open({
      agentId, sessionId, title: task.split(/\r?\n/)[0], timestamp: item.tsMs,
      ...(!sessionId.includes(":routine:") ? { legacy: { taskId: routineTaskId(item.text)!, messageId: item.id } } : {}),
    }) : undefined} />;
  return (
    <div className="flex min-w-0 max-w-[min(85%,42rem)] flex-col items-end gap-1 self-end">
      <div
        data-testid="user-bubble"
        className={cn("jarvis-chat-tinted min-w-0 rounded-[20px] px-4 py-2.5 text-base leading-6 [overflow-wrap:anywhere]", !tint && "jarvis-chat-out")}
        style={tint ? { background: tint.background, color: tint.color } : undefined}
      >
        <MessageWithChips text={text} choices={choices} />
      </div>
      {item.attachments.length > 0 ? (
        <div className="flex flex-wrap justify-end gap-1">
          {item.attachments.map((a) => (
            a.url && (a.kind === "image" || mediaKind(a.url)) ? <MediaPreview key={a.name} src={a.url} label={a.name} kind={mediaKind(a.url) ?? "image"} /> : <span key={a.name} className="rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">
              {a.name}
            </span>
          ))}
        </div>
      ) : null}
    </div>
  );
}

/**
 * The "Retry" of the transcript: only its latest turn, only when that turn
 * failed, and it sends the message of the person's that started it again.
 */
export function retryOf(items: readonly TimelineItem[], send: (text: string) => void): { turnId: string; run: () => void } | null {
  let turn: TurnItem | null = null;
  for (let i = items.length - 1; i >= 0; i -= 1) {
    const item = items[i];
    if (!turn) {
      if (item.type === "turn") {
        const silent = !item.blocks.some((block) => block.kind === "text" && block.text.trim());
        if (item.status !== "error" && !(item.status === "done" && silent && item.error)) return null;
        turn = item;
      } else if (item.type === "user" && item.origin !== "control") {
        return null;
      }
      continue;
    }
    if (item.type === "user" && !item.origin && item.text.trim() && !assignmentOf(item.text) && !item.teamEvent) {
      const text = item.text;
      const turnId = turn.id;
      return { turnId, run: () => send(text) };
    }
    if (item.type === "turn") return null;
  }
  return null;
}

function TurnBubble({
  item,
  agent,
  memory,
  onDecide,
  nameOf,
  peerFace,
  workOpen,
  onShowWork,
  onRetry,
}: {
  item: TurnItem;
  agent: SocietyAgent;
  memory?: NoticeItem[];
  onDecide: (approvalId: string, decision: ApprovalDecision) => Promise<void>;
  nameOf?: (idOrName: string) => string;
  peerFace?: (peer: string) => ReactNode;
  workOpen?: boolean;
  /** Opens the work inspector on a turn (by its id). */
  onShowWork?: (turnId: string) => void;
  onRetry?: () => void;
}) {
  const t = useT();
  const [openId, setOpenId] = useState<string | null>(null);
  const memoryLinks = useMemo<MemoryLink[] | undefined>(
    () => memory?.flatMap((notice) => {
      const path = memoryNoticePath(notice);
      return path ? [{ key: notice.id, title: memoryNoticeTitle(t, path), onOpen: () => setOpenId(notice.id) }] : [];
    }),
    [memory, t],
  );
  const opened = openId ? memory?.find((notice) => notice.id === openId) : undefined;
  const face = useMemo(() => <AgentSwatch agent={{ ...agent, state: undefined }} size={28} expressive />, [agent]);
  const showWork = useMemo(() => onShowWork ? () => onShowWork(item.id) : undefined, [onShowWork, item.id]);
  // An agent's turn reads like a messenger: its messages, what it changed,
  // and while it works its face with a word for what it is doing.
  // The face stays a face: the effect beside it says what it is doing, so
  // the swatch's own "working" dots would only repeat it.
  return <>
    <MessengerTurn turn={item} avatar={face} color={agentColor(agent)} onDecide={onDecide} memoryLinks={memoryLinks}
      nameOf={nameOf} peerFace={peerFace} onShowWork={showWork} workOpen={workOpen} onRetry={onRetry} />
    {opened && <MemoryNoticeViewer item={opened} onClose={() => setOpenId(null)} />}
  </>;
}

/**
 * Markdown as prose, not as marks.
 *
 * Models write in Markdown — an answer or a thought rendered without a
 * typography scale shows raw `**like this**` and runs its lists together.
 * One scale serves both here: the answer inherits the bubble's ink, the
 * thought passes `muted`, and nothing else differs.
 */
export function Prose({ text, muted }: { text: string; muted?: boolean }) {
  return (
    <div
      className={cn(
        "prose prose-neutral max-w-none dark:prose-invert [overflow-wrap:anywhere]",
        muted ? "text-xs leading-relaxed text-muted-foreground" : "text-sm leading-relaxed text-foreground",
        "prose-p:my-1.5 first:prose-p:mt-0 last:prose-p:mb-0",
        "prose-headings:my-2 prose-headings:text-[1em] prose-headings:font-semibold prose-headings:text-foreground",
        "prose-strong:font-semibold prose-strong:text-foreground",
        "prose-ul:my-1.5 prose-ol:my-1.5 prose-li:my-0.5",
        "prose-a:text-primary prose-a:underline prose-a:underline-offset-2",
        "prose-code:rounded prose-code:bg-secondary prose-code:px-1 prose-code:py-0.5 prose-code:font-mono",
        "prose-code:text-[0.9em] prose-code:font-normal prose-code:before:hidden prose-code:after:hidden",
        "prose-pre:my-2 prose-pre:rounded-xl prose-pre:bg-background prose-pre:p-3 prose-pre:text-xs prose-pre:text-foreground",
        "prose-hr:my-3 prose-blockquote:border-l-2 prose-blockquote:pl-3 prose-blockquote:not-italic",
      )}
    >
      <ChatMarkdown text={text} />
    </div>
  );
}

// ---------------------------------------------------------------------------
// composer
// ---------------------------------------------------------------------------

interface ComposerProps {
  onClear?: () => void;
  agent: SocietyAgent;
  mentionable: SocietyAgent[];
  busy: boolean;
  sessionId: string | null;
  cwd: string;
  provider: string;
  /** Which chat surface the attachments belong to (the front page by default). */
  surface?: AgentChatSurface;
  onSend: (text: string, attachments?: ReturnType<typeof useChatAttachments>["attachments"]) => Promise<void | "sent" | "failed" | "stale">;
  onCancel: () => Promise<void>;
}

export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, surface = "jarvis", onClear, onSend, onCancel }: ComposerProps) {
  const t = useT();
  const chatStore = useAgentChatApi();
  const [ownModelSaving, setModelSaving] = useState(false);
  // The Agents header may carry the brain picker; then it owns the save state.
  const headerModel = useHeaderModelSlot();
  const modelSaving = ownModelSaving || Boolean(headerModel?.saving);
  const messageDraft = useComposerDraft(chatStore, sessionId);
  const value = messageDraft.text;
  const setValue = (text: string) => writeComposerDraft(chatStore, sessionId, {
    ...readComposerDraft(chatStore, sessionId), text,
  });
  const [plusOpen, setPlusOpen] = useState(false);
  const plusRef = useRef<HTMLDivElement>(null);
  const [problem, setProblem] = useState<string | null>(null);
  const [mention, setMention] = useState<{ query: string; start: number } | null>(null);
  const [activeIndex, setActiveIndex] = useState(0);
  const fieldRef = useRef<ComposerChipFieldHandle>(null);
  const composerRef = useRef<HTMLDivElement>(null);
  const fileInput = useRef<HTMLInputElement>(null);
  const attachments = useChatAttachments({ sessionId, cwd, provider, surface }, (message) => setProblem(message),
    { owner: chatStore, key: sessionId ?? "" });
  useLayoutEffect(() => {
    const field = fieldRef.current;
    const current = field?.getDraft();
    if (current && (current.text !== messageDraft.text || JSON.stringify(current.choices) !== JSON.stringify(messageDraft.choices))) {
      field?.hydrate(messageDraft.text, messageDraft.choices);
    }
  }, [messageDraft, sessionId]);
  const commands = useChatCommands({ value, agentId: agent.agentId, onClear,
    attachments: attachments.attachments, attachmentsBusy: attachments.analyzing > 0, onAttachmentsSent: attachments.clear,
    setValue: (next) => { setValue(next); fieldRef.current?.setText(next); },
    onModel: () => composerRef.current?.querySelector<HTMLButtonElement>("[data-chat-model-trigger]")?.click(),
  });
  const dictation = useComposerDictation((next) => {
    const text = typeof next === "function" ? next(value) : next;
    setValue(text);
    fieldRef.current?.setText(text);
  }, () => void submit());
  const timeline = useAgentChat((s) => s.timeline);
  // A card waiting on the person: the composer becomes a second way to answer it.
  const openAsk = useMemo(() => openQuestionOf(timeline), [timeline]);
  const sending = useAgentChat((s) => s.busy);
  // Track HTTP admission and running work independently of composer readiness.
  const live = runningTurn(timeline) !== null || sending;
  // Admission is serialized by the store; execution waits in the backend.
  // A pending HTTP request or credential card does not lock this composer.
  const canQueue = surface === "jarvis" || surface === "society";
  const sessionReady = surface !== "society" || Boolean(sessionId && chatStore.getState().activeSessionId === sessionId);

  // "@" completes teammates AND the capability catalog — plugins, MCP
  // servers, CLIs, skills, Jarvis tools — on every agent card, including
  // Jarvis'. Naming one pins it for the turn (see `submit`).
  const [codingAgents, setCodingAgents] = useState<AgentStatus[]>([]);
  const [codingLoading, setCodingLoading] = useState(false);
  const [codingError, setCodingError] = useState(false);
  const [codingRetry, setCodingRetry] = useState(0);
  const [codingFolder, setCodingFolder] = useState("");
  const mentionOpen = mention !== null;
  useEffect(() => {
    if (!mentionOpen) return;
    let current = true;
    setCodingLoading(true);
    setCodingError(false);
    void fetchIdeAgents().then((result) => {
      if (current) setCodingAgents(result.terminal_available ? result.agents : []);
    }).catch(() => { if (current) setCodingError(true); })
      .finally(() => { if (current) setCodingLoading(false); });
    return () => { current = false; };
  }, [mentionOpen, codingRetry]);
  const capabilities = useSocietyCapabilities(true, mentionOpen);
  const catalog = useMemo(
    () => buildMentionCatalog(mentionable, capabilities.data ?? [], codingAgents, capabilities.plugins ?? []),
    [mentionable, capabilities.data, codingAgents, capabilities.plugins],
  );
  const codingSelections = useMemo(() => codingMentionsInText(value, catalog), [value, catalog]);
  useEffect(() => { if (!codingSelections.length) setCodingFolder(""); }, [codingSelections.length]);
  const matches = useMemo(
    () => (mention ? filterMentions(catalog, mention.query) : []),
    [mention, catalog],
  );

  useEffect(() => {
    setActiveIndex(0);
  }, [mention?.query, mention?.start]);
  useEffect(() => {
    if (activeIndex >= matches.length) setActiveIndex(Math.max(0, matches.length - 1));
  }, [matches.length, activeIndex]);

  const onDraftChange = (draft: ComposerDraft) => {
    writeComposerDraft(chatStore, sessionId, { text: draft.text, choices: draft.choices });
    setMention(mentionToken(draft.text, draft.caret));
  };

  const insertMention = (item: MentionItem) => {
    if (item.kind === "coding" && !item.connected) return;
    const field = fieldRef.current;
    const draft = field?.getDraft();
    const start = mention?.start ?? draft?.caret ?? value.length;
    const caret = draft?.caret ?? value.length;
    const before = (draft?.text ?? value).slice(0, start);
    const after = (draft?.text ?? value).slice(caret);
    if (item.agent || item.codingAgent) {
      const next = `${before}@${item.value} ${after}`;
      field?.hydrate(next, draft?.choices ?? []);
    } else {
      const row = mentionChoice(item);
      const next = `${before}${choiceToken(row)} ${after}`;
      field?.hydrate(next, [...(draft?.choices ?? []), row]);
    }
    setMention(null);
  };

  const submit = async () => {
    if (await commands.execute(fieldRef.current?.getDraft().text.trim() ?? value.trim())) return;
    const draft = fieldRef.current?.getDraft();
    const fullDraft = draft?.text ?? value;
    const draftText = fullDraft.trim();
    const submittedFolder = codingFolder;
    const text = draftText;
    if ((!text && attachments.attachments.length === 0) || !sessionReady || (busy || live) && !commands.canSteer && !canQueue || modelSaving || attachments.analyzing > 0) return;
    const chosenIds = new Set((draft?.choices ?? []).map((row) => row.id));
    const chosen = [...chosenIds].map((id) => catalog.find((item) => item.key === id));
    if (chosen.some((item) => !item || !item.connected)) {
      setProblem(t("common.error_generic"));
      return;
    }
    // Chips hold stable catalog IDs, even if new entries have changed short tags.
    const chosenTags = new Set((draft?.choices ?? []).map((row) => choiceToken(row).toLowerCase()));
    const unselectedText = text.replace(/(^|\s)(@[^\s@]+)/g, (whole, space: string, token: string) =>
      chosenTags.has(token.toLowerCase()) ? space : whole,
    );
    const named = mentionsInText(unselectedText, catalog);
    named.pinIds = [...new Set([...named.pinIds, ...chosen.flatMap((item) => item?.pinIds ?? [])])];
    const lines: string[] = [];
    if (named.agents.length > 0 && surface === "society") {
      const teammates = named.agents.map((a) => `${JSON.stringify(a.name)} (id ${JSON.stringify(a.agentId)})`).join(", ");
      lines.push(
        `${MENTION_MARK} Current sender: the user. Current recipient: ${JSON.stringify(agent.name)} (id ${JSON.stringify(agent.agentId)}). ` +
        `Mentioned teammates: ${teammates}. For teammate contact requested by the user, use society_message_agent; ` +
        "use kind 'query' when asking for information. If a work assignment is needed, contact the lead or an orchestrator with that tool. " +
        "Reply to the user here. An @mention or prose addressed to a teammate does not deliver a message.",
      );
    } else if (surface === "jarvis") {
      lines.push(...named.agents.map(
        (a) => `${DELEGATE_MARK} ${t("society.chat.delegate_line").replace("{0}", a.name).replace("{1}", a.agentId)}`,
      ));
    }
    if (named.pinIds.length > 0) lines.push(`${TOOL_PIN_MARK} ${named.pinIds.join(", ")}]`);
    const codingHint = codingAssignmentHint(codingSelections, codingFolder);
    if (codingHint) lines.push(codingHint);
    const hint = lines.join("\n");
    setProblem(null);
    const answerByMessage = chatStore.getState().answerByMessage;
    if (openAsk && answerByMessage && text && !hint && attachments.attachments.length === 0) {
      writeComposerDraft(chatStore, sessionId, { text: "", choices: [] });
      fieldRef.current?.clear();
      // A running turn took the message as its answer: nothing else to send.
      if (await answerByMessage(text)) return;
    }
    const held = attachments.take();
    if (!text && held.attachments.length === 0) return;
    const draftTarget = captureComposerDraftTarget(chatStore, sessionId);
    const sentDraft = { text: fullDraft, choices: draft?.choices ?? messageDraft.choices };
    writeComposerDraft(chatStore, sessionId, { text: "", choices: [] });
    fieldRef.current?.clear();
    setMention(null);
    setCodingFolder("");
    try {
      const result = await onSend(hint ? `${text}\n\n${hint}` : text, held.attachments);
      const sendError = chatStore.getState().lastError;
      if (result === "failed" || result === undefined && sendError) throw new Error(sendError ?? t("common.error_generic"));
      releaseHeldFiles(held);
    } catch (err) {
      if (draftTarget.superseded) {
        releaseHeldFiles(held);
        useEventStore.getState().pushToast("error", t("society.chat.message_not_sent").replace("{0}", sentDraft.text));
        return;
      }
      // Restore only this submission's draft, even after changing agents.
      // Preserve anything typed while the HTTP request was pending.
      const current = readComposerDraft(chatStore, draftTarget.sessionId);
      writeComposerDraft(chatStore, draftTarget.sessionId, {
        text: [sentDraft.text, current.text].filter(Boolean).join("\n"),
        choices: [...sentDraft.choices, ...current.choices.filter((row) => !sentDraft.choices.some((sent) => sent.id === row.id))],
      });
      restoreHeldFiles(chatStore, draftTarget.sessionId ?? "", held);
      setCodingFolder(submittedFolder);
      setProblem(err instanceof Error ? err.message : String(err));
    }
  };

  const pickerOpen = mentionOpen;
  useEffect(() => {
    if (!plusOpen) return;
    const onDown = (event: PointerEvent) => {
      if (!plusRef.current?.contains(event.target as Node)) setPlusOpen(false);
    };
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") setPlusOpen(false);
    };
    document.addEventListener("pointerdown", onDown, true);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("pointerdown", onDown, true);
      document.removeEventListener("keydown", onKey);
    };
  }, [plusOpen]);

  return (
    <div className="shrink-0 px-4 pb-4 pt-2 sm:px-6">
      <div className={CHAT_MEASURE}><ChatCommandPanel control={commands} anchorRef={composerRef} /></div>
      {problem ? <p className="mb-1 px-1 text-xs text-destructive">{problem}</p> : null}
      {mentionOpen && codingError ? <button type="button" className="mb-1 text-xs text-destructive underline" onClick={() => setCodingRetry((n) => n + 1)}>{t("society.chat.coding_retry")}</button> : null}
      {mentionOpen && capabilities.inventoryError ? <button type="button" className="mb-1 text-xs text-destructive underline" onClick={capabilities.retryInventory}>{t("common.retry")}</button> : null}
      <div className={CHAT_MEASURE}>
        <ChatAttachmentStrip attachments={attachments.attachments} analyzing={attachments.analyzing} onRemove={attachments.remove} />
      </div>
      <MentionPicker
        anchorRef={composerRef}
        open={pickerOpen}
        items={matches}
        loading={capabilities.isLoading || codingLoading}
        activeIndex={activeIndex}
        onHover={setActiveIndex}
        onPick={insertMention}
        grouped={!mention?.query.trim()}
      />
      <div
        ref={composerRef}
        className={cn(
          CHAT_MEASURE,
          "as-composer relative flex items-end gap-1.5",
          attachments.dragging && "border-border-strong",
          // The whole composer reads as armed while the mic is open, not just
          // the 32px button someone has to go looking for.
          dictation.dictating && "border-success/35 focus-within:border-success/50",
        )}
        {...attachments.dragHandlers}
      >
        <div className="relative" ref={plusRef}>
          <button
            type="button"
            onClick={() => setPlusOpen((v) => !v)}
            aria-label={t("society.chat.more")}
            aria-expanded={plusOpen}
            aria-haspopup="menu"
            data-testid="composer-plus"
            className="as-round-button"
          >
            <Plus className={cn("h-4 w-4 transition-transform duration-200 motion-reduce:transition-none", plusOpen && "rotate-45")} aria-hidden />
          </button>
          {plusOpen ? (
            <div role="menu" aria-label={t("society.chat.more")} className="as-menu absolute bottom-full left-0 z-20 mb-2 w-64" data-testid="composer-plus-menu">
              {surface === "society" ? (
                <button type="button" role="menuitem" className="as-menu-row" data-testid="composer-model-row" onClick={() => {
                  setPlusOpen(false);
                  composerRef.current?.querySelector<HTMLButtonElement>("[data-chat-model-trigger]")?.click();
                }}>
                  <span className="min-w-0 flex-1 truncate">{t("society.chat.model")}</span>
                  <span className="as-menu-row-value">{agent.model || agent.providerLabel || t("society.chat.model_default")}</span>
                </button>
              ) : null}
              <button type="button" role="menuitem" className="as-menu-row" onClick={() => {
                setPlusOpen(false);
                fileInput.current?.click();
              }}>
                {t("society.chat.attach")}
              </button>
              <button type="button" role="menuitem" className="as-menu-row" onClick={() => {
                setPlusOpen(false);
                fieldRef.current?.insertText("@");
                fieldRef.current?.focus();
              }}>
                {t("chat_tools.all")}
              </button>
              <button type="button" role="menuitem" className="as-menu-row" onClick={() => {
                setPlusOpen(false);
                fieldRef.current?.insertText("@coding/");
                fieldRef.current?.focus();
              }}>
                {t("society.chat.mention_group_coding")}
              </button>
            </div>
          ) : null}
          <input
            ref={fileInput}
            type="file"
            multiple
            className="hidden"
            onChange={(e) => {
              const files = Array.from(e.target.files ?? []);
              if (files.length) void attachments.attachFiles(files);
              e.target.value = "";
            }}
          />
        </div>
        <ComposerChipField
          ref={fieldRef}
          placeholder={
            dictation.dictating
              ? t("chats_view.dictation_listening")
              : openAsk
                ? t("question_card.composer_placeholder").replace("{agent}", openAsk.question.asker || agent.name)
                : t("society.chat.placeholder").replace("{0}", agent.name)
          }
          disabled={false}
          onSubmit={() => (dictation.dictating ? dictation.stopAndSend() : void submit())}
          onDraftChange={onDraftChange}
          onPasteFiles={attachments.onPaste}
          onKeyDown={(e) => {
            if (commands.onKeyDown(e)) return true;
            if (!pickerOpen) return false;
            if (e.key === "ArrowDown") {
              e.preventDefault();
              if (matches.length) setActiveIndex((i) => (i + 1) % matches.length);
              return true;
            }
            if (e.key === "ArrowUp") {
              e.preventDefault();
              if (matches.length) setActiveIndex((i) => (i - 1 + matches.length) % matches.length);
              return true;
            }
            if (e.key === "Escape") {
              e.preventDefault();
              setMention(null);
              return true;
            }
            if (e.key === "Tab" || (e.key === "Enter" && !e.shiftKey)) {
              const item = matches[activeIndex] ?? matches[0];
              if (item) {
                e.preventDefault();
                insertMention(item);
                return true;
              }
              if (e.key === "Tab") return true;
            }
            return false;
          }}
          className="max-h-[180px]"
        />
        {/* The brain picker has no chip of its own: the "+" menu's Model row
            and "/model" press its hidden trigger, and its menu opens over the
            composer. It stays mounted so a save in flight still reports back. */}
        {surface === "society" ? (
          <AgentModelPicker key={agent.agentId} agent={agent} busy={busy} onSavingChange={setModelSaving} anchorRef={composerRef} bare />
        ) : null}
        <DictationButton
          dictating={dictation.dictating}
          onToggle={dictation.toggle}
          startLabel={t("society.chat.record")}
          stopLabel={t("society.chat.stop_recording")}
          shape="round"
        />
        {(busy || live) && <button type="button" onClick={() => void onCancel()}
          aria-label={t("society.chat.stop")} data-testid="composer-cancel"
          className="as-round-button" data-tone="ink">
          <Square className="h-3.5 w-3.5" aria-hidden />
        </button>}
        {(
          <button
            type="button"
            // While recording, Send ends the dictation and sends once the
            // words land, so it is live before the box holds any text.
            onClick={() => (dictation.dictating ? dictation.stopAndSend() : void submit())}
            disabled={!sessionReady || modelSaving || attachments.analyzing > 0 || (!value.trim() && messageDraft.choices.length === 0 && attachments.attachments.length === 0 && !dictation.dictating)}
            aria-label={t("society.chat.send")}
            data-testid="composer-send"
            className="as-round-button" data-tone="send"
          >
            <Send className="h-3.5 w-3.5" aria-hidden />
          </button>
        )}
      </div>
      {codingSelections.length > 0 && <div className={CHAT_MEASURE}>
        <CodingProjectChoice agents={codingSelections.flatMap((item) => item.codingAgent ? [item.codingAgent] : [])} folder={codingFolder} onFolder={setCodingFolder} />
      </div>}
    </div>
  );
}