Skip to content

AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).

35.9 KB
Raw Blame
"use client";

import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";

import Icon from "@/components/Icon";
import AdvancedFold from "@/components/settings/AdvancedFold";
import { WritesCard } from "@/components/settings/ReachCard";
import SettingsCard from "@/components/settings/SettingsCard";
import Switch from "@/components/Switch";
import Button from "@/components/ui/Button";
import {
  checkInboxNow,
  describeVoiceProfile,
  getDelegation,
  getVoiceProfile,
  learnVoiceProfile,
  refreshVoiceSignature,
  resetVoiceProfile,
  setDelegationTeam,
  setInboxWatch,
  setReadMyCalendar,
  updateVoiceProfile,
  type DelegationSettings,
  type DelegationTeam,
  type DescribedVoice,
  type InboxWatch,
  type ReadMyCalendar,
  type VoiceProfile,
} from "@/lib/api";
import { formatAgo } from "@/lib/setupStatus";
import { addPhrase, markNew, STYLE_PHRASES, styleSentences } from "@/lib/voiceStyle";

// Delegate → Act as me: let the Executive draft email AS you, in your own
// Gmail Drafts, when you ask it to — and, with What it writes as you at
// Draft replies automatically, for mail that needs you, which it sends when you tap Send
// on Today (or on its own, under Handle it for me, which has its own tab).
// Backed by GET /delegation, PUT /delegation/reach (WritesCard) and /delegation/voice.
// Not offered to anyone who can't have it (the owner can, and team members
// once the owner lets them: PUT /delegation/team) or on a backend without
// it: the hub then shows no tile, and this page says so.
//
// The page body: the mailbox and What it writes as you (with the inbox
// watcher's status under Draft replies automatically) up front; How I write, the
// page's `advanced` cards and Let team members use it under Advanced.

export const ACT_AS_ME_INTRO =
  "Drafts written as you, in your own mailbox. You send them.";

const LENGTHS = ["short", "medium", "long"] as const;
const FORMALITIES = ["casual", "neutral", "formal"] as const;
// The audiences a greeting is learned for (delegation/voice.py AUDIENCES) and
// its per-line limit (GREETING_MAX_CHARS).
const AUDIENCES = ["team", "contact", "other"] as const;
const AUDIENCE_LABEL: Record<string, string> = {
  team: "To your team",
  contact: "To your contacts",
  other: "To anyone else",
};
const GREETING_MAX_CHARS = 60;
// The longest description POST /delegation/voice/describe takes
// (delegation/voice.py DESCRIPTION_MAX_CHARS).
const DESCRIPTION_MAX_CHARS = 2000;
// While Check now runs, how often the card looks again, and for how long.
const CHECK_POLL_MS = 3000;
const MAX_CHECK_POLLS = 40;

function lines(text: string): string[] {
  return text
    .split("\n")
    .map((l) => l.trim())
    .filter(Boolean);
}

// The greetings as the form edits them: one per audience, "" for none.
function greetingFields(p: VoiceProfile): Record<string, string> {
  return Object.fromEntries(AUDIENCES.map((a) => [a, p.greetings[a] ?? ""]));
}

// `onSettings` hears every change made here, so the page's other cards
// (What it's learned) keep up; `children` sit after Read my calendar, and
// `advanced` (with its `advancedLabel` for the fold's summary) after How I
// write, under Advanced.
export default function ActAsMeCard({
  onSettings,
  children,
  advanced,
  advancedLabel,
}: {
  onSettings?: (next: DelegationSettings) => void;
  children?: ReactNode;
  advanced?: ReactNode;
  advancedLabel?: string;
} = {}) {
  const [settings, setSettingsState] = useState<DelegationSettings | null>(null);
  const setSettings = useCallback(
    (next: DelegationSettings | ((prev: DelegationSettings | null) => DelegationSettings | null)) => {
      setSettingsState(next);
      if (typeof next !== "function") onSettings?.(next);
    },
    [onSettings],
  );
  const [state, setState] = useState<"loading" | "hidden" | "ready" | "error">("loading");
  const [busy, setBusy] = useState(false);

  const load = useCallback(async (signal?: AbortSignal) => {
    try {
      const next = await getDelegation(signal);
      if (!next) {
        setState("hidden");
        return;
      }
      setSettingsState(next);
      setState("ready");
    } catch (err) {
      if ((err as Error)?.name === "AbortError") return;
      setState("error");
    }
  }, []);

  useEffect(() => {
    const controller = new AbortController();
    void load(controller.signal);
    return () => controller.abort();
  }, [load]);

  // While an inbox check runs, look again every few seconds until it's done.
  // A failed look keeps the card as it is and tries again; after
  // MAX_CHECK_POLLS it stops waiting and offers Check now again.
  const checking = settings?.inbox?.checking ?? false;
  const polls = useRef(0);
  const [pollTick, setPollTick] = useState(0);
  const [stoppedWaiting, setStoppedWaiting] = useState(false);
  useEffect(() => {
    if (!checking) {
      polls.current = 0;
      return;
    }
    if (polls.current >= MAX_CHECK_POLLS) {
      setStoppedWaiting(true);
      return;
    }
    const timer = setTimeout(() => {
      polls.current += 1;
      getDelegation()
        .then((next) => {
          if (next) setSettingsState(next);
        })
        .catch(() => { /* keep the card; the next look may work */ })
        .finally(() => setPollTick((n) => n + 1));
    }, CHECK_POLL_MS);
    return () => clearTimeout(timer);
  }, [checking, pollTick]);

  if (state === "loading") return <p className="text-[15px] text-fg-muted">Loading…</p>;
  if (state === "hidden") {
    return (
      <SettingsCard>
        <p className="text-[15px] text-fg-muted leading-relaxed">
          Act as me isn&apos;t available to you here. The owner of this Open Executive can turn it
          on for team members.
        </p>
      </SettingsCard>
    );
  }
  if (state === "error" || !settings) {
    return (
      <SettingsCard>
        <p className="text-[15px] text-fg-muted">Couldn&apos;t load this setting.</p>
      </SettingsCard>
    );
  }

  const connected = settings.gmail.status === "connected";
  const outlook = settings.gmail.provider === "microsoft";
  const mailbox = outlook ? "Outlook" : "Gmail";
  const on = settings.enabled;

  const recheck = async () => {
    setBusy(true);
    await load();
    setBusy(false);
  };

  const pre =
    "mt-2 whitespace-pre-wrap break-all rounded-xl border border-line bg-surface px-3 py-2 text-xs text-fg font-mono";
  return (
    <>
      <SettingsCard
        title={connected ? `Your ${mailbox}` : "Your mailbox"}
        description={connected ? `Connected to ${settings.gmail.email}.` : settings.gmail.message}
        action={
          connected ? (
            <span className="inline-flex items-center gap-2 text-sm font-medium text-fg">
              <span className="w-2.5 h-2.5 rounded-full bg-emerald-500" aria-hidden="true" />
              Connected
            </span>
          ) : undefined
        }
      >
        {!connected && (
          <div className="space-y-3">
            {settings.gmail.status === "not_configured" && (
              <div>
                <p className="text-sm text-fg-muted leading-relaxed">
                  For Gmail, on a computer with a browser, with the Executive&apos;s Google OAuth
                  client exported, run this and sign in as yourself, then put the file it writes
                  where the API reads it (see the Act as me section of .env.example):
                </p>
                <pre className={pre}>{settings.gmail.connect_command}</pre>
                {settings.gmail.outlook_connect_command && (
                  <>
                    <p className="mt-3 text-sm text-fg-muted leading-relaxed">
                      For Outlook, with the Executive&apos;s Microsoft 365 app exported, run this
                      instead and sign in as yourself with the code it prints:
                    </p>
                    <pre className={pre}>{settings.gmail.outlook_connect_command}</pre>
                  </>
                )}
              </div>
            )}
            <Button variant="primary" onClick={() => void recheck()} disabled={busy}>
              {busy ? "Checking…" : "Check again"}
            </Button>
          </div>
        )}
      </SettingsCard>

      {connected || on ? (
        <WritesCard
          settings={settings}
          onSettings={setSettings}
          inbox={
            settings.inbox?.enabled && (
              <InboxSection
                inbox={stoppedWaiting ? { ...settings.inbox, checking: false } : settings.inbox}
                mailbox={mailbox}
                onSettings={setSettings}
                onInbox={(inbox) => {
                  setStoppedWaiting(false);
                  polls.current = 0;
                  setSettings((prev) => (prev ? { ...prev, inbox } : prev));
                }}
              />
            )
          }
        />
      ) : null}

      {settings.calendar && (
        <CalendarSection calendar={settings.calendar} actAsMeOn={on} onSettings={setSettings} />
      )}

      {children}

      <AdvancedFold
        id="act-as-me-advanced"
        summary={["How I write", advanced ? advancedLabel : null, settings.team ? "Let team members use it" : null]
          .filter(Boolean)
          .join(" · ")}
      >
        <VoiceSection connected={connected} outlook={outlook} />
        {advanced}
        {settings.team && <TeamSection team={settings.team} onSettings={setSettings} />}
      </AdvancedFold>
    </>
  );
}

// The owner's "Let team members use Act as me" (PUT /delegation/team), shown
// only to the owner and only where the install allows it. Each member
// connects their own Gmail and turns it on for themselves; the owner sees
// counts only, never their mail, drafts or reply cards.
function TeamSection({
  team,
  onSettings,
}: {
  team: DelegationTeam;
  onSettings: (next: DelegationSettings) => void;
}) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const toggle = async () => {
    setBusy(true);
    setError(null);
    try {
      onSettings(await setDelegationTeam(!team.enabled));
    } catch (err) {
      setError(err instanceof Error ? err.message : "Could not save the setting.");
    } finally {
      setBusy(false);
    }
  };

  return (
    <SettingsCard
      title="Let team members use it"
      titleId="act-as-me-team-label"
      description={
        team.enabled
          ? "On: each team member can connect their own Gmail or Outlook and turn it on for themselves. Their mail, drafts and replies stay theirs alone. You see only who uses it and how much."
          : "Off: only you can use Act as me."
      }
      action={
        <Switch
          checked={team.enabled}
          onChange={() => void toggle()}
          disabled={busy}
          labelledBy="act-as-me-team-label"
        />
      }
    >
      {team.enabled && team.members.length > 0 && (
        <ul className="divide-y divide-line">
          {team.members.map((m) => (
            <li key={m.person_id} className="py-2 text-sm text-fg-muted">
              <span className="font-medium text-fg">{m.name}</span>
              {`: ${m.drafts_30d} ${m.drafts_30d === 1 ? "draft" : "drafts"}, ${m.sent_30d} sent in the last 30 days`}
              {m.inbox ? ". Drafts replies to their inbox." : "."}
            </li>
          ))}
        </ul>
      )}
      {error && <p className="mt-2 text-sm text-red-500">{error}</p>}
    </SettingsCard>
  );
}

// Inside What it writes as you, under Draft replies automatically: how the inbox
// watcher is doing, Check now (POST /delegation/inbox/check) and where its
// replies are kept (PUT /delegation/inbox {mailbox_drafts}).
function InboxSection({
  inbox,
  mailbox,
  onSettings,
  onInbox,
}: {
  inbox: InboxWatch;
  mailbox: string;
  onSettings: (next: DelegationSettings) => void;
  onInbox: (next: InboxWatch) => void;
}) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const on = inbox.enabled;

  // Also keep each reply in their mailbox's Drafts (off: on its card alone).
  const inDrafts = !!inbox.mailbox_drafts;
  const keepInDrafts = async (next: boolean) => {
    setBusy(true);
    setError(null);
    try {
      onSettings(await setInboxWatch({ mailbox_drafts: next }));
    } catch (err) {
      setError(err instanceof Error ? err.message : "Could not save the setting.");
    } finally {
      setBusy(false);
    }
  };

  const checkNow = async () => {
    setBusy(true);
    setError(null);
    try {
      onInbox(await checkInboxNow());
    } catch (err) {
      setError(err instanceof Error ? err.message : "Couldn't check your inbox.");
    } finally {
      setBusy(false);
    }
  };

  const last = inbox.last_poll_at && !inbox.checking ? ` Last checked ${formatAgo(inbox.last_poll_at)}.` : "";
  return (
    <div aria-label="Your inbox">
      {on && (
        <div className="ml-7 flex flex-wrap items-center gap-x-4 gap-y-2">
          <span className="text-sm text-fg-muted">
            {inbox.message}
            {last}
          </span>
          <Button size="sm" onClick={() => void checkNow()} disabled={busy || inbox.checking}>
            {inbox.checking ? "Checking…" : "Check now"}
          </Button>
        </div>
      )}
      {on && (
        <label className="mt-4 flex cursor-pointer items-start gap-3 border-t border-line pt-4">
          <input
            type="checkbox"
            checked={inDrafts}
            disabled={busy}
            onChange={(e) => void keepInDrafts(e.target.checked)}
            className="mt-0.5 h-5 w-5 flex-shrink-0 accent-indigo-500"
          />
          <span>
            <span className="block text-[15px] font-semibold text-fg">Also save inbox replies in my {mailbox} Drafts</span>
            <span className="mt-0.5 block text-sm text-fg-muted leading-snug">
              {inDrafts
                ? `Each reply is in your ${mailbox} Drafts too, so you can open it there.`
                : `Off: replies wait on their cards only, so your ${mailbox} Drafts stay clear.`}
            </span>
          </span>
        </label>
      )}
      {error && <p className="mt-2 text-sm text-red-500">{error}</p>}
    </div>
  );
}

// Read my calendar (PUT /delegation/calendar): the Executive reads your own
// calendar, read-only, when you ask about your day. Turning it on checks the
// calendar opens; a sign-in made without it shows the command that adds it,
// and one that already includes it shows nothing more.
function CalendarSection({
  calendar,
  actAsMeOn,
  onSettings,
}: {
  calendar: ReadMyCalendar;
  actAsMeOn: boolean;
  onSettings: (next: DelegationSettings) => void;
}) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const on = calendar.enabled;

  const toggle = async () => {
    setBusy(true);
    setError(null);
    try {
      onSettings(await setReadMyCalendar(!on));
    } catch (err) {
      setError(err instanceof Error ? err.message : "Could not save the setting.");
    } finally {
      setBusy(false);
    }
  };

  return (
    <SettingsCard
      title="Read my calendar"
      titleId="act-as-me-calendar-label"
      description={
        on
          ? "Ask about your day or your week in chat and it reads your own calendar. It never changes it."
          : actAsMeOn
            ? "Off: it can't see your calendar. On, it reads it when you ask, and never changes it."
            : "Set What it writes as you above Off first."
      }
      action={
        <Switch
          checked={on}
          onChange={() => void toggle()}
          disabled={busy || (!on && !actAsMeOn)}
          labelledBy="act-as-me-calendar-label"
        />
      }
    >
      {!on && actAsMeOn && calendar.granted !== true && (
        <div>
          <p className="text-sm text-fg-muted leading-relaxed">
            {calendar.granted === false
              ? "Your mailbox sign-in doesn't include your calendar yet. Run this once to add it:"
              : "If you connected your mailbox before, run this once to add your calendar to the sign-in:"}
          </p>
          <pre className="mt-2 whitespace-pre-wrap break-all rounded-xl border border-line bg-surface px-3 py-2 text-xs text-fg font-mono">
            {calendar.connect_command}
          </pre>
        </div>
      )}
      {error && <p className="mt-2 text-sm text-red-500">{error}</p>}
    </SettingsCard>
  );
}

// "How I write": the style drafts written as you follow, shown as a few plain
// sentences. Two ways to set it: describe it in your own words (a model turns
// that into the style, shown with what's new marked and a sample reply,
// saved only with Save), or learn it from your sent mail. The fields sit
// behind "Fine-tune details", and stay open while an edit is unsaved.
function VoiceSection({ connected, outlook = false }: { connected: boolean; outlook?: boolean }) {
  const [mode, setMode] = useState<"view" | "describe" | "review">("view");
  const [description, setDescription] = useState("");
  const [proposed, setProposed] = useState<DescribedVoice | null>(null);
  const [editing, setEditing] = useState(false);
  const [profile, setProfile] = useState<VoiceProfile | null>(null);
  const [greetings, setGreetings] = useState<Record<string, string>>({});
  const [habits, setHabits] = useState("");
  const [avoid, setAvoid] = useState("");
  const [signOff, setSignOff] = useState("");
  const [length, setLength] = useState("");
  const [formality, setFormality] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);
  const [loadFailed, setLoadFailed] = useState(false);

  const adopt = useCallback((p: VoiceProfile) => {
    setProfile(p);
    setGreetings(greetingFields(p));
    setHabits(p.habits.join("\n"));
    setAvoid(p.avoid.join("\n"));
    setSignOff(p.sign_off);
    setLength(p.length);
    setFormality(p.formality);
  }, []);

  useEffect(() => {
    const controller = new AbortController();
    getVoiceProfile(controller.signal)
      .then(adopt)
      .catch((err) => {
        if ((err as Error)?.name === "AbortError") return;
        setLoadFailed(true);
      });
    return () => controller.abort();
  }, [adopt]);

  if (loadFailed) {
    return (
      <SettingsCard title="How I write">
        <p className="text-sm text-fg-muted">Couldn&apos;t load how you write.</p>
      </SettingsCard>
    );
  }
  if (!profile) return null;

  // keepEdits (lock, signature, examples): a field you've changed and not
  // saved keeps your text; every other field takes the new value, which may
  // come from a change made elsewhere.
  const run = async (action: () => Promise<VoiceProfile>, keepEdits = false) => {
    const before = profile;
    setBusy(true);
    setError(null);
    setNotice(null);
    try {
      const next = await action();
      if (!keepEdits) {
        adopt(next);
        return;
      }
      const keep = (saved: string, fresh: string) => (typed: string) => (typed === saved ? fresh : typed);
      setProfile(next);
      setHabits(keep(before.habits.join("\n"), next.habits.join("\n")));
      setAvoid(keep(before.avoid.join("\n"), next.avoid.join("\n")));
      setSignOff(keep(before.sign_off, next.sign_off));
      setLength(keep(before.length, next.length));
      setFormality(keep(before.formality, next.formality));
      const [was, now] = [greetingFields(before), greetingFields(next)];
      setGreetings((typed) =>
        Object.fromEntries(AUDIENCES.map((a) => [a, keep(was[a], now[a])(typed[a] ?? "")])),
      );
    } catch (err) {
      setError(err instanceof Error ? err.message : "Could not save.");
    } finally {
      setBusy(false);
    }
  };

  const writeStyle = async () => {
    setBusy(true);
    setError(null);
    setNotice(null);
    try {
      setProposed(await describeVoiceProfile(description));
      setMode("review");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Couldn't write your style. Try again.");
    } finally {
      setBusy(false);
    }
  };

  const saveProposed = async () => {
    if (!proposed) return;
    await run(() =>
      updateVoiceProfile({
        greetings: proposed.greetings,
        sign_off: proposed.sign_off,
        length: proposed.length,
        formality: proposed.formality,
        habits: proposed.habits,
        avoid: proposed.avoid,
      }),
    );
    setMode("view");
    setProposed(null);
    setDescription("");
    setNotice("Saved. Drafts written as you now follow this.");
  };

  const takeGmailSignature = () =>
    void run(async () => {
      const next = await refreshVoiceSignature();
      if (!next.signature) {
        setNotice(
          profile.signature
            ? "Your Gmail settings have no signature now, so none is added."
            : "Your Gmail settings have no signature to add.",
        );
      }
      return next;
    }, true);

  const learned = profile.learned_at !== null;
  const sentences = styleSentences(profile);
  const hasStyle = sentences.length > 0;
  const savedGreetings = greetingFields(profile);
  const dirty =
    AUDIENCES.some((a) => greetings[a] !== savedGreetings[a]) ||
    habits !== profile.habits.join("\n") ||
    avoid !== profile.avoid.join("\n") ||
    signOff !== profile.sign_off ||
    length !== profile.length ||
    formality !== profile.formality;
  const linkButton =
    "min-h-touch text-sm font-medium text-accent hover:underline disabled:opacity-50 disabled:no-underline";
  const field =
    "rounded-xl border border-line bg-surface px-3 text-[15px] text-fg focus:outline-none focus:border-line-strong";
  const showForm = editing || dirty;
  const source =
    profile.updated_by === "learn"
      ? `Learned from ${profile.sample_count} of your sent emails`
      : learned
        ? "Learned from your sent mail, then changed by you"
        : "Set by you";
  const feedback = (
    <>
      {notice && <p className="mt-2 text-sm text-fg-muted">{notice}</p>}
      {error && <p className="mt-2 text-sm text-red-500">{error}</p>}
    </>
  );

  if (mode === "describe") {
    return (
      <SettingsCard
        title="Describe how you write"
        description={
          hasStyle
            ? "Write it the way you'd tell a new assistant. It changes your current style rather than starting over."
            : "Write it the way you'd tell a new assistant."
        }
      >
        <label htmlFor="voice-description" className="text-sm font-medium text-fg">
          In your own words
        </label>
        <GrowingTextarea
          id="voice-description"
          value={description}
          onChange={setDescription}
          minRows={5}
          maxLength={DESCRIPTION_MAX_CHARS}
          placeholder={`For example: I keep emails short, usually three or four lines. First names only. I sign off "Thanks, Sam".`}
        />
        <div className="mt-3 flex flex-wrap gap-2" aria-label="Add a phrase">
          {STYLE_PHRASES.map((phrase) => (
            <button
              key={phrase}
              type="button"
              onClick={() => setDescription((d) => addPhrase(d, phrase))}
              className="min-h-touch rounded-full border border-line bg-surface-overlay px-3 text-sm font-medium text-fg hover:bg-surface-hover"
            >
              <span className="text-accent">+</span> {phrase}
            </button>
          ))}
        </div>
        <div className="mt-4 flex flex-wrap items-center gap-2">
          <Button variant="primary" disabled={busy || !description.trim()} onClick={() => void writeStyle()}>
            {busy ? "Writing your style…" : "Write my style"}
          </Button>
          <Button variant="ghost" disabled={busy} onClick={() => setMode("view")}>
            Cancel
          </Button>
        </div>
        <p className="mt-2 text-[13px] text-fg-subtle">Nothing changes until you save.</p>
        {feedback}
      </SettingsCard>
    );
  }

  if (mode === "review" && proposed) {
    return (
      <SettingsCard title="Here's your new style" description="Check it, then save. New lines are marked.">
        <ul className="space-y-2">
          {markNew(profile, proposed).map(({ text, isNew }) => (
            <StyleLine key={text} text={text} isNew={isNew} />
          ))}
        </ul>
        {proposed.sample_reply && (
          <div className="mt-5 text-sm">
            <div className="font-medium text-fg">A reply would read like</div>
            <div className="mt-2 whitespace-pre-wrap break-words border-l-2 border-accent pl-3 leading-relaxed text-fg">
              {proposed.sample_reply}
            </div>
          </div>
        )}
        <div className="mt-5 flex flex-wrap items-center gap-2 border-t border-line pt-4">
          <Button variant="primary" disabled={busy} onClick={() => void saveProposed()}>
            {busy ? "Saving…" : "Save"}
          </Button>
          <Button disabled={busy} onClick={() => setMode("describe")}>
            Change it
          </Button>
        </div>
        {feedback}
      </SettingsCard>
    );
  }

  return (
    <SettingsCard
      title="How I write"
      description={
        hasStyle
          ? "Drafts written as you follow this."
          : "Tell the Executive how you write, or let it learn from your sent mail. Drafts written as you follow it."
      }
    >
      {hasStyle && (
        <div className="mb-4 rounded-2xl border border-line bg-surface px-4 py-3">
          <ul className="space-y-2">
            {sentences.map((text) => (
              <StyleLine key={text} text={text} />
            ))}
          </ul>
          <p className="mt-2 text-[13px] text-fg-subtle">
            {source}
            {profile.locked ? " · locked, so it won't be relearned" : ""}
          </p>
        </div>
      )}
      <div className="flex flex-col gap-2 sm:flex-row sm:flex-wrap">
        <Button
          variant="primary"
          disabled={busy}
          onClick={() => {
            setError(null);
            setNotice(null);
            setMode("describe");
          }}
        >
          Describe it in your own words
        </Button>
        {!profile.locked && (
          <Button disabled={busy || !connected} onClick={() => void run(learnVoiceProfile)}>
            {busy ? "Working…" : learned ? "Learn again from my sent mail" : "Learn from my sent mail"}
          </Button>
        )}
      </div>
      {!dirty && (
        <button
          type="button"
          onClick={() => setEditing((v) => !v)}
          aria-expanded={showForm}
          aria-controls="voice-editor"
          className="mt-4 flex w-full min-h-touch items-center justify-between gap-3 border-t border-line pt-3 text-left text-sm"
        >
          <span className="font-medium text-accent">{showForm ? "Done fine-tuning" : "Fine-tune details"}</span>
          <span className="flex items-center gap-1 text-fg-subtle">
            <span className="hidden sm:inline">Greetings, sign-off, signature</span>
            <Icon
              name="chevron-right"
              size="w-4 h-4"
              className={`transition-transform ${showForm ? "rotate-90" : ""}`}
            />
          </span>
        </button>
      )}

      {showForm && (
        <div id="voice-editor" className="mt-5 space-y-5">
          <div className="flex flex-wrap gap-4">
            <label className="flex items-center gap-2 text-sm text-fg-muted">
              Length
              <select value={length} onChange={(e) => setLength(e.target.value)} className={`${field} h-10`}>
                <option value="">—</option>
                {LENGTHS.map((l) => (
                  <option key={l} value={l}>
                    {l}
                  </option>
                ))}
              </select>
            </label>
            <label className="flex items-center gap-2 text-sm text-fg-muted">
              Tone
              <select
                value={formality}
                onChange={(e) => setFormality(e.target.value)}
                className={`${field} h-10`}
              >
                <option value="">—</option>
                {FORMALITIES.map((f) => (
                  <option key={f} value={f}>
                    {f}
                  </option>
                ))}
              </select>
            </label>
          </div>

          <fieldset>
            <legend className="text-sm font-medium text-fg">Greeting</legend>
            <p className="text-[13px] text-fg-subtle leading-relaxed">
              {"{first}"} becomes their first name. Leave one empty to let each draft choose.
            </p>
            <div className="mt-2 space-y-2">
              {AUDIENCES.map((audience) => (
                <label
                  key={audience}
                  className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-3 text-sm text-fg-muted"
                >
                  <span className="sm:w-36 flex-shrink-0">{AUDIENCE_LABEL[audience]}</span>
                  <input
                    type="text"
                    value={greetings[audience] ?? ""}
                    onChange={(e) => setGreetings((g) => ({ ...g, [audience]: e.target.value }))}
                    placeholder="Not set"
                    maxLength={GREETING_MAX_CHARS}
                    className={`${field} h-10 min-w-0 flex-1`}
                  />
                </label>
              ))}
            </div>
          </fieldset>

          <label className="block text-sm font-medium text-fg">
            Sign-off
            <GrowingTextarea value={signOff} onChange={setSignOff} minRows={2} />
          </label>
          <label className="block text-sm font-medium text-fg">
            Habits (one per line)
            <GrowingTextarea value={habits} onChange={setHabits} minRows={3} />
          </label>
          <label className="block text-sm font-medium text-fg">
            Never (one per line)
            <GrowingTextarea value={avoid} onChange={setAvoid} minRows={2} />
          </label>

          <div className="text-sm text-fg-muted">
            <div className="font-medium text-fg">Signature</div>
            {profile.signature ? (
              <>
                <p className="mt-0.5 leading-relaxed">
                  {outlook
                    ? "Added to the end of every draft. Outlook doesn't share your signature with apps, so it can't be refreshed from there."
                    : "Added to the end of every draft, from your Gmail settings."}
                </p>
                <div className="mt-2 whitespace-pre-wrap break-words border-l-2 border-line pl-3 leading-relaxed text-fg">
                  {profile.signature}
                </div>
                <div className="mt-1 flex flex-wrap gap-x-4">
                  {!outlook && (
                    <button
                      type="button"
                      disabled={busy || !connected}
                      onClick={takeGmailSignature}
                      className={linkButton}
                    >
                      Refresh from Gmail
                    </button>
                  )}
                  <button
                    type="button"
                    disabled={busy}
                    onClick={() => void run(() => updateVoiceProfile({ clear_signature: true }), true)}
                    className={linkButton}
                  >
                    Don&apos;t add my signature
                  </button>
                </div>
              </>
            ) : (
              <>
                <p className="mt-0.5 leading-relaxed">
                  {outlook
                    ? "No signature is added to drafts: Outlook doesn't share your signature with apps, so drafts end with your sign-off."
                    : "No signature is added to drafts."}
                </p>
                {!outlook && (
                  <button
                    type="button"
                    disabled={busy || !connected}
                    onClick={takeGmailSignature}
                    className={linkButton}
                  >
                    Add my Gmail signature
                  </button>
                )}
              </>
            )}
          </div>

          {profile.exemplars.length > 0 && (
            <div className="text-sm text-fg-muted">
              <div className="font-medium text-fg">Examples of your writing</div>
              <p className="mt-0.5 leading-relaxed">
                Short passages from your sent mail that set the tone. Drafts never reuse what they say.
              </p>
              <ul className="mt-2 space-y-2">
                {profile.exemplars.map((example, i) => (
                  <li
                    key={i}
                    className="whitespace-pre-wrap break-words border-l-2 border-line pl-3 leading-relaxed text-fg"
                  >
                    {example}
                  </li>
                ))}
              </ul>
              <button
                type="button"
                disabled={busy}
                onClick={() => void run(() => updateVoiceProfile({ clear_exemplars: true }), true)}
                className={linkButton}
              >
                Remove examples
              </button>
            </div>
          )}

          <div className="flex flex-wrap items-center gap-2 border-t border-line pt-4">
            <Button
              variant="primary"
              disabled={busy || !dirty}
              onClick={() =>
                void run(() =>
                  updateVoiceProfile({
                    greetings: Object.fromEntries(
                      AUDIENCES.map((a) => [a, (greetings[a] ?? "").trim()]).filter(([, g]) => g),
                    ),
                    habits: lines(habits),
                    avoid: lines(avoid),
                    sign_off: signOff,
                    length,
                    formality,
                  }),
                )
              }
            >
              Save changes
            </Button>
            <Button
              disabled={busy}
              onClick={() => void run(() => updateVoiceProfile({ locked: !profile.locked }), true)}
            >
              {profile.locked ? "Unlock" : "Lock"}
            </Button>
            <Button variant="ghost" disabled={busy} onClick={() => void run(resetVoiceProfile)}>
              Reset
            </Button>
          </div>
        </div>
      )}
      {feedback}
    </SettingsCard>
  );
}

// One sentence of the style, marked when a described style adds it.
function StyleLine({ text, isNew = false }: { text: string; isNew?: boolean }) {
  return (
    <li className="flex items-baseline gap-2.5 text-[15px] leading-relaxed text-fg">
      <span aria-hidden className="h-1.5 w-1.5 flex-shrink-0 -translate-y-0.5 rounded-full bg-accent" />
      <span className="min-w-0 flex-1">{text}</span>
      {isNew && (
        <span className="flex-shrink-0 rounded-full bg-accent/15 px-2 py-0.5 text-[11px] font-semibold uppercase tracking-wide text-accent">
          New
        </span>
      )}
    </li>
  );
}

// A textarea as tall as its text, so every line shows without an inner
// scrollbar; it refits when the text changes (typed or loaded) and when the
// window's width does.
function GrowingTextarea({
  id,
  value,
  onChange,
  minRows,
  maxLength,
  placeholder,
}: {
  id?: string;
  value: string;
  onChange: (value: string) => void;
  minRows: number;
  maxLength?: number;
  placeholder?: string;
}) {
  const ref = useRef<HTMLTextAreaElement>(null);
  const fit = useCallback(() => {
    const el = ref.current;
    if (!el) return;
    el.style.height = "auto";
    // scrollHeight leaves out the border, which border-box sizing counts.
    el.style.height = `${el.scrollHeight + el.offsetHeight - el.clientHeight}px`;
  }, []);
  useLayoutEffect(fit, [fit, value]);
  useEffect(() => {
    window.addEventListener("resize", fit);
    return () => window.removeEventListener("resize", fit);
  }, [fit]);
  return (
    <textarea
      ref={ref}
      id={id}
      value={value}
      maxLength={maxLength}
      placeholder={placeholder}
      onChange={(e) => onChange(e.target.value)}
      rows={minRows}
      className="mt-1.5 block w-full resize-none overflow-hidden rounded-xl border border-line bg-surface px-3 py-2 text-[15px] font-normal leading-relaxed text-fg focus:outline-none focus:border-line-strong"
    />
  );
}