Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

87.0 KB
Raw Blame
import { loopIcon } from "./loop-icon";
import {
  ensureSentMail,
  openSentEmail,
  openSentEmailById,
  isSentMailLoading,
  loadSentMail,
  resetSentMail,
  resetSelectedSentEmail,
  selectedSentEmail,
  sentEmailPageTpl,
  sentChatTpl,
  selectedSentChat,
  updateSentChat,
  sentMailTpl,
} from "./sent-mail";
import { html, nothing, render, type TemplateResult } from "lit";
import { live } from "lit/directives/live.js";
import { ref } from "lit/directives/ref.js";
import {
  Archive,
  ArrowUpRight,
  CheckCheck,
  ChevronDown,
  ChevronRight,
  Inbox as InboxGlyph,
  MoreHorizontal,
  PanelRightClose,
  PanelRightOpen,
  Plus,
  RefreshCw,
  Undo2,
  X,
} from "lucide";
import { embeddedComposer } from "./embedded-composer";
import type { ComposerSubmission } from "./composer";
import { api, ApiError, putUiState } from "./core-bridge";
import { onInboxItemEvent, onInboxResync } from "./conversations";
import { createInboxEventCoalescer } from "./inbox-coalesce";
import { charForName } from "./emoji-picker";
import type { DensityTier } from "./density";
import { deepLinkPath, UI_BASE } from "./deep-link";
import { appState, can } from "./shell-state";
import { renderSidebarTop, switchView } from "./shell";
import { openSession, sessionsState } from "./sessions";
import { splitMentions } from "./linkify";
import { splitSlackWire } from "./slack-text";
import { openLoop } from "./loops";
import { listBackLink } from "./list-page";
import { registerPaneKind } from "./pane-kinds";
import { exitSplitIfActive, notifyPanesChanged } from "./split";
import { tip } from "./tooltip";
import { brandName, fieldSelect, menuSelect, avatarTpl, relTime, sheenLabel, workingWave } from "./ui";
import { slackMark } from "./slack-mark";
import { icon } from "./icons";
import { assistantSidebar, assistantMessage } from "./assistant-sidebar";
import { inboxChat } from "./inbox-chat";

export type InboxSource = "gmail" | "slack" | "generic";

export interface InboxDraft {
  to?: string[];
  cc?: string[];
  subject?: string;
  body: string;
}

export interface InboxContextMessage {
  author: string;
  authorId?: string;
  avatarUrl?: string;
  at?: number;
  text: string;
  images?: string[];
  reply?: boolean;
  nearby?: boolean;
}

export interface LedgerThreadMessage {
  id: string;
  role: "human" | "agent" | "system";
  text: string;
  at: number;
}

type InboxPriority = "urgent" | "high" | "normal" | "low";

export interface LedgerItem {
  triage?: { priority?: InboxPriority; reason?: string; groupId?: string; pinned?: string[] };
  id: string;
  loopId: string;
  dedupeKey: string;
  state: "pending" | "processed" | "held" | "actioned" | "dismissed" | "failed";
  summary?: string;
  parkedReason?: string;
  source?: string;
  sourcePayload: Record<string, unknown>;
  sourceAt?: number;
  proposal?: { data: Record<string, unknown>; by: "agent" | "human"; at: number; sessionId?: string };
  thread: LedgerThreadMessage[];
  actedAt?: number;
  actionKind?: string;
  actionResult?: string;
  updatedAt: number;
}

export interface InboxItem {
  priority?: InboxPriority;
  priorityReason?: string;
  priorityPinned?: boolean;
  groupId?: string;
  sentChat?: boolean;
  id: string;
  loopId: string;
  source: InboxSource;
  sourceKey: string;
  reviewState?: string;
  attention?: boolean;
  proposalData?: Record<string, unknown>;
  outputs?: ReviewOutput[];
  detailLoaded?: boolean;
  status: "open" | "sent" | "dismissed" | "replied";
  title: string;
  from: string;
  fromDetail?: string;
  snippet: string;
  context?: InboxContextMessage[];
  participants?: Participant[];
  receivedAt: number;
  externalUrl?: string;
  draft?: InboxDraft;
  draftEdited?: boolean;
  draftAt?: number;
  draftSessionId?: string;
  thread: LedgerThreadMessage[];
  gmail?: { threadId: string; subject?: string; to?: string[]; cc?: string[] };
  slack?: { channelId: string; channelLabel?: string; ts: string; threadTs?: string; userId?: string };
  sentAt?: number;
  dismissedAt?: number;
  repliedAt?: number;
  externalReplyText?: string;
  noReplyNeeded?: { reason?: string };
  reactions?: string[];
  probablyResolved?: boolean;
  automated?: boolean;
  images?: string[];
  updatedAt: number;
  sourceContextFetched?: boolean;
  sourceContextPartial?: boolean;
  sourceRefreshError?: string;
}

export interface InboxView {
  id: string;
  name: string;
  sources: InboxSource[];
}

export interface InboxSyncCron {
  id: string;
  enabled: boolean;
  lastFiredAt?: number;
}

const DEFAULT_VIEWS: InboxView[] = [
  { id: "all", name: "All", sources: ["gmail", "slack"] },
  { id: "gmail", name: "Email", sources: ["gmail"] },
  { id: "slack", name: "Slack", sources: ["slack"] },
  { id: "sent", name: "Sent", sources: [] },
];

function isInboxViewId(value: string | null): value is string {
  return value !== null && [...DEFAULT_VIEWS, ...inboxViews()].some((view) => view.id === value);
}

function inboxViewIdForSegment(segment: string | null): string | null {
  if (segment?.startsWith("loop-")) return segment.slice(5);
  if (segment === "email") return "gmail";
  return isInboxViewId(segment) ? segment : null;
}

function inboxViewSegment(viewId: string): string {
  if (viewId === "gmail") return "email";
  return DEFAULT_VIEWS.some((view) => view.id === viewId) ? viewId : `loop-${viewId}`;
}

const INBOX_FILTERS = [
  { id: "all", label: "All emails", description: "All synced emails, including newsletters and automated mail" },
  {
    id: "human",
    label: "Light filtering — exclude notifications",
    description: "Emails from people, including conversations that need no reply",
  },
  {
    id: "triaged",
    label: "Heavy filtering — only emails that need your attention",
    description: "Emails identified as needing a reply or review",
  },
] as const;

type InboxFilter = (typeof INBOX_FILTERS)[number]["id"];

export const inboxState = {
  filter: "human" as InboxFilter,
  filterBusy: false,
  items: [] as InboxItem[],
  selected: [] as Array<{
    id: string;
    name: string;
    icon?: string;
    sources?: string[];
    count: number;
    source?: string;
    cronId?: string;
    syncCron?: InboxSyncCron | null;
    ingestionActive?: boolean;
    prioritize?: boolean;
    consolidate?: boolean;
  }>,
  available: [] as Array<{
    id: string;
    name: string;
    icon?: string;
    sources?: string[];
    source?: string;
    selected: boolean;
  }>,
  total: 0,
  nextCursor: null as string | null,
  picker: false,
  menuId: null as string | null,
  selectionBusy: false,
  migrationPending: false,
  loopId: null as string | null,
  syncCron: null as InboxSyncCron | null,
  loaded: false,
  loading: false,
  error: null as string | null,
  fetchedAt: 0,
  notice: null as string | null,
  syncBusy: false,
};

const draftConflicts = new Map<string, number>();
const draftEdits = new Map<string, InboxDraft & { basedOnAt?: number }>();
const acting = new Set<string>();
const chatting = new Set<string>();

let archiveToastHost: HTMLDivElement | null = null;
let archiveToastTimer: ReturnType<typeof setTimeout> | undefined;

function closeArchiveToast(): void {
  clearTimeout(archiveToastTimer);
  archiveToastHost?.remove();
  archiveToastHost = null;
}

function showArchiveToast(item: InboxItem): void {
  closeArchiveToast();
  const host = document.createElement("div");
  archiveToastHost = host;
  document.body.append(host);
  let busy = false;
  const schedule = (): void => {
    clearTimeout(archiveToastTimer);
    if (!busy && !host.matches(":hover") && !host.contains(document.activeElement)) {
      archiveToastTimer = setTimeout(() => {
        if (archiveToastHost === host) closeArchiveToast();
      }, 8000);
    }
  };
  const draw = (): void => {
    render(
      html`<div
        class="action-toast"
        role="status"
        @mouseenter=${() => clearTimeout(archiveToastTimer)}
        @mouseleave=${schedule}
        @focusin=${() => clearTimeout(archiveToastTimer)}
        @focusout=${() => queueMicrotask(schedule)}
      >
        ${icon(Archive, 16)}
        <span>Dismissed from inbox</span>
        <button
          type="button"
          ?disabled=${busy}
          @click=${async () => {
            busy = true;
            clearTimeout(archiveToastTimer);
            draw();
            const restored = await setItemStatus(item, "open");
            if (archiveToastHost !== host) return;
            if (restored) closeArchiveToast();
            else {
              busy = false;
              draw();
              schedule();
            }
          }}
        >
          ${busy ? "Undoing…" : "Undo"}
        </button>
        <button class="icon-btn" type="button" aria-label="Dismiss notification" @click=${closeArchiveToast}>
          ${icon(X, 14)}
        </button>
      </div>`,
      host,
    );
  };
  draw();
  schedule();
}

interface InboxSurface {
  host: HTMLElement;
  viewId: string;
  pane: boolean;
  density: () => DensityTier;
  selectedId: string | null;
  showHandled: boolean;
}

const surfaces = new Set<InboxSurface>();

export function resetInboxState(): void {
  resetSentMail();
  closeArchiveToast();
  inboxState.items = [];
  inboxState.selected = [];
  inboxState.available = [];
  inboxState.total = 0;
  inboxState.filter = "human";
  inboxState.filterBusy = false;
  inboxState.nextCursor = null;
  feedWindows.clear();
  inboxState.picker = false;
  inboxState.loopId = null;
  inboxState.syncCron = null;
  inboxState.loaded = false;
  inboxState.loading = false;
  inboxState.error = null;
  inboxState.fetchedAt = 0;
  inboxState.notice = null;
  inboxState.syncBusy = false;
  draftEdits.clear();
  draftConflicts.clear();
  acting.clear();
  chatting.clear();
}

export function inboxViews(): InboxView[] {
  return [
    { id: "all", name: "All", sources: ["gmail", "slack", "generic"] },
    ...inboxState.selected.map((loop) => ({ id: loop.id, name: loop.name, sources: [] as InboxSource[] })),
  ];
}

export function inboxViewName(viewId: string): string {
  return inboxViews().find((v) => v.id === viewId)?.name ?? DEFAULT_VIEWS.find((v) => v.id === viewId)?.name ?? "All";
}

export function itemsFor(viewId: string, status: "open" | "handled"): InboxItem[] {
  return inboxState.items.filter((item) => {
    if (item.sentChat) return false;
    if (viewId !== "all" && viewId !== "sent" && item.loopId !== viewId && item.source !== viewId) return false;
    if (viewId === "sent") return item.status === "sent" && item.source !== "generic";
    if (status !== "open") return item.status !== "open";
    if (item.status !== "open") return false;
    if (item.source === "gmail") {
      if (inboxState.filter === "all") return true;
      if (item.automated) return false;
      if (inboxState.filter === "human") return true;
      if (item.probablyResolved) return false;
    }
    return item.attention !== false || (item.groupId !== undefined && loopTriage(item).consolidate);
  });
}

export function inboxOpenCount(viewId = "all"): number {
  if (!inboxState.loaded) return 0;
  return viewId === "all" ? inboxState.total : (inboxState.selected.find((loop) => loop.id === viewId)?.count ?? 0);
}

const str = (v: unknown): string | undefined => (typeof v === "string" && v ? v : undefined);

function draftOf(item: LedgerItem): InboxDraft | undefined {
  const data = item.proposal?.data;
  if (!data || typeof data.body !== "string") return undefined;
  return {
    body: data.body,
    ...(Array.isArray(data.to) ? { to: data.to as string[] } : {}),
    ...(Array.isArray(data.cc) ? { cc: data.cc as string[] } : {}),
    ...(str(data.subject) ? { subject: data.subject as string } : {}),
  };
}

function resolvedStatus(entry: LedgerItem): InboxItem["status"] {
  if (entry.state === "actioned") return entry.source === "gmail" || entry.source === "slack" ? "sent" : "dismissed";
  if (entry.state !== "dismissed") return "open";
  return entry.actionKind === "replied" ? "replied" : "dismissed";
}

export function toInboxItem(entry: LedgerItem): InboxItem {
  const payload = entry.sourcePayload;
  const sourceId = entry.source ?? payload.source;
  const source: InboxSource = sourceId === "gmail" || sourceId === "slack" ? sourceId : "generic";
  const draft = draftOf(entry);
  const resolved = resolvedStatus(entry);
  const reactions = Array.isArray(payload.reactions) ? (payload.reactions as string[]) : undefined;
  return {
    id: entry.id,
    loopId: entry.loopId,
    source,
    sourceKey: entry.dedupeKey,
    status: resolved,
    sentChat: payload.sentChat === true,
    ...(payload.sentChat === true ? { detailLoaded: true } : {}),
    title: str(payload.title) ?? entry.summary ?? "Review item",
    reviewState: entry.parkedReason
      ? "Needs input"
      : (({ held: "Needs review" } as Record<string, string>)[entry.state] ?? "Work in progress"),
    attention: entry.state === "held" || (entry.state === "failed" && Boolean(entry.parkedReason)),
    proposalData: entry.proposal?.data,
    from: str(payload.from) ?? "",
    snippet: str(payload.snippet) ?? entry.parkedReason ?? entry.summary ?? "",
    receivedAt: entry.sourceAt ?? (typeof payload.receivedAt === "number" ? payload.receivedAt : entry.updatedAt),
    thread: entry.thread,
    updatedAt: entry.updatedAt,
    ...(entry.triage?.priority ? { priority: entry.triage.priority } : {}),
    ...(entry.triage?.reason ? { priorityReason: entry.triage.reason } : {}),
    ...(entry.triage?.pinned?.includes("priority") ? { priorityPinned: true } : {}),
    ...(entry.triage?.groupId ? { groupId: entry.triage.groupId } : {}),
    ...(str(payload.fromDetail) ? { fromDetail: payload.fromDetail as string } : {}),
    sourceContextFetched: payload.sourceContextFetched === true,
    sourceContextPartial: payload.sourceContextPartial === true,
    ...(typeof payload.sourceRefreshError === "string" ? { sourceRefreshError: payload.sourceRefreshError } : {}),
    ...(source === "slack" && Array.isArray(payload.participants)
      ? {
          participants: payload.participants.flatMap((person) =>
            person && typeof person.id === "string" && typeof person.name === "string"
              ? [{ key: person.id, name: person.name, avatarUrl: str(person.avatarUrl) }]
              : [],
          ),
        }
      : {}),
    ...(Array.isArray(payload.context) ? { context: payload.context as InboxContextMessage[] } : {}),
    ...(str(payload.externalUrl) ? { externalUrl: payload.externalUrl as string } : {}),
    ...(draft ? { draft } : {}),
    ...(entry.proposal?.by === "human" ? { draftEdited: true } : {}),
    ...(entry.proposal ? { draftAt: entry.proposal.at } : {}),
    ...(entry.proposal?.sessionId ? { draftSessionId: entry.proposal.sessionId } : {}),
    ...(payload.gmail ? { gmail: payload.gmail as InboxItem["gmail"] } : {}),
    ...(payload.slack ? { slack: payload.slack as InboxItem["slack"] } : {}),
    ...(reactions?.length ? { reactions } : {}),
    ...(payload.probablyResolved === true ? { probablyResolved: true } : {}),
    ...(payload.automated === true ? { automated: true } : {}),
    ...(Array.isArray(payload.images)
      ? { images: (payload.images as unknown[]).filter((u): u is string => typeof u === "string") }
      : {}),
    ...(resolved === "sent" && entry.actedAt !== undefined ? { sentAt: entry.actedAt } : {}),
    ...(resolved === "dismissed" && entry.actedAt !== undefined ? { dismissedAt: entry.actedAt } : {}),
    ...(resolved === "replied" && entry.actedAt !== undefined ? { repliedAt: entry.actedAt } : {}),
    ...(resolved === "replied" && entry.actionResult ? { externalReplyText: entry.actionResult } : {}),
    ...(entry.actionKind === "no_reply_needed"
      ? { noReplyNeeded: entry.actionResult ? { reason: entry.actionResult } : {} }
      : {}),
  };
}

let pollTimer: number | null = null;

function anySurfaceVisible(): boolean {
  if (!can("inbox")) return false;
  if (appState.currentView === "inbox") return true;
  return [...surfaces].some((s) => s.pane && s.host.isConnected);
}

function ensurePolling(): void {
  if (!can("inbox")) return;
  if (pollTimer !== null) return;
  pollTimer = window.setInterval(() => {
    if (document.visibilityState !== "visible" || !anySurfaceVisible()) return;
    void refreshInbox({ silent: true });
  }, 120_000);
}

const feedWindows = new Map<string, { limit: number; nextCursor: string | null }>();
let refreshFollowUp = false;
let resyncMissedWhileHidden = false;

export async function refreshInbox(
  opts: { silent?: boolean; ifStaleMs?: number; more?: boolean; viewId?: string } = {},
): Promise<void> {
  if (!can("inbox")) return;
  if (inboxState.loading) {
    if (opts.ifStaleMs === undefined || resyncMissedWhileHidden) refreshFollowUp = true;
    return;
  }
  if (opts.ifStaleMs !== undefined && !resyncMissedWhileHidden && Date.now() - inboxState.fetchedAt < opts.ifStaleMs)
    return;
  resyncMissedWhileHidden = false;
  inboxState.loading = true;
  if (!opts.silent || inboxState.loaded) drawAll();
  try {
    type Feed = {
      migrationPending: boolean;
      filter: InboxFilter;
      selected: typeof inboxState.selected;
      available: typeof inboxState.available;
      items: LedgerItem[];
      total: number;
      nextCursor: string | null;
    };
    const viewIds = new Set(["all", fullViewId, ...[...surfaces].map((surface) => surface.viewId)]);
    const moreView = opts.viewId ?? fullViewId;
    const combined = new Map<string, InboxItem>();
    const windows = new Map(feedWindows);
    let metadata: Feed | undefined;
    let refreshFilter: InboxFilter | undefined;
    const fetchFeed = async (qs: URLSearchParams): Promise<Feed> => {
      if (refreshFilter) qs.set("filter", refreshFilter);
      const feed = await api<Feed>(`/api/inbox?${qs}`);
      const filter = feed.filter ?? "human";
      if (refreshFilter && filter !== refreshFilter) throw new Error("Inbox filter changed during refresh. Try again.");
      refreshFilter = filter;
      return feed;
    };
    for (const viewId of [...viewIds, ...[...viewIds].filter((id) => id !== "sent").map((id) => `handled:${id}`)]) {
      const handled = viewId.startsWith("handled:");
      const filterView = handled ? viewId.slice(8) : viewId;
      const previous = feedWindows.get(viewId);
      const limit = (previous?.limit ?? 40) + (opts.more && moreView === viewId ? 40 : 0);
      const qs = new URLSearchParams();
      if (handled) qs.set("view", "handled");
      else if (filterView === "sent") qs.set("view", "sent");
      if (filterView !== "all" && filterView !== "sent")
        qs.set(
          "loopId",
          (metadata?.selected ?? inboxState.selected).find((loop) => loop.source === filterView)?.id ?? filterView,
        );
      let found = await fetchFeed(qs);
      while (found.nextCursor && found.items.length < limit) {
        qs.set("cursor", found.nextCursor);
        const page = await fetchFeed(qs);
        found = { ...page, items: [...found.items, ...page.items] };
      }
      windows.set(viewId, { limit, nextCursor: found.nextCursor });
      metadata = found;
      for (const entry of found.items) combined.set(entry.id, toInboxItem(entry));
    }
    if (!metadata) return;
    feedWindows.clear();
    for (const [view, window] of windows) feedWindows.set(view, window);
    inboxState.selected = metadata.selected;
    inboxState.available = metadata.available;
    inboxState.total = metadata.total;
    inboxState.filter = refreshFilter!;
    inboxState.migrationPending = metadata.migrationPending;
    const next = [...combined.values()];
    const openId = fullSurface?.selectedId;
    const detail = openId ? inboxState.items.find((item) => item.id === openId && item.detailLoaded) : undefined;
    inboxState.items = next;
    if (detail && inboxState.selected.some((loop) => loop.id === detail.loopId)) {
      upsertItem(detail);
      void loadDetail(detail.id, detail.loopId);
    }
    if (openId && !detail) {
      const entry = inboxState.items.find((item) => item.id === openId);
      if (entry) void loadDetail(entry.id, entry.loopId);
    }
    const localItems = await fetchLocalInboxItems();
    if (localItems.length) inboxState.items = localItems;
    inboxState.loaded = true;
    inboxState.error = null;
    inboxState.fetchedAt = Date.now();
  } catch (e) {
    inboxState.error = e instanceof Error ? e.message : String(e);
  } finally {
    inboxState.loading = false;
    drawAll();
  }
  if (refreshFollowUp) {
    refreshFollowUp = false;
    void refreshInbox({ silent: true });
  }
}

interface ReviewOutput {
  id: string;
  title: string;
  summary?: string;
  shipAction: string;
  externalRef?: string;
  decisionNote?: string;
  state: string;
}

async function loadDetail(itemId: string, loopId: string): Promise<void> {
  try {
    const result = await api<{ item: LedgerItem; outputs: ReviewOutput[] }>(
      `/api/loops/${encodeURIComponent(loopId)}/items/${encodeURIComponent(itemId)}`,
    );
    if (!inboxState.selected.some((loop) => loop.id === loopId)) return;
    upsertItem({ ...toInboxItem(result.item), outputs: result.outputs, detailLoaded: true });
    drawAll();
  } catch (error) {
    inboxState.items = inboxState.items.filter((item) => item.id !== itemId);
    notify(error instanceof Error ? error.message : "Could not load item");
  }
}

async function selectInboxFilter(filter: InboxFilter): Promise<void> {
  if (inboxState.filterBusy || inboxState.loading || inboxState.filter === filter) return;
  inboxState.filterBusy = true;
  drawAll();
  try {
    const saved = await putUiState("inbox-filter", filter, Date.now());
    feedWindows.clear();
    await refreshInbox();
    if (inboxState.error) notify(inboxState.error);
    else if (!saved.ok)
      notify("A newer inbox filter was already saved. Your selection wasn't saved. Please try again.");
  } catch (error) {
    notify(error instanceof Error ? error.message : "Could not save inbox filter");
  } finally {
    inboxState.filterBusy = false;
    drawAll();
  }
}

async function toggleSelection(id: string): Promise<void> {
  if (inboxState.selectionBusy) return;
  inboxState.selectionBusy = true;
  drawAll();
  const ids = inboxState.selected.map((loop) => loop.id);
  try {
    await api("/api/inbox/selection", {
      method: "POST",
      body: JSON.stringify({ loopIds: ids.includes(id) ? ids.filter((value) => value !== id) : [...ids, id] }),
    });
    if (fullViewId === id) fullViewId = "all";
    await refreshInbox();
  } catch (error) {
    notify(error instanceof Error ? error.message : "Could not update Inbox");
  } finally {
    inboxState.selectionBusy = false;
    drawAll();
  }
}

async function decideReview(
  item: InboxItem,
  output: ReviewOutput,
  decision: "ship" | "return",
  note = "",
): Promise<boolean> {
  if (acting.has(item.id)) return false;
  acting.add(item.id);
  drawAll();
  try {
    const result = await api<{ output: ReviewOutput }>(
      `/api/loops/${encodeURIComponent(item.loopId)}/outputs/${encodeURIComponent(output.id)}/decide`,
      { method: "POST", body: JSON.stringify({ decision, note }) },
    );
    const messages: Record<string, string> = { shipped: "Action completed", returned: "Changes requested" };
    notify(messages[result.output.state] ?? "Awaiting confirmation. Check the Loop before retrying.");
    await loadDetail(item.id, item.loopId);
    await refreshInbox({ silent: true });
    return true;
  } catch (error) {
    notify(error instanceof Error ? error.message : "Could not confirm action");
    return false;
  } finally {
    acting.delete(item.id);
    drawAll();
  }
}

function reviewActionLabel(action: string): string {
  const labels: Record<string, string> = { open_draft_pr: "Open draft PR", open_pr: "Open PR", send: "Send" };
  return labels[action] ?? `Approve ${action.replaceAll("_", " ")}`;
}

function reviewStateLabel(state: string): string {
  const labels: Record<string, string> = {
    unconfirmed: "Awaiting confirmation",
    shipping: "Action in progress",
    returned: "Changes requested",
    superseded: "Superseded",
  };
  return labels[state] ?? state;
}

function usesOutputReview(item: InboxItem): boolean {
  return (
    item.source === "generic" ||
    Boolean(item.outputs?.some((output) => ["ready", "shipping", "unconfirmed"].includes(output.state)))
  );
}

const ARTIFACT_KINDS: Record<string, string> = {
  open_draft_pr: "Draft pull request",
  open_pr: "Pull request",
  send: "Message",
  reply: "Message",
  send_email: "Email",
  send_slack: "Slack message",
};

function subjectTpl(item: InboxItem): TemplateResult {
  const members = groupOf(item);
  const expanded = expandedSubjects.has(item.id);
  const shown = expanded ? members : members.slice(0, 5);
  return html`<section
    class="inbox-subject"
    aria-label=${members.length > 1 ? `${members.length} similar items` : "Item"}
  >
    ${members.length > 1 ? html`<div class="inbox-subject-label">${members.length} similar</div>` : nothing}
    <ul>
      ${shown.map(
        (member) =>
          html`<li>
            <span class="inbox-subject-key">${member.source === "generic" ? member.sourceKey : member.from}</span>
            <span class="inbox-subject-text">${member.snippet || member.title}</span>
            <span class="inbox-subject-at" title=${fmtClock(member.receivedAt)}>${relTime(member.receivedAt)}</span>
            ${member.externalUrl ? html`<a class="inbox-external-link" href=${member.externalUrl} target="_blank" rel="noopener noreferrer" aria-label="Open source">${icon(ArrowUpRight, 12)}</a>` : nothing}
          </li>`,
      )}
    </ul>
    ${
      members.length > shown.length || expanded
        ? html`<button
            class="inbox-subject-more"
            type="button"
            @click=${() => {
              if (expanded) expandedSubjects.delete(item.id);
              else expandedSubjects.add(item.id);
              drawAll();
            }}
          >
            ${expanded ? "Show fewer" : `Show all ${members.length}`}
          </button>`
        : nothing
    }
  </section>`;
}

function artifactTpl(item: InboxItem, output: ReviewOutput, members: number): TemplateResult {
  const link = output.externalRef && /^https?:\/\//i.test(output.externalRef) ? output.externalRef : undefined;
  return html`<section class="inbox-artifact">
    <div class="inbox-artifact-head">
      <span>${ARTIFACT_KINDS[output.shipAction] ?? "Response"}</span>
      ${link ? html`<a class="inbox-external-link" href=${link} target="_blank" rel="noopener noreferrer">View ${icon(ArrowUpRight, 12)}</a>` : nothing}
    </div>
    <h2>${output.title}</h2>
    ${output.summary ? html`<div class="inbox-artifact-body">${output.summary}</div>` : nothing}
    ${output.decisionNote ? html`<p class="inbox-review-note">Requested changes: ${output.decisionNote}</p>` : nothing}
    ${
      output.state === "ready"
        ? html`<div class="inbox-artifact-actions">
            <button
              class="btn primary"
              ?disabled=${acting.has(item.id)}
              ${members > 1 ? tip(`Resolves all ${members}`) : nothing}
              @click=${() => void decideReview(item, output, "ship")}
            >
              ${reviewActionLabel(output.shipAction)}
            </button>
          </div>`
        : html`<p class="inbox-artifact-state" role="status">${reviewStateLabel(output.state)}</p>`
    }
  </section>`;
}

function reviewTpl(item: InboxItem, withChat = true): TemplateResult {
  if (!item.detailLoaded) return html`<div class="empty compact">Loading review…</div>`;
  const outputs = item.outputs ?? [];
  const members = groupOf(item).length;
  return html`<div class="inbox-generic-review">
    ${subjectTpl(item)}
    ${!outputs.length && item.proposalData ? html`<pre class="inbox-proposal-data">${JSON.stringify(item.proposalData, null, 2)}</pre>` : nothing}
    ${outputs.map((output) => artifactTpl(item, output, members))} ${withChat ? chatTpl(item) : nothing}
  </div>`;
}

async function fetchLocalInboxItems(): Promise<InboxItem[]> {
  if (!["localhost", "127.0.0.1", "[::1]"].includes(location.hostname)) return [];
  try {
    const response = await fetch("/inbox-seed.local.json", { cache: "no-store" });
    if (!response.ok) return [];
    const payload = (await response.json()) as { items?: unknown };
    if (!Array.isArray(payload.items)) return [];
    return payload.items.filter(
      (item): item is InboxItem =>
        typeof item === "object" &&
        item !== null &&
        typeof (item as InboxItem).id === "string" &&
        typeof (item as InboxItem).sourceKey === "string" &&
        ((item as InboxItem).source === "gmail" || (item as InboxItem).source === "slack"),
    );
  } catch {
    return [];
  }
}

let realtimeWired = false;

const enqueueRealtimeEvent = createInboxEventCoalescer(
  250,
  () => void refreshWhenVisible(),
  (fn, ms) => void window.setTimeout(fn, ms),
);

async function refreshWhenVisible(): Promise<void> {
  if (document.visibilityState !== "visible" || !anySurfaceVisible()) {
    resyncMissedWhileHidden = true;
    return;
  }
  await refreshInbox({ silent: true });
}

function upsertItem(next: InboxItem): void {
  if (inboxState.items.some((i) => i.id === next.id)) replaceItem(next);
  else inboxState.items = [next, ...inboxState.items];
}

function ensureRealtime(): void {
  if (realtimeWired) return;
  realtimeWired = true;
  onInboxItemEvent((event) => {
    if (!can("inbox")) return;
    if (inboxState.loaded && !inboxState.selected.some((loop) => loop.id === event.loopId)) return;
    enqueueRealtimeEvent({ loopId: event.loopId, itemId: event.itemId });
  });
  onInboxResync(() => {
    if (!can("inbox")) return;
    void refreshWhenVisible();
  });
  document.addEventListener("visibilitychange", () => {
    if (document.visibilityState !== "visible" || !anySurfaceVisible()) return;
    void refreshInbox({ ifStaleMs: 30_000, silent: true });
  });
}

function inboxItemById(id: string): InboxItem | undefined {
  const sent = selectedSentChat(id);
  return sent?.id === id ? toInboxItem(sent) : inboxState.items.find((item) => item.id === id);
}

async function continueSentReply(item: InboxItem): Promise<void> {
  try {
    replaceItem(await postAction(item, "reply"));
    drawAll();
  } catch (error) {
    notify(`Couldn't start a reply: ${error instanceof Error ? error.message : error}`);
  }
}

function replaceItem(next: InboxItem): void {
  inboxState.items = inboxState.items.map((i) => (i.id === next.id ? next : i));
}

function notify(msg: string | null): void {
  inboxState.notice = msg;
  drawAll();
  if (msg) {
    window.setTimeout(() => {
      if (inboxState.notice === msg) {
        inboxState.notice = null;
        drawAll();
      }
    }, 4000);
  }
}

function draftSubject(item: InboxItem, draft: InboxDraft): string {
  if (draft.subject !== undefined) return draft.subject;
  return item.gmail?.subject ? `Re: ${item.gmail.subject.replace(/^re:\s*/i, "")}` : "";
}

function headerPeek(item: InboxItem, draft: InboxDraft): string {
  const to = (draft.to ?? []).join(", ");
  const subject = draftSubject(item, draft);
  return [to, subject].filter(Boolean).join(" · ") || "Recipients and subject";
}

function effectiveDraft(item: InboxItem): InboxDraft {
  const edited = draftEdits.get(item.id);
  if (edited) {
    const { basedOnAt: _basedOnAt, ...draft } = edited;
    return draft;
  }
  return {
    body: "",
    ...(item.source === "gmail"
      ? { to: item.gmail?.to ?? [], cc: item.gmail?.cc ?? [], subject: item.gmail?.subject }
      : {}),
    ...item.draft,
  };
}

function sameDraft(a: InboxDraft | undefined, b: InboxDraft): boolean {
  return Boolean(
    a &&
    a.body === b.body &&
    (a.subject ?? "") === (b.subject ?? "") &&
    (a.to ?? []).join(",") === (b.to ?? []).join(",") &&
    (a.cc ?? []).join(",") === (b.cc ?? []).join(","),
  );
}

function editDraft(item: InboxItem, patch: Partial<InboxDraft>): void {
  const basedOnAt = draftEdits.get(item.id)?.basedOnAt ?? item.draftAt;
  draftEdits.set(item.id, { ...effectiveDraft(item), ...patch, ...(basedOnAt !== undefined ? { basedOnAt } : {}) });
}

function isDraftConflict(e: unknown): boolean {
  return e instanceof ApiError && (e.body as { error?: unknown } | null)?.error === "draft_changed";
}

async function explainDraftConflict(item: InboxItem, edited: boolean): Promise<void> {
  draftConflicts.set(item.id, (draftConflicts.get(item.id) ?? 0) + 1);
  await refetchItem(item);
  const fresh = inboxItemById(item.id);
  const overlay = draftEdits.get(item.id);
  if (overlay && fresh?.draftAt !== undefined) draftEdits.set(item.id, { ...overlay, basedOnAt: fresh.draftAt });
  const preview = (fresh?.draft?.body ?? "").trim().slice(0, 140);
  notify(
    edited
      ? `The agent redrafted this reply while you were editing. Your text is kept in the box. New draft: "${preview}". Send again to use yours.`
      : "The draft changed while you were looking. Review the new draft, then send again.",
  );
}

function addressHeaderList(raw: string): string[] {
  return raw.trim() ? [raw.trim()] : [];
}

function actionPath(item: InboxItem, leaf: "action" | "followup"): string {
  return `/api/loops/${encodeURIComponent(item.loopId)}/items/${encodeURIComponent(item.id)}/${leaf}`;
}

const sourceRefreshAt = new Map<string, number>();
function ensureItemSource(item: InboxItem): void {
  if (!item.slack || Date.now() - (sourceRefreshAt.get(item.id) ?? 0) < 60_000) return;
  for (const [id, at] of sourceRefreshAt) if (Date.now() - at >= 60_000) sourceRefreshAt.delete(id);
  sourceRefreshAt.set(item.id, Date.now());
  void refetchItem(item, true);
}

async function refetchItem(item: InboxItem, refreshSource = false): Promise<void> {
  try {
    const { item: fresh } = await api<{ item: LedgerItem }>(
      `/api/loops/${encodeURIComponent(item.loopId)}/items/${encodeURIComponent(item.id)}${refreshSource ? "?refreshSource=1" : ""}`,
    );
    updateSentChat(fresh);
    replaceItem({ ...toInboxItem(fresh), detailLoaded: true });
    drawAll();
  } catch {
    void refreshInbox({ silent: true });
  }
}

async function postAction(item: InboxItem, kind: string, args?: Record<string, unknown>): Promise<InboxItem> {
  const { item: next } = await api<{ item: LedgerItem }>(actionPath(item, "action"), {
    method: "POST",
    body: JSON.stringify({ kind, ...(args ? { args } : {}) }),
  });
  updateSentChat(next);
  return { ...toInboxItem(next), detailLoaded: true };
}

const persistQueue = new Map<string, Promise<void>>();
const persistWaiting = new Set<string>();

function enqueueForItem(itemId: string, task: () => Promise<void>): Promise<void> {
  const queued = (persistQueue.get(itemId) ?? Promise.resolve()).then(task);
  persistQueue.set(itemId, queued);
  const clear = (): void => {
    if (persistQueue.get(itemId) === queued) persistQueue.delete(itemId);
  };
  void queued.then(clear, clear);
  return queued;
}

export function persistDraft(item: InboxItem): Promise<void> {
  if (persistWaiting.has(item.id)) return persistQueue.get(item.id) ?? Promise.resolve();
  persistWaiting.add(item.id);
  return enqueueForItem(item.id, () => {
    persistWaiting.delete(item.id);
    return persistDraftNow(item.id);
  });
}

async function persistDraftNow(itemId: string): Promise<void> {
  const item = inboxItemById(itemId);
  if (!item) return;
  const edited = draftEdits.get(item.id);
  if (!edited) return;
  const saved = item.draft;
  if (sameDraft(saved, edited)) {
    draftEdits.delete(item.id);
    return;
  }
  const { basedOnAt, ...proposal } = edited;
  try {
    const next = await postAction(item, "edit", {
      proposal,
      ...(basedOnAt !== undefined ? { expectedProposalAt: basedOnAt } : {}),
    });
    const newer = draftEdits.get(item.id);
    if (newer === edited) draftEdits.delete(item.id);
    else if (newer && next.draftAt !== undefined) draftEdits.set(item.id, { ...newer, basedOnAt: next.draftAt });
    replaceItem(next);
    drawAll();
  } catch (e) {
    if (isDraftConflict(e)) return explainDraftConflict(item, true);
    notify(`Couldn't save the draft: ${e instanceof Error ? e.message : e}`);
  }
}

export async function setItemStatus(item: InboxItem, status: "open" | "dismissed"): Promise<boolean> {
  if (acting.has(item.id)) return false;
  acting.add(item.id);
  drawAll();
  try {
    upsertItem(await postAction(item, status === "dismissed" ? "dismiss" : "reopen"));
    if (status === "dismissed") showArchiveToast(item);
    return true;
  } catch (e) {
    notify(`Couldn't update the item: ${e instanceof Error ? e.message : e}`);
    return false;
  } finally {
    acting.delete(item.id);
    drawAll();
  }
}

export async function askAgent(
  item: InboxItem,
  message: string,
  options?: ComposerSubmission,
  snapshot = { draft: effectiveDraft(item), conflictRevision: draftConflicts.get(item.id) ?? 0 },
): Promise<boolean> {
  const text = message.trim();
  if ((!text && !options?.attachments?.length) || chatting.has(item.id)) return false;
  const ready = item.outputs?.find((output) => output.state === "ready");
  if (ready && text && !options?.attachments?.length) return decideReview(item, ready, "return", text);
  const { draft, conflictRevision } = snapshot;
  chatting.add(item.id);
  drawAll();
  try {
    await enqueueForItem(item.id, async () => {
      if ((draftConflicts.get(item.id) ?? 0) !== conflictRevision)
        throw new Error("The draft changed. Review it before sending again.");
      await persistDraftNow(item.id);
      if (draftEdits.has(item.id)) throw new Error("Save the draft before continuing. Your edits have been kept.");
      const current = inboxItemById(item.id) ?? item;
      if (!sameDraft(effectiveDraft(current), draft)) {
        throw new Error("The draft changed. Review it before continuing.");
      }
      const { item: next } = await api<{ item: LedgerItem }>(actionPath(item, "followup"), {
        method: "POST",
        body: JSON.stringify({
          message: text,
          ...options,
          ...(current.draftAt !== undefined ? { expectedProposalAt: current.draftAt } : {}),
        }),
      });
      updateSentChat(next);
      replaceItem({ ...toInboxItem(next), outputs: item.outputs, detailLoaded: true });
    });
    return true;
  } catch (e) {
    if (isDraftConflict(e)) await refetchItem(item);
    notify(`The agent couldn't answer: ${e instanceof Error ? e.message : e}`);
    return false;
  } finally {
    chatting.delete(item.id);
    drawAll();
  }
}

async function setUpSync(loopId?: string): Promise<void> {
  if (inboxState.syncBusy) return;
  inboxState.syncBusy = true;
  drawAll();
  try {
    const out = await api<{ loop: { id: string } | null; syncCron: InboxSyncCron | null }>("/api/inbox/sync-cron", {
      method: "POST",
      body: JSON.stringify({ enabled: true, loopId }),
    });
    inboxState.syncCron = out.syncCron;
    inboxState.loopId = out.loop?.id ?? inboxState.loopId;
    notify("Sync is on. First pass runs within 15 minutes.");
    await refreshInbox({ silent: true });
  } catch (e) {
    notify(`Couldn't set up sync: ${e instanceof Error ? e.message : e}`);
  } finally {
    inboxState.syncBusy = false;
    drawAll();
  }
}

async function syncNow(viewId: string): Promise<void> {
  const crons = syncLoops(viewId).flatMap((loop) => (loop.syncCron ? [loop.syncCron] : []));
  if (!crons.length || inboxState.syncBusy) return;
  inboxState.syncBusy = true;
  drawAll();
  try {
    for (const cron of crons)
      await api(`/api/crons/${encodeURIComponent(cron.id)}/run`, { method: "POST", body: "{}" });
    notify("Sync kicked off. New items appear as the agent finishes drafting.");
  } catch (e) {
    notify(`Couldn't start a sync: ${e instanceof Error ? e.message : e}`);
  } finally {
    inboxState.syncBusy = false;
    drawAll();
  }
}

function openDraftSession(e: MouseEvent, sessionId: string): void {
  e.preventDefault();
  const session = sessionsState.list.find((s) => s.id === sessionId);
  if (session) void openSession(session);
  else window.location.assign(deepLinkPath(UI_BASE, "chats", sessionId));
}

function sourceGlyph(item: InboxItem): TemplateResult {
  return loopIcon(inboxState.selected.find((loop) => loop.id === item.loopId) ?? { source: item.source }, 14);
}

function fmtClock(ms: number): string {
  return new Date(ms).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" });
}

interface Participant {
  key: string;
  name: string;
  avatarUrl?: string;
}

function participantName(raw: string): string {
  return (raw.match(/^\s*"?([^"<]+?)"?\s*</)?.[1] ?? raw).trim();
}

function participantKey(raw: string): string {
  return (raw.match(/<([^>]+)>/)?.[1] ?? raw).trim().toLowerCase();
}

function participantsOf(item: InboxItem): Participant[] {
  const slack = item.source === "slack";
  const found = new Map<string, Participant>((slack ? (item.participants ?? []) : []).map((p) => [p.key, p]));
  for (const message of [
    {
      author: item.from,
      authorId: slack ? (item.slack?.userId ?? item.participants?.[0]?.key) : undefined,
      avatarUrl: undefined,
    },
    ...(item.context ?? []),
  ]) {
    const name = participantName(message.author ?? "");
    if (!name) continue;
    const id = slack ? message.authorId : undefined;
    if (slack && !id && [...found.values()].some((person) => person.name === name)) continue;
    const key = id ?? participantKey(message.author);
    if (!found.has(key)) found.set(key, { key, name, avatarUrl: slack ? message.avatarUrl : undefined });
  }
  return [...found.values()];
}

const AVATARS_SHOWN = 4;

export function participantsTpl(item: InboxItem): TemplateResult | typeof nothing {
  const people = participantsOf(item);
  if (!people.length) return nothing;
  const shown = people.length > AVATARS_SHOWN ? people.slice(0, AVATARS_SHOWN - 1) : people;
  const rest = people.slice(shown.length);
  return html`<span class="inbox-avatars" aria-label=${`In this conversation: ${people.map((p) => p.name).join(", ")}`}>
    ${shown.map(avatarTpl)}
    ${
      rest.length
        ? html`<span class="inbox-avatar more" ${tip(rest.map((p) => p.name).join(", "))} aria-hidden="true"
            >+${rest.length}</span
          >`
        : nothing
    }
  </span>`;
}

function selfHandle(): string {
  const me = appState.me?.user ?? "";
  return (me.split("@")[0] || me).trim().toLowerCase();
}

export function slackTextTpl(item: InboxItem, text: string, opts: { links?: boolean } = {}): TemplateResult {
  if (item.source !== "slack") return html`${text}`;
  const self = selfHandle();
  const mentionChip = (handle: string): TemplateResult =>
    html`<span class="slack-mention ${handle.toLowerCase() === self ? "self" : ""}">@${handle}</span>`;
  const withMentions = (str: string): Array<TemplateResult | string> =>
    splitMentions(str).map((m) => (m.kind === "text" ? m.text : mentionChip(m.handle)));
  return html`${splitSlackWire(text).map((seg) => {
    if (seg.kind === "mention") return mentionChip(seg.handle);
    if (seg.kind === "link") {
      if (opts.links === false) return html`<span ${tip(seg.href)}>${withMentions(seg.label)}</span>`;
      return html`<a class="inbox-text-link" href=${seg.href} target="_blank" rel="noreferrer noopener"
        >${withMentions(seg.label)}</a
      >`;
    }
    return withMentions(seg.text);
  })}`;
}

function itemImagesTpl(item: InboxItem, urls: string[] | undefined, ctxIndex: number): TemplateResult | typeof nothing {
  if (!urls?.length) return nothing;
  const base = `${UI_BASE}/api/loops/${encodeURIComponent(item.loopId)}/items/${encodeURIComponent(item.id)}/image`;
  return html`<div class="inbox-images">
    ${urls.map((_u, j) => {
      const src = `${base}?ctx=${ctxIndex}&i=${j}`;
      return html`<a href=${src} target="_blank" rel="noreferrer noopener"
        ><img class="inbox-image" src=${src} loading="lazy" alt="attached image"
      /></a>`;
    })}
  </div>`;
}

export const CONTEXT_TAIL = 6;
const CONTEXT_PAGE = 20;
const revealedContext = new Map<string, number>();

function revealEarlier(item: InboxItem, marker: Element): void {
  const scroller = marker.closest<HTMLElement>(".inbox-scroll");
  const before = scroller ? scroller.scrollHeight - scroller.scrollTop : 0;
  revealedContext.set(item.id, (revealedContext.get(item.id) ?? 0) + CONTEXT_PAGE);
  drawAll();
  if (scroller) scroller.scrollTop = scroller.scrollHeight - before;
}

const watchedEarlier = new WeakSet<Element>();

function watchEarlier(item: InboxItem, el: Element | undefined): void {
  const scroller = el?.closest<HTMLElement>(".inbox-scroll");
  if (!el || !scroller || watchedEarlier.has(el) || typeof IntersectionObserver === "undefined") return;
  watchedEarlier.add(el);
  let userScrolled = false;
  const markScrolled = (): void => void (userScrolled = true);
  scroller.addEventListener("wheel", markScrolled, { passive: true });
  scroller.addEventListener("touchmove", markScrolled, { passive: true });
  const observer = new IntersectionObserver((entries) => {
    if (!el.isConnected) return observer.disconnect();
    if (!userScrolled || !entries.some((entry) => entry.isIntersecting)) return;
    revealEarlier(item, el);
  });
  observer.observe(el);
}

export function contextTpl(item: InboxItem): TemplateResult | typeof nothing {
  const context = (item.context ?? []).map((message, index) => ({ ...message, imageIndex: index }));
  const rows = item.sourceContextFetched
    ? context
    : [
        ...context.filter((m) => !item.slack || m.nearby === true),
        {
          author: item.from,
          authorId: item.slack?.userId ?? (item.source === "slack" ? item.participants?.[0]?.key : undefined),
          at: item.receivedAt,
          text: item.snippet,
          images: item.images,
          imageIndex: -1,
          reply: false,
          nearby: false,
        },
      ];
  const hidden = Math.max(0, rows.length - CONTEXT_TAIL - (revealedContext.get(item.id) ?? 0));
  return html`<div class="inbox-context">
    ${
      hidden
        ? html`<button
            class="inbox-source-notice inbox-earlier"
            ${ref((el) => watchEarlier(item, el))}
            @click=${(event: MouseEvent) => revealEarlier(item, event.currentTarget as Element)}
          >
            ${hidden === 1 ? "1 earlier message" : `${hidden} earlier messages`}
          </button>`
        : nothing
    }
    ${item.sourceRefreshError ? html`<div class="inbox-source-notice" role="status">${item.sourceRefreshError}</div>` : nothing}
    ${item.sourceContextPartial ? html`<div class="inbox-source-notice">Showing part of this conversation. Open in Slack for the full history.</div>` : nothing}
    ${rows.slice(hidden).map((m) => {
      const participant = item.source === "slack" ? item.participants?.find((p) => p.key === m.authorId) : undefined;
      const author = participant?.name ?? m.author;
      const name = participantName(author) || author;
      const avatarUrl = participant ? participant.avatarUrl : m.avatarUrl;
      return html`
        <div class="inbox-context-msg ${m.reply ? "inbox-thread-reply" : ""} ${m.nearby ? "inbox-nearby-context" : ""}">
          ${avatarTpl({ key: m.authorId ?? participantKey(m.author), name, avatarUrl: item.source === "slack" ? avatarUrl : undefined })}
          <div class="inbox-context-body">
            <div class="inbox-context-head">
              <span class="inbox-context-author">${name}</span>
              ${m.nearby ? html`<span class="inbox-context-at">Nearby in channel</span>` : nothing}
              ${m.at ? html`<span class="inbox-context-at">${relTime(m.at)}</span>` : nothing}
            </div>
            <div class="inbox-context-text">${slackTextTpl(item, m.text)}</div>
            ${itemImagesTpl(item, m.images, m.imageIndex)}
          </div>
        </div>
      `;
    })}
  </div>`;
}

export function chatTpl(item: InboxItem, compact = false): TemplateResult {
  const busy = chatting.has(item.id);
  const submit = (event: MouseEvent, instruction: string): void => {
    const composer = (event.currentTarget as HTMLElement).closest(".inbox-chat")?.querySelector(".embedded-composer");
    composer?.dispatchEvent(new CustomEvent("composer-submit", { detail: instruction }));
  };
  return assistantSidebar({
    context: {
      kind: "thread",
      source: item.source,
      hasDraft: Boolean(item.draft),
      sent: Boolean(item.sentChat),
      resolved: Boolean(item.probablyResolved),
    },
    messages: html`${item.thread.map((message) => assistantMessage({ role: message.role, text: message.text }))}`,
    busy,
    status: busy ? html`<div class="inbox-chat-working">${workingWave()}<span>Thinking…</span></div>` : nothing,
    showPrompts: item.status === "open" && item.thread.length === 0,
    send:
      item.status === "open" && !usesOutputReview(item) && (!item.sentChat || item.draft)
        ? { disabled: busy || acting.has(item.id), run: (event) => submit(event, "Send it") }
        : undefined,
    onPrompt: (prompt, event) => submit(event, prompt),
    composer: embeddedComposer(
      `inbox:${appState.me?.user ?? "anon"}:${item.loopId}:${item.id}`,
      {
        placeholder: `Ask ${brandName()} for something`,
        prepareSubmit: () => {
          const snapshot = {
            draft: effectiveDraft(inboxItemById(item.id) ?? item),
            conflictRevision: draftConflicts.get(item.id) ?? 0,
          };
          return async (text, options) => {
            if (!(await askAgent(item, text, options, snapshot)))
              throw new Error("Could not complete the request. Your message has been kept.");
          };
        },
      },
      compact,
    ),
  });
}

export function draftMessageTpl(item: InboxItem): TemplateResult | typeof nothing {
  if (item.status !== "open" || usesOutputReview(item) || (item.sentChat && !item.draft)) return nothing;
  const busy = chatting.has(item.id);
  const draft = effectiveDraft(item);
  const gmail = item.source === "gmail";
  const showCc = gmail && ((draft.cc?.length ?? 0) > 0 || (item.gmail?.cc?.length ?? 0) > 0);
  return html`
    <div class="inbox-draft ${gmail ? "email" : "slack"}">
      <div class="inbox-draft-head">
        <span class="inbox-draft-label">Draft reply</span>
        ${
          item.draftSessionId
            ? html`<a
                class="inbox-session-link"
                href=${deepLinkPath(UI_BASE, "chats", item.draftSessionId)}
                title="See how the agent arrived at this draft"
                @click=${(e: MouseEvent) => openDraftSession(e, item.draftSessionId!)}
              >
                ${icon(ArrowUpRight, 12)}<span>Open agent session</span>
              </a>`
            : nothing
        }
        ${
          item.externalUrl
            ? html`<a class="inbox-external-link" href=${item.externalUrl} target="_blank" rel="noreferrer noopener">
                ${icon(ArrowUpRight, 12)}<span>Open in ${gmail ? "Gmail" : "Slack"}</span>
              </a>`
            : nothing
        }
      </div>
      ${
        gmail
          ? html`
              <details class="inbox-draft-headers">
                <summary><span class="inbox-draft-headers-peek">${headerPeek(item, draft)}</span></summary>
                <div class="inbox-draft-headers-fields">
                  <label class="inbox-field">
                    <span>To</span>
                    <input
                      type="text"
                      ?disabled=${busy}
                      .value=${live((draft.to ?? []).join(", "))}
                      placeholder="[email protected]"
                      @input=${(e: Event) => editDraft(item, { to: addressHeaderList((e.currentTarget as HTMLInputElement).value) })}
                      @blur=${() => void persistDraft(item)}
                    />
                  </label>
                  ${
                    showCc
                      ? html`<label class="inbox-field">
                          <span>Cc</span>
                          <input
                            type="text"
                            ?disabled=${busy}
                            .value=${live((draft.cc ?? []).join(", "))}
                            @input=${(e: Event) => editDraft(item, { cc: addressHeaderList((e.currentTarget as HTMLInputElement).value) })}
                            @blur=${() => void persistDraft(item)}
                          />
                        </label>`
                      : nothing
                  }
                  <label class="inbox-field">
                    <span>Subject</span>
                    <input
                      type="text"
                      ?disabled=${busy}
                      .value=${live(draftSubject(item, draft))}
                      @input=${(e: Event) => editDraft(item, { subject: (e.currentTarget as HTMLInputElement).value })}
                      @blur=${() => void persistDraft(item)}
                    />
                  </label>
                </div>
              </details>
            `
          : nothing
      }
      <div class="inbox-draft-body-wrap">
        <textarea
          class="inbox-draft-body"
          aria-label="Draft reply"
          ?disabled=${busy}
          rows=${gmail ? 7 : 3}
          placeholder=${item.draft ? "" : "No draft yet. The next sync writes one, or write your own."}
          .value=${live(draft.body)}
          @input=${(e: Event) => editDraft(item, { body: (e.currentTarget as HTMLTextAreaElement).value })}
          @blur=${() => void persistDraft(item)}
        ></textarea>
      </div>
      ${
        !gmail && item.reactions?.length
          ? html`<div class="inbox-reactions">${item.reactions.map((name) => reactionChipTpl(name))}</div>`
          : nothing
      }
    </div>
  `;
}

function reactionChipTpl(name: string): TemplateResult {
  const char = charForName(name);
  return html`<span class="inbox-reaction-chip" title=${`:${name}:`}>${char ?? `:${name}:`}</span>`;
}

function handledStateLabel(item: InboxItem): string {
  if (item.status === "sent") return "Sent";
  if (item.status === "replied") return "Replied";
  return item.noReplyNeeded ? "No reply needed" : "Dismissed";
}

function itemSideMark(item: InboxItem, handled: boolean): TemplateResult | typeof nothing {
  if (handled) return html`<span class="inbox-item-state">${handledStateLabel(item)}</span>`;
  if (item.draft)
    return html`<span class="inbox-item-drafted" title="A reply is drafted and ready">${icon(CheckCheck, 12)}</span>`;
  return nothing;
}

function reopenButtonTpl(item: InboxItem): TemplateResult {
  return html`<button class="btn inbox-reopen" type="button" @click=${() => void setItemStatus(item, "open")}>
    ${icon(Undo2, 13)}<span>Reopen</span>
  </button>`;
}

export function handledNoteTpl(item: InboxItem): TemplateResult {
  if (item.status === "sent") {
    return html`<div class="inbox-handled-note">
      ${icon(CheckCheck, 13)}<span>Reply sent ${item.sentAt ? relTime(item.sentAt) : ""}</span>
    </div>`;
  }
  if (item.status === "replied") {
    const where = item.source === "slack" ? "Slack" : "Gmail";
    return html`<div class="inbox-handled-note inbox-replied-note">
      <div class="inbox-handled-line">
        ${icon(CheckCheck, 13)}<span>You replied in ${where} ${item.repliedAt ? relTime(item.repliedAt) : ""}</span>
        ${reopenButtonTpl(item)}
      </div>
      ${item.externalReplyText ? html`<div class="inbox-replied-text">${slackTextTpl(item, item.externalReplyText)}</div>` : nothing}
    </div>`;
  }
  const label = `${handledStateLabel(item)} ${item.dismissedAt ? relTime(item.dismissedAt) : ""}`;
  if (item.noReplyNeeded?.reason)
    return html`<div class="inbox-handled-note inbox-replied-note">
      <div class="inbox-handled-line">${icon(X, 13)}<span>${label}</span> ${reopenButtonTpl(item)}</div>
      <div class="inbox-replied-text">${item.noReplyNeeded.reason}</div>
    </div>`;
  return html`<div class="inbox-handled-note">
    ${icon(X, 13)}<span>${label}</span>
    ${reopenButtonTpl(item)}
  </div>`;
}

function dismissItemTpl(item: InboxItem): TemplateResult | typeof nothing {
  if (item.status !== "open") return nothing;
  return html`<button
    class="inbox-dismiss"
    type="button"
    ?disabled=${chatting.has(item.id) || acting.has(item.id)}
    @click=${() => void (groupOf(item).length > 1 ? archiveGroup(item) : setItemStatus(item, "dismissed"))}
  >
    ${groupOf(item).length > 1 ? `Archive all ${groupOf(item).length}` : "Dismiss"}
  </button>`;
}

const PRIORITY_LABELS: Record<InboxPriority, string> = {
  urgent: "Urgent",
  high: "High",
  normal: "Normal",
  low: "Low",
};

async function overrideTriage(item: InboxItem, kind: "prioritize" | "ungroup", args?: Record<string, unknown>) {
  if (acting.has(item.id)) return;
  acting.add(item.id);
  drawAll();
  try {
    upsertItem(await postAction(item, kind, args));
    void refreshInbox({ silent: true });
  } catch (e) {
    notify(`Couldn't update the item: ${e instanceof Error ? e.message : e}`);
  } finally {
    acting.delete(item.id);
    drawAll();
  }
}

function loopTriage(item: InboxItem): { prioritize: boolean; consolidate: boolean } {
  const loop = inboxState.selected.find((selected) => selected.id === item.loopId);
  return { prioritize: loop?.prioritize === true, consolidate: loop?.consolidate === true };
}

function priorityMarkTpl(item: InboxItem): TemplateResult | typeof nothing {
  if ((item.priority !== "urgent" && item.priority !== "high") || item.status !== "open") return nothing;
  const reason = item.priorityPinned ? "Set by you" : item.priorityReason;
  return html`<span class="inbox-priority inbox-priority-${item.priority}" ${reason ? tip(reason) : nothing}
    >${PRIORITY_LABELS[item.priority]}</span
  >`;
}

function triageControlsTpl(item: InboxItem): TemplateResult | typeof nothing {
  if (item.status !== "open") return nothing;
  const { prioritize } = loopTriage(item);
  if (!prioritize && !item.groupId) return nothing;
  return html`<span class="inbox-triage-controls" ${prioritize ? tip("Priority") : nothing}>
    ${
      prioritize
        ? fieldSelect({
            className: "inbox-filter-control inbox-priority-control",
            ariaLabel: "Priority",
            value: item.priority ?? "normal",
            disabled: acting.has(item.id),
            onChange: (value) => void overrideTriage(item, "prioritize", { priority: value }),
            options: (Object.keys(PRIORITY_LABELS) as InboxPriority[]).map(
              (value) =>
                html`<option value=${value} ?selected=${(item.priority ?? "normal") === value}>
                  ${PRIORITY_LABELS[value]}
                </option>`,
            ),
          })
        : nothing
    }
    ${
      item.groupId
        ? html`<button
            class="inbox-dismiss"
            type="button"
            ?disabled=${acting.has(item.id)}
            @click=${() => void overrideTriage(item, "ungroup")}
          >
            Remove from group
          </button>`
        : nothing
    }
  </span>`;
}

const expandedSubjects = new Set<string>();

function groupOf(item: InboxItem): InboxItem[] {
  if (!item.groupId || !loopTriage(item).consolidate) return [item];
  const members = inboxState.items.filter((other) => other.groupId === item.groupId && other.status === "open");
  const head = members.find((member) => member.id === item.groupId);
  return head ? [head, ...members.filter((member) => member !== head)] : [item];
}

async function archiveGroup(head: InboxItem): Promise<void> {
  if (acting.has(head.id)) return;
  acting.add(head.id);
  drawAll();
  try {
    upsertItem(await postAction(head, "dismiss", { group: true }));
    showArchiveToast(head);
    await refreshInbox({ silent: true });
  } catch (e) {
    notify(`Couldn't archive the group: ${e instanceof Error ? e.message : e}`);
  } finally {
    acting.delete(head.id);
    drawAll();
  }
}

function groupedRowsTpl(surface: InboxSurface, items: InboxItem[]): TemplateResult[] {
  const members = new Map<string, InboxItem[]>();
  for (const item of items) {
    if (!item.groupId || !loopTriage(item).consolidate) continue;
    members.set(item.groupId, [...(members.get(item.groupId) ?? []), item]);
  }
  const rows: TemplateResult[] = [];
  const drawn = new Set<string>();
  for (const item of items) {
    const group = item.groupId ? members.get(item.groupId) : undefined;
    if (!group || group.length < 2 || !group.some((member) => member.id === item.groupId)) {
      rows.push(itemRowTpl(surface, item));
      continue;
    }
    if (drawn.has(item.groupId!)) continue;
    drawn.add(item.groupId!);
    rows.push(
      itemRowTpl(
        surface,
        group.find((member) => member.id === item.groupId)!,
        group.length,
      ),
    );
  }
  return rows;
}

function itemRowTpl(surface: InboxSurface, item: InboxItem, groupSize = 1): TemplateResult {
  const inlineDetail = surface.pane;
  const open = surface.selectedId === item.id;
  const expanded = inlineDetail && open;
  const expandedAttr = inlineDetail ? String(open) : nothing;
  const handled = item.status !== "open";
  const gmail = item.source === "gmail";
  const slack = item.source === "slack";
  const senderId = item.slack?.userId ?? item.participants?.[0]?.key;
  const sender = item.participants?.find((person) => person.key === senderId) ?? {
    key: senderId ?? participantKey(item.from),
    name: participantName(item.from) || "Slack",
  };
  const heading = gmail ? item.from || item.title : (item.slack?.channelLabel ?? item.title);
  const sub = gmail ? item.title : item.from || inboxViewName(item.loopId);
  return html`
    <div class="inbox-item ${expanded ? "expanded" : ""} ${handled ? "handled" : ""} src-${item.source}">
      <div class="inbox-item-summary">
        <button
          class="inbox-item-row"
          type="button"
          aria-expanded=${expandedAttr}
          @click=${() => {
            const previous = surface.selectedId;
            if (previous && previous !== item.id) {
              const prevItem = inboxState.items.find((i) => i.id === previous);
              if (prevItem) void persistDraft(prevItem);
            }
            surface.selectedId = inlineDetail && open ? null : item.id;
            if (surface.selectedId) void loadDetail(item.id, item.loopId);
            if (!inlineDetail) syncInboxUrl(surface.selectedId, true);
            drawAll();
          }}
        >
          <span class="inbox-item-glyph ${slack ? "inbox-sender-avatar" : ""}">
            ${
              slack
                ? html`${participantsOf(item).length > 1 ? participantsTpl(item) : avatarTpl(sender)}<span
                      class="inbox-sender-badge"
                      aria-hidden="true"
                      >${slackMark(10)}</span
                    >`
                : sourceGlyph(item)
            }
          </span>
          <span class="inbox-item-main">
            <span class="inbox-item-top">
              ${groupSize > 1 ? html`<span class="inbox-group-count">${groupSize} similar ·</span>` : nothing}
              <span class="inbox-item-heading">${heading}</span>
              <span class="inbox-item-sub">${sub}</span>
            </span>
            <span class="inbox-item-snippet">${slackTextTpl(item, item.snippet, { links: false })}</span>
          </span>
          <span class="inbox-item-side">
            ${slack ? nothing : participantsTpl(item)} ${priorityMarkTpl(item)} ${itemSideMark(item, handled)}
            <span class="inbox-item-time" title=${fmtClock(item.receivedAt)}>${relTime(item.receivedAt)}</span>
            ${icon(expanded ? ChevronDown : ChevronRight, 13)}
          </span>
        </button>
        ${
          !handled
            ? html`<button
                class="session-menu-btn inbox-item-dismiss"
                type="button"
                aria-label=${groupSize > 1 ? `Archive ${groupSize} similar` : `Archive ${item.title || heading}`}
                ${tip(groupSize > 1 ? `Archive all ${groupSize}` : "Archive")}
                ?disabled=${acting.has(item.id)}
                @click=${() => void (groupSize > 1 ? archiveGroup(item) : setItemStatus(item, "dismissed"))}
              >
                ${icon(Archive, 13.5)}
              </button>`
            : nothing
        }
      </div>
      ${
        expanded
          ? html`<div class="inbox-item-detail">
              ${
                usesOutputReview(item)
                  ? html`${triageControlsTpl(item) === nothing ? nothing : html`<div class="inbox-item-detail-actions">${triageControlsTpl(item)}</div>`}${reviewTpl(item)}`
                  : html`${handled ? nothing : html`<div class="inbox-item-detail-actions">${triageControlsTpl(item)}${dismissItemTpl(item)}</div>`}
                    ${groupOf(item).length > 1 ? subjectTpl(item) : nothing} ${contextTpl(item)}
                    ${draftMessageTpl(item)} ${handled ? handledNoteTpl(item) : chatTpl(item, true)}`
              }
            </div>`
          : nothing
      }
    </div>
  `;
}

const MIGRATION_STATUS = "Moving your Inbox…";
const MIGRATION_HINT = "Available once your existing Inbox finishes moving";

function syncStatusLabel(cron: InboxSyncCron): string {
  if (!cron.enabled) return "Sync paused";
  return cron.lastFiredAt ? `Synced ${relTime(cron.lastFiredAt)}` : "First sync pending";
}

function syncActionTpl(opts: {
  label: string;
  busyLabel: string;
  busy: boolean;
  disabled?: boolean;
  tooltip: string;
  action: () => void;
}): TemplateResult {
  return html`<button
    class="btn inbox-sync-action"
    type="button"
    ${tip(opts.tooltip)}
    ?disabled=${opts.busy || opts.disabled}
    @click=${opts.action}
  >
    ${icon(RefreshCw, 13)}<span>${opts.busy ? opts.busyLabel : opts.label}</span>
  </button>`;
}

function syncLoops(viewId: string) {
  return inboxState.selected.filter(
    (loop) => loop.source && (viewId === "all" || loop.id === viewId || loop.source === viewId),
  );
}

const ASSISTANT_HIDDEN_KEY = "web-ui:inbox-assistant-hidden";
let assistantHidden = ((): boolean => {
  try {
    return localStorage.getItem(ASSISTANT_HIDDEN_KEY) === "1";
  } catch {
    return false;
  }
})();

function assistantToggleTpl(): TemplateResult {
  const label = assistantHidden ? "Show assistant" : "Hide assistant";
  return html`<button
    class="icon-btn compact subtle inbox-assistant-toggle"
    type="button"
    aria-label=${label}
    aria-expanded=${String(!assistantHidden)}
    ${tip(label)}
    @click=${() => {
      assistantHidden = !assistantHidden;
      try {
        localStorage.setItem(ASSISTANT_HIDDEN_KEY, assistantHidden ? "1" : "0");
      } catch {
        void 0;
      }
      drawAll();
    }}
  >
    ${icon(assistantHidden ? PanelRightOpen : PanelRightClose, 17)}
  </button>`;
}

function syncLineTpl(surface: InboxSurface): TemplateResult | typeof nothing {
  if (surface.viewId === "sent") {
    const busy = isSentMailLoading();
    return syncActionTpl({
      label: "Refresh",
      busyLabel: "Refreshing…",
      busy,
      tooltip: "Refresh sent mail",
      action: () => void loadSentMail(drawAll),
    });
  }
  const loops = syncLoops(surface.viewId);
  const crons = loops.flatMap((loop) => (loop.syncCron ? [loop.syncCron] : []));
  const moving = inboxState.migrationPending;
  if (!crons.length && !moving) return nothing;
  const status =
    crons.length === 1 ? syncStatusLabel(crons[0]!) : `${crons.filter((cron) => cron.enabled).length} syncs on`;
  return html`<span class="inbox-sync-line">
    ${syncActionTpl({
      label: "Sync",
      busyLabel: "Syncing…",
      busy: inboxState.syncBusy,
      disabled: moving,
      tooltip: moving ? MIGRATION_HINT : "Sync now",
      action: () => void syncNow(surface.viewId),
    })}
    <span class="inbox-sync-status" role=${moving ? "status" : nothing}>${moving ? MIGRATION_STATUS : status}</span>
  </span>`;
}

function surfaceTpl(surface: InboxSurface): TemplateResult {
  const density = surface.density();
  const compact = density !== "full";
  const allOpen = itemsFor(surface.viewId, "open");
  const resolvedItems = allOpen.filter((item) => item.source !== "gmail" && item.probablyResolved);
  const openItems = allOpen.filter((item) => item.source === "gmail" || !item.probablyResolved);
  const selectedLoop = inboxState.selected.find((loop) => loop.id === surface.viewId);
  const showEmailFilter =
    surface.viewId === "all" ||
    surface.viewId === "gmail" ||
    selectedLoop?.source === "gmail" ||
    selectedLoop?.sources?.includes("gmail");
  let emptyMessage = "No messages in this view yet. Sync to check for new messages.";
  if (showEmailFilter && inboxState.filter === "triaged")
    emptyMessage = "Nothing is waiting on you. Choose Light filtering or All emails to see more emails.";
  if (surface.viewId === "sent") emptyMessage = "No sent messages yet. Sent Email and Slack replies will appear here.";
  const handledItems = itemsFor(surface.viewId, "handled");
  const hasMore = !!feedWindows.get(surface.viewId)?.nextCursor;
  const setupLoops = inboxState.selected.filter(
    (loop) =>
      loop.source && !loop.cronId && !loop.ingestionActive && (surface.viewId === loop.id || surface.viewId === "all"),
  );
  const chips = html`
    <div class="inbox-chips" role="tablist" aria-label="Inbox views">
      ${inboxViews().map((v) => {
        const count = inboxOpenCount(v.id);
        return html`<button
          class="inbox-chip ${surface.viewId === v.id ? "active" : ""}"
          type="button"
          role="tab"
          aria-selected=${surface.viewId === v.id ? "true" : "false"}
          @click=${() => {
            if (surface === fullSurface) selectInboxView(v.id, true);
            else surface.viewId = v.id;
            void refreshInbox();
            drawAll();
          }}
        >
          ${v.id === "all" ? nothing : loopIcon(inboxState.selected.find((loop) => loop.id === v.id) ?? {})}<span>${v.name}</span>${count > 0 ? html`<span class="inbox-chip-count">${count}</span>` : nothing}
        </button>`;
      })}
      <button
        class="inbox-chip ${surface.viewId === "sent" ? "active" : ""}"
        type="button"
        role="tab"
        aria-selected=${surface.viewId === "sent"}
        @click=${() => {
          if (surface === fullSurface) selectInboxView("sent", true);
          else surface.viewId = "sent";
          ensureSentMail(drawAll);
          drawAll();
        }}
      >
        Sent
      </button>
    </div>
    <div class="inbox-view-actions">
      <button
        class="icon-btn subtle compact inbox-add-loop"
        type="button"
        aria-label="Add Loop"
        aria-expanded=${inboxState.picker}
        @click=${() => {
          inboxState.picker = !inboxState.picker;
          drawAll();
        }}
      >
        ${icon(Plus, 16)}
      </button>
      ${
        surface.viewId !== "all" && surface.viewId !== "sent"
          ? html`<button
              class="icon-btn subtle compact"
              aria-label=${`Options for ${inboxViewName(surface.viewId)}`}
              @click=${() => {
                inboxState.menuId = inboxState.menuId === surface.viewId ? null : surface.viewId;
                drawAll();
              }}
            >
              ${icon(MoreHorizontal, 16)}
            </button>`
          : nothing
      }
    </div>
  `;
  const list = html`
    ${
      !inboxState.loaded && inboxState.loading
        ? html`<div class="empty compact" role="status" aria-label="Reading your inbox…">
            <span aria-hidden="true">
              <span class="working-mark">${workingWave()}</span>${sheenLabel("Reading your inbox…", true)}
            </span>
          </div>`
        : nothing
    }
    ${
      inboxState.error && !inboxState.loaded
        ? html`<div class="empty compact">Couldn't load the inbox: ${inboxState.error}</div>`
        : nothing
    }
    ${
      inboxState.loaded && openItems.length === 0
        ? html`<div class="empty compact inbox-zero">${emptyMessage}</div>`
        : nothing
    }
    <div class="inbox-list">${groupedRowsTpl(surface, openItems)}</div>
    ${
      resolvedItems.length
        ? html`<div class="inbox-resolved-sect">
            <div class="inbox-resolved-head">Probably resolved · no reply likely needed</div>
            <div class="inbox-list inbox-resolved-list">${resolvedItems.map((i) => itemRowTpl(surface, i))}</div>
          </div>`
        : nothing
    }
    ${
      handledItems.length
        ? html`
            <button
              class="inbox-handled-toggle"
              type="button"
              aria-expanded=${surface.showHandled ? "true" : "false"}
              @click=${() => {
                surface.showHandled = !surface.showHandled;
                drawAll();
              }}
            >
              ${icon(surface.showHandled ? ChevronDown : ChevronRight, 13)}
              <span>Handled (${handledItems.length})</span>
            </button>
            ${surface.showHandled ? html`<div class="inbox-list handled">${handledItems.map((i) => itemRowTpl(surface, i))}</div>` : nothing}${surface.showHandled && feedWindows.get(`handled:${surface.viewId}`)?.nextCursor ? html`<button class="inbox-load-more" type="button" ?disabled=${inboxState.loading} @click=${() => void refreshInbox({ more: true, viewId: `handled:${surface.viewId}` })}>Load more handled</button>` : nothing}
          `
        : nothing
    }
  `;
  return html`
    <div class="inbox-surface ${compact ? "compact" : ""}" data-density=${density}>
      <div class="inbox-toolbar">
        ${chips} ${surface.pane ? html`<span class="inbox-toolbar-spacer"></span>${syncLineTpl(surface)}` : nothing}
      </div>
      ${
        showEmailFilter || hasMore
          ? html`
              <div class="inbox-filter-bar">
                ${
                  showEmailFilter
                    ? html`<div class="inbox-filter">
                        <span>Emails</span>
                        ${menuSelect({
                          className: "inbox-email-filter-control",
                          ariaLabel: "Email filter",
                          ariaDescription: INBOX_FILTERS.find((filter) => filter.id === inboxState.filter)?.description,
                          value: inboxState.filter,
                          disabled: inboxState.filterBusy || inboxState.loading,
                          keyboardNavigation: true,
                          onSelect: (value) => void selectInboxFilter(value as InboxFilter),
                          options: INBOX_FILTERS.map((filter) => ({ value: filter.id, label: filter.label })),
                        })}
                      </div>`
                    : nothing
                }
                ${
                  hasMore
                    ? html`<button
                        class="inbox-load-more"
                        type="button"
                        ?disabled=${inboxState.loading}
                        @click=${() => void refreshInbox({ more: true, viewId: surface.viewId })}
                      >
                        Load more
                      </button>`
                    : nothing
                }
              </div>
            `
          : nothing
      }
      ${
        setupLoops.length
          ? html`<section class="inbox-setup" aria-label="Set up account sync">
              ${setupLoops.map(
                (loop) =>
                  html`<div class="inbox-setup-row">
                    <span class="inbox-setup-icon" aria-hidden="true">${loopIcon(loop, 17)}</span>
                    <div class="inbox-setup-copy">
                      <span class="inbox-setup-title">${loop.name}</span
                      ><span class="inbox-setup-description"
                        >${inboxState.migrationPending ? MIGRATION_STATUS : "Sync not set up"}</span
                      >
                    </div>
                    <button
                      class="inbox-setup-action"
                      aria-label=${`Set up ${loop.name}`}
                      ${inboxState.migrationPending ? tip(MIGRATION_HINT) : nothing}
                      ?disabled=${inboxState.syncBusy || inboxState.migrationPending}
                      @click=${() => void setUpSync(loop.id)}
                    >
                      <span>${inboxState.syncBusy ? "Setting up…" : "Set up"}</span>${icon(ChevronRight, 14)}
                    </button>
                  </div>`,
              )}
            </section>`
          : nothing
      }
      ${
        inboxState.menuId
          ? html`<div class="inbox-loop-menu" role="menu">
              <button
                class="btn"
                role="menuitem"
                ?disabled=${!can("loops")}
                @click=${() => {
                  const id = inboxState.menuId!;
                  inboxState.menuId = null;
                  switchView("loops");
                  openLoop(id);
                }}
              >
                Open Loop
              </button>
              <button
                class="btn"
                role="menuitem"
                @click=${() => {
                  const id = inboxState.menuId!;
                  inboxState.menuId = null;
                  void toggleSelection(id);
                }}
              >
                Remove from Inbox
              </button>
            </div>`
          : nothing
      }
      ${
        inboxState.picker
          ? html`<section class="inbox-loop-picker" aria-label="Add Loop">
              <div class="inbox-draft-head">
                <strong>Loops in your Inbox</strong
                ><button
                  class="icon-btn"
                  aria-label="Close picker"
                  @click=${() => {
                    inboxState.picker = false;
                    drawAll();
                  }}
                >
                  ${icon(X, 16)}
                </button>
              </div>
              <p>Choose the Loops you want to review here.</p>
              ${inboxState.available.map((loop) => html`<label><input type="checkbox" .checked=${loop.selected} ?disabled=${inboxState.selectionBusy} @change=${() => void toggleSelection(loop.id)} />${loopIcon(loop)}<span>${loop.name}</span><span>${loop.selected ? "Included" : "Add"}</span></label>`)}
            </section>`
          : nothing
      }
      ${inboxState.notice ? html`<div class="inbox-notice" role="status">${inboxState.notice}</div>` : nothing}
      <div class="inbox-scroll">
        ${
          surface.viewId === "sent"
            ? sentMailTpl(drawAll, (message) => {
                resetActiveInboxItem();
                if (surface.pane) {
                  exitSplitIfActive();
                  switchView("inbox");
                }
                fullViewId = "sent";
                if (fullSurface) fullSurface.selectedId = null;
                syncInboxUrl(message.id, true);
                void openSentEmail(message, drawAll);
              })
            : list
        }
      </div>
    </div>
  `;
}

function itemPageTpl(item: InboxItem): TemplateResult {
  const handled = item.status !== "open";
  const gmail = item.source === "gmail";
  let heading = item.slack?.channelLabel ?? item.title;
  if (gmail) heading = item.from || item.title;
  else if (item.source === "generic") heading = inboxViewName(item.loopId);
  const sub = gmail ? item.title : "";
  const grouped = groupOf(item).length > 1 ? subjectTpl(item) : nothing;
  let detail: TemplateResult;
  if (!item.detailLoaded) detail = html`<div class="empty compact">Loading message…</div>`;
  else if (usesOutputReview(item)) detail = reviewTpl(item, false);
  else
    detail = html`${grouped} ${contextTpl(item)} ${draftMessageTpl(item)} ${handled ? handledNoteTpl(item) : nothing}`;
  return html`
    <div class="pane-head inbox-item-head src-${item.source}">
      <div class="inbox-item-head-copy">
        ${listBackLink("Inbox", closeInboxItem)}
        <h1 class="pane-title">
          <span class="inbox-item-glyph">${sourceGlyph(item)}</span><span>${heading}</span>
          <span class="inbox-item-head-meta">
            ${participantsTpl(item)} ${itemSideMark(item, handled)}
            <span class="inbox-item-time" title=${fmtClock(item.receivedAt)}>${relTime(item.receivedAt)}</span>
          </span>
        </h1>
        ${sub ? html`<div class="pane-subtitle">${sub}</div>` : nothing}
      </div>
      ${triageControlsTpl(item)} ${dismissItemTpl(item)} ${item.detailLoaded ? assistantToggleTpl() : nothing}
    </div>
    <div class="inbox-surface inbox-item-surface">
      <div class="inbox-scroll inbox-item-thread">
        ${inboxState.notice ? html`<div class="inbox-notice" role="status">${inboxState.notice}</div>` : nothing}
        ${detail}
      </div>
    </div>
    ${
      item.detailLoaded && !assistantHidden
        ? html`<aside class="inbox-item-aside" aria-label="Conversation assistant">${chatTpl(item)}</aside>`
        : nothing
    }
  `;
}

function sentDraftTpl(): TemplateResult | undefined {
  const saved = selectedSentChat();
  if (!saved) return;
  const item = toInboxItem(saved);
  if (item.status === "open" && item.draft) return html`${draftMessageTpl(item)}`;
  if (item.status !== "open")
    return html`<div class="inbox-draft">
      <p>Reply sent.</p>
      <button class="btn" @click=${() => void continueSentReply(item)}>Write another reply</button>
    </div>`;
  return undefined;
}

function keepingChatLogsPinned(host: HTMLElement, draw: () => void): void {
  const logs = () => [...host.querySelectorAll<HTMLElement>(".inbox-chat-log")];
  const wasAtBottom = logs().map((el) => el.scrollHeight - el.scrollTop - el.clientHeight < 24);
  draw();
  logs().forEach((el, i) => {
    if (wasAtBottom[i] ?? true) el.scrollTop = el.scrollHeight;
  });
}

function drawSurface(surface: InboxSurface): void {
  if (!can("inbox")) {
    render(nothing, surface.host);
    return;
  }
  if (!surface.host.isConnected && surface.pane) return;
  keepingChatLogsPinned(surface.host, () => render(surfaceTpl(surface), surface.host));
  const selected = inboxState.items.find((item) => item.id === surface.selectedId);
  if (selected) ensureItemSource(selected);
}

let fullSurface: InboxSurface | null = null;
let fullViewId = "all";
let pendingItemId: string | null = null;
let loadingDeepLink = false;
async function loadDeepLink(id: string): Promise<void> {
  try {
    const result = await api<{ item: LedgerItem; outputs: ReviewOutput[] }>(
      `/api/inbox?itemId=${encodeURIComponent(id)}`,
    );
    upsertItem({ ...toInboxItem(result.item), outputs: result.outputs, detailLoaded: true });
  } catch {
    if (fullSurface?.selectedId === id) fullSurface.selectedId = null;
    fullViewId = "sent";
    await openSentEmailById(id, drawAll);
  } finally {
    loadingDeepLink = false;
    drawAll();
  }
}

function drawFull(): void {
  if (!can("inbox") || appState.currentView !== "inbox" || !appState.mainEl) return;
  if (!fullSurface || !fullSurface.host.isConnected || fullSurface.host.parentElement !== appState.mainEl) {
    const host = document.createElement("div");
    host.className = "pane inbox-page content-wide-page";
    fullSurface = {
      host,
      viewId: fullViewId,
      pane: false,
      density: () => "full" as DensityTier,
      selectedId: fullSurface?.selectedId ?? null,
      showHandled: fullSurface?.showHandled ?? false,
    };
    appState.mainEl.replaceChildren(host);
  }
  fullSurface.viewId = fullViewId;
  if (pendingItemId) {
    fullSurface.selectedId = pendingItemId;
    pendingItemId = null;
  }
  const openItem = fullSurface.selectedId ? inboxState.items.find((i) => i.id === fullSurface?.selectedId) : undefined;
  const openSentEmail = selectedSentEmail();
  if (fullSurface.selectedId && !openItem?.detailLoaded && inboxState.loaded && !loadingDeepLink) {
    loadingDeepLink = true;
    void loadDeepLink(fullSurface.selectedId);
  }
  syncInboxUrl(openSentEmail?.id ?? fullSurface.selectedId);
  const host = fullSurface.host;
  host.classList.toggle("inbox-thread-page", Boolean(openItem?.detailLoaded) && !assistantHidden);
  const surface = fullSurface;
  let page: TemplateResult | typeof nothing;
  if (openItem) page = itemPageTpl(openItem);
  else if (openSentEmail) {
    page = sentEmailPageTpl(
      drawAll,
      sentChatTpl(drawAll, (item) => chatTpl(toInboxItem(item))),
      sentDraftTpl(),
      closeInboxItem,
    );
  } else
    page = html`
      <div class="inbox-index-layout">
        <div class="inbox-index-feed">
          <div class="pane-head">
            <h1 class="pane-title">Inbox</h1>
            <div class="pane-head-actions">${syncLineTpl(surface)} ${assistantToggleTpl()}</div>
          </div>
          ${surfaceTpl(surface)}
        </div>
        ${
          assistantHidden
            ? nothing
            : inboxChat({
                kind: "inbox",
                hasEmail: inboxState.selected.some(
                  (loop) => loop.sources?.includes("gmail") || loop.source === "gmail",
                ),
                hasSlack: inboxState.selected.some(
                  (loop) => loop.sources?.includes("slack") || loop.source === "slack",
                ),
                hasDrafts: inboxState.items.some((item) => Boolean(item.draft) && item.status === "open"),
              })
        }
      </div>
    `;
  keepingChatLogsPinned(host, () => render(page, host));
  if (openItem) ensureItemSource(openItem);
}

function syncInboxUrl(itemId: string | null, push = false): void {
  if (appState.currentView !== "inbox") return;
  const next = deepLinkPath(UI_BASE, "inbox", null, null, itemId ?? inboxViewSegment(fullViewId));
  if (`${location.pathname}${location.search}` === next) return;
  if (push) history.pushState(null, "", next);
  else history.replaceState(null, "", next);
}

export function resetActiveInboxItem(): void {
  const sent = selectedSentChat();
  if (sent) void persistDraft(toInboxItem(sent));
  resetSelectedSentEmail();
  const open = fullSurface?.selectedId;
  if (!open || !fullSurface) return;
  const item = inboxState.items.find((i) => i.id === open);
  if (item) void persistDraft(item);
  fullSurface.selectedId = null;
}

function closeInboxItem(): void {
  resetActiveInboxItem();
  syncInboxUrl(null);
  if (fullViewId === "sent") ensureSentMail(drawAll);
  drawAll();
}

export function routeInboxHistory(segment: string | null): void {
  if (!can("inbox")) return;
  resetActiveInboxItem();
  const viewId = inboxViewIdForSegment(segment);
  if (viewId) {
    fullViewId = viewId;
    pendingItemId = null;
    if (fullSurface) {
      fullSurface.viewId = viewId;
      fullSurface.selectedId = null;
    }
    if (viewId === "sent") ensureSentMail(drawAll);
  } else {
    fullViewId = "all";
    pendingItemId = segment;
    if (fullSurface) {
      fullSurface.viewId = "all";
      fullSurface.selectedId = segment;
    }
  }
  if (appState.currentView === "inbox") drawAll();
}

export function drawAll(): void {
  for (const s of surfaces) drawSurface(s);
  drawFull();
  renderSidebarTop();
  notifyPanesChanged();
}

export function selectInboxView(viewId: string, push = false): void {
  resetActiveInboxItem();
  if (!isInboxViewId(viewId)) viewId = "all";
  fullViewId = viewId;
  if (fullSurface) {
    fullSurface.viewId = viewId;
    fullSurface.selectedId = null;
  }
  syncInboxUrl(null, push);
}

export async function renderInbox(): Promise<void> {
  ensurePolling();
  ensureRealtime();
  drawFull();
  await refreshInbox({ ifStaleMs: 30_000, silent: true });
}

export function mountInboxPane(opts: {
  host: HTMLElement;
  viewId: string;
  density: () => DensityTier;
  onDensityChange: (handler: () => void) => void;
}): { dispose: () => void } {
  const surface: InboxSurface = {
    host: opts.host,
    viewId: opts.viewId,
    pane: true,
    density: opts.density,
    selectedId: null,
    showHandled: false,
  };
  surfaces.add(surface);
  opts.host.classList.add("inbox-pane-host");
  opts.onDensityChange(() => drawSurface(surface));
  ensurePolling();
  ensureRealtime();
  drawSurface(surface);
  void refreshInbox({ ifStaleMs: 30_000, silent: true });
  return {
    dispose() {
      surfaces.delete(surface);
      opts.host.classList.remove("inbox-pane-host");
    },
  };
}

registerPaneKind({
  paramsKey: "inboxView",
  glyph: InboxGlyph,
  title: (id) => inboxViewName(id),
  badge: (id) => (can("inbox") ? inboxOpenCount(id) : 0),
  mount: ({ host, id, density, onDensityChange }) => mountInboxPane({ host, viewId: id, density, onDensityChange }),
  maximize: (id) => {
    exitSplitIfActive();
    selectInboxView(id);
    switchView("inbox");
  },
});