/* ===========================================================
   indie.chat — React app
   =========================================================== */
const { useState, useEffect, useRef, useCallback } = React;
/* the Connections dialog and what goes with it live in connections.jsx, shared with Settings */
const { FilesIcon, PlugIcon, ConnGlyph, serviceName, reaches, ConnectionsModal } = window.IndieConn;
const L = window.IndieLib;

/* Translate. An arrow rather than a bound reference, so it always reads the
   CURRENT locale — switching languages re-renders the tree and every t() call
   picks up the new catalogue without anything being re-imported. */
const t = (k, v) => L.t(k, v);
const tb = (k, v) => L.tb(k, v);

/* The theme showing now ("light" | "dark"), re-rendering on every switch;
   appearance.js announces them, including ones from another tab or the OS. */
const currentTheme = () => (window.IndieTheme ? window.IndieTheme.effective() : "light");
function useTheme() {
  const [theme, setTheme] = useState(currentTheme);
  useEffect(() => {
    const on = () => setTheme(currentTheme());
    window.addEventListener("indie:theme", on);
    return () => window.removeEventListener("indie:theme", on);
  }, []);
  return theme;
}

/* ---------- icons ---------- */
const SendIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M12 19V5M5 12l7-7 7 7" />
  </svg>
);
const MenuIcon = () => (
  <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="#4d4d51" strokeWidth="2" strokeLinecap="round">
    <path d="M3 6h18M3 12h18M3 18h18" />
  </svg>
);
const ClipIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48" />
  </svg>
);
const SearchIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="11" cy="11" r="7" /><path d="M21 21l-4.3-4.3" />
  </svg>
);
const ShieldIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
  </svg>
);
const MicIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <rect x="9" y="2" width="6" height="12" rx="3" />
    <path d="M5 11a7 7 0 0 0 14 0M12 18v4" />
  </svg>
);
const DownloadIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M12 3v12M8 11l4 4 4-4M5 21h14" />
  </svg>
);
const EyeIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12z" /><circle cx="12" cy="12" r="3" />
  </svg>
);
const BookIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><path d="M4 5.5A1.5 1.5 0 0 1 5.5 4H19v14H5.5A1.5 1.5 0 0 0 4 19.5z"/><path d="M8 8h7M8 11.5h7"/></svg>
);
const ToolsIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M14.7 6.3a4 4 0 0 1-5.2 5.2L4 17v3h3l5.5-5.5a4 4 0 0 1 5.2-5.2l-2.5 2.5-2-2 2.5-2.5z" />
  </svg>
);
const FileGenIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
    <path d="M14 2v6h6" />
    <path d="M12 18v-6" /><path d="M9 15h6" />
  </svg>
);
const PlusIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M12 5v14M5 12h14" /></svg>
);
const BotIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <rect x="4" y="8" width="16" height="11" rx="2" /><path d="M12 8V4" /><circle cx="12" cy="3" r="1" />
    <circle cx="9" cy="13" r="1.1" fill="currentColor" /><circle cx="15" cy="13" r="1.1" fill="currentColor" /><path d="M9.5 16.5h5" />
  </svg>
);
const BellIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" /><path d="M13.7 21a2 2 0 0 1-3.4 0" />
  </svg>
);
const ClockIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" />
  </svg>
);
const HelpIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="12" r="9" /><path d="M9.6 9.3a2.5 2.5 0 0 1 4.9.7c0 1.7-2.5 2-2.5 3.5" /><circle cx="12" cy="17" r="0.9" fill="currentColor" stroke="none" />
  </svg>
);
const MoonIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" />
  </svg>
);
const SunIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="12" r="4" />
    <path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4" />
  </svg>
);
const GearIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="12" r="3" />
    <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
  </svg>
);
const RefreshIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M21 12a9 9 0 1 1-2.64-6.36" /><path d="M21 3v6h-6" />
  </svg>
);
const LockIcon = ({ open }) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <rect x="5" y="11" width="14" height="10" rx="2" />
    {open ? <path d="M8 11V7a4 4 0 0 1 7.5-2" /> : <path d="M8 11V7a4 4 0 0 1 8 0v4" />}
  </svg>
);

/* Brand wordmark — reads the (white-labelable) brand name; colors the first dot
   with the accent, so "indie.chat" keeps its look and "acme.ai" gets one too. */
function BrandName() {
  const n = (L.BRAND && L.BRAND.brandName) || "indie.chat";
  /* Accent the separator AND everything after it, and accept ':' as well as
     '.', so "indie.chat" keeps its look while "acme:agents" gets the same
     treatment instead of rendering flat. (From the crefo deployment.) */
  const i = n.search(/[.:]/);
  if (i < 0) return n;
  return <>{n.slice(0, i)}<b className="bd">{n.slice(i)}</b></>;
}

/* ========================================================
   ORIGIN UNREACHABLE

   The last resort, NOT the first response. When the origin cannot be reached
   the app first asks for an uncached navigation (see `forceNetworkReload`), so
   the browser makes a real request and shows its own certificate or connection
   dialog — which explains the problem, and offers the way through it, far
   better than anything we could write here.

   This screen is what is left when that cannot help: the reload has already
   been used this tab, or the browser says it has no network at all (in which
   case the cached app is the point and is left alone). One sentence and a
   button; the detail belongs in the operator's README.
   ======================================================== */
function UnreachableScreen({ offline, onRetry, retrying }) {
  return (
    <div className="auth-screen">
      <div className="auth-card">
        <div className="auth-brand">
          <div className="logo" style={{ width: 38, height: 38, marginRight: 12 }} />
          <div>
            <div className="brand-name"><BrandName /></div>
            <div className="brand-tag">{L.BRAND.tagline}</div>
          </div>
        </div>

        <div className="auth-error">{t("offline.title")}</div>
        <p className="auth-offline">{t(offline ? "offline.offlineBody" : "offline.serverBody")}</p>

        <button className="btn primary auth-submit" onClick={onRetry} disabled={retrying}>
          {retrying ? t("common.pleaseWait") : t("offline.retry")}
        </button>
      </div>
    </div>
  );
}

/* Shown for the moment between deciding to reload and the reload happening.
   Deliberately says nothing about why: the browser is about to. */
function ReloadingScreen() {
  return (
    <div style={{ height: "100%", display: "grid", placeItems: "center", background: "var(--canvas)" }}>
      <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-4)", letterSpacing: "0.1em", textTransform: "uppercase" }}>
        {t("offline.reloading")}
      </span>
    </div>
  );
}

/* ========================================================
   LOGIN SCREEN
   ======================================================== */
function LoginScreen({ onLogin }) {
  const [tab,      setTab]      = useState("login");
  const [email,    setEmail]    = useState("");
  const [password, setPassword] = useState("");
  const [name,     setName]     = useState("");
  const [loading,  setLoading]  = useState(false);
  const [error,    setError]    = useState(null);
  const [notice,   setNotice]   = useState(null);
  const [reloading, setReloading] = useState(false);

  /* Explicitly hand the credential to the browser's password manager. The form
     submits via fetch (no navigation), so Chrome/Edge's save heuristic doesn't
     fire on its own; the Credential Management API triggers the save prompt.
     Safari/Firefox fall back to the autocomplete attributes on submit. */
  const saveCredential = async (id, pass, nm) => {
    try {
      if (window.PasswordCredential && window.isSecureContext) {
        await navigator.credentials.store(new window.PasswordCredential({ id, password: pass, name: nm || id }));
      }
    } catch { /* user dismissed, or unsupported — harmless */ }
  };

  const submit = async e => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setNotice(null);
    try {
      if (tab === "login") {
        const u = await L.Auth.login(email.trim(), password);
        await saveCredential(email.trim(), password, u && u.name);
        onLogin(u);
      } else {
        const res = await L.Auth.register(email.trim(), name.trim(), password);
        /* Save the new credential now (works whether or not approval is pending). */
        await saveCredential(email.trim(), password, name.trim());
        if (res && res.pending) {
          /* Awaiting admin approval — don't log in; send them back to sign-in. */
          setTab("login");
          setName(""); setPassword("");
          setNotice(res.message || t("auth.pendingApproval"));
        } else {
          onLogin(res);
        }
      }
    } catch (err) {
      /* A request that never reached the server is not a rejected credential —
         reporting it as one is what sent people off to reset a working
         password. It cannot succeed on a retry either, so hand the problem to
         the browser: drop the cached app and reload, and let it show its own
         certificate dialog. Only if that is not available do we say anything. */
      if (L.isTransportFailure(err) && L.canForceNetworkReload()) {
        setReloading(true);
        L.forceNetworkReload();
        return;                      /* the page is going away; leave it loading */
      }
      setError(err.message || t("err.generic"));
    } finally {
      setLoading(false);
    }
  };

  if (reloading) return <ReloadingScreen />;

  return (
    <div className="auth-screen">
      <div className="auth-card">
        <div className="auth-brand">
          <div className="logo" style={{ width: 38, height: 38, marginRight: 12 }} />
          <div>
            <div className="brand-name"><BrandName /></div>
            <div className="brand-tag">{L.BRAND.tagline}</div>
          </div>
        </div>

        <div className="auth-tabs">
          <button className={"auth-tab " + (tab === "login"    ? "on" : "")} onClick={() => { setTab("login");    setError(null); }}>{t("auth.signIn")}</button>
          <button className={"auth-tab " + (tab === "register" ? "on" : "")} onClick={() => { setTab("register"); setError(null); setNotice(null); }}>{t("auth.register")}</button>
        </div>

        <form onSubmit={submit} className="auth-form">
          {error  && <div className="auth-error">{error}</div>}
          {notice && <div className="auth-notice">{notice}</div>}
          {tab === "register" && !notice && (
            <div className="auth-note-sm">{t("auth.approvalNote")}</div>
          )}
          {tab === "register" && (
            <div className="field">
              <label>{t("auth.name")}</label>
              <input name="name" autoComplete="name" value={name} onChange={e => setName(e.target.value)} placeholder={t("auth.namePlaceholder")} required autoFocus />
            </div>
          )}
          <div className="field">
            <label>{t("auth.email")}</label>
            <input type="email" name="email" autoComplete="username" value={email} onChange={e => setEmail(e.target.value)}
                   placeholder="you@example.com" required autoFocus={tab === "login"} />
          </div>
          <div className="field">
            <label>{t("auth.password")}</label>
            <input type="password" name="password"
                   autoComplete={tab === "register" ? "new-password" : "current-password"}
                   value={password} onChange={e => setPassword(e.target.value)}
                   placeholder={tab === "register" ? t("auth.passwordHint") : "••••••••"} required />
          </div>
          <button type="submit" className="btn primary auth-submit" disabled={loading}>
            {loading ? t("common.pleaseWait") : (tab === "login" ? t("auth.signInAction") : t("auth.createAccount"))}
          </button>
        </form>

      </div>
    </div>
  );
}

/* ========================================================
   ROUTINES — scheduled prompts (cron) that run on the server
   ======================================================== */
const DOW = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
/* a weekday in the reader's language (4 January 2026 was a Sunday) */
const dowName = i => new Date(2026, 0, 4 + (i % 7)).toLocaleDateString(L.lang(), { weekday: "long" });
function cronToText(cron) {
  const f = String(cron || "").trim().split(/\s+/);
  if (f.length !== 5) return cron;
  const [m, h, dom, mon, dow] = f;
  /* a time of day as the reader writes it (8:00 AM, 08:00) */
  const at = (hh, mm) => L.fmtTime(new Date(2026, 0, 1, +hh, +mm).getTime());
  if (cron === "* * * * *") return t("cadence.minute");
  if (m === "0" && h === "*" && dom === "*" && mon === "*" && dow === "*") return t("cadence.hourly");
  if (/^\*\/\d+$/.test(m) && h === "*") return t("cadence.everyMinutes", { n: m.slice(2) });
  if (/^\d+$/.test(m) && /^\d+$/.test(h) && dom === "*" && mon === "*" && dow === "*") return t("cadence.dailyAt") + " " + at(h, m);
  if (/^\d+$/.test(m) && /^\d+$/.test(h) && dom === "*" && mon === "*" && dow === "1-5") return t("cadence.weekdaysAt") + " " + at(h, m);
  if (/^\d+$/.test(m) && /^\d+$/.test(h) && dom === "*" && mon === "*" && /^\d+$/.test(dow)) return t("cadence.weeklyAt", { day: dowName(+dow), time: at(h, m) });
  return cron;
}
/* The inverse: recover the preset + its inputs from a stored cron, so EDITING a
   routine opens the same controls that created it instead of dropping the user
   into raw cron. Anything we can't recognise stays custom, which is lossless. */
function cronToParts(cron) {
  const f = String(cron || "").trim().split(/\s+/);
  const out = { kind: "custom", time: "09:00", dow: 1, cron: String(cron || "0 9 * * *") };
  if (f.length !== 5) return out;
  const [m, h, dom, mon, dw] = f;
  const hhmm = () => String(+h).padStart(2, "0") + ":" + String(+m).padStart(2, "0");
  if (cron.trim() === "* * * * *") return { ...out, kind: "minute" };
  if (m === "0" && h === "*" && dom === "*" && mon === "*" && dw === "*") return { ...out, kind: "hourly" };
  if (/^\*\/30$/.test(m) && h === "*" && dom === "*" && mon === "*" && dw === "*") return { ...out, kind: "30min" };
  if (/^\d+$/.test(m) && /^\d+$/.test(h) && dom === "*" && mon === "*") {
    if (dw === "*")   return { ...out, kind: "daily",    time: hhmm() };
    if (dw === "1-5") return { ...out, kind: "weekdays", time: hhmm() };
    if (/^\d+$/.test(dw)) return { ...out, kind: "weekly", time: hhmm(), dow: +dw % 7 };
  }
  return out;
}

/* ============================================================
   ROUTINES — the ONE place scheduled work lives.

   A routine is a prompt plus a cadence. It runs in one of two modes:
     chat  — answers into its own conversation, on a provider + model you pick
     agent — runs a full turn on an agent (its workspace, files and tools),
             landing in that agent's transcript as a ⏰ turn. An enabled agent
             routine is what the sidebar calls a LOOP, and it's what promotes
             an agent into the Background tab.
   The mode is a field on the routine, not a different feature, so the same
   list, the same editor and the same controls cover both — and a routine can
   be moved between them without being recreated.
   ============================================================ */
/* Built per render, not once at load: a const would freeze these labels in
   whatever language the page happened to start in. Same for the other
   translated lists below. */
const routineCadences = () => [
  { key: "minute",   label: t("cadence.minuteTest") },
  { key: "30min",    label: t("cadence.halfHour") },
  { key: "hourly",   label: t("cadence.hourly") },
  { key: "daily",    label: t("cadence.daily") },
  { key: "weekdays", label: t("cadence.weekdays") },
  { key: "weekly",   label: t("cadence.weekly") },
  { key: "custom",   label: t("cadence.custom") },
];

function RoutinesPanel({ onClose, model, onOpenConv, onOpenAgent, agents, focusAgentId, onChanged, chatOn = true, startNew = false, workspaceId = null, apps = [], focusAppId = null }) {
  const [routines, setRoutines] = useState(null);
  const [err, setErr] = useState(null);
  const [busy, setBusy] = useState(false);
  const [view, setView] = useState("list");        /* list | editor */
  const [editId, setEditId] = useState(null);      /* null = creating */
  const [filter, setFilter] = useState(focusAgentId ? "agent" : "all");
  const [confirmDel, setConfirmDel] = useState(null);

  const mcpAvail    = L.toolEnabled("mcp");
  const skillsAvail = L.enabledSkills().length > 0;
  const searchAvail = L.toolEnabled("search");
  const provs = L.providersList();
  const agentList = agents || [];

  /* ---- the editor's form ----
     With plain chat switched off, routines run on agents only, and someone
     who has no agent yet can still make one: NEW_AGENT creates it on save. */
  const NEW_AGENT = "__new";
  const blank = () => ({
    title: "", prompt: "",
    mode: focusAgentId || !chatOn ? "agent" : "chat",
    /* your own agent, never a shared one by default: a routine on a shared
       agent writes its runs into a transcript everyone can read */
    agentId: focusAgentId || ((agentList.find(a => a.scope === "user") || {}).id) || NEW_AGENT,
    provider: L.getProvider() || (provs[0] && provs[0].name),
    model: model || "",
    kind: "daily", time: "09:00", dow: 1, cron: "0 9 * * *",
    tools: false, search: false, notify: true, quiet: "",
    /* the app it keeps up to date: the one it was opened from, if any */
    appId: focusAppId || "",
    /* every run without the agent's conversation (agent routines) */
    fresh: false,
  });
  const [f, setF] = useState(blank);
  const set = (k, v) => setF(prev => ({ ...prev, [k]: v }));
  const fModels = L.modelsFor(f.provider);

  /* Keep the model valid for the chosen provider — and for the chosen MODE.
     An agent routine carries no model, so converting one to chat arrives here
     with model:"" and must be defaulted, or it would save a chat routine with
     no model to answer from. */
  useEffect(() => {
    if (f.mode !== "chat") return;
    const m = L.modelsFor(f.provider);
    if (!m.some(x => x.id === f.model)) set("model", (m[0] && m[0].id) || "");
  }, [f.provider, f.mode]);

  /* ---- push notifications (shared by every routine on this device) ---- */
  const [pushState, setPushState] = useState({ supported: false, permission: "default", subscribed: false });
  const [pushBusy, setPushBusy] = useState(false);
  const refreshPush = () => L.Push.status().then(setPushState).catch(() => {});
  useEffect(() => { refreshPush(); }, []);
  const enableNotifications = async () => {
    setPushBusy(true); setErr(null);
    try { await L.Push.enable(); await L.Push.test(); await refreshPush(); }
    catch (e) { setErr(String(e.message || e)); }
    finally { setPushBusy(false); }
  };

  const load = () => L.RoutinesAPI.list().then(setRoutines).catch(e => setErr(String(e.message || e)));
  useEffect(() => { load(); if (startNew) openNew(); }, []);
  const changed = () => { load(); onChanged && onChanged(); };

  const buildCron = () => {
    const [hh, mm] = String(f.time || "09:00").split(":");
    if (f.kind === "minute")   return "* * * * *";
    if (f.kind === "30min")    return "*/30 * * * *";
    if (f.kind === "hourly")   return "0 * * * *";
    if (f.kind === "daily")    return `${+mm} ${+hh} * * *`;
    if (f.kind === "weekdays") return `${+mm} ${+hh} * * 1-5`;
    if (f.kind === "weekly")   return `${+mm} ${+hh} * * ${f.dow}`;
    return String(f.cron || "").trim();
  };

  const openNew = () => { setF(blank()); setEditId(null); setErr(null); setView("editor"); };
  const openEdit = r => {
    const parts = cronToParts(r.cron);
    const ep = provs.find(p => p.name === r.endpoint);
    setF({
      title: r.title || "", prompt: r.prompt || "",
      mode: r.mode || (r.agentId ? "agent" : "chat"),
      agentId: r.agentId || focusAgentId || (agentList[0] && agentList[0].id) || "",
      provider: (ep && ep.name) || L.getProvider() || (provs[0] && provs[0].name),
      model: r.model || "",
      kind: parts.kind, time: parts.time, dow: parts.dow, cron: parts.cron,
      tools: !!r.mcp, search: !!r.search, notify: r.notify !== false, quiet: r.quiet || "",
      appId: r.appId || "", fresh: !!r.fresh,
    });
    setEditId(r.id); setErr(null); setView("editor");
  };

  const save = async () => {
    setErr(null);
    if (!f.title.trim() || !f.prompt.trim()) { setErr(t("routine.errNeedTitle")); return; }
    const cron = buildCron();
    if (cron.trim().split(/\s+/).length !== 5) { setErr("A cron expression needs 5 fields: min hour dom mon dow."); return; }
    let body = {
      title: f.title.trim(), prompt: f.prompt.trim(), cron,
      tzOffset: new Date().getTimezoneOffset(), notify: f.notify, redact: "off",
      quiet: f.quiet.trim(),
    };
    if (f.mode === "agent") {
      if (!f.agentId) { setErr(t("routine.errNeedAgent")); return; }
      /* The agent brings its own model, tools and workspace, so none of the
         chat-side config applies; send null to clear it on a converted row. */
      body = { ...body, agentId: f.agentId, appId: f.appId || null, fresh: !!f.fresh };
    } else {
      const ep = provs.find(e => e.name === f.provider);
      if (!ep || !ep.base) { setErr(t("routine.errNeedProvider")); return; }
      if (!f.model) { setErr(t("routine.errNeedModel")); return; }
      body = {
        ...body, agentId: null,
        url: ep.base + ep.path, model: f.model, endpoint: ep.name,
        mcp: f.tools && mcpAvail, servers: f.tools ? L.enabledMcpServers() : [],
        skills: f.tools ? L.enabledSkills() : [],
        search: f.search && searchAvail,
      };
    }
    setBusy(true);
    try {
      if (body.agentId === NEW_AGENT) {
        const ag = await L.AgentsAPI.create({ name: f.title.trim(), description: platformDesc.routine(f.title.trim()), connections: "chosen", ...(workspaceId ? { workspaceId } : {}) });
        body = { ...body, agentId: ag.id };
        set("agentId", ag.id);
      }
      if (editId) await L.RoutinesAPI.update(editId, body);
      else await L.RoutinesAPI.create({ ...body, enabled: true });
      setView("list"); setEditId(null);
      changed();
    } catch (e) { setErr(String(e.message || e)); }
    finally { setBusy(false); }
  };

  const toggle = async r => { try { await L.RoutinesAPI.update(r.id, { enabled: !r.enabled }); } catch (e) { setErr(String(e.message || e)); } changed(); };
  const runNow = async r => { try { await L.RoutinesAPI.runNow(r.id); } catch (e) { setErr(String(e.message || e)); } setTimeout(changed, 1200); };
  const del    = async r => { try { await L.RoutinesAPI.remove(r.id); } catch (e) { setErr(String(e.message || e)); } setConfirmDel(null); changed(); };

  const fmt = ms => ms ? new Date(ms).toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }) : "—";
  const agentNameById = id => { const a = agentList.find(x => x.id === id); return a ? (agentName(a) || "Agent") : "deleted agent"; };
  const isAgent = r => (r.mode || (r.agentId ? "agent" : "chat")) === "agent";

  const all = routines || [];
  const shown = all.filter(r => {
    if (focusAgentId && filter === "agent") return r.agentId === focusAgentId;
    if (filter === "chat")  return !isAgent(r);
    if (filter === "agent") return isAgent(r);
    return true;
  });
  const counts = { all: all.length, chat: all.filter(r => !isAgent(r)).length, agent: all.filter(isAgent).length };

  /* ---------------- editor ---------------- */
  const editor = (
    <>
      <div className="field"><label>{t("common.title")}</label>
        <input value={f.title} onChange={e => set("title", e.target.value)}
               placeholder={f.mode === "agent" ? t("routine.egTitle1") : t("routine.egTitle2")} /></div>
      <div className="field">
        <label>{f.mode === "agent" ? t("routine.missionLabel") : "Prompt"}</label>
        <textarea value={f.prompt} onChange={e => set("prompt", e.target.value)} rows={3}
                  placeholder={f.mode === "agent"
                    ? t("routine.egPrompt1")
                    : t("routine.egPrompt2")} /></div>

      {/* With plain chat off, a new routine runs on an agent and there is no
          choice to explain; an existing chat routine still shows where it runs. */}
      {(chatOn || f.mode === "chat") && (
      <div className="field"><label>{t("routine.runsAs")}</label>
        <div className="mode-seg">
          <button className={f.mode === "chat" ? "on" : ""} onClick={() => set("mode", "chat")}>
            <ClockIcon /> Chat
            <span>{t("routine.chatModeSub")}</span>
          </button>
          <button className={f.mode === "agent" ? "on" : ""} onClick={() => set("mode", "agent")}>
            <BotIcon /> Agent
            <span>{t("routine.agentModeSub")}</span>
          </button>
        </div>
      </div>
      )}

      {f.mode === "agent" ? (
        <>
          <div className="field"><label>Agent</label>
            <select value={f.agentId} onChange={e => set("agentId", e.target.value)}>
              {agentList.map(a => <option key={a.id} value={a.id}>{agentName(a) || "Agent"}{a.scope === "global" ? " (shared)" : ""}</option>)}
              <option value={NEW_AGENT}>{t("routine.newAgentOption")}</option>
            </select></div>
          <div className="note">{tb("routine.agentModeNote", { tab: t("sidebar.background") })}</div>
          {/* An app it keeps up to date: each run is told which one, and to
              write what it finds into that app's data. */}
          {(apps.length > 0 || f.appId) && (
            <div className="field"><label>{t("routine.appLabel")}</label>
              <select value={f.appId} onChange={e => set("appId", e.target.value)}>
                <option value="">{t("routine.appNone")}</option>
                {apps.map(a => <option key={a.id} value={a.id}>{(a.icon ? a.icon + " " : "") + appName(a)}</option>)}
                {f.appId && !apps.some(a => a.id === f.appId) && <option value={f.appId}>{t("app.thisApp")}</option>}
              </select>
              <span className="hint">{t("routine.appHint")}</span></div>
          )}
          {/* A job that keeps what it learns in files, a wiki or an app needs
              nothing from yesterday's conversation, and carrying it along is
              what fills a small model's window. */}
          <div className="routine-row">
            <button className={"tool-toggle " + (f.fresh ? "on" : "")} onClick={() => set("fresh", !f.fresh)}>
              ⟲ {t("routine.fresh")}
            </button>
            <span className="hint">{t("routine.freshHint")}</span>
          </div>
        </>
      ) : (
        <>
          <div className="routine-grid">
            <div className="field"><label>{t("topbar.provider")}</label>
              <select value={f.provider} onChange={e => set("provider", e.target.value)}>
                {provs.map(p => <option key={p.name} value={p.name}>{L.providerLabel(p.name) || p.name}</option>)}
              </select></div>
            <div className="field"><label>{t("topbar.model")}</label>
              <select value={f.model} onChange={e => set("model", e.target.value)}>
                {fModels.map(m => <option key={m.id} value={m.id}>{m.label}</option>)}
              </select></div>
          </div>
          <div className="routine-row">
            {searchAvail && (
              <button className={"tool-toggle " + (f.search ? "on" : "")} onClick={() => set("search", !f.search)}>
                <SearchIcon /> {t("tools.search")}
              </button>
            )}
            {(mcpAvail || skillsAvail) && (
              <button className={"tool-toggle " + (f.tools ? "on" : "")} onClick={() => set("tools", !f.tools)}>
                <ToolsIcon /> Tools
              </button>
            )}
          </div>
        </>
      )}

      <div className="routine-grid">
        <div className="field"><label>{t("routine.cadence")}</label>
          <select value={f.kind} onChange={e => set("kind", e.target.value)}>
            {routineCadences().map(c => <option key={c.key} value={c.key}>{c.label}</option>)}
          </select></div>
        {(f.kind === "daily" || f.kind === "weekly" || f.kind === "weekdays") && (
          <div className="field"><label>{t("routine.time")}</label>
            <input type="time" value={f.time} onChange={e => set("time", e.target.value)} /></div>
        )}
        {f.kind === "weekly" && (
          <div className="field"><label>{t("routine.day")}</label>
            <select value={f.dow} onChange={e => set("dow", +e.target.value)}>
              {DOW.map((d, i) => <option key={i} value={i}>{dowName(i)}</option>)}
            </select></div>
        )}
        {f.kind === "custom" && (
          <div className="field"><label>{t("routine.cron")}</label>
            <input value={f.cron} onChange={e => set("cron", e.target.value)} placeholder="0 9 * * 1-5" spellCheck="false" /></div>
        )}
      </div>

      <div className="routine-row">
        <button className={"tool-toggle " + (f.notify ? "on" : "")} onClick={() => set("notify", !f.notify)}
                title={t("routine.notifyHint")}>
          <BellIcon /> {t("routine.notify")}
        </button>
        <span className="hint">{t("routine.localTime")} <code>{buildCron()}</code></span>
      </div>

      {/* "Nothing to report" should not buzz a phone: an answer that starts
          with this text is kept in the transcript but sends no push. */}
      <div className="field"><label>{t("routine.quiet")}</label>
        <input value={f.quiet} onChange={e => set("quiet", e.target.value)}
               placeholder={t("routine.quietPlaceholder")} maxLength={120} spellCheck="false" />
        <span className="hint">{t("routine.quietHint")}</span></div>

      {L.Push.supported() && f.notify && !(pushState.subscribed && pushState.permission === "granted") && (
        <div className="push-row">
          <button className="btn" onClick={enableNotifications} disabled={pushBusy}>
            <BellIcon /> {pushBusy ? t("push.enabling") : t("push.enable")}
          </button>
        </div>
      )}

      {err && <div className="auth-error" style={{ marginTop: 4 }}>{err}</div>}
    </>
  );

  /* ---------------- list ---------------- */
  const list = (
    <>
      <div className="note">{tb("routine.panelNote")}</div>

      <div className="routine-filters">
        {[["all", t("common.all")], ["chat", "Chat"], ["agent", "Agent"]].filter(([k]) => k !== "chat" || chatOn || counts.chat > 0).map(([k, lbl]) => (
          <button key={k} className={"rf-tab " + (filter === k ? "on" : "")} onClick={() => setFilter(k)}>
            {lbl} <span>{counts[k]}</span>
          </button>
        ))}
        <span style={{ flex: 1 }} />
        <button className="btn primary" onClick={openNew}>+ {t("routine.new")}</button>
      </div>
      {focusAgentId && filter === "agent" && (
        <div className="hint" style={{ marginTop: -4 }}>
          {tb("routine.filterNote", { all: t("common.all") })}
        </div>
      )}

      {routines == null ? <div className="note">{t("common.loading")}</div>
        : shown.length === 0 ? (
          <div className="note">
            {all.length === 0 ? t("routine.empty")
                              : t("routine.emptyFilter")}
          </div>
        ) : (
          <div className="routine-list">
            {shown.map(r => (
              <div className={"routine-item " + (r.enabled ? "" : "off")} key={r.id}>
                <div className="ri-main">
                  <div className="ri-title">
                    <span className={"ri-mode " + (isAgent(r) ? "agent" : "chat")}>
                      {isAgent(r) ? "◉ agent" : "⏰ chat"}
                    </span>
                    {r.title}
                  </div>
                  <div className="ri-meta">
                    <span>{cronToText(r.cron)}</span>
                    <span className="ri-dot">·</span>
                    <span>{isAgent(r)
                      ? agentNameById(r.agentId)
                      : (L.findModel(r.model) ? L.findModel(r.model).label : r.model)}</span>
                    {!isAgent(r) && r.search && <><span className="ri-dot">·</span><span>{t("tools.search")}</span></>}
                    {!isAgent(r) && r.mcp && <><span className="ri-dot">·</span><span>{t("tools.tools")}</span></>}
                    {r.appId && <><span className="ri-dot">·</span><span className="ri-app">▦ {appName(apps.find(a => a.id === r.appId) || {}) || t("app.thisApp")}</span></>}
                    {isAgent(r) && r.fresh && <><span className="ri-dot">·</span><span title={t("routine.freshHint")}>⟲ {t("routine.freshBadge")}</span></>}
                    {r.notify && <><span className="ri-dot">·</span><span>{t("routine.notify")}</span></>}
                    {r.quiet && <><span className="ri-dot">·</span><span title={r.quiet}>{t("routine.quietBadge")}</span></>}
                    {r.precheck && <><span className="ri-dot">·</span><span title={t("routine.precheckHint")}>{t("routine.precheckBadge", { tool: r.precheck.tool })}</span></>}
                  </div>
                  <div className="ri-meta sub">
                    {r.enabled ? <>Next: {fmt(r.nextRun)}</> : <>{t("routine.paused")}</>}
                    {r.lastRun && <><span className="ri-dot">·</span>Last: {fmt(r.lastRun)} ({r.lastStatus || "—"})</>}
                  </div>
                  <div className="ri-prompt">{r.prompt}</div>
                </div>
                <div className="ri-actions">
                  {confirmDel === r.id ? (
                    <>
                      <span className="ri-confirm">{t("common.deleteQ")}</span>
                      <button className="act-btn danger" onClick={() => del(r)}>{t("common.deleteYes")}</button>
                      <button className="act-btn" onClick={() => setConfirmDel(null)}>{t("common.cancel")}</button>
                    </>
                  ) : (
                    <>
                      {isAgent(r)
                        ? <button className="act-btn" onClick={() => { onOpenAgent && onOpenAgent(r.agentId); onClose(); }}>{t("routine.openAgent")}</button>
                        : r.convId && <button className="act-btn" onClick={() => { onOpenConv(r.convId); onClose(); }}>{t("common.open")}</button>}
                      <button className="act-btn" onClick={() => runNow(r)}>{t("routine.runNow")}</button>
                      <button className="act-btn" onClick={() => toggle(r)}>{r.enabled ? "◼ Pause" : "▶ Resume"}</button>
                      <button className="act-btn" onClick={() => openEdit(r)}>{t("common.edit")}</button>
                      <button className="act-btn danger" onClick={() => setConfirmDel(r.id)}>{t("common.delete")}</button>
                    </>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      {err && <div className="auth-error">{err}</div>}
    </>
  );

  return (
    <div className="modal-scrim" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal routines-modal">
        <div className="modal-head">
          <div>
            <span className="eb">{view === "list" ? t("routine.subtitle") : (editId ? t("common.edit") : t("common.new"))}</span>
            <h2>{view === "list" ? t("routine.nav") : (editId ? t("routine.edit") : t("routine.new"))}</h2>
          </div>
          <button className="modal-x" onClick={onClose}>✕</button>
        </div>
        <div className="modal-body">{view === "list" ? list : editor}</div>
        {view === "editor" && (
          <div className="modal-foot">
            <span style={{ flex: 1 }} />
            <button className="btn" onClick={() => { setView("list"); setErr(null); }}>{t("common.cancel")}</button>
            <button className="btn primary" onClick={save} disabled={busy}>
              {busy ? "Saving…" : (editId ? t("common.saveChanges") : t("routine.create"))}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

/* ---------- markdown body ---------- */
function Markdown({ text, mermaid }) {
  const ref = useRef(null);
  useEffect(() => { if (!ref.current) return; L.decorateCode(ref.current); if (mermaid) renderMermaidIn(ref.current); });
  return (
    <div className="msg-body md" ref={ref}
         dangerouslySetInnerHTML={{ __html: L.renderMarkdown(text) }} />
  );
}

/* ---------- generated-file download card ---------- */
const faLabel = () => ({ xlsx: t("file.xlsx"), docx: t("file.docx"), pdf: t("file.pdf") });
function FileArtifact({ art }) {
  const [state, setState] = useState("idle");   /* idle | working | done | error */
  const [err, setErr] = useState("");
  const kind = art.kind;
  const base = (art.title || "document").replace(/\.[a-z0-9]{2,5}$/i, "").trim() || "document";
  const name = base + "." + kind;
  const download = async () => {
    if (state === "working" || art.pending) return;
    setState("working"); setErr("");
    try { await L.generateFile(kind, art.title || base, art.body); setState("done"); }
    catch (e) { setErr((e && e.message) || t("file.genFailed")); setState("error"); }
  };
  return (
    <div className={"file-art " + (art.pending ? "pending" : "")}>
      <span className="fa-ic"><FileGenIcon /></span>
      <span className="fa-meta">
        <span className="fa-name">{name}</span>
        <span className="fa-kind">
          {art.pending ? t("file.preparing") : (faLabel()[kind] || kind.toUpperCase())}
          {state === "error" && <span className="fa-err"> · {err}</span>}
        </span>
      </span>
      {!art.pending && (
        <button className="fa-btn" onClick={download} disabled={state === "working"}>
          {state === "working" ? t("file.generating") : state === "done" ? t("file.downloadAgain") : (state === "error" ? "Retry" : "Download")}
        </button>
      )}
    </div>
  );
}

/* A file the agent produced this turn — download straight from its workspace. */
function AgentFileCard({ file, onDownload }) {
  const [state, setState] = useState("idle");   /* idle | working | error */
  const [err, setErr] = useState("");
  const go = async () => {
    if (state === "working") return;
    setState("working"); setErr("");
    try { await onDownload(file.path); setState("idle"); }
    catch (e) { setErr((e && e.message) || t("file.downloadFailed")); setState("error"); }
  };
  return (
    <div className="file-art">
      <span className="fa-ic"><FileGenIcon /></span>
      <span className="fa-meta">
        <span className="fa-name">{file.path}</span>
        <span className="fa-kind">
          {fmtBytes(file.size)}
          {state === "error" && <span className="fa-err"> · {err}</span>}
        </span>
      </span>
      <button className="fa-btn" onClick={go} disabled={state === "working"}>
        {state === "working" ? t("file.downloading") : state === "error" ? "Retry" : "Download"}
      </button>
    </div>
  );
}

/* ---------- one tool call ----------
   Collapsed it is a single line. Opened it shows the FULL arguments and the
   full result — the command that actually ran, the path it wrote, the payload
   it got back — which the summary line necessarily truncates. */
/* A tool result often ENDS in a link the user is meant to click — an Excel
   export, a generated report. The compact row would show it as truncated plain
   text, so surface the first markdown link as a real anchor.
   (Contributed back from the crefo deployment.) */
function toolResultLink(res) {
  if (!res) return null;
  const m = String(res).match(/\[([^\]]*)\]\((https?:\/\/[^\s)]+)\)/);
  if (!m) return null;
  return {
    label: m[1] || "Open",
    url: m[2],
    download: /\/(export|download)|\.(xlsx|xls|csv|docx|pdf|zip|json)(\?|$)/i.test(m[2]),
  };
}

/* ---------- a tool's view (MCP Apps, and the older MCP-UI) ----------
   server.js keeps a call whose tool has a view (mcp_views) and the step
   carries ui.viewId. The view's page comes from /api/mcp-views/:id/frame,
   served with the policy its server declared, and runs sandboxed without
   allow-same-origin: an opaque origin, no cookie, no storage, no API of
   this app. It speaks MCP Apps (JSON-RPC over postMessage, protocol
   2026-01-26) with the bridge below, which answers only that frame: its own
   server's tools and resources through the app, links (http and https
   only), a message into the message box (the person sends it), context for
   the agent's next turn, full screen, downloads. Older MCP-UI pages post
   {type, payload} messages; the bridge takes those too. */
const MCP_UI_PROTOCOL = "2026-01-26";
const VIEW_CONTEXT = new Map();   /* agent or conversation id -> what a view wants the next turn to know */
/* the newest context a view left for this agent or chat, taken once */
function takeViewContext(key) {
  const c = key && VIEW_CONTEXT.get(key);
  if (!c) return "";
  VIEW_CONTEXT.delete(key);
  return "[What the " + c.tool + " view shows the person now: " + c.text.slice(0, 4000) + "]";
}
const viewTextOf = content => (Array.isArray(content) ? content : content ? [content] : [])
  .map(c => (c && c.type === "text" && typeof c.text === "string" ? c.text : "")).filter(Boolean).join("\n").trim();
function viewHostStyles() {
  const cs = getComputedStyle(document.documentElement), v = n => cs.getPropertyValue(n).trim() || undefined;
  return { variables: {
    "--color-background-primary": v("--surface"), "--color-background-secondary": v("--surface-2"), "--color-background-tertiary": v("--surface-3"),
    "--color-text-primary": v("--ink"), "--color-text-secondary": v("--ink-2"), "--color-text-tertiary": v("--ink-3"), "--color-text-danger": v("--maroon"),
    "--color-border-primary": v("--line"), "--color-border-secondary": v("--line-2"), "--color-ring-primary": v("--terra"),
    "--font-sans": v("--sans"), "--font-mono": v("--mono"), "--border-radius-md": v("--rad"), "--border-radius-lg": v("--rad-lg"),
  } };
}
function McpView({ viewId }) {
  const [info, setInfo] = useState(null);
  const [err, setErr] = useState(null);
  const [height, setHeight] = useState(180);
  const [full, setFull] = useState(false);
  const [gone, setGone] = useState(false);
  const [link, setLink] = useState(null);
  const [pending, setPending] = useState([]);
  const frameRef = useRef(null);
  const st = useRef({ ready: false, download: null });
  const theme = useTheme();
  useEffect(() => { let off = false; L.McpViewsAPI.get(viewId).then(r => { if (!off) setInfo(r); }).catch(e => { if (!off) setErr((e && e.message) || t("view.failed")); }); return () => { off = true; }; }, [viewId]);
  const post = msg => { const w = frameRef.current && frameRef.current.contentWindow; if (w) { try { w.postMessage(msg, "*"); } catch {} } };
  const context = () => ({
    theme: currentTheme(), styles: viewHostStyles(), displayMode: full ? "fullscreen" : "inline", availableDisplayModes: ["inline", "fullscreen"],
    containerDimensions: full ? {} : { maxHeight: 720 }, locale: L.lang ? L.lang() : "en", timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    platform: "web", userAgent: "indie.chat", deviceCapabilities: { touch: "ontouchstart" in window, hover: matchMedia("(hover: hover)").matches },
    ...(info && info.tool && info.tool.name ? { toolInfo: { tool: { name: info.tool.name, description: info.tool.description || "", inputSchema: info.tool.inputSchema || { type: "object", properties: {} } } } } : {}),
  });
  /* the host's side of the protocol, for this frame only */
  useEffect(() => {
    if (!info || info.error || info.kind === "url") return;
    const reply = (id, result) => post({ jsonrpc: "2.0", id, result });
    const fail = (id, code, message) => post({ jsonrpc: "2.0", id, error: { code, message: String(message || "error").slice(0, 300) } });
    const legacyReply = (messageId, payload) => post({ type: "ui-message-response", messageId, payload });
    const openLink = u => {
      let url = null; try { const x = new URL(String(u || "")); if (x.protocol === "https:" || x.protocol === "http:") url = x.href; } catch {}
      if (!url) return false;
      const w = window.open(url, "_blank", "noopener,noreferrer");
      if (!w) setLink(url);
      return true;
    };
    const compose = text => window.dispatchEvent(new CustomEvent("indie:compose", { detail: { text: text.slice(0, 4000), agentId: info.agentId || null, convId: info.convId || null } }));
    /* a file only when the person just did something (a click in the view
       counts): otherwise it waits as a button they click, so a page cannot
       drop files into Downloads by itself */
    const activeNow = () => !navigator.userActivation || navigator.userActivation.isActive;
    const download = (contents, asked) => {
      if (!asked && !activeNow()) { setPending(cur => [...cur, ...(Array.isArray(contents) ? contents : []).slice(0, 10)].slice(0, 10)); return; }
      for (const c of (Array.isArray(contents) ? contents : []).slice(0, 10)) {
        const r = c && c.type === "resource" && c.resource;
        if (r && (typeof r.text === "string" || typeof r.blob === "string")) {
          const bytes = typeof r.blob === "string" ? Uint8Array.from(atob(r.blob), ch => ch.charCodeAt(0)) : new TextEncoder().encode(r.text);
          const a = document.createElement("a");
          a.href = URL.createObjectURL(new Blob([bytes], { type: r.mimeType || "application/octet-stream" }));
          a.download = (String(r.uri || "").split("/").pop() || "download").replace(/[\\/:*?"<>|]+/g, "_").slice(0, 120);
          document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 30000);
        } else if (c && c.type === "resource_link" && c.uri) openLink(c.uri);
      }
    };
    const onMsg = async ev => {
      if (!frameRef.current || ev.source !== frameRef.current.contentWindow) return;
      const d = ev.data;
      if (!d || typeof d !== "object") return;
      if (d.jsonrpc === "2.0" && typeof d.method === "string") {
        const { id, method } = d, p = d.params || {};
        try {
          switch (method) {
            case "ui/initialize":
              return reply(id, { protocolVersion: MCP_UI_PROTOCOL, hostInfo: { name: "indie.chat", version: "1.0.0" },
                hostCapabilities: { openLinks: {}, downloadFile: {}, serverTools: {}, serverResources: {}, logging: {}, message: { text: {} }, updateModelContext: { text: {} },
                  sandbox: { csp: info.csp || {} } },
                hostContext: context() });
            case "ui/notifications/initialized":
              st.current.ready = true;
              post({ jsonrpc: "2.0", method: "ui/notifications/tool-input", params: { arguments: info.args || {} } });
              post({ jsonrpc: "2.0", method: "ui/notifications/tool-result", params: info.result || { content: [] } });
              return;
            case "ui/notifications/size-changed":
              if (typeof p.height === "number" && p.height > 0) setHeight(Math.max(40, Math.min(720, Math.ceil(p.height))));
              return;
            case "ui/notifications/request-teardown": setGone(true); return;
            case "notifications/message": return;
            case "ping": return reply(id, {});
            case "tools/call": return reply(id, await L.McpViewsAPI.call(viewId, String(p.name || ""), p.arguments || {}));
            case "resources/read": return reply(id, await L.McpViewsAPI.resource(viewId, String(p.uri || "")));
            case "ui/open-link": return openLink(p.url) ? reply(id, {}) : fail(id, -32000, "Invalid URL");
            case "ui/message": { const text = viewTextOf(p.content); if (!text) return fail(id, -32000, "Invalid message format"); compose(text); return reply(id, {}); }
            case "ui/update-model-context": {
              const text = [viewTextOf(p.content), p.structuredContent ? JSON.stringify(p.structuredContent).slice(0, 3000) : ""].filter(Boolean).join("\n");
              const key = info.agentId || info.convId;
              if (key) { if (text) VIEW_CONTEXT.set(key, { tool: info.tool.name, text }); else VIEW_CONTEXT.delete(key); }
              return reply(id, {});
            }
            case "ui/request-display-mode": { const mode = p.mode === "fullscreen" ? "fullscreen" : "inline"; setFull(mode === "fullscreen"); return reply(id, { mode }); }
            case "ui/download-file": download(p.contents); return reply(id, {});
            default: if (id != null) return fail(id, -32601, "Method not found: " + method);
          }
        } catch (e) { if (id != null) fail(id, -32000, (e && e.message) || e); }
        return;
      }
      /* the older MCP-UI messages */
      const mid = d.messageId, pl = d.payload || {};
      try {
        if (d.type === "ui-lifecycle-iframe-ready") return post({ type: "ui-lifecycle-iframe-render-data", payload: { renderData: { toolInput: info.args || {}, toolOutput: info.result && info.result.structuredContent, theme: currentTheme(), locale: L.lang ? L.lang() : "en" } } });
        if (d.type === "ui-size-change") { if (typeof pl.height === "number" && pl.height > 0) setHeight(Math.max(40, Math.min(720, Math.ceil(pl.height)))); return; }
        if (mid) post({ type: "ui-message-received", messageId: mid });
        if (d.type === "tool") { const r = await L.McpViewsAPI.call(viewId, String(pl.toolName || ""), pl.params || {}); return mid && legacyReply(mid, { response: r }); }
        if (d.type === "prompt" && pl.prompt) { compose(String(pl.prompt)); return mid && legacyReply(mid, { response: { ok: true } }); }
        if (d.type === "intent" && pl.intent) { compose(String(pl.intent) + (pl.params ? " " + JSON.stringify(pl.params) : "")); return mid && legacyReply(mid, { response: { ok: true } }); }
        if (d.type === "link" && pl.url) return mid && legacyReply(mid, openLink(pl.url) ? { response: { ok: true } } : { error: "Invalid URL" });
        if (d.type === "notify") return mid && legacyReply(mid, { response: { ok: true } });
      } catch (e) { if (mid) legacyReply(mid, { error: (e && e.message) || String(e) }); }
    };
    st.current.download = download;
    window.addEventListener("message", onMsg);
    return () => window.removeEventListener("message", onMsg);
  }, [info, full, viewId]);
  /* what changed on the host: the theme, full screen */
  useEffect(() => { if (st.current.ready) post({ jsonrpc: "2.0", method: "ui/notifications/host-context-changed", params: { theme: currentTheme(), styles: viewHostStyles() } }); }, [theme]);
  useEffect(() => { if (st.current.ready) post({ jsonrpc: "2.0", method: "ui/notifications/host-context-changed", params: { displayMode: full ? "fullscreen" : "inline", containerDimensions: full ? {} : { maxHeight: 720 } } }); }, [full]);
  useEffect(() => { if (!full) return; const k = e => { if (e.key === "Escape") setFull(false); }; window.addEventListener("keydown", k); return () => window.removeEventListener("keydown", k); }, [full]);
  if (gone) return null;
  if (err) return <div className="mcp-view-note">{t("view.failed")}: {err}</div>;
  if (!info) return <div className="mcp-view-note">{t("common.loading")}</div>;
  if (info.error) return <div className="mcp-view-note">{t("view.failed")}: {info.error}</div>;
  const frame = info.kind === "url"
    ? <iframe className="mcp-view-frame" src={info.url} title={info.tool.name} sandbox="allow-scripts allow-same-origin allow-forms" referrerPolicy="no-referrer" style={{ height: full ? "100%" : 420 }} />
    : <iframe ref={frameRef} className="mcp-view-frame" src={L.McpViewsAPI.frameUrl(viewId)} title={info.tool.name} sandbox="allow-scripts allow-forms" referrerPolicy="no-referrer"
              style={{ height: full ? "100%" : height }} />;
  return (
    <div className={"mcp-view" + (info.prefersBorder === false ? " bare" : "") + (full ? " full" : "")}>
      <div className="mcp-view-head">
        <span className="mcp-view-src" title={t("view.fromServer", { server: info.server })}>{info.server} · {info.tool.name}</span>
        <button className="mcp-view-btn" onClick={() => setFull(f => !f)} title={full ? t("view.inline") : t("view.fullscreen")}>{full ? "✕" : "⤢"}</button>
      </div>
      {frame}
      {link && <a className="mcp-view-link" href={link} target="_blank" rel="noopener noreferrer" onClick={() => setLink(null)}>↗ {t("view.openLink")} {link.slice(0, 80)}</a>}
      {pending.length > 0 && (
        <div className="mcp-view-link">
          {pending.map((c, i) => (
            <button key={i} className="mcp-view-dl" onClick={() => { st.current.download && st.current.download([c], true); setPending(cur => cur.filter((_, j) => j !== i)); }}>
              ⬇ {(String((c.resource && c.resource.uri) || c.uri || "").split("/").pop() || "download").slice(0, 80)}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function ToolStep({ step }) {
  const [open, setOpen] = useState(false);
  const args = step.arguments;
  const argText = args == null ? "" : (typeof args === "string" ? args : JSON.stringify(args));
  const res = step.result;
  const link = toolResultLink(res);
  const hasDetail = !!argText || res != null;
  /* Tool args and results are usually JSON, often JSON-in-a-string; pretty-print
     when it parses, show it verbatim when it doesn't. */
  const pretty = v => {
    if (v == null) return "";
    let out;
    if (typeof v === "string") { try { out = JSON.stringify(JSON.parse(v), null, 2); } catch { out = v; } }
    else { try { out = JSON.stringify(v, null, 2); } catch { out = String(v); } }
    return out.length > 20000 ? out.slice(0, 20000) + "\n… truncated for display" : out;
  };
  return (
    <div className={"tool-step " + (step.isError ? "err " : "") + (open ? "open" : "")}>
      <button className="ts-row" onClick={() => hasDetail && setOpen(o => !o)}
              title={hasDetail ? (open ? t("tool.hideDetails") : t("tool.showDetails")) : undefined}>
        <span className="ts-ic"><ToolsIcon /></span>
        <span className="ts-name">{step.name}</span>
        <span className="ts-args">{argText}</span>
        <span className="ts-res">{res == null ? "…" : "→ " + String(res).replace(/\s+/g, " ").slice(0, 120)}</span>
        {hasDetail && <span className="ts-caret">{open ? "▾" : "▸"}</span>}
      </button>
      {link && (
        <a className="ts-link" href={link.url} target="_blank" rel="noopener noreferrer"
           {...(link.download ? { download: "" } : {})}>
          {link.download ? "⬇ " : "↗ "}{link.label}
        </a>
      )}
      {step.ui && step.ui.viewId && <McpView viewId={step.ui.viewId} />}
      {open && (
        <div className="ts-detail">
          {argText && (<>
            <div className="ts-lbl mono">{t("tool.arguments")}</div>
            <pre>{pretty(args)}</pre>
          </>)}
          <div className="ts-lbl mono">{res == null ? t("tool.resultRunning") : step.isError ? "Error" : "Result"}</div>
          {res != null && <pre>{pretty(res)}</pre>}
        </div>
      )}
    </div>
  );
}

/* ---------- one message ---------- */
/* What an agent proposed for itself in a turn (server.js, setting an agent
   up by talking): a connection it needs, or its own standing instructions.
   A connection opens the agent's Connections at that service; instructions
   are applied in the person's own request. Either says when it is done. */
const SERVICE_GROUP = { google_gmail: "mail", google_drive: "files", google_calendar: "calendar",
                        ms_outlook: "mail", ms_onedrive: "files", ms_calendar: "calendar", ms_teams: "messenger", imap_mail: "mail" };
function ProposalCard({ p, state, onAct }) {
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(null);
  if (p.kind === "connection") {
    const have = (state.granted || {})[p.service];
    const enough = !!have && (p.access === "read" || have !== "read");
    return (
      <div className="proposal-card">
        <ConnGlyph group={SERVICE_GROUP[p.service] || "other"} />
        <div className="proposal-main">
          <div className="proposal-title">{t("prop.connTitle", { name: serviceName(p.service, p.name), access: window.IndieConn.accessLabel(p.service, p.access) })}</div>
          {p.why && <div className="proposal-why">{p.why}</div>}
        </div>
        {enough ? <span className="conn-chip on">{t("conn.added")}</span>
          : <button className="btn primary" onClick={() => onAct(p)}>{t("prop.connAdd", { name: serviceName(p.service, p.name) })}</button>}
      </div>
    );
  }
  const applied = typeof state.instructions === "string" && state.instructions.trim() === String(p.text || "").trim();
  const apply = async () => { setBusy(true); setErr(null); try { await onAct(p); } catch (e) { setErr((e && e.message) || String(e)); } finally { setBusy(false); } };
  return (
    <div className="proposal-card col">
      <div className="proposal-title">{t("prop.instrTitle")}</div>
      {p.why && <div className="proposal-why">{p.why}</div>}
      <pre className="proposal-text">{p.text}</pre>
      <div className="proposal-acts">
        {applied ? <span className="conn-chip on">{t("prop.applied")}</span>
          : state.mayEdit ? <button className="btn primary" disabled={busy} onClick={apply}>{busy ? "…" : t("prop.apply")}</button>
          : <span className="proposal-why">{t("prop.instrNotYours")}</span>}
        {err && <span className="proposal-err">{err}</span>}
      </div>
    </div>
  );
}
function Message({ m, modelLabel, provider, requestedLabel, mismatch, streaming, isLast, busy, onEdit, onRegenerate, onRetry, onDownloadFile, onProposal, proposalState, onFresh, onLarger, manageNote }) {
  const [copied, setCopied] = useState(false);
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState("");
  const [reasonOpen, setReasonOpen] = useState(null);   /* null = auto */
  const isUser = m.role === "user";

  /* Reasoning may arrive as a dedicated field (reasoning_content) and/or inline
     as <think>…</think> in the content. Merge both; the answer is content with
     any <think> block stripped out. */
  const split = !isUser && L.splitThink ? L.splitThink(m.content || "") : { think: "", rest: m.content || "" };
  const reasoning = !isUser ? [m.reasoning, split.think].filter(Boolean).join("\n").trim() : "";
  const answer = isUser ? m.content : split.rest;
  /* Pull any ```file:<kind> blocks out of the answer -> download cards. */
  const arts = (!isUser && L.extractFileArtifacts) ? L.extractFileArtifacts(answer) : { text: answer, artifacts: [] };
  const bodyText  = isUser ? m.content : arts.text;
  const artifacts = arts.artifacts || [];
  const autoOpen = streaming && !(answer || "").trim();   /* expand while still thinking */
  const reasonShown = reasonOpen === null ? autoOpen : reasonOpen;

  const copy = () => {
    /* L.copyText falls back for insecure origins (plain-http LAN deployments),
       where navigator.clipboard does not exist at all. */
    Promise.resolve(L.copyText(isUser ? m.content : (bodyText || ""))).then(ok => {
      if (ok !== false) { setCopied(true); setTimeout(() => setCopied(false), 1200); }
    });
  };
  const startEdit = () => { setDraft(m.content || ""); setEditing(true); };
  const saveEdit  = () => { const t = draft.trim(); if (t) { onEdit(t); setEditing(false); } };
  return (
    <div className={"msg " + (isUser ? "user" : "bot")}>
      <div className="msg-head">
        <span className="msg-sq" />
        <span className="msg-role">{isUser ? "You" : modelLabel}</span>
        {isUser && m.scheduled && <span className="msg-provider" title={t("msg.scheduledHint")}>⏰ scheduled</span>}
        {!isUser && provider && <span className="msg-provider">via {provider}</span>}
        {m.ts && <span className="msg-time">{L.clock(m.ts)}</span>}
      </div>
      {!isUser && mismatch && (
        <div className="model-warn">
          <span className="warn-ic">⚠</span>
          {tb("msg.modelMismatch", { asked: requestedLabel, provider: provider || t("msg.theProvider"), got: modelLabel })}
        </div>
      )}
      {m.searched && (
        <div className="search-pill"><span className="tt-dot" /> {t("msg.searchedWeb")}</div>
      )}
      {m.redactions != null && (
        <div className="redaction-note">
          <span className="rn-ic"><ShieldIcon /></span>
          {m.redactions
            ? <span>{t("msg.redactedBefore")} · <b>{L.redactionSummary(m.redactionTypes) || t("msg.redactedItems", { n: m.redactions })}</b></span>
            : <span>{t("msg.nothingRedacted")}</span>}
        </div>
      )}
      {m.images && m.images.length > 0 && (
        <div className="msg-images">
          {m.images.map((im, i) => (
            <img key={i} className="msg-img" src={im.dataUrl} alt={im.name || "image"} title={im.name || ""} />
          ))}
        </div>
      )}
      {m.attachments && m.attachments.length > 0 && (
        <div className="msg-attach">
          {m.attachments.map((a, i) => (
            <div key={i} className={"chip " + (a.binary ? "bin" : "")}>
              <span className="chip-ic" />
              <span className="chip-name">{a.name}</span>
              <span className="chip-sz">{a.size != null ? fmtSize(a.size) : ""}</span>
            </div>
          ))}
        </div>
      )}
      {!isUser && m.toolSteps && m.toolSteps.length > 0 && (
        <div className="tool-steps">
          {m.toolSteps.map((s, i) => <ToolStep key={i} step={s} />)}
        </div>
      )}
      {isUser
        ? (editing
            ? <div className="msg-edit">
                <textarea value={draft} autoFocus rows={Math.min(12, (draft.match(/\n/g) || []).length + 2)}
                          onChange={e => setDraft(e.target.value)}
                          onKeyDown={e => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); saveEdit(); } if (e.key === "Escape") setEditing(false); }} />
                <div className="edit-actions">
                  <button className="act-btn" onClick={() => setEditing(false)}>{t("common.cancel")}</button>
                  <button className="act-btn primary" onClick={saveEdit} disabled={!draft.trim()}>{t("msg.saveSubmit")}</button>
                </div>
              </div>
            : <div className="msg-body">{m.content}</div>)
        : (
          <>
            {reasoning && (
              <div className="reason">
                <button className="reason-toggle" onClick={() => setReasonOpen(!reasonShown)}>
                  <span className="reason-caret">{reasonShown ? "▾" : "▸"}</span>
                  <span className="reason-label">{autoOpen ? t("msg.thinking") : t("msg.reasoning")}</span>
                </button>
                {reasonShown && <div className="reason-body">{reasoning}</div>}
              </div>
            )}
            <Markdown text={bodyText || ""} mermaid={!streaming} />
            {streaming && <span className="caret" />}
            {artifacts.map((a, i) => <FileArtifact key={i} art={a} />)}
            {onDownloadFile && m.files && m.files.length > 0 && (
              <div className="msg-files">
                {m.files.map((f, i) => <AgentFileCard key={i} file={f} onDownload={onDownloadFile} />)}
              </div>
            )}
            {onProposal && m.proposals && m.proposals.length > 0 && (
              <div className="msg-proposals">
                {m.proposals.map((p, i) => <ProposalCard key={i} p={p} state={proposalState || {}} onAct={onProposal} />)}
              </div>
            )}
          </>
        )}
      {/* Compaction summarises the older turns away, so it necessarily loses
          detail. Shown on the turn it happened in, live and afterwards, so a
          session that did this is distinguishable from one that did not. */}
      {/* Which app this turn was told about. The pointer to it lives in an
          injected prompt line the reader never sees, so an agent talking about
          an app nobody mentioned looked like a hallucination. */}
      {!isUser && m.appContext && (
        <div className="stopped-note">▦ {tb(m.appContext.routine ? "msg.appContextRoutine" : "msg.appContext", { name: m.appContext.name })}</div>
      )}
      {!isUser && m.compacting && streaming && <div className="stopped-note">⟳ {t("msg.compacting")}</div>}
      {!isUser && Array.isArray(m.compactions) && m.compactions.length > 0 && (
        <div className="stopped-note">⟳ {t("msg.compacted", { n: m.compactions.length })}</div>
      )}
      {!isUser && m.stopped && !streaming && <div className="stopped-note">⏹ {t("msg.stoppedNote")}</div>}
      {/* the turn wrote to its owner's memory: said, with the way to see and change it */}
      {!isUser && m.memory && m.memory.length > 0 && (
        <a className="stopped-note memory-note" href="settings.html#memory" title={t("msg.memoryHint")}>✎ {t("msg.memory", { files: m.memory.join(", ") })}</a>
      )}
      {/* it started without the agent's conversation, and why (server.js
          startAgentRun): a follow-up question about it should not surprise */}
      {!isUser && m.freshStart && <div className="stopped-note">⟲ {t(m.freshStart === "retry" ? "msg.freshRetry" : m.freshStart === "routine" ? "msg.freshRoutine" : "msg.freshPerson")}</div>}
      {/* a turn that failed keeps its place: what was asked stays above it (issue #51) */}
      {!isUser && m.error && !streaming && m.errorKind === "context-full" && (() => {
        /* The conversation no longer fits the window: no answer is coming
           until it is started afresh or moved to a model with a larger one. */
        const info = m.errorInfo || {};
        const big = info.larger;
        return (
          <div className="stopped-note err ctx-full">
            <div>⚠ {t("msg.ctxFull", { window: L.fmtNum(info.window || 0) })}</div>
            {info.compactionError && <div className="ctx-full-why">{t("msg.ctxFullWhy", { error: info.compactionError })}</div>}
            {isLast && <div className="ctx-full-why">{(onFresh || onLarger) ? t(big ? "msg.ctxFullHint" : "msg.ctxFullHintNoLarger") : manageNote}</div>}
            {isLast && (onFresh || (onLarger && big)) && (
              <div className="ctx-full-acts">
                {onFresh && <button className="act-btn" onClick={onFresh} disabled={busy}>{t("msg.ctxFresh")}</button>}
                {onLarger && big && <button className="act-btn" onClick={() => onLarger(big)} disabled={busy}>
                  {t("msg.ctxLarger", { name: big.model || big.backendLabel, window: L.fmtNum(big.contextWindow) })}</button>}
              </div>
            )}
          </div>
        );
      })()}
      {!isUser && m.error && !streaming && m.errorKind !== "context-full" && (
        <div className="stopped-note err">⚠ {t("msg.failedNote", { error: m.error })}
          {/connect|reach|timed? ?out|ECONN|ENOTFOUND|EAI_AGAIN|fetch failed|network|socket/i.test(m.error) && <> {t("msg.failedUnreachable")}</>}
        </div>
      )}
      {!isUser && m.truncated && !m.stopped && !streaming && (
        <div className="stopped-note">✂ {m.truncated.outputTokens
          ? t("msg.truncated", { n: L.fmtNum(m.truncated.outputTokens) })
          : t("msg.truncatedPlain")}</div>
      )}
      {!isUser && m.queuedPos != null && streaming && <div className="stopped-note">⏳ {t("msg.queuedNote", { n: m.queuedPos })}</div>}
      {!streaming && !editing && (
        <div className="msg-actions">
          {m.content && <button className="act-btn" onClick={copy}>{copied ? "Copied" : "Copy"}</button>}
          {isUser && onEdit && <button className="act-btn" onClick={startEdit} disabled={busy}>{t("common.edit")}</button>}
          {!isUser && isLast && onRegenerate && m.content && <button className="act-btn" onClick={onRegenerate} disabled={busy}>{t("msg.regenerate")}</button>}
          {!isUser && isLast && onRetry && m.error && <button className="act-btn" onClick={onRetry} disabled={busy}>{t("msg.retry")}</button>}
        </div>
      )}
    </div>
  );
}

/* ---------- model selector ---------- */
/* One dropdown, shared by every picker in the app: chat's provider, chat's
   model, and an agent's pair of the same two. Everything that differs between
   them is passed in, so they cannot drift apart again. */
function PickerMenu({ cap, label, title, options, value, onPick, onOpen, children }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);
  /* Opening the menu is the moment the answer matters, and the only moment it
     is worth asking for: residency changes while you sit there. */
  const toggle = () => { const next = !open; setOpen(next); if (next && onOpen) onOpen(); };
  return (
    <div className="model-sel" ref={ref}>
      <button className="model-btn" onClick={toggle} title={title}>
        {children || <span className="sq" />}
        <span className="sel-label">{label}</span>
        <span className="chev">▼</span>
      </button>
      {open && (
        <div className="model-menu">
          <div className="menu-cap">{cap}</div>
          {options.map(o => o.header ? (
            <div key={String(o.id)} className="menu-cap group">{o.label}</div>
          ) : (
            <button key={String(o.id)} className={"model-opt " + (o.id === value ? "sel" : "")}
                    onClick={() => { onPick(o.id); setOpen(false); }}>
              <span className="sq" />
              <span className="label">
                {o.label}
                {/* Loaded, and therefore answers immediately. Only ever shown
                    when the provider actually told us; a model with no badge
                    means "unknown", never "cold". */}
                {o.loaded && <span className="model-warm" title={t("model.loadedHint")}>{t("model.loaded")}</span>}
                {o.desc ? <span className="desc">{o.desc}</span> : null}
              </span>
              {o.id === value && <span className="check">✓</span>}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* How full the context window is, as of the last completed turn. The same
   budget pi compacts against, so watching it climb explains the compaction
   note when it arrives rather than surprising the reader with it. */
function ContextGauge({ used, window: win }) {
  if (!used || !win) return null;
  const pct = Math.min(100, Math.round((used / win) * 100));
  /* Only once it matters. Shown from the first turn, "35% · 23k/64k" was a
     number nobody could place; it explains itself when a conversation is
     getting full and the agent is about to summarise. */
  if (pct < 60) return null;
  const k = n => (n >= 1000 ? Math.round(n / 1000) + "k" : String(n));
  return (
    <span className={"ctx-gauge" + (pct >= 85 ? " hot" : pct >= 60 ? " warm" : "")}
          title={t("ctx.hint", { used: used.toLocaleString(), window: win.toLocaleString() })}>
      <span className="ctx-bar"><span className="ctx-fill" style={{ width: pct + "%" }} /></span>
      {pct}% · {k(used)}/{k(win)}
    </span>
  );
}

/* ONE menu for where an agent runs and on which model. It used to be two, an
   engine and then a model on it: two dropdowns side by side read as one
   setting cut in half, and "Default (...)" beside "Backend default" told
   nobody anything. Every entry is a whole choice now: the recommended
   default first, then each engine with its models under its name. */
const PICK_SEP = "\u0001";
/* the engines, kept for the page's life: every agent bar and the start page
   would otherwise ask again, and show a wrong label until the answer came */
let ENGINES_CACHE = null;
function AgentEngineSelect({ agent, onPick }) {
  const [list, setList] = useState(ENGINES_CACHE);
  const [models, setModels] = useState({});   /* base -> models it serves */
  const [loaded, setLoaded] = useState({});   /* base -> models it holds in memory */
  useEffect(() => { L.AgentsAPI.backends().then(l => { ENGINES_CACHE = l; setList(l); }).catch(() => {}); }, []);
  const opts = (list && list.options) || [];
  const defKey = list && list.default;
  const def = opts.find(o => o.key === defKey) || null;
  /* the model agents following the default run: priority 1's (server.js model priority) */
  const defModel = (list && list.defaultModel) || (def && def.model);
  const cur = opts.find(o => o.key === agent.backend) || def;
  /* each engine's catalogue once (it is cached per base): the current one at
     once, so the button can name the model, the rest when the menu opens */
  const loadModels = bases => bases.forEach(base => {
    if (!base) return;
    L.loadModelsForBase(base).then(m => setModels(x => ({ ...x, [base]: m || [] })))
                             .catch(() => setModels(x => ({ ...x, [base]: [] })));
  });
  useEffect(() => { if (cur && cur.base) loadModels([cur.base]); }, [cur && cur.base]);
  const onOpen = () => {
    loadModels(opts.map(o => o.base));
    opts.forEach(o => { if (o.base) L.loadedModels(o.base).then(l => setLoaded(x => ({ ...x, [o.base]: l || [] }))).catch(() => {}); });
  };
  const isLoaded = (base, id) => !!(loaded[base] && loaded[base].some(l => L.sameModel(l.id, id)));
  const nameOf = (base, id) => {
    const m = (models[base] || []).find(x => L.sameModel(x.id, id)) || L.findModel(id);
    return (m && m.label) || id || "";
  };
  const key = (backend, model) => (backend || "") + PICK_SEP + (model || "");

  const options = [];
  if (def) options.push({ id: key(null, null), label: t("agent.recommendedEntry"),
                          desc: def.label, loaded: isLoaded(def.base, defModel) });
  const listed = new Set();   /* an engine sharing a provider with an earlier one lists no models twice */
  for (const o of opts) {
    const entries = [];
    /* the engine's own default; for the default engine that is "Recommended" above */
    if (o.key !== defKey) entries.push({ id: key(o.key, null), label: nameOf(o.base, o.model),
                                         desc: t("agent.engineDefaultModel"), loaded: isLoaded(o.base, o.model) });
    if (!listed.has(o.base)) {
      listed.add(o.base);
      for (const m of models[o.base] || []) {
        if (L.sameModel(m.id, o.model)) continue;   /* that is the entry above */
        entries.push({ id: key(o.key, m.id), label: m.label, desc: m.desc, loaded: isLoaded(o.base, m.id) });
      }
    }
    if (entries.length) options.push({ header: true, id: "h" + PICK_SEP + o.key, label: o.label }, ...entries);
  }

  /* which entry this agent is on: no choice of its own, or its engine's own
     default on the default engine, is "Recommended" */
  const pin = agent.modelPin && !(cur && L.sameModel(agent.modelPin, cur.model)) ? agent.modelPin : null;
  const curKey = cur ? cur.key : defKey;
  const value = curKey === defKey && !pin ? key(null, null) : key(curKey, pin);
  const running = nameOf(cur && cur.base, pin || (!agent.backend ? defModel : (cur && cur.model)));
  const label = value === key(null, null) ? t("agent.engineButtonDefault", { model: running }) : running;

  /* nothing until the engines are known: before that the button could only
     guess, and it guessed "recommended" for an agent on another engine */
  if (!list) return null;
  return (
    <PickerMenu cap={t("agent.engineModel")} title={t("agent.engineHint")} onOpen={onOpen}
                label={label} options={options} value={value}
                onPick={v => { const i = v.indexOf(PICK_SEP); onPick({ backend: v.slice(0, i) || null, model: v.slice(i + 1) || null }); }} />
  );
}

function ModelSelect({ model, setModel, models, base }) {
  const list = models || L.MODELS;
  const cur = list.find(m => m.id === model) || list[0] || { label: model };
  /* Which of these the provider is holding in memory. Asked when the menu is
     opened, because that is when it is read and when it is current. null means
     the provider does not report it, and then nothing is marked at all. */
  const [loaded, setLoaded] = useState(null);
  const refresh = useCallback(() => {
    if (!base) return;
    L.loadedModels(base).then(setLoaded).catch(() => setLoaded(null));
  }, [base]);
  useEffect(() => { setLoaded(null); }, [base]);
  const isLoaded = id => !!(loaded && loaded.some(l => L.sameModel(l.id, id)));
  return (
    <PickerMenu cap={t("topbar.model")} label={cur.label} value={model} onOpen={refresh}
                options={list.map(m => ({ id: m.id, label: m.label, desc: m.desc, loaded: isLoaded(m.id) }))}
                onPick={setModel} />
  );
}

/* ---------- provider selector ---------- */
function ProviderSelect({ provider, setProvider, live }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const list = L.providersList();
  const selName = provider || (list[0] && list[0].name);
  useEffect(() => {
    const h = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);
  return (
    <div className="model-sel prov-sel" ref={ref}>
      <button className="model-btn" onClick={() => setOpen(!open)} title={t("topbar.provider")}>
        <span className={"prov-dot " + (live && live === selName ? "on" : "")} />
        <span className="sel-label">{L.providerLabel(selName)}</span>
        <span className="chev">▼</span>
      </button>
      {open && (
        <div className="model-menu">
          <div className="menu-cap">{t("topbar.provider")}</div>
          {list.map(p => (
            <button key={p.name} className={"model-opt " + (p.name === selName ? "sel" : "")}
                    onClick={() => { setProvider(p.name); setOpen(false); }}>
              <span className={"prov-dot " + (live && live === p.name ? "on" : "")} />
              <span className="label">
                {L.providerLabel(p.name)}
                <span className="desc">{p.note || (p.base || "").replace(/^https?:\/\//, "")}</span>
              </span>
              {p.name === selName && <span className="check">✓</span>}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---------- empty state ---------- */
const suggestions = () => [
  { k: "Explain", t: t("empty.s1") },
  { k: "Draft",   t: t("empty.s2") },
  { k: "Code",    t: t("empty.s3") },
  { k: "Compare", t: t("empty.s4") },
];
function Empty({ onPick }) {
  return (
    <div className="empty">
      <div className="empty-mark" />
      <h1><BrandName /></h1>
      <p className="sub">{t("empty.blurb")}</p>
      <div className="eyebrow">{t("empty.tryOne")}</div>
      <div className="prompts">
        {suggestions().map((s, i) => (
          <button key={i} className="prompt" onClick={() => onPick(s.t)}>
            <span className="p-k">{s.k}</span>
            <span className="p-t">{s.t}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

/* ---------- composer ---------- */
const TEXT_RE = /^(text\/|application\/(json|xml|javascript|x-sh|x-yaml|sql))|\.(md|markdown|csv|tsv|json|js|jsx|ts|tsx|py|rb|go|rs|java|c|cpp|h|css|html|xml|yml|yaml|toml|ini|sh|sql|txt|log)$/i;
function isTextFile(f) { return TEXT_RE.test(f.type) || TEXT_RE.test(f.name); }
/* Drop a file anywhere on the window, not just on the composer strip — that
   strip is a small target, and everyone aims at the conversation.

   The overlay does not know which composer is mounted, so it announces the
   files as an event and whichever composer is listening claims them. The event
   is cancelable and the claimer calls preventDefault, so if two composers are
   ever mounted at once the file is still only added once.

   A drop ON a composer is handled by the composer's own onDrop, and the same
   native event then bubbles up to this window listener. The composer has
   already called preventDefault by then, so a prevented drop is left alone:
   re-announcing it added every file dropped on the composer twice, with two
   uploads and two conversions. */
function WindowDrop() {
  const [over, setOver] = useState(false);
  const depth = useRef(0);
  useEffect(() => {
    const hasFiles = e => Array.from((e.dataTransfer && e.dataTransfer.types) || []).includes("Files");
    const onEnter = e => { if (!hasFiles(e)) return; e.preventDefault(); depth.current++; setOver(true); };
    const onOver  = e => { if (!hasFiles(e)) return; e.preventDefault(); };
    const onLeave = e => { if (!hasFiles(e)) return; depth.current--; if (depth.current <= 0) { depth.current = 0; setOver(false); } };
    const onDrop  = e => {
      if (!hasFiles(e)) return;
      depth.current = 0; setOver(false);
      if (e.defaultPrevented) return;        /* a composer already took it */
      e.preventDefault();
      const files = e.dataTransfer && e.dataTransfer.files;
      if (files && files.length) window.dispatchEvent(new CustomEvent("indie:files", { detail: files, cancelable: true }));
    };
    window.addEventListener("dragenter", onEnter);
    window.addEventListener("dragover", onOver);
    window.addEventListener("dragleave", onLeave);
    window.addEventListener("drop", onDrop);
    return () => {
      window.removeEventListener("dragenter", onEnter);
      window.removeEventListener("dragover", onOver);
      window.removeEventListener("dragleave", onLeave);
      window.removeEventListener("drop", onDrop);
    };
  }, []);
  if (!over) return null;
  return (
    <div className="drop-veil">
      <div className="drop-veil-box"><ClipIcon /> {t("attach.dropAnywhere")}</div>
    </div>
  );
}

/* Raster images go to the model's VISION path (image_url), NOT MarkItDown. */
function isImageFile(f) { return /^image\/(png|jpe?g|gif|webp|bmp)$/i.test(f.type) || /\.(png|jpe?g|gif|webp|bmp)$/i.test(f.name); }
function fmtSize(n) {
  return n < 1024 ? n + "B" : n < 1048576 ? (n / 1024).toFixed(0) + "K" : (n / 1048576).toFixed(1) + "M";
}

/* Read an image as a data URL, downscaling large ones (max 1568px, JPEG) to
   keep the request/payload small for vision models. */
function fileToImageDataUrl(file) {
  return new Promise((resolve, reject) => {
    const r = new FileReader();
    r.onerror = () => reject(new Error("read failed"));
    r.onload = () => {
      const raw = String(r.result);
      const img = new Image();
      img.onerror = () => resolve(raw);
      img.onload = () => {
        const MAX = 1568;
        let w = img.naturalWidth, h = img.naturalHeight;
        if (!w || !h || Math.max(w, h) <= MAX) { resolve(raw); return; }
        const s = MAX / Math.max(w, h); w = Math.round(w * s); h = Math.round(h * s);
        try {
          const c = document.createElement("canvas"); c.width = w; c.height = h;
          c.getContext("2d").drawImage(img, 0, 0, w, h);
          resolve(c.toDataURL("image/jpeg", 0.85));
        } catch { resolve(raw); }
      };
      img.src = raw;
    };
    r.readAsDataURL(file);
  });
}

/* ---------- Tools toggle + per-server dropdown ---------- */
function ToolsControl({ on, onToggle }) {
  const [open, setOpen] = useState(false);
  const [servers, setServers] = useState(() => L.getMcpServers());
  const ref = useRef(null);
  useEffect(() => { L.loadMcpServers().then(() => setServers([...L.getMcpServers()])); }, []);
  useEffect(() => {
    if (!open) return;
    const h = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, [open]);
  const toggleServer = (id, val) => { L.setMcpServerEnabled(id, val); setServers([...L.getMcpServers()]); };
  const hasServers = servers.length > 0;
  return (
    <div className="tool-toggle-wrap" ref={ref}>
      <button className={"tool-toggle " + (on ? "on" : "")} onClick={onToggle}
              title={t("tools.mcpHint")}>
        <ToolsIcon /> Tools
      </button>
      {hasServers && (
        <button className={"tt-caret-btn " + (on ? "on" : "")} title={t("tools.chooseServers")}
                onClick={() => setOpen(o => !o)}>▾</button>
      )}
      {open && hasServers && (
        <div className="mcp-menu">
          <div className="mcp-menu-head">{t("tools.mcpServers")}</div>
          {servers.map(s => (
            <label key={s.id} className="mcp-menu-row">
              <button className={"mcp-switch " + (s.enabled === false ? "" : "on")}
                      onClick={e => { e.preventDefault(); toggleServer(s.id, s.enabled === false); }}><span /></button>
              <span className="mcp-menu-name">{s.name}</span>
            </label>
          ))}
        </div>
      )}
    </div>
  );
}

function Composer({ onSend, onStop, busy, presetText, clearPreset, mcpAvailable }) {
  const [text,   setText]   = useState("");
  const [focus,  setFocus]  = useState(false);
  const [drag,   setDrag]   = useState(false);
  const [files,  setFiles]  = useState([]);
  const [search, setSearch] = useState(false);
  const [recording,    setRecording]    = useState(false);
  const [transcribing, setTranscribing] = useState(false);
  const [voiceErr,     setVoiceErr]      = useState(null);
  const ta        = useRef(null);
  const fileInput = useRef(null);
  const dragDepth = useRef(0);
  const rec       = useRef(null);   /* { ctx, processor, source, stream, chunks } */

  const [priv,   setPriv]   = useState(false);
  const [mcp,    setMcp]    = useState(false);
  const [mkfile, setMkfile] = useState(false);
  const skillsAvail      = L.enabledSkills().length > 0;
  /* "Tools" covers MCP tools AND Skills — available if either exists */
  const mcpOn            = (mcpAvailable && L.toolEnabled("mcp")) || skillsAvail;
  const searchAvailable  = L.toolEnabled("search");
  const filesAvailable   = L.toolEnabled("files");
  const privacyAvailable = L.toolEnabled("privacy");
  const filegenAvailable = L.toolEnabled("filegen");
  const voiceAvailable   = typeof navigator !== "undefined" && navigator.mediaDevices && window.AudioContext;

  useEffect(() => {
    if (presetText) {
      setText(presetText);
      clearPreset();
      requestAnimationFrame(() => ta.current && ta.current.focus());
    }
  }, [presetText]);

  useEffect(() => {
    const el = ta.current; if (!el) return;
    el.style.height = "auto";
    el.style.height = Math.min(el.scrollHeight, 220) + "px";
  }, [text]);

  const MAX_UPLOAD = 32 * 1024 * 1024; /* must match server express.raw limit */
  const patchFile = (id, patch) => setFiles(fs => fs.map(x => x.id === id ? { ...x, ...patch } : x));

  /* EVERY file goes through the same server-side converter, images included:
     a photo of a document is a document, and OCR turns it into text the model
     can quote instead of squinting at. An image additionally keeps its data URL
     so the model still SEES it, and a PDF that turned out to be a scan comes
     back with page images when even OCR found nothing. Text and pictures are
     not either/or here — a file can contribute both. */
  const addFiles = list => {
    Array.from(list).forEach(f => {
      const id = Math.random().toString(36).slice(2);
      const image = isImageFile(f);
      setFiles(fs => [...fs, { id, name: f.name, size: f.size, type: f.type, isImage: image, converting: true }]);
      if (f.size > MAX_UPLOAD) {
        patchFile(id, { converting: false, error: "too large (max 32 MB)" });
        return;
      }
      /* The picture itself, for vision. Read locally: it is already in the
         browser, and this keeps working even if conversion fails. */
      if (image) {
        fileToImageDataUrl(f)
          .then(url => patchFile(id, { dataUrl: url }))
          .catch(() => {});
      }
      L.convertFile(f)
        .then(r => patchFile(id, {
          converting: false, text: r.markdown, chars: r.chars, truncated: r.truncated,
          ocr: r.ocr, pages: r.pages || [], note: r.note,
        }))
        .catch(e => patchFile(id, {
          converting: false,
          /* An image we could not convert is still perfectly usable: the model
             looks at it. Only a non-image is a dead end worth reporting. */
          error: image ? undefined : ((e && e.message) || "conversion failed"),
        }));
    });
  };

  /* ---- voice input: capture mic → WAV → the server's speech service ---- */
  const startRecording = async () => {
    setVoiceErr(null);
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      const ctx    = new (window.AudioContext || window.webkitAudioContext)();
      const source = ctx.createScriptProcessor ? ctx.createScriptProcessor(4096, 1, 1) : ctx.createScriptProcessor(4096, 1, 1);
      const mic    = ctx.createMediaStreamSource(stream);
      const chunks = [];
      source.onaudioprocess = e => { chunks.push(new Float32Array(e.inputBuffer.getChannelData(0))); };
      mic.connect(source); source.connect(ctx.destination);
      rec.current = { ctx, processor: source, source: mic, stream, chunks };
      setRecording(true);
    } catch (e) {
      setVoiceErr(e && e.name === "NotAllowedError" ? t("voice.denied") : t("voice.startFailed"));
    }
  };

  const stopRecording = async () => {
    const r = rec.current; rec.current = null;
    setRecording(false);
    if (!r) return;
    try { r.processor.disconnect(); r.source.disconnect(); } catch {}
    r.stream.getTracks().forEach(t => t.stop());
    const sampleRate = r.ctx.sampleRate;
    try { await r.ctx.close(); } catch {}

    const totalSamples = r.chunks.reduce((n, c) => n + c.length, 0);
    if (totalSamples < sampleRate * 0.3) { setVoiceErr(t("voice.tooShort")); return; } /* < 0.3s */

    setTranscribing(true);
    try {
      const wav  = L.pcmToWavBlob(r.chunks, sampleRate);
      const said = await L.transcribeAudio(wav);
      if (said) {
        setText(t => (t ? t.replace(/\s*$/, " ") : "") + said);
        requestAnimationFrame(() => ta.current && ta.current.focus());
      } else {
        setVoiceErr(t("voice.noSpeech"));
      }
    } catch (e) {
      setVoiceErr((e && e.message) || t("voice.failed"));
    } finally {
      setTranscribing(false);
    }
  };

  const toggleMic = () => { if (transcribing) return; recording ? stopRecording() : startRecording(); };

  /* Files dropped anywhere on the window (see WindowDrop). No dependency array:
     addFiles closes over current state, so the listener is re-bound each render
     rather than capturing a stale one. Claiming the event stops a second
     mounted composer from adding the same file twice. */
  useEffect(() => {
    const onFiles = e => {
      if (e.defaultPrevented || !e.detail || !e.detail.length) return;
      if (!filesAvailable) return;
      e.preventDefault();
      addFiles(e.detail);
    };
    window.addEventListener("indie:files", onFiles);
    return () => window.removeEventListener("indie:files", onFiles);
  });

  /* One chooser per tap. A hidden input opened twice shows the picker twice,
     which is what a doubled activation looks like on a phone — and touch
     surfaces have more ways to double-fire than a mouse does. Cheap to make
     impossible rather than to keep diagnosing. */
  const pickerBusy = useRef(0);
  const openPicker = () => {
    const now = Date.now();
    if (now - pickerBusy.current < 800) return;
    pickerBusy.current = now;
    if (fileInput.current) fileInput.current.click();
  };

  const onDrop      = e => { e.preventDefault(); dragDepth.current = 0; setDrag(false); if (filesAvailable && e.dataTransfer.files?.length) addFiles(e.dataTransfer.files); };
  const onDragEnter = e => { e.preventDefault(); if (!filesAvailable) return; dragDepth.current++; setDrag(true); };
  const onDragLeave = e => { e.preventDefault(); dragDepth.current--; if (dragDepth.current <= 0) setDrag(false); };
  /* Paste (Ctrl/Cmd+V) an image from the clipboard -> attach it. */
  const onPaste = e => {
    if (!filesAvailable) return;
    const imgs = [...(e.clipboardData?.items || [])]
      .filter(it => it.kind === "file" && it.type.startsWith("image/"))
      .map(it => { const f = it.getAsFile(); if (!f) return null; return f.name ? f : new File([f], "pasted-" + Date.now() + "." + ((f.type.split("/")[1]) || "png"), { type: f.type }); })
      .filter(Boolean);
    if (imgs.length) { e.preventDefault(); addFiles(imgs); }
  };

  const converting = files.some(f => f.converting);
  const submit = () => {
    const t = text.trim();
    if ((!t && !files.length) || busy || converting) return;
    /* forward attachments that are ready: text (MarkItDown) or images (data URL) */
    onSend(t, { files: files.filter(f => f.text || f.dataUrl || (f.pages && f.pages.length)), search: search && searchAvailable, privacy: priv && privacyAvailable, tools: mcp && mcpOn, mcp: mcp && mcpOn, filegen: mkfile && filegenAvailable });
    setText(""); setFiles([]);
  };
  const key = e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); submit(); } };

  return (
    <div className="composer-wrap">
      <div className={"composer " + (focus ? "focus " : "") + (drag ? "drag" : "")}
           onDrop={onDrop} onDragOver={e => e.preventDefault()}
           onDragEnter={onDragEnter} onDragLeave={onDragLeave}>

        {files.length > 0 && (
          <div className="attach-row">
            {files.map(f => (
              <div key={f.id}
                   className={"chip " + (f.error ? "bin " : "") + (f.converting ? "loading" : "")}
                   title={f.error ? f.error : f.converting ? (f.isImage ? t("attach.readingImage") : t("attach.converting"))
                          : [f.name, f.note, f.truncated ? t("attach.truncated").trim() : ""].filter(Boolean).join(" — ")}>
                {f.isImage && f.dataUrl
                  ? <img className="chip-thumb" src={f.dataUrl} alt="" />
                  : <span className="chip-ic" />}
                <span className="chip-name">{f.name}</span>
                <span className="chip-sz">
                  {/* Say what actually happened: silently OCR'ing a scan and
                      still labelling it "image" is why people could not tell
                      whether their document had been read. */}
                  {f.converting ? (f.isImage ? "reading…" : "converting…")
                    : f.error ? "failed"
                    : f.ocr === "tesseract" ? t("attach.ocr")
                    : (f.pages && f.pages.length) ? t("attach.pages", { n: f.pages.length })
                    : f.isImage ? "image"
                    : f.truncated ? "truncated" : fmtSize(f.size)}
                </span>
                <button className="chip-x" onClick={() => setFiles(fs => fs.filter(x => x.id !== f.id))}>✕</button>
              </div>
            ))}
          </div>
        )}

        <div className="composer-row">
          {filesAvailable && (
            <>
              <button type="button" className="attach-btn" title={t("attach.files")} onClick={openPicker}><ClipIcon /></button>
              <input ref={fileInput} type="file" multiple hidden onChange={e => { addFiles(e.target.files); e.target.value = ""; }} />
            </>
          )}
          <textarea
            ref={ta} value={text} rows={1}
            placeholder={drag ? t("attach.drop") : t("composer.placeholder", { brand: L.BRAND.brandName || "indie.chat" })}
            onChange={e => setText(e.target.value)}
            onKeyDown={key}
            onPaste={onPaste}
            onFocus={() => setFocus(true)}
            onBlur={() => setFocus(false)}
          />
          {voiceAvailable && (
            <button className={"mic-btn " + (recording ? "rec " : "") + (transcribing ? "busy" : "")}
                    onClick={toggleMic} disabled={transcribing}
                    title={recording ? t("voice.stopAndTranscribe") : transcribing ? t("voice.transcribing") : voiceTitle()}>
              <MicIcon />
            </button>
          )}
          {busy
            ? <button className="stop" onClick={onStop} title={t("common.stop")}><span className="sq" /></button>
            : <button className="send" onClick={submit} disabled={converting || recording || transcribing || (!text.trim() && !files.length)} title={converting ? t("attach.convertingAll") : t("common.send")}><SendIcon /></button>}
        </div>

        <div className="composer-foot">
          <div className="foot-left">
            {searchAvailable && (
              <button className={"tool-toggle " + (search ? "on" : "")} onClick={() => setSearch(s => !s)} title={t("tools.webSearch")}>
                <SearchIcon /> {t("tools.search")}
              </button>
            )}
            {privacyAvailable && (
              <button className={"tool-toggle " + (priv ? "on" : "")} onClick={() => setPriv(p => !p)}
                      title={t("tools.privacyHint")}>
                <ShieldIcon /> {t("tools.private")} <span className="tt-sub">(OPF)</span>
              </button>
            )}
            {mcpOn && <ToolsControl on={mcp} onToggle={() => setMcp(m => !m)} />}
            {filegenAvailable && (
              <button className={"tool-toggle " + (mkfile ? "on" : "")} onClick={() => setMkfile(m => !m)}
                      title={t("tools.filegenHint")}>
                <FileGenIcon /> {t("tools.makeFile")}
              </button>
            )}
            {recording
              ? <span className="voice-status rec"><span className="rec-dot" /> {t("voice.recording")}</span>
              : transcribing
              ? <span className="voice-status"><span className="rec-dot busy" /> {t("voice.transcribing")}</span>
              : voiceErr
              ? <span className="voice-status err">{voiceErr}</span>
              : <span className="hint">{tb("composer.hint")}</span>}
          </div>
          {text.length > 0 && <span className="count">{text.length}</span>}
        </div>
      </div>
    </div>
  );
}

/* ---------- draggable pane divider ----------
   Reports the pointer position while dragging; the owner turns that into a
   size and clamps it. Pointer capture is what makes the drag survive the
   cursor outrunning a 7px handle — and what lets it keep tracking over the
   app iframe, which otherwise swallows the events. Double-click resets,
   arrow keys nudge for anyone not using a mouse. */
function Splitter({ axis, onDrag, onNudge, onReset, label, className }) {
  const [on, setOn] = useState(false);
  /* Latest handler without re-subscribing the listeners on every parent render. */
  const dragRef = useRef(onDrag);
  dragRef.current = onDrag;
  /* Listen on WINDOW rather than the handle: the pointer routinely leaves a 7px
     target mid-drag, and next to an app the neighbour is a sandboxed iframe
     that would otherwise swallow the events (body.resizing also disables its
     pointer events while a drag is live). */
  useEffect(() => {
    if (!on) return;
    const move = e => dragRef.current(e.clientX, e.clientY);
    const up   = () => setOn(false);
    window.addEventListener("pointermove", move);
    window.addEventListener("pointerup", up);
    window.addEventListener("pointercancel", up);
    document.body.classList.add("resizing");
    if (axis === "h") document.body.classList.add("row");
    return () => {
      window.removeEventListener("pointermove", move);
      window.removeEventListener("pointerup", up);
      window.removeEventListener("pointercancel", up);
      document.body.classList.remove("resizing", "row");
    };
  }, [on, axis]);
  return (
    <div className={"splitter " + axis + (on ? " on" : "") + (className ? " " + className : "")}
         role="separator" aria-orientation={axis === "v" ? "vertical" : "horizontal"}
         aria-label={label} tabIndex={0} title={label + " — drag to resize, double-click to reset"}
         onDoubleClick={onReset}
         onKeyDown={e => {
           const k = { ArrowLeft: -16, ArrowRight: 16, ArrowUp: -16, ArrowDown: 16 }[e.key];
           if (k == null) return;
           e.preventDefault(); onNudge(k);
         }}
         onPointerDown={e => { if (e.button === 0) { e.preventDefault(); setOn(true); } }}
    />
  );
}

/* Is the box busy, and is it somebody else's turn?
   One model server usually sits behind a self-hosted deployment, so another
   person's run is why yours waits — which used to be invisible, leaving "it is
   slow today" as the only available explanation. Counts only, never who or
   what: a busy light does not need to say what anyone is working on. */
function BoxBusy({ box }) {
  if (!box || !box.total) return null;
  const others = box.others || 0;
  const label = others
    ? t("box.others", { n: others })
    : t("box.mine", { n: box.mine });
  const title = (others ? t("box.othersHint") : t("box.mineHint"))
    + (box.queued ? " " + t("box.queuedHint", { n: box.queued }) : "");
  return (
    <span className={"box-busy" + (others ? " others" : "")} title={title}>
      <span className="bb-dot" />
      {label}{box.queued ? " · " + t("box.queued", { n: box.queued }) : ""}
    </span>
  );
}

/* ---------- sidebar ---------- */
function Sidebar({ convs, agents, activeId, activeKind, onSelect, onNew, onNewAgent, onDelete, onDeleteAgent, apps, activeAppId, onSelectApp, onNewApp, onNewAppFromTemplate, onNewFromBundle, appBusy, onDeleteApp, user, onLogout, onRoutines, onNewRoutine, chatOn, activity, sideTab, onSideTab, panes, onPane, workspaces, curWs, onSwitchWs, onNewWs, onWsPanel }) {
  const initials = user ? user.name.split(" ").map(w => w[0]).join("").slice(0, 2).toUpperCase() : "?";
  const isAdmin  = user && ["owner", "admin"].includes(user.role);
  const inst     = useInstall();
  const theme    = useTheme();
  const [menuOpen, setMenuOpen] = useState(false);
  const appsRef  = useRef(null);
  /* New app is one click: a blank app with its own agent. Templates sit
     behind their own entry, offered only when there are some beside blank
     (deployments ship their own: a CRM, a review queue). */
  const hasTemplates = (L.appTemplateList() || appTemplateFallback()).some(tp => tp.key !== "blank");

  /* Pane drags. The sidebar's own width is measured from the window edge; the
     apps list from its own top, so the number stays right however much sits
     above it. */
  const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
  const sideW = () => clamp(Math.round(panes.side || 264), 210, Math.min(460, window.innerWidth - 360));
  const setSide = v => onPane("side", clamp(Math.round(v), 210, Math.min(460, window.innerWidth - 360)));
  const setAppsH = y => {
    const top = appsRef.current ? appsRef.current.getBoundingClientRect().top : 0;
    onPane("apps", clamp(Math.round(y - top), 56, Math.max(96, window.innerHeight - top - 200)));
  };

  /* FOREGROUND: interactive chats + agents. BACKGROUND: agents that work
     unattended (long runs, schedules) — richer status rows. */
  const shownAgents = (agents || []).filter(a => isAdmin || !isLibrarianAgent(a));
  const bgAgents = shownAgents.filter(a => a.background);
  const entries = [
    ...(convs || []).map(c => ({ kind: "chat",  id: c.id, title: c.title || t("chat.untitled"), updated: c.updated || 0 })),
    ...shownAgents.filter(a => !a.background).map(a => ({ kind: "agent", id: a.id, title: agentName(a) || "Agent", desc: agentDesc(a), updated: a.updated || 0, scope: a.scope, wiki: a.wiki, bundle: a.bundle })),
  ].sort((x, y) => (y.updated || 0) - (x.updated || 0));
  /* The shared wiki's sole writer (the Librarian) is infrastructure: the server
     refuses to delete it, so don't offer the affordance. */
  const isLibrarian = a => a.scope === "global" && a.wiki === "write";

  const runs = (activity && activity.runs) || [];
  const schedules = (activity && activity.schedules) || [];
  const asking = new Set(((activity && activity.asks) || []).map(a => a.agentId));
  const bgIds = new Set(bgAgents.map(a => a.id));
  const liveCount   = runs.filter(r => (r.status === "running" || r.status === "queued") && bgIds.has(r.agentId)).length;
  const orphanCount = runs.filter(r => r.status === "orphaned" && bgIds.has(r.agentId)).length;
  const mins = ms => { const m = Math.max(1, Math.round(ms / 60000)); return m < 60 ? m + "m" : Math.round(m / 60 * 10) / 10 + "h"; };
  const inMs = ms => { const m = Math.round(ms / 60000); return m < 60 ? "in " + Math.max(1, m) + "m" : m < 60 * 48 ? "in " + Math.round(m / 60) + "h" : "in " + Math.round(m / 1440) + "d"; };
  const services = (activity && activity.services) || [];
  const bgStatus = a => {
    const mine = runs.filter(r => r.agentId === a.id);
    const live = mine.find(r => r.status === "running");
    const queued = mine.find(r => r.status === "queued");
    const orphan = mine.find(r => r.status === "orphaned");
    const sched = schedules.filter(s => s.agentId === a.id && s.enabled && s.nextRun).sort((x, y) => x.nextRun - y.nextRun)[0];
    const upSvc = services.filter(s => s.agentId === a.id && s.status === "running").length;
    const schedTxt = (sched ? " · ⏰ " + inMs(sched.nextRun - Date.now()) : "") + (upSvc ? " · ▲ " + upSvc + " svc" : "");
    if (asking.has(a.id)) return { cls: "ask", text: "? " + t("ask.waiting") + schedTxt };
    if (live)   return { cls: "live",   text: "● running · " + mins(Date.now() - (live.started || live.created)) + schedTxt };
    if (queued) return { cls: "queued", text: "● queued" + schedTxt };
    if (orphan) return { cls: "orphan", text: t("run.interrupted") + schedTxt };
    const done = mine.filter(r => r.finished).sort((x, y) => y.finished - x.finished)[0];
    if (done) return { cls: done.status === "error" ? "orphan" : "idle", text: (done.status === "error" ? "✗ failed · " : "✓ done · ") + L.relTime(done.finished) + schedTxt };
    return { cls: "idle", text: (sched ? "⏰ " + inMs(sched.nextRun - Date.now()) : "idle") };
  };

  return (
    <aside className="sidebar">
      <div className="brand">
        <div className="logo" />
        <div>
          <div className="brand-name"><BrandName /></div>
          <div className="brand-tag">{L.BRAND.tagline}</div>
        </div>
      </div>
      <WorkspaceSwitch workspaces={workspaces || []} current={curWs} onSwitch={onSwitchWs} onNew={onNewWs} onPanel={onWsPanel} />
      <div className="new-split">
        <button className="new-chat" onClick={onNewAgent}>{t("sidebar.newAgent")} <span className="plus"><BotIcon /></span></button>
        <button className="new-caret" title={t("sidebar.newMenu")} onClick={() => setMenuOpen(o => !o)}>▾</button>
        {menuOpen && (
          <>
            <div className="new-scrim" onClick={() => setMenuOpen(false)} />
            <div className="new-menu">
              <button onClick={() => { setMenuOpen(false); onNewAgent(); }}><BotIcon /> {t("sidebar.newAgent")} <span className="beta">beta</span></button>
              <button onClick={() => { setMenuOpen(false); onNewApp(); }}><span className="new-menu-ic">▦</span> {t("sidebar.newApp")}</button>
              {onNewFromBundle && <button onClick={() => { setMenuOpen(false); onNewFromBundle(); }}><span className="new-menu-ic">◆</span> {t("bundle.newMenu")}</button>}
              {hasTemplates && (
                <button onClick={() => { setMenuOpen(false); onNewAppFromTemplate(); }}><span className="new-menu-ic">▤</span> {t("sidebar.newAppFromTemplate")}</button>
              )}
              {chatOn && <button onClick={() => { setMenuOpen(false); onNew(); }}><PlusIcon /> {t("sidebar.newChat")}</button>}
            </div>
          </>
        )}
      </div>
      {/* Labelled, not a bare "+": people looking for where apps come from
          went to "New agent" and never noticed the small plus. */}
      <div className="conv-head mono apps-head">
        {t("sidebar.apps")}
        <button className="apps-add" title={t("sidebar.newAppHint")} onClick={onNewApp} disabled={appBusy}><PlusIcon /> {appBusy ? t("app.creating") : t("sidebar.newApp")}</button>
      </div>
      {(apps || []).length > 0 && (
        <div className="apps-list" ref={appsRef}>
          {apps.map(a => (
            <div key={a.id}
                 className={"conv app-tab " + (a.id === activeAppId ? "active" : "")}
                 onClick={() => onSelectApp(a.id)}>
              <div className="conv-title">
                <span className="app-ic">{a.icon || "▦"}</span>
                {appName(a)}
                {a.scope === "global" && <span className="app-scope" title={t("app.globalHint")}>G</span>}
              </div>
              {(a.scope !== "global" || isAdmin) && (
                <button className="conv-del" title={a.scope === "global" ? t("app.deleteGlobal") : t("app.delete")}
                        onClick={ev => { ev.stopPropagation(); onDeleteApp(a.id); }}>✕</button>
              )}
            </div>
          ))}
        </div>
      )}
      {(apps || []).length > 0 && (
        <Splitter axis="h" label={t("pane.appsAgents")}
                  onDrag={(x, y) => setAppsH(y)}
                  onNudge={d => setAppsH((appsRef.current ? appsRef.current.getBoundingClientRect().bottom : 0) + d)}
                  onReset={() => onPane("apps", null)} />
      )}

      <div className="side-tabs">
        <button className={"side-tab " + (sideTab !== "bg" ? "on" : "")} onClick={() => onSideTab("fg")}>{t("sidebar.foreground")}</button>
        <button className={"side-tab " + (sideTab === "bg" ? "on" : "")} onClick={() => onSideTab("bg")}>
          {t("sidebar.background")}
          {liveCount > 0 && <span className="side-tab-badge live">{liveCount}</span>}
          {liveCount === 0 && orphanCount > 0 && <span className="side-tab-badge orphan">{orphanCount}</span>}
        </button>
      </div>
      <div className="conv-list">
        {sideTab !== "bg" ? (<>
          {entries.length === 0 && (
            <div style={{ padding: "10px 12px", fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-4)" }}>
              {t("sidebar.nothingYet")}
            </div>
          )}
          {entries.map(e => (
            <div key={e.kind + ":" + e.id}
                 className={"conv " + (e.id === activeId && e.kind === activeKind && !activeAppId ? "active" : "")}
                 onClick={() => onSelect(e.id, e.kind)}>
              <div className="conv-title">
                {e.kind === "agent" && <span className="entry-badge"><BotIcon /> AGENT</span>}
                {e.bundle && <span className="entry-bundle" title={t("bundle.madeFrom", { name: bl(e.bundle.name) })}>{e.bundle.icon}</span>}
                {e.title}
                {e.scope === "global" && <span className="app-scope" title={t("agent.sharedHint")}>G</span>}
              </div>
              {e.desc && <div className="conv-desc" title={e.desc}>{e.desc}</div>}
              <div className="conv-meta">{asking.has(e.id) ? <span className="ask-meta">? {t("ask.waiting")}</span> : L.relTime(e.updated)}</div>
              {isLibrarian(e)
                ? <span className="conv-locked" title={t("agent.librarianLocked")}>✎</span>
                : <button className="conv-del" title={t("common.delete")}
                          onClick={ev => { ev.stopPropagation(); (e.kind === "agent" ? onDeleteAgent : onDelete)(e.id); }}>✕</button>}
            </div>
          ))}
        </>) : (<>
          {/* Scheduled work is set up where it shows up: this tab. It used to
              point at a Routines entry at the bottom of the sidebar, which
              people looking here did not find. */}
          <div className="bg-actions">
            <button className="bg-new" onClick={onNewRoutine}><PlusIcon /> {t("routine.new")}</button>
            <button className="bg-all" onClick={onRoutines}>{t("routine.all")}</button>
          </div>
          {bgAgents.length === 0 && (
            <div style={{ padding: "4px 14px 12px", fontSize: 12, color: "var(--ink-3)", lineHeight: 1.5 }}>
              {tb("sidebar.bgEmpty", { foreground: t("sidebar.foreground") })}
            </div>
          )}
          {bgAgents.sort((x, y) => (y.updated || 0) - (x.updated || 0)).map(a => {
            const st = bgStatus(a);
            return (
              <div key={a.id}
                   className={"conv bg-row " + (a.id === activeId && activeKind === "agent" && !activeAppId ? "active" : "")}
                   onClick={() => onSelect(a.id, "agent")}>
                <div className="conv-title">
                  <span className="entry-badge"><BotIcon /> AGENT</span>
                  {agentName(a) || "Agent"}
                </div>
                <div className={"bg-status " + st.cls}>{st.text}</div>
                {isLibrarian(a)
                  ? <span className="conv-locked" title={t("agent.librarianLocked")}>✎</span>
                  : <button className="conv-del" title={t("common.delete")}
                            onClick={ev => { ev.stopPropagation(); onDeleteAgent(a.id); }}>✕</button>}
              </div>
            );
          })}
        </>)}
      </div>

      {/* Routines live in the Background tab (New routine, All routines) and
          behind each agent's Schedule button, so the footer has no entry of
          its own: two ways in read as two different things. */}
      <div className="sidebar-foot">
        {/* ONE settings page for everyone. The old admin console is its
            Workspace group now, so there is no separate Admin link, and
            Settings no longer hides behind a topbar gear. */}
        <a className="foot-link" href="/settings.html" title={t("nav.settingsHint")}>
          <GearIcon /> {t("nav.settings")}
        </a>
        {/* The quick switch: it names what it switches TO. Light, dark or
            follow the system lives in Settings -> Preferences. */}
        <button className="foot-link" onClick={() => window.IndieTheme && window.IndieTheme.toggle()}
                aria-pressed={theme === "dark"} title={t("nav.themeHint")}>
          {theme === "dark" ? <SunIcon /> : <MoonIcon />} {theme === "dark" ? t("nav.lightMode") : t("nav.darkMode")}
        </button>
        {inst.available() && (
          <button className="install-link" title={t("pwa.installHint")}
                  onClick={() => { if (inst.canPrompt()) inst.prompt(); else inst.requestShow(); }}>
            <DownloadIcon /> {t("pwa.installApp")}
          </button>
        )}
      </div>

      {user && (
        <div className="user-foot">
          <a className="user-link" href="/settings.html#account" title={t("settings.nav.account")}>
            <span className="user-avatar">{initials}</span>
            <span className="user-info">
              <span className="user-name">{user.name}</span>
              <span className="user-email">{user.email}</span>
            </span>
          </a>
          {(user.authSource !== "box" || user.logoutUrl) && <button className="logout-btn" onClick={onLogout} title={t("nav.signOut")}>⏻</button>}
        </div>
      )}
      <Splitter axis="v" className="side-edge" label={t("pane.sidebar")}
                onDrag={x => setSide(x)}
                onNudge={d => setSide(sideW() + d)}
                onReset={() => onPane("side", null)} />
    </aside>
  );
}

/* ========================================================
   ROOT APP
   ======================================================== */
/* ========================================================
   AGENT VIEW — a persistent coding agent's thread (pi-powered, beta)
   ======================================================== */
function fmtBytes(n) {
  if (n == null) return "";
  if (n < 1024) return n + " B";
  if (n < 1024 * 1024) return (n / 1024).toFixed(1) + " KB";
  return (n / (1024 * 1024)).toFixed(1) + " MB";
}

const CanvasIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <rect x="3" y="4" width="18" height="16" rx="2" /><path d="M14 4v16" />
  </svg>
);

/* Lazy-load the (large) mermaid bundle only when a diagram actually needs it. */
function ensureMermaid() {
  if (window.__mermaidLoad) return window.__mermaidLoad;
  window.__mermaidLoad = new Promise((resolve, reject) => {
    if (window.mermaid) { resolve(window.mermaid); return; }
    const s = document.createElement("script");
    s.src = "vendor/mermaid.min.js";
    s.onload = () => resolve(window.mermaid);
    s.onerror = () => reject(new Error("mermaid failed to load"));
    document.head.appendChild(s);
  });
  return window.__mermaidLoad;
}

/* Upgrade any ```mermaid code blocks inside `el` to rendered SVG diagrams.
   Shared by the chat/agent transcript (inline) and the canvas panel. */
async function renderMermaidIn(el) {
  if (!el) return;
  const blocks = [...el.querySelectorAll("code.language-mermaid")].filter(c => !c.dataset.mmdDone);
  if (!blocks.length) return;
  let mermaid;
  try { mermaid = await ensureMermaid(); } catch { return; }
  for (const code of blocks) {
    code.dataset.mmdDone = "1";
    const src = code.textContent || "";
    const host = code.closest("pre") || code;
    try {
      const fig = document.createElement("div"); fig.className = "mermaid-fig";
      fig.innerHTML = await drawMermaid(mermaid, src);
      fig.dataset.src = src;            /* kept, so a theme switch can redraw it */
      host.replaceWith(fig);
    } catch {}
  }
}
/* Mermaid bakes its colours into the SVG, so a diagram is drawn in the theme
   showing at the time, and redrawn when the theme switches; otherwise a light
   diagram's dark text would sit on a dark page until the next reload. */
async function drawMermaid(mermaid, src) {
  mermaid.initialize({ startOnLoad: false, securityLevel: "strict", theme: currentTheme() === "dark" ? "dark" : "neutral" });
  const { svg } = await mermaid.render("mmd-" + Math.random().toString(36).slice(2), src);
  return svg;
}
window.addEventListener("indie:theme", async () => {
  const figs = [...document.querySelectorAll(".mermaid-fig[data-src]")];
  if (!figs.length || !window.mermaid) return;
  for (const fig of figs) { try { fig.innerHTML = await drawMermaid(window.mermaid, fig.dataset.src); } catch {} }
});

/* The visual canvas: renders one payload (markdown+mermaid / html / url / pdf / xlsx). */
/* A document to look at, in the canvas and in a workspace's Files: a PDF as
   it is, Word and PowerPoint converted to PDF, a spreadsheet as a page with
   its formulas calculated, number formats, colours and charts (server.js,
   sendPreview). The PDF shows in the browser's own viewer from a blob, the
   spreadsheet in a frame with no scripts and no origin. An agent image from
   before previews cannot convert: a spreadsheet then falls back to the old
   table from MarkItDown. */
function DocView({ agentId, wsId, path }) {
  const [st, setSt] = useState({ status: "loading" });
  const mdRef = useRef(null);
  useEffect(() => {
    let cancelled = false, url = null;
    setSt({ status: "loading" });
    const isPdf = /\.pdf$/i.test(path);
    const load = isPdf && agentId ? L.AgentsAPI.fileBlob(agentId, path).then(b => ({ pdf: new Blob([b], { type: "application/pdf" }) }))
      : agentId ? L.AgentsAPI.preview(agentId, path) : L.WorkspacesAPI.preview(wsId, path);
    load.then(r => {
      if (cancelled) return;
      if (r.pdf) { url = URL.createObjectURL(r.pdf); setSt({ status: "ready", url }); }
      else setSt({ status: "ready", html: r.html });
    }).catch(async e => {
      if (cancelled) return;
      if (agentId && /\.(xlsx|xlsm|xls|ods|csv)$/i.test(path) && e && e.status !== 404) {
        try { const md = await L.AgentsAPI.previewMarkdown(agentId, path); if (!cancelled) setSt({ status: "ready", md }); return; } catch {}
      }
      if (!cancelled) setSt({ status: "error", error: (e && e.message) || String(e) });
    });
    return () => { cancelled = true; if (url) setTimeout(() => URL.revokeObjectURL(url), 4000); };
  }, [agentId, wsId, path]);
  useEffect(() => {
    if (st.md == null || !mdRef.current) return;
    mdRef.current.innerHTML = L.renderMarkdown(st.md);
  }, [st.md]);
  if (st.status === "error") return <div className="canvas-status err">{t("canvas.previewFailed", { error: st.error })}</div>;
  if (st.status !== "ready") return <div className="canvas-status">{t("canvas.preparing")}</div>;
  if (st.url) return <iframe className="canvas-frame" src={st.url} title={t("canvas.pdfPreview")} />;
  if (st.md != null) return <div className="canvas-md md canvas-table" ref={mdRef} />;
  /* sandbox with no flags: no scripts, no forms, an opaque origin */
  return <iframe className="canvas-frame sheet" sandbox="" srcDoc={st.html} title={t("canvas.sheetPreview")} />;
}

/* A file's canvas kind from its name, for a document opened from Files. */
function docKind(name) {
  const ext = (String(name).match(/\.([a-z0-9]+)$/i) || [])[1] || "";
  const e = ext.toLowerCase();
  return e === "pdf" ? "pdf" : /^(xlsx|xlsm|xls|ods|csv)$/.test(e) ? "xlsx" : /^(pptx?|odp)$/.test(e) ? "pptx" : "docx";
}

/* the address of a "url" canvas if it is one the app may frame or link, else null */
function canvasHttpUrl(u) {
  const v = String(u || "").trim();
  if (!/^https?:\/\//i.test(v)) return null;
  try { const x = new URL(v); return x.protocol === "http:" || x.protocol === "https:" ? x.href : null; } catch { return null; }
}
function AgentCanvas({ agentId, payload }) {
  const mdRef = useRef(null);
  const kind = payload.kind;

  /* Markdown: render + upgrade ```mermaid blocks to SVG, then highlight the rest. */
  useEffect(() => {
    if (kind !== "markdown") return;
    const el = mdRef.current; if (!el) return;
    el.innerHTML = L.renderMarkdown(payload.content || "");
    if (L.decorateCode) try { L.decorateCode(el); } catch {}
    renderMermaidIn(el);
  }, [kind, payload.content]);

  if (kind === "html")
    /* allow-forms + allow-modals: a form submit or confirm()/alert() inside
       agent-built HTML fails SILENTLY without them (no page-visible error).
       Scripts are already allowed, so neither flag adds reachable surface;
       still no allow-same-origin — the document keeps its opaque origin. */
    return <iframe className="canvas-frame" sandbox="allow-scripts allow-popups allow-forms allow-modals" srcDoc={payload.content || ""} title={t("canvas.htmlPreview")} />;
  /* Only an http(s) address is framed (canvasHttpUrl): a transcript saved
     before the engine checked may still hold anything, and "javascript:..."
     in this frame would run as the app's own page. */
  if (kind === "url")
    return canvasHttpUrl(payload.content)
      ? <iframe className="canvas-frame" sandbox="allow-scripts allow-popups allow-forms allow-same-origin" src={canvasHttpUrl(payload.content)} title={t("canvas.sitePreview")} />
      : <div className="canvas-md"><p><code>{String(payload.content || "").slice(0, 500)}</code></p></div>;
  if (payload.path && (kind === "pdf" || kind === "xlsx" || kind === "docx" || kind === "pptx"))
    return <DocView agentId={agentId} path={payload.path} />;
  return <div className="canvas-md md" ref={mdRef} />;
}

/* Jump, don't glide: .scroll is scroll-behavior:smooth, which is right for the
   inch-by-inch autoscroll of a streaming answer and wrong for "take me to the
   end of a thousand-line thread". Suspending the property beats
   behavior:"instant", which older Safari rejects outright. */
function jumpNow(el) {
  const prev = el.style.scrollBehavior;
  el.style.scrollBehavior = "auto";
  el.scrollTop = el.scrollHeight;
  el.style.scrollBehavior = prev;
}

/* A transcript that follows new content, plus a way back to the end.

   Driven by a ResizeObserver rather than by a render signature, because the
   height of a thread is not final when React commits it: markdown, syntax
   highlighting, KaTeX and images all settle afterwards, and a jump measured
   too early lands in the middle of a long conversation. Watching the box
   catches every one of those, and streamed tokens for free.

   `id` is the thread being shown: a new one starts pinned to its newest turn.
   Chat passes in the App's own refs (its streaming callbacks poke stickRef
   directly); the agent view lets the hook own them. */
function useTranscriptScroll(id, extRef, extStick) {
  const ownRef = useRef(null), ownStick = useRef(true);
  const ref = extRef || ownRef, stick = extStick || ownStick;
  const [away, setAway] = useState(false);
  /* A CALLBACK ref, not a plain one: this hook lives in a component that
     renders the auth gate first, so the scroller mounts several renders later
     and a plain ref would sit at null with nothing to re-trigger setup. The
     external ref object is still filled in, so the streaming callbacks that
     read scrollRef.current keep working untouched. */
  const [node, setNode] = useState(null);
  const attach = useCallback(el => { ref.current = el; setNode(el); }, []);
  useEffect(() => {
    const el = node; if (!el) return;
    const gapNow = () => el.scrollHeight - el.scrollTop - el.clientHeight;
    /* Pinning is INSTANT even though .scroll is smooth: a smooth scroll emits
       intermediate scroll events whose gap is still large, which would turn
       following off halfway through its own animation. */
    const sync = () => {
      if (stick.current) { jumpNow(el); setAway(false); }
      else setAway(gapNow() > 240);      /* far enough that the button earns its place */
    };
    const onScroll = () => { const g = gapNow(); stick.current = g < 80; setAway(g > 240); };
    el.addEventListener("scroll", onScroll, { passive: true });
    const ro = typeof ResizeObserver === "function" ? new ResizeObserver(sync) : null;
    if (ro) { ro.observe(el); if (el.firstElementChild) ro.observe(el.firstElementChild); }
    /* The observer covers a visible tab; these cover the rest: a browser
       without ResizeObserver, and a tab that is hidden while the thread opens
       (no frames, so no observer callbacks either). Cheap and idempotent. */
    const settle = [0, 250, 700].map(ms => setTimeout(sync, ms));
    stick.current = true; sync();
    return () => {
      el.removeEventListener("scroll", onScroll);
      if (ro) ro.disconnect();
      settle.forEach(clearTimeout);
    };
  }, [node, id]);
  const toBottom = useCallback(() => {
    const el = ref.current; if (!el) return;
    stick.current = true; setAway(false); jumpNow(el);
  }, []);
  return { ref: attach, away, toBottom };
}
function ScrollDown({ show, onClick }) {
  if (!show) return null;
  return (
    <button className="scroll-down" onClick={onClick} title={t("chat.toEnd")} aria-label={t("chat.toEnd")}>
      <svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor"
           strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 5v14M19 12l-7 7-7-7" />
      </svg>
    </button>
  );
}

/* The agent's LOOPS: standing missions run on a cadence ("monitor X", "handle
   support inbox"). This panel is the control surface — see each loop's prompt,
   edit it, start/stop it, fire it now. Any active loop (or service) makes the
   agent a background agent; pause them all and it returns to Foreground. */
function AgentView({ agent, onMenu, onRename, onSetBackend, onInstructions, busy, reconnecting, engineReady, onSend, onStop, orphan, onDismissOrphan, onOpenRoutines, box, dockedApp, canPickModel, queue, queueAct, workspaces, isAdmin, onMoveWs, asks, onAnswerAsk, modelHint, modelHintAct, contextAct, setConfirm, onOpenApp, onBundleRemoved, onAppData }) {
  /* made from a bundle: its setup card, "About this bundle", and a first question for the box */
  const [bView, reloadB, setBView] = useBundleView(agent, busy);
  const [showAbout, setShowAbout] = useState(false);
  const [preset, setPreset] = useState("");
  const [editing, setEditing] = useState(false);
  /* No point offering the wiki on an agent that has no access to one. */
  const wikiAvailable = agent.wiki && agent.wiki !== "none";
  const [draft, setDraft] = useState(agentName(agent));
  const [showFiles, setShowFiles] = useState(false);
  const [showConn, setShowConn] = useState(false);   /* false | true | { service, access }: open at that service */
  /* what it may use now, so a card under a reply can say "added" */
  const [granted, setGranted] = useState({});
  const loadGranted = () => L.AgentConnectorsAPI.get(agent.id)
    .then(d => setGranted(Object.fromEntries((d.grants || []).filter(g => g.account && g.fits).map(g => [g.service, g.access])))).catch(() => {});
  useEffect(() => { setGranted({}); loadGranted(); }, [agent.id]);
  const [files, setFiles] = useState([]);
  const [filesLoading, setFilesLoading] = useState(false);
  const [dl, setDl] = useState(null);            /* path currently downloading */
  useEffect(() => { setDraft(agentName(agent)); setEditing(false); setShowFiles(false); setShowConn(false); setFiles([]); setServices([]); }, [agent.id]);
  const msgs = agent.messages || [];
  /* The agent transcript keeps itself pinned to the newest turn. Chat has done
     this since the beginning through the App's own refs, but those belong to
     the chat view's scroller — this one is a different element, so an agent
     answer used to stream away below the fold with nothing following it. */
  const scroller = useTranscriptScroll(agent.id);
  /* The newest turn that reported usage. Older turns keep theirs, so scrolling
     back shows what the window looked like then rather than now. */
  const lastContext = [...msgs].reverse().find(m => m && m.context) ?
    [...msgs].reverse().find(m => m && m.context).context : null;
  const modelLabel = (L.findModel(agent.model) || {}).label || agent.model || "—";
  /* The ENGINE's own name: "custom" here is an agent backend, not the chat's "your own endpoint". */
  const provLabel  = agent.backendLabel || L.providerLabel(agent.endpoint) || agent.endpoint || "—";

  /* Visual canvas: every payload the agent has produced (persisted on messages)
     plus any live ones this session, with a selector to switch between them.
     Auto-opens + selects the newest when a fresh one arrives; toggleable. */
  /* A document the person opened from Files (peek): a canvas the turn makes
     takes the focus and closes it, since the new output is what to look at
     and the peek would otherwise shift the index once the turn is saved. */
  const [peek, setPeek] = useState(null);
  const saved = msgs.flatMap(m => (m.role === "assistant" && Array.isArray(m.canvases)) ? m.canvases : []);
  const canvases = [...saved, ...(peek ? [peek] : []), ...(agent.liveCanvases || [])];
  const [canvasOpen, setCanvasOpen] = useState(false);
  const [sel, setSel] = useState(0);
  const liveLen = (agent.liveCanvases || []).length;
  const prevLive = useRef(0);
  useEffect(() => { if (liveLen > prevLive.current) { setPeek(null); setCanvasOpen(true); setSel(saved.length + liveLen - 1); } prevLive.current = liveLen; }, [liveLen]);
  useEffect(() => { setCanvasOpen(false); setSel(0); setPeek(null); prevLive.current = (agent.liveCanvases || []).length; }, [agent.id]);
  const openPeek = p => {
    const i = saved.findIndex(c => c.path === p);
    if (i < 0) setPeek({ kind: docKind(p), path: p, title: p.split("/").pop() });
    setSel(i >= 0 ? i : saved.length); setCanvasOpen(true);
  };
  const canvas = canvases.length ? canvases[Math.min(sel, canvases.length - 1)] : null;

  const [services, setServices] = useState([]);
  const loadFiles = async () => {
    setFilesLoading(true);
    try { const r = await L.AgentsAPI.files(agent.id); setFiles(r.files || []); }
    catch { setFiles([]); }
    finally { setFilesLoading(false); }
    L.AgentsAPI.services(agent.id).then(r => setServices(r.services || [])).catch(() => setServices([]));
  };
  const stopSvc = async name => {
    try { await L.AgentsAPI.stopService(agent.id, name); setServices(ss => ss.filter(s => s.name !== name)); }
    catch (e) { alert(t("agent.svcStopFailed") + " " + ((e && e.message) || e)); }
  };
  const showSvcLogs = async name => {
    try { const r = await L.AgentsAPI.serviceLogs(agent.id, name); alert("Logs — " + name + "\n\n" + (r.logs || "(no output yet)")); }
    catch (e) { alert(t("agent.logsFailed") + " " + ((e && e.message) || e)); }
  };
  /* Refresh the file list when a turn finishes (the agent may have written files). */
  const wasBusy = useRef(busy);
  useEffect(() => {
    if (wasBusy.current && !busy && showFiles) loadFiles();
    wasBusy.current = busy;
  }, [busy]);
  const toggleFiles = () => { const n = !showFiles; setShowFiles(n); if (n) loadFiles(); };
  const download = async (p) => { setDl(p); try { await L.AgentsAPI.download(agent.id, p); } catch (e) { alert(t("file.downloadFailedWith") + " " + e.message); } finally { setDl(null); } };

  return (
    <div className={"agent-shell" + (canvasOpen && canvas ? " canvas-open" : "")}>
      <div className="agent-pane">
      <div className="topbar">
        <div style={{ display: "flex", alignItems: "center", minWidth: 0 }}>
          <button className="menu-btn" onClick={onMenu}><MenuIcon /></button>
          <div className="topbar-title">
            <span className="tt-kind">Agent</span>
            {editing
              ? <input className="agent-name-edit" value={draft} autoFocus
                       onChange={e => setDraft(e.target.value)}
                       onBlur={() => { setEditing(false); const n = draft.trim(); if (n && n !== agentName(agent)) onRename(agent.id, n); }}
                       onKeyDown={e => { if (e.key === "Enter") e.target.blur(); if (e.key === "Escape") { setDraft(agentName(agent)); setEditing(false); } }} />
              : <span className="tt-name" onClick={() => setEditing(true)} title={agentName(agent) + ". Click to rename."}>{agentName(agent)}</span>}
          </div>
        </div>
        <div className="tools">
          <BoxBusy box={box} />
          <ContextGauge {...(lastContext || {})} />
          {canPickModel && <AgentEngineSelect agent={agent} onPick={patch => onSetBackend(agent.id, patch)} />}
          <span className="agent-tag">BETA</span>
          {agent.bundle && (
            <button className="bundle-chip" title={t("bundle.aboutHint")} onClick={() => setShowAbout(true)}>
              <span className="bundle-chip-ic">{agent.bundle.icon}</span><span className="btn-label">{bl(agent.bundle.name)}</span>
              {bView && !bView.dismissed && bView.manage && bView.done < bView.total && <span className="bundle-chip-n">{bView.done}/{bView.total}</span>}
            </button>
          )}
          {agent.wiki && agent.wiki !== "none" && (
            <span className={"loop-chip" + (agent.wiki === "write" ? "" : " ro")}
                  title={agent.wiki === "write" ? t("agent.wikiChipWrite") : t("agent.wikiChipRead")}>
              {agent.wiki === "write" ? "✎ wiki" : "▤ wiki"}
            </span>
          )}
          {agent.background && <span className="loop-chip" title={t("agent.backgroundHint")}>◉ loop</span>}
          <button className={"icon-btn labelled" + (agent.background ? " on" : "")}
                  title={t("routine.agentHint")}
                  onClick={() => onOpenRoutines && onOpenRoutines(agent.id)}><ClockIcon /> <span className="btn-label">{t("routine.schedule")}</span></button>
          <button className={"icon-btn labelled" + (showConn ? " on" : "")} title={t("conn.buttonHint")}
                  onClick={() => setShowConn(true)}><PlugIcon /> <span className="btn-label">{t("conn.button")}</span></button>
          {canvases.length > 0 && <button className={"icon-btn" + (canvasOpen ? " on" : "")} title={t("canvas.title")} onClick={() => setCanvasOpen(o => !o)}><CanvasIcon /></button>}
          <button className={"icon-btn" + (showFiles ? " on" : "")} title={t("agent.files")} onClick={toggleFiles}><FilesIcon /></button>
          {onMoveWs && !dockedApp && <MoveToWorkspace item={agent} workspaces={workspaces} isAdmin={isAdmin} onMove={ws => onMoveWs(agent.id, ws)} />}
          <a className="icon-btn" title={t("nav.guide")} href={guideHref()} target="_blank" rel="noopener"><HelpIcon /></a>
        </div>
      </div>

      {orphan && !busy && (
        <div style={{ padding: "10px 24px 0" }}>
          <div className="orphan-banner">
            <span className="sq" style={{ width: 8, height: 8, background: "var(--maroon)", flex: "none" }} />
            <span>A run was interrupted{orphan.title ? " — “" + orphan.title + "”" : ""} (server restart). The workspace and session are intact.</span>
            <button className="act-btn" onClick={() => { onSend(t("run.resumeHint"), [], false); onDismissOrphan && onDismissOrphan(orphan.id); }}>{t("run.resume")}</button>
            <button className="x" onClick={() => onDismissOrphan && onDismissOrphan(orphan.id)}>✕</button>
          </div>
        </div>
      )}

      <div className="scroll-wrap">
        <div className="scroll" ref={scroller.ref}>
          {msgs.length === 0
            ? (
              <div className="agent-empty">
                <div className="agent-empty-ic"><BotIcon /></div>
                <h2>{agentName(agent)}</h2>
                {agentDesc(agent) && <p className="agent-empty-purpose">{agentDesc(agent)}</p>}
                {/* Where to begin. Docked to an app, the job is that app;
                    otherwise say that apps are made here, and how, because
                    nothing else on an empty agent does. */}
                {/* a bundle's agent has a job, not an app to build */}
                {agent.bundle
                  ? <p>{dockedApp ? tb("bundle.emptyDocked", { name: dockedApp }) : tb("bundle.emptyAlone", { name: bl(agent.bundle.name) })}</p>
                  : dockedApp
                  ? <p>{tb("agent.emptyDocked", { name: dockedApp })}</p>
                  : <><p>{tb("agent.emptyDesc")}</p><p>{tb("agent.emptyApps")}</p></>}
                <p className="agent-empty-model">{modelLabel} · {t("common.via")} {provLabel}</p>
                {!agent.backend && !agent.modelPin && <p className="agent-empty-model">{t("agent.emptyModelDefault")}</p>}
              </div>
            )
            : (
              <div className="thread">
                {msgs.map((m, i) => (
                  <Message key={i} m={m}
                           modelLabel={(L.findModel(m.servedModel || m.model) || {}).label || m.model || agent.name}
                           provider={L.providerLabel(m.endpoint)}
                           onDownloadFile={download}
                           proposalState={{ granted, instructions: agent.instructions, mayEdit: typeof agent.instructions === "string" }}
                           onProposal={p => p.kind === "connection" ? setShowConn({ service: p.service, access: p.access }) : onInstructions && onInstructions(agent.id, p.text)}
                           isLast={i === msgs.length - 1} busy={busy}
                           onRetry={() => { const ask = msgs.slice(0, i).reverse().find(x => x.role === "user"); if (ask && ask.content) onSend(ask.content, [], false); }}
                           /* a conversation that no longer fits: the owner (an admin
                              on a shared agent) starts it afresh or moves it */
                           onFresh={contextAct && m.errorKind === "context-full" && (agent.scope !== "global" || isAdmin) ? () => contextAct.fresh(agent.id) : undefined}
                           onLarger={contextAct && m.errorKind === "context-full" && (agent.scope !== "global" || isAdmin) ? e => contextAct.larger(agent.id, e) : undefined}
                           manageNote={t("msg.ctxFullMember")}
                           streaming={busy && i === msgs.length - 1 && m.role === "assistant"} />
                ))}
              </div>
            )}
        </div>
        <ScrollDown show={scroller.away} onClick={scroller.toBottom} />
      </div>

      {showConn && <ConnectionsModal agent={agent} title={agentName(agent)} initial={showConn === true ? null : showConn} onClose={() => { setShowConn(false); loadGranted(); reloadB(); }} />}
      {showAbout && bView && <BundleAbout agent={agent} view={bView} reload={reloadB} setView={setBView} onClose={() => setShowAbout(false)} onAppData={onAppData}
                                          onOpenApp={id => onOpenApp && onOpenApp(id)} setConfirm={setConfirm}
                                          onSetup={() => L.BundlesAPI.update(agent.id, { setup: { dismissed: false } }).then(setBView).catch(() => {})}
                                          onRemoved={() => { setShowAbout(false); onBundleRemoved && onBundleRemoved(agent.id); }} />}
      {showFiles && (
        <div className="agent-files">
          {services.length > 0 && (
            <div style={{ padding: "8px 14px", borderBottom: "1px solid var(--line)" }}>
              <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ink-4)", marginBottom: 6 }}>{t("agent.services")}</div>
              {services.map(s => (
                <div key={s.name} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, padding: "3px 0" }}>
                  <span style={{ width: 7, height: 7, borderRadius: "50%", flex: "none", background: s.status === "running" ? "var(--green)" : "var(--maroon)" }} />
                  <span style={{ fontFamily: "var(--mono)", fontSize: 11.5 }}>{s.name}</span>
                  <span style={{ color: "var(--ink-4)", fontSize: 11 }}>{s.status}</span>
                  <span style={{ marginLeft: "auto", display: "flex", gap: 6 }}>
                    <button className="agent-files-refresh" onClick={() => showSvcLogs(s.name)}>{t("agent.logs")}</button>
                    <button className="agent-files-refresh" style={{ color: "var(--maroon)" }} onClick={() => stopSvc(s.name)}>{t("common.stop")}</button>
                  </span>
                </div>
              ))}
            </div>
          )}
          <div className="agent-files-head">
            <span>{t("agent.files")} {files.length ? "(" + files.length + ")" : ""}</span>
            <button className="agent-files-refresh" onClick={loadFiles} disabled={filesLoading}>{filesLoading ? "Loading…" : "Refresh"}</button>
          </div>
          {!filesLoading && files.length === 0 && <div className="agent-files-empty">{t("agent.noFiles")}</div>}
          {files.length > 0 && (
            <div className="agent-files-list">
              {files.map(f => (
                <div className="agent-file" key={f.path}>
                  <span className="agent-file-name" title={f.path}>{f.path}</span>
                  <span className="agent-file-size">{fmtBytes(f.size)}</span>
                  {L.canPreview(f.path) && <button className="agent-file-dl" onClick={() => openPeek(f.path)} title={t("file.preview")}><EyeIcon /></button>}
                  <button className="agent-file-dl" onClick={() => download(f.path)} disabled={dl === f.path} title={t("common.download")}>
                    {dl === f.path ? "…" : <DownloadIcon />}
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {reconnecting && (
        <div style={{ padding: "0 24px" }}>
          <div className="reconnect-banner"><span className="rec-dot busy" /> {t("agent.reconnecting")}</div>
        </div>
      )}

      {/* made from a bundle and not set up yet: what it needs, step by step (for whoever may set it up;
          a member on a shared bundle has About) */}
      {bView && !bView.dismissed && bView.manage && (
        <BundleSetupCard agent={agent} view={bView} reload={reloadB} setView={setBView} onAppData={onAppData}
                         onConnect={x => setShowConn(x)} onTry={text => setPreset(text)} onAbout={() => setShowAbout(true)} />
      )}
      {/* the same message box as a new agent's on the start page */}
      <AgentComposer key={agent.id} agentId={agent.id} agentName={agentName(agent)} wikiAvailable={wikiAvailable}
                     presetText={preset} clearPreset={() => setPreset("")}
                     placeholder={agent.bundle ? t("bundle.placeholder", { name: agentName(agent) }) : undefined}
                     busy={busy} engineReady={engineReady} onSend={onSend} onStop={onStop}
                     asks={asks} onAnswerAsk={onAnswerAsk && ((askId, body) => onAnswerAsk(agent.id, askId, body))}
                     modelHint={modelHint} onModelHint={modelHintAct && { wait: () => modelHintAct.wait(agent.id), switchTo: () => modelHintAct.switchTo(agent.id) }}
                     queue={queue} onQueue={queueAct && {
                       now: qid => queueAct.now(agent.id, qid), resume: () => queueAct.resume(agent.id),
                       remove: qid => queueAct.remove(agent.id, qid), clear: () => queueAct.clear(agent.id),
                     }} />
      </div>

      {canvasOpen && canvas && (
        <div className="agent-canvas">
          <div className="agent-canvas-head">
            <span className="acv-kind">{canvas.kind}</span>
            <span className="acv-title" title={canvas.title || canvas.path || ""}>{canvas.title || canvas.path || "Canvas"}</span>
            {canvas.kind === "url" && canvasHttpUrl(canvas.content) && <a className="acv-open" href={canvasHttpUrl(canvas.content)} target="_blank" rel="noopener noreferrer">{t("canvas.open")}</a>}
            {canvas.path && ["pdf", "xlsx", "docx", "pptx"].includes(canvas.kind) && <button className="acv-open" onClick={() => download(canvas.path)}>{t("common.download")}</button>}
            <button className="acv-close" title={t("canvas.close")} onClick={() => setCanvasOpen(false)}>✕</button>
          </div>
          {canvases.length > 1 && (
            <div className="acv-tabs">
              {canvases.map((c, i) => (
                <button key={i} className={"acv-tab" + (i === Math.min(sel, canvases.length - 1) ? " on" : "")}
                        title={c.title || c.path || c.kind} onClick={() => setSel(i)}>
                  {c.title || c.path || c.kind}
                </button>
              ))}
            </div>
          )}
          <div className="agent-canvas-body">
            <AgentCanvas key={sel + "|" + canvas.kind + (canvas.path || "") + (canvas.title || "")} agentId={agent.id} payload={canvas} />
          </div>
        </div>
      )}
    </div>
  );
}

/* The model a turn waits on says nothing (or the turn failed), and it failed
   a test just now: say so, and offer the first model of the deployment's
   priority list that answered its own test (App's model watcher, server.js
   model priority). */
const engineName = e => !e ? "" : ((L.findModel(e.model) || {}).label || (!e.pinned && e.backendLabel) || e.model);
function waitWords(ms) {
  const s = Math.max(1, Math.round(ms / 1000));
  return s < 120 ? t("model.waitSec", { n: s }) : t("model.waitMin", { n: Math.round(s / 60) });
}
function ModelHint({ h, act }) {
  const cur = engineName(h.current), next = engineName(h.suggest);
  return (
    <div className="model-hint" role="status">
      <div className="mh-text">
        {h.suggest
          ? tb(h.failed ? "model.hintFailed" : "model.hintSuggest", { current: cur, wait: waitWords(Date.now() - h.since), next, n: h.suggest.priority })
          : tb("model.hintNone", { current: cur, wait: waitWords(Date.now() - h.since) })}
        {h.current && h.current.error && <div className="mh-why">{h.current.timeout ? t("model.hintTimeout", { n: h.current.timeout }) : t("model.hintWhy", { error: h.current.error })}</div>}
        {h.error && <div className="mh-why err">{h.error}</div>}
      </div>
      <div className="mh-acts">
        {h.suggest && h.mayPersist && (
          <button className="btn primary" disabled={!!h.switching} onClick={() => act && act.switchTo()}>
            {h.switching ? t("model.switching") : t("model.switchSend", { model: next })}
          </button>
        )}
        {h.suggest && !h.mayPersist && <span className="mh-note">{t("model.adminSwitches")}</span>}
        <button className="btn" disabled={!!h.switching} onClick={() => act && act.wait()}>{t(h.failed ? "common.dismiss" : "model.keepWaiting")}</button>
      </div>
    </div>
  );
}

/* The message box of an agent, and of a new agent on the start page: ONE
   component, so starting an agent and talking to one look and work the same
   (attachments, voice, paste, drop anywhere, the wiki and privacy switches).
   They used to differ, and the start page had a bare text field. Keyed per
   agent by its parent, so each agent gets its own text, files and switches.
   With no agentId yet, ensureAgent() makes the agent on demand: its first file
   needs a workspace to land in. */
/* An agent's composer switches as this browser remembers them (wiki, and the
   tools switched off), by agent id or "new" for the start page. */
function agentFlags(key) {
  let f = {}; try { f = JSON.parse(localStorage.getItem("indie.agent.flags." + key) || "{}") || {}; } catch {}
  const strs = v => Array.isArray(v) ? v.filter(x => typeof x === "string") : [];
  return { wiki: f.wiki === true, toolsOff: strs(f.toolsOff), mcpOff: strs(f.mcpOff) };
}

/* ---------- the agent composer's Tools menu ----------
   Web search and each connected MCP server's tools, each with a switch. What
   is off is left out of the turns this browser starts on this agent: the
   server does not connect a switched-off server or hand the container the
   search key, and pi drops single tools (agentToolCatalog in server.js).
   Routines keep every tool. The list is the agent's own scope, so a shared
   agent shows the shared servers only. */
const TOOL_CATALOG = new Map();   /* agent id | "new" -> { at, data }, for a minute */
function loadToolCatalog(agentId, workspaceId) {
  const k = agentId || ("new:" + (workspaceId || "")), hit = TOOL_CATALOG.get(k);
  if (hit && Date.now() - hit.at < 60000) return Promise.resolve(hit.data);
  return L.AgentsAPI.tools(agentId, workspaceId).then(data => { TOOL_CATALOG.set(k, { at: Date.now(), data }); return data; });
}
function ToolSwitchRow({ on, label, sub, title, nested, strong, onFlip }) {
  return (
    <button type="button" role="switch" aria-checked={on} title={title || ""} onClick={onFlip}
            className={"atm-row" + (nested ? " nested" : "") + (on ? "" : " off")}>
      <span className={"mcp-switch " + (on ? "on" : "")}><span /></span>
      <span className="atm-text">
        <span className={"atm-name" + (strong ? " strong" : "")}>{label}</span>
        {sub ? <span className="atm-sub">{sub}</span> : null}
      </span>
    </button>
  );
}

function AgentToolsMenu({ agentId, workspaceId, toolsOff, mcpOff, setToolsOff, setMcpOff }) {
  const [open, setOpen] = useState(false);
  const [cat, setCat] = useState(() => { const h = TOOL_CATALOG.get(agentId || ("new:" + (workspaceId || ""))); return h ? h.data : null; });
  const [err, setErr] = useState(null);
  const ref = useRef(null);
  useEffect(() => {
    let live = true;
    loadToolCatalog(agentId, workspaceId).then(d => { if (live) { setCat(d); setErr(null); } },
                                  e => { if (live) setErr((e && e.message) || "error"); });
    return () => { live = false; };
  }, [agentId, workspaceId, open]);
  useEffect(() => {
    if (!open) return;
    const away = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const esc = e => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("mousedown", away); document.addEventListener("keydown", esc);
    return () => { document.removeEventListener("mousedown", away); document.removeEventListener("keydown", esc); };
  }, [open]);
  const servers = (cat && cat.servers) || [];
  /* Nothing to switch (no web search for agents here, no MCP servers) still
     gets the button, and the menu says why: hidden, it looked like a feature
     that had not arrived. */
  const none = !!cat && !cat.search && !servers.length;
  const offTool = new Set(toolsOff), offServer = new Set(mcpOff);
  const flip = (list, set, v) => set(list.includes(v) ? list.filter(x => x !== v) : [...list, v]);
  const total = cat ? (cat.search ? 1 : 0) + servers.reduce((n, s) => n + s.tools.length, 0) : 0;
  const off = cat ? (cat.search && offTool.has("web_search") ? 1 : 0)
    + servers.reduce((n, s) => n + (offServer.has(s.name) ? s.tools.length : s.tools.filter(x => offTool.has(x.id)).length), 0) : 0;
  return (
    <div className="tool-toggle-wrap atm-wrap" ref={ref}>
      <button type="button" className={"tool-toggle " + (!cat || off < total ? "on" : "")} aria-expanded={open}
              onClick={() => setOpen(o => !o)} title={t("agent.toolsHint")}>
        <ToolsIcon /> {off ? t("agent.toolsSomeOff", { n: off }) : t("agent.tools")}
      </button>
      {open && (
        <div className="mcp-menu agent-tools-menu" role="dialog" aria-label={t("agent.toolsTitle")}>
          <div className="mcp-menu-head">{t("agent.toolsTitle")}</div>
          {!cat && <div className={"atm-note" + (err ? " err" : "")}>{err ? t("agent.toolsLoadFailed", { error: err }) : t("common.loading")}</div>}
          {cat && cat.search && (
            <ToolSwitchRow on={!offTool.has("web_search")} label={t("tools.webSearch")} strong
                           onFlip={() => flip(toolsOff, setToolsOff, "web_search")} />
          )}
          {servers.map(s => {
            const on = !offServer.has(s.name);
            return (
              <div key={s.name} className="atm-server">
                <ToolSwitchRow on={on} label={s.name} strong title={t("agent.toolsAllOf", { name: s.name })}
                               sub={s.error ? t("agent.toolsUnreachable") : t("agent.toolsCount", { n: s.tools.length })}
                               onFlip={() => flip(mcpOff, setMcpOff, s.name)} />
                {on && s.tools.map(x => (
                  <ToolSwitchRow key={x.id} nested on={!offTool.has(x.id)} label={x.name} sub={x.description} title={x.description}
                                 onFlip={() => flip(toolsOff, setToolsOff, x.id)} />
                ))}
              </div>
            );
          })}
          {none && <div className="atm-note">{t("agent.toolsNone")}</div>}
          {cat && !none && <div className="atm-note">{t("agent.toolsNote")}</div>}
        </div>
      )}
    </div>
  );
}

/* A routine the agent proposes (routine_create / routine_update): what it
   would run, when, and for which app, so the person can confirm it with one
   click instead of copying a prompt into the editor. A change shows only what
   changes, with what it was. The server makes the routine when they confirm. */
function RoutineAskCard({ a, onAnswer }) {
  const r = a.routine || {}, f = r.fields || {}, was = r.before || null;
  const create = r.action === "create";
  const app = (id, name) => id ? "▦ " + (name || t("app.thisApp")) : t("ask.routineNoApp");
  const rows = [];
  const row = (k, label, now, before) => rows.push(
    <div className="rk-row" key={k}>
      <span className="rk-k">{label}</span>
      <span className="rk-v">{before != null && <span className="rk-was">{before}</span>}{before != null && " → "}{now}</span>
    </div>);
  if (f.title !== undefined && !create) row("title", t("ask.routineName"), f.title, was && was.title);
  if (f.cron !== undefined) row("cron", t("ask.routineWhen"), <>{cronToText(f.cron)} <code>{f.cron}</code></>, was ? cronToText(was.cron) : null);
  if (f.enabled !== undefined) row("enabled", t("ask.routineState"), f.enabled ? t("ask.routineResume") : t("routine.paused"), null);
  if (f.appId !== undefined && (create ? !!f.appId : true)) row("app", t("ask.routineApp"), app(f.appId, r.appName), was ? app(was.appId, was.appName) : null);
  if (f.notify !== undefined) row("notify", t("routine.notify"), f.notify ? t("ask.routineOn") : t("ask.routineOff"), was ? (was.notify ? t("ask.routineOn") : t("ask.routineOff")) : null);
  return (
    <div className="ask-card approve routine">
      <div className="ask-head"><span className="ask-ic">⏰</span> <span>{create ? tb("ask.routineCreate", { title: r.title }) : tb("ask.routineUpdate", { title: (was && was.title) || r.title })}</span></div>
      {rows.length > 0 && <div className="rk-rows">{rows}</div>}
      {f.prompt !== undefined && (
        /* open: a new task is what the person most needs to read before saying yes */
        <details className="rk-prompt" open>
          <summary>{create ? t("ask.routineTask") : t("ask.routineTaskNew")}</summary>
          <pre className="ask-args">{f.prompt}</pre>
        </details>
      )}
      <div className="ask-acts">
        <button className="btn primary" onClick={() => onAnswer({ approved: true })}>{create ? t("ask.routineCreateBtn") : t("ask.routineUpdateBtn")}</button>
        <button className="btn" onClick={() => onAnswer({ approved: false })}>{t("ask.decline")}</button>
        <span className="ask-time">{t("ask.until", { time: L.fmtTime ? L.fmtTime(a.expires) : new Date(a.expires).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) })}</span>
      </div>
    </div>
  );
}

/* The email card (server.js, emailGate): a mail an agent wrote through a
   connected mailbox, shown before it goes anywhere. The person changes what
   they like (recipients, subject, text, attachments) and sends it, keeps it
   as a draft, or discards it; what they send back is what runs. */
const mailList = v => String(v || "").split(/[,;\n]/).map(x => x.trim()).filter(Boolean);
function EmailAskCard({ a, agentId, agentName, onAnswer }) {
  const e = a.email || {};
  const [to, setTo] = useState((e.to || []).join(", "));
  const [cc, setCc] = useState((e.cc || []).join(", "));
  const [bcc, setBcc] = useState((e.bcc || []).join(", "));
  const [copies, setCopies] = useState(!!((e.cc || []).length || (e.bcc || []).length));
  const [subject, setSubject] = useState(e.subject || "");
  const [body, setBody] = useState(e.body || "");
  const [files, setFiles] = useState(e.attach || []);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(null);
  const fileRef = useRef(null);
  const reply = !!e.reply;
  const send = a.action === "send";
  const go = action => {
    if (!body.trim()) return setErr(t("mail.needText"));
    if (!reply && !mailList(to).length && !mailList(cc).length && !mailList(bcc).length) return setErr(t("mail.needTo"));
    setErr(null); setBusy(true);
    onAnswer({ approved: true, action, email: { to: mailList(to), cc: mailList(cc), bcc: mailList(bcc), subject, body, attach: files.map(f => f.path) } });
  };
  const addFiles = async list => {
    setErr(null); setBusy(true);
    try {
      for (const f of list) {
        const name = "mail/outgoing/" + f.name.replace(/[\\/:*?"<>|]+/g, "_");
        const r = await L.AgentsAPI.upload(agentId, f, name);
        setFiles(cur => [...cur.filter(x => x.path !== "/workspace/" + r.path), { path: "/workspace/" + r.path, name: r.path.split("/").pop(), size: r.size }]);
      }
    } catch (x) { setErr((x && x.message) || t("mail.attachFailed")); }
    finally { setBusy(false); if (fileRef.current) fileRef.current.value = ""; }
  };
  const size = n => n == null ? "" : n < 1024 ? n + " B" : n < 1048576 ? Math.round(n / 1024) + " KB" : (n / 1048576).toFixed(1) + " MB";
  const svc = { google_gmail: "Gmail", ms_outlook: "Outlook", imap_mail: t("mail.mailbox") }[a.service] || a.server;
  const blocked = !a.canSend && (a.sendBlocked === "policy" ? t("mail.noSendPolicy") : a.sendBlocked === "scope" ? t("mail.noSendScope") : a.sendBlocked === "access" ? t("mail.noSendAccess") : a.sendBlocked === "grant" ? t("mail.noSendGrant") : "");
  const until = t("ask.until", { time: L.fmtTime ? L.fmtTime(a.expires) : new Date(a.expires).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) });
  return (
    <div className="ask-card approve email-card">
      <div className="ask-head"><span className="ask-ic">✉</span> <span>{tb(send ? "mail.titleSend" : "mail.titleDraft", { agent: agentName || t("mail.theAgent") })}</span></div>
      <div className="ask-account">{svc}{a.account ? " · " + a.account : ""}</div>
      {reply && <div className="email-reply">{t("mail.isReply")}</div>}
      <div className="email-fields">
        <label className="email-row"><span>{t("mail.to")}</span><input value={to} onChange={ev => setTo(ev.target.value)} spellCheck="false" placeholder={reply ? t("mail.replyTo") : ""} /></label>
        {copies ? (<>
          <label className="email-row"><span>{t("mail.cc")}</span><input value={cc} onChange={ev => setCc(ev.target.value)} spellCheck="false" /></label>
          <label className="email-row"><span>{t("mail.bcc")}</span><input value={bcc} onChange={ev => setBcc(ev.target.value)} spellCheck="false" /></label>
        </>) : <button className="email-copies" onClick={() => setCopies(true)}>{t("mail.addCopies")}</button>}
        <label className="email-row"><span>{t("mail.subject")}</span><input value={subject} onChange={ev => setSubject(ev.target.value)} placeholder={reply ? t("mail.replySubject") : ""} /></label>
        <textarea className="email-body" value={body} rows={Math.min(14, Math.max(5, body.split("\n").length + 1))} onChange={ev => setBody(ev.target.value)} aria-label={t("mail.text")} />
      </div>
      <div className="email-files">
        {files.map(f => (
          <span className="email-file" key={f.path} title={f.path}>
            <ClipIcon />
            {f.path.startsWith("/workspace/")
              ? <button className="email-file-name" onClick={() => L.AgentsAPI.download(agentId, f.path.slice("/workspace/".length)).catch(() => {})}>{f.name}</button>
              : <span className="email-file-name">{f.name}</span>}
            {f.size != null && <span className="email-file-size">{size(f.size)}</span>}
            <button className="email-file-x" title={t("mail.removeFile")} aria-label={t("mail.removeFile") + " " + f.name} onClick={() => setFiles(cur => cur.filter(x => x.path !== f.path))}>✕</button>
          </span>
        ))}
        <button className="email-attach" disabled={busy || !agentId} onClick={() => fileRef.current && fileRef.current.click()}><ClipIcon /> {t("mail.attach")}</button>
        <input ref={fileRef} type="file" multiple hidden onChange={ev => ev.target.files && ev.target.files.length && addFiles([...ev.target.files])} />
      </div>
      {blocked && <div className="email-blocked">{blocked}</div>}
      {err && <div className="auth-error" style={{ marginTop: 8 }}>{err}</div>}
      <div className="ask-acts">
        {send && a.canSend && <button className="btn primary" disabled={busy} onClick={() => go("send")}>{t("mail.send")}</button>}
        <button className={"btn" + (send && a.canSend ? "" : " primary")} disabled={busy} onClick={() => go("draft")}>{t("mail.saveDraft")}</button>
        {!send && a.canSend && <button className="btn" disabled={busy} onClick={() => go("send")}>{t("mail.sendNow")}</button>}
        <button className="btn" disabled={busy} onClick={() => onAnswer({ approved: false })}>{t("mail.discard")}</button>
        <span className="ask-time">{until}</span>
      </div>
    </div>
  );
}

function AgentComposer({ agentId, agentName, workspaceId, ensureAgent, wikiAvailable, busy, engineReady, onSend, onStop, placeholder, hint, presetText, clearPreset, queue, onQueue, asks, onAnswerAsk, modelHint, onModelHint }) {
  const [text, setText] = useState("");
  /* composer attachments (uploaded into the workspace) + voice input */
  const [attach, setAttach] = useState([]);
  const [drag, setDrag] = useState(false);
  const [recording, setRecording] = useState(false);
  const [transcribing, setTranscribing] = useState(false);
  const [voiceErr, setVoiceErr] = useState(null);
  const [priv, setPriv] = useState(false);
  const privacyAvailable = L.toolEnabled("privacy");
  /* Whether this turn gets the wiki and the MCP tools. Per agent and remembered
     here rather than on the row: it is how YOU want to work with this agent,
     not something the agent is. The wiki starts OFF: most turns do not need it,
     and mounting a knowledge base into a coding job just adds noise. */
  const flagKey = "indie.agent.flags." + (agentId || "new");
  const [useWiki, setUseWiki] = useState(() => agentFlags(agentId || "new").wiki === true);
  /* The tools are on unless switched off one by one (or a whole server) in the
     Tools menu: one switch for all of them was a control nobody could place,
     and a turn without its tools just did less. */
  const [toolsOff, setToolsOff] = useState(() => agentFlags(agentId || "new").toolsOff);
  const [mcpOff, setMcpOff] = useState(() => agentFlags(agentId || "new").mcpOff);
  useEffect(() => {
    try { localStorage.setItem(flagKey, JSON.stringify({ wiki: useWiki, toolsOff, mcpOff })); } catch {}
  }, [flagKey, useWiki, toolsOff, mcpOff]);
  const fileInput = useRef(null);
  const dragDepth = useRef(0);
  const rec = useRef(null);
  const taRef = useRef(null);
  const voiceAvailable = typeof navigator !== "undefined" && navigator.mediaDevices && window.AudioContext;
  useEffect(() => { const el = taRef.current; if (!el) return; el.style.height = "auto"; el.style.height = Math.min(el.scrollHeight, 220) + "px"; el.style.overflowY = el.scrollHeight > 220 ? "auto" : "hidden"; }, [text]);
  useEffect(() => {
    if (!presetText) return;
    setText(presetText); clearPreset && clearPreset();
    requestAnimationFrame(() => taRef.current && taRef.current.focus());
  }, [presetText]);
  /* a tool's view puts a message here (ui/message): the person reads it and sends it */
  useEffect(() => {
    const on = e => {
      const d = e.detail || {};
      if (!d.text || !agentId || d.agentId !== agentId) return;
      setText(cur => (cur.trim() ? cur.replace(/\s+$/, "") + "\n\n" : "") + d.text);
      requestAnimationFrame(() => taRef.current && taRef.current.focus());
    };
    window.addEventListener("indie:compose", on);
    return () => window.removeEventListener("indie:compose", on);
  }, [agentId]);

  /* ---- attachments: uploaded into the workspace + converted for context ---- */
  const MAX_UPLOAD = 32 * 1024 * 1024;
  const patchAtt = (id, patch) => setAttach(fs => fs.map(x => x.id === id ? { ...x, ...patch } : x));
  const addFiles = list => {
    Array.from(list).forEach(f => {
      const id = Math.random().toString(36).slice(2);
      setAttach(fs => [...fs, { id, name: f.name, size: f.size, busy: true }]);
      if (f.size > MAX_UPLOAD) { patchAtt(id, { busy: false, error: "too large (max 32 MB)" }); return; }
      /* Put the real file in the workspace AND extract text for prompt context,
         through the SAME converter chat uses, so a scan is already OCR'd text
         by the time the agent sees it, instead of a file it has to work out how
         to read for itself. */
      /* a new agent comes into being with its first file, which needs a workspace */
      const up = (agentId ? Promise.resolve(agentId) : ensureAgent()).then(id => L.AgentsAPI.upload(id, f));
      const cv = L.convertFile(f).catch(() => null);
      Promise.all([up, cv])
        .then(([u, c]) => patchAtt(id, {
          busy: false, path: u.path,
          text: c && c.markdown ? c.markdown : "",
          truncated: c && c.truncated, ocr: c && c.ocr, note: c && c.note,
        }))
        .catch(e => patchAtt(id, { busy: false, error: (e && e.message) || "upload failed" }));
    });
  };

  /* ---- voice input: mic → WAV → the server's speech service (same as chat) ---- */
  const startRecording = async () => {
    setVoiceErr(null);
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      const ctx = new (window.AudioContext || window.webkitAudioContext)();
      const proc = ctx.createScriptProcessor(4096, 1, 1);
      const mic = ctx.createMediaStreamSource(stream);
      const chunks = [];
      proc.onaudioprocess = e => { chunks.push(new Float32Array(e.inputBuffer.getChannelData(0))); };
      mic.connect(proc); proc.connect(ctx.destination);
      rec.current = { ctx, processor: proc, source: mic, stream, chunks };
      setRecording(true);
    } catch (e) {
      setVoiceErr(e && e.name === "NotAllowedError" ? t("voice.denied") : t("voice.startFailed"));
    }
  };
  const stopRecording = async () => {
    const r = rec.current; rec.current = null;
    setRecording(false);
    if (!r) return;
    try { r.processor.disconnect(); r.source.disconnect(); } catch {}
    r.stream.getTracks().forEach(t => t.stop());
    const sampleRate = r.ctx.sampleRate;
    try { await r.ctx.close(); } catch {}
    const total = r.chunks.reduce((n, c) => n + c.length, 0);
    if (total < sampleRate * 0.3) { setVoiceErr(t("voice.tooShort")); return; }
    setTranscribing(true);
    try {
      const wav = L.pcmToWavBlob(r.chunks, sampleRate);
      const said = await L.transcribeAudio(wav);
      if (said) { setText(t => (t ? t.replace(/\s*$/, " ") : "") + said); requestAnimationFrame(() => taRef.current && taRef.current.focus()); }
      else setVoiceErr(t("voice.noSpeech"));
    } catch (e) { setVoiceErr((e && e.message) || t("voice.failed")); }
    finally { setTranscribing(false); }
  };
  const toggleMic = () => { if (transcribing) return; recording ? stopRecording() : startRecording(); };

  /* Files dropped anywhere on the window (see WindowDrop). No dependency array:
     addFiles closes over current state, so the listener is re-bound each render
     rather than capturing a stale one. Claiming the event stops a second
     mounted composer from adding the same file twice. */
  useEffect(() => {
    const onFiles = e => {
      if (e.defaultPrevented || !e.detail || !e.detail.length) return;
      e.preventDefault();
      addFiles(e.detail);
    };
    window.addEventListener("indie:files", onFiles);
    return () => window.removeEventListener("indie:files", onFiles);
  });

  /* One chooser per tap. A hidden input opened twice shows the picker twice,
     which is what a doubled activation looks like on a phone, and touch
     surfaces have more ways to double-fire than a mouse does. Cheap to make
     impossible rather than to keep diagnosing. */
  const pickerBusy = useRef(0);
  const openPicker = () => {
    const now = Date.now();
    if (now - pickerBusy.current < 800) return;
    pickerBusy.current = now;
    if (fileInput.current) fileInput.current.click();
  };

  const onDrop      = e => { e.preventDefault(); dragDepth.current = 0; setDrag(false); if (e.dataTransfer.files?.length) addFiles(e.dataTransfer.files); };
  const onDragEnter = e => { e.preventDefault(); dragDepth.current++; setDrag(true); };
  const onDragLeave = e => { e.preventDefault(); dragDepth.current--; if (dragDepth.current <= 0) setDrag(false); };
  /* Paste (Ctrl/Cmd+V) an image -> upload it into the workspace. */
  const onPaste = e => {
    const imgs = [...(e.clipboardData?.items || [])]
      .filter(it => it.kind === "file" && it.type.startsWith("image/"))
      .map(it => { const f = it.getAsFile(); if (!f) return null; return f.name ? f : new File([f], "pasted-" + Date.now() + "." + ((f.type.split("/")[1]) || "png"), { type: f.type }); })
      .filter(Boolean);
    if (imgs.length) { e.preventDefault(); addFiles(imgs); }
  };

  const converting = attach.some(f => f.busy);
  /* While the agent works, sending queues the message (the server holds it
     and runs it when the turn is done), so there is nothing to wait for. */
  const openAsks = (asks || []).filter(a => a.status === "open");
  const question = openAsks.find(a => a.kind === "question");
  const submit = () => {
    const t = text.trim();
    if ((!t && !attach.length) || converting || recording || transcribing) return;
    /* the agent asked and waits: what you type is the answer (files still
       go as a message of their own) */
    if (question && t && !attach.length && onAnswerAsk) { onAnswerAsk(question.id, { text: t }); setText(""); return; }
    const ready = attach.filter(f => f.path && !f.error);
    onSend(t, ready, priv && privacyAvailable, { useWiki, useTools: true, toolsOff, mcpOff });
    setText(""); setAttach([]);
  };
  /* Edit: the message leaves the queue and comes back into this box, with
     its files, to be changed and sent again. */
  const editQueued = async q => {
    if (!onQueue || !(await onQueue.remove(q.id))) return;
    const d = q.draft || { text: q.text, files: [] };
    setText(cur => [cur.trim(), d.text || ""].filter(Boolean).join("\n\n"));
    setAttach(fs => [...fs, ...(d.files || []).filter(f => f.path).map(f => ({
      id: Math.random().toString(36).slice(2), name: f.name, size: f.size, path: f.path, text: f.text || "", truncated: f.truncated,
    }))]);
    requestAnimationFrame(() => taRef.current && taRef.current.focus());
  };
  const waiting = (queue && queue.items) || [];

  return (
    engineReady === false ? (
      <div className="composer-wrap">
        <div className="agent-coming">
          ⚙ {tb("agent.engineMissing")}
        </div>
      </div>
    ) : (
      <div className="composer-wrap">
        {modelHint && <ModelHint h={modelHint} act={onModelHint} />}
        {openAsks.length > 0 && (
          <div className="agent-asks">
            {openAsks.map(a => a.kind === "routine" ? (
              <RoutineAskCard key={a.id} a={a} onAnswer={body => onAnswerAsk && onAnswerAsk(a.id, body)} />
            ) : a.kind === "email" ? (
              <EmailAskCard key={a.id} a={a} agentId={agentId} agentName={agentName} onAnswer={body => onAnswerAsk && onAnswerAsk(a.id, body)} />
            ) : a.kind === "approve" ? (
              <div className="ask-card approve" key={a.id}>
                <div className="ask-head"><span className="ask-ic">?</span> <span>{tb("ask.approveTitle", { tool: a.tool, server: a.server })}</span></div>
                {a.account && <div className="ask-account">{t("ask.approveAccount", { account: a.account })}</div>}
                {a.args && a.args !== "{}" && <pre className="ask-args">{a.args}</pre>}
                <div className="ask-acts">
                  <button className="btn primary" onClick={() => onAnswerAsk && onAnswerAsk(a.id, { approved: true })}>{t("ask.allow")}</button>
                  <button className="btn" onClick={() => onAnswerAsk && onAnswerAsk(a.id, { approved: false })}>{t("ask.decline")}</button>
                  <span className="ask-time">{t("ask.until", { time: L.fmtTime ? L.fmtTime(a.expires) : new Date(a.expires).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) })}</span>
                </div>
              </div>
            ) : (
              <div className="ask-card" key={a.id}>
                <div className="ask-head"><span className="ask-ic">?</span> <span>{t("ask.questionTitle")}</span></div>
                <div className="ask-q">{a.question}</div>
                {(a.options || []).length > 0 && (
                  <div className="ask-opts">
                    {a.options.map((o, i) => <button key={i} className="ask-opt" onClick={() => onAnswerAsk && onAnswerAsk(a.id, { text: o })}>{o}</button>)}
                  </div>
                )}
                <div className="ask-hint">{(a.options || []).length ? t("ask.typeHintOptions") : t("ask.typeHint")}</div>
              </div>
            ))}
          </div>
        )}
        {waiting.length > 0 && (
          <div className={"agent-queue" + (queue.held ? " held" : "")}>
            <div className="aq-head">
              <span className="aq-title">{t("queue.title", { n: waiting.length })}</span>
              {queue.held && <span className="aq-held">{queue.error ? t("queue.heldError", { error: queue.error }) : t("queue.held")}</span>}
              <span className="aq-acts">
                {queue.held && <button className="aq-btn primary" onClick={() => onQueue && onQueue.resume()}>{t("queue.resume")}</button>}
                {waiting.some(q => q.mine) && <button className="aq-btn" title={t("queue.clearHint")} onClick={() => onQueue && onQueue.clear()}>{t("queue.clear")}</button>}
              </span>
            </div>
            {waiting.map((q, i) => q.mine ? (
              <div className="aq-row" key={q.id}>
                <span className="aq-n">{i + 1}</span>
                <span className="aq-text" title={q.text}>
                  {q.scheduled && <span className="aq-tag">⏰ {q.routineTitle || t("queue.routine")}</span>}
                  {q.text || (q.attachments || []).map(f => f.name).join(", ")}
                </span>
                {(q.attachments || []).length > 0 && <span className="aq-files"><ClipIcon /> {t("queue.files", { n: q.attachments.length })}</span>}
                <span className="aq-acts">
                  <button className="aq-btn" title={t("queue.sendNowHint")} onClick={() => onQueue && onQueue.now(q.id)}>{t("queue.sendNow")}</button>
                  {!q.scheduled && <button className="aq-btn" onClick={() => editQueued(q)}>{t("queue.edit")}</button>}
                  <button className="aq-x" title={t("queue.remove")} onClick={() => onQueue && onQueue.remove(q.id)}>✕</button>
                </span>
              </div>
            ) : (
              <div className="aq-row other" key={q.id}>
                <span className="aq-n">{i + 1}</span>
                <span className="aq-text">{t("queue.someoneElse")}</span>
              </div>
            ))}
          </div>
        )}
        <div className={"composer agent-composer " + (drag ? "drag" : "")}
             onDrop={onDrop} onDragOver={e => e.preventDefault()}
             onDragEnter={onDragEnter} onDragLeave={onDragLeave}>
          {attach.length > 0 && (
            <div className="attach-row">
              {attach.map(f => (
                <div key={f.id} className={"chip " + (f.error ? "bin " : "") + (f.busy ? "loading" : "")}
                     title={f.error ? f.error : f.busy ? t("agent.uploading") : (f.truncated ? f.name + " (text truncated for context)" : f.name)}>
                  <span className="chip-ic" />
                  <span className="chip-name">{f.name}</span>
                  <span className="chip-sz">{f.busy ? "uploading…" : f.error ? "failed" : fmtBytes(f.size)}</span>
                  <button className="chip-x" onClick={() => setAttach(fs => fs.filter(x => x.id !== f.id))}>✕</button>
                </div>
              ))}
            </div>
          )}
          <div className="composer-row">
            <button type="button" className="attach-btn" title={t("agent.attachHint")} onClick={openPicker}><ClipIcon /></button>
            <input ref={fileInput} type="file" multiple hidden onChange={e => { addFiles(e.target.files); e.target.value = ""; }} />
            <textarea ref={taRef} rows={1} value={text}
                      placeholder={drag ? t("agent.dropFiles") : question ? t("ask.placeholder") : busy ? t("queue.placeholder") : (placeholder || t("agent.placeholder"))}
                      onChange={e => setText(e.target.value)}
                      onPaste={onPaste}
                      onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); submit(); } }} />
            {voiceAvailable && (
              <button className={"mic-btn " + (recording ? "rec " : "") + (transcribing ? "busy" : "")}
                      onClick={toggleMic} disabled={transcribing}
                      title={recording ? t("voice.stopAndTranscribe") : transcribing ? t("voice.transcribing") : voiceTitle()}>
                <MicIcon />
              </button>
            )}
            {busy && (text.trim() || attach.length > 0) && (
              <button className={"send queue-send" + (question && !attach.length ? " answer" : "")} onClick={submit} disabled={converting || recording || transcribing}
                      title={converting ? t("agent.uploadingAll") : question && !attach.length ? t("ask.send") : t("queue.add")}><SendIcon /></button>
            )}
            {busy
              ? <button className="stop" onClick={onStop} title={t("common.stop")}><span className="sq" /></button>
              : <button className="send" onClick={submit} disabled={converting || recording || transcribing || (!text.trim() && !attach.length)} title={converting ? t("agent.uploadingAll") : "Send"}><SendIcon /></button>}
          </div>
        </div>
        <div className="composer-foot">
          <div className="foot-left">
            {wikiAvailable && (
              <button className={"tool-toggle " + (useWiki ? "on" : "")} onClick={() => setUseWiki(v => !v)}
                      title={t("agent.wikiHint")}>
                <BookIcon /> {t("agent.useWiki")}
              </button>
            )}
            <AgentToolsMenu agentId={agentId} workspaceId={workspaceId} toolsOff={toolsOff} mcpOff={mcpOff} setToolsOff={setToolsOff} setMcpOff={setMcpOff} />
            {privacyAvailable && (
              <button className={"tool-toggle " + (priv ? "on" : "")} onClick={() => setPriv(p => !p)}
                      title={t("agent.privacyHint")}>
                <ShieldIcon /> {t("agent.hidePersonal")}
              </button>
            )}
            {recording
              ? <span className="voice-status rec"><span className="rec-dot" /> {t("voice.recording")}</span>
              : transcribing
              ? <span className="voice-status"><span className="rec-dot busy" /> {t("voice.transcribing")}</span>
              : voiceErr
              ? <span className="voice-status err">{voiceErr}</span>
              : <span className="hint">{tb(hint || "agent.composerHint")}</span>}
          </div>
        </div>
      </div>
    )
  );
}

/* ========================================================
   APPS — modular workspace tabs (dashboards, CRMs, notes, …)
   A sandboxed iframe renders the app document in a CENTRAL pane while the
   linked agent's chat docks on the right. The iframe can only talk through
   the postMessage SDK below: persisted versioned state + named data
   connectors — no cookies, no origin, no direct API access.
   ======================================================== */
const APP_SDK =
  '<script>window.IndieApp=(function(){var seq=0,pend={},scbs=[];' +
  'window.addEventListener("message",function(e){var d=e.data;if(!d||!d.__indieapp)return;' +
  'if(d.event==="state"){for(var i=0;i<scbs.length;i++){try{scbs[i](d.state,d.v)}catch(x){}}return}' +
  /* the host's light/dark switch: on <html data-theme>, where app CSS reads it,
     in window.__indieTheme, and as an indie:theme event for an app with its
     own picker (Wiki, Brain), whose explicit choice can then re-assert itself */
  'if(d.event==="theme"){var th=d.theme==="dark"?"dark":"light";window.__indieTheme=th;' +
  'document.documentElement.setAttribute("data-theme",th);' +
  'try{window.dispatchEvent(new CustomEvent("indie:theme",{detail:{theme:th}}))}catch(x){}return}' +
  'if(d.toolCall)return;' +
  'var p=pend[d.id];if(!p)return;delete pend[d.id];d.error?p[1](new Error(d.error)):p[0](d.result)});' +
  'function call(m,params){return new Promise(function(res,rej){var id=++seq;pend[id]=[res,rej];' +
  'parent.postMessage({__indieapp:true,id:id,method:m,params:params||{}},"*")})}' +
  'return{getState:function(){return call("get_state")},' +
  'setState:function(patch,replace){return call("set_state",{patch:patch,replace:!!replace})},' +
  'fetch:function(connector,params){return call("fetch",{connector:connector,params:params})},' +
  'ask:function(text){return call("ask",{text:text})},' +
  'onState:function(cb){scbs.push(cb)}}})();' +
  /* WebMCP (navigator.modelContext) polyfill: apps register tools the standard
     way; the host relays agent tool-calls into execute() and results back.
     Defers to a native implementation if the browser ever ships one. */
  '(function(){var reg={},order=[];' +
  'function meta(){return order.map(function(n){var t=reg[n];return{name:t.name,description:t.description||"",inputSchema:t.inputSchema||{type:"object",properties:{}}}})}' +
  'function announce(){try{parent.postMessage({__indieapp:true,event:"tools",tools:meta()},"*")}catch(e){}}' +
  'function add(t){if(!t||typeof t.name!=="string"||!t.name.trim()||typeof t.execute!=="function")return false;' +
  'if(!reg[t.name])order.push(t.name);reg[t.name]=t;return true}' +
  'var native=navigator.modelContext;' +
  'var api={provideContext:function(ctx){reg={};order=[];(((ctx||{}).tools)||[]).forEach(add);announce();' +
  'if(native&&native.provideContext){try{native.provideContext(ctx)}catch(e){}}},' +
  'registerTool:function(t){if(add(t))announce();' +
  'if(native&&native.registerTool){try{native.registerTool(t)}catch(e){}}' +
  'return{unregister:function(){delete reg[t.name];order=order.filter(function(n){return n!==t.name});announce()}}}};' +
  'try{Object.defineProperty(navigator,"modelContext",{value:api,configurable:true})}catch(e){navigator.modelContext=api}' +
  'window.addEventListener("message",function(e){var d=e.data;if(!d||!d.__indieapp||!d.toolCall)return;' +
  'var tc=d.toolCall,t=reg[tc.name];' +
  'function reply(result,error){try{parent.postMessage({__indieapp:true,toolResult:{id:tc.id,result:result,error:error}},"*")}catch(x){}}' +
  'if(!t)return reply(null,"Unknown tool: "+tc.name);' +
  'Promise.resolve().then(function(){return t.execute(tc.input||{})}).then(function(out){' +
  'if(out==null)out={content:[{type:"text",text:"ok"}]};' +
  'if(typeof out==="string")out={content:[{type:"text",text:out}]};' +
  'reply(out)},function(err){reply(null,String((err&&err.message)||err))})});' +
  '})();</' + 'script>';
/* The same thin scrollbar as the host's (indie.css), in a neutral grey that
   reads on an app's light and dark backgrounds alike. */
const APP_SCROLLBAR = '<style>*::-webkit-scrollbar{width:8px;height:8px}' +
  '*::-webkit-scrollbar-track,*::-webkit-scrollbar-corner{background:transparent}' +
  '*::-webkit-scrollbar-thumb{background:rgba(128,128,128,.4);border-radius:8px}*::-webkit-scrollbar-button{display:none}' +
  '@supports (-moz-appearance:none){*{scrollbar-width:thin;scrollbar-color:rgba(128,128,128,.4) transparent}}</style>';
/* Inject the SDK inside <head> so a full document keeps its doctype (and
   standards mode); fall back to prepending for bare fragments. */
function appSrcDoc(html, theme) {
  const h = String(html || "");
  /* the theme first, so the app's own CSS has it before its first paint */
  const th = theme === "dark" ? "dark" : "light";
  /* The interface language too: apps write their labels in English and German
     and show the one <html lang> names. A switch re-mounts the whole tree
     (Root), so the frame reloads with the new value and needs no message. */
  const lg = L.lang() === "de" ? "de" : "en";
  /* the platform's scrollbar inside apps too, as a default: it comes first in
     the head, so an app's own scrollbar rules still win */
  const sdk = APP_SCROLLBAR + '<script>window.__indieTheme="' + th + '";document.documentElement.setAttribute("data-theme","' + th + '");' +
    'window.__indieLang="' + lg + '";document.documentElement.setAttribute("lang","' + lg + '")</' + 'script>' + APP_SDK;
  if (/<head[^>]*>/i.test(h)) return h.replace(/<head[^>]*>/i, m => m + sdk);
  return sdk + h;
}

/* Personal <-> shared, for admins. The consequences live IN the panel rather
   than in a tooltip: both of them are invisible at the moment of clicking and
   expensive to find out afterwards, and one of them ("everyone can now read
   what is saved in here") is somebody's private data. */
/* Everyone sees how an app is shared; admins can change it. Members used to
   see nothing at all, so "how do I share this with colleagues?" had no
   answer on screen. */
function AppScopeControl({ app, onSetScope, isAdmin }) {
  const [open, setOpen] = useState(false);
  const [busy, setBusy] = useState(false);
  const [warn, setWarn] = useState(null);
  const ref = useRef(null);
  const isGlobal = app.scope === "global";
  useEffect(() => {
    const h = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);
  useEffect(() => { setWarn(null); setOpen(false); }, [app.id]);
  const go = async () => {
    setBusy(true);
    try {
      const r = await onSetScope(isGlobal ? "personal" : "global");
      setWarn((r && r.warnings) || null);
      setOpen(false);
    } finally { setBusy(false); }
  };
  return (
    <div className="app-scope" ref={ref}>
      <button className={"app-scope-btn" + (isGlobal ? " on" : "")} onClick={() => setOpen(!open)}
              title={isGlobal ? t("app.globalHint") : t("app.shareHint")}>
        {isGlobal ? t("app.scopeGlobal") : t("app.share")}
      </button>
      {open && !isAdmin && (
        <div className="app-scope-panel">
          <div className="menu-cap">{t("app.scopeCap")}</div>
          <p>{tb(isGlobal ? "app.shareMemberGlobal" : "app.shareMemberPersonal")}</p>
          <div className="app-scope-actions">
            <button className="act-btn" onClick={() => setOpen(false)}>{t("common.ok")}</button>
          </div>
        </div>
      )}
      {open && isAdmin && (
        <div className="app-scope-panel">
          <div className="menu-cap">{t("app.scopeCap")}</div>
          <p>{isGlobal ? tb("app.scopeToPersonal") : tb("app.scopeToGlobal")}</p>
          <ul>
            <li>{isGlobal ? t("app.scopeDataPersonal") : t("app.scopeDataGlobal")}</li>
            <li>{isGlobal ? t("app.scopeConnPersonal") : t("app.scopeConnGlobal")}</li>
          </ul>
          <div className="app-scope-actions">
            <button className="act-btn" onClick={() => setOpen(false)}>{t("common.cancel")}</button>
            <button className="act-btn primary" disabled={busy} onClick={go}>
              {busy ? t("common.pleaseWait") : (isGlobal ? t("app.scopeMakePersonal") : t("app.scopeMakeGlobal"))}
            </button>
          </div>
        </div>
      )}
      {/* What the server found once it had the app in front of it: the actual
          connector names, which the panel above can only describe in general. */}
      {warn && warn.length > 0 && (
        <div className="app-scope-panel done">
          <div className="menu-cap">{t("app.scopeChanged")}</div>
          {warn.map((w, i) => <p key={i}>{w.text}</p>)}
          <div className="app-scope-actions">
            <button className="act-btn" onClick={() => setWarn(null)}>{t("common.ok")}</button>
          </div>
        </div>
      )}
    </div>
  );
}

function AppWorkspace({ app, busy, appStateTick, appHtmlTick, onAsk, onMenu, locked, onLock,
                        agents, dockedAgent, onLinkAgent, onNewAgent, isAdmin, onSetScope, box, workspaces, onMoveWs, routines = [], onSchedule }) {
  const [full, setFull] = useState(null);       /* { html, state, version } */
  const [err, setErr] = useState(null);
  const [frameKey, setFrameKey] = useState(0);  /* bump to reload the iframe */
  const [toolCount, setToolCount] = useState(0);
  const [agentMenu, setAgentMenu] = useState(false);
  const frameRef = useRef(null);
  const stateRef = useRef({});
  const verRef = useRef(0);
  const toolsRef = useRef([]);      /* WebMCP tools the iframe registered */
  const bridgeIdRef = useRef(null); /* live SSE bridge to the server */
  /* The app follows the light/dark switch. Its document is built from the
     html ALONE (with the theme showing at that moment, so it paints right the
     first time): rebuilt per render, a switch would change srcDoc and reload
     the app, losing whatever someone was in the middle of. Switches, and any
     reload, are pushed in as a message instead. */
  const theme = useTheme();
  const docRef = useRef({ html: null, doc: "" });
  const postTheme = () => {
    const w = frameRef.current && frameRef.current.contentWindow;
    if (w) { try { w.postMessage({ __indieapp: true, event: "theme", theme: currentTheme() }, "*"); } catch {} }
  };
  useEffect(() => { postTheme(); }, [theme]);
  if (full && docRef.current.html !== full.html) docRef.current = { html: full.html, doc: appSrcDoc(full.html, theme) };

  /* Load the document (fresh iframe). Re-runs when the agent rewrites the
     html (appHtmlTick) or the user hits reload. */
  useEffect(() => {
    let gone = false;
    setErr(null);
    /* fresh document -> stale tool registrations die with it */
    toolsRef.current = []; setToolCount(0);
    if (bridgeIdRef.current) L.AppsAPI.postTools(app.id, bridgeIdRef.current, []).catch(() => {});
    L.AppsAPI.get(app.id)
      .then(f => { if (gone) return; stateRef.current = f.state || {}; verRef.current = f.version || 0; setFull(f); })
      .catch(e => { if (!gone) setErr((e && e.message) || t("app.loadFailed")); });
    return () => { gone = true; };
  }, [app.id, frameKey, appHtmlTick]);
  useEffect(() => { setFull(null); }, [app.id]);   /* don't show the old app while switching */

  /* WebMCP bridge: a long-lived channel the server uses to run this app's
     registered tools when the agent calls them (app_call). We relay the call
     into the sandboxed iframe and post execute()'s result back. */
  useEffect(() => {
    const ctrl = new AbortController();
    L.bridgeApp(app.id, {
      onOpen: id => {
        bridgeIdRef.current = id;
        if (toolsRef.current.length) L.AppsAPI.postTools(app.id, id, toolsRef.current).catch(() => {});
      },
      onCall: evt => {
        const w = frameRef.current && frameRef.current.contentWindow;
        if (!w) { L.AppsAPI.postCallResult(app.id, evt.callId, null, t("app.notRendered")).catch(() => {}); return; }
        try { w.postMessage({ __indieapp: true, toolCall: { id: evt.callId, name: evt.tool, input: evt.input || {} } }, "*"); }
        catch { L.AppsAPI.postCallResult(app.id, evt.callId, null, t("app.frameUnreachable")).catch(() => {}); }
      },
    }, ctrl.signal);
    return () => { ctrl.abort(); bridgeIdRef.current = null; };
  }, [app.id]);

  const postState = () => {
    const w = frameRef.current && frameRef.current.contentWindow;
    if (w) { try { w.postMessage({ __indieapp: true, event: "state", state: stateRef.current, v: verRef.current }, "*"); } catch {} }
  };

  /* Live state: the agent writes state server-side (app_state) and the
     server's background refreshers keep updating it on their own, so poll
     the cheap versioned endpoint — fast while the agent runs, gently while
     idle — and push changes into the iframe. */
  useEffect(() => {
    if (!full) return;
    let stop = false;
    const check = async () => {
      try {
        const r = await L.AppsAPI.state(app.id, verRef.current);
        if (!stop && r && !r.unchanged) { stateRef.current = r.state; verRef.current = r.v; postState(); }
      } catch {}
    };
    check();
    const t = setInterval(check, busy ? 2500 : 25000);
    return () => { stop = true; clearInterval(t); };
  }, [busy, appStateTick, full]);

  /* postMessage bridge — the ONLY door out of the sandbox. Validates the
     source window and answers with the user's own auth (cookie/token stays
     out of the iframe). */
  useEffect(() => {
    const onMsg = async e => {
      const w = frameRef.current && frameRef.current.contentWindow;
      if (!w || e.source !== w) return;
      const d = e.data;
      if (!d || !d.__indieapp) return;
      /* WebMCP: the iframe announced its registered tools */
      if (d.event === "tools") {
        toolsRef.current = Array.isArray(d.tools) ? d.tools : [];
        setToolCount(toolsRef.current.length);
        if (bridgeIdRef.current) L.AppsAPI.postTools(app.id, bridgeIdRef.current, toolsRef.current).catch(() => {});
        return;
      }
      /* WebMCP: execute() finished — relay the result to the waiting agent */
      if (d.toolResult) {
        L.AppsAPI.postCallResult(app.id, d.toolResult.id, d.toolResult.result, d.toolResult.error).catch(() => {});
        return;
      }
      if (!d.method) return;
      const reply = (result, error) => { try { w.postMessage({ __indieapp: true, id: d.id, result, error }, "*"); } catch {} };
      try {
        if (d.method === "get_state") reply(stateRef.current);
        else if (d.method === "set_state") {
          const r = await L.AppsAPI.setState(app.id, (d.params && d.params.patch) || {}, !!(d.params && d.params.replace));
          stateRef.current = r.state; verRef.current = r.v;
          reply(r.state); postState();
        }
        else if (d.method === "fetch") reply(await L.AppsAPI.connector(d.params && d.params.connector, d.params && d.params.params, app.id));
        else if (d.method === "ask") {
          if (onAsk) { onAsk(String((d.params && d.params.text) || "").slice(0, 4000)); reply({ ok: true }); }
          else reply(null, t("app.noAgentLinked"));
        }
        else reply(null, "Unknown method: " + d.method);
      } catch (ex) { reply(null, (ex && ex.message) || String(ex)); }
    };
    window.addEventListener("message", onMsg);
    return () => window.removeEventListener("message", onMsg);
  }, [app.id, onAsk]);

  return (
    <div className="appws-stage">
      <div className="topbar">
        <div style={{ display: "flex", alignItems: "center", minWidth: 0 }}>
          <button className="menu-btn" onClick={onMenu}><MenuIcon /></button>
          <div className="topbar-title">
            <span className="tt-kind">App</span>
            <span className="tt-name" title={appName(app)}>{(app.icon ? app.icon + " " : "") + appName(app)}</span>
          </div>
          {toolCount > 0 && (
            <span className="app-tools-chip" title={t("app.toolsChipHint", { n: toolCount })}>
              ⚡ {t("app.toolsChip", { n: toolCount })}
            </span>
          )}
          {/* What keeps this app up to date: its routines, or a way to make one
              (it runs on the docked agent and writes the app's data). */}
          {onSchedule && <AppRoutineChip routines={routines} onClick={() => onSchedule(routines.length > 0)} />}
        </div>
        <div className="tools">
          <BoxBusy box={box} />
          {/* Which agent is docked beside this app — switchable, and
              disconnectable without deleting anything. */}
          <div className="app-agent-sel">
            <button className={"app-agent-btn" + (dockedAgent ? "" : " none")}
                    onClick={() => setAgentMenu(o => !o)}
                    title={dockedAgent
                      ? t("app.dockedAgentWith") + " " + agentName(dockedAgent) + ". Click to switch or disconnect."
                      : t("app.noAgentDocked")}>
              <BotIcon />
              <span className="aa-name">{dockedAgent ? agentName(dockedAgent) : t("app.noAgent")}</span>
              <span className="aa-caret">▾</span>
            </button>
            {agentMenu && (<>
              <div className="new-scrim" onClick={() => setAgentMenu(false)} />
              <div className="app-agent-menu">
                <div className="aam-head mono">{t("app.dockedAgent")}</div>
                <div className="aam-list">
                  {(agents || []).map(a => (
                    <button key={a.id} className={a.id === app.agentId ? "on" : ""}
                            onClick={() => { setAgentMenu(false); if (a.id !== app.agentId) onLinkAgent(a.id); }}>
                      <BotIcon /> <span className="aa-name">{agentName(a) || "Agent"}</span>
                      {a.scope === "global" && <span className="app-scope">G</span>}
                    </button>
                  ))}
                </div>
                <button className="aam-new" onClick={() => { setAgentMenu(false); onNewAgent(); }}>
                  <PlusIcon /> {t("app.newAgentForApp")}
                </button>
                {app.agentId && (
                  <button className="aam-off" onClick={() => { setAgentMenu(false); onLinkAgent(null); }}>
                    ⊘ {t("app.disconnectAgent")}
                  </button>
                )}
              </div>
            </>)}
          </div>
          <AppScopeControl app={app} isAdmin={isAdmin} onSetScope={onSetScope} />
          {onMoveWs && app.template !== "wiki" && <MoveToWorkspace item={app} workspaces={workspaces} isAdmin={isAdmin} onMove={ws => onMoveWs(app.id, ws)} />}
          <button className={"app-lock" + (locked ? " on" : "")} onClick={() => onLock(!locked)}
                  title={locked ? t("app.lockedHint") : t("app.unlockedHint")}>
            <LockIcon open={!locked} /> {locked ? t("app.locked") : t("app.unlocked")}
          </button>
          {/* labelled: icons alone were "I don't know what these buttons are" */}
          <a className="icon-btn labelled" title={t("nav.guide")} href={guideHref()} target="_blank" rel="noopener"><HelpIcon /> <span className="btn-label">{t("nav.guideShort")}</span></a>
          <button className="icon-btn labelled" title={t("app.reload")} onClick={() => setFrameKey(k => k + 1)}><RefreshIcon /> <span className="btn-label">{t("app.reloadShort")}</span></button>
        </div>
      </div>
      {err && <div className="appws-note">{err}</div>}
      {!full && !err && <div className="appws-note mono">{t("common.loading")}</div>}
      {full && (
        <iframe key={frameKey + ":" + appHtmlTick} ref={frameRef} className="appws-frame" title={appName(app)}
                /* allow-downloads: an app may hand the user a file it built from
                   its own data (a CSV export). allow-modals: embedded tools
                   guard destructive actions with confirm(), which a sandbox
                   without the flag makes return false SILENTLY — the button
                   looks dead. Still no allow-same-origin, so the document
                   keeps its opaque origin. */
                sandbox="allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads allow-modals"
                srcDoc={docRef.current.doc} onLoad={postTheme} />
      )}
    </div>
  );
}

/* The routines that keep an app up to date, in its top bar: when the next
   run is, or that it is paused; with none, the way to make one. */
function AppRoutineChip({ routines, onClick }) {
  const on = routines.filter(r => r.enabled);
  const next = on.map(r => r.nextRun).filter(Boolean).sort((x, y) => x - y)[0];
  const when = ms => {
    const d = new Date(ms), today = new Date();
    return d.toDateString() === today.toDateString() ? L.fmtTime(ms) : d.toLocaleDateString(L.lang(), { weekday: "short" }) + " " + L.fmtTime(ms);
  };
  /* short, because the top bar is: the app's name must keep its room; what
     runs when is in the tooltip */
  const label = !routines.length ? t("routine.schedule")
    : !on.length ? t("app.routinePaused")
    : (routines.length > 1 ? t("app.routinesChip", { n: routines.length }) + " · " : "") + (next ? t("app.routineNext", { time: when(next) }) : cronToText(on[0].cron));
  const tip = routines.map(r => r.title + ": " + cronToText(r.cron) + (r.enabled ? "" : " (" + t("app.routinePaused") + ")")).join("\n");
  return (
    <button className={"app-routine-chip" + (routines.length ? "" : " none") + (routines.length && !on.length ? " off" : "")}
            onClick={onClick} title={routines.length ? tip + "\n\n" + t("app.routineChipHint") : t("app.scheduleHint")}>
      <ClockIcon /> <span>{label}</span>
    </button>
  );
}

/* Right-pane placeholder until an agent is linked to the app. A new app gets
   its own agent when it is created, so this shows for apps that have none yet
   (a shared app someone else made, a disconnected one). It says WHY an app
   needs an agent and leads with the usual answer: people faced with a list of
   unrelated agents did not know whether to pick one or make one. */
function AppAgentPicker({ agents, onPick, onNew }) {
  return (
    <div className="app-agent-pick">
      <div className="agent-empty-ic"><BotIcon /></div>
      <h3>{t("app.pickAgent")}</h3>
      <p>{t("app.pickAgentDesc")}</p>
      <button className="app-pick-btn new" onClick={onNew}>
        <PlusIcon /> {t("app.newAgentForApp")} <span className="app-pick-rec">{t("common.recommended")}</span>
      </button>
      {(agents || []).length > 0 && <div className="app-pick-or mono">{t("app.pickExisting")}</div>}
      {(agents || []).map(a => (
        <button key={a.id} className="app-pick-btn" onClick={() => onPick(a.id)}><BotIcon /> {agentName(a)}</button>
      ))}
    </div>
  );
}

/* Destructive-action confirm. Deleting an agent or an app throws away real
   state — a persistent workspace volume, running services, a definition other
   people share — so the consequence is spelled out rather than left to a
   generic "are you sure". Escape and the scrim both cancel; the confirm button
   takes focus but is never triggered by a stray Enter on the page. */
function ConfirmModal({ title, body, confirmLabel, onConfirm, onClose }) {
  useEffect(() => {
    const onKey = e => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);
  return (
    <div className="modal-scrim" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal confirm-modal">
        <div className="modal-head">
          <h2><span className="eb">{t("common.confirm")}</span>{title}</h2>
          <button className="modal-x" onClick={onClose}>✕</button>
        </div>
        <div className="modal-body">{body}</div>
        <div className="modal-foot">
          <span style={{ flex: 1 }} />
          <button className="btn" onClick={onClose}>{t("common.cancel")}</button>
          <button className="btn danger" autoFocus onClick={onConfirm}>{confirmLabel || "Delete"}</button>
        </div>
      </div>
    </div>
  );
}

/* "New app" template chooser. The list comes from the SERVER (/api/config), so
   the templates a deployment ships in its config appear here with no client
   change — and a module that is switched off takes its templates with it.
   The built-ins below are only the pre-config fallback. */
const appTemplateFallback = () => [
  { key: "finance", icon: "📈", name: "Markets", description: t("tpl.finance") },
  { key: "notes",   icon: "🗒️", name: "Notes", description: t("tpl.notes") },
  { key: "blank",   icon: "▦",  name: "New app", description: t("tpl.blank") },
];
/* The server writes the blurb, so a config-supplied template keeps the wording
   its operator chose. The five built-ins have a catalogue key and use it. */
const BUILTIN_TPL = ["finance", "notes", "wiki", "brain", "my-wiki", "my-brain", "blank"];
const tplBlurb = tp => (BUILTIN_TPL.includes(tp.key) ? t("tpl." + tp.key) : "") || tp.description || tp.desc;
/* Built-in names in the reader's language. The server stores the English
   default; it is translated on display for as long as nobody renamed it, so a
   later language switch still works both ways. A deployment's own templates
   keep the name their operator wrote. */
const TPL_DEFAULT_NAME = { finance: "Markets", notes: "Notes", wiki: "Wiki", brain: "Brain Overview", blank: "New app" };
/* An app or template that names itself per language (its html's
   <meta name="indie-app-name" lang=...>, read by the server into `names`)
   is shown in the reader's language first. */
const ownName = x => (x && x.names && x.names[L.lang()]) || "";
const tplName = tp => ownName(tp) || (TPL_DEFAULT_NAME[tp.key] && t("tplName." + tp.key)) || tp.name;
const appName = a => ownName(a) || ((a && a.template && TPL_DEFAULT_NAME[a.template] === a.name) ? t("tplName." + a.template) : ((a && a.name) || ""));
/* The same for the placeholder names agents get until their first turn
   renames them: "New agent", and "<app> agent" for one made with an app. */
const agentName = a => {
  const n = (a && a.name) || "";
  if (n === "New agent") return t("sidebar.newAgent");
  const m = /^(.+) agent$/.exec(n);
  const key = m && Object.keys(TPL_DEFAULT_NAME).find(k => TPL_DEFAULT_NAME[k] === m[1]);
  return key ? t("app.agentFor", { name: t("tplName." + key) }) : n;
};
/* The microphone says where a recording is transcribed: on the deployment's
   own speech service, or (the fallback) by Google. */
const voiceTitle = () => (L.speechEngine() === "local" ? t("voice.inputLocal") : t("voice.inputGoogle"));
/* The "?" opens the getting-started guide in the reader's language. */
const guideHref = () => "/help/start." + (L.lang() === "de" ? "de" : "en") + ".html";
/* The shared wiki's single writer is infrastructure: admins see it, members
   do not, since there is nothing in it for them to drive. */
const isLibrarianAgent = a => !!a && a.scope === "global" && a.wiki === "write";
/* One line saying what an agent is for. The Librarian's is the platform's own,
   so it is written in the reader's language rather than stored. */
const tplNameOf = n => { const k = Object.keys(TPL_DEFAULT_NAME).find(x => TPL_DEFAULT_NAME[x] === n); return k ? t("tplName." + k) : n; };
const PLATFORM_DESC = [
  [/^Builds and changes the app “(.+)”\.$/, m => t("agent.forAppDesc", { name: tplNameOf(m[1]) })],
  [/^Runs the routine “(.+)”\.$/,          m => t("routine.agentDesc", { title: m[1] })],
];
/* The descriptions the platform writes itself are stored in this one English
   form and read in the reader's language, as built-in names are; a person's
   own words are shown as written. */
const platformDesc = {
  forApp: name => "Builds and changes the app “" + (name || "App") + "”.",
  routine: title => "Runs the routine “" + title + "”.",
};
const agentDesc = a => {
  if (isLibrarianAgent(a)) return t("agent.librarianDesc");
  const d = (a && a.description) || "";
  for (const [re, fmt] of PLATFORM_DESC) { const m = re.exec(d); if (m) return fmt(m); }
  return d;
};
function AppPickerModal({ onCreate, onClose, creating, isAdmin }) {
  const [global, setGlobal] = useState(false);
  /* blank is New app itself, one click away in the sidebar */
  const templates = (L.appTemplateList() || appTemplateFallback()).filter(tp => tp.key !== "blank");
  return (
    <div className="modal-scrim" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal app-picker">
        <div className="modal-head">
          <div><span className="eb">{t("sidebar.apps")}</span><h2>{t("sidebar.newAppFromTemplate")}</h2></div>
          <button className="modal-x" onClick={onClose}>✕</button>
        </div>
        <div className="modal-body">
          <p className="app-picker-intro">{tb("app.pickerIntro")}</p>
          {templates.map(tp => (
            <button key={tp.key} className="app-tpl" disabled={!!creating} onClick={() => onCreate(tp.key, global)}>
              <span className="app-tpl-ic">{tp.icon}</span>
              <span className="app-tpl-tx">
                <b>{tplName(tp)}</b>
                <span>{tplBlurb(tp)}</span>
              </span>
              {creating === tp.key && <span className="app-tpl-busy">{t("app.creating")}</span>}
            </button>
          ))}
          {isAdmin && (
            <label className="app-global-opt">
              <input type="checkbox" checked={global} onChange={e => setGlobal(e.target.checked)} />
              {t("app.globalOpt")}
            </label>
          )}
        </div>
      </div>
    </div>
  );
}

/* ========================================================
   AGENT BUNDLES (server.js, bundles.js): a ready-made agent for one job.
   Adding one makes an agent with its role, its app, its routines (off until
   switched on), its skills and starting files; the setup card in the agent's
   view then walks through what it needs: connections, a few questions, the
   schedules, a first thing to ask. Everything it makes is the person's own.
   ======================================================== */
/* a bundle's text in the reader's language: {en, de} or a plain string */
const bl = v => (v == null ? "" : typeof v === "string" ? v : (v[L.lang()] || v.en || Object.values(v)[0] || ""));
const bundleAppName = b => (b.app && b.app.names && (b.app.names[L.lang()] || b.app.names.en)) || bl(b.name);
/* the start page: a row of ready-made agents under the message box */
function BundleStartRow({ onOpen }) {
  const [list, setList] = useState(null);
  useEffect(() => { L.BundlesAPI.list().then(d => setList((d.bundles || []).filter(b => b.offered))).catch(() => setList([])); }, []);
  if (!list || !list.length) return null;
  return (
    <div className="bundle-start">
      <div className="eyebrow">{t("bundle.startEyebrow")}</div>
      <div className="bundle-start-row">
        {list.slice(0, 4).map(b => (
          <button key={b.key} className="bundle-pill" title={bl(b.summary)} onClick={() => onOpen(b.key)}>
            <span className="bundle-pill-ic">{b.icon}</span><span className="bundle-pill-name">{bl(b.name)}</span>
          </button>
        ))}
        <button className="bundle-pill more" onClick={() => onOpen(null)}>{t("bundle.all")}</button>
      </div>
    </div>
  );
}
/* What one bundle brings, as a short line under its name in the catalog. */
function bundleFacts(b) {
  const parts = [t("bundle.factAgent")];
  if (b.app) parts.push(t("bundle.factApp"));
  if (b.routines.length) parts.push(t("bundle.factRoutines", { n: b.routines.length }));
  const req = (b.needs || []).filter(n => n.required).map(n => t("bundle.need." + n.kind));
  if (req.length) parts.push(t("bundle.factNeeds", { what: req.join(", ") }));
  return parts.join(" · ");
}
/* The catalog, and one bundle's sheet: what you get, what it needs, what it does on its own. */
function BundleCatalog({ initial, onClose, onAdded, isAdmin, ws }) {
  const [list, setList] = useState(null);
  const [edition, setEdition] = useState(null);
  const [err, setErr] = useState(null);
  const [open, setOpen] = useState(initial || null);
  useEscape(onClose);
  useEffect(() => { L.BundlesAPI.list().then(d => { setList(d.bundles || []); setEdition(d.edition || null); }).catch(e => setErr((e && e.message) || t("err.loadFailed"))); }, []);
  const cur = open && list ? list.find(b => b.key === open) : null;
  const shown = (list || []).filter(b => b.offered || isAdmin);
  /* an edition's own agents first, under its heading (the server already sorts them first) */
  const ours = edition ? shown.filter(b => b.edition) : [], rest = shown.filter(b => !ours.includes(b));
  const card = b => (
    <button key={b.key} className="bundle-card" onClick={() => setOpen(b.key)}>
      <span className="bundle-card-ic">{b.icon}</span>
      <span className="bundle-card-tx">
        <b>{bl(b.name)}{!b.offered && <span className="conn-chip">{t("bundle.hidden")}</span>}{b.added > 0 && <span className="conn-chip on">{t("bundle.added")}</span>}</b>
        <span>{bl(b.summary)}</span>
        <span className="bundle-card-facts">{bundleFacts(b)}</span>
      </span>
    </button>
  );
  return (
    <div className="modal-scrim" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal bundle-modal" role="dialog" aria-label={t("bundle.catalogTitle")}>
        <div className="modal-head">
          <div><span className="eb">{t("bundle.eyebrow")}</span><h2>{cur ? <><span className="bundle-h-ic">{cur.icon}</span>{bl(cur.name)}</> : t("bundle.catalogTitle")}</h2></div>
          <button className="modal-x" onClick={onClose} aria-label={t("common.close")}>✕</button>
        </div>
        {cur
          ? <BundleSheet b={cur} isAdmin={isAdmin} ws={ws} onBack={() => setOpen(null)} onAdded={onAdded} />
          : (
            <div className="modal-body">
              <p className="app-picker-intro">{t("bundle.catalogIntro")}</p>
              {err && <div className="set-msg bad" role="alert">{err}</div>}
              {!list && !err && <div className="bundle-loading">{t("common.loading")}</div>}
              {list && !shown.length && <div className="bundle-loading">{t("bundle.none")}</div>}
              {ours.length > 0 && <div className="bundle-group">{bl(edition.audience)}</div>}
              {ours.map(card)}
              {ours.length > 0 && rest.length > 0 && <div className="bundle-group">{t("bundle.more")}</div>}
              {rest.map(card)}
            </div>
          )}
      </div>
    </div>
  );
}
function BundleSheet({ b, isAdmin, ws, onBack, onAdded }) {
  const [scope, setScope] = useState("me");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(null);
  /* everyone's agent lives in General or a shared workspace */
  const canEveryone = isAdmin && (!ws || ws.scope === "global");
  const add = async () => {
    setBusy(true); setErr(null);
    try {
      const r = await L.BundlesAPI.install(b.key, { scope: canEveryone ? scope : "me", workspaceId: ws ? ws.id : null, lang: L.lang(), tzOffset: new Date().getTimezoneOffset() });
      onAdded(r);
    } catch (e) { setErr((e && e.message) || t("bundle.addFailed")); setBusy(false); }
  };
  const needs = b.needs || [];
  return (<>
    <div className="modal-body bundle-sheet">
      <p className="bundle-desc">{bl(b.description)}</p>
      <section>
        <h3>{t("bundle.youGet")}</h3>
        <ul className="bundle-list">
          <li><span className="bundle-li-ic"><BotIcon /></span><span><b>{t("bundle.getAgent", { name: bl(b.agent.name) })}</b><span className="bundle-sub">{bl(b.agent.description)}</span></span></li>
          {b.app && <li><span className="bundle-li-ic">{b.app.icon}</span><span><b>{t("bundle.getApp", { name: bundleAppName(b) })}</b><span className="bundle-sub">{t("bundle.getAppSub")}</span></span></li>}
          {b.routines.map(r => (
            <li key={r.key}><span className="bundle-li-ic"><ClockIcon /></span><span><b>{bl(r.title)}</b> <span className="bundle-when">{cronToText(r.cron)}</span><span className="bundle-sub">{bl(r.summary)}</span></span></li>
          ))}
          {b.skills.length > 0 && <li><span className="bundle-li-ic">✦</span><span><b>{t("bundle.getSkills", { n: b.skills.length })}</b><span className="bundle-sub">{b.skills.map(k => k.name).join(", ")}</span></span></li>}
          {b.files.length > 0 && <li><span className="bundle-li-ic"><FilesIcon /></span><span><b>{t("bundle.getFiles", { n: b.files.length })}</b><span className="bundle-sub">{b.files.join(", ")}</span></span></li>}
        </ul>
      </section>
      <section>
        <h3>{t("bundle.itNeeds")}</h3>
        {needs.length ? (
          <ul className="bundle-list">
            {needs.map(n => (
              <li key={n.kind}><span className="bundle-li-ic"><ConnGlyph group={n.kind} /></span>
                <span><b>{t("bundle.need." + n.kind)}</b> <span className="bundle-when">{t("bundle.access." + n.access)}{!n.required ? " · " + t("bundle.optional") : ""}</span><span className="bundle-sub">{bl(n.why)}</span></span></li>
            ))}
          </ul>
        ) : <p className="bundle-sub">{t("bundle.needsNothing")}</p>}
      </section>
      <section>
        <h3>{t("bundle.onItsOwn")}</h3>
        <p className="bundle-sub">{t(b.routines.length ? "bundle.onItsOwnRoutines" : "bundle.onItsOwnNone")}{needs.some(n => n.kind === "mail") ? " " + t("bundle.mailCard") : ""}</p>
      </section>
      {canEveryone && (
        <section>
          <h3>{t("bundle.for")}</h3>
          <label className="bundle-radio"><input type="radio" name="bscope" checked={scope === "me"} onChange={() => setScope("me")} /> <span><b>{t("bundle.forMe")}</b><span className="bundle-sub">{t("bundle.forMeHint")}</span></span></label>
          <label className="bundle-radio"><input type="radio" name="bscope" checked={scope === "everyone"} onChange={() => setScope("everyone")} /> <span><b>{t("bundle.forEveryone")}</b><span className="bundle-sub">{t("bundle.forEveryoneHint")}</span></span></label>
        </section>
      )}
      {ws && <p className="bundle-ws">▣ {tb("bundle.inWorkspace", { name: ws.name })}</p>}
      {err && <div className="set-msg bad" role="alert">{err}</div>}
    </div>
    <div className="modal-foot bundle-foot">
      <button className="btn" onClick={onBack}>{t("bundle.back")}</button>
      <button className="btn primary" disabled={busy} onClick={add}>{busy ? t("bundle.adding") : t("bundle.add", { name: bl(b.name) })}</button>
    </div>
  </>);
}
/* An agent's bundle: what the setup card and "About this bundle" read. */
function useBundleView(agent, busy) {
  const [view, setView] = useState(null);
  const id = agent && agent.bundle ? agent.id : null;
  const load = () => { if (!id) { setView(null); return Promise.resolve(); } return L.BundlesAPI.ofAgent(id).then(setView).catch(() => setView(null)); };
  /* again when a turn ends: the first thing asked is a step */
  useEffect(() => { load(); }, [id, busy]);
  return [view, load, setView];
}
/* The setup card above the message box: what the bundle needs, step by step. */
function BundleSetupCard({ agent, view, reload, setView, onConnect, onTry, onAbout, onAppData }) {
  const [open, setOpen] = useState(null);
  const [ans, setAns] = useState(view.answers || {});
  const [busy, setBusy] = useState(null);
  const [err, setErr] = useState(null);
  useEffect(() => { setAns(view.answers || {}); }, [view.installId]);
  const steps = ["connect", "questions", "schedules", "try"].filter(k => k !== "questions" || view.questions.length).filter(k => k !== "schedules" || view.routines.length);
  /* the first step not done is open, until the person opens another */
  const firstOpen = steps.find(k => !view.steps[k]) || null;
  const cur = open || firstOpen;
  const doneN = steps.filter(k => view.steps[k]).length;
  const run = async (key, fn) => { setBusy(key); setErr(null); try { await fn(); } catch (e) { setErr((e && e.message) || String(e)); } finally { setBusy(null); } };
  const useAccount = (n, acc) => run("acc:" + acc.id, async () => {
    await L.AgentConnectorsAPI.add(agent.id, { service: acc.service, accountId: acc.id, access: n.access });
    await reload();
  });
  /* the answers that go into the app reach an open app at once, not at its next poll */
  const saveAnswers = () => run("answers", async () => { setView(await L.BundlesAPI.update(agent.id, { answers: ans })); setOpen(null); onAppData && onAppData(); });
  const toggle = (r, on) => run("r:" + r.id, async () => {
    await L.RoutinesAPI.update(r.id, { enabled: on });
    setView(await L.BundlesAPI.update(agent.id, { setup: { schedulesSeen: true } }));
  });
  const seen = () => run("seen", async () => { setView(await L.BundlesAPI.update(agent.id, { setup: { schedulesSeen: true } })); setOpen(null); });
  const done = () => run("done", async () => { setView(await L.BundlesAPI.update(agent.id, { setup: { dismissed: true } })); });
  const example = () => run("example", async () => { await L.BundlesAPI.data(agent.id, "example"); onAppData && onAppData(); });
  const head = (k, title, sub) => (
    <button className={"bsetup-step-h" + (view.steps[k] ? " done" : "") + (cur === k ? " open" : "")} onClick={() => setOpen(cur === k ? "__none" : k)} aria-expanded={cur === k}>
      <span className="bsetup-check">{view.steps[k] ? "✓" : steps.indexOf(k) + 1}</span>
      <span className="bsetup-step-t">{title}</span>
      {sub && <span className="bsetup-step-s">{sub}</span>}
    </button>
  );
  return (
    <div className="bundle-setup" role="region" aria-label={t("bundle.setupTitle", { name: bl(view.name) })}>
      <div className="bsetup-head">
        <span className="bsetup-ic">{view.icon}</span>
        <span className="bsetup-title">{t("bundle.setupTitle", { name: bl(view.name) })}</span>
        <span className="bsetup-count">{doneN}/{steps.length}</span>
        <button className="bsetup-link" onClick={onAbout}>{t("bundle.about")}</button>
        {view.manage && <button className="bsetup-link" onClick={done} disabled={busy === "done"}>{doneN === steps.length ? t("bundle.setupFinish") : t("bundle.setupLater")}</button>}
      </div>
      {steps.includes("connect") && (
        <div className="bsetup-step">
          {head("connect", t("bundle.stepConnect"), !view.needs.length ? t("bundle.nothing")
            : view.needs.some(n => n.required || n.met) ? view.needs.filter(n => n.met).length + "/" + view.needs.length : t("bundle.optional"))}
          {cur === "connect" && (
            <div className="bsetup-body">
              {!view.needs.length && <p className="bundle-sub">{t("bundle.needsNothing")}</p>}
              {view.needs.map(n => (
                <div key={n.kind} className="bsetup-need">
                  <span className="bundle-li-ic"><ConnGlyph group={n.kind} /></span>
                  <div className="bsetup-need-main">
                    <div><b>{t("bundle.need." + n.kind)}</b> <span className="bundle-when">{t("bundle.access." + n.access)}{!n.required ? " · " + t("bundle.optional") : ""}</span></div>
                    {n.met
                      ? <div className="bsetup-met">✓ {serviceName(n.grant.service, n.grant.account || n.grant.service)}{n.grant.account ? " · " + n.grant.account : ""} · {window.IndieConn.accessLabel(n.grant.service, n.grant.access)}{!n.enough && <span className="bsetup-warn"> · {t("bundle.lessAccess")}</span>}</div>
                      : <div className="bundle-sub">{bl(n.why)}</div>}
                    {!n.met && view.manage && (
                      <div className="bsetup-acts">
                        {n.accounts.map(acc => (
                          <button key={acc.id} className="btn" disabled={!!busy} onClick={() => useAccount(n, acc)}>{busy === "acc:" + acc.id ? "…" : t("bundle.useAccount", { name: acc.label || acc.provider })}</button>
                        ))}
                        {n.services.map(s => (
                          <button key={s.service} className={"btn" + (n.accounts.length ? "" : " primary")} onClick={() => onConnect({ service: s.service, access: n.access })}>{t("bundle.connect", { name: serviceName(s.service, s.name) })}</button>
                        ))}
                        {!n.services.length && !n.accounts.length && <span className="bundle-sub">{t("bundle.noService")}</span>}
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
      {steps.includes("questions") && (
        <div className="bsetup-step">
          {head("questions", t("bundle.stepQuestions"))}
          {cur === "questions" && (
            <div className="bsetup-body">
              {view.questions.map(q => (
                <label key={q.key} className="bsetup-q">
                  <span className="bsetup-q-l">{bl(q.label)}</span>
                  {q.multiline
                    ? <textarea rows={3} value={ans[q.key] || ""} onChange={e => setAns(a => ({ ...a, [q.key]: e.target.value }))} disabled={!view.manage} />
                    : <input value={ans[q.key] || ""} onChange={e => setAns(a => ({ ...a, [q.key]: e.target.value }))} disabled={!view.manage} />}
                  {q.hint && <span className="bundle-sub">{bl(q.hint)}</span>}
                </label>
              ))}
              {view.manage && <div className="bsetup-acts"><button className="btn primary" disabled={busy === "answers"} onClick={saveAnswers}>{busy === "answers" ? "…" : t("bundle.saveAnswers")}</button></div>}
            </div>
          )}
        </div>
      )}
      {steps.includes("schedules") && (
        <div className="bsetup-step">
          {head("schedules", t("bundle.stepSchedules"), t("bundle.schedulesOn", { n: view.routines.filter(r => r.enabled).length, total: view.routines.length }))}
          {cur === "schedules" && (
            <div className="bsetup-body">
              <p className="bundle-sub">{t("bundle.schedulesLead")}</p>
              {view.routines.map(r => (
                <div key={r.id} className="bsetup-routine">
                  <label className={"bsetup-switch" + (r.missing.length && !r.enabled ? " off" : "")}>
                    <input type="checkbox" checked={!!r.enabled} disabled={!view.manage || !!busy || (!r.enabled && r.missing.length > 0)} onChange={e => toggle(r, e.target.checked)} />
                    <span><b>{r.title}</b> <span className="bundle-when">{cronToText(r.cron)}</span>
                      <span className="bundle-sub">{bl(r.summary)}</span>
                      {r.missing.length > 0 && !r.enabled && <span className="bsetup-warn">{t("bundle.routineNeeds", { what: r.missing.map(k => t("bundle.need." + k)).join(", ") })}</span>}
                    </span>
                  </label>
                </div>
              ))}
              {view.manage && !view.steps.schedules && <div className="bsetup-acts"><button className="btn" onClick={seen} disabled={!!busy}>{t("bundle.schedulesLater")}</button></div>}
            </div>
          )}
        </div>
      )}
      {steps.includes("try") && (
        <div className="bsetup-step">
          {head("try", t("bundle.stepTry"))}
          {cur === "try" && (
            <div className="bsetup-body">
              <div className="bsetup-try">
                {view.tryIt.map((x, i) => <button key={i} className="bsetup-try-q" onClick={() => onTry(bl(x))}>{bl(x)}</button>)}
              </div>
              {view.hasExample && view.app && view.manage && (
                <div className="bsetup-acts">
                  <button className="btn" disabled={!!busy} onClick={example}>{busy === "example" ? "…" : t("bundle.loadExample")}</button>
                  <span className="bundle-sub">{t("bundle.loadExampleHint")}</span>
                </div>
              )}
            </div>
          )}
        </div>
      )}
      {err && <div className="set-msg bad" role="alert">{err}</div>}
    </div>
  );
}
/* "About this bundle": its parts, its schedules, its data, and removing it. */
function BundleAbout({ agent, view, reload, setView, onClose, onOpenApp, onRemoved, onSetup, setConfirm, onAppData }) {
  const [busy, setBusy] = useState(null);
  const [err, setErr] = useState(null);
  const [msg, setMsg] = useState(null);
  useEscape(onClose);
  const run = async (key, fn) => { setBusy(key); setErr(null); setMsg(null); try { await fn(); } catch (e) { setErr((e && e.message) || String(e)); } finally { setBusy(null); } };
  const toggle = (r, on) => run("r:" + r.id, async () => { await L.RoutinesAPI.update(r.id, { enabled: on }); await reload(); });
  const data = mode => setConfirm({
    title: t(mode === "example" ? "bundle.exampleTitle" : "bundle.emptyTitle"),
    confirmLabel: t(mode === "example" ? "bundle.loadExample" : "bundle.emptyData"),
    body: <p>{t(mode === "example" ? "bundle.exampleBody" : "bundle.emptyBody", { app: view.app ? view.app.name : "" })}</p>,
    onConfirm: () => run(mode, async () => { await L.BundlesAPI.data(agent.id, mode); onAppData && onAppData(); setMsg(t(mode === "example" ? "bundle.exampleDone" : "bundle.emptyDone")); }),
  });
  const remove = () => setConfirm({
    title: t("bundle.removeTitle", { name: bl(view.name) }),
    confirmLabel: t("bundle.remove"),
    body: (<>
      <p>{t("bundle.removeBody")}</p>
      <ul className="bundle-list tight">
        <li>{t("bundle.removeAgent", { name: agentName(agent) })}</li>
        {view.app && <li>{t("bundle.removeApp", { name: view.app.name })}</li>}
        {view.routines.length > 0 && <li>{t("bundle.removeRoutines", { n: view.routines.length })}</li>}
      </ul>
      <p className="bundle-sub">{t("bundle.removeKeeps")}</p>
    </>),
    onConfirm: async () => { try { await L.BundlesAPI.remove(agent.id); onRemoved(); } catch (e) { setErr((e && e.message) || String(e)); } },
  });
  return (
    <div className="modal-scrim" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal bundle-modal" role="dialog" aria-label={t("bundle.aboutTitle")}>
        <div className="modal-head">
          <div><span className="eb">{t("bundle.aboutTitle")}</span><h2><span className="bundle-h-ic">{view.icon}</span>{bl(view.name)} <span className="bundle-ver">{view.version}</span></h2></div>
          <button className="modal-x" onClick={onClose} aria-label={t("common.close")}>✕</button>
        </div>
        <div className="modal-body bundle-sheet">
          <p className="bundle-desc">{bl(view.summary)}</p>
          {view.latest && <div className="set-callout">{t("bundle.newer", { v: view.latest })}</div>}
          <section>
            <h3>{t("bundle.parts")}</h3>
            <ul className="bundle-list">
              <li><span className="bundle-li-ic"><BotIcon /></span><span><b>{agentName(agent)}</b><span className="bundle-sub">{t("bundle.partAgent")}</span></span></li>
              {view.app && <li><span className="bundle-li-ic">{view.app.icon}</span><span><b>{view.app.name}</b><span className="bundle-sub">{t("bundle.partApp")}</span></span>
                <button className="btn sm" onClick={() => { onOpenApp(view.app.id); onClose(); }}>{t("bundle.openApp")}</button></li>}
              {view.skills.length > 0 && <li><span className="bundle-li-ic">✦</span><span><b>{t("bundle.getSkills", { n: view.skills.length })}</b><span className="bundle-sub">{view.skills.map(k => k.name + ": " + k.description).join(" · ")}</span></span></li>}
              {view.files.length > 0 && <li><span className="bundle-li-ic"><FilesIcon /></span><span><b>{t("bundle.getFiles", { n: view.files.length })}</b><span className="bundle-sub">{view.files.join(", ")}</span></span></li>}
            </ul>
          </section>
          {view.routines.length > 0 && (
            <section>
              <h3>{t("bundle.stepSchedules")}</h3>
              {view.routines.map(r => (
                <label key={r.id} className={"bsetup-switch" + (r.missing.length && !r.enabled ? " off" : "")}>
                  <input type="checkbox" checked={!!r.enabled} disabled={!view.manage || !!busy || (!r.enabled && r.missing.length > 0)} onChange={e => toggle(r, e.target.checked)} />
                  <span><b>{r.title}</b> <span className="bundle-when">{cronToText(r.cron)}{r.enabled && r.nextRun ? " · " + t("bundle.next", { when: L.fmtTime(r.nextRun) }) : ""}</span>
                    {r.missing.length > 0 && !r.enabled && <span className="bsetup-warn">{t("bundle.routineNeeds", { what: r.missing.map(k => t("bundle.need." + k)).join(", ") })}</span>}
                  </span>
                </label>
              ))}
            </section>
          )}
          {view.manage && view.app && (
            <section>
              <h3>{t("bundle.data")}</h3>
              <div className="bsetup-acts">
                {view.hasExample && <button className="btn" disabled={!!busy} onClick={() => data("example")}>{t("bundle.loadExample")}</button>}
                <button className="btn" disabled={!!busy} onClick={() => data("empty")}>{t("bundle.emptyData")}</button>
              </div>
            </section>
          )}
          {msg && <div className="set-msg ok">{msg}</div>}
          {err && <div className="set-msg bad" role="alert">{err}</div>}
        </div>
        {view.manage && (
          <div className="modal-foot bundle-foot">
            <button className="btn danger" onClick={remove}>{t("bundle.remove")}</button>
            {view.dismissed && <button className="btn" onClick={() => { onSetup(); onClose(); }}>{t("bundle.setupAgain")}</button>}
          </div>
        )}
      </div>
    </div>
  );
}

/* Where new work starts when plain chat is switched off: say what you need
   and an agent takes it on. Sending makes the agent, so a visit that sends
   nothing leaves nothing behind, and New app sits here too because building
   an app is the other thing people arrive to do. */
const startSuggestions = () => [
  { k: t("start.kApp"),     t: t("start.s1") },
  { k: t("start.kExplain"), t: t("empty.s1") },
  { k: t("start.kDraft"),   t: t("empty.s2") },
  { k: t("start.kCode"),    t: t("empty.s3") },
];
/* The start page's Connections: its agent does not exist until the first
   message, so this is what every new agent of the person starts with
   (connections.jsx without an agent); the one made here gets it at once. */
function StartConnections() {
  const [open, setOpen] = useState(false);
  const [count, setCount] = useState(0);
  const load = () => L.AccountsAPI.newAgents().then(d => setCount((d.grants || []).length)).catch(() => {});
  useEffect(() => { load(); }, []);
  return (<>
    <button className={"icon-btn labelled" + (open ? " on" : "")} title={t("conn.newHint")} onClick={() => setOpen(true)}>
      <PlugIcon /> <span className="btn-label">{t("conn.button")}{count ? " · " + count : ""}</span>
    </button>
    {open && <ConnectionsModal agent={null} title={t("conn.newTitle")} onClose={() => { setOpen(false); load(); }} />}
  </>);
}
function AgentStart({ onStart, ensureAgent, engineReady, onNewApp, appBusy, onMenu, box, error, onDismissError, canPickModel, engine, onEngine, ws, onWsPanel, onBundle }) {
  const [preset, setPreset] = useState("");   /* a suggestion card fills the box */
  const pick = v => setPreset(v);
  return (<>
    <div className="topbar">
      <div style={{ display: "flex", alignItems: "center", minWidth: 0 }}>
        <button className="menu-btn" onClick={onMenu}><MenuIcon /></button>
        <div className="topbar-title">
          <span className="tt-kind">{t("topbar.new")}</span><span className="tt-name">{t("start.title")}</span>
        </div>
      </div>
      <div className="tools">
        <BoxBusy box={box} />
        {/* The agent is made with the first message, so its engine and model
            are chosen here, before it exists; without this menu a new agent
            could only be switched after its first turn had already run. */}
        <StartConnections />
        {canPickModel && <AgentEngineSelect agent={engine} onPick={onEngine} />}
        <a className="icon-btn labelled" title={t("nav.guide")} href={guideHref()} target="_blank" rel="noopener"><HelpIcon /> <span className="btn-label">{t("nav.guideShort")}</span></a>
      </div>
    </div>
    <div className="scroll-wrap">
      <div className="scroll">
        <div className="empty agent-start">
          <div className="empty-mark" />
          <h1><BrandName /></h1>
          <p className="sub">{t("start.blurb")}</p>
          {/* In a workspace, say so: what is made here shares its files, memory and services. */}
          {ws && (
            <p className="ws-start">
              <span className="ws-start-text"><span className="ws-ic">▣</span> {tb("ws.startIn", { name: ws.name })}</span>
              <span className="ws-start-links">
                <button className="ws-start-link" onClick={() => onWsPanel && onWsPanel("memory")}>{t("ws.memory")}</button>
                <button className="ws-start-link" onClick={() => onWsPanel && onWsPanel("files")}>{t("ws.files")}</button>
              </span>
            </p>
          )}
          <div className="start-actions">
            <button className="btn" onClick={onNewApp} disabled={appBusy}>
              <span className="new-menu-ic">▦</span> {appBusy ? t("app.creating") : t("sidebar.newApp")}
            </button>
          </div>
          {/* ready-made agents: a bundle is an agent with its app, routines and skills for one job */}
          {onBundle && <BundleStartRow onOpen={onBundle} />}
          <div className="eyebrow">{t("empty.tryOne")}</div>
          <div className="prompts">
            {startSuggestions().map((sg, i) => (
              <button key={i} className="prompt" onClick={() => pick(sg.t)}>
                <span className="p-k">{sg.k}</span>
                <span className="p-t">{sg.t}</span>
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
    {error && (
      <div style={{ padding: "0 24px" }}>
        <div className="banner">
          <span className="sq" style={{ width: 8, height: 8, background: "var(--maroon)" }} />
          {error}
          <button className="x" onClick={onDismissError}>✕</button>
        </div>
      </div>
    )}
    {/* the agent's own message box: files, voice, the wiki and privacy
        switches work here as they do in any agent */}
    <AgentComposer key={"new:" + (ws ? ws.id : "")} agentId={null} workspaceId={ws ? ws.id : null} ensureAgent={ensureAgent} wikiAvailable={L.moduleOn("brain")}
                   busy={false} engineReady={engineReady} onSend={onStart} onStop={() => {}}
                   placeholder={t("start.placeholder")} hint="start.hint"
                   presetText={preset} clearPreset={() => setPreset("")} />
  </>);
}

/* ========================================================
   WORKSPACES: a place to work in, with its own agents and apps, shared
   files (/files in every turn), a memory every agent reads and adds to
   (MEMORY.md), its own MCP servers and its own wiki. General holds
   everything that is in no workspace.
   ======================================================== */
function useEscape(onClose) {
  useEffect(() => {
    const k = e => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, [onClose]);
}
/* The switcher at the top of the sidebar, with the open workspace's own
   things one click away under it. */
function WorkspaceSwitch({ workspaces, current, onSwitch, onNew, onPanel }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const away = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const esc = e => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("mousedown", away); document.addEventListener("keydown", esc);
    return () => { document.removeEventListener("mousedown", away); document.removeEventListener("keydown", esc); };
  }, [open]);
  return (
    <div className="ws-switch" ref={ref}>
      <button className="ws-current" onClick={() => setOpen(o => !o)} title={t("ws.switchHint")} aria-expanded={open}>
        <span className="ws-ic">▣</span>
        <span className="ws-label">
          <span className="ws-cap">{t("ws.cap")}</span>
          <span className="ws-name">{current ? current.name : t("ws.general")}</span>
        </span>
        {current && current.scope === "global" && <span className="app-scope" title={t("ws.shared")}>G</span>}
        <span className="ws-caret">▾</span>
      </button>
      {current && (
        <div className="ws-links">
          <button onClick={() => onPanel("files")}>{t("ws.files")}</button>
          <button onClick={() => onPanel("memory")}>{t("ws.memory")}</button>
          <button onClick={() => onPanel("services")}>{t("ws.services")}</button>
          <button className="ws-gear" title={t("ws.settings")} onClick={() => onPanel("settings")}><GearIcon /></button>
        </div>
      )}
      {open && (
        <div className="ws-menu">
          <button className={"ws-opt" + (!current ? " on" : "")} onClick={() => { setOpen(false); onSwitch(null); }}>
            <span className="ws-opt-name">{t("ws.general")}</span>
            <span className="ws-opt-sub">{t("ws.generalHint")}</span>
          </button>
          {workspaces.map(w => (
            <button key={w.id} className={"ws-opt" + (current && current.id === w.id ? " on" : "")} onClick={() => { setOpen(false); onSwitch(w.id); }}>
              <span className="ws-opt-name">{w.name}{w.scope === "global" && <span className="app-scope" title={t("ws.shared")}>G</span>}</span>
              {w.description && <span className="ws-opt-sub">{w.description}</span>}
            </button>
          ))}
          <div className="ws-sep" />
          <button className="ws-opt new" onClick={() => { setOpen(false); onNew(); }}><PlusIcon /> {t("ws.new")}</button>
        </div>
      )}
    </div>
  );
}
/* Move an agent or an app to another workspace (or General): what existed
   before workspaces starts in General. Something shared with everyone may only
   go where everyone can follow it, and only an admin moves it. */
function MoveToWorkspace({ item, workspaces, isAdmin, onMove }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const away = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", away);
    return () => document.removeEventListener("mousedown", away);
  }, [open]);
  const shared = item.scope === "global";
  if (shared && !isAdmin) return null;
  const here = item.workspaceId || null;
  const targets = [{ id: null, name: t("ws.general") }, ...(workspaces || []).filter(w => !shared || w.scope === "global")]
    .filter(w => w.id !== here);
  if (!targets.length) return null;
  return (
    <div className="ws-move" ref={ref}>
      <button className={"icon-btn" + (open ? " on" : "")} title={t("ws.moveHint")} onClick={() => setOpen(o => !o)}><span className="ws-ic">▣</span></button>
      {open && (
        <div className="ws-menu ws-move-menu">
          <div className="mcp-menu-head">{t("ws.moveTo")}</div>
          {targets.map(w => (
            <button key={w.id || "general"} className="ws-opt" onClick={() => { setOpen(false); onMove(w.id); }}>
              <span className="ws-opt-name">{w.name}{w.scope === "global" && <span className="app-scope">G</span>}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
function NewWorkspaceModal({ isAdmin, onCreate, onClose }) {
  const [name, setName] = useState("");
  const [desc, setDesc] = useState("");
  const [global, setGlobal] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(null);
  useEscape(onClose);
  const create = async () => {
    if (!name.trim() || busy) return;
    setBusy(true); setErr(null);
    try { await onCreate({ name: name.trim(), description: desc.trim(), ...(global ? { scope: "global" } : {}) }); }
    catch (e) { setErr((e && e.message) || t("ws.createFailed")); setBusy(false); }
  };
  return (
    <div className="modal-scrim" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <form className="modal ws-new" onSubmit={e => { e.preventDefault(); create(); }}>
        <div className="modal-head">
          <div><span className="eb">{t("ws.cap")}</span><h2>{t("ws.newTitle")}</h2></div>
          <button type="button" className="modal-x" onClick={onClose}>✕</button>
        </div>
        <div className="modal-body">
          <p className="ws-lead">{t("ws.newLead")}</p>
          <div className="field">
            <label>{t("ws.name")}</label>
            <input autoFocus value={name} maxLength={80} placeholder={t("ws.namePlaceholder")} onChange={e => setName(e.target.value)} />
          </div>
          <div className="field">
            <label>{t("ws.description")}</label>
            <input value={desc} maxLength={300} onChange={e => setDesc(e.target.value)} />
          </div>
          {isAdmin && (
            <label className="app-global-opt">
              <input type="checkbox" checked={global} onChange={e => setGlobal(e.target.checked)} />
              {t("ws.shareAll")}
            </label>
          )}
          {err && <div className="ws-err">{err}</div>}
        </div>
        <div className="modal-foot">
          <span style={{ flex: 1 }} />
          <button type="button" className="btn" onClick={onClose}>{t("common.cancel")}</button>
          <button type="submit" className="btn primary" disabled={!name.trim() || busy}>{busy ? t("ws.creating") : t("ws.create")}</button>
        </div>
      </form>
    </div>
  );
}
/* A workspace's own things. Files and memory belong to everyone who works in
   it; its services, name and the delete button to whoever manages it (the
   owner, or an admin for a shared one). */
function WorkspacePanel({ ws, tab: firstTab, onClose, onChanged, onDeleted }) {
  const [tab, setTab] = useState(firstTab || "files");
  const [access, setAccess] = useState(ws.access);   /* open to everyone, or members only (People) */
  useEscape(onClose);
  const tabs = [["files", t("ws.files")], ["memory", t("ws.memory")], ["skills", t("ws.skills")], ["services", t("ws.services")],
                ...(ws.scope === "global" ? [["people", t("ws.people")]] : []), ["settings", t("ws.about")]];
  return (
    <div className="modal-scrim" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal ws-panel">
        <div className="modal-head">
          <div><span className="eb">{t("ws.cap")}{ws.scope === "global" ? " · " + (access === "members" ? t("ws.sharedMembers") : t("ws.shared")) : ""}</span><h2>{ws.name}</h2></div>
          <button className="modal-x" onClick={onClose}>✕</button>
        </div>
        <div className="ws-tabs">
          {tabs.map(([k, label]) => <button key={k} className={"ws-tab" + (tab === k ? " on" : "")} onClick={() => setTab(k)}>{label}</button>)}
        </div>
        <div className="modal-body">
          {tab === "files" && <WsFiles ws={ws} />}
          {tab === "memory" && <WsMemory ws={ws} />}
          {tab === "skills" && <WsSkills ws={ws} />}
          {tab === "services" && <WsServices ws={ws} />}
          {tab === "people" && <WsMembers ws={ws} onAccess={setAccess} onLeft={() => onDeleted && onDeleted(ws.id)} />}
          {tab === "settings" && <WsSettings ws={ws} onChanged={onChanged} onDeleted={onDeleted} />}
        </div>
      </div>
    </div>
  );
}
function WsFiles({ ws }) {
  const [files, setFiles] = useState(null);     /* null: loading, not empty */
  const [uploading, setUploading] = useState(0);
  const [err, setErr] = useState(null);
  const [dl, setDl] = useState(null);
  const [armed, setArmed] = useState(null);     /* path: a first click on delete arms it */
  const [viewing, setViewing] = useState(null); /* path shown in place of the list */
  const [folder, setFolder] = useState(null);   /* the company folder, when there is one */
  const input = useRef(null);
  const load = () => L.WorkspacesAPI.files(ws.id)
    .then(r => { setFiles((r.files || []).slice().sort((a, b) => a.path.localeCompare(b.path))); setFolder(r.folder || null); })
    .catch(e => { setFiles([]); setErr((e && e.message) || String(e)); });
  useEffect(() => { setFiles(null); setViewing(null); load(); }, [ws.id]);
  const upload = async list => {
    setErr(null);
    for (const f of Array.from(list || [])) {
      setUploading(n => n + 1);
      try { await L.WorkspacesAPI.upload(ws.id, f); }
      catch (e) { setErr(t("ws.fileFailed", { error: (e && e.message) || String(e) })); }
      finally { setUploading(n => n - 1); }
    }
    load();
  };
  const remove = async p => {
    if (armed !== p) { setArmed(p); return; }
    setArmed(null);
    try { await L.WorkspacesAPI.removeFile(ws.id, p); load(); }
    catch (e) { setErr(t("ws.fileFailed", { error: (e && e.message) || String(e) })); }
  };
  const download = async p => {
    setDl(p);
    try { await L.WorkspacesAPI.download(ws.id, p); }
    catch (e) { setErr(t("ws.fileFailed", { error: (e && e.message) || String(e) })); }
    finally { setDl(null); }
  };
  if (viewing) return (
    <div className="ws-pane ws-view">
      <div className="ws-row-acts">
        <button className="aq-btn" onClick={() => setViewing(null)}>{t("ws.backToFiles")}</button>
        <span className="ws-view-name" title={viewing}>{viewing}</span>
        <button className="aq-btn" onClick={() => download(viewing)} disabled={dl === viewing}>{dl === viewing ? "…" : t("common.download")}</button>
      </div>
      {err && <div className="ws-err">{err}</div>}
      <div className="ws-view-body"><DocView wsId={ws.id} path={viewing} /></div>
    </div>
  );
  return (
    <div className="ws-pane" onDragOver={e => e.preventDefault()} onDrop={e => { e.preventDefault(); upload(e.dataTransfer.files); }}>
      <p className="ws-lead">{tb("ws.filesLead")}</p>
      <WsFolder ws={ws} folder={folder} onChanged={() => { setFiles(null); load(); }} />
      <div className="ws-row-acts">
        <button className="btn" onClick={() => input.current && input.current.click()} disabled={uploading > 0}>{uploading ? t("ws.uploading") : t("ws.upload")}</button>
        <input ref={input} type="file" multiple hidden onChange={e => { upload(e.target.files); e.target.value = ""; }} />
        <span className="ws-hint">{t("ws.dropHint")}</span>
      </div>
      {err && <div className="ws-err">{err}</div>}
      {files === null ? <div className="ws-empty">{t("common.loading")}</div>
        : files.length === 0 ? <div className="ws-empty">{tb("ws.noFiles")}</div>
        : (
          <div className="ws-list">
            {files.map(f => (
              <div className="ws-item" key={f.path}>
                <span className="ws-item-name" title={f.path}>{f.path}</span>
                <span className="ws-item-meta">{fmtBytes(f.size)}</span>
                {L.canPreview(f.path) && <button className="aq-btn" onClick={() => setViewing(f.path)}>{t("file.preview")}</button>}
                <button className="aq-btn" onClick={() => download(f.path)} disabled={dl === f.path}>{dl === f.path ? "…" : t("common.download")}</button>
                <button className={"aq-btn" + (armed === f.path ? " danger" : "")} onClick={() => remove(f.path)} onBlur={() => setArmed(a => a === f.path ? null : a)}>
                  {armed === f.path ? t("ws.confirmDelete") : t("common.delete")}
                </button>
              </div>
            ))}
          </div>
        )}
    </div>
  );
}
/* Where a workspace's files live: here, or a company folder kept in step
   with them (server.js, workspace folders). Admins link one; everyone sees
   its state and may sync now. */
const FOLDER_FIELDS = {
  smb: [["host", "ws.folderHost", "fileserver.office.lan"], ["share", "ws.folderShare", "Projects"], ["path", "ws.folderPath", "Legal/2026"], ["user", "ws.folderUser", ""], ["domain", "ws.folderDomain", "WORKGROUP"], ["pass", "ws.folderPass", ""]],
  webdav: [["url", "ws.folderUrl", "https://cloud.example.com/remote.php/dav/files/USER/"], ["path", "ws.folderPath", "Projects/Legal"], ["user", "ws.folderUser", ""], ["pass", "ws.folderAppPass", ""]],
  sharepoint: [["site", "ws.folderSite", "https://contoso.sharepoint.com/sites/Legal"], ["library", "ws.folderLibrary", "Documents"], ["path", "ws.folderPath", "Contracts"]],
};
function WsFolder({ ws, folder, onChanged }) {
  const [info, setInfo] = useState(null);       /* { mayLink, microsoft } */
  const [form, setForm] = useState(null);       /* the link form's fields, while open */
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(null);
  useEffect(() => { L.WorkspacesAPI.folder(ws.id).then(setInfo).catch(() => setInfo({ mayLink: false })); }, [ws.id]);
  const act = async (fn, after) => {
    setBusy(true); setErr(null);
    try { await fn(); if (after) after(); onChanged(); }
    catch (e) { setErr(e && e.code === "has-files" ? t("ws.folderHasFiles", { n: e.data.files }) : (e && e.message) || String(e)); }
    finally { setBusy(false); }
  };
  if (folder) return (
    <div className="ws-folder">
      <div className="ws-folder-head">
        <span className="ws-folder-kind">{t("ws.folderKind." + folder.type)}</span>
        <span className="ws-folder-label" title={folder.label}>{folder.label}</span>
      </div>
      <div className="ws-folder-state">
        {folder.lastError
          ? <span className="ws-err">{t("ws.folderFailed", { error: folder.lastError })}</span>
          : <span>{folder.lastSync ? t("ws.folderSynced", { when: new Date(folder.lastSync).toLocaleTimeString(), n: folder.files == null ? "?" : folder.files }) : t("ws.folderNever")}</span>}
        {folder.type === "sharepoint" && folder.account && <span className="ws-hint">{t("ws.folderAccount", { account: folder.account })}</span>}
        <button className="aq-btn" disabled={busy} onClick={() => act(() => L.WorkspacesAPI.sync(ws.id))}>{busy ? t("ws.folderSyncing") : t("ws.folderSyncNow")}</button>
        {info && info.mayLink && <button className="aq-btn" disabled={busy} onClick={() => act(() => L.WorkspacesAPI.unlinkFolder(ws.id))}>{t("ws.folderUnlink")}</button>}
      </div>
      {err && <div className="ws-err">{err}</div>}
    </div>
  );
  if (!info || !info.mayLink) return null;
  if (!form) return <div className="ws-row-acts"><button className="aq-btn" onClick={() => setForm({ type: "smb" })}>{t("ws.folderLink")}</button><span className="ws-hint">{t("ws.folderLinkHint")}</span></div>;
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  return (
    <div className="ws-folder ws-folder-form">
      <div className="ws-folder-types">
        {["smb", "webdav", "sharepoint"].map(k => (
          <button key={k} className={"aq-btn" + (form.type === k ? " on" : "")} onClick={() => setForm({ type: k })}>{t("ws.folderKind." + k)}</button>
        ))}
      </div>
      {form.type === "webdav" && (
        <label className="ws-check"><input type="checkbox" checked={form.vendor === "nextcloud"} onChange={e => set("vendor", e.target.checked ? "nextcloud" : "other")} /> {t("ws.folderNextcloud")}</label>
      )}
      {form.type === "sharepoint" && (
        (info.microsoft || []).length
          ? <select className="set-approval" value={form.connectionId || ""} onChange={e => set("connectionId", e.target.value)}>
              <option value="">{t("ws.folderPickMicrosoft")}</option>
              {info.microsoft.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          : <p className="ws-note">{t("ws.folderNeedsMicrosoft")}</p>
      )}
      <div className="ws-folder-fields">
        {FOLDER_FIELDS[form.type].map(([k, label, ph]) => (
          <label key={k}><span>{t(label)}</span>
            <input type={k === "pass" ? "password" : "text"} value={form[k] || ""} placeholder={ph} spellCheck="false" autoComplete="off" onChange={e => set(k, e.target.value)} />
          </label>
        ))}
      </div>
      <p className="ws-note">{t("ws.folderTwoWay")}</p>
      <div className="ws-row-acts">
        <button className="aq-btn" onClick={() => { setForm(null); setErr(null); }}>{t("common.cancel")}</button>
        <button className="btn" disabled={busy} onClick={() => act(() => L.WorkspacesAPI.linkFolder(ws.id, form), () => setForm(null))}>{busy ? t("ws.folderLinking") : t("ws.folderLinkNow")}</button>
      </div>
      {err && <div className="ws-err">{err}</div>}
    </div>
  );
}
function WsMemory({ ws }) {
  const [text, setText] = useState(null);
  const [orig, setOrig] = useState("");
  const [max, setMax] = useState(8000);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [err, setErr] = useState(null);
  useEffect(() => {
    setText(null);
    L.WorkspacesAPI.memory(ws.id)
      .then(r => { setText(r.text || ""); setOrig(r.text || ""); if (r.promptMax) setMax(r.promptMax); })
      .catch(e => { setText(""); setErr((e && e.message) || String(e)); });
  }, [ws.id]);
  const save = async () => {
    setSaving(true); setErr(null);
    try { await L.WorkspacesAPI.setMemory(ws.id, text); setOrig(text); setSaved(true); setTimeout(() => setSaved(false), 1600); }
    catch (e) { setErr((e && e.message) || String(e)); }
    finally { setSaving(false); }
  };
  return (
    <div className="ws-pane">
      <p className="ws-lead">{tb("ws.memoryLead")}</p>
      {text === null ? <div className="ws-empty">{t("common.loading")}</div> : (<>
        <textarea className="ws-memory-text" value={text} spellCheck={false} onChange={e => setText(e.target.value)} />
        <div className="ws-row-acts">
          {text.length > max && <span className="ws-warn">{t("ws.memoryLong", { n: L.fmtNum ? L.fmtNum(max) : max })}</span>}
          <span style={{ flex: 1 }} />
          {saved && <span className="ws-saved">{t("ws.saved")}</span>}
          <button className="btn primary" onClick={save} disabled={saving || text === orig}>{t("ws.save")}</button>
        </div>
      </>)}
      {err && <div className="ws-err">{err}</div>}
    </div>
  );
}
/* A workspace's skills (server.js, skills): everyone who works in it writes
   them, like its memory, and every agent in it gets them. Below, the plugins
   its manager switches on for it; required ones come anyway. */
function WsSkills({ ws }) {
  const [rows, setRows] = useState(null);
  const [plugins, setPlugins] = useState([]);
  const [text, setText] = useState("");
  const [editing, setEditing] = useState(null);
  const [draft, setDraft] = useState("");
  const [err, setErr] = useState(null);
  const load = () => Promise.all([
    L.SkillsAPI.list(ws.id).then(r => setRows(r.workspace || [])),
    L.PluginsAPI.list().then(r => setPlugins(r.plugins || [])).catch(() => setPlugins([])),
  ]).catch(e => { setRows([]); setErr((e && e.message) || String(e)); });
  useEffect(() => { setRows(null); setEditing(null); load(); }, [ws.id]);
  const act = async fn => { setErr(null); try { await fn(); await load(); return true; } catch (e) { setErr((e && e.message) || String(e)); return false; } };
  const md = s => "---\nname: " + s.name + "\ndescription: " + (s.description || "") + "\n---\n" + (s.content || "");
  return (
    <div className="ws-pane">
      <p className="ws-lead">{tb("ws.skillsLead")}</p>
      {rows === null ? <div className="ws-empty">{t("common.loading")}</div>
        : rows.length === 0 ? <div className="ws-empty">{t("ws.noSkills")}</div>
        : (
          <div className="ws-list">
            {rows.map(r => editing === r.id ? (
              <div className="ws-item ws-skill-edit" key={r.id}>
                <textarea className="ws-memory-text" value={draft} onChange={e => setDraft(e.target.value)} rows={8} spellCheck="false" />
                <div className="ws-row-acts">
                  <button className="aq-btn" onClick={() => setEditing(null)}>{t("common.cancel")}</button>
                  <button className="aq-btn" onClick={async () => { if (await act(() => L.SkillsAPI.update(r.id, { markdown: draft }))) setEditing(null); }}>{t("common.save")}</button>
                </div>
              </div>
            ) : (
              <div className="ws-item" key={r.id}>
                <button className={"mcp-switch " + (r.enabled ? "on" : "")} role="switch" aria-checked={!!r.enabled} aria-label={r.name}
                        onClick={() => act(() => L.SkillsAPI.update(r.id, { enabled: !r.enabled }))}><span /></button>
                <span className="ws-item-name" title={r.description}><b>{r.name}</b> <span className="ws-item-meta">{r.description}</span></span>
                <button className="aq-btn" onClick={() => { setEditing(r.id); setDraft(md(r)); }}>{t("common.edit")}</button>
                <button className="aq-x" title={t("common.delete")} onClick={() => act(() => L.SkillsAPI.remove(r.id))}>✕</button>
              </div>
            ))}
          </div>
        )}
      <textarea className="ws-memory-text ws-skill-new" value={text} onChange={e => setText(e.target.value)} rows={4} spellCheck="false"
                placeholder={"---\nname: Minutes\ndescription: Write meeting minutes the way this team does\n---\nStart with the decisions, then …"} />
      <div className="ws-row-acts">
        <button className="btn" disabled={!text.trim()} onClick={async () => { if (await act(() => L.SkillsAPI.create({ scope: "workspace", workspaceId: ws.id, markdown: text.trim() }))) setText(""); }}>{t("settings.addSkill")}</button>
      </div>
      {plugins.length > 0 && (<>
        <h3 className="ws-sub">{t("ws.plugins")}</h3>
        {!ws.manage && <p className="ws-note">{t("ws.pluginsReadonly")}</p>}
        <div className="ws-list">
          {plugins.map(p => {
            const on = p.required || (p.workspaces || []).includes(ws.id);
            return (
              <div className="ws-item" key={p.id}>
                <button className={"mcp-switch " + (on ? "on" : "")} role="switch" aria-checked={on} aria-label={p.name} disabled={p.required || !ws.manage}
                        onClick={() => act(() => L.PluginsAPI.use(p.id, !on, ws.id))}><span /></button>
                <span className="ws-item-name" title={p.description}><b>{p.name}</b> <span className="ws-item-meta">{p.required ? t("settings.pluginRequired") : p.description}</span></span>
              </div>
            );
          })}
        </div>
      </>)}
      {err && <div className="ws-err">{err}</div>}
    </div>
  );
}
function WsServices({ ws }) {
  const [rows, setRows] = useState(null);
  const [manage, setManage] = useState(false);
  const [name, setName] = useState("");
  const [url, setUrl] = useState("");
  const [err, setErr] = useState(null);
  const load = () => L.WorkspacesAPI.servers(ws.id)
    .then(r => { setRows(r.servers || []); setManage(!!r.manage); })
    .catch(e => { setRows([]); setErr((e && e.message) || String(e)); });
  useEffect(() => { setRows(null); load(); }, [ws.id]);
  const act = async fn => { setErr(null); try { await fn(); load(); } catch (e) { setErr((e && e.message) || String(e)); } };
  return (
    <div className="ws-pane">
      <p className="ws-lead">{t("ws.servicesLead")}</p>
      {rows !== null && !manage && <p className="ws-note">{t("ws.servicesReadonly")}</p>}
      {rows === null ? <div className="ws-empty">{t("common.loading")}</div>
        : rows.length === 0 ? <div className="ws-empty">{t("ws.noServices")}</div>
        : (
          <div className="ws-list">
            {rows.map(r => (
              <div className="ws-item" key={r.id}>
                <button className={"mcp-switch " + (r.enabled ? "on" : "")} disabled={!manage} role="switch" aria-checked={!!r.enabled}
                        onClick={() => act(() => L.McpServersAPI.update(r.id, { enabled: !r.enabled }))}><span /></button>
                <span className="ws-item-name"><b>{r.name}</b> <span className="ws-item-meta">{r.url}</span></span>
                <select className="set-approval" value={r.approval || "never"} disabled={!manage} title={t("settings.mcpApprovalHint")}
                        aria-label={t("settings.mcpApprovalHint")} onChange={e => act(() => L.McpServersAPI.update(r.id, { approval: e.target.value }))}>
                  <option value="never">{t("settings.mcpApproval.never")}</option>
                  <option value="changes">{t("settings.mcpApproval.changes")}</option>
                  <option value="always">{t("settings.mcpApproval.always")}</option>
                </select>
                {manage && <button className="aq-x" title={t("ws.removeService")} onClick={() => act(() => L.McpServersAPI.remove(r.id))}>✕</button>}
              </div>
            ))}
          </div>
        )}
      {manage && (
        <form className="ws-add" onSubmit={e => { e.preventDefault(); if (url.trim()) act(async () => { await L.WorkspacesAPI.addServer(ws.id, { name: name.trim(), url: url.trim() }); setName(""); setUrl(""); }); }}>
          <input value={name} onChange={e => setName(e.target.value)} placeholder={t("ws.serviceName")} />
          <input value={url} onChange={e => setUrl(e.target.value)} placeholder={t("ws.serviceUrl")} />
          <button className="btn" disabled={!url.trim()}>{t("ws.addService")}</button>
        </form>
      )}
      {err && <div className="ws-err">{err}</div>}
    </div>
  );
}
/* Who may use a shared workspace (server.js, members of a shared workspace):
   everyone, as shared workspaces always were, or only its members, as a
   Bereich is in the agent studio. Whoever manages it switches, adds and
   removes; everyone sees who is in it and may leave. */
function WsMembers({ ws, onAccess, onLeft }) {
  const [d, setD] = useState(null);
  const [err, setErr] = useState(null);
  const [armed, setArmed] = useState(null);        /* "open" | a member id: a first click arms it */
  const [pick, setPick] = useState("");
  const load = () => L.WorkspacesAPI.members(ws.id).then(setD).catch(e => { setErr((e && e.message) || String(e)); setD({ members: [], access: "everyone" }); });
  useEffect(() => { setD(null); load(); }, [ws.id]);
  const act = async (fn, after) => {
    setErr(null); setArmed(null);
    try { const r = await fn(); if (r && r.left) { onLeft && onLeft(); return; } setD(r); onAccess && onAccess(r.access); after && after(); }
    catch (e) { setErr((e && e.message) || String(e)); }
  };
  if (!d) return <div className="ws-pane"><p className="ws-note">{t("common.loading")}</p></div>;
  const people = d.people || [];
  const chosen = people.find(p => (p.name + " <" + p.email + ">") === pick || p.email === pick.trim().toLowerCase());
  return (
    <div className="ws-pane">
      <p className="ws-note">{d.access === "members" ? t("ws.accessMembers") : t("ws.accessEveryone")}</p>
      {d.manage && (d.access === "everyone"
        ? <div className="ws-row-acts"><button className="btn" onClick={() => act(() => L.WorkspacesAPI.setAccess(ws.id, "members"))}>{t("ws.onlyMembers")}</button>
            <span className="ws-note">{t("ws.onlyMembersHint")}</span></div>
        : <div className="ws-row-acts"><button className="btn" onClick={() => armed === "open" ? act(() => L.WorkspacesAPI.setAccess(ws.id, "everyone")) : setArmed("open")}>
            {armed === "open" ? t("ws.openConfirm") : t("ws.openEveryone")}</button>
            {armed === "open" && <span className="ws-warn">{t("ws.openHint")}</span>}</div>)}
      {d.access === "members" && (
        <div className="ws-members">
          {d.members.map(m => (
            <div className="ws-member" key={m.id}>
              <span className="ws-member-name">{m.name}{m.me ? " · " + t("ws.you") : ""}</span>
              <span className="ws-member-mail">{m.email}</span>
              {d.manage
                ? <select className="adm-select ws-member-role" value={m.role} aria-label={t("ws.role")} onChange={e => act(() => L.WorkspacesAPI.setMember(ws.id, m.id, e.target.value))}>
                    <option value="admin">{t("ws.roleAdmin")}</option><option value="member">{t("ws.roleMember")}</option>
                  </select>
                : <span className="ws-member-roletext">{m.role === "admin" ? t("ws.roleAdmin") : t("ws.roleMember")}</span>}
              {(d.manage || m.me) && (
                <button className="mini danger" onClick={() => armed === m.id ? act(() => L.WorkspacesAPI.removeMember(ws.id, m.id)) : setArmed(m.id)}>
                  {armed === m.id ? (m.me ? t("ws.leaveConfirm") : t("ws.removeConfirm")) : (m.me ? t("ws.leave") : t("ws.remove"))}
                </button>
              )}
            </div>
          ))}
        </div>
      )}
      {armed && armed !== "open" && <p className="ws-warn">{t("ws.removeHint")}</p>}
      {d.manage && d.access === "members" && (
        <div className="ws-member-add">
          <input list={"ws-people-" + ws.id} value={pick} onChange={e => setPick(e.target.value)} placeholder={t("ws.addPerson")} aria-label={t("ws.addPerson")} />
          <datalist id={"ws-people-" + ws.id}>{people.map(p => <option key={p.id} value={p.name + " <" + p.email + ">"} />)}</datalist>
          <button className="btn primary" disabled={!chosen} onClick={() => act(() => L.WorkspacesAPI.setMember(ws.id, chosen.id, "member"), () => setPick(""))}>{t("ws.add")}</button>
        </div>
      )}
      {err && <div className="ws-err">{err}</div>}
    </div>
  );
}
function WsSettings({ ws, onChanged, onDeleted }) {
  const [name, setName] = useState(ws.name);
  const [desc, setDesc] = useState(ws.description || "");
  const [armed, setArmed] = useState(false);
  const [saved, setSaved] = useState(false);
  const [err, setErr] = useState(null);
  const save = async () => {
    setErr(null);
    try { const r = await L.WorkspacesAPI.update(ws.id, { name: name.trim(), description: desc.trim() }); onChanged && onChanged(r); setSaved(true); setTimeout(() => setSaved(false), 1600); }
    catch (e) { setErr((e && e.message) || String(e)); }
  };
  const del = async () => {
    if (!armed) { setArmed(true); return; }
    try { await L.WorkspacesAPI.remove(ws.id); onDeleted && onDeleted(ws.id); }
    catch (e) { setErr((e && e.message) || String(e)); setArmed(false); }
  };
  return (
    <div className="ws-pane">
      <div className="field">
        <label>{t("ws.name")}</label>
        <input value={name} maxLength={80} disabled={!ws.manage} onChange={e => setName(e.target.value)} />
      </div>
      <div className="field">
        <label>{t("ws.description")}</label>
        <input value={desc} maxLength={300} disabled={!ws.manage} onChange={e => setDesc(e.target.value)} />
      </div>
      <p className="ws-note">{ws.scope === "global" ? t("ws.scopeGlobal") : t("ws.scopeUser")}</p>
      {!ws.manage && <p className="ws-note">{t("ws.settingsReadonly")}</p>}
      {ws.manage && (
        <div className="ws-row-acts">
          {ws.mayDelete !== false && <button className="btn danger" onClick={del}>{armed ? t("ws.deleteConfirm") : t("ws.delete")}</button>}
          <span style={{ flex: 1 }} />
          {saved && <span className="ws-saved">{t("ws.saved")}</span>}
          <button className="btn primary" onClick={save} disabled={!name.trim() || (name.trim() === ws.name && desc.trim() === (ws.description || ""))}>{t("ws.save")}</button>
        </div>
      )}
      {armed && <p className="ws-warn">{t("ws.deleteBody")}</p>}
      {err && <div className="ws-err">{err}</div>}
    </div>
  );
}

function App() {
  const ui = L.load();

  /* --- auth state --- */
  const [user,         setUser]         = useState(L.getCachedUser()); // show cached immediately
  /* Derived once HERE. Sidebar has its own copy of this line, and a prop that
     read `isAdmin` from App's scope was a bare undefined identifier: React does
     not warn, it throws, and a ReferenceError during render takes the entire
     tree down rather than the one control that wanted it. */
  const isAdmin = !!user && ["owner", "admin"].includes(user.role);
  const [authChecked,  setAuthChecked]  = useState(false);
  /* The origin answered nothing at all — not "signed out". Kept apart from
     `user` so an unreachable server never renders as a login prompt. */
  const [unreachable,  setUnreachable]  = useState(false);
  const [recheck,      setRecheck]      = useState(false);
  /* Dropping the worker and reloading, so the browser can show its own dialog. */
  const [reloading,    setReloading]    = useState(false);

  /* --- chat state --- */
  const [convs,    setConvs]    = useState([]);
  const [agents,   setAgents]   = useState([]);
  const [activeId, setActiveId] = useState(ui.activeId || null);
  const [activeKind, setActiveKind] = useState(ui.activeKind || "chat");   /* 'chat' | 'agent' */
  /* --- apps (modular workspace tabs) --- */
  const [apps, setApps] = useState([]);
  /* --- workspaces: the one you work in (null = General), remembered per browser --- */
  const [workspaces, setWorkspaces] = useState([]);
  const [wsLoaded, setWsLoaded] = useState(false);
  const [activeWs, setActiveWs] = useState(() => { try { return localStorage.getItem("indie.workspace") || null; } catch { return null; } });
  useEffect(() => { try { if (activeWs) localStorage.setItem("indie.workspace", activeWs); else localStorage.removeItem("indie.workspace"); } catch {} }, [activeWs]);
  const [wsPanel, setWsPanel] = useState(null);   /* { tab } open on the current workspace, or { create: true } */
  const curWs = workspaces.find(w => w.id === activeWs) || null;
  const wsId = curWs ? curWs.id : null;
  /* what belongs where you are: the workspace's own, or in General what is in none */
  const inWs = x => !!x && (x.workspaceId || null) === wsId;
  const [activeAppId, setActiveAppId] = useState(ui.activeAppId || null);
  const [showAppPicker, setShowAppPicker] = useState(false);
  const [creatingApp, setCreatingApp] = useState(null);
  const [confirm, setConfirm] = useState(null);   /* pending destructive action */
  const [showBundles, setShowBundles] = useState(null);   /* the bundle catalog: {} or { key } */
  /* Pane sizes are the user's and they persist. Their own store, because
     L.save() deliberately whitelists only the session keys. A null value means
     "back to the stylesheet default" — that's what double-clicking a divider
     does. Written on a short debounce so a drag doesn't hammer localStorage. */
  const [panes, setPanes] = useState(() => L.getJSON("indie.panes", {}) || {});
  const onPane = (k, v) => setPanes(p => ({ ...p, [k]: v }));
  const panesSaveRef = useRef(null);
  useEffect(() => {
    clearTimeout(panesSaveRef.current);
    panesSaveRef.current = setTimeout(() => L.setJSON("indie.panes", panes), 250);
    return () => clearTimeout(panesSaveRef.current);
  }, [panes]);
  const wsRef = useRef(null);         /* the app workspace, for the chat-split drag */
  const dragChat = x => {
    const r = wsRef.current && wsRef.current.getBoundingClientRect();
    if (!r) return;
    onPane("chat", Math.max(280, Math.min(Math.round(r.right - x), Math.max(320, r.width - 360))));
  };
  const [appStateTick, setAppStateTick] = useState(0);  /* agent changed some app's state */
  const [appHtmlTicks, setAppHtmlTicks] = useState({}); /* app id -> times the agent rewrote it */
  /* Apps stay MOUNTED after the user switches to a chat or an agent, hidden
     rather than torn down. Reason: an app's own memory is the only place it
     has for anything it must not persist (the iframe has no origin, so no
     localStorage, and its server-side state is shared and 256 KB).
     Unmounting on every sidebar click threw that away, so a table loaded
     from a local file was gone after one look at a chat, and its WebMCP
     tools with it. WARM_APPS bounds the iframes we keep.
     The list keeps INSERTION order and evicts the least recently used entry
     IN PLACE: React mirrors array order in the DOM, and moving an iframe
     element reloads it, which is the very thing this avoids. */
  const WARM_APPS = 4;
  const [warmApps_, setWarmApps_] = useState([]);   /* [{ id, at }], stable order */
  const warmSeq = useRef(0);
  useEffect(() => {
    if (!activeAppId) return;
    setWarmApps_(w => {
      const e = { id: activeAppId, at: ++warmSeq.current };
      const i = w.findIndex(x => x.id === activeAppId);
      if (i >= 0) { const n = w.slice(); n[i] = e; return n; }
      if (w.length < WARM_APPS) return [...w, e];
      const lru = w.reduce((m, x, k) => x.at < w[m].at ? k : m, 0);
      const n = w.slice(); n[lru] = e; return n;
    });
  }, [activeAppId]);
  const dropWarm = id => setWarmApps_(w => w.filter(x => x.id !== id));
  /* The active app counts as warm in the SAME render it becomes active, not
     one effect later, so the pane never blanks for a frame. */
  const warmApps = [...warmApps_.map(x => x.id), ...(activeAppId && !warmApps_.some(x => x.id === activeAppId) ? [activeAppId] : [])]
    .map(id => apps.find(a => a.id === id)).filter(Boolean);
  /* Sidebar tabs: foreground (interactive work) vs background (agents that
     work unattended — long runs, schedules). */
  const [sideTab, setSideTab] = useState("fg");
  const [activity, setActivity] = useState(null);       /* runs + schedules + load */
  const [activityTick, setActivityTick] = useState(0);  /* bump to refresh now */
  const [model,    setModel]    = useState(ui.model || L.DEFAULT_MODEL);
  /* Per-entry (conversation OR agent) run state, so chats and agents can run
     concurrently and you can leave one mid-turn without affecting another. */
  const [runningIds,      setRunningIds]      = useState({});   /* cid -> true while a run is in flight */
  const [reconnectingIds, setReconnectingIds] = useState({});   /* cid -> true while its stream is reconnecting */
  const [error,    setError]    = useState(null);
  const [convsLoaded, setConvsLoaded] = useState(false);
  const [agentsLoaded, setAgentsLoaded] = useState(false);
  const [endpoint, setEndpoint] = useState(localStorage.getItem("indie.endpoint") || null);
  const [provider, setProviderState] = useState(L.getProvider());
  const [navOpen,  setNavOpen]  = useState(false);
  const [preset,   setPreset]   = useState("");
  const [showRoutines, setShowRoutines] = useState(false);
  const [routinesFocus, setRoutinesFocus] = useState(null);   /* agent the panel opened from */
  const [mcpAvail, setMcpAvail] = useState(false);
  const [engineReady, setEngineReady] = useState(null);   /* agent engine status (null = unknown) */
  const [, setBrandV] = useState(0);                       /* bump to re-render when branding loads */
  const [cfgV, setCfgV] = useState(0);                     /* bump to re-ask the providers for models */

  const scrollRef = useRef(null);
  const stickRef  = useRef(true);
  const filegenRef = useRef(false);   /* was "Make file" on for the last send */
  const runsRef   = useRef(new Map()); /* cid -> { runId, ctrl } for in-flight runs */

  /* Per-entry run helpers. busy/reconnecting below reflect the ACTIVE entry. */
  const setRunning = (cid, on) => setRunningIds(m => { if (!!m[cid] === on) return m; const n = { ...m }; if (on) n[cid] = true; else delete n[cid]; return n; });
  const setReconn  = (cid, on) => setReconnectingIds(m => { if (!!m[cid] === on) return m; const n = { ...m }; if (on) n[cid] = true; else delete n[cid]; return n; });
  const busy         = !!runningIds[activeId];
  const reconnecting = !!reconnectingIds[activeId];

  const active        = activeKind === "chat" ? (convs.find(c => c.id === activeId) || null) : null;
  const activeAgent   = activeKind === "agent" ? (agents.find(a => a.id === activeId) || null) : null;
  const activeApp     = apps.find(a => a.id === activeAppId) || null;
  const appAgent      = activeApp && activeApp.agentId ? (agents.find(a => a.id === activeApp.agentId) || null) : null;
  /* Plain chat is a module, off unless a deployment turns it on: new work
     starts with an agent. Conversations from before stay readable. */
  const chatOn = L.moduleOn("chat");
  const canPickModel = isAdmin || L.membersPickModels();
  /* Lists people choose an agent from leave out the shared wiki's maintainer
     for members, as the sidebar does; docking still resolves against all. */
  const pickAgents = isAdmin ? agents : agents.filter(a => !isLibrarianAgent(a));
  /* What is on screen now, for stream handlers that outlive their render. */
  const viewRef = useRef({});
  viewRef.current = { activeKind, activeId, activeAppId };
  /* An interrupted (server-restart) run for a given agent — drives the
     Resume banner in the agent view. */
  const orphanFor = id => ((activity && activity.runs) || []).find(r => r.agentId === id && r.status === "orphaned") || null;
  const dismissOrphan = async id => {
    setActivity(a => a ? { ...a, runs: a.runs.filter(r => r.id !== id) } : a);
    try { await L.AgentsAPI.dismissRun(id); } catch {}
  };
  const curProvider   = provider || (L.providersList()[0] || {}).name;
  /* The built-in catalog is the immediate answer; the provider's own list
     replaces it as soon as it arrives. Starting from the catalog means the
     picker is never empty, and never blocks on a gateway that is slow or
     unreachable. */
  const [providerModels, setProviderModels] = useState(() => L.modelsFor(curProvider));
  const modelLabel    = (L.findModel(model) || providerModels[0] || { label: model }).label;

  /* --- persist UI state (not conversations) --- */
  useEffect(() => { L.save({ activeId, model, activeKind, activeAppId }); }, [activeId, model, activeKind, activeAppId]);

  /* Ask the provider what it serves, and only THEN judge the selection.
     Validating against the built-in catalog would throw away a perfectly good
     saved choice, because that catalog is a subset of what the gateway has. */
  useEffect(() => {
    let gone = false;
    setProviderModels(L.modelsFor(curProvider));
    L.loadModels(curProvider).then(list => {
      /* null = the provider could not be asked. Then the selection stands:
         judging it against the built-in catalog is what used to reset a saved
         model to the default on every reload. */
      if (gone || !list || !list.length) return;
      setProviderModels(list);
      setModel(m => {
        if (list.some(x => x.id === m)) return m;          /* the saved pick is real */
        const preferred = L.defaultModelFor(curProvider);   /* else this provider's own default */
        return list.some(x => x.id === preferred) ? preferred : list[0].id;
      });
    }).catch(() => {});
    return () => { gone = true; };
  }, [curProvider, cfgV]);

  /* Load the account's MCP servers (global + own) into the cache, then discover
     whether any MCP tools are available (gates the Tools toggle). */
  useEffect(() => {
    if (!user) return;
    /* this browser's skills from before move into the account, once */
    L.migrateSkills().catch(() => {});
    L.loadMcpServers().then(() => {
      if (L.toolEnabled("mcp")) L.mcpToolsList().then(r => setMcpAvail((r.tools || []).length > 0)).catch(() => {});
    });
  }, [user]);

  /* Load app-wide branding (public; works before auth) and re-render text once
     it arrives. Accent + title are applied immediately from cache on load. */
  useEffect(() => { L.loadBranding().then(() => setBrandV(v => v + 1)); }, []);

  /* Load what this DEPLOYMENT is: its providers, app templates and modules.
     Auth-gated, so it lands just after sign-in; the cached copy is applied
     synchronously at script load so a returning user never sees the built-in
     catalog first.

     This used to also drop a selected model that was not in the built-in
     catalog, which reset a perfectly good choice to the default on EVERY
     reload once the picker could offer what the gateway really serves. The
     catalog is a subset; only the provider can say what exists, so bumping
     cfgV re-asks it and that answer decides. */
  useEffect(() => {
    if (!user) return;
    L.loadConfig().then(() => { setBrandV(v => v + 1); setCfgV(v => v + 1); });
  }, [user]);

  /* Check the agent engine (Docker + image) when an agent is opened. The agent
     image is often still being PULLED when the app first answers (a fresh
     install, or an update that bumped the image tag), so while docker is up but
     the image is missing keep polling and clear the notice by itself once it
     lands — no reload. (Contributed back from the crefo deployment.) */
  useEffect(() => {
    if (!user || activeKind !== "agent" || engineReady === true) return;
    let stop = false, t = null, tries = 0;
    const check = () => L.AgentsAPI.engine().then(r => {
      if (stop) return;
      setEngineReady(!!r.ready);
      if (!r.ready && r.docker && r.image === false && ++tries < 30) t = setTimeout(check, 5000);
    }).catch(() => { if (!stop) setEngineReady(false); });
    check();
    return () => { stop = true; if (t) clearTimeout(t); };
  }, [user, activeKind, engineReady]);

  /* --- auth check + load convs on mount --- */
  const checkAuth = () => {
    setRecheck(true);
    let leaving = false;
    return L.Auth.me().then(u => {
      setUnreachable(false);
      L.clearForcedReload();    /* reached it — a later failure may reload again */
      setUser(u);
      if (u) { loadConvs(); loadAgents(); loadApps(); loadWorkspaces(); }
    }).catch(err => {
      /* Only a request that never landed means unreachable; anything else the
         server actually said is a plain "not signed in". */
      if (!L.isTransportFailure(err)) { setUnreachable(false); setUser(null); return; }
      /* The app is on screen but the origin is not answering, which means a
         worker served it from cache and the browser never got to show why.
         Get out of the way rather than explain: drop the worker and reload, so
         the next navigation is a real request and the browser's own
         certificate dialog is what the user sees. */
      if (L.canForceNetworkReload()) { leaving = true; setReloading(true); L.forceNetworkReload(); return; }
      setUnreachable(true);
    }).finally(() => {
      if (leaving) return;      /* the page is going away — don't paint a screen */
      setAuthChecked(true);
      setRecheck(false);
    });
  };
  useEffect(() => { checkAuth(); }, []);

  /* Open the right conversation when a routine notification is tapped — whether
     the app was already open (SW postMessage) or launched fresh (#conv= hash). */
  useEffect(() => {
    const openConv = id => { if (id) { setActiveId(id); setNavOpen(false); setShowRoutines(false); loadConvs(); } };
    const m = (location.hash || "").match(/conv=([^&]+)/);
    if (m) { openConv(decodeURIComponent(m[1])); history.replaceState(null, "", location.pathname); }
    if (!("serviceWorker" in navigator)) return;
    const onMsg = e => { if (e.data && e.data.type === "open-conversation") openConv(e.data.convId); };
    navigator.serviceWorker.addEventListener("message", onMsg);
    return () => navigator.serviceWorker.removeEventListener("message", onMsg);
  }, []);

  const loadConvs = async () => {
    try {
      const apiConvs = await L.ConvsAPI.list();
      setConvs(apiConvs);
    } catch (e) {
      console.error(t("err.loadConvs"), e);
    } finally {
      setConvsLoaded(true);   /* gates reattach until the DB convs are in state */
    }
  };
  const loadAgents = async () => {
    /* List omits transcripts (kept light); preserve any already-loaded messages. */
    try {
      const list = await L.AgentsAPI.list();
      setAgents(prev => list.map(a => { const p = prev.find(x => x.id === a.id); return p && p.messages ? { ...a, messages: p.messages } : a; }));
    } catch (e) { console.error(t("err.loadAgents"), e); }
    finally { setAgentsLoaded(true); }
  };
  const loadApps = async () => {
    try { setApps(await L.AppsAPI.list()); }
    catch (e) { console.error(t("err.loadApps"), e); }
  };
  const loadWorkspaces = async () => {
    try { const r = await L.WorkspacesAPI.list(); setWorkspaces(r.workspaces || []); }
    catch (e) { console.error("Couldn't load the workspaces:", e); }
    finally { setWsLoaded(true); }
  };

  /* Background activity feed: powers the BACKGROUND tab's status lines, the
     tab badge, and orphan/resume banners. Polls faster while anything runs. */
  useEffect(() => {
    if (!user) return;
    let stop = false, timer = null;
    const tick = async () => {
      try {
        const a = await L.AgentsAPI.activity();
        if (!stop) setActivity(a);
        /* Poll faster while ANYTHING is running, not just your own work: the
           box indicator reports other people's turns, and deciding the cadence
           from your own runs alone left it up to 25s stale in both directions
           — showing a turn that had finished, and missing one that had not
           started. */
        const mineBusy = a && a.runs && a.runs.some(r => r.status === "running" || r.status === "queued");
        const busyAny = mineBusy || !!(a && a.box && a.box.total);
        if (!stop) timer = setTimeout(tick, busyAny ? 6000 : 25000);
      } catch { if (!stop) timer = setTimeout(tick, 30000); }
    };
    tick();
    return () => { stop = true; clearTimeout(timer); };
  }, [user, activityTick]);

  /* A routine changed (created/paused/retargeted/deleted): the server derives
     `background` from active agent routines + services, so refresh the agents
     list and activity — an agent may have just been promoted or demoted. */
  const onRoutinesChanged = () => { loadAgents(); setActivityTick(t => t + 1); };
  /* ONE routines panel for the whole app. Opening it from an agent just scopes
     the initial filter to that agent; it is the same list and the same editor
     the sidebar opens, so chat and agent schedules never drift apart. */
  const [routinesNew, setRoutinesNew] = useState(false);   /* open straight into a new routine */
  const [routinesApp, setRoutinesApp] = useState(null);   /* the app a new routine keeps up to date */
  const openRoutines = (agentId = null, startNew = false, appId = null) => { setRoutinesFocus(agentId); setRoutinesNew(!!startNew); setRoutinesApp(appId); setShowRoutines(true); setNavOpen(false); };
  const loadAgentFull = async id => {
    try {
      const full = await L.AgentsAPI.get(id);
      /* liveCanvases reset: the turn's canvases are now persisted on messages. */
      setAgents(as => as.some(a => a.id === id) ? as.map(a => a.id === id ? { ...a, ...full, liveCanvases: [] } : a) : [{ ...full, liveCanvases: [] }, ...as]);
    } catch (e) {
      /* Stale selection (agent deleted elsewhere): drop it and reset the view. */
      if (e && e.status === 404) {
        setAgents(as => as.filter(a => a.id !== id));
        setActiveId(cur => cur === id ? null : cur);
      } else console.error(t("err.loadAgent"), e);
    }
  };

  /* --- autoscroll while streaming --- */
  const scrollToBottom = useCallback(() => {
    const el = scrollRef.current; if (!el) return;
    el.scrollTop = el.scrollHeight;
  }, []);
  /* The chat transcript uses the SAME scroller as the agent view, handing it
     the App's own refs so the streaming callbacks below keep working against
     stickRef exactly as they did. Must stay above the auth early-returns — it
     is a hook. */
  const chatScroll = useTranscriptScroll(activeKind + ":" + activeId, scrollRef, stickRef);

  /* --- handlers --- */
  const handleLogin = async u => {
    setUser(u);
    await loadConvs();
    loadAgents(); loadApps(); loadWorkspaces();
  };

  const handleLogout = async () => {
    await L.Auth.logout();
    setUser(null);
    setConvs([]); setAgents([]); setApps([]); setWorkspaces([]); setWsLoaded(false);
    setActiveId(null); setActiveKind("chat"); setActiveAppId(null); setWarmApps_([]);
  };

  /* With plain chat off this is the start page: New agent lands here and the
     agent is made with the first message, so an idle click leaves no empty
     agent behind. */
  const newChat = () => { draftAgentRef.current = null; setActiveKind("chat"); setActiveId(null); setActiveAppId(null); setNavOpen(false); setError(null); };

  const selectEntry = (id, kind) => { setActiveKind(kind); setActiveId(id); setActiveAppId(null); setNavOpen(false); setError(null); if (kind === "agent" && !runsRef.current.has(id)) loadAgentFull(id); };
  /* Switch workspace. What is open stays open only if it belongs there;
     otherwise the start page, where a new agent is made in the workspace. */
  const switchWorkspace = id => {
    setActiveWs(id || null); setNavOpen(false); setError(null);
    const cur = activeAppId ? apps.find(a => a.id === activeAppId) : activeKind === "agent" ? agents.find(a => a.id === activeId) : null;
    if (!cur || (cur.workspaceId || null) !== (id || null)) {
      draftAgentRef.current = null;
      setActiveAppId(null); setActiveKind("chat"); setActiveId(null);
    }
  };
  /* Moving something takes you along, so it stays open in front of you. An
     app takes its own agent with it (the one docked to it, if it is yours). */
  const moveAgentToWs = async (id, to) => {
    try {
      const r = await L.AgentsAPI.update(id, { workspaceId: to });
      setAgents(as => as.map(a => a.id === id ? { ...a, ...r } : a));
      setActiveWs(to || null);
    } catch (e) { setError((e && e.message) || t("ws.moveFailed")); }
  };
  const moveAppToWs = async (id, to) => {
    const app = apps.find(a => a.id === id);
    try {
      const r = await L.AppsAPI.update(id, { workspaceId: to });
      setApps(as => as.map(a => a.id === id ? { ...a, ...r } : a));
      const ag = app && app.agentId ? agents.find(a => a.id === app.agentId) : null;
      if (ag && ag.scope !== "global") {
        const ar = await L.AgentsAPI.update(ag.id, { workspaceId: to }).catch(() => null);
        if (ar) setAgents(as => as.map(a => a.id === ag.id ? { ...a, ...ar } : a));
      }
      setActiveWs(to || null);
    } catch (e) { setError((e && e.message) || t("ws.moveFailed")); }
  };
  const createWorkspace = async w => {
    const r = await L.WorkspacesAPI.create(w);
    setWsPanel(null);
    await loadWorkspaces();
    loadApps();          /* its own Wiki app */
    switchWorkspace(r.id);
  };
  /* Something opened from elsewhere (a notification, the routines list, a
     reload) that lives in another workspace takes you to that workspace. */
  useEffect(() => {
    if (!wsLoaded) return;
    const cur = activeAppId ? apps.find(a => a.id === activeAppId) : activeKind === "agent" ? agents.find(a => a.id === activeId) : null;
    if (!cur) return;
    const home = cur.workspaceId || null;
    if (home !== (activeWs || null) && (!home || workspaces.some(w => w.id === home))) setActiveWs(home);
  }, [wsLoaded, activeId, activeKind, activeAppId, agentsLoaded, apps.length]);
  /* A remembered workspace that is gone (deleted, or no longer shared). */
  useEffect(() => { if (wsLoaded && activeWs && !workspaces.some(w => w.id === activeWs)) setActiveWs(null); }, [wsLoaded, workspaces]);

  /* --- apps: open / create / link agent / delete --- */
  /* A bundle was added: open its app with its agent beside it (or the agent), where the setup card waits. */
  const bundleAdded = async r => {
    setShowBundles(null); setError(null); setNavOpen(false);
    await loadAgents();
    await loadApps();
    if (r.appId) setActiveAppId(r.appId); else setActiveAppId(null);
    setActiveKind("agent"); setActiveId(r.agentId);
    loadAgentFull(r.agentId);
  };
  /* Removing a bundle took its agent, app and routines: let them go here too. */
  const bundleRemoved = agentId => {
    setAgents(as => as.filter(a => a.id !== agentId));
    if (activeId === agentId) { setActiveId(null); setActiveKind("agent"); }
    setActiveAppId(null);
    loadAgents(); loadApps();
  };
  const selectApp = (id, row) => {
    const app = row || apps.find(a => a.id === id);
    setActiveAppId(id); setNavOpen(false); setError(null);
    /* Focus the linked agent so the docked chat, busy state, stop and
       re-attach all point at the right thread. */
    if (app && app.agentId && agents.some(a => a.id === app.agentId)) {
      setActiveKind("agent"); setActiveId(app.agentId);
      if (!runsRef.current.has(app.agentId)) loadAgentFull(app.agentId);
    }
  };
  /* A new app comes with its own agent, docked. Nothing happens in an app
     without one (it is who builds and changes it), and asking people to pick
     from a list of unrelated agents was where they got stuck. The docked-agent
     menu still swaps it for another. If making the agent fails, the app opens
     on the picker as before. */
  const creatingRef = useRef(false);
  const createApp = async (template, global) => {
    if (creatingRef.current) return;
    creatingRef.current = true;
    setCreatingApp(template);
    try {
      const a = await L.AppsAPI.create({ template, ...(global ? { scope: "global" } : {}), ...(wsId ? { workspaceId: wsId } : {}) });
      let agentId = null;
      try {
        const ag = await L.AgentsAPI.create({ name: (a.name || "App") + " agent", description: platformDesc.forApp(a.name), connections: "chosen", ...(await agentBackendSnapshot()), ...(wsId ? { workspaceId: wsId } : {}) });
        await L.AppsAPI.update(a.id, { agentId: ag.id });
        agentId = ag.id;
        await loadAgents();
      } catch (e) { console.warn("Couldn't create the app's agent:", e); }
      setShowAppPicker(false);
      await loadApps();
      /* Not selectApp: its agent lookup reads this render's list, which does
         not have the agent made a moment ago. */
      setActiveAppId(a.id); setNavOpen(false); setError(null);
      if (agentId) { setActiveKind("agent"); setActiveId(agentId); loadAgentFull(agentId); }
    } catch (e) { setError((e && e.message) || t("app.createFailed")); }
    finally { setCreatingApp(null); creatingRef.current = false; }
  };
  const deleteApp = async id => {
    setApps(as => as.filter(a => a.id !== id));
    if (id === activeAppId) setActiveAppId(null);
    dropWarm(id);
    try { await L.AppsAPI.remove(id); }
    catch (e) { setError((e && e.message) || t("app.deleteFailed")); loadApps(); }
  };
  const askDeleteApp = id => {
    const a = (apps || []).find(x => x.id === id);
    if (!a) return;
    setConfirm({
      title: t("app.deleteTitle", { name: appName(a) || t("app.thisApp") }),
      confirmLabel: t("app.delete"),
      body: (<>
        <p>{t("app.deleteBody")}</p>
        {a.scope === "global" && <p className="warn-line">{tb("app.deleteGlobalWarn")}</p>}
      </>),
      onConfirm: () => deleteApp(id),
    });
  };
  /* User-only code lock: locked apps can't be rewritten/deleted by the agent. */
  /* Scope is admin-only and server-enforced; this just applies the answer and
     hands the warnings back to the control that asked. */
  const setAppScope = async (id, scope) => {
    try {
      const r = await L.AppsAPI.update(id, { scope });
      setApps(as => as.map(a => a.id === id ? { ...a, ...r } : a));
      loadApps();
      return r;
    } catch (e) { setError((e && e.message) || t("app.scopeFailed")); return null; }
  };
  const toggleAppLock = async locked => {
    if (!activeAppId) return;
    setApps(as => as.map(a => a.id === activeAppId ? { ...a, locked } : a));   /* optimistic */
    try { await L.AppsAPI.update(activeAppId, { locked }); }
    catch (e) { setApps(as => as.map(a => a.id === activeAppId ? { ...a, locked: !locked } : a)); setError((e && e.message) || t("app.lockFailed")); }
  };
  /* Dock an agent to the open app — or pass null to disconnect it. On a global
     app the link is per user (server-side link table), so this only ever
     changes what THIS user has docked. */
  const linkAppAgent = async (agentId) => {
    if (!activeAppId) return;
    try {
      await L.AppsAPI.update(activeAppId, { agentId: agentId || null });
      setApps(as => as.map(a => a.id === activeAppId ? { ...a, agentId: agentId || null } : a));
      if (agentId) {
        setActiveKind("agent"); setActiveId(agentId);
        if (!runsRef.current.has(agentId)) loadAgentFull(agentId);
      }
    } catch (e) { setError((e && e.message) || t("app.linkFailed")); }
  };
  const newAgentForApp = async () => {
    try {
      const a = await L.AgentsAPI.create({ name: ((activeApp && activeApp.name) || "App") + " agent",
                                           description: platformDesc.forApp(activeApp && activeApp.name), connections: "chosen",
                                           ...(await agentBackendSnapshot()),
                                           ...(activeApp && activeApp.workspaceId ? { workspaceId: activeApp.workspaceId } : {}) });
      await loadAgents();
      await linkAppAgent(a.id);
    } catch (e) { setError((e && e.message) || t("agent.createFailed")); }
  };
  /* An agent's app_* tool call landed (SSE): refresh the tabs; nudge the open
     app — state changes flow via the versioned poll, html rewrites reload. */
  const onAppEvent = e => {
    /* An agent made a new app (the server docks it to that agent). If the
       person is watching that agent with no app open, open the new one beside
       the chat, so "build me an app" ends with the app on screen rather than
       a tab to go and find. viewRef: this handler is the closure of the render
       that started the run. */
    if (e && e.action === "created" && e.id) {
      L.AppsAPI.list().then(list => {
        setApps(list);
        const v = viewRef.current, row = list.find(a => a.id === e.id);
        if (row && !v.activeAppId && v.activeKind === "agent" && row.agentId && row.agentId === v.activeId) {
          setActiveAppId(row.id); setNavOpen(false);
        }
      }).catch(err => console.error(t("err.loadApps"), err));
      return;
    }
    loadApps();
    if (!e) return;
    if (e.action === "state") setAppStateTick(t => t + 1);
    /* Only the rewritten app reloads; the other mounted ones keep their memory. */
    else if (e.action === "updated") setAppHtmlTicks(m => ({ ...m, [e.id || "*"]: (m[e.id || "*"] || 0) + 1 }));
    else if (e.action === "deleted") { setActiveAppId(cur => cur === e.id ? null : cur); dropWarm(e.id); }
  };

  /* Agents run on the admin-selected tool-capable backend (Settings → Agent
     engine); snapshot it at creation so the UI shows the right model, and the
     server re-pins every turn anyway. */
  const agentBackendSnapshot = async () => {
    try { const b = await L.AgentsAPI.backend(); return { model: b.model, endpoint: b.endpoint, url: b.url }; }
    catch {
      /* Offline fallback: this deployment's OWN first provider, never a
         hardcoded host — the server re-pins the real backend on the next turn
         regardless, so this only decides the label shown until then. */
      const ep = (L.ENDPOINTS || [])[0];
      if (!ep) return {};
      return { model: (ep.models[0] || {}).id, endpoint: ep.name, url: ep.base + ep.path };
    }
  };
  /* The engine and model the next new agent starts on, picked on the start
     page and remembered on this device, so New agent starts where the last
     one did. Only applied for someone who may pick models at all. */
  const NEW_ENGINE_KEY = "indie.newAgentEngine";
  const [newEngine, setNewEngine] = useState(() => {
    try { const v = JSON.parse(localStorage.getItem(NEW_ENGINE_KEY) || "null"); if (v && typeof v === "object") return { backend: v.backend || null, modelPin: v.modelPin || null }; } catch {}
    return { backend: null, modelPin: null };
  });
  const pickNewEngine = p => {
    const v = { backend: p.backend || null, modelPin: p.model || null };
    setNewEngine(v);
    try { localStorage.setItem(NEW_ENGINE_KEY, JSON.stringify(v)); } catch {}
  };
  /* The agent the start page is about to use. It is made on demand: by the
     first file attached (which needs a workspace) or by sending, once, and a
     fresh start page (New agent) forgets it. */
  const draftAgentRef = useRef(null);
  const draftAgent = () => draftAgentRef.current || (draftAgentRef.current =
    (async () => L.AgentsAPI.create({ name: "New agent", connections: "chosen", ...(await agentBackendSnapshot()), ...(wsId ? { workspaceId: wsId } : {}) }))()
      .catch(e => { draftAgentRef.current = null; throw e; }));
  const ensureDraftAgent = () => draftAgent().then(a => a.id);
  /* The landing's composer: the first message makes the agent (or takes the
     one its first file made) and starts its first turn, with the engine picked
     on the start page and the switches set in its box. */
  const startAgent = async (text, files, priv, flags) => {
    setError(null);
    try {
      let a = await draftAgent();
      draftAgentRef.current = null;
      if (canPickModel && ((a.backend || null) !== newEngine.backend || (a.modelPin || null) !== newEngine.modelPin))
        a = { ...a, ...(await L.AgentsAPI.update(a.id, { backend: newEngine.backend, model: newEngine.modelPin })) };
      /* its own box opens with the switches the start page's had */
      const sw = { useWiki: !!(flags && flags.useWiki), toolsOff: (flags && flags.toolsOff) || [], mcpOff: (flags && flags.mcpOff) || [] };
      try { localStorage.setItem("indie.agent.flags." + a.id, JSON.stringify({ wiki: sw.useWiki, toolsOff: sw.toolsOff, mcpOff: sw.mcpOff })); } catch {}
      const row = { ...a, messages: [] };
      setAgents(as => [row, ...as.filter(x => x.id !== a.id)]);
      setActiveKind("agent"); setActiveId(a.id); setActiveAppId(null); setNavOpen(false);
      agentSend(row, text, files || [], priv, { ...sw, useTools: true });
    } catch (e) { setError((e && e.message) || t("agent.createFailed")); }
  };
  const newAgent = async () => {
    setError(null);
    try {
      /* Placeholder name — the server auto-names it after the first turn. */
      const a = await L.AgentsAPI.create({ name: "New agent", connections: "chosen", ...(await agentBackendSnapshot()), ...(wsId ? { workspaceId: wsId } : {}) });
      await loadAgents();
      setActiveKind("agent"); setActiveId(a.id); setActiveAppId(null); setNavOpen(false);
    } catch (e) { setError((e && e.message) || "Couldn't create agent"); }
  };

  const deleteConv = async id => {
    setConvs(cs => cs.filter(c => c.id !== id));
    if (id === activeId && activeKind === "chat") setActiveId(null);
    try { await L.ConvsAPI.delete(id); } catch (e) { console.error("Delete failed:", e); }
  };
  const deleteAgent = async id => {
    setAgents(as => as.filter(a => a.id !== id));
    if (id === activeId && activeKind === "agent") { setActiveId(null); setActiveKind("chat"); }
    /* The server has the last word (it refuses the wiki maintainer), so put the
       row back and say why rather than leaving the sidebar lying. */
    try { await L.AgentsAPI.remove(id); }
    catch (e) { setError((e && e.message) || t("agent.deleteFailed")); loadAgents(); }
  };
  /* Deleting an agent is not just a row: its workspace volume, its services and
     its loops go with it. Spell that out before doing it. */
  const askDeleteAgent = id => {
    const a = (agents || []).find(x => x.id === id);
    if (!a) return;
    const svc   = ((activity && activity.services)  || []).filter(s => s.agentId === id && s.status === "running").length;
    const loops = ((activity && activity.schedules) || []).filter(s => s.agentId === id && s.enabled).length;
    setConfirm({
      title: t("agent.deleteTitle", { name: agentName(a) || t("agent.thisAgent") }),
      confirmLabel: t("agent.delete"),
      body: (<>
        <p>{t("agent.deleteBody")}</p>
        {(svc > 0 || loops > 0) && (
          <p className="warn-line">
            {svc > 0 && <>{t("agent.deleteSvcWarn", { n: svc })} </>}
            {loops > 0 && <>{t("agent.deleteLoopWarn", { n: loops })}</>}
          </p>
        )}
        {a.scope === "global" && <p className="warn-line">{tb("agent.deleteGlobalWarn")}</p>}
      </>),
      onConfirm: () => deleteAgent(id),
    });
  };
  const renameAgent = async (id, name) => {
    setAgents(as => as.map(a => a.id === id ? { ...a, name } : a));
    try { await L.AgentsAPI.update(id, { name }); } catch (e) { console.error("Rename agent failed:", e); }
  };
  /* instructions an agent proposed for itself, applied in the person's own request */
  const setAgentInstructions = async (id, instructions) => {
    const r = await L.AgentsAPI.update(id, { instructions });
    setAgents(as => as.map(a => a.id === id ? { ...a, instructions: r.instructions != null ? r.instructions : instructions } : a));
  };
  /* Which engine this agent runs on. null = follow the deployment default.
     The server returns the refreshed row, so the model and endpoint the
     transcript labels itself with move at the same time. */
  /* `patch` is {backend} or {model} — the two halves of an agent's engine. */
  const setAgentBackend = async (id, patch) => {
    const optimistic = "backend" in patch ? { backend: patch.backend, modelPin: null } : { modelPin: patch.model };
    setAgents(as => as.map(a => a.id === id ? { ...a, ...optimistic } : a));
    try {
      const r = await L.AgentsAPI.update(id, patch);
      setAgents(as => as.map(a => a.id === id ? { ...a, ...r } : a));
    } catch (e) { setError((e && e.message) || "Couldn't change the engine"); loadAgents(); }
  };

  /* Messages waiting for a busy agent, held on the server (runOrQueue):
     agent id -> { items, held, error }. */
  const [queues, setQueues] = useState({});
  const [reattachTick, setReattachTick] = useState(0);
  /* What an agent asked and is waiting for (a question, or an approval): agent id -> [ask]. */
  const [asks, setAsks] = useState({});
  const refreshAsks = cid => L.AgentsAPI.asks(cid)
    .then(r => setAsks(m => ({ ...m, [cid]: r.asks || [] })))
    .catch(() => {});
  const answerAsk = async (cid, askId, body) => {
    setAsks(m => ({ ...m, [cid]: (m[cid] || []).filter(a => a.id !== askId) }));
    try { const r = await L.AgentsAPI.answerAsk(cid, askId, body); if (r && r.routine) onRoutinesChanged(); }
    catch (e) { setError((e && e.message) || t("ask.failed")); refreshAsks(cid); }
  };
  const seenRunsRef = useRef({});   /* agent id -> newest finished run the open transcript includes */
  /* A model that says nothing (server.js, model priority). modelWatchRef:
     agent id -> how the turn this browser follows is doing: when it really
     started (the `started` event, so a queue is not counted), the model's last
     word, open tool calls (a running tool is not the model's silence). After
     modelWaitSec without a word (three times that once it has said something)
     the server tests the model quietly: answering, it is only slow and nothing
     is shown; not answering, modelHints[agent id] offers the first model of
     the priority list that answered its test. The same after a turn failed
     (offerAfterFailure). With one model in the list there is nothing to
     offer, and nothing is tested (`alone`). */
  const [modelHints, setModelHints] = useState({});
  const modelWatchRef = useRef(new Map());
  const setModelHint = (cid, h) => setModelHints(m => { if (!h && !m[cid]) return m; const n = { ...m }; if (h) n[cid] = h; else delete n[cid]; return n; });
  useEffect(() => {
    if (!user) return;
    const iv = setInterval(() => {
      const wait = L.modelWaitSec() * 1000;
      for (const [cid, w] of modelWatchRef.current) {
        if (w.queued || w.tools > 0 || w.checking || w.hinted || w.alone) continue;
        const from = w.lastAt || w.startedAt;
        if (!from || Date.now() - from < (w.said ? 3 * wait : wait)) continue;
        w.checking = true;
        L.AgentsAPI.modelCheck(cid).then(r => {
          const cur = modelWatchRef.current.get(cid);
          if (!cur || cur.runId !== w.runId) return;           /* that turn is over */
          cur.checking = false;
          if (!(r.tried && r.tried.length)) { cur.alone = true; return; }
          if (r.current && r.current.ok) { cur.lastAt = Date.now(); return; }   /* there, just slow */
          cur.hinted = true;
          setModelHint(cid, { runId: w.runId, since: from, current: r.current, suggest: r.suggest, mayPersist: !!r.mayPersist });
        }).catch(() => { const cur = modelWatchRef.current.get(cid); if (cur && cur.runId === w.runId) { cur.checking = false; cur.lastAt = Date.now(); } });
      }
    }, 5000);
    return () => clearInterval(iv);
  }, [user]);
  /* A turn that failed: was it the model? Then the next one that answers. */
  const offerAfterFailure = (cid, runId, since) => L.AgentsAPI.modelCheck(cid).then(r => {
    if (!r || !r.suggest || !r.current || r.current.ok !== false || runsRef.current.has(cid)) return;
    setModelHint(cid, { runId, since, current: r.current, suggest: r.suggest, mayPersist: !!r.mayPersist, failed: true });
  }).catch(() => {});
  const modelHintAct = {
    /* keep waiting: ask again after another full wait (after a failure: dismiss) */
    wait: cid => { const w = modelWatchRef.current.get(cid); if (w) { w.hinted = false; w.lastAt = Date.now(); } setModelHint(cid, null); },
    /* stop the turn that waits, switch the agent, and send the same message again */
    switchTo: async cid => {
      const h = modelHints[cid]; const ag = agents.find(a => a.id === cid);
      if (!h || !h.suggest || !ag) return;
      const ask = [...(ag.messages || [])].reverse().find(m => m.role === "user");
      setModelHint(cid, { ...h, switching: true, error: null });
      try {
        const row = await L.AgentsAPI.engineFallback(cid, h.suggest);
        /* The server must have the stop BEFORE the message below arrives: a
           stopped turn holds its queue, except for what was sent after the
           stop (run.stopAt), which is this message. Then as Stop does. A
           turn that failed has nothing to stop. */
        const cur = runsRef.current.get(cid);
        if (cur) { if (cur.runId) await L.stopRun(cur.runId); stopEntry(cid, "agent"); }
        setAgents(as => as.map(a => a.id === cid ? { ...a, ...row, messages: a.messages } : a));
        setModelHint(cid, null);
        const f = agentFlags(cid);
        if (ask && ask.content) agentSend({ ...ag, ...row }, ask.content, [], false, { useWiki: f.wiki, toolsOff: f.toolsOff, mcpOff: f.mcpOff, useTools: true });
      } catch (e) { setModelHint(cid, { ...h, switching: false, error: (e && e.message) || String(e) }); }
    },
  };
  /* A conversation that no longer fits the model's window (a turn failed
     with kind context-full): start it afresh, or move the agent to a model of
     the priority list with a larger window; then the same message again. */
  const contextAct = (() => {
    const resend = (ag, row) => {
      const ask = [...(ag.messages || [])].reverse().find(m => m.role === "user");
      const f = agentFlags(ag.id);
      if (ask && ask.content) agentSend({ ...ag, ...(row || {}) }, ask.content, [], false, { useWiki: f.wiki, toolsOff: f.toolsOff, mcpOff: f.mcpOff, useTools: true });
    };
    return {
      fresh: async cid => {
        const ag = agents.find(a => a.id === cid); if (!ag) return;
        try { await L.AgentsAPI.fresh(cid); resend(ag); }
        catch (e) { setError((e && e.message) || String(e)); }
      },
      larger: async (cid, entry) => {
        const ag = agents.find(a => a.id === cid); if (!ag) return;
        try {
          const row = await L.AgentsAPI.engineFallback(cid, entry);
          setAgents(as => as.map(a => a.id === cid ? { ...a, ...row, messages: a.messages } : a));
          resend(ag, row);
        } catch (e) { setError((e && e.message) || String(e)); }
      },
    };
  })();
  const refreshQueue = cid => L.AgentsAPI.queue(cid)
    .then(q => setQueues(m => ({ ...m, [cid]: q })))
    .catch(() => {});

  /* Follow one agent turn into the transcript: the person's message (unless
     the caller already put it there), an empty answer, then pi's tool steps
     and answer as they stream. Used by a send, by a queued message that
     started by itself, by Send now and by Continue, and by the re-attach after
     a reload. The stream is the run's, not the view's: leaving the agent does
     not stop it. */
  const followAgentRun = (cid, runId, { userText, attachments, ts, scheduled, model: runModel, insert } = {}) => {
    const now = Date.now();
    if (insert) {
      const userMsg = { role: "user", content: userText || "", ts: ts || now, attachments: attachments && attachments.length ? attachments : undefined, scheduled: scheduled || undefined };
      setAgents(as => as.map(a => a.id === cid
        ? { ...a, messages: [...(a.messages || []), userMsg, { role: "assistant", content: "", ts: now, model: runModel || a.model }], updated: now }
        : a));
    }
    if (viewRef.current.activeId === cid) { stickRef.current = true; requestAnimationFrame(scrollToBottom); }
    const controller = new AbortController();
    runsRef.current.set(cid, { runId, ctrl: controller });
    setRunning(cid, true);
    let acc = "", accR = "", steps = [], props = [], next = null;
    /* the model watcher (modelWatchRef): from now, unless a queue says otherwise */
    const watch = { runId, startedAt: Date.now(), lastAt: null, tools: 0, said: false, queued: false, checking: false, hinted: false };
    modelWatchRef.current.set(cid, watch);
    setModelHint(cid, null);   /* one about an earlier turn */
    const heard = () => {
      watch.lastAt = Date.now(); watch.said = true;
      /* it answers after all: whatever was suggested no longer applies */
      if (watch.hinted) { watch.hinted = false; setModelHint(cid, null); }
    };
    const unwatch = () => { if (modelWatchRef.current.get(cid) === watch) modelWatchRef.current.delete(cid); setModelHints(m => m[cid] && m[cid].runId === runId ? (({ [cid]: _, ...rest }) => rest)(m) : m); };
    const patchBot = patch => setAgents(as => as.map(a => {
      if (a.id !== cid) return a;
      const m = (a.messages || []).slice();
      for (let i = m.length - 1; i >= 0; i--) { if (m[i].role === "assistant") { m[i] = { ...m[i], ...patch }; break; } }
      return { ...a, messages: m, updated: Date.now() };
    }));
    const stick = () => { if (viewRef.current.activeId === cid && stickRef.current) requestAnimationFrame(scrollToBottom); };
    /* only if this run is still the one we follow: a newer one may have taken over */
    const finish = () => {
      const cur = runsRef.current.get(cid);
      if (cur && cur.runId === runId) { runsRef.current.delete(cid); setRunning(cid, false); setReconn(cid, false); }
    };
    L.attachRun(runId, {
      signal: controller.signal,
      onTool: e => { heard(); watch.tools++; steps = [...steps, { name: e.name, arguments: e.arguments, result: null }]; patchBot({ toolSteps: steps, queuedPos: undefined }); stick(); },
      onToolResult: e => { watch.tools = Math.max(0, watch.tools - 1); watch.lastAt = Date.now(); for (let i = steps.length - 1; i >= 0; i--) { if (steps[i].name === e.name && steps[i].result === null) { steps[i] = { ...steps[i], result: e.result, isError: e.isError, ...(e.ui ? { ui: e.ui } : {}) }; break; } } steps = [...steps]; patchBot({ toolSteps: steps }); },
      onToken: tok => { heard(); acc += tok; patchBot({ content: acc, queuedPos: undefined }); stick(); },
      onReasoning: r => { heard(); accR += r; patchBot({ reasoning: accR, queuedPos: undefined }); },
      onQueued: pos => { watch.queued = true; patchBot({ queuedPos: pos }); },
      onStarted: at => { watch.queued = false; watch.startedAt = Math.min(Date.now(), Number(at) || Date.now()); },
      onReplay: () => { acc = ""; accR = ""; steps = []; props = []; patchBot({ content: "", reasoning: undefined, toolSteps: undefined, proposals: undefined }); },
      onProposal: p => { props = [...props, p]; patchBot({ proposals: props }); },
      /* the files of the person's memory this turn wrote (server.js, completeAgentRun) */
      onMemory: files => patchBot({ memory: files }),
      onRedaction: e => patchBot({ privacy: true, redactions: e.count, redactionTypes: e.types }),
      onCanvas: c => setAgents(as => as.map(a => a.id === cid ? { ...a, liveCanvases: [...(a.liveCanvases || []), c] } : a)),
      /* a summary that failed summarised nothing: not counted */
      onCompaction: e => patchBot(e.phase === "start"
        ? { compacting: true }
        : (e.aborted || e.failed) ? { compacting: false }
        : { compacting: false, compactions: [{ reason: e.reason, tokensBefore: e.tokensBefore }] }),
      /* a scheduled run that had no room starts over without the conversation:
         what the first attempt streamed is not this turn's answer */
      onFresh: e => { acc = ""; accR = ""; steps = []; patchBot({ content: "", reasoning: undefined, toolSteps: undefined, compactions: undefined, compacting: false, freshStart: e.why || "retry" }); },
      onContext: e => patchBot({ context: { used: e.used, window: e.window, percent: e.percent } }),
      onApp: onAppEvent,
      onRenamed: name => setAgents(as => as.map(a => a.id === cid ? { ...a, name } : a)),
      onReconnecting: () => setReconn(cid, true),
      onReconnected: () => setReconn(cid, false),
      onFinal: txt => { acc = txt || acc; patchBot({ content: acc, queuedPos: undefined }); },
      /* the queued message that started as this turn finished */
      onNext: e => { next = e; },
      /* the agent asks, and waits; or its question was settled */
      onAsk: a => { if (a && a.status === "open") setAsks(m => ({ ...m, [cid]: [...(m[cid] || []).filter(x => x.id !== a.id), a] })); },
      onAnswered: e => setAsks(m => ({ ...m, [cid]: (m[cid] || []).filter(x => x.id !== e.id) })),
      onStopped: () => { unwatch(); patchBot({ stopped: true, queuedPos: undefined }); finish(); refreshQueue(cid); refreshAsks(cid); },
      onError: err => {
        unwatch(); finish(); refreshQueue(cid); refreshAsks(cid);
        if (err && err.name === "AbortError") return;
        patchBot({ error: (err && err.message) || "Agent run failed", errorKind: (err && err.kind) || undefined, errorInfo: (err && err.info) || undefined, queuedPos: undefined });
        /* explained on the turn itself, with what helps; the model is fine */
        if (err && err.kind === "context-full") return;
        setError((err && err.message) || "Agent run failed");
        offerAfterFailure(cid, runId, watch.startedAt);
      },
      onDone: async () => {
        unwatch(); finish(); setActivityTick(t => t + 1); refreshQueue(cid); refreshAsks(cid);
        /* The transcript first, so the next turn's message lands after this
           turn's answer rather than inside the reload. */
        await loadAgentFull(cid);
        if (next && next.runId && !next.other && !runsRef.current.has(cid))
          followAgentRun(cid, next.runId, { userText: next.userText, attachments: next.attachments, ts: next.ts, scheduled: next.scheduled, insert: true });
      },
    });
  };
  /* A run the server started for this agent while we were not following it
     (Send now, Continue): take over from whatever stream was attached. */
  const adoptStartedRun = async (cid, brief) => {
    const cur = runsRef.current.get(cid);
    if (cur && cur.runId === brief.runId) return;
    if (cur) { try { cur.ctrl && cur.ctrl.abort(); } catch {} runsRef.current.delete(cid); setRunning(cid, false); }
    await loadAgentFull(cid);
    followAgentRun(cid, brief.runId, { ...brief, insert: true });
  };
  /* A message queued while we follow no turn on this agent (sent just after
     Stop, or the agent was busy with a routine): poll briefly for the turn it
     becomes, so its answer streams here instead of appearing later. */
  const watchForRun = async cid => {
    for (let i = 0; i < 40; i++) {
      await new Promise(r => setTimeout(r, i < 10 ? 700 : 1500));
      if (runsRef.current.has(cid)) return;
      const info = await L.activeRunInfo(cid);
      if (info && !runsRef.current.has(cid)) { await adoptStartedRun(cid, info); return; }
    }
  };

  /* Run an agent turn (pi in its container). Streams pi's tool steps + answer
     into the agent's transcript via the same durable-run plumbing as chat.
     While the agent is busy the message joins its queue instead (the server
     decides: it may also queue a message we thought would run now, when a
     routine just started a turn). */
  const agentSend = async (agent, text, files, priv, flags) => {
    const t = (text || "").trim();
    const atts = Array.isArray(files) ? files : [];
    if (!t && !atts.length) return;
    const redact = priv ? L.privacyMode() : "off";
    setError(null);
    const cid = agent.id;
    const now = Date.now();

    /* The model prompt prepends each uploaded file's extracted text (capped) and
       notes that the real file lives in the workspace; the displayed user turn
       stays clean (text + attachment chips). */
    const CAP = 12000;
    const blocks = atts.map(f => {
      const body = (f.text || "").slice(0, CAP);
      const more = (f.text || "").length > CAP ? "\n…(truncated: read the full file at " + f.path + " in your workspace)" : "";
      return "--- Uploaded file: " + f.path + " (saved in your workspace) ---\n" + (body || "(binary or empty: read it from the workspace)") + more + "\n--- end of " + f.path + " ---";
    }).join("\n\n");
    const prompt = [takeViewContext(cid), blocks, t].filter(Boolean).join("\n\n") || t;
    const attachMeta = atts.map(f => ({ name: f.name, size: f.size }));
    /* what Edit puts back in the box if this ends up queued */
    const draft = { text: t, files: atts.map(f => ({ name: f.name, size: f.size, path: f.path, text: f.text, truncated: f.truncated })) };

    const following = runsRef.current.has(cid) || !!runningIds[cid];
    if (!following) {
      const userMsg = { role: "user", content: t, ts: now, attachments: attachMeta.length ? attachMeta : undefined };
      const botMsg  = { role: "assistant", content: "", ts: now, model: agent.model };
      setAgents(as => as.map(a => a.id === cid ? { ...a, messages: [...(a.messages || []), userMsg, botMsg], updated: now } : a));
      stickRef.current = true; requestAnimationFrame(scrollToBottom);
      setRunning(cid, true);
      runsRef.current.set(cid, { runId: null, ctrl: new AbortController() });
    }
    /* take back the optimistic turn: the message was queued, or never sent */
    const unsend = () => {
      if (following) return;
      setAgents(as => as.map(a => {
        if (a.id !== cid) return a;
        const m = (a.messages || []).slice();
        if (m.length && m[m.length - 1].role === "assistant" && !m[m.length - 1].content) m.pop();
        if (m.length && m[m.length - 1].role === "user" && m[m.length - 1].ts === now) m.pop();
        return { ...a, messages: m };
      }));
      const cur = runsRef.current.get(cid);
      if (cur && !cur.runId) runsRef.current.delete(cid);
      setRunning(cid, false);
    };
    /* If this agent is docked beside an open app, tell the run which one so
       the model's app_* tools target it (the app row's `locked` flag decides
       whether code edits are allowed, server-enforced). */
    const appId = (activeApp && activeApp.agentId === cid) ? activeApp.id : undefined;
    let r;
    try {
      r = await L.AgentsAPI.run(cid, prompt, L.enabledSkills(), L.enabledMcpServers(),
        { userText: t, attachments: attachMeta, redact, appId, queue: true, draft,
          /* the person's memory: asked for by the app, so an API caller sees no change (server.js, turnMemoryMode) */
          useMemory: true,
          useWiki: !!(flags && flags.useWiki), useTools: !(flags && flags.useTools === false),
          toolsOff: (flags && flags.toolsOff) || agentFlags(cid).toolsOff, mcpOff: (flags && flags.mcpOff) || agentFlags(cid).mcpOff });
    } catch (e) { if (!following) { const cur = runsRef.current.get(cid); if (cur && !cur.runId) runsRef.current.delete(cid); setRunning(cid, false); } setError((e && e.message) || "Couldn't start the agent."); return; }
    if (r.queued) {
      unsend();
      setQueues(m => ({ ...m, [cid]: { items: r.items || [], held: !!r.held, error: r.error || null } }));
      if (!runsRef.current.has(cid)) watchForRun(cid);
      return;
    }
    /* The server says which model this turn runs on; our copy of the agent may predate a change of engine. */
    if (r.model) setAgents(as => as.map(a => a.id === cid ? { ...a, model: r.model } : a));
    if (following) {
      /* we thought it busy, the server ran it at once: follow it like a queued turn */
      await adoptStartedRun(cid, { runId: r.runId, userText: t, attachments: attachMeta, ts: now, model: r.model });
      return;
    }
    if (r.model) setAgents(as => as.map(a => {
      if (a.id !== cid) return a;
      const m = (a.messages || []).slice();
      for (let i = m.length - 1; i >= 0; i--) { if (m[i].role === "assistant") { m[i] = { ...m[i], model: r.model }; break; } }
      return { ...a, messages: m };
    }));
    followAgentRun(cid, r.runId, {});
  };
  /* The queue's own controls, from the agent's message box. */
  const queueAct = {
    now: async (cid, qid) => {
      try {
        const r = await L.AgentsAPI.queueNow(cid, qid);
        setQueues(m => ({ ...m, [cid]: r }));
        if (r.started && r.started.runId) await adoptStartedRun(cid, r.started);
      } catch (e) { setError((e && e.message) || t("queue.failed")); refreshQueue(cid); }
    },
    resume: async cid => {
      try {
        const r = await L.AgentsAPI.queueResume(cid);
        setQueues(m => ({ ...m, [cid]: r }));
        if (r.started && r.started.runId) await adoptStartedRun(cid, r.started);
      } catch (e) { setError((e && e.message) || t("queue.failed")); refreshQueue(cid); }
    },
    remove: async (cid, qid) => {
      try { const r = await L.AgentsAPI.queueRemove(cid, qid); setQueues(m => ({ ...m, [cid]: r })); return true; }
      catch (e) { setError((e && e.message) || t("queue.failed")); refreshQueue(cid); return false; }
    },
    clear: async cid => {
      try { const r = await L.AgentsAPI.queueClear(cid); setQueues(m => ({ ...m, [cid]: r })); }
      catch (e) { setError((e && e.message) || t("queue.failed")); refreshQueue(cid); }
    },
  };

  /* --- send message --- */
  /* a tool's view in this chat puts a message into the box (ui/message) */
  useEffect(() => {
    const on = e => { const d = e.detail || {}; if (d.text && d.convId && d.convId === activeId && activeKind !== "agent") setPreset(d.text); };
    window.addEventListener("indie:compose", on);
    return () => window.removeEventListener("indie:compose", on);
  }, [activeId, activeKind]);
  const send = async (textRaw, opts = {}) => {
    setError(null);
    const fileList   = opts.files || [];
    /* A file can give us BOTH: an image carries its picture and whatever OCR
       read off it, and a scanned PDF with no text at all still hands over page
       images. So these are two independent harvests over the same list, not a
       split into two kinds of file. */
    const textFiles  = fileList.filter(f => f.text);
    const attachMeta = textFiles.map(f => ({ name: f.name, size: f.size, type: f.type }));
    const images     = fileList.flatMap(f => [
      ...(f.dataUrl ? [{ name: f.name, dataUrl: f.dataUrl }] : []),
      ...((f.pages || []).map((u, i) => ({ name: f.name + " (page " + (i + 1) + ")", dataUrl: u }))),
    ]);

    /* Treat an activeId that isn't in the loaded list (e.g. a stale/deleted id
       persisted in localStorage) as a fresh conversation. */
    const existing = activeId ? convs.find(c => c.id === activeId) : null;
    let convId  = existing ? activeId : null;
    const isNew = !convId;

    /* Capture prior messages now, before any state mutations */
    const priorMessages = existing ? (existing.messages || []) : [];

    /* Web search now runs server-side (the run/routine paths share it), so the
       key never reaches the client and routines can search too. We just pass a
       flag and mark the message when the server emits a `searched` event. */
    const doSearch  = !!opts.search;
    const privacy   = !!opts.privacy;
    const redact    = privacy ? L.privacyMode() : "off";
    const userMsg   = { role: "user", content: textRaw, ts: Date.now(), attachments: attachMeta, images, privacy };
    const convTitle = (textRaw || (attachMeta[0] && attachMeta[0].name) || (images[0] && images[0].name) || "New chat").slice(0, 48).replace(/\n/g, " ");

    /* Create or update conv in local state */
    if (!convId) {
      convId = L.uid();
      setConvs(cs => [{ id: convId, title: convTitle, created: Date.now(), updated: Date.now(), messages: [userMsg] }, ...cs]);
      setActiveId(convId);
    } else {
      setConvs(cs => cs.map(c => c.id === convId
        ? { ...c, updated: Date.now(), messages: [...c.messages, userMsg] }
        : c));
    }

    const botTs  = Date.now();
    const botMsg = { role: "assistant", content: "", ts: botTs, model };
    setConvs(cs => cs.map(c => c.id === convId
      ? { ...c, messages: [...c.messages, botMsg] }
      : c));

    stickRef.current = true;
    requestAnimationFrame(scrollToBottom);

    /* Text file contents (MarkItDown) become context; images go to the vision
       path. apiContent() returns a plain string when there are no images, or an
       OpenAI vision content array (text + image_url parts) when there are. */
    const apiContent = (textContent, imgs) => {
      if (!imgs || !imgs.length) return textContent;
      const arr = [];
      if (textContent) arr.push({ type: "text", text: textContent });
      for (const im of imgs) arr.push({ type: "image_url", image_url: { url: im.dataUrl } });
      return arr;
    };
    const fileBlocks = textFiles
      .map(f => "--- Attached file: " + f.name + " (converted to Markdown) ---\n"
              + f.text
              + "\n--- end of " + f.name + " ---")
      .join("\n\n");
    const parts = [];
    /* what a tool's view of this chat wants the model to know (ui/update-model-context) */
    const viewCtx = takeViewContext(convId);
    if (viewCtx)    parts.push(viewCtx);
    if (fileBlocks) parts.push(fileBlocks);
    if (textRaw)    parts.push(textRaw);
    const combinedText = parts.join("\n\n");

    /* Build API payload (vision-aware; prior turns keep their images too) */
    const payload = [...priorMessages, userMsg]
      .filter(m => m.content !== "" || (m.images && m.images.length) || m.role === "user")
      .map(m => ({ role: m.role, content: apiContent(m === userMsg ? combinedText : m.content, m.images) }));

    /* Teach the model the file-block protocol when "Make file" is on. Remember
       the setting so regenerate/edit re-run with the same capability. */
    filegenRef.current = !!opts.filegen;
    if (opts.filegen) payload.unshift({ role: "system", content: L.filegenSystemPrompt() });

    const controller = new AbortController();
    runsRef.current.set(convId, { runId: null, ctrl: controller });
    setRunning(convId, true);

    const cid = convId; /* capture for closure */
    let acc = "";
    let accR = "";   /* accumulated reasoning (reasoning_content) for this turn */
    let served = { endpoint: null, model: null }; /* the provider + model that ACTUALLY answered */
    let mcpSteps = []; /* MCP tool-call steps for this turn */

    const patchBot = patch => setConvs(cs => cs.map(c => {
      if (c.id !== cid) return c;
      const msgs = c.messages.slice();
      for (let i = msgs.length - 1; i >= 0; i--) {
        if (msgs[i].role === "assistant") { msgs[i] = { ...msgs[i], ...patch }; break; }
      }
      return { ...c, messages: msgs, updated: Date.now() };
    }));

    const dropEmptyBot = () => setConvs(cs => cs.map(c => {
      if (c.id !== cid) return c;
      const msgs = c.messages.slice();
      const last = msgs[msgs.length - 1];
      if (last && last.role === "assistant" && !last.content && !(last.toolSteps || []).length && !last.reasoning) msgs.pop();
      return { ...c, messages: msgs };
    }));

    /* Pick the model endpoint (selected provider first; must be a valid URL). */
    const isHttp = u => { try { return /^https?:$/.test(new URL(u).protocol); } catch { return false; } };
    const provs = L.providersList();
    const selName = L.getProvider();
    const ep = (selName && provs.find(e => e.name === selName && isHttp((e.base || "") + (e.path || ""))))
            || provs.find(e => isHttp((e.base || "") + (e.path || "")));
    if (!ep) { setRunning(cid, false); runsRef.current.delete(cid); setError("No valid model endpoint — check Connection settings."); dropEmptyBot(); return; }
    served.endpoint = ep.name;
    patchBot({ endpoint: ep.name });

    /* Start a DURABLE server-side run, then attach to its event stream. The run
       keeps generating and persists the answer itself even if we disconnect, so
       closing the tab / switching windows / a dropped network never loses it. */
    let runId = null;
    try {
      const r = await L.startChatRun({
        url: ep.base + ep.path, model, messages: payload, redact,
        servers: L.enabledMcpServers(), mcp: !!opts.mcp, search: doSearch,
        skills: opts.mcp ? L.enabledSkills() : [],
        convId: cid, isNew, title: convTitle,
        persistMessages: [...priorMessages, userMsg],
        endpoint: ep.name, assistantTs: botTs,
      });
      runId = r.runId;
    } catch (e) {
      setRunning(cid, false); runsRef.current.delete(cid);
      setError((e && e.message) || "Couldn't start the request.");
      dropEmptyBot();
      return;
    }
    runsRef.current.set(cid, { runId, ctrl: controller });
    setEndpoint(ep.name);

    await L.attachRun(runId, {
      signal: controller.signal,
      onTool: e => {
        mcpSteps = [...mcpSteps, { name: e.name, arguments: e.arguments, result: null }];
        patchBot({ toolSteps: mcpSteps });
        if (stickRef.current) requestAnimationFrame(scrollToBottom);
      },
      onToolResult: e => {
        for (let i = mcpSteps.length - 1; i >= 0; i--) {
          if (mcpSteps[i].name === e.name && mcpSteps[i].result === null) {
            mcpSteps[i] = { ...mcpSteps[i], result: e.result, isError: e.isError, ...(e.ui ? { ui: e.ui } : {}) }; break;
          }
        }
        mcpSteps = [...mcpSteps];
        patchBot({ toolSteps: mcpSteps });
      },
      onToken: t => { acc += t; patchBot({ content: acc }); if (stickRef.current) requestAnimationFrame(scrollToBottom); },
      onReasoning: r => { accR += r; patchBot({ reasoning: accR }); if (stickRef.current) requestAnimationFrame(scrollToBottom); },
      onReset: () => { acc = ""; patchBot({ content: "" }); },   /* mid-answer drop: clear partial, the retry re-streams */
      onSearched: () => patchBot({ searched: true }),
      onRedaction: e => patchBot({ privacy: true, redactions: e.count, redactionTypes: e.types }),
      onReplay: () => { acc = ""; accR = ""; mcpSteps = []; patchBot({ content: "", reasoning: undefined, toolSteps: undefined, searched: undefined }); },
      onReconnecting: () => setReconn(cid, true),
      onReconnected: () => setReconn(cid, false),
      onServed: m => { served.model = m; patchBot({ servedModel: m }); },
      onFinal: txt => { acc = txt || acc; patchBot({ content: acc }); },
      onStopped: () => { patchBot({ stopped: true }); /* keep whatever streamed */ },
      onGone: () => setError("This answer expired before it could be recovered. Please send it again."),
      onError: err => {
        setRunning(cid, false); setReconn(cid, false); runsRef.current.delete(cid);
        if (err && err.name === "AbortError") return;   /* we detached on purpose */
        setError((err && err.message) || "Request failed");
      },
      onDone: () => {
        setRunning(cid, false); setReconn(cid, false); runsRef.current.delete(cid);
        setEndpoint(served.endpoint);
        if (!acc && !accR && !mcpSteps.length) dropEmptyBot();   /* server persisted; nothing came back */
      },
    });
  };

  /* Stop is a deliberate cancel of the ACTIVE entry's run: abort our view AND
     tell the server to end it (closing the tab leaves it running in the bg). */
  const stopEntry = (cid, kind) => {
    const r = runsRef.current.get(cid);
    if (r) { if (r.runId) L.stopRun(r.runId); if (r.ctrl) r.ctrl.abort(); runsRef.current.delete(cid); }
    setRunning(cid, false); setReconn(cid, false);
    if (kind === "agent") modelWatchRef.current.delete(cid);
    /* Keep the partial answer/reasoning and flag it stopped (server persists the
       same, so it survives a reload; the next turn keeps this as context). */
    const markStopped = list => list.map(x => {
      if (x.id !== cid) return x;
      const msgs = (x.messages || []).slice();
      for (let i = msgs.length - 1; i >= 0; i--) { if (msgs[i].role === "assistant") { msgs[i] = { ...msgs[i], stopped: true }; break; } }
      return { ...x, messages: msgs };
    });
    if (kind === "agent") { setAgents(markStopped); settleQueue(cid); }
    else setConvs(markStopped);
  };
  const stop = () => stopEntry(activeId, activeKind);
  /* After Stop the server still has to wind the turn down (the container gets
     a few seconds) before it holds the queue or starts a message sent since.
     We no longer follow that stream, so ask until the agent is free. */
  const settleQueue = async cid => {
    for (let i = 0; i < 40; i++) {
      await new Promise(r => setTimeout(r, 800));
      let q; try { q = await L.AgentsAPI.queue(cid); } catch { return; }
      setQueues(m => ({ ...m, [cid]: q }));
      if (!q.busy) return;
    }
  };

  /* Re-attach to a still-running background run when an entry is opened (after a
     reload, a new window, another device, or just navigating back to it). Works
     for BOTH chats and agents. The server replays the run's full event buffer,
     so we rebuild the live answer and tail it. If we're already streaming this
     entry in-process (runsRef has it), we skip — no double attach. */
  useEffect(() => {
    if (!user || !activeId) return;
    const cid = activeId, kind = activeKind;
    if (kind === "chat" ? !convsLoaded : !agentsLoaded) return;
    if (runsRef.current.has(cid)) return;   /* already streaming in-process */
    /* An agent turn's message is only in the transcript once the turn is done,
       so the server says what was asked and it goes in above the answer (the
       old way cleared the previous answer and streamed this turn into it).
       Followed like any other turn: leaving the agent does not detach it. */
    if (kind === "agent") {
      let cancelled = false;
      (async () => {
        try { await loadAgentFull(cid); } catch {}
        if (cancelled || runsRef.current.has(cid)) return;
        const info = await L.activeRunInfo(cid);
        if (cancelled || !info || runsRef.current.has(cid)) return;
        followAgentRun(cid, info.runId, { userText: info.userText, attachments: info.attachments, ts: info.ts, scheduled: info.scheduled, insert: true });
      })();
      return () => { cancelled = true; };
    }
    const ctrl = new AbortController();
    let cancelled = false;
    (async () => {
      if (cancelled || runsRef.current.has(cid)) return;
      const runId = await L.activeRun(cid);
      if (cancelled || !runId || runsRef.current.has(cid)) return;
      runsRef.current.set(cid, { runId, ctrl });
      setRunning(cid, true);
      const store = kind === "agent" ? setAgents : setConvs;
      /* Ensure a trailing assistant bubble exists, cleared so the replay rebuilds it. */
      store(list => list.map(x => {
        if (x.id !== cid) return x;
        const msgs = (x.messages || []).slice();
        const last = msgs[msgs.length - 1];
        if (!last || last.role !== "assistant") msgs.push({ role: "assistant", content: "", ts: Date.now(), model });
        else msgs[msgs.length - 1] = { ...last, content: "", reasoning: undefined, toolSteps: undefined };
        return { ...x, messages: msgs };
      }));
      let acc = "", accR = "", steps = [], props = [];
      const patchBot = patch => store(list => list.map(x => {
        if (x.id !== cid) return x;
        const msgs = (x.messages || []).slice();
        for (let i = msgs.length - 1; i >= 0; i--) { if (msgs[i].role === "assistant") { msgs[i] = { ...msgs[i], ...patch }; break; } }
        return { ...x, messages: msgs, updated: Date.now() };
      }));
      const cleanup = () => { setRunning(cid, false); setReconn(cid, false); const cur = runsRef.current.get(cid); if (cur && cur.runId === runId) runsRef.current.delete(cid); };
      await L.attachRun(runId, {
        signal: ctrl.signal,
        onTool: e => { steps = [...steps, { name: e.name, arguments: e.arguments, result: null }]; patchBot({ toolSteps: steps }); },
        onToolResult: e => { for (let i = steps.length - 1; i >= 0; i--) { if (steps[i].name === e.name && steps[i].result === null) { steps[i] = { ...steps[i], result: e.result, isError: e.isError, ...(e.ui ? { ui: e.ui } : {}) }; break; } } steps = [...steps]; patchBot({ toolSteps: steps }); },
        onToken: t => { acc += t; patchBot({ content: acc }); },
        onReasoning: r => { accR += r; patchBot({ reasoning: accR }); },
        onReset: () => { acc = ""; patchBot({ content: "" }); },
        onSearched: () => patchBot({ searched: true }),
        onRedaction: e => patchBot({ privacy: true, redactions: e.count, redactionTypes: e.types }),
        onCanvas: c => { if (kind === "agent") setAgents(as => as.map(a => a.id === cid ? { ...a, liveCanvases: [...(a.liveCanvases || []), c] } : a)); },
        onCompaction: e => patchBot(e.phase === "start"
          ? { compacting: true }
          : (e.aborted || e.failed) ? { compacting: false }
          : { compacting: false, compactions: [{ reason: e.reason, tokensBefore: e.tokensBefore }] }),
        onFresh: e => { acc = ""; accR = ""; steps = []; patchBot({ content: "", reasoning: undefined, toolSteps: undefined, compactions: undefined, compacting: false, freshStart: e.why || "retry" }); },
        onContext: e => patchBot({ context: { used: e.used, window: e.window, percent: e.percent } }),
        onApp: onAppEvent,
        onQueued: pos => patchBot({ queuedPos: pos }),
        onRenamed: name => { if (kind === "agent") setAgents(as => as.map(a => a.id === cid ? { ...a, name } : a)); },
        onReplay: () => { acc = ""; accR = ""; steps = []; props = []; patchBot({ content: "", reasoning: undefined, toolSteps: undefined, searched: undefined, proposals: undefined }); },
        onProposal: p => { props = [...props, p]; patchBot({ proposals: props }); },
        /* the files of the person's memory this turn wrote (server.js, completeAgentRun) */
        onMemory: files => patchBot({ memory: files }),
        onReconnecting: () => setReconn(cid, true),
        onReconnected: () => setReconn(cid, false),
        onServed: m => patchBot({ servedModel: m }),
        onFinal: txt => { acc = txt || acc; patchBot({ content: acc }); },
        onStopped: () => { patchBot({ stopped: true }); cleanup(); },
        onError: () => { cleanup(); },
        onDone: () => { cleanup(); if (kind === "agent") loadAgentFull(cid); },
      });
    })();
    return () => { cancelled = true; ctrl.abort(); };
  }, [user, activeId, activeKind, convsLoaded, agentsLoaded, reattachTick]);

  /* The open agent's queue, when it opens and whenever the activity feed says
     it changed somewhere else (a routine queued a turn, another tab); and a
     turn the server started on its own while this agent is on screen gets
     followed here too. */
  useEffect(() => { if (user && activeKind === "agent" && activeId) { refreshQueue(activeId); refreshAsks(activeId); } }, [user, activeKind, activeId]);
  /* What the transcript just opened includes: the runs the last look had seen
     finish. Taken when the agent OPENS, not at the next look: a routine that
     ran and finished between opening and that look (seconds, then up to 25 s
     of quiet polling) set the mark itself and never appeared until a reload. */
  useEffect(() => {
    if (activeKind !== "agent" || !activeId) return;
    seenRunsRef.current[activeId] = ((activity && activity.runs) || [])
      .filter(r => r.agentId === activeId && r.finished).reduce((m, r) => Math.max(m, r.finished), 0);
  }, [activeKind, activeId]);
  useEffect(() => {
    if (!activity || activeKind !== "agent" || !activeId) return;
    const q = (activity.queues || []).find(x => x.agentId === activeId);
    const known = queues[activeId];
    if (known && ((known.items || []).length !== (q ? q.n : 0) || !!known.held !== !!(q && q.held))) refreshQueue(activeId);
    const live = (activity.runs || []).some(r => r.agentId === activeId && (r.status === "running" || r.status === "queued"));
    if (live && !runsRef.current.has(activeId)) setReattachTick(n => n + 1);
    const nAsks = (activity.asks || []).filter(a => a.agentId === activeId).length;
    if (nAsks !== (asks[activeId] || []).length) refreshAsks(activeId);
    /* ...and one that started and finished between two looks (a quick
       routine): its turn is in the transcript now, so fetch that */
    const done = (activity.runs || []).filter(r => r.agentId === activeId && r.finished).reduce((m, r) => Math.max(m, r.finished), 0);
    const seen = seenRunsRef.current[activeId];
    if (seen === undefined || done < seen) seenRunsRef.current[activeId] = done;
    else if (done > seen && !runsRef.current.has(activeId)) { seenRunsRef.current[activeId] = done; loadAgentFull(activeId); }
  }, [activity]);

  /* ---- edit & regenerate ---- */
  /* OpenAI content for a stored message: string, or vision array if it has images */
  const apiContentFor = m => {
    if (!m.images || !m.images.length) return m.content;
    const arr = [];
    if (m.content) arr.push({ type: "text", text: m.content });
    for (const im of m.images) arr.push({ type: "image_url", image_url: { url: im.dataUrl } });
    return arr;
  };

  /* Re-run the assistant from a base message list (ending in a user message).
     Replaces the trailing assistant turn. Shared by regenerate + edit. */
  const streamReply = async (cid, baseMessages, redact) => {
    setError(null);
    const botTs  = Date.now();
    const botMsg = { role: "assistant", content: "", ts: botTs, model };
    setConvs(cs => cs.map(c => c.id === cid ? { ...c, messages: [...baseMessages, botMsg], updated: Date.now() } : c));
    stickRef.current = true; requestAnimationFrame(scrollToBottom);

    const payload = baseMessages
      .filter(m => m.content !== "" || (m.images && m.images.length) || m.role === "user")
      .map(m => ({ role: m.role, content: apiContentFor(m) }));
    if (filegenRef.current) payload.unshift({ role: "system", content: L.filegenSystemPrompt() });

    const controller = new AbortController(); runsRef.current.set(cid, { runId: null, ctrl: controller }); setRunning(cid, true);
    let acc = ""; let accR = ""; let served = { endpoint: null, model: null };

    const patchBot = patch => setConvs(cs => cs.map(c => {
      if (c.id !== cid) return c;
      const msgs = c.messages.slice();
      for (let i = msgs.length - 1; i >= 0; i--) if (msgs[i].role === "assistant") { msgs[i] = { ...msgs[i], ...patch }; break; }
      return { ...c, messages: msgs, updated: Date.now() };
    }));
    const flush = () => patchBot({ content: acc });
    const persist = () => {
      if (!acc) return;
      const finalMsgs = [...baseMessages, { role: "assistant", content: acc, ts: botTs, model, endpoint: served.endpoint, servedModel: served.model || model, reasoning: accR || undefined }];
      L.ConvsAPI.update(cid, { messages: finalMsgs }).catch(e => console.error("Update conv failed:", e));
    };

    await L.streamChat({
      model, messages: payload, redact, signal: controller.signal,
      onToken: t => { acc += t; flush(); },
      onReasoning: r => { accR += r; patchBot({ reasoning: accR }); if (stickRef.current) requestAnimationFrame(scrollToBottom); },
      onDone: info => {
        const ep = info && info.endpoint; const sm = (info && info.model) || null;
        served = { endpoint: ep, model: sm };
        setEndpoint(ep); setRunning(cid, false); runsRef.current.delete(cid);
        setConvs(cs => cs.map(c => {
          if (c.id !== cid) return c;
          const msgs = c.messages.slice();
          for (let i = msgs.length - 1; i >= 0; i--) if (msgs[i].role === "assistant") { msgs[i] = { ...msgs[i], content: acc, endpoint: ep, servedModel: sm || msgs[i].model }; break; }
          return { ...c, messages: msgs };
        }));
        persist();
      },
      onError: err => {
        setRunning(cid, false); runsRef.current.delete(cid);
        if (err && err.name === "AbortError") { persist(); return; }
        setError((err && err.message) || "Request failed");
        if (!acc) setConvs(cs => cs.map(c => {
          if (c.id !== cid) return c;
          const msgs = c.messages.slice();
          if (msgs.length && msgs[msgs.length - 1].role === "assistant" && !msgs[msgs.length - 1].content) msgs.pop();
          return { ...c, messages: msgs };
        }));
      },
    });
  };

  const regenerateLast = cid => {
    if (busy) return;
    const conv = convs.find(c => c.id === cid); if (!conv) return;
    const msgs = conv.messages;
    let cut = msgs.length;
    while (cut > 0 && msgs[cut - 1].role === "assistant") cut--;   /* drop trailing assistant turn */
    if (cut === 0) return;
    const base = msgs.slice(0, cut);
    const lastUser = [...base].reverse().find(m => m.role === "user");
    streamReply(cid, base, lastUser && lastUser.privacy ? L.privacyMode() : "off");
  };

  const editAndResend = (cid, index, newText) => {
    if (busy) return;
    const conv = convs.find(c => c.id === cid); if (!conv) return;
    const msgs = conv.messages;
    if (index < 0 || index >= msgs.length || msgs[index].role !== "user") return;
    const editedUser = { ...msgs[index], content: newText };
    const base = [...msgs.slice(0, index), editedUser];
    streamReply(cid, base, editedUser.privacy ? L.privacyMode() : "off");
  };

  /* ---- render ---- */

  /* About to reload past the cached app — say nothing, the browser is next. */
  if (reloading) return <ReloadingScreen />;

  /* Show loading until auth is verified to avoid flash of wrong screen */
  if (!authChecked) {
    return (
      <div style={{ height: "100%", display: "grid", placeItems: "center", background: "var(--canvas)" }}>
        <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-4)", letterSpacing: "0.1em", textTransform: "uppercase" }}>
          {t("common.loading")}
        </span>
      </div>
    );
  }

  /* Unreachable outranks "no user": the cached user is still valid, we simply
     cannot confirm it, and offering a sign-in form that cannot leave the
     browser is what made an expired certificate read as a bad password. */
  if (unreachable) return <UnreachableScreen offline={navigator.onLine === false} onRetry={checkAuth} retrying={recheck} />;

  if (!user) return <LoginScreen onLogin={handleLogin} />;

  const msgs = active ? active.messages : [];

  return (
    <div className={"app " + (navOpen ? "nav-open" : "")}
         style={{
           "--side-w": panes.side ? panes.side + "px" : undefined,
           "--apps-h": panes.apps ? panes.apps + "px" : undefined,
           "--chat-w": panes.chat ? panes.chat + "px" : undefined,
         }}>
      <div className="scrim" onClick={() => setNavOpen(false)} />
      <Sidebar
        convs={wsId ? [] : convs} agents={agents.filter(inWs)} activeId={activeId} activeKind={activeKind}
        onSelect={selectEntry}
        onNew={newChat} onNewAgent={chatOn ? newAgent : newChat} onDelete={deleteConv} onDeleteAgent={askDeleteAgent}
        apps={apps.filter(inWs)} activeAppId={activeAppId} onSelectApp={selectApp}
        workspaces={workspaces} curWs={curWs} onSwitchWs={switchWorkspace}
        onNewWs={() => { setNavOpen(false); setWsPanel({ create: true }); }}
        onWsPanel={tab => { setNavOpen(false); setWsPanel({ tab }); }}
        onNewApp={() => { setNavOpen(false); createApp("blank"); }}
        onNewAppFromTemplate={() => { setShowAppPicker(true); setNavOpen(false); }} appBusy={!!creatingApp} onDeleteApp={askDeleteApp}
        onNewFromBundle={() => { setShowBundles({}); setNavOpen(false); }}
        user={user} onLogout={handleLogout}
        onRoutines={() => openRoutines(null)} onNewRoutine={() => openRoutines(null, true)} chatOn={chatOn}
        activity={activity} sideTab={sideTab} onSideTab={setSideTab}
        panes={panes} onPane={onPane}
      />
      <div className="main">
        {/* Every recently opened app keeps its pane; only the active one is
            shown, the rest sit hidden with their iframe (and its memory,
            state poll and WebMCP bridge) intact. The docked chat is rendered
            for the active app alone: it follows the active agent. */}
        {warmApps.map(a => {
          const on = !!activeApp && a.id === activeApp.id;
          const ag = a.agentId ? (agents.find(x => x.id === a.agentId) || null) : null;
          return (
          <div key={a.id} className="appws" hidden={!on} ref={on ? wsRef : null}>
            <AppWorkspace app={a} busy={!!(ag && runningIds[ag.id])}
                          appStateTick={appStateTick}
                          appHtmlTick={(appHtmlTicks[a.id] || 0) + (appHtmlTicks["*"] || 0)}
                          locked={!!a.locked} onLock={toggleAppLock}
                          onMenu={() => setNavOpen(true)}
                          agents={pickAgents.filter(x => (x.workspaceId || null) === (a.workspaceId || null))} dockedAgent={ag}
                          onLinkAgent={linkAppAgent} onNewAgent={newAgentForApp}
                          isAdmin={isAdmin} onSetScope={scope => setAppScope(a.id, scope)}
                          workspaces={workspaces} onMoveWs={moveAppToWs}
                          box={activity && activity.box}
                          routines={((activity && activity.schedules) || []).filter(r => r.appId === a.id)}
                          onSchedule={ag ? (has => has ? openRoutines(ag.id) : openRoutines(ag.id, true, a.id)) : null}
                          onAsk={ag ? (text => agentSend(ag, text, [], false)) : null} />
            {on && (<>
            <Splitter axis="v" label={t("split.appAgent")}
                      onDrag={x => dragChat(x)}
                      onNudge={d => {
                        const r = wsRef.current && wsRef.current.getBoundingClientRect();
                        if (r) dragChat(r.right - ((panes.chat || Math.round(r.width * 0.3)) + d));
                      }}
                      onReset={() => onPane("chat", null)} />
            <div className="appws-chat">
              {appAgent ? (
                <AgentView box={activity && activity.box} agent={appAgent} dockedApp={appName(a) || t("app.thisApp")} canPickModel={canPickModel} onMenu={() => setNavOpen(true)} onRename={renameAgent} onSetBackend={setAgentBackend} onInstructions={setAgentInstructions}
                           busy={busy} reconnecting={reconnecting} engineReady={engineReady}
                           orphan={orphanFor(appAgent.id)} onDismissOrphan={dismissOrphan}
                           onOpenRoutines={openRoutines} queue={queues[appAgent.id]} queueAct={queueAct}
                           asks={asks[appAgent.id]} onAnswerAsk={answerAsk}
                           modelHint={modelHints[appAgent.id]} modelHintAct={modelHintAct} contextAct={contextAct} isAdmin={isAdmin}
                           setConfirm={setConfirm} onOpenApp={id => selectApp(id)} onBundleRemoved={bundleRemoved} onAppData={() => setAppStateTick(x => x + 1)}
                           onSend={(text, files, priv, flags) => agentSend(appAgent, text, files, priv, flags)} onStop={stop} />
              ) : (
                <AppAgentPicker agents={pickAgents.filter(x => (x.workspaceId || null) === (a.workspaceId || null))} onPick={linkAppAgent} onNew={newAgentForApp} />
              )}
            </div>
            </>)}
          </div>
          );
        })}
        {activeApp ? null : activeKind === "agent" && activeAgent ? (
          <AgentView box={activity && activity.box} agent={activeAgent} canPickModel={canPickModel} onMenu={() => setNavOpen(true)} onRename={renameAgent} onSetBackend={setAgentBackend} onInstructions={setAgentInstructions}
                     workspaces={workspaces} isAdmin={isAdmin} onMoveWs={moveAgentToWs}
                     busy={busy} reconnecting={reconnecting} engineReady={engineReady}
                     orphan={orphanFor(activeAgent.id)} onDismissOrphan={dismissOrphan}
                     onOpenRoutines={openRoutines} queue={queues[activeAgent.id]} queueAct={queueAct}
                     asks={asks[activeAgent.id]} onAnswerAsk={answerAsk}
                     modelHint={modelHints[activeAgent.id]} modelHintAct={modelHintAct} contextAct={contextAct}
                     setConfirm={setConfirm} onOpenApp={id => selectApp(id)} onBundleRemoved={bundleRemoved} onAppData={() => setAppStateTick(x => x + 1)}
                     onSend={(text, files, priv, flags) => agentSend(activeAgent, text, files, priv, flags)} onStop={stop} />
        ) : !chatOn && !active ? (
          <AgentStart onStart={startAgent} ensureAgent={ensureDraftAgent} engineReady={engineReady}
                      ws={curWs} onWsPanel={tab => setWsPanel({ tab })}
                      onNewApp={() => createApp("blank")} appBusy={!!creatingApp}
                      onMenu={() => setNavOpen(true)} box={activity && activity.box}
                      error={error} onDismissError={() => setError(null)}
                      canPickModel={canPickModel} engine={newEngine} onEngine={pickNewEngine}
                      onBundle={key => setShowBundles(key ? { key } : {})} />
        ) : (<>
        <div className="topbar">
          <div style={{ display: "flex", alignItems: "center", minWidth: 0 }}>
            <button className="menu-btn" onClick={() => setNavOpen(true)}><MenuIcon /></button>
            <div className="topbar-title">
              {active
                ? <><span className="tt-kind">{t("nav.chat")}</span><span className="tt-name" title={active.title}>{active.title}</span></>
                : <><span className="tt-kind">{t("topbar.new")}</span><span className="tt-name">{t("topbar.startConversation")}</span></>}
            </div>
          </div>
          <div className="tools">
            <BoxBusy box={activity && activity.box} />
            {canPickModel && (<>
            <ProviderSelect
              provider={provider} live={endpoint}
              setProvider={name => { L.setProvider(name); setProviderState(name); }} />
            <ModelSelect model={model} setModel={setModel} models={providerModels}
                         base={(L.providersList().find(p => p.name === curProvider) || {}).base} />
            </>)}
            <a className="icon-btn labelled" title={t("nav.guide")} href={guideHref()} target="_blank" rel="noopener"><HelpIcon /> <span className="btn-label">{t("nav.guideShort")}</span></a>
          </div>
        </div>

        <div className="scroll-wrap">
        <div className="scroll" ref={chatScroll.ref}>
          {msgs.length === 0
            ? <Empty onPick={t => setPreset(t)} />
            : (
              <div className="thread">
                {msgs.map((m, i) => {
                  const requestedId    = m.model || model;
                  const servedId       = m.servedModel || requestedId;
                  const known          = L.findModel(servedId);
                  const modelLabel     = known ? known.label : servedId; /* raw id when off-catalog */
                  const reqKnown       = L.findModel(requestedId);
                  const requestedLabel = reqKnown ? reqKnown.label : requestedId;
                  /* Warn only on a GENUINE substitution. Normalise by dropping
                     provider prefixes + separators so "privatemode/gpt-oss-120b"
                     == "openai/gpt-oss-120b". Never warn for aliases that resolve
                     to a concrete model by design: router/* routers, any "*latest"
                     pointer (e.g. kimi-latest -> kimi-k2.6), or a model flagged
                     alias:true in the catalog. */
                  const norm = s => String(s || "").toLowerCase().split("/").pop().replace(/[\s._-]/g, "");
                  const isAlias = /^router\//i.test(requestedId)
                               || /latest/i.test(requestedId)
                               || !!(reqKnown && reqKnown.alias);
                  const mismatch = !!m.servedModel && !isAlias && norm(m.servedModel) !== norm(requestedId);
                  return (
                    <Message key={i} m={m}
                             modelLabel={modelLabel}
                             provider={L.providerLabel(m.endpoint)}
                             requestedLabel={requestedLabel}
                             mismatch={mismatch}
                             isLast={i === msgs.length - 1}
                             busy={busy}
                             onEdit={m.role === "user" ? (text => editAndResend(active.id, i, text)) : undefined}
                             onRegenerate={m.role === "assistant" ? (() => regenerateLast(active.id)) : undefined}
                             streaming={busy && i === msgs.length - 1 && m.role === "assistant"} />
                  );
                })}
              </div>
            )}
        </div>
        <ScrollDown show={chatScroll.away} onClick={chatScroll.toBottom} />
        </div>

        {reconnecting && (
          <div style={{ padding: "0 24px" }}>
            <div className="reconnect-banner">
              <span className="rec-dot busy" /> {t("chat.reconnecting")}
            </div>
          </div>
        )}
        {error && (
          <div style={{ padding: "0 24px" }}>
            <div className="banner">
              <span className="sq" style={{ width: 8, height: 8, background: "var(--maroon)" }} />
              {error}
              <a className="act-btn" href="/settings.html"
                 style={{ marginLeft: "auto", color: "var(--maroon)", borderColor: "var(--terra-line)", textDecoration: "none" }}>{t("nav.connection")}</a>
              <button className="x" onClick={() => setError(null)}>✕</button>
            </div>
          </div>
        )}

        <Composer onSend={send} onStop={stop} busy={busy} mcpAvailable={mcpAvail}
                  presetText={preset} clearPreset={() => setPreset("")} />
        </>)}
      </div>
      {showRoutines && <RoutinesPanel model={model} agents={pickAgents} focusAgentId={routinesFocus} workspaceId={wsId}
        chatOn={chatOn} startNew={routinesNew} apps={apps} focusAppId={routinesApp}
        onClose={() => { setShowRoutines(false); setRoutinesFocus(null); setRoutinesNew(false); setRoutinesApp(null); }}
        onChanged={onRoutinesChanged}
        onOpenConv={id => { setActiveKind("chat"); setActiveId(id); setActiveAppId(null); loadConvs(); }}
        onOpenAgent={id => { setActiveKind("agent"); setActiveId(id); setActiveAppId(null); loadAgentFull(id); }} />}
      {wsPanel && wsPanel.create && <NewWorkspaceModal isAdmin={isAdmin} onCreate={createWorkspace} onClose={() => setWsPanel(null)} />}
      {wsPanel && !wsPanel.create && curWs && (
        <WorkspacePanel key={curWs.id} ws={curWs} tab={wsPanel.tab} onClose={() => setWsPanel(null)}
          onChanged={() => loadWorkspaces()}
          onDeleted={() => { setWsPanel(null); switchWorkspace(null); loadWorkspaces(); loadAgents(); loadApps(); }} />
      )}
      {/* the admin's setup on a new installation, a new person's welcome (onboarding.jsx) */}
      {user && window.IndieOnboard && <window.IndieOnboard.Onboarding me={user} ws={curWs} onBundleAdded={bundleAdded}
                                                                  onNewApp={() => createApp("blank")} />}
      {showBundles && <BundleCatalog initial={showBundles.key || null} isAdmin={isAdmin} ws={curWs}
                                     onClose={() => setShowBundles(null)} onAdded={bundleAdded} />}
      {showAppPicker && <AppPickerModal onCreate={createApp} creating={creatingApp}
        isAdmin={isAdmin}
        onClose={() => setShowAppPicker(false)} />}
      {confirm && <ConfirmModal {...confirm}
        onConfirm={() => { const go = confirm.onConfirm; setConfirm(null); go(); }}
        onClose={() => setConfirm(null)} />}
    </div>
  );
}

/* ---------- PWA install prompt ---------- */
const IosShareIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ width: 15, height: 15, verticalAlign: "-3px" }}>
    <path d="M12 15V3M8 7l4-4 4 4" />
    <path d="M6 11H5a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-6a2 2 0 0 0-2-2h-1" />
  </svg>
);

/* Shared install manager — beforeinstallprompt is captured in the HTML head
   into window.__deferredInstall; both the banner and the sidebar button use
   this. */
const Install = (() => {
  const subs = new Set();
  const notify = () => subs.forEach(f => { try { f(); } catch {} });
  let showReq = 0;
  if (typeof window !== "undefined") window.addEventListener("bip-captured", notify);
  const ua = (typeof navigator !== "undefined" && navigator.userAgent) || "";
  const isIOS = /iphone|ipad|ipod/i.test(ua)
    || (typeof navigator !== "undefined" && navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
  const isInstalled = () => {
    try { return (window.matchMedia && window.matchMedia("(display-mode: standalone)").matches) || window.navigator.standalone === true; }
    catch { return false; }
  };
  return {
    isIOS,
    isInstalled,
    canPrompt: () => !!window.__deferredInstall,
    available: () => !isInstalled() && (isIOS || !!window.__deferredInstall),
    async prompt() {
      const e = window.__deferredInstall;
      if (!e) return false;
      e.prompt();
      try { await e.userChoice; } catch {}
      window.__deferredInstall = null; notify();
      return true;
    },
    requestShow() { showReq++; try { localStorage.removeItem("indie.pwa.dismissed"); } catch {} notify(); },
    showToken: () => showReq,
    subscribe(cb) { subs.add(cb); return () => subs.delete(cb); },
  };
})();

function useInstall() {
  const [, force] = useState(0);
  useEffect(() => Install.subscribe(() => force(n => n + 1)), []);
  return Install;
}

function InstallPrompt() {
  const inst = useInstall();
  const [dismissed, setDismissed] = useState(() => {
    try { return !!localStorage.getItem("indie.pwa.dismissed"); } catch { return false; }
  });
  const seenToken = useRef(inst.showToken());

  /* A sidebar "Install app" tap bumps the show token — re-show even if dismissed. */
  if (inst.showToken() !== seenToken.current) { seenToken.current = inst.showToken(); if (dismissed) setDismissed(false); }

  const dismiss = () => { setDismissed(true); try { localStorage.setItem("indie.pwa.dismissed", "1"); } catch {} };

  if (dismissed || !inst.available()) return null;
  return (
    <div className="pwa-banner" role="dialog" aria-label={t("pwa.install")}>
      <img className="pwa-ic" src="/icons/icon-192.png" alt="" />
      {inst.isIOS ? (
        <span className="pwa-txt">
          {tb("pwa.iosA", { brand: (L.BRAND.brandName || "indie.chat") })}<IosShareIcon />{tb("pwa.iosB")}
        </span>
      ) : (
        <span className="pwa-txt">{tb("pwa.add", { brand: (L.BRAND.brandName || "indie.chat") })}</span>
      )}
      {inst.canPrompt() && <button className="pwa-install" onClick={() => inst.prompt()}>{t("pwa.install")}</button>}
      <button className="pwa-x" onClick={dismiss} aria-label={t("common.dismiss")}>✕</button>
    </div>
  );
}

function Root() {
  /* Re-mount the whole tree when the language changes. Keying on the locale is
     blunt but correct: every t() call is evaluated during render, so anything
     short of a full re-render leaves stale strings in components that did not
     happen to update. It costs one re-mount on an action users take rarely. */
  const [lang, setLang] = useState(L.lang());
  useEffect(() => {
    const onLang = e => setLang(e.detail);
    window.addEventListener("indie:lang", onLang);
    return () => window.removeEventListener("indie:lang", onLang);
  }, []);
  return <React.Fragment key={lang}><App /><InstallPrompt /><WindowDrop /></React.Fragment>;
}

L.configureMarked();
L.seedAdmin();
ReactDOM.createRoot(document.getElementById("root")).render(<Root />);
