Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

31.0 KB
Raw Blame
/* ═══════════════════════════════════════════════════════════════
   Live events from the runtime → app state. Each conversation surface
   (Chat, Code) has its own event stream scoped to its own session, so
   their activity never mixes; plus one bots stream. Nothing polls for
   what streams.
   ═══════════════════════════════════════════════════════════════ */

import { useEffect } from "react";
import { openStream } from "~/api/stream";
import * as api from "~/api/mercury";
import { ApiError, http } from "~/api/client";
import type { BotActivityEvent, BotInboxEntry, BotStatus, ChatMessage, CodeMode, ImageIntent, PendingMedia, PendingPrompt, ThoughtTrace, ReplyUsage, ResearchPlanPrompt, ResearchSnapshot } from "~/api/types";
import { useBots, useChat, useRuntimeState, type AgentState } from "./store";
import { conversations, useCodeSessions, type ConversationState, type ConversationStore, type Surface } from "./conversation";
import type { ArtifactRef } from "~/api/artifacts";
import { useNotify } from "./notify/store";
import { addNote, addReasoning, addText, endReasoning, finishTool, finishTrace, hasProcess, liveFromSnapshot, markStopped, newTrace, normalizeMessages, setPhase, startTool } from "./trace";

export function useRuntimeEvents(enabled: boolean): void {
  const chatId = conversations.chat((s) => s.activeId);
  const codeId = conversations.code((s) => s.activeId);

  useSurfaceStream(enabled, "chat", chatId, true);
  useSurfaceStream(enabled, "code", codeId, false);

  useEffect(() => {
    if (!enabled) return;
    const stream = openStream("/api/bots/events", {
      onEvent: (event, raw) => {
        if (event === "bot_roster") {
          // Roster news (an edit, a new crew member, a delete) from any screen.
          const r = safeJson<{ bots: BotStatus[] }>(raw);
          if (r?.bots) useBots.getState().setBots(r.bots, true);
          return;
        }
        if (event === "bot_approval") {
          // A bot asked, or its question was answered or timed out.
          void refreshApprovals();
          return;
        }
        if (event === "bot_inbox") {
          // A result, a reported failure, or a run that needs you.
          const entry = safeJson<BotInboxEntry>(raw);
          if (!entry) return;
          useBots.getState().inboxChanged();
          void refreshBots();
          void import("./notify/notify").then(({ tellBotInbox }) => tellBotInbox(entry));
          return;
        }
        if (event !== "bot_activity") return;
        const ev = safeJson<BotActivityEvent>(raw);
        if (!ev) return;
        // Everything goes to the live feed; the roster label follows steps only.
        useBots.getState().addLive([{ ...ev, at: ev.at ?? Date.now() }]);
        if (ev.kind === "thinking" || ev.kind === "queued") return;
        useBots.getState().setActivity(ev.botId, ev.kind === "turn-end" ? null : ev.label);
        if (ev.kind === "turn-end" || ev.kind === "turn-start") void refreshBots();
      },
    });
    return () => stream.close();
  }, [enabled]);

  // The chrome (rail, status bar) shows one agent state: the busiest surface.
  useEffect(() => {
    const rank: Record<AgentState, number> = { "needs-you": 5, working: 4, streaming: 3, thinking: 2, idle: 1, offline: 0 };
    const sync = () => {
      if (!useRuntimeState.getState().connected) return;
      const a = conversations.chat.getState();
      const b = conversations.code.getState();
      const top = rank[a.agent] >= rank[b.agent] ? a : b;
      useRuntimeState.setState({ agent: top.agent, step: top.step, prompts: [...a.prompts, ...b.prompts] });
    };
    const offA = conversations.chat.subscribe(sync);
    const offB = conversations.code.subscribe(sync);
    return () => { offA(); offB(); };
  }, []);
}

/**
 * One stream per surface. Unscoped (no session yet) the runtime would send
 * every web event; only the chat surface listens unscoped, so a brand-new
 * Code view never shows Chat's traffic.
 */
function useSurfaceStream(enabled: boolean, surface: Surface, sessionId: string | null, tracksConnection: boolean): void {
  useEffect(() => {
    if (!enabled) return;
    if (!sessionId && surface !== "chat") return;
    const store = conversations[surface];
    const query = sessionId ? `?sessionId=${encodeURIComponent(sessionId)}` : "";
    const stream = openStream(`/api/chat/events${query}`, {
      onOpen: () => { if (tracksConnection) useRuntimeState.getState().setConnected(true); },
      onClose: (reason) => { if (tracksConnection && reason !== "closed") useRuntimeState.getState().setConnected(false); },
      onEvent: (event, raw) => handleEvent(store, event, raw),
    });
    return () => stream.close();
  }, [enabled, surface, sessionId, tracksConnection]);
}

function safeJson<T>(raw: string): T | null {
  try {
    return JSON.parse(raw) as T;
  } catch {
    return null;
  }
}

/** When each surface's last reply landed: a late "thinking" right after it is not a new turn. */
const lastReplyAt = new WeakMap<ConversationStore, number>();

/** Artifacts that arrived before their reply did: attached when it lands. */
const pendingArtifacts = new WeakMap<ConversationStore, ArtifactRef[]>();

/** Is a step's result a failure? The runtime says so now; older ones only by the text. */
export function stepFailed(data: Record<string, unknown>, summary: string | undefined): boolean {
  if (typeof data.failed === "boolean") return data.failed;
  return !!summary && /^(error|failed|denied|blocked|HTTP [45]\d\d\b|Request to .* timed out)/i.test(summary.trim());
}

const FINAL_RESEARCH = new Set(["done", "partial", "stopped", "failed", "cancelled"]);

/** A research update: the chip and panel follow it; a finished run's report card goes on its answer. */
function onResearch(store: ConversationStore, data: Record<string, unknown>): void {
  const conv = store.getState();
  if (data.state === "armed" || data.state === "off") {
    const armed = data.state === "armed";
    conv.setResearch((r) => ({ ...r, armed, planFirst: armed && data.planFirst === true, topic: typeof data.topic === "string" ? data.topic : null }));
    return;
  }
  if (typeof data.runId !== "string") return;
  const run = data as unknown as ResearchSnapshot;
  conv.setResearch((r) => ({ ...r, armed: false, planFirst: false, run }));
  if (!FINAL_RESEARCH.has(run.state) || run.state === "cancelled") return;
  // The answer is the last assistant message (the run's final update comes after it).
  const msgs = store.getState().messages;
  for (let i = msgs.length - 1; i >= 0; i--) {
    if (msgs[i].role === "user") break;
    if (msgs[i].role === "assistant") {
      store.getState().setMessages([...msgs.slice(0, i), { ...msgs[i], research: run }, ...msgs.slice(i + 1)]);
      return;
    }
  }
}

export function handleEvent(store: ConversationStore, event: string, raw: string): void {
  const conv = store.getState();
  const data = safeJson<Record<string, unknown>>(raw) ?? {};
  // A scoped stream may still carry another session's events on old runtimes.
  const eventSession = typeof data.sessionId === "string" ? data.sessionId : null;
  if (eventSession && conv.activeId && eventSession !== conv.activeId) return;
  switch (event) {
    case "connected":
    case "provider":
      // `connected` names it `provider`; older `provider` events only `name`.
      useRuntimeState.getState().setProvider(String(data.provider ?? data.name ?? ""), String(data.model ?? ""));
      break;
    case "status":
      // The runtime's live status: a permission change made anywhere (a toggle here, /permissions
      // in a terminal, another device) reaches every toggle on screen.
      if (data.permission === "allow-all" || data.permission === "ask-me") useRuntimeState.getState().setAllowAll(data.permission === "allow-all");
      break;
    case "queued":
      // Waiting behind another chat's turn: say so, instead of "Thinking".
      conv.setWaiting({ position: Number(data.position) || 1, busyWith: typeof data.busyWith === "string" ? data.busyWith : undefined, busySessionId: typeof data.busySessionId === "string" ? data.busySessionId : undefined });
      conv.setAgent("thinking");
      break;
    case "queue_dropped": {
      // A stop took this chat's waiting message(s) out of line (ADR-038): they won't run.
      const wasWaiting = !!conv.waiting;
      conv.setWaiting(null);
      if (conv.stopping) { finishStopped(store); break; }
      if (wasWaiting && !conv.streaming && !conv.live) conv.setAgent("idle");
      const n = Number(data.dropped) || 1;
      conv.setNotice({ message: `Stopped before it started: ${n === 1 ? "your waiting message wasn't sent" : `${n} waiting messages weren't sent`}.`, level: "info", at: Date.now() });
      break;
    }
    case "thinking": {
      // Sent every few seconds while a turn makes progress (it keeps a
      // Telegram typing dot alive). It starts a turn on screen only when none
      // is showing, and never turns "Working"/"Answering" back to "Thinking".
      conv.setWaiting(null);
      const quiet = conv.agent === "idle" || conv.agent === "offline";
      if (quiet && !conv.live && Date.now() - (lastReplyAt.get(store) ?? 0) < 2500) break;
      if (quiet) conv.setAgent("thinking");
      conv.setLive((l) => l);
      break;
    }
    case "phase":
      if (typeof data.phase === "string" && data.phase) {
        const label = typeof data.detail === "string" && data.detail && !/^(stall|step budget|verification gate|execute guard|completion contract)$/i.test(data.detail) ? `${data.phase} · ${data.detail}` : data.phase;
        if (conv.live || conv.agent !== "idle") conv.setLive((l) => setPhase(l, label));
      }
      break;
    case "media_pending": {
      // A video or song started in the background: hold its place until it arrives.
      if (typeof data.jobId !== "string") break;
      const job = { jobId: data.jobId, kind: data.kind === "music" ? "music" as const : "video" as const, prompt: String(data.prompt ?? ""), startedAt: Number(data.startedAt) || Date.now(), ...(typeof data.aspect === "string" ? { aspect: data.aspect } : {}) };
      conv.setPendingMedia((list) => [...list.filter((p) => p.jobId !== job.jobId), job]);
      break;
    }
    case "media_ready": {
      // A video or song made in the background (after its turn ended): its own message.
      if (typeof data.jobId === "string") conv.setPendingMedia((list) => list.filter((p) => p.jobId !== data.jobId));
      const items = Array.isArray(data.artifacts) ? (data.artifacts as ArtifactRef[]) : [];
      conv.addMessage({ id: crypto.randomUUID(), role: "assistant", content: String(data.text ?? ""), timestamp: new Date().toISOString(), ...(items.length ? { artifacts: items } : {}) });
      void refreshThreads();
      break;
    }
    case "progress":
      // "Checking my work…": a note inside the running turn, not its reply.
      if (typeof data.text === "string" && data.text.trim()) conv.setLive((l) => addNote(l, data.text as string));
      break;
    case "research":
      onResearch(store, data);
      break;
    case "research_plan":
      conv.setResearchPlan(data as unknown as ResearchPlanPrompt);
      break;
    case "research_plan_resolved":
      if (conv.researchPlan?.id === data.id) conv.setResearchPlan(null);
      break;
    case "notice":
      if (typeof data.message === "string") conv.setNotice({ message: data.message, level: data.level === "warning" ? "warning" : "info", at: Date.now() });
      break;
    case "plan": {
      const steps = Array.isArray(data.steps) ? (data.steps as Array<{ label: string; status: "pending" | "active" | "done" }>) : [];
      const state = data.state === "paused" || data.state === "stopped" ? data.state : undefined;
      if (steps.length) conv.setPlan({ steps, updatedAt: Number(data.updatedAt) || Date.now(), ...(state ? { state } : {}) });
      break;
    }
    case "artifacts": {
      const items = Array.isArray(data.items) ? (data.items as ArtifactRef[]) : [];
      if (!items.length) break;
      const last = conv.messages[conv.messages.length - 1];
      const turnOver = conv.agent === "idle" || conv.agent === "needs-you";
      if (turnOver && last?.role === "assistant") {
        conv.setMessages([...conv.messages.slice(0, -1), { ...last, artifacts: [...(last.artifacts ?? []), ...items] }]);
      } else {
        pendingArtifacts.set(store, [...(pendingArtifacts.get(store) ?? []), ...items]);
      }
      break;
    }
    case "reasoning":
      conv.setWaiting(null);
      if (data.done === true) { if (conv.live) conv.setLive((l) => endReasoning(l)); break; }
      if (typeof data.text === "string" && data.text) conv.setLive((l) => addReasoning(l, data.text as string));
      break;
    case "step_start": {
      conv.setWaiting(null);
      const tool = String(data.tool ?? "");
      conv.setStep({ total: Number(data.totalSteps ?? 0), current: Number(data.step ?? data.stepNumber ?? 0), tool });
      conv.setAgent("working");
      conv.setLive((l) => startTool(l, {
        key: typeof data.id === "string" ? data.id : undefined,
        tool,
        title: typeof data.title === "string" ? data.title : undefined,
        label: String(data.label ?? tool),
        step: Number(data.step) || undefined,
        ...(data.media && typeof data.media === "object" ? { media: data.media as ThoughtTrace["steps"][number]["media"] } : {}),
      }));
      break;
    }
    case "step_done": {
      const tool = String(data.tool ?? "");
      const summary = typeof data.summary === "string" ? data.summary : undefined;
      // "HTTP 403" and "timed out" are failures too (they used to show a green check).
      const failed = stepFailed(data, summary);
      const shown = failed && typeof data.reason === "string" && data.reason ? data.reason : summary;
      conv.setStep({ total: Number(data.totalSteps ?? 0), current: Number(data.stepNumber ?? 0), tool });
      conv.setLive((l) => finishTool(l, {
        key: typeof data.id === "string" ? data.id : undefined,
        tool,
        failed,
        summary: shown,
        durationMs: typeof data.durationMs === "number" ? data.durationMs : undefined,
      }));
      break;
    }
    case "text_delta":
      conv.setWaiting(null);
      conv.setAgent("streaming");
      conv.appendStreaming(String(data.text ?? ""));
      conv.setLive((l) => addText(l, String(data.text ?? "")));
      break;
    case "text_done": {
      conv.setWaiting(null);
      conv.setNotice(null);
      const text = String(data.fullText ?? data.text ?? raw);
      // The runtime's reply to a stop is its "⏹ Task stopped" note: end the turn as stopped.
      if (isStopNote(text) || (store.getState().stopping && !text.trim())) { finishStopped(store); void refreshThreads(); break; }
      const live = store.getState().live;
      const trace = hasProcess(live) ? finishTrace(live) : undefined;
      lastReplyAt.set(store, Date.now());
      conv.clearStreaming();
      conv.clearLive();
      const artifacts = pendingArtifacts.get(store);
      pendingArtifacts.delete(store);
      const usage = replyUsage(data.usage);
      conv.addMessage({ id: crypto.randomUUID(), role: "assistant", content: text, timestamp: new Date().toISOString(), ...(trace ? { trace } : {}), ...(artifacts?.length ? { artifacts } : {}), ...(usage ? { usage } : {}) });
      conv.setStep(null);
      store.getState().setAgent(store.getState().prompts.length ? "needs-you" : "idle");
      void refreshThreads();
      break;
    }
    case "permission_request":
      conv.addPrompt(toPrompt("permission", data, String(data.prompt ?? "")));
      break;
    case "permission_continue":
      conv.addPrompt(toPrompt("continue", data, String(data.question ?? "")));
      break;
    case "choice_prompt":
      conv.addPrompt(toPrompt("choice", data, String(data.question ?? "")));
      break;
    case "permission_resolved":
    case "choice_resolved":
      if (typeof data.id === "string") conv.removePrompt(data.id);
      break;
    case "error": {
      conv.setWaiting(null);
      conv.setNotice(null);
      const message = typeof data.message === "string" ? data.message : raw || "Something went wrong";
      conv.clearStreaming();
      conv.clearLive();
      conv.setStep(null);
      conv.setAgent("idle");
      conv.addMessage({ id: crypto.randomUUID(), role: "system", content: message, timestamp: new Date().toISOString() });
      conv.setStopping(false);
      break;
    }
    default:
      break;
  }
}

/** What a reply cost, from the runtime's final event (runtimes from #296 on). */
export function replyUsage(raw: unknown): ReplyUsage | undefined {
  if (!raw || typeof raw !== "object") return undefined;
  const u = raw as Record<string, unknown>;
  const n = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : undefined);
  const inputTokens = n(u.inputTokens);
  const outputTokens = n(u.outputTokens);
  if (inputTokens === undefined || outputTokens === undefined) return undefined;
  return {
    inputTokens,
    outputTokens,
    cachedInputTokens: n(u.cachedInputTokens) ?? 0,
    ...(typeof u.provider === "string" ? { provider: u.provider } : {}),
    ...(typeof u.model === "string" ? { model: u.model } : {}),
    ...(n(u.steps) !== undefined ? { steps: n(u.steps) } : {}),
    ...(n(u.elapsedMs) !== undefined ? { elapsedMs: n(u.elapsedMs) } : {}),
  };
}

function toPrompt(kind: PendingPrompt["kind"], data: Record<string, unknown>, text: string): PendingPrompt {
  const rawOptions = Array.isArray(data.options) ? data.options : [];
  const options = rawOptions.map((o) => {
    if (typeof o === "string") return { value: o, label: labelFor(o) };
    const obj = o as { value?: string; label?: string };
    return { value: String(obj.value ?? ""), label: String(obj.label ?? obj.value ?? "") };
  });
  return { id: String(data.id ?? crypto.randomUUID()), kind, text, options, targetId: typeof data.targetId === "string" ? data.targetId : undefined, raisedAt: Date.now() };
}

function labelFor(value: string): string {
  switch (value) {
    case "yes": return "Allow";
    case "always": return "Always allow";
    case "no": return "Deny";
    default: return value;
  }
}

export async function refreshThreads(): Promise<void> {
  try {
    const { threads } = await api.chat.threads();
    useChat.getState().setThreads(threads);
    useNotify.getState().keepOnly(new Set(threads.map((t) => t.id)));
  } catch { /* offline: keep what we have */ }
}

/** Only update local labels after the runtime has persisted the owner's title. */
export async function renameThread(threadId: string, title: string): Promise<void> {
  const renamed = await api.chat.renameThread(threadId, title);
  const { threads, setThreads } = useChat.getState();
  setThreads(threads.map((thread) => thread.id === renamed.id ? { ...thread, title: renamed.title } : thread));
}

/**
 * Save a thread to come back to, or unsave it. Shows at once; puts it back
 * if the runtime says no.
 */
export async function setThreadSaved(threadId: string, saved: boolean): Promise<void> {
  const mark = (savedAt: string | undefined) => {
    const { threads, setThreads } = useChat.getState();
    setThreads(threads.map((t) => (t.id === threadId ? { ...t, savedAt } : t)));
  };
  const before = useChat.getState().threads.find((t) => t.id === threadId)?.savedAt;
  mark(saved ? new Date().toISOString() : undefined);
  try {
    const res = await api.chat.save(threadId, saved);
    mark(res.savedAt ?? undefined);
  } catch (err) {
    mark(before);
    throw err;
  }
}

export async function refreshApprovals(): Promise<void> {
  try {
    useBots.getState().setApprovals(await api.bots.approvals());
  } catch { /* an older runtime has no approvals */ }
}

export async function refreshBots(): Promise<void> {
  void refreshApprovals();
  try {
    const { bots, available, unread } = await api.bots.list();
    useBots.getState().setBots(bots, available, unread);
  } catch { /* bots unavailable on this runtime */ }
}

/**
 * A chat's running reply as the screen showed it, kept when you switch
 * away, so coming back shows it at once (the runtime's snapshot then
 * brings it up to date).
 */
const leftMidTurn = new Map<string, { live: ThoughtTrace | null; streaming: string; agent: AgentState; step: ConversationState["step"] }>();

function busy(agent: AgentState): boolean {
  return agent === "thinking" || agent === "working" || agent === "streaming";
}

/** The runtime's snapshot of a reply still being worked on, onto the screen. */
async function restoreRunningTurn(store: ConversationStore, id: string): Promise<void> {
  let snap: { running: boolean; startedAt?: number; activity?: string; trace?: unknown; text?: string };
  try {
    snap = await api.chat.live(id);
  } catch {
    return; // older Mercury: what was kept on screen stays
  }
  const s = store.getState();
  if (s.activeId !== id) return;
  if (!snap.running) {
    // It finished while you were away: the reply is in the messages now.
    if (busy(s.agent) && !s.waiting) { s.clearLive(); s.clearStreaming(); s.setAgent(s.prompts.length ? "needs-you" : "idle"); }
    return;
  }
  const live = liveFromSnapshot(snap.trace, snap.text ?? "", snap.startedAt ?? Date.now(), snap.activity);
  s.setLive(() => live);
  if (snap.text) { s.clearStreaming(); s.appendStreaming(snap.text); }
  const running = live.steps.some((st) => st.status === "running");
  if (!s.prompts.length) s.setAgent(running ? "working" : snap.text ? "streaming" : "thinking");
}

/** Ask the composer of a surface to take the cursor (after the view has rendered). */
export function focusComposer(surface: Surface): void {
  if (typeof window === "undefined") return;
  window.dispatchEvent(new CustomEvent("mercury:focus-composer", { detail: { surface } }));
}

export async function openThread(surface: Surface, id: string | null): Promise<void> {
  const store = conversations[surface];
  // Leaving a chat mid-reply: keep what it showed.
  const before = store.getState();
  if (before.activeId && before.activeId !== id && (before.live || busy(before.agent))) {
    leftMidTurn.set(before.activeId, { live: before.live, streaming: before.streaming, agent: before.agent, step: before.step });
  }
  store.getState().setActive(id);
  store.getState().clearStreaming();
  // A new chat or another session: the cursor goes to the message box, ready to type.
  focusComposer(surface);
  // Coming back to one: show it straight away, then ask the runtime how far it got.
  const kept = id ? leftMidTurn.get(id) : undefined;
  if (id && kept) {
    leftMidTurn.delete(id);
    if (kept.live) store.getState().setLive(() => kept.live!);
    if (kept.streaming) store.getState().appendStreaming(kept.streaming);
    store.getState().setAgent(kept.agent);
    store.getState().setStep(kept.step);
  }
  if (!id) {
    store.getState().setMessages([]);
    return;
  }
  store.getState().setLoading(true);
  useNotify.getState().seen(id);
  // Prompts still waiting here (asked while you were elsewhere, perhaps from a notification).
  void http.get<{ prompts?: Array<Record<string, unknown>> }>(`/api/chat/pending?sessionId=${encodeURIComponent(id)}`)
    .then((r) => {
      if (store.getState().activeId !== id) return;
      for (const p of r.prompts ?? []) {
        if (p.type === "research_plan") { store.getState().setResearchPlan(p as unknown as ResearchPlanPrompt); continue; }
        const kind = p.type === "choice_prompt" ? "choice" : p.type === "permission_continue" ? "continue" : "permission";
        store.getState().addPrompt(toPrompt(kind, p, String(p.prompt ?? p.question ?? "")));
      }
    })
    .catch(() => { /* older Mercury */ });
  // Still waiting in line behind another chat? (Opened after the message was sent.)
  store.getState().setWaiting(null);
  void http.get<{ state: string; position?: number; busyWith?: string; busySessionId?: string }>(`/api/chat/threads/${encodeURIComponent(id)}/queue`)
    .then((q) => {
      if (store.getState().activeId !== id || q.state !== "queued") return;
      store.getState().setWaiting({ position: q.position ?? 1, busyWith: q.busyWith, busySessionId: q.busySessionId });
      store.getState().setAgent("thinking");
    })
    .catch(() => { /* older Mercury */ });
  // Research here: on for the next message, or a run going (opened mid-run, it picks up live).
  void api.chat.research(id)
    .then((r) => {
      if (store.getState().activeId !== id) return;
      if (r.armed || r.run) store.getState().setResearch(() => ({ armed: r.armed, planFirst: r.planFirst, topic: r.topic ?? null, run: r.run }));
      if (r.run?.state === "running") store.getState().setAgent("working");
    })
    .catch(() => { /* older Mercury */ });
  // The plan Mercury was working through in this conversation, if any.
  void http.get<{ plan: { steps: Array<{ label: string; status: "pending" | "active" | "done" }>; updatedAt: number; state?: "paused" | "stopped" } | null }>(`/api/chat/plan?sessionId=${encodeURIComponent(id)}`)
    .then((r) => { if (store.getState().activeId === id && r.plan?.steps?.length) store.getState().setPlan(r.plan); })
    .catch(() => { /* older Mercury: no plans */ });
  try {
    const thread = await api.chat.thread(id);
    store.getState().setMessages(normalizeMessages(thread.messages ?? []));
    // A reply still being worked on (here or from another device): show it as far as it got.
    await restoreRunningTurn(store, id);
    // Videos or songs still being made for this chat: their placeholders.
    void http.get<{ jobs?: PendingMedia[] }>(`/api/media/jobs?sessionId=${encodeURIComponent(id)}`)
      .then((r) => { if (store.getState().activeId === id) store.getState().setPendingMedia(() => r.jobs ?? []); })
      .catch(() => { /* older Mercury */ });
  } catch {
    store.getState().setMessages([]);
  } finally {
    store.getState().setLoading(false);
  }
}

export interface CodeTurn {
  mode: Exclude<CodeMode, "off">;
  folder: string | null;
}

export async function sendMessage(surface: Surface, content: string, attachments: Array<{ name: string; data: string; mime?: string }> = [], code?: CodeTurn, media?: ImageIntent): Promise<void> {
  const store = conversations[surface];
  let id = store.getState().activeId;
  if (!id) {
    const thread = await api.chat.createThread(surface === "code" ? `Code · ${content.slice(0, 40)}` : undefined);
    id = thread.id;
    // An effort picked before the chat existed belongs to it.
    const pendingEffort = store.getState().pendingEffort;
    store.getState().setActive(id);
    if (pendingEffort) {
      store.getState().setPendingEffort(undefined);
      await api.chat.setEffort(id, pendingEffort).catch(() => undefined);
    }
    store.getState().setMessages([]);
    if (surface === "code") useCodeSessions.getState().upsert({ id, folder: code?.folder ?? null, createdAt: new Date().toISOString() });
  }
  const shown = content || `(Attached: ${attachments.map((a) => a.name).join(", ")})`;
  const optimistic: ChatMessage = {
    id: crypto.randomUUID(),
    role: "user",
    content: shown,
    timestamp: new Date().toISOString(),
    ...(attachments.length
      ? { attachments: attachments.map((a) => ({ name: a.name, kind: a.mime?.startsWith("image/") ? "image" : "document", mime: a.mime, src: a.mime?.startsWith("image/") ? `data:${a.mime};base64,${a.data}` : undefined })) }
      : {}),
  };
  store.getState().addMessage(optimistic);
  store.getState().setAgent("thinking");
  store.getState().setLive(() => newTrace());
  await api.chat.send(content, id, attachments.map(({ name, data }) => ({ name, data })), code ? { programming: code.mode, cwd: code.folder ?? undefined } : undefined, media);
  void refreshThreads();
}

/** The note the runtime sends back when a turn is stopped (agent.ts, "⏹ Task stopped. …"). */
export function isStopNote(text: string): boolean {
  return /^\s*⏹\s*Task (stopped|halted)\b/.test(text);
}

/**
 * Stop button. Marks what was running as stopped straight away (so the
 * screen never claims a step finished), asks the runtime to stop, and ends
 * the turn when its confirmation arrives, or after a few seconds if it
 * never does (an older runtime, or the turn ended on its own meanwhile).
 */
export async function stopTurn(store: ConversationStore): Promise<void> {
  const s = store.getState();
  if (s.stopping) return;
  s.setStopping(true);
  if (s.live) s.setLive((l) => markStopped(l));
  try {
    await api.chat.stop(s.activeId);
  } catch (err) {
    store.getState().setStopping(false);
    throw err;
  }
  setTimeout(() => { if (store.getState().stopping) finishStopped(store); }, 8000);
}

/** Is Mercury working on this conversation right now (or still stopping)? */
export function turnRunning(store: ConversationStore): boolean {
  const s = store.getState();
  return s.stopping || !!s.streaming || (s.agent !== "idle" && s.agent !== "offline");
}

const pause = (ms: number) => new Promise((r) => setTimeout(r, ms));

/**
 * Undo your last message: stop the turn if it's running (and wait for it
 * to end), take the message and Mercury's reply out of the conversation
 * (the runtime forgets them too), and put your text back in the box.
 */
export async function undoLast(store: ConversationStore, message: ChatMessage): Promise<void> {
  const threadId = store.getState().activeId;
  if (!threadId) throw new Error("No conversation is open.");
  if (turnRunning(store)) {
    await stopTurn(store);
    for (let waited = 0; turnRunning(store) && waited < 12_000; waited += 150) await pause(150);
  }
  // The runtime may still be writing the stopped turn: give it a moment.
  let result: Awaited<ReturnType<typeof api.chat.undo>> | null = null;
  for (let attempt = 0; ; attempt++) {
    try {
      result = await api.chat.undo(threadId, message.content);
      break;
    } catch (err) {
      const busy = err instanceof ApiError && err.status === 409 && err.data.busy === true;
      if (!busy || attempt >= 25) throw err;
      await pause(400);
    }
  }
  const s = store.getState();
  if (s.activeId !== threadId) return;
  const at = s.messages.findIndex((m) => m.id === message.id);
  s.setMessages(at >= 0 ? s.messages.slice(0, at) : s.messages);
  s.setDraft(result.content);
}

/** End the current turn as stopped: keep the partial answer, mark the trace, say so. */
function finishStopped(store: ConversationStore): void {
  const s = store.getState();
  const partial = s.streaming;
  const live = s.live;
  const now = Date.now();
  const busy = s.agent === "thinking" || s.agent === "working" || s.agent === "streaming";
  s.clearStreaming();
  s.clearLive();
  s.setStep(null);
  s.setStopping(false);
  // Nothing was running any more (the answer finished first): nothing to mark.
  if (!busy && !partial && !live) return;
  const trace = hasProcess(live) ? finishTrace(live, { stopped: true }, now) : undefined;
  s.addMessage({ id: crypto.randomUUID(), role: "assistant", content: partial, stopped: true, timestamp: new Date().toISOString(), ...(trace ? { trace } : {}) });
  s.setAgent(s.prompts.length ? "needs-you" : "idle");
}

export async function answerPrompt(store: ConversationStore, prompt: PendingPrompt, value: string | null): Promise<void> {
  await api.chat.answer(prompt.id, value ?? "", prompt.targetId);
  store.getState().removePrompt(prompt.id);
}