AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(ui): simplify every screen with a six-place menu and focused pages (#341)
Rufus3155921a77a7
diff --git a/packages/core/openexecutive/architecture/prebuilt/peer_memory.json b/packages/core/openexecutive/architecture/prebuilt/peer_memory.jsonindex ec08cf84..a86d227b 100644--- a/packages/core/openexecutive/architecture/prebuilt/peer_memory.json+++ b/packages/core/openexecutive/architecture/prebuilt/peer_memory.json@@ -2,6 +2,6 @@"section_id": "peer_memory","title": "Peer Memory (Person + Department)","markdown": "An external, peer-keyed memory layer gives the Executive durable cross-channel recall, sitting on top of Honcho via `openexecutive.memory.honcho_client`. The `HONCHO_ENABLED` env var gates it; when false every entry point short-circuits with `outcome=disabled` and behavior matches the pre-Honcho posture.\n\n### Two scopes\n\n- **Per-person**, keyed by `Person.id` — a user chatting from Discord, Telegram, email, or web is one peer card, so facts shared in any channel surface in the others. Each entry point resolves the caller to a `Person.id` (channel-ID lookups for adapters; `x-caller-email` for web).\n- **Per-department**, keyed by `department_<slug>` — each department accumulates an institutional voice from dept-scoped decisions, advice, committee outcomes, and dept-bound specialist turns.\n\n### Private to the principal\n\nThe principal's contacts are private to them (see Org), and two rules keep them out of shared memory. A turn about the principal's private mail (`Session.private_to_principal`: mail from a contact, or mail the principal forwarded) writes nothing to peer or department memory — its reply summarises that mail. And the principal's own peer memory, drawn from all their conversations, answers only the principal: `ask_about_person` with `person_id` = the principal returns the empty \"no data\" answer on any turn but the principal's own verified one (a teammate's own view of the principal, `target_person_id` = the principal, is the teammate's memory and still answers), and `GET /memories/people` / `/conclusions` leave the principal out for anyone else.\n\n### Flow\n\n`prefetch` runs once per turn and injects a `<peer_memory>` block into the user turn (empty on timeout or error). `HONCHO_PREFETCH_MODE` picks how the block is produced. `representation` (the default) reads the person's peer card and the derived conclusions most relevant to the inbound message straight from Honcho (`peer.context(search_query=…)`, `HONCHO_PREFETCH_MAX_CONCLUSIONS` of them, default 20): a GET with no LLM behind it, about 100 ms self-hosted. The block keeps whole lines only, up to a size cap (a line that does not fit is dropped, never cut), strips control characters and defangs a literal closing tag, since conclusions derive from text anyone who can email the Executive wrote. A person Honcho knows nothing about yet yields no block and an `empty` audit outcome. `dialectic` asks Honcho's chat endpoint with the message as the question and injects the synthesized prose (an LLM call, seconds), where `reasoning_level` trades latency for depth. The mode applies to every per-person prefetch, committee turns included. Only `prefetch_department` (one dialectic question per consulted specialist that maps to a department, yielding `<department_memory>`) and the `ask_about_person` tool always use the chat endpoint: they are deliberate questions off the inline path, the split Honcho's own guidance draws between `context()` for per-turn grounding and `chat()` for reasoned answers. After the response, `sync_turn` and `sync_department_turn` persist the exchange as fire-and-forget background tasks that never block the user. The Executive's reply is written under an `executive` peer resolved with `observe_me=false`: the person's representation sees both sides of the exchange, but Honcho no longer derives a representation of the Executive itself, which nothing read and which is where a person's words were occasionally misattributed to the Executive. Both record the person's words only. Honcho derives facts about a person from everything posted under their peer, so a turn whose prompt carries text the person did not write passes `memory_text` to `Executive.chat` / `stream_chat` / `stream_chat_with_committee`, and that — not the prompt — is what both syncs post: an inbound email records the sender's new text, the attachment filenames and its subject unless that is a reply's or forward's (`Re:`, `Fwd:`, `AW:`, `SV:`, `Re[2]:`, `[EXT] Re:` … — the earlier message's subject, often the Executive's own) (never the \"You have an inbound email\" framing, the headers with the Executive's own address in `To:`, the `[POLICY]` notice or the quoted chain, which held the Executive's own earlier email and taught Honcho that the sender *was* the Executive); a web upload records the typed text and filenames, not the extracted document text; a briefing handoff records a short line of what the user asked, phrased as the user speaking and ended before the headline, which follows on its own line (\"Let's discuss this flagged artifact.\" / \"I approve this proposal.\" — an \"Asked to …\" line came back as \"<user> was asked to …\", and a \"?\" in a headline inside the sentence voided the extraction quote); approve-with-edits records the same short line without the edited text, which starts as the Executive's card body and is often sent unchanged, not the Executive's card body it seeds. Filenames are noted as \"(Attached files: …)\", never the \"[Attached: …]\" label that marks inlined document text. The same speaker text, not the prompt, is what episodic extraction and the open-loop pass quote commitments from (see Memory and Attunement). Without `memory_text` the prompt is used, as before. The `<outbound_reply_context>` block that inbound hydration prepends for the LLM turn is also stripped before the message is posted, and from the prefetch query, so the Executive's own DM is never learned as something the person said.\n\n### What it knows, on Pulse\n\nThe Pulse page's Memory section has a **People** tab beside Decisions, Initiatives and Advice, backed by `GET /memories/people` (`people_overview`). It is read-only and costs no LLM call: one listing of the workspace's peers, then, for each peer that matches a rostered person by id, one page of that person's self-conclusions (newest first, `?recent=` of them, plus the total) and one card read with the identity lines the roster already supplies stripped out. Peers are matched, never created — `peer(id)` is a get-or-create POST, and a page you merely open must not mint peers for people who have never talked — and the `executive` and `department_*` peers and archived people are skipped. The listing runs under one clock (the SDK walks every page, bounded only per request otherwise) and each person is then read under the unscaled prefetch budget, at most eight at a time because these reads share the client with the live chat prefetch; one person's failure or timeout marks only that entry (`error`) and the others still render. The header and the tab share one in-flight request per page load. The header's Memories tile adds the conclusion total to the three episodic counts (its hint says how many are peer notes) without waiting on the read, and the tab hides itself when peer memory is disabled. Peers are matched only by an id spelled exactly as OE writes it, once per person, so a stray or repeated peer skips rather than fails or double-counts; within the newest page the conclusions are ordered by instant here (not by the rendered timestamp, which is not chronological across offsets) rather than trusting the server's order. Card elements and conclusions are split on physical lines before the scrub, so an identity claim on the second line of one element is caught too. Every line passes the same control-character and closing-tag scrub as the `<peer_memory>` block, since the text was derived from what people wrote. One `peer_memory` audit row per call, `op=overview`.\n\nEach person renders as a card: the peer card as a list of lines (long ones fold behind a toggle), then their notes in a scrollable pane seeded with the overview's newest few. **Show all** reads `GET /memories/people/{person_id}/conclusions?page=&size=` (`person_conclusions`; `size` 1–100, default 50) page by page as the pane scrolls: the same newest-first self-conclusions, ordered by instant and scrubbed exactly as the overview's, with `{status, person_id, items, page, size, total, has_more}`. The peer is found through the same workspace listing, never `peer(id)`, so an unknown, archived or never-talked person is a 404 rather than a new peer. Same clocks as the overview, one `peer_memory` audit row per page, `op=conclusions`.\n\n### Prefetch budget\n\nIn representation mode the prefetch is a single read with no LLM behind it: it runs on `HONCHO_PREFETCH_TIMEOUT_S` unscaled and `reasoning_level` is ignored. The rest of this section is the dialectic mode.\n\n`HONCHO_PREFETCH_TIMEOUT_S` is the knob for the **fast per-turn path** and is used unscaled there. The two per-turn callers pick different levels on purpose: `stream_chat` awaits the prefetch inline before the first streamed byte and defaults to `minimal`, the cheapest level, after `low` was measured hitting the ~5 s tail for peers with large representations; the chat route runs the prefetch inside the same gather as knowledge and episodic retrieval, so its `low` adds no dead air of its own and buys a fuller answer. Only the deliberate levels scale off it — `medium` 4x, `high` 5x, `max` 6x — capped by an absolute ceiling and never taken below the configured base. At the default 3s base that is 12s for `medium` with `high`/`max` at the 15s ceiling; at a 10s base every deliberate level *is* the ceiling. The multipliers only differentiate below it — the ceiling is the binding constraint at realistic bases, by design.\n\nHoncho's dialectic latency scales steeply with the level (roughly 2s at `low` against 8s at `medium`), so a single flat budget made the deeper levels unreachable: every `medium` call — the committee path — timed out and the turn silently ran with no peer memory at all, which is strictly worse than having asked for `low`. `medium` gets more headroom than its measurement alone implies because the budget spans `peer()` plus `chat()`, and a budget set at the mean still times out on half the calls.\n\nThe fast levels stay unscaled for two reasons: `prefetch` is awaited inline before the first streamed byte, so multiplying the base there would add dead air to every ordinary turn; and a multiplier above 1.0 flattens every level onto the ceiling once the base approaches it, which would make the operator's knob stop distinguishing the two paths. Each prefetch audit row records the `timeout_s` it ran under.\n\nThe SDK client's HTTP timeout is an **outer** bound, kept strictly greater than every *per-call* budget; the aggregate ceilings on whole passes are deliberately not folded in, since it applies per request and would otherwise hand every unbudgeted call a bound several times too long. Because it is no longer a tight bound, all three fire-and-forget bodies (person sync, department sync, department note) — whose individual calls are not separately budgeted — carry their own aggregate ceiling, as does the session listing in the workspace purge.\n\n### Peer identity\n\nPeers are keyed by `Person.id`, so the only identity signal Honcho gets from the key alone is a bare integer — and its dreaming agent concludes that the number *is* the person's name (observed in production as a card reading `IDENTITY: Name: 1`). Because cards are injected into the dialectic system prompt on every `chat()`, that error propagates into every later answer about that person. So both sync paths seed each person peer's card from the roster, for the sender, the department-turn originator, and co-present peers alike.\n\nThe card carries the **name only** — email and role would export roster PII to a third-party memory service, including for people who were merely cc'd, and neither is needed to fix the defect. `set_card` replaces the whole card, so only `IDENTITY:` lines are swapped and the deriver's own `ATTRIBUTE:` / `RELATIONSHIP:` lines survive; the existing card is split on physical lines first, since one list element may itself span lines and hide an identity claim on its second.\n\nRoster values are attacker-reachable — `upsert_person` is a chat tool an inbound email sender can reach — so a value is NFKC-normalised, stripped of control and format characters, whitespace-flattened, length-capped, and then held to an **allow-list** of letters, combining marks, digits and a small punctuation set, with the colon lookalikes the category allow-list would otherwise admit **stripped out** — taken from Unicode's confusables data (everything it maps to `:`), not from character names, since U+A4FD `ꓽ` is a Lisu *tone letter* whose name never says colon. They are stripped rather than grounds for refusing the value, because the visarga is the nominative ending in formal Devanagari and Gujarati names: refusing would leave those people never seeded, while stripping keeps the name as its stem form and still lets no colon shape reach the card. Modifier letters as a class stay allowed (々 in 佐々木, ー in ジョーンズ, ʻ in Hawaiʻi). A deny-list of structure tokens is not enough here: the consumer is an LLM system prompt rather than a parser, so `ATTRIBUTE :`, a fullwidth colon and a homoglyph all read the same to the model while defeating a literal match. The allow-list refuses every colon variant, which is what card structure depends on — checked by an exhaustive test over every Unicode codepoint whose name contains COLON plus an explicit test of the confusables the names miss. It does **not** stop a value that is merely persuasive prose — OE already embeds `full_name` in its own system prompt, so that exposure is pre-existing rather than introduced here.\n\nSeeding runs *after* the message write and *outside* the sync ceiling, and is audited as its own `seed_identity` row (`ok` only when no peer's attempt failed; `error` when any did, with the `failed` count on the row; `timeout` when the pass or the roster read hit its ceiling; `empty` when there was nobody to seed) — so the sync row is a pure record of the persist, emitted the instant the write lands, and a slow card round trip can neither delay nor replace it. It is bounded per peer *and* per pass, and is best-effort. It is memoized per `(workspace, person)` on the facts sent with a recheck interval — a rename re-seeds immediately, and because the deriver keeps re-deriving identity from the peer id, a one-shot memo would let `IDENTITY: Name: 1` come back unnoticed. A failed attempt is memoized separately and briefly — including every peer a pass-ceiling cut-off left in flight or unreached — so a degraded card endpoint is probed once per interval rather than once per peer per turn.\n\n### Cross-pollination & isolation\n\nWhen a person turn touches a department, the dept peer joins the person's session as a co-present peer — the hybrid peer graph that lets later queries synthesize across both timelines, with synthesis depth degrading at greater peer-graph distance. Demo fixtures run in a sacrificial `openexec-fixture-<name>` workspace so demo turns never pollute real peer cards. Every wrapper call emits a `peer_memory` audit row (`op` + `outcome`) into the per-turn flow at `/audit/session/{id}`.",- "mermaid": "flowchart TD\n Turn[\"Executive turn\"]\n Gate{\"HONCHO_ENABLED\"}\n Pre[\"prefetch: representation read (default)<br/>or dialectic query; prefetch_department: dialectic\"]\n Inj[\"peer_memory + department_memory<br/>injected into USER turn\"]\n Sync[\"sync_turn / sync_department_turn<br/>fire-and-forget\"]\n Honcho[\"Honcho peers<br/>person + department\"]\n Audit[\"peer_memory audit row\"]\n Turn --> Gate\n Gate -->|enabled| Pre\n Pre -->|context() / chat()| Honcho\n Honcho --> Inj\n Inj --> Turn\n Turn -->|after response| Sync\n Sync -->|\"co-present peers\"| Honcho\n Pulse[\"Pulse People tab<br/>GET /memories/people (read-only)\"]\n Pulse -->|\"conclusions + card\"| Honcho\n Pre --> Audit\n Sync --> Audit\n Pulse --> Audit\n class Turn entry\n class Gate compute\n class Pre compute\n class Sync compute\n class Honcho external\n class Pulse entry\n class Audit storage\n",+ "mermaid": "flowchart TD\n Turn[\"Executive turn\"]\n Gate{\"HONCHO_ENABLED\"}\n Pre[\"prefetch: representation read (default)<br/>or dialectic query; prefetch_department: dialectic\"]\n Inj[\"peer_memory + department_memory<br/>injected into USER turn\"]\n Sync[\"sync_turn / sync_department_turn<br/>fire-and-forget\"]\n Honcho[\"Honcho peers<br/>person + department\"]\n Audit[\"peer_memory audit row\"]\n Turn --> Gate\n Gate -->|enabled| Pre\n Pre -->|\"context() / chat()\"| Honcho\n Honcho --> Inj\n Inj --> Turn\n Turn -->|after response| Sync\n Sync -->|\"co-present peers\"| Honcho\n Pulse[\"Pulse People tab<br/>GET /memories/people (read-only)\"]\n Pulse -->|\"conclusions + card\"| Honcho\n Pre --> Audit\n Sync --> Audit\n Pulse --> Audit\n class Turn entry\n class Gate compute\n class Pre compute\n class Sync compute\n class Honcho external\n class Pulse entry\n class Audit storage\n","generated_at": "2026-09-25T16:41:20.505933+00:00"}diff --git a/packages/core/openexecutive/guide/prebuilt/artifacts.json b/packages/core/openexecutive/guide/prebuilt/artifacts.jsonindex 69566b59..57d7a644 100644--- a/packages/core/openexecutive/guide/prebuilt/artifacts.json+++ b/packages/core/openexecutive/guide/prebuilt/artifacts.json@@ -1,7 +1,7 @@{"section_id": "artifacts","title": "Documents",- "markdown": "**What it is:** Your library of finished deliverables — memos, web pages, Word documents, spreadsheets, links to things the Executive created in your own apps, and the outputs of workflow runs — in one place.\n\n**What it does:**\n\n- See all active documents, filtered by kind (drafts vs workflow outputs). Anything that isn't plain text shows a small badge: *Web page*, *Word document*, *Spreadsheet*, or the app a link opens.\n- Open any document to read it. Web pages display in a locked-down frame that can't run scripts or load anything from the internet; spreadsheets show as tables; links open straight into the app they live in.\n- Download it in its own format (.md, .html, .docx, .xlsx). Any Markdown document — including every workflow output — can also be downloaded as a Word file.\n- **Send it to someone**: ask the Executive to share a document with a person. It messages them the title and a link on their usual channel (the link opens in Open Executive, so it's for people who have access), or — if Google Workspace is connected — emails the file itself as an attachment (Word, Excel, web page or Markdown).\n- **Revise in chat**: opens a new chat about that document. The Executive rereads it, writes the new version, and archives the old one; the new version links back to the one it replaced.\n- The Executive remembers what it has written: it can list and reread its documents, and past documents surface in its answers when relevant.\n- Archive a document to tuck it away (with a quick undo) and restore it later.\n- Permanently delete one when you're sure, with a confirmation step.\n- Switch between **Active** and **Archived** views.\n\n**How to use:**\n\n1. Get something in here. Ask the Executive for a deliverable and say the format if you care — *\"as a Word doc\"*, *\"as a spreadsheet\"*, *\"as a one-page web page\"*, or *\"in my Google Sheets / Notion / OneDrive\"*. When you ask, it always publishes the result and replies with a link. For your own apps it uses whatever you've connected; with nothing connected it makes the file itself. It also drafts things unprompted when a finding is worth your time. Drafts appear as a card in the Briefing's **Needs you** lane, and every workflow run adds its output here automatically.\n2. Open **Documents** in the sidebar. Filter by **Drafts** or **Workflows**, and switch between **Active** and **Archived**.\n3. Click a document to read it; use **Copy** or a **Download** button to take it elsewhere, or **Revise in chat** to ask for changes.\n4. Hover over a row to **Archive** it (an **Undo** appears for a moment), **Restore** it from the Archived view, or **Delete permanently** (you'll be asked to confirm).\n\n**Example:** *\"Put the vendor pricing comparison in a spreadsheet for me.\"* A spreadsheet lands in **Needs you** and in **Documents**, previewed as tables with a **Download .xlsx** button. Later: *\"Add a column for contract length to that pricing spreadsheet\"* — the Executive rereads it, publishes the revised version, and archives the first one.\n\n*Note: archiving is a soft-delete — nothing is lost until you explicitly delete it.*",+ "markdown": "**What it is:** Your library of finished deliverables — memos, web pages, Word documents, spreadsheets, links to things the Executive created in your own apps, and the outputs of workflow runs — in one place.\n\n**What it does:**\n\n- See all active documents, filtered by kind (**Drafts** vs **Workflows** outputs). Anything that isn't plain text shows a small badge: *Web page*, *Word document*, *Spreadsheet*, or the app a link opens.\n- Open any document to read it. Web pages display in a locked-down frame that can't run scripts or load anything from the internet; spreadsheets show as tables; links open straight into the app they live in.\n- Download it in its own format (.md, .html, .docx, .xlsx). Any Markdown document — including every workflow output — can also be downloaded as a Word file.\n- **Send it to someone**: ask the Executive to share a document with a person. It messages them the title and a link on their usual channel (the link opens in Open Executive, so it's for people who have access), or — if Google Workspace is connected — emails the file itself as an attachment (Word, Excel, web page or Markdown).\n- **Revise in chat**: opens a new chat about that document. The Executive rereads it, writes the new version, and archives the old one; the new version links back to the one it replaced.\n- The Executive remembers what it has written: it can list and reread its documents, and past documents surface in its answers when relevant.\n- Archive a document to tuck it away (with a quick undo) and restore it later.\n- Permanently delete one when you're sure, with a confirmation step.\n- Switch between active and archived documents from the **⋯** next to the filter.\n\n**How to use:**\n\n1. Get something in here. Ask the Executive for a deliverable and say the format if you care — *\"as a Word doc\"*, *\"as a spreadsheet\"*, *\"as a one-page web page\"*, or *\"in my Google Sheets / Notion / OneDrive\"*. When you ask, it always publishes the result and replies with a link. For your own apps it uses whatever you've connected; with nothing connected it makes the file itself. It also drafts things unprompted when a finding is worth your time. Drafts appear as a card in **Needs you** on Home, and every workflow run adds its output here automatically.\n2. Open **Work** in the sidebar and pick the **Documents** tab. Filter by **Drafts** or **Workflows**; **Show archived** (in the **⋯** beside the filter) switches to archived documents, and **Show active documents** switches back.\n3. Click a document to read it; use **Copy** or **Download** (pick the format) to take it elsewhere, or **Revise in chat** to ask for changes.\n4. Each row's **⋯** menu has **Archive** (an **Undo** appears for a moment), **Restore** in the archived view, and **Delete permanently** (you'll be asked to confirm). The same actions are in the **⋯** on a document's own page.\n\n**Example:** *\"Put the vendor pricing comparison in a spreadsheet for me.\"* A spreadsheet lands in **Needs you** and in **Documents**, previewed as tables with a **Download .xlsx** button. Later: *\"Add a column for contract length to that pricing spreadsheet\"* — the Executive rereads it, publishes the revised version, and archives the first one.\n\n*Note: archiving is a soft-delete — nothing is lost until you explicitly delete it.*","mermaid": null,- "generated_at": "2026-09-24T17:32:29.068328+00:00"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/ask_oe.json b/packages/core/openexecutive/guide/prebuilt/ask_oe.jsonindex 0ff2199b..2be8ada7 100644--- a/packages/core/openexecutive/guide/prebuilt/ask_oe.json+++ b/packages/core/openexecutive/guide/prebuilt/ask_oe.json@@ -1,7 +1,7 @@{"section_id": "ask_oe","title": "Ask OE",- "markdown": "**What it is:** A page-aware assistant panel docked on the right of every screen (except the chat home, which *is* the chat). Open it with the **Ask OE** button in the top bar or **Ctrl/Cmd + .** — it's the same Executive you talk to in chat, but it knows what page you're looking at.\n\n**What it does:**\n\n- **Explains the current page.** Ask \"what does this page do?\" or \"what does authority scope mean?\" and the answer is grounded in this guide's section for the page you're on.\n- **Fills forms for you.** On a screen with a form (the workflow builder, the Add-person dialog, the company profile), describe what you want in plain language and the suggested values land directly in the form, highlighted so you can see what came from the Executive.\n- **You always click Save.** Ask OE never submits a form. Suggested values are just that — review them, edit anything, and save through the form's normal button. An **Undo** on the proposal card restores what was there before, and a highlight clears the moment you edit that field yourself.\n\n**How to use:**\n\n1. On any page, click **Ask OE** in the top bar or press **Ctrl/Cmd + .** (press it again to close).\n2. Ask about the page — \"what's the difference between Flag and Reject here?\" — or, on a form page, describe what you want filled in.\n3. Check the highlighted fields. Edit anything that's off, then click the form's own **Save** / **Create** button. Click **Undo** on the proposal card to put the form back as it was.\n4. Click **New conversation** in the panel header to start fresh.\n\n**Where it works:** every page inside the app shell. Form-filling is wired into the workflow builder (**Workflows → + New workflow**), the **Add person** dialog, and the **Company profile**; other pages get the explain tier, with form support arriving screen by screen.\n\n**Example:** on **Workflows → + New workflow**, open Ask OE and type *\"create a weekly Monday 9am competitor watch where the CMO checks our top three competitors for pricing and product changes, and send it to me\"*. The name, steps and schedule fill in; you review them and click **Create workflow**.\n\n**Good to know:** panel conversations are normal chat sessions — they appear in your session history and the audit log like any other turn.",+ "markdown": "**What it is:** A page-aware assistant panel docked on the right of every screen (except the chat home, which *is* the chat). Open it with the **Ask OE** button in the top bar or **Ctrl/Cmd + .** — it's the same Executive you talk to in chat, but it knows what page you're looking at.\n\n**What it does:**\n\n- **Explains the current page.** Ask \"what does this page do?\" or \"what does authority scope mean?\" and the answer is grounded in this guide's section for the page you're on.\n- **Fills forms for you.** On a screen with a form (the workflow builder, the Add-person dialog, the company profile), describe what you want in plain language and the suggested values land directly in the form, highlighted so you can see what came from the Executive.\n- **You always click Save.** Ask OE never submits a form. Suggested values are just that — review them, edit anything, and save through the form's normal button. An **Undo** on the proposal card restores what was there before, and a highlight clears the moment you edit that field yourself.\n\n**How to use:**\n\n1. On any page, click **Ask OE** in the top bar or press **Ctrl/Cmd + .** (press it again to close).\n2. Ask about the page — \"what's the difference between Flag and Reject here?\" — or, on a form page, describe what you want filled in.\n3. Check the highlighted fields. Edit anything that's off, then click the form's own **Save** / **Create** button. Click **Undo** on the proposal card to put the form back as it was.\n4. Click **New conversation** in the panel header to start fresh.\n\n**Where it works:** every page inside the app shell. Form-filling is wired into the workflow builder (**Work → Workflows**, then **New workflow** in the **⋯** beside **Start**), the **Add person** dialog, and the **Company profile**; other pages get the explain tier, with form support arriving screen by screen.\n\n**Example:** on the workflow builder (**New workflow** in the **⋯** beside **Start** on **Workflows**), open Ask OE and type *\"create a weekly Monday 9am competitor watch where the CMO checks our top three competitors for pricing and product changes, and send it to me\"*. The name, steps and schedule fill in; you review them and click **Create workflow**.\n\n**Good to know:** panel conversations are normal chat sessions — they appear in your session history and the audit log like any other turn.","mermaid": null,- "generated_at": "2026-09-23T00:00:00+00:00"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/audit.json b/packages/core/openexecutive/guide/prebuilt/audit.jsonindex ca208863..ac4d8c44 100644--- a/packages/core/openexecutive/guide/prebuilt/audit.json+++ b/packages/core/openexecutive/guide/prebuilt/audit.json@@ -1,7 +1,7 @@{"section_id": "audit","title": "Audit Log",- "markdown": "**What it is:** A searchable, append-only record of everything the system did — every chat turn, specialist consult, tool call, alert, scheduled action, and inbound integration.\n\n**What it does:**\n\n- Filter events by type, session, date, or free-text search.\n- Open any event to see its full payload — the message, tool input, and result.\n- View a per-session flow chart showing what led to what.\n- See cost and token summaries for each session.\n\n**How to use:**\n\n1. Open **Settings → Audit log**. It opens on **Sessions** — one card per conversation.\n2. Click **Open flow chart →** on a session to see it step by step. Click any node to see exactly what the agent saw and did; the side drawer shows the full payload, with **Copy**.\n3. Switch to **Events** for the raw list, and click a row for its full payload. Clicking a session id filters to that session.\n4. Narrow things down with **Search summary…**, the event-type dropdown, **Session id**, and **From / Until**. **Clear filters** resets them.\n\n**Example:** *\"Why did the Executive message our vendor on Tuesday?\"* — search for the vendor's name, set **From / Until** to Tuesday, then open that session's flow chart and follow it from the inbound message to the outbound send.\n\n*Note: the log is immutable — it's the trail for understanding (and trusting) what the Executive did.*",+ "markdown": "**What it is:** A searchable, append-only record of everything the system did — every chat turn, specialist consult, tool call, alert, scheduled action, and inbound integration.\n\n**What it does:**\n\n- Filter events by type, session, date, or free-text search.\n- Open any event to see its full payload — the message, tool input, and result.\n- View a per-session flow chart showing what led to what.\n- See cost and token summaries for each session.\n\n**How to use:**\n\n1. Open **Settings → Advanced → Audit log**. It opens on **Sessions** — one card per conversation.\n2. Click **Open flow chart →** on a session to see it step by step. Click any node to see exactly what the agent saw and did; the side drawer shows the full payload, with **Copy**.\n3. Switch to **Events** for the raw list, and click a row for its full payload. Clicking a session id filters to that session.\n4. Narrow things down with **Search summary…**, the event-type dropdown, **Session id**, and **From / Until**. **Clear filters** resets them.\n\n**Example:** *\"Why did the Executive message our vendor on Tuesday?\"* — search for the vendor's name, set **From / Until** to Tuesday, then open that session's flow chart and follow it from the inbound message to the outbound send.\n\n*Note: the log is immutable — it's the trail for understanding (and trusting) what the Executive did.*","mermaid": null,- "generated_at": "2026-09-23T00:00:00+00:00"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/chat.json b/packages/core/openexecutive/guide/prebuilt/chat.jsonindex c60f6ca3..283ea823 100644--- a/packages/core/openexecutive/guide/prebuilt/chat.json+++ b/packages/core/openexecutive/guide/prebuilt/chat.json@@ -1,7 +1,7 @@{"section_id": "chat","title": "Chat & Briefing",- "markdown": "**What it is:** The home surface where you talk to the Executive in plain language. It opens on a *briefing* — a quick read of what's happened across the company — and you drop into a chat whenever you want to ask or decide something.\n\n**What it does:**\n\n- Hold a natural conversation with the Executive, which quietly pulls in whichever specialists a question needs.\n- Keep separate chat sessions with full history, so you can pick up where you left off.\n- Attach files to a message — up to 5 per turn, 20 MB each (images, PDF, Word, text, Markdown, CSV) — for the Executive to read alongside your knowledge base.\n- Stop a reply while it is still coming — whatever has been written is kept and marked *Stopped by you*, so you can redirect without waiting the answer out. (Escape works too.)\n- Toggle **Committee** on a question that matters: a slower pass where reviewers challenge the draft answer before you see it.\n- Continue any briefing item straight into a chat thread, with the context already filled in.\n- Open **Agent activity** in the top bar to watch what's happening behind a reply — which specialists were consulted and which tools ran.\n- See what an answer drew on: click **Sources** under a reply to list the documents and web pages it looked at — your own documents, the built-in knowledge and any web pages — with links where there are any.\n\n**How to use:**\n\n1. Click **New chat** in the sidebar. (Click **Briefing** any time to get back to the briefing.)\n2. Type your question and press **Enter** to send — **Shift + Enter** starts a new line. When the box is empty, a greyed-out suggested follow-up may appear; press **Tab** or **→** to use it.\n3. To include a file, click the paperclip next to the message box and pick up to 5 files. (Drag-and-drop isn't supported in chat.) Attachments are read for that conversation only — to make a document permanently available, upload it to the Knowledge Base.\n4. For a decision that matters, click the **Committee** pill next to Send *before* sending. It applies to that one message; you'll see *Drafting → Committee review → Revising* while it works.\n5. Changed your mind mid-answer? Click the stop button (it replaces Send while a reply is streaming) or press **Esc**.\n6. Rate a reply with 👍 / 👎, and find old conversations under **Recent** in the sidebar (it has a search box).\n7. If part of an answer couldn't be completed — say the finance side — you still get the rest, with a short note under it. Ask again to fill in the missing part.\n\n**Example prompts:**\n\n- \"Here's our Q3 board deck — what questions should I expect from the board?\" *(with the PDF attached)*\n- \"Should we raise prices 10% for new customers? I want the finance and marketing view.\" *(with Committee on)*\n- \"What changed across the company this week that I should know about?\"\n\n*Tip: this is the front door — almost everything else in the app is something the Executive references or acts on from here.*",+ "markdown": "**What it is:** Where you talk to the Executive in plain language. The app opens on **Home** — a quick read of what's happened across the company and what needs you — and you drop into a chat whenever you want to ask or decide something.\n\n**What it does:**\n\n- Hold a natural conversation with the Executive, which quietly pulls in whichever specialists a question needs.\n- Keep separate chat sessions with full history, so you can pick up where you left off.\n- Attach files to a message — up to 5 per turn, 20 MB each (images, PDF, Word, text, Markdown, CSV) — for the Executive to read alongside your knowledge base.\n- Stop a reply while it is still coming — whatever has been written is kept and marked *Stopped by you*, so you can redirect without waiting the answer out. (Escape works too.)\n- Turn on **Committee review** for a question that matters: a slower pass where reviewers challenge the draft answer before you see it.\n- Continue any item on Home straight into a chat thread, with the context already filled in.\n- Choose **Show agent activity** in the **⋯** menu at the top right to watch what's happening behind a reply — which specialists were consulted and which tools ran.\n- See what an answer drew on: click **Sources** under a reply to list the documents and web pages it looked at — your own documents, the built-in knowledge and any web pages — with links where there are any.\n\n**How to use:**\n\n1. Click **New chat** at the top of the sidebar (on a phone, **New chat** in the middle of the bar at the bottom), or type into the **Ask your Executive anything…** box on Home. Click **Home** any time to get back.\n2. Type your question and press **Enter** to send — **Shift + Enter** starts a new line. When the box is empty, a greyed-out suggested follow-up may appear; press **Tab** or **→** to use it.\n3. To include a file, click the **+** next to the message box, choose **Attach files or photos** and pick up to 5 files. (Drag-and-drop isn't supported in chat.) Attachments are read for that conversation only — to make a document permanently available, add it on the **Knowledge** page.\n4. For a decision that matters, click the **+** next to the message box and choose **Committee review** *before* sending. A **Committee review on** chip appears above the box (click it to turn it off). It applies to that one message; you'll see *Drafting → Committee review → Revising* while it works.\n5. Changed your mind mid-answer? Click the stop button (it replaces Send while a reply is streaming) or press **Esc**.\n6. Rate a reply with 👍 / 👎. Find old conversations under **Chats** in the sidebar: every conversation, including ones from Slack, Telegram and Discord, with a search box and a tab per channel. Delete one from its **⋯** menu.\n7. If part of an answer couldn't be completed — say the finance side — you still get the rest, with a short note under it. Ask again to fill in the missing part.\n\n**Example prompts:**\n\n- \"Here's our Q3 board deck — what questions should I expect from the board?\" *(with the PDF attached)*\n- \"Should we raise prices 10% for new customers? I want the finance and marketing view.\" *(with Committee on)*\n- \"What changed across the company this week that I should know about?\"\n\n*Tip: this is the front door — almost everything else in the app is something the Executive references or acts on from here.*","mermaid": null,- "generated_at": "2026-09-25T12:54:23.620111+00:00"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/clients.json b/packages/core/openexecutive/guide/prebuilt/clients.jsonindex ca123bdd..3361d3fa 100644--- a/packages/core/openexecutive/guide/prebuilt/clients.json+++ b/packages/core/openexecutive/guide/prebuilt/clients.json@@ -1,7 +1,7 @@{"section_id": "clients","title": "Client Companies",- "markdown": "**What it is:** Multi-client mode for fractional work. Each client is a named **slot** holding a complete, separate company — profile, people, chats, memory, watchlist, everything — and you switch the live workspace between them.\n\n**What it does:**\n\n- Create a client by snapshotting the current company, starting blank, or having AI draft one from your intake notes and attachments.\n- Activate a slot to make it the live company; the previous client's full state is saved back to its slot first.\n- Keep **engagement metadata** on every slot — your role (e.g. Fractional CFO), status, retainer, primary contact, and renewal date — visible across all clients.\n- Get renewal reminders even for clients that are parked.\n\n**How to use:**\n\n1. Open **Settings → Client Companies**.\n2. Add a client, one of three ways:\n - **New client** → enter a name → **From current company** (captures what's live now) → **Create**.\n - **New client** → **Blank (onboard fresh)** → **Create**, then **Activate** it and run onboarding.\n - **New client from intake notes** → paste your notes and attach any files → **Draft client** → check it → **Create & activate** (or **Create client** to park it).\n3. Click **Activate** on a client to switch to it. The current client is saved back to its slot first; **Save now** saves it on demand.\n4. Click **Engagement details** to record your role, status, renewal date, retainer, primary contact and notes, then **Save details**.\n\n**Example intake notes:** *\"Kickoff call with Meridian Solar — 120-person residential installer in Arizona, $38M revenue, PE-backed since 2024. I'm their fractional CFO, 10 hours a week, $8K/month retainer, renewal in March. Priorities: 13-week cash forecast and a lender-ready model.\"*\n\n*Note: switching clients swaps the whole working state, so nothing leaks between engagements. Switching is disabled while a simulator company is loaded — unload it first. Single-company users can ignore this screen entirely.*",+ "markdown": "**What it is:** Multi-client mode for fractional work. Each client is a named **slot** holding a complete, separate company — profile, people, chats, memory, watchlist, everything — and you switch the live workspace between them.\n\n**What it does:**\n\n- Create a client by snapshotting the current company, starting blank, or having AI draft one from your intake notes and attachments.\n- Activate a slot to make it the live company; the previous client's full state is saved back to its slot first.\n- Keep **engagement metadata** on every slot — your role (e.g. Fractional CFO), status, retainer, primary contact, and renewal date — visible across all clients.\n- Get renewal reminders even for clients that are parked.\n\n**How to use:**\n\n1. Open **Settings → Advanced → Client Companies**.\n2. Add a client, one of three ways:\n - **New client** → **From a company** → enter a name → **From current company** (captures what's live now) → **Create**.\n - **New client** → **From a company** → **Blank (onboard fresh)** → **Create**, then **Activate** it and run onboarding.\n - **New client** → **From intake notes** → paste your notes and attach any files → **Draft client** → check it → **Create & activate** (or **Create client** to park it).\n3. Click **Activate** on a client to switch to it. The current client is saved back to its slot first; **Save now** saves it on demand.\n4. Choose **Engagement details** in a client's **⋯** menu to record your role, status, renewal date, retainer, primary contact and notes, then **Save details**.\n\n**Example intake notes:** *\"Kickoff call with Meridian Solar — 120-person residential installer in Arizona, $38M revenue, PE-backed since 2024. I'm their fractional CFO, 10 hours a week, $8K/month retainer, renewal in March. Priorities: 13-week cash forecast and a lender-ready model.\"*\n\n*Note: switching clients swaps the whole working state, so nothing leaks between engagements. Switching is disabled while a simulator company is loaded — unload it first. Single-company users can ignore this screen entirely.*","mermaid": null,- "generated_at": "2026-09-23T00:00:00+00:00"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/company_profile.json b/packages/core/openexecutive/guide/prebuilt/company_profile.jsonindex 4f5c77ed..6ad0e230 100644--- a/packages/core/openexecutive/guide/prebuilt/company_profile.json+++ b/packages/core/openexecutive/guide/prebuilt/company_profile.json@@ -1,7 +1,7 @@{"section_id": "company_profile","title": "Company Profile & Onboarding",- "markdown": "**What it is:** Your company's identity and strategy — mission, market, competitors, financials, and org structure — that grounds everything the Executive says.\n\n**What it does:**\n\n- **Describe your business in your own words** the first time — paste a paragraph, or attach a deck or one-pager. The Executive asks a few follow-up questions, then shows you a filled-in draft profile, team list, and departments.\n- Review and edit that draft before anything is saved; nothing is written until you hit save. Prefer a form? A step-by-step version is linked at the bottom of the setup screen.\n- View and edit every section of the profile inline, any time afterward.\n- Feed this context to all specialists so advice fits *your* company, not a generic one.\n- Kick off background research after setup to suggest things worth watching.\n\n**How to use:**\n\n*First-time setup*\n\n1. Click **Set up company** in the sidebar (or **Set up profile →** on the banner in chat).\n2. Describe your business — what you do, who you sell to, roughly how big you are. Optionally **Attach files** (up to 8: a deck, one-pager, or spreadsheet). Click **Get started**.\n3. Answer the follow-up questions (up to 8), or click **Skip ahead — draft my profile now**.\n4. On **Here's what I understood**, edit the profile, **Your team**, and **Departments**. Make sure exactly one person is marked as you. Check **Your sign-in email**: it's filled in with the account you're signed in with, and it's how the Executive knows the person marked as you is you — change it if you're setting this up for someone else. Click **Save & finish setup** — or **Not quite — ask me more questions**.\n\nPrefer filling in fields? Click **Prefer a form? Use the step-by-step version** for a 12-step wizard.\n\n*Afterwards*\n\n- Open **Company profile**, click **Edit** on any section (Company Basics, Mission & Vision, Target Customer, Competitive Landscape, Strategic Priorities, Financials, and more), make your changes, and click **Save**. List fields take one item per line.\n- **Re-run setup →** takes you back through the conversation. Only the current owner can mark someone else as \"This is me\" when re-running it, because saving makes that person the owner.\n- Ask OE can fill in profile sections for you — you still click **Save**.\n\n**Example description:** *\"We're Northwind Tools — a 40-person B2B SaaS company selling inventory software to independent hardware stores in the US. About $6M ARR, growing 60% a year, Series A last spring. Our main competitors are Lightspeed and spreadsheets. This year's priorities are launching in Canada and getting net revenue retention above 110%.\"*\n\n*Note: until a profile exists, the app nudges you to set one up — it's the foundation the rest builds on.*",+ "markdown": "**What it is:** Your company's identity and strategy — mission, market, competitors, financials, and org structure — that grounds everything the Executive says.\n\n**What it does:**\n\n- **Describe your business in your own words** the first time — paste a paragraph, or attach a deck or one-pager. The Executive asks a few follow-up questions, then shows you a filled-in draft profile, team list, and departments.\n- Review and edit that draft before anything is saved; nothing is written until you hit save. Prefer a form? A step-by-step version is linked at the bottom of the setup screen.\n- View and edit every section of the profile inline, any time afterward.\n- Feed this context to all specialists so advice fits *your* company, not a generic one.\n- Kick off background research after setup to suggest things worth watching.\n\n**How to use:**\n\n*First-time setup*\n\n1. Open **Company** in the sidebar and pick the **Set up company** tab (or click **Set up profile →** on the banner in chat).\n2. Describe your business — what you do, who you sell to, roughly how big you are. Optionally **Attach files** (up to 8: a deck, one-pager, or spreadsheet). Click **Get started**.\n3. Answer the follow-up questions (up to 8), or click **Skip ahead — draft my profile now**.\n4. On **Here's what I understood**, edit the profile, **Your team**, and **Departments**. Make sure exactly one person is marked as you. Check **Your sign-in email**: it's filled in with the account you're signed in with, and it's how the Executive knows the person marked as you is you — change it if you're setting this up for someone else. Click **Save & finish setup** — or **Not quite — ask me more questions**.\n\nPrefer filling in fields? Click **Prefer a form? Use the step-by-step version** for a 12-step wizard.\n\n*Afterwards*\n\n- Open **Company** in the sidebar and pick the **Company profile** tab, click **Edit** on any section (Company Basics, Mission & Vision, Target Customer, Competitive Landscape, Strategic Priorities, Financials, and more), make your changes, and click **Save**. List fields take one item per line.\n- **Re-run setup** (in the **⋯** at the top of the profile) takes you back through the conversation. Only the current owner can mark someone else as \"This is me\" when re-running it, because saving makes that person the owner.\n- Ask OE can fill in profile sections for you — you still click **Save**.\n\n**Example description:** *\"We're Northwind Tools — a 40-person B2B SaaS company selling inventory software to independent hardware stores in the US. About $6M ARR, growing 60% a year, Series A last spring. Our main competitors are Lightspeed and spreadsheets. This year's priorities are launching in Canada and getting net revenue retention above 110%.\"*\n\n*Note: until a profile exists, the app nudges you to set one up — it's the foundation the rest builds on.*","mermaid": null,- "generated_at": "2026-09-23T00:00:00+00:00"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/council.json b/packages/core/openexecutive/guide/prebuilt/council.jsonindex 6a906c8e..b1f9b222 100644--- a/packages/core/openexecutive/guide/prebuilt/council.json+++ b/packages/core/openexecutive/guide/prebuilt/council.json@@ -1,7 +1,7 @@{"section_id": "council","title": "Agent Council",- "markdown": "**What it is:** The configuration hub for the specialists behind the Executive — the place to tune how each one thinks and how the Executive sounds.\n\n**What it does:**\n\n- Pick any agent and add instructions, or override its role, system prompt, model, or deep-reasoning toggle.\n- Set the Executive's **voice persona** — the tone it speaks to you in.\n- Test a draft configuration with a one-off query before committing.\n- View version history and roll back, or reset an agent to its built-in default.\n\n**How to use:**\n\n1. Open **Settings → Agent Council** and pick an agent from the list. An amber dot means it's already been customized.\n2. Change what you need:\n - **Role** — its one-line job description.\n - **Model** — provider and model; the default is marked *(default)*.\n - **Deep reasoning** — slower, more thorough thinking (not available on Haiku models).\n - **Additional instructions** — a few lines added after its built-in prompt, such as \"Quote figures in EUR\". The agent keeps getting improvements to its built-in prompt. Clear the box to remove them.\n - **System prompt** — its full instructions. Editing it replaces the built-in prompt, so later improvements to it won't reach this agent; prefer **Additional instructions** when you can. **Restore default prompt in editor** brings the original back.\n - **Research focus** — specialists only.\n3. Try it before saving: in **Test this draft**, type a question and click **Run test**. It uses your unsaved settings and changes nothing.\n4. Click **Save**. The change applies on the next call.\n5. To undo, click **Reset to default**, or open **Version history** and click **Restore** on an earlier version.\n\n*Change the Executive's voice:* select the Executive and scroll to **Voice Persona**. Choose an **Active persona** and click the main **Save**. To write your own, click **+ New**, give it a display name and a persona body, and click **Create** — or **Duplicate** an existing persona and edit the copy.\n\n**Example persona body:**\n\n```\n- Direct and brief; lead with the recommendation, then the reasoning\n- Plain English, no jargon or buzzwords\n- Numbers over adjectives\n- End with the one decision you need from me\n```\n\n*Note: changes take effect on the next call — no restart needed. This is a power-user surface under Settings.*",+ "markdown": "**What it is:** The configuration hub for the specialists behind the Executive — the place to tune how each one thinks and how the Executive sounds.\n\n**What it does:**\n\n- Pick any agent and add instructions, or override its role, system prompt, model, or deep-reasoning toggle.\n- Set the Executive's **voice persona** — the tone it speaks to you in.\n- Test a draft configuration with a one-off query before committing.\n- View version history and roll back, or reset an agent to its built-in default.\n\n**How to use:**\n\n1. Open **Settings → Advanced → Agent Council**. It opens in a simple view: **Quality** at the top sets every agent's model and deep reasoning at once. Under **Your agents**, each main agent is a card with its area and model; an amber dot and **Has your instructions** mean you've already changed it. Click a card to open that agent in a panel with its **Additional instructions**, then click **Save** (or **Cancel**). **Show all agents** lists the internal ones too.\n2. For everything else, click **Advanced** at the top (the browser remembers it; **Back to simple view** returns). Click an agent's card; its panel splits the settings into tabs — **Model**, **Instructions**, **Prompt**, **Test** and **History**:\n - **Role** — its one-line job description.\n - **Model** — provider and model; the default is marked *(default)*.\n - **Deep reasoning** — slower, more thorough thinking (not available on Haiku models).\n - **Additional instructions** — a few lines added after its built-in prompt, such as \"Quote figures in EUR\". The agent keeps getting improvements to its built-in prompt. Clear the box to remove them.\n - **System prompt** — its full instructions. Editing it replaces the built-in prompt, so later improvements to it won't reach this agent; prefer **Additional instructions** when you can. **Restore default prompt in editor** brings the original back.\n - **Research focus** — specialists only.\n3. Try it before saving: on the **Test** tab, under **Test this draft**, type a question and click **Run test**. It uses your unsaved settings and changes nothing.\n4. Click **Save** at the bottom of the panel. The change applies on the next call.\n5. To undo, choose **Reset to default** in the **⋯** menu at the bottom of the agent's panel, or open the **History** tab and click **Restore** on an earlier version.\n\n*Change the Executive's voice:* pick one under **Voice** on **Settings → Your Executive**. To write your own, open the Council's **Advanced** view, click the **Executive** card and open the **Prompt** tab: **Voice Persona** there has the **Active persona** (save it with the main **Save**), and **+ New**, which asks for a display name and a persona body — then click **Create** — or **Duplicate** an existing persona and edit the copy.\n\n**Example persona body:**\n\n```\n- Direct and brief; lead with the recommendation, then the reasoning\n- Plain English, no jargon or buzzwords\n- Numbers over adjectives\n- End with the one decision you need from me\n```\n\n*Note: changes take effect on the next call — no restart needed. This is a power-user surface under Settings.*","mermaid": null,- "generated_at": "2026-10-01T15:38:41Z"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/departments.json b/packages/core/openexecutive/guide/prebuilt/departments.jsonindex 78a95548..c1f3f345 100644--- a/packages/core/openexecutive/guide/prebuilt/departments.json+++ b/packages/core/openexecutive/guide/prebuilt/departments.json@@ -1,7 +1,7 @@{"section_id": "departments","title": "Departments",- "markdown": "**What it is:** The org units the Executive works through. Each department has goals, an authority level, a head, and a specialist agent behind it.\n\n**What it does:**\n\n- View every department with its goal count and health (on-track / at-risk / off-track).\n- Create departments and give them a mission, goals, budget, and headcount.\n- Set the **authority level** — act automatically, propose for approval, or always escalate.\n- Wire up a head person and team channels (Slack, Discord, Telegram).\n\n**How to use:**\n\n1. Open **Departments** and click **+ Add department**. Enter a **Name** (and, optionally, a mission) and click **Create**. New departments start at *Proposes, you approve*.\n2. Open the department and click **Edit settings**:\n - **Department head** — the person who owns it.\n - **Authority level** — **Acts on its own**, **Proposes, you approve**, or **Escalates to a human**.\n - **Recurring check-in** — when the department checks in. New departments check in `daily@09:00`; change it to e.g. `daily@14:00` or `weekly@mon@09:00` (times are UTC).\n - **Headcount** and **Budget (USD)**.\n - **Team channels** — a Slack channel ID, Discord channel ID or Telegram chat ID. Leave them blank and messages go to the department head by DM.\n - **Watched entities** — one per line.\n\n Then click **Save settings**.\n3. Click **+ Add Goal**: pick a timeframe (week, month, quarter, year, or ongoing), enter the **Key result** and **Target** (and current progress if you know it), set a status, and click **Add Goal**. Each goal has **Edit** and **Delete**.\n4. Keep goals current by just telling the Executive what happened — it updates the matching goal and records why.\n5. Set a new goal the same way: tell the Executive the target, and it adds the goal under the right department (or area), creating that department if you don't have one yet. Only the owner can do this, from the web app or their own Slack or Discord — a teammate, or an email, can't. It adds one goal for each target you actually give it (at most 8 per department this way) — ask it to \"set up some goals\" and it asks you which ones.\n\n**Examples from chat:** *\"We closed 40% of the Q3 ARR target.\"* · *\"We lost the Acme deal.\"* · *\"New Sales goal: 20 paying customers by December 31.\"* · *\"Make Sarah the head of Marketing.\"*\n\n**Goals page:** **Goals** in the sidebar (under **You** when you use Open Executive just for yourself) lists every goal in one place, grouped by **area** — an area is what a department is called there. Each goal shows its status, timeframe, target and where it stands now, with **Edit** and **Delete**. Click **+ Add goal**, pick the **Area** it belongs to, and fill it in as above; areas with no goals yet are listed under **Other areas** so you can start one there. The page works the same when you use it with your team — it's just not in the team sidebar.\n\n**Just for yourself?** In that mode department check-ins are paused and the sidebar shows **Goals** instead of **Departments**. The departments are still there — open `/departments` to rename an area or change its settings.\n\n*Note: the authority level is what decides whether the Executive acts on its own or asks first within that department's scope.*",+ "markdown": "**What it is:** The org units the Executive works through. Each department has goals, an authority level, a head, and a specialist agent behind it.\n\n**What it does:**\n\n- View every department with its goal count and health (on-track / at-risk / off-track).\n- Create departments and give them a mission, goals, budget, and headcount.\n- Set the **authority level** — act automatically, propose for approval, or always escalate.\n- Wire up a head person and team channels (Slack, Discord, Telegram).\n\n**How to use:**\n\n1. Open **Company** in the sidebar, pick the **Departments** tab, and click **Add department**. Enter a **Name** (and, optionally, a mission) and click **Create**. New departments start at *Proposes, you approve*.\n2. Open the department and click **Edit settings**. The settings open in a side panel, split into tabs (**Charter**, **How it acts**, **Numbers**, **Channels**, **Watched**):\n - **Department head** — the person who owns it.\n - **Authority level** — **Acts on its own**, **Proposes, you approve**, or **Escalates to a human**.\n - **Recurring check-in** — when the department checks in. New departments check in `daily@09:00`; change it to e.g. `daily@14:00` or `weekly@mon@09:00` (times are UTC).\n - **Headcount** and **Budget (USD)**.\n - **Team channels** — a Slack channel ID, Discord channel ID or Telegram chat ID. Leave them blank and messages go to the department head by DM.\n - **Watched entities** — one per line.\n\n Then click **Save settings**.\n3. Click **Add goal**: pick a timeframe (week, month, quarter, year, or ongoing), enter the **Key result** and **Target** (and current progress if you know it), set a status, and click **Add goal**. Each goal's **⋯** menu has **Edit goal** and **Delete goal**.\n4. Keep goals current by just telling the Executive what happened — it updates the matching goal and records why.\n5. Set a new goal the same way: tell the Executive the target, and it adds the goal under the right department (or area), creating that department if you don't have one yet. Only the owner can do this, from the web app or their own Slack or Discord — a teammate, or an email, can't. It adds one goal for each target you actually give it (at most 8 per department this way) — ask it to \"set up some goals\" and it asks you which ones.\n\n**Examples from chat:** *\"We closed 40% of the Q3 ARR target.\"* · *\"We lost the Acme deal.\"* · *\"New Sales goal: 20 paying customers by December 31.\"* · *\"Make Sarah the head of Marketing.\"*\n\n**Goals page:** the **Goals** tab of **Company** (of **You** when you use Open Executive just for yourself) lists every goal in one place, grouped by department — called an **area** when it's just you. Each goal shows its status, timeframe, target and where it stands now, with **Edit goal** and **Delete goal** in its **⋯** menu. Click **Add goal**, pick the department (or **Area**) it belongs to, and fill it in as above; ones with no goals yet are listed at the bottom so you can start one there.\n\n**Just for yourself?** In that mode department check-ins are paused and **Company** becomes **You**, with **Goals** and no **Departments** tab. The departments are still there — open `/departments` to rename an area or change its settings.\n\n*Note: the authority level is what decides whether the Executive acts on its own or asks first within that department's scope.*","mermaid": null,- "generated_at": "2026-09-25T16:20:57Z"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/integrations.json b/packages/core/openexecutive/guide/prebuilt/integrations.jsonindex a32ca01b..3359bfd1 100644--- a/packages/core/openexecutive/guide/prebuilt/integrations.json+++ b/packages/core/openexecutive/guide/prebuilt/integrations.json@@ -1,7 +1,7 @@{"section_id": "integrations","title": "Integrations",- "markdown": "**What it is:** The channels that connect the Executive to where your team already works — so proposals, updates, and replies flow through familiar tools instead of just the web app.\n\n**What it does:**\n\n- **Slack / Google Chat:** receive messages and thread replies, send proposals and alerts.\n- **Discord / Telegram:** direct-message conversations for proposals and approvals.\n- **Email:** poll for inbound mail and send outbound replies.\n- **Google Workspace:** the Executive can send and draft Gmail (recipients limited to your People roster) and manage Calendar events, including Google Meet links.\n- **Microsoft 365:** the Executive can send, reply to and draft Outlook mail and manage Outlook calendar events with Teams links (recipients and attendees limited to your People roster). Its own inbox and calendar can run on either Google or Microsoft — a per-install setting, not a per-message choice.\n- **MCP:** expose the Executive's specialist council and company context to external AI tools.\n\n**How to use:**\n\n*Before anyone can use a channel,* an administrator turns it on (see *Setup* below) and restarts the app. Then add each person's channel ID under **People → Contact & routing** — Slack, Discord and Telegram only answer people on your roster. **Settings → Setup status** then shows whether each channel is working, and what to do if it isn't.\n\n*Talking to the Executive*\n\n- **Slack** — DM the app, or @mention it in a channel; it replies in a thread. Keep replying in that thread without mentioning it again.\n- **Discord** — DM the bot or @mention it (it usually answers in a new thread). Or use the slash commands `/ask` and `/today`.\n- **Telegram** — message the bot directly; text, documents and photos all work.\n- **Google Chat** — DM the app, or add it to a space and @mention it.\n- **Email** — send mail to the Executive's address; it picks up unread inbox mail on a regular poll.\n- **Signing off a paused workflow** — reply in the thread on Slack, Discord or Telegram: \"yes\", \"LGTM\", \"no\", \"not now\".\n\n**Example (Slack):** *\"@Executive what's blocking the Q3 hiring plan?\"* — the answer arrives in a thread, and you can follow up there.\n\n*Setup (administrators)* — each channel is switched on with environment settings:\n\n| Channel | Settings |\n|---|---|\n| Slack | `SLACK_BOT_TOKEN`, `SLACK_APP_TOKEN` (Socket Mode) |\n| Discord | `DISCORD_BOT_TOKEN`, `DISCORD_APP_ID`; enable the bot's Message Content intent (see the README) |\n| Telegram | `TELEGRAM_BOT_TOKEN`, `TELEGRAM_WEBHOOK_SECRET`; webhook at `/webhook/telegram` |\n| Google Chat | `GOOGLE_CHAT_PROJECT_NUMBER` plus a service account — see `docs/google_chat_setup.md` |\n| Email, Gmail & Calendar | `EXEC_EMAIL_ADDRESS` plus the Google Workspace connection — see `docs/deployment.md` |\n| Microsoft 365 | `MS365_MCP_CLIENT_ID`, `MS365_MCP_TENANT_ID`, `MS365_MCP_EXPECTED_USERNAME`, then a one-time sign-in with `ms365-mcp-launch.sh --login` — see `docs/deployment.md`. `EMAIL_PROVIDER` / `CALENDAR_PROVIDER` choose whether the Executive's own inbox and calendar are Google or Microsoft |\n\n*Use the Executive from other AI tools (MCP)* — the API serves an MCP endpoint at `/mcp`; clients authenticate with the backend shared secret. In Claude Code:\n\n```bash\nclaude mcp add --transport http open-executive http://localhost:8000/mcp \\\n --header \"x-api-key: YOUR_BACKEND_SHARED_SECRET\"\n```\n\nOther MCP clients take the same URL and `x-api-key` header. They get `ask_executive`, `consult_specialist`, `search_knowledge` and `list_workflows`, plus read-only company context.\n\n*Note: every channel is recorded in the Audit Log. Replying to approve a paused workflow works on Slack, Discord and Telegram only — not email or Google Chat. Channels are turned on with environment configuration, not from this screen.*",+ "markdown": "**What it is:** The channels that connect the Executive to where your team already works — so proposals, updates, and replies flow through familiar tools instead of just the web app.\n\n**What it does:**\n\n- **Slack / Google Chat:** receive messages and thread replies, send proposals and alerts.\n- **Discord / Telegram:** direct-message conversations for proposals and approvals.\n- **Email:** poll for inbound mail and send outbound replies.\n- **Google Workspace:** the Executive can send and draft Gmail (recipients limited to your People roster) and manage Calendar events, including Google Meet links.\n- **Microsoft 365:** the Executive can send, reply to and draft Outlook mail and manage Outlook calendar events with Teams links (recipients and attendees limited to your People roster). Its own inbox and calendar can run on either Google or Microsoft — a per-install setting, not a per-message choice.\n- **MCP:** expose the Executive's specialist council and company context to external AI tools.\n\n**How to use:**\n\n*Before anyone can use a channel,* an administrator turns it on (see *Setup* below) and restarts the app. Then add each person's channel ID under **People → Contact & routing** — Slack, Discord and Telegram only answer people on your roster. **Settings → Advanced → Setup status** then shows whether each channel is working, and what to do if it isn't.\n\n*Talking to the Executive*\n\n- **Slack** — DM the app, or @mention it in a channel; it replies in a thread. Keep replying in that thread without mentioning it again.\n- **Discord** — DM the bot or @mention it (it usually answers in a new thread). Or use the slash commands `/ask` and `/today`.\n- **Telegram** — message the bot directly; text, documents and photos all work.\n- **Google Chat** — DM the app, or add it to a space and @mention it.\n- **Email** — send mail to the Executive's address; it picks up unread inbox mail on a regular poll.\n- **Signing off a paused workflow** — reply in the thread on Slack, Discord or Telegram: \"yes\", \"LGTM\", \"no\", \"not now\".\n\n**Example (Slack):** *\"@Executive what's blocking the Q3 hiring plan?\"* — the answer arrives in a thread, and you can follow up there.\n\n*Setup (administrators)* — each channel is switched on with environment settings:\n\n| Channel | Settings |\n|---|---|\n| Slack | `SLACK_BOT_TOKEN`, `SLACK_APP_TOKEN` (Socket Mode) |\n| Discord | `DISCORD_BOT_TOKEN`, `DISCORD_APP_ID`; enable the bot's Message Content intent (see the README) |\n| Telegram | `TELEGRAM_BOT_TOKEN`, `TELEGRAM_WEBHOOK_SECRET`; webhook at `/webhook/telegram` |\n| Google Chat | `GOOGLE_CHAT_PROJECT_NUMBER` plus a service account — see `docs/google_chat_setup.md` |\n| Email, Gmail & Calendar | `EXEC_EMAIL_ADDRESS` plus the Google Workspace connection — see `docs/deployment.md` |\n| Microsoft 365 | `MS365_MCP_CLIENT_ID`, `MS365_MCP_TENANT_ID`, `MS365_MCP_EXPECTED_USERNAME`, then a one-time sign-in with `ms365-mcp-launch.sh --login` — see `docs/deployment.md`. `EMAIL_PROVIDER` / `CALENDAR_PROVIDER` choose whether the Executive's own inbox and calendar are Google or Microsoft |\n\n*Use the Executive from other AI tools (MCP)* — the API serves an MCP endpoint at `/mcp`; clients authenticate with the backend shared secret. In Claude Code:\n\n```bash\nclaude mcp add --transport http open-executive http://localhost:8000/mcp \\\n --header \"x-api-key: YOUR_BACKEND_SHARED_SECRET\"\n```\n\nOther MCP clients take the same URL and `x-api-key` header. They get `ask_executive`, `consult_specialist`, `search_knowledge` and `list_workflows`, plus read-only company context.\n\n*Note: every channel is recorded in the Audit Log. Replying to approve a paused workflow works on Slack, Discord and Telegram only — not email or Google Chat. Channels are turned on with environment configuration, not from this screen.*","mermaid": null,- "generated_at": "2026-10-01T21:30:00Z"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/jobs.json b/packages/core/openexecutive/guide/prebuilt/jobs.jsonindex 0dd0aa19..8d3394ed 100644--- a/packages/core/openexecutive/guide/prebuilt/jobs.json+++ b/packages/core/openexecutive/guide/prebuilt/jobs.json@@ -1,7 +1,7 @@{"section_id": "jobs","title": "Workflows",- "markdown": "**What it is:** Structured, multi-step workflows that produce a *deliverable* — a board deck, a go-to-market plan, a performance review — or *get something done* with your connected tools, like filing emailed bills into a spreadsheet, rather than just a chat reply.\n\n**What it does:**\n\n- Start from **Start here** at the top of the **Build** tab: say what you want done, and pick how to build it.\n- Your own workflows sit under **Your workflows**; below them are a few **ready-made** picks, and **Browse all** opens the full list with search and area chips (**System** holds the workflows Open Executive runs on its own, like the morning brief).\n- Start a run and watch it stream its progress step by step.\n- See your runs split into **Active**, **Awaiting sign-off**, **Done**, and **Error**, and search them by name.\n- Create your own **custom workflow** by describing it: the assistant asks a few clarifying questions, then drafts it for you to review.\n- Let a workflow **use tools** — Gmail, Google Sheets, Drive and anything else connected — to actually do the work, not just write about it.\n- Put a custom workflow on a **schedule** (e.g. every Monday at 09:00) so it runs without being asked.\n- Each finished run produces a document you can read and keep.\n- Manage **Playbooks** on their own tab — the methods and templates the Executive follows in chat and inside workflows (see **Playbooks** in this guide). A workflow page lists the playbooks it follows, and a custom workflow's specialist step can **Follow a playbook** too.\n\n**How to use:**\n\n*Run a workflow*\n\n1. Open **Workflows** and click one of the ready-made picks on the **Build** tab, or **Browse all ready-made workflows** and narrow the list with the chips or the search box.\n2. Fill in the fields (required ones have a red \\*). **Insert example** or **Load sample run** fills in realistic values if you just want to try it.\n3. Click **Continue**, then **Run workflow**. Progress streams step by step; when it finishes you land on the run page, with **Copy** and **Download .md**.\n\n*Build your own*\n\n1. Under **Start here**, describe the job in plain words — what it should produce, who it's for, and how often — or pick one of the suggestions, then click **Start**. (**+ New workflow** opens the same conversation; **Step by step** opens the advanced editor, and **Talk it through in chat** starts a chat.)\n2. Answer the clarifying questions (usually two or three) by typing or by clicking a suggested answer. **Draft it now** skips the rest.\n3. Review the draft: its steps, schedule, what you fill in each run, the assumptions it made, and the **tools** each action step will use (ones that can change things are marked).\n4. Click **Create workflow** — this approves those tools, and runs use them without asking again — or **Keep refining** and type what to change, or **Edit details** to fine-tune it field by field. It appears under **Your workflows**, with **Edit** and **Delete**.\n\n*Advanced editor* — reached from **Step by step** under **Start here**, **Edit** on a custom workflow, **Edit details** on a draft, or **Use the advanced editor**:\n\n1. **Details:** a unique **Name** in snake_case (e.g. `weekly_competitor_watch`; 3–49 characters, starting with a letter), a title, description, section and estimated minutes.\n2. **Input fields:** click **+ Add field** for anything the person running it must supply. Use a field in a step's goal as `{field_name}`.\n3. **Steps:** add **+ Specialist** steps (pick a specialist, write its goal), **+ Action** steps (write what to get done and where, then **Search tools** and **+ Add** the ones it may use), and, if someone must sign off, an **+ Approval gate** (who to ask, the question, a timeout, and what happens on timeout). New steps are added at the bottom — use **↑** to move them above the synthesis step, which pulls everything together and must stay last; put an approval gate just before it. Up to 12 steps and 16 input fields.\n4. **Schedule (optional):** tick **Run on a schedule**, enter a cadence, and choose who the result is delivered to. Scheduled workflows can't have required inputs or approval gates.\n5. Click **Create workflow** (**Save changes** when editing).\n\nCadences are written like this (times are UTC): `daily@09:00`, `weekly@mon@09:00`, or `quarterly@01-09:00` (the 1st of January, April, July and October).\n\n*Workflows that use tools* — describe the job and where things live, e.g. *\"Every morning, find the bills I email you, read each PDF and add a row (vendor, amount, due date) to my Bill tracker sheet.\"* The assistant finds the right tools (here Gmail search and attachments, reading PDFs, and appending rows to Google Sheets) and asks about anything it needs, like which sheet. While a run works, the run page shows each tool as it's used, and the result lists every action taken. A workflow can only use the tools you approved, and every tool call is recorded in the audit log. You can also ask for one in chat: a workflow that uses tools is saved **switched off**, and the Executive gives you a link. It shows under *Waiting for your approval* at the top of the **Build** tab; open it, check the steps and tools, and click **Turn on workflow** — until then it can't run or follow a schedule.\n\n*Signing off a paused run* — when a run reaches an approval gate it moves to **Awaiting sign-off** and the approver is messaged directly. They answer by replying on Slack, Discord or Telegram — \"yes\", \"LGTM\", \"no\", \"not now\" — or with **Approve** / **Decline** on the run page (the principal can answer any sign-off there too). \"No\" or \"not now\" ends the run.\n\n*The first write somewhere new* — a workflow that uses tools picks where to write each time it runs (this month's tab, the sender of an invoice, a new doc per client). The first time it wants to write somewhere it hasn't written before — a different spreadsheet, a new recipient — that one write waits, the rest of the run carries on, and whoever created the workflow is asked: yes lets it write there now and in future runs, no skips it. The places a workflow may write without asking are listed under **Approved targets** on its page; remove one and it asks again.\n\n**From chat:**\n\n- *\"What workflows can you run?\"* or *\"Run a competitive teardown of Acme.\"* — the Executive runs it and brings the result back into the conversation.\n- *\"Build me a workflow called weekly_competitor_watch: the CMO checks our top three competitors for pricing and product changes, then summarise. Run it every Monday at 09:00 UTC and send it to me.\"* — the Executive drafts it, shows you a summary, and saves it once you say yes.\n\n*Note: outputs are listed in Documents. Ask OE can also fill in the advanced editor form for you.*",+ "markdown": "**What it is:** Structured, multi-step workflows that produce a *deliverable* — a board deck, a go-to-market plan, a performance review — or *get something done* with your connected tools, like filing emailed bills into a spreadsheet, rather than just a chat reply.\n\n**What it does:**\n\n- Start from **What do you want to get done?** at the top of the page: say what you want done in a sentence, or pick a suggestion.\n- Your own workflows sit under **Your workflows**, each with **Run** and a **⋯** menu (**Edit**, **Delete**). **Browse N ready-made** opens the full ready-made list in a side panel, with search and area chips (**System** holds the workflows Open Executive runs on its own, like the morning brief).\n- Start a run and watch it stream its progress step by step.\n- See your runs under **Runs** (in the switch beside **Your workflows**), split into **Active**, **Awaiting sign-off**, **Done**, and **Error**, and search them by name.\n- Create your own **custom workflow** by describing it: the assistant asks a few clarifying questions, then drafts it for you to review.\n- Let a workflow **use tools** — Gmail, Google Sheets, Drive and anything else connected — to actually do the work, not just write about it.\n- Put a custom workflow on a **schedule** (e.g. every Monday at 09:00) so it runs without being asked.\n- Each finished run produces a document you can read and keep.\n- Manage **Playbooks** from the same switch — the methods and templates the Executive follows in chat and inside workflows (see **Playbooks** in this guide). A workflow page lists the playbooks it follows, and a custom workflow's specialist step can **Follow a playbook** too.\n\n**How to use:**\n\n*Run a workflow*\n\n1. Open **Work** in the sidebar (it opens on **Workflows**), click **Browse N ready-made**, and narrow the list with the chips or the search box. Click a workflow to open it.\n2. Fill in the fields (required ones have a red \\*). **Use example** next to a field, or **Fill with an example** for the whole form, fills in realistic values if you just want to try it.\n3. Click **Continue**, then **Run workflow**. Progress streams step by step; when it finishes you land on the run page, with **Copy** and **Download .md**.\n\n*Build your own*\n\n1. Under **What do you want to get done?**, describe the job in plain words — what it should produce, who it's for, and how often — or pick one of the suggestions, then click **Start**. (The **⋯** beside **Start** has **New workflow**, which opens the same conversation, **New workflow, step by step**, which opens the advanced editor, and **Talk it through in chat**, which starts a chat.)\n2. Answer the clarifying questions (usually two or three) by typing or by clicking a suggested answer. **Draft it now** skips the rest.\n3. Review the draft: its steps, schedule, what you fill in each run, the assumptions it made, and the **tools** each action step will use (ones that can change things are marked).\n4. Click **Create workflow** — this approves those tools, and runs use them without asking again — or **Keep refining** and type what to change, or **Edit details** to fine-tune it field by field. It appears under **Your workflows**, with **Edit** and **Delete** in its **⋯** menu.\n\n*Advanced editor* — reached from **New workflow, step by step** in the **⋯** beside **Start**, **Edit** on a custom workflow, **Edit details** on a draft, or **Use the advanced editor**:\n\n1. **Details:** a unique **Name** in snake_case (e.g. `weekly_competitor_watch`; 3–49 characters, starting with a letter), a title, description, section and estimated minutes.\n2. **Input fields:** click **+ Add field** for anything the person running it must supply. Use a field in a step's goal as `{field_name}`.\n3. **Steps:** add **+ Specialist** steps (pick a specialist, write its goal), **+ Action** steps (write what to get done and where, then **Search tools** and **+ Add** the ones it may use), and, if someone must sign off, an **+ Approval gate** (who to ask, the question, a timeout, and what happens on timeout). New steps are added at the bottom — use **↑** to move them above the synthesis step, which pulls everything together and must stay last; put an approval gate just before it. Up to 12 steps and 16 input fields.\n4. **Schedule (optional):** tick **Run on a schedule**, enter a cadence, and choose who the result is delivered to. Scheduled workflows can't have required inputs or approval gates.\n5. Click **Create workflow** (**Save changes** when editing).\n\nCadences are written like this (times are UTC): `daily@09:00`, `weekly@mon@09:00`, or `quarterly@01-09:00` (the 1st of January, April, July and October).\n\n*Workflows that use tools* — describe the job and where things live, e.g. *\"Every morning, find the bills I email you, read each PDF and add a row (vendor, amount, due date) to my Bill tracker sheet.\"* The assistant finds the right tools (here Gmail search and attachments, reading PDFs, and appending rows to Google Sheets) and asks about anything it needs, like which sheet. While a run works, the run page shows each tool as it's used, and the result lists every action taken. A workflow can only use the tools you approved, and every tool call is recorded in the audit log. You can also ask for one in chat: a workflow that uses tools is saved **switched off**, and the Executive gives you a link. It shows under *Waiting for your approval* at the top of **Your workflows**; open it, check the steps and tools, and click **Turn on workflow** — until then it can't run or follow a schedule.\n\n*Signing off a paused run* — when a run reaches an approval gate it moves to **Awaiting sign-off** and the approver is messaged directly. They answer by replying on Slack, Discord or Telegram — \"yes\", \"LGTM\", \"no\", \"not now\" — or with **Approve** / **Decline** on the run page (the principal can answer any sign-off there too). \"No\" or \"not now\" ends the run.\n\n*The first write somewhere new* — a workflow that uses tools picks where to write each time it runs (this month's tab, the sender of an invoice, a new doc per client). The first time it wants to write somewhere it hasn't written before — a different spreadsheet, a new recipient — that one write waits, the rest of the run carries on, and whoever created the workflow is asked: yes lets it write there now and in future runs, no skips it. The places a workflow may write without asking are listed under **Approved targets** on its page; remove one and it asks again.\n\n**From chat:**\n\n- *\"What workflows can you run?\"* or *\"Run a competitive teardown of Acme.\"* — the Executive runs it and brings the result back into the conversation.\n- *\"Build me a workflow called weekly_competitor_watch: the CMO checks our top three competitors for pricing and product changes, then summarise. Run it every Monday at 09:00 UTC and send it to me.\"* — the Executive drafts it, shows you a summary, and saves it once you say yes.\n\n*Note: outputs are listed in Documents. Ask OE can also fill in the advanced editor form for you.*","mermaid": null,- "generated_at": "2026-09-24T00:00:00Z"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/knowledge.json b/packages/core/openexecutive/guide/prebuilt/knowledge.jsonindex b0dd99b3..4e6ac920 100644--- a/packages/core/openexecutive/guide/prebuilt/knowledge.json+++ b/packages/core/openexecutive/guide/prebuilt/knowledge.json@@ -1,7 +1,7 @@{"section_id": "knowledge","title": "Knowledge Base",- "markdown": "**What it is:** Your company's documents, in one place. Add handbooks, past decks, policies and plans, and the Executive reads them when answering. Files from a connected Google Drive folder or Notion workspace show up here too.\n\n**What it does:**\n\n- Opens on **Company documents**: one list of everything the Executive reads about your company, newest first.\n- Marks each document with where it came from — **Uploaded**, **Google Drive** or **Notion** — and when it was added or last synced.\n- Indexes each document automatically so specialists can pull the relevant passages into their reasoning.\n- Keeps connected sources up to date on a schedule, with a **Sync now** button when you can't wait.\n- Under **Advanced**: test retrieval in **Query mode**, browse the **Reference Library**, approve knowledge in the **Review queue**, and add your own playbooks and lessons learned.\n\n**How to use:**\n\n*Add a document*\n\n1. Open **Knowledge base**. It opens on **Company documents**.\n2. Drag files onto the drop area, or click **Add documents** (PDF, Word, Markdown or text, up to 50 MB each). You can add several at once.\n3. Once *Adding…* finishes, the document is searchable. Click its name or **View** to read the text the Executive sees, or **Delete** to remove it. To replace a document, delete it and add the new version.\n\n*Documents from Google Drive or Notion*\n\n1. Connect them in **Settings → Integrations**. Their files then appear in the list with a **Google Drive** or **Notion** badge, the time they were last synced and when they were last edited.\n2. **Open in Google Drive ↗** (or Notion) opens the original. Synced files can't be deleted here — remove them from the shared folder or Notion and they drop off on the next sync.\n3. Each connected source has a card above the list showing when it last synced and how often it syncs. Click **Sync now** to pick up a change straight away. If a sync failed, the card says why and links to the settings.\n\n*Check what the Executive will find*\n\n1. Open **Advanced → Query mode**, type a question, and click **Run**.\n2. Optionally narrow by **Specialist**, by source (**Include**), or by **Domains**. The results show which passages would be pulled and which specialists would see them — a lower distance means a closer match.\n\n*Add your own playbook*\n\n1. Open **Advanced**, expand **Built-in playbooks**, find the domain, and click **+** next to **Playbooks** (or **Failures** for a lessons-learned case).\n2. Enter a filename and the Markdown content, then click **Create file**.\n3. New playbooks wait in the **Review queue** and aren't used until you approve them — or click **Approve** under the filename. Open any playbook and use **Edit** / **Preview** to change it later.\n\n**Example:** add `pricing-policy-2026.pdf`, then in Query mode ask *\"what discount can sales offer without approval?\"* to confirm the right passage comes back.\n\n*Note: there's also a read-only built-in knowledge base (curated business know-how) that ships with the app. Files attached in chat are not added to the Knowledge Base.*",+ "markdown": "**What it is:** Your company's documents, in one place. Add handbooks, past decks, policies and plans, and the Executive reads them when answering. Files from a connected Google Drive folder or Notion workspace show up here too.\n\n**What it does:**\n\n- Opens on **Company documents**: one list of everything the Executive reads about your company, newest first.\n- Marks each document with where it came from — **Uploaded**, **Google Drive** or **Notion** — and when it was added or last synced.\n- Indexes each document automatically so specialists can pull the relevant passages into their reasoning.\n- Keeps connected sources up to date on a schedule, with a **Sync now** button when you can't wait.\n- Under the **Advanced** tab: approve knowledge in the **Review queue**, add your own playbooks and lessons learned under **Built-in playbooks**, browse the **Reference library**, and test retrieval in **Query test**.\n\n**How to use:**\n\n*Add a document*\n\n1. Open **Knowledge** in the sidebar. It opens on the **Company documents** tab.\n2. Drag files onto the drop area, or click **Add documents** (PDF, Word, Markdown or text, up to 50 MB each). You can add several at once.\n3. Once *Adding…* finishes, the document is searchable. Click its name or **View** to read the text the Executive sees; **Delete**, in the row's **⋯** menu, removes it. To replace a document, delete it and add the new version.\n\n*Documents from Google Drive or Notion*\n\n1. An administrator connects them with environment settings (see `docs/drive_sync_setup.md` and the other sync setup guides in `docs/`). Their files then appear in the list with a **Google Drive** or **Notion** badge, the time they were last synced and when they were last edited.\n2. **Open in Google Drive ↗** (or Notion), in the row's **⋯** menu, opens the original. Synced files can't be deleted here — remove them from the shared folder or Notion and they drop off on the next sync.\n3. Each connected source has a card above the list showing when it last synced and how often it syncs. Click **Sync now** to pick up a change straight away. If a sync failed, the card says why and links here.\n\n*Check what the Executive will find*\n\n1. Open the **Advanced** tab, then **Query test**, type a question, and click **Run**.\n2. Optionally narrow by **Specialist**, by source (**Include**), or by **Domains**. The results show which passages would be pulled and which specialists would see them — a lower distance means a closer match.\n\n*Add your own playbook*\n\n1. Open the **Advanced** tab, then **Built-in playbooks**, and click **+ Playbook** (or **+ Failure case** for a lessons-learned case). Pick the domain it belongs to.\n2. Enter a filename and the Markdown content, then click **Create file**.\n3. New playbooks wait in the **Review queue** and aren't used until you approve them — or click **Approve** under the filename. Open any playbook and use **Edit** / **Preview** to change it later; **Flag for revision** and **Delete file** are in its **⋯** menu.\n\n**Example:** add `pricing-policy-2026.pdf`, then in **Query test** ask *\"what discount can sales offer without approval?\"* to confirm the right passage comes back.\n\n*Note: there's also a read-only built-in knowledge base (curated business know-how) that ships with the app. Files attached in chat are not added to Knowledge.*","mermaid": null,- "generated_at": "2026-10-01T14:24:24+00:00"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/people.json b/packages/core/openexecutive/guide/prebuilt/people.jsonindex 1c950f12..9e20e085 100644--- a/packages/core/openexecutive/guide/prebuilt/people.json+++ b/packages/core/openexecutive/guide/prebuilt/people.json@@ -1,7 +1,7 @@{"section_id": "people","title": "People",- "markdown": "**What it is:** Everyone the Executive knows about, in two tabs. **Team** is the people who work with you — each with a response SLA, a preferred channel and the approvals they hold. **Contacts** is everyone outside the team — clients, contractors, advisors, or anyone else you deal with — and it is private to you.\n\n**What it does:**\n\n- Add team members with their role, email, and chat IDs (Slack / Discord / Telegram).\n- Set a response SLA so the Executive knows when a proposal is overdue.\n- Assign **authority scopes** (e.g. approve spend under $10k, sign off on hiring) so proposals route to the right person.\n- Mark the principal (you) and set availability or on-leave dates.\n- Keep **contacts** so the Executive can email or invite them — but only when you ask it to directly (in the web app, or from your own Slack or Discord). A contact can't sign in, can't message the Executive, never approves anything, and is never chased.\n- Keep contacts **private**: only you see them. Nobody else on your team sees the Contacts tab, finds a contact when they ask the Executive, or sees an alert about one.\n\n**Team member or contact?**\n\n| | Team member | Contact |\n|---|---|---|\n| Signs in to Open Executive (with an email) | Yes | No |\n| Messages the Executive on Slack / Discord / Telegram | Yes | No |\n| Approves proposals, gets check-ins and reminders | Yes | No |\n| The Executive emails or invites them | On any task | Only when you ask directly |\n| Who sees them | Everyone on the team | Only you |\n\n**How to use:**\n\n1. Open **People**, pick the **Team** or **Contacts** tab (only you, the principal, see Contacts), and click **+ Add person** (or **+ Add contact**).\n2. Choose **Team member** or **Contact** at the top of the dialog, then enter **Full name** (the only required field) and **Role** — for a contact, their role and company (e.g. *Head of Procurement, Acme*) — and their email. If this is you, tick **This is me — Primary** — this can only be set when adding someone, and you are always on the team.\n3. For a team member, expand **Contact & routing**: the preferred channel, **Expected reply within *N* hours** (their SLA — default 24), email, and Slack / Discord / Telegram IDs. Those IDs are also what lets this person talk to the Executive on those channels.\n4. For a team member, expand **Approval authority** and click each scope they hold:\n\n | Button | They can approve |\n |---|---|\n | Spend <$2K / <$10K / >$10K | Spend up to that amount (>$10K covers large spend) |\n | Hiring | Hiring sign-off |\n | Vendors | New vendor onboarding |\n | Credit | Customer credits |\n | Legal | Legal signatures |\n | Board | Board communications |\n | All (wildcard) | Anything — the catch-all for approvals no one else is scoped for; usually the principal |\n\n5. Click **Add person** (or **Add contact**). Later, open the person and click **Edit** to set **On leave until**, add **Availability windows** (days, hours, timezone), change their scopes, or move them between team and contacts; **Archive person** retires them from the roster.\n\n**Who can change it:** only the principal can add, edit or archive people — until someone is the principal, whoever sets up first can. Everyone signed in can see the team (your contacts stay yours alone), and teammates can still edit their own working style and mark their open loops done on their page.\n\n**Example from chat:** *\"Add Sarah Chen as our fractional CFO — [email protected] — she approves spend under $10k and usually replies within 48 hours.\"* Or: *\"Add Jordan Lee from Acme as a contact — [email protected] — and send them the proposal.\"* Or open **+ Add person**, press **Ctrl/Cmd + .**, and describe the person — Ask OE fills in the dialog for you to check and save.\n\n**Forward it to the Executive:** forward an email from a client to the Executive's address and it replies to you — not them — with a summary, a draft reply you can send, any dates or commitments, and an offer to add the sender as a contact. Mail a contact sends the Executive directly is summarised for you, never answered on its own. Either way it stays between you and the Executive: it tells no one else, and any alert it raises is yours alone.\n\n**Just for yourself?** When you use Open Executive just for yourself, setup adds only you — marked as the principal, with authority over everything. **People** stays in the sidebar under **You** and opens on **Contacts**: anyone you add from chat is a contact unless you say otherwise, and the **Team** tab shows just you. If you add a team member, Open Executive offers to switch to team mode — or you can keep using it just for yourself. The Briefing doesn't show a People card in this mode.\n\n*Note: authority scopes are how the Executive figures out who on the team to ask for any given approval.*",+ "markdown": "**What it is:** Everyone the Executive knows about, in two tabs. **Team** is the people who work with you — each with a response SLA, a preferred channel and the approvals they hold. **Contacts** is everyone outside the team — clients, contractors, advisors, or anyone else you deal with — and it is private to you.\n\n**What it does:**\n\n- Add team members with their role, email, and chat IDs (Slack / Discord / Telegram).\n- Set a response SLA so the Executive knows when a proposal is overdue.\n- Assign **authority scopes** (e.g. approve spend under $10k, sign off on hiring) so proposals route to the right person.\n- Mark the principal (you) and set availability or on-leave dates.\n- Keep **contacts** so the Executive can email or invite them — but only when you ask it to directly (in the web app, or from your own Slack or Discord). A contact can't sign in, can't message the Executive, never approves anything, and is never chased.\n- Keep contacts **private**: only you see them. Nobody else on your team sees the Contacts tab, finds a contact when they ask the Executive, or sees an alert about one.\n\n**Team member or contact?**\n\n| | Team member | Contact |\n|---|---|---|\n| Signs in to Open Executive (with an email) | Yes | No |\n| Messages the Executive on Slack / Discord / Telegram | Yes | No |\n| Approves proposals, gets check-ins and reminders | Yes | No |\n| The Executive emails or invites them | On any task | Only when you ask directly |\n| Who sees them | Everyone on the team | Only you |\n\n**How to use:**\n\n1. Open **Company** in the sidebar (it opens on **People**), pick the **Team** or **Contacts** tab (only you, the principal, see Contacts), and click **Add person** (or **Add contact**).\n2. Choose **Team member** or **Contact** at the top of the dialog, then enter **Full name** (the only required field) and **Role** — for a contact, their role and company (e.g. *Head of Procurement, Acme*) — and their email. If this is you, tick **This is me — Primary** — this can only be set when adding someone, and you are always on the team.\n3. For a team member, expand **Contact & routing**: the preferred channel, **Expected reply within *N* hours** (their SLA — default 24), email, and Slack / Discord / Telegram IDs. Those IDs are also what lets this person talk to the Executive on those channels.\n4. For a team member, expand **Approval authority** and click each scope they hold:\n\n | Button | They can approve |\n |---|---|\n | Spend <$2K / <$10K / >$10K | Spend up to that amount (>$10K covers large spend) |\n | Hiring | Hiring sign-off |\n | Vendors | New vendor onboarding |\n | Credit | Customer credits |\n | Legal | Legal signatures |\n | Board | Board communications |\n | All (wildcard) | Anything — the catch-all for approvals no one else is scoped for; usually the principal |\n\n5. Click **Add person** (or **Add contact**). Later, open the person and click **Edit** to change their details, scopes, or move them between team and contacts; **On leave until** and **Availability windows** (days, hours, timezone) are on the **Approvals & availability** tab. **Archive person**, in the **⋯** menu next to **Edit**, retires them from the roster.\n\n**Who can change it:** only the principal can add, edit or archive people — until someone is the principal, whoever sets up first can. Everyone signed in can see the team (your contacts stay yours alone), and teammates can still edit their own working style and mark their open loops done on their page.\n\n**Example from chat:** *\"Add Sarah Chen as our fractional CFO — [email protected] — she approves spend under $10k and usually replies within 48 hours.\"* Or: *\"Add Jordan Lee from Acme as a contact — [email protected] — and send them the proposal.\"* Or open **Add person**, press **Ctrl/Cmd + .**, and describe the person — Ask OE fills in the dialog for you to check and save.\n\n**Forward it to the Executive:** forward an email from a client to the Executive's address and it replies to you — not them — with a summary, a draft reply you can send, any dates or commitments, and an offer to add the sender as a contact. Mail a contact sends the Executive directly is summarised for you, never answered on its own. Either way it stays between you and the Executive: it tells no one else, and any alert it raises is yours alone.\n\n**Just for yourself?** When you use Open Executive just for yourself, setup adds only you — marked as the principal, with authority over everything. **People** stays in the sidebar under **You** and opens on **Contacts**: anyone you add from chat is a contact unless you say otherwise, and the **Team** tab shows just you. If you add a team member, Open Executive offers to switch to team mode — or you can keep using it just for yourself. Home doesn't show a People tile in this mode.\n\n*Note: authority scopes are how the Executive figures out who on the team to ask for any given approval.*","mermaid": null,- "generated_at": "2026-09-25T15:52:09.517837+00:00"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/pulse.json b/packages/core/openexecutive/guide/prebuilt/pulse.jsonindex 970024ef..bb1c868b 100644--- a/packages/core/openexecutive/guide/prebuilt/pulse.json+++ b/packages/core/openexecutive/guide/prebuilt/pulse.json@@ -1,7 +1,7 @@{"section_id": "pulse","title": "Pulse (Memory)",- "markdown": "**What it is:** The Executive's running memory and heartbeat — the decisions it has made with you, the initiatives it's tracking, the advice it has gathered, and the rhythm of work it runs on its own.\n\n**What it does:**\n\n- Browse past **decisions** with their rationale and outcome.\n- Track **initiatives** as planned, active, paused, or completed.\n- Review **advice** collected from specialists, searchable by topic.\n- See your **corrections** — facts you corrected or asked the Executive to keep, where you said them, and what they replaced. They hold everywhere: every conversation, brief, scheduled run and alert review.\n- See the **heartbeat** — the recurring cadence of daily briefs, department check-ins, system scans, and pending scheduled follow-ups.\n- Edit or delete any item to keep the Executive's memory accurate.\n\n**How to use:**\n\n1. Just chat. Decisions, initiatives and advice are pulled out of your conversations automatically after each chat — there's nothing to add by hand.\n2. Click **Pulse** in the sidebar. **Heartbeat** shows the rhythm the Executive runs on; **Memory** has tabs for **decisions**, **initiatives**, **advice** and **corrections** (side by side on a wide screen, stacked on a narrow one).\n3. Hover over any row and click **Edit** to correct it — fix a decision's rationale or outcome, change its domain or tags, or move an initiative to *completed* — then **Save**.\n4. Click **Delete** to remove something that's simply wrong. This can't be undone.\n5. To correct a fact, just say it in chat — *\"Maple House is 48 units, not 52\"* or *\"we're 42 people now\"*. The Executive keeps it (a company-profile field such as headcount or burn updates the profile too), and it shows under **corrections** with your words. Hover a correction and click **Retire** when it no longer holds; older versions stay under **Show history**. You can also email a correction from your own address: nothing changes until you reply CONFIRM to the confirmation email the Executive sends you. Teammates on your People list can correct facts too, from the web app or their own Slack or Discord. Theirs are marked with their name and wait for your approval at the top of the tab, and they appear in your morning brief. Untick **needs my approval** next to a teammate you trust to let theirs apply straight away; one that would replace yours still waits for you. Only you can retire someone else's correction.\n\n**Example:** tell the Executive *\"we've decided to push the EU launch to Q2 so we can finish SOC 2 first.\"* Afterwards, **Pulse → decisions** shows that decision with its rationale. If it captured the wrong reason, edit it — future answers build on what's recorded here.\n\n**Just for yourself?** When you use Open Executive just for yourself, the heartbeat leaves out department check-ins and the \"Awaiting people\" list, and the count of active projects takes the department check-ins' place at the top. The same projects appear on the Briefing under **Your projects**.\n\n*Note: this memory is searchable across the system, so what's captured here informs future answers.*",+ "markdown": "**What it is:** The Executive's running memory and heartbeat — the decisions it has made with you, the initiatives it's tracking, the advice it has gathered, and the rhythm of work it runs on its own.\n\n**What it does:**\n\n- Browse past **decisions** with their rationale and outcome.\n- Track **initiatives** as planned, active, paused, or completed.\n- Review **advice** collected from specialists, searchable by topic.\n- See your **corrections** — facts you corrected or asked the Executive to keep, where you said them, and what they replaced. They hold everywhere: every conversation, brief, scheduled run and alert review.\n- See the **heartbeat** — the recurring cadence of daily briefs, department check-ins, system scans, and pending scheduled follow-ups.\n- Edit or delete any item to keep the Executive's memory accurate.\n\n**How to use:**\n\n1. Just chat. Decisions, initiatives and advice are pulled out of your conversations automatically after each chat — there's nothing to add by hand.\n2. Click **Pulse** in the sidebar. At the top are three numbers — beats today, the next beat (when the next scheduled action is due) and memories — with the rest under **More stats**. Below them, the **Heartbeat** tab shows the rhythm the Executive runs on, with **Activity**, **Rhythm** and **Follow-ups** views; the **Memory** tab has tabs for **Decisions**, **Initiatives**, **Advice**, **Corrections** and **People**.\n3. Choose **Edit** in any row's **⋯** menu to correct it — fix a decision's rationale or outcome, change its domain or tags, or move an initiative to *completed* — then **Save**.\n4. Choose **Delete** in the same menu to remove something that's simply wrong. This can't be undone.\n5. To correct a fact, just say it in chat — *\"Maple House is 48 units, not 52\"* or *\"we're 42 people now\"*. The Executive keeps it (a company-profile field such as headcount or burn updates the profile too), and it shows under **Corrections** with your words. Choose **Retire (stop using it)** in a correction's **⋯** menu when it no longer holds; older versions stay under **Show history**. You can also email a correction from your own address: nothing changes until you reply CONFIRM to the confirmation email the Executive sends you. Teammates on your People list can correct facts too, from the web app or their own Slack or Discord. Theirs are marked with their name and wait for your approval at the top of the tab, and they appear in your morning brief. Untick **needs my approval** next to a teammate you trust to let theirs apply straight away; one that would replace yours still waits for you. Only you can retire someone else's correction.\n\n**Example:** tell the Executive *\"we've decided to push the EU launch to Q2 so we can finish SOC 2 first.\"* Afterwards, **Pulse → Memory → Decisions** shows that decision with its rationale. If it captured the wrong reason, edit it — future answers build on what's recorded here.\n\n**Just for yourself?** When you use Open Executive just for yourself, the heartbeat leaves out department check-ins and the \"Awaiting people\" list, and the count of active projects takes the department check-ins' place under **More stats**. The same projects appear on Home under **Your projects**.\n\n*Note: this memory is searchable across the system, so what's captured here informs future answers.*","mermaid": null,- "generated_at": "2026-09-29T00:00:00Z"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/review.json b/packages/core/openexecutive/guide/prebuilt/review.jsonindex bff4d519..e541200a 100644--- a/packages/core/openexecutive/guide/prebuilt/review.json+++ b/packages/core/openexecutive/guide/prebuilt/review.json@@ -1,7 +1,7 @@{"section_id": "review","title": "Review Queue",- "markdown": "**What it is:** A quality-control queue for incoming knowledge, facts, and information *before* the Executive starts relying on it.\n\n**What it does:**\n\n- List items awaiting review with their status (pending, approved, rejected, needs revision) and priority.\n- Open any item to see its full content and where it came from.\n- Approve, reject, or flag an item for revision — and attach corrections without changing the original.\n- Bulk-approve everything pending, or a whole domain at once when you trust the source.\n\n**How to use:**\n\n1. Open **Knowledge base** in the sidebar and open **Advanced** in the left-hand panel and click **Review queue** — the badge shows how many items are waiting, even while **Advanced** is closed.\n2. On the **Review queue** tab, click **View** on an item to read it and see where it came from.\n3. Decide:\n - **Approve** — the Executive can use it.\n - **Flag** — mark it *needs revision* as a reminder to follow up. A flagged item stays in use until you reject it.\n - **Reject** — keep it out; you can add a note saying why.\n - Use the priority dropdown (↓ Low / Normal / ↑ High) to order your queue.\n4. To fix a detail instead of rejecting the whole item, open **View**, type in *Add a correction or clarification…* and click **Add**. Active corrections are given to the Executive alongside the item; toggle one to **Inactive** to retire it.\n5. Trust a source? Click **Approve all pending**, or on the **All items** tab use **Approve all pending in *domain***.\n\n**Where items come from:** playbook and failure-case files you add or edit in the Knowledge Base, and any domain you choose to **Curate** — curating holds that domain's built-in knowledge back from the Executive until you approve it (**Stop curating** releases it). Company documents you upload go straight to the Knowledge Base and don't appear here.\n\n**Example:** you add a *discount-policy* playbook under finance. It shows up here as pending; open it, add the correction *\"Discounts over 15% need CFO sign-off\"*, then **Approve** — the Executive now uses the playbook with your correction attached.\n\n*Tip: when you open a playbook or failure case in the Knowledge base, its review status shows under the filename, with **Approve** and **Flag** right there.*\n\n*Note: approved and flagged items feed retrieval; pending and rejected ones are kept out. Editing an approved playbook flags it for re-review without taking it out of use.*",+ "markdown": "**What it is:** A quality-control queue for incoming knowledge, facts, and information *before* the Executive starts relying on it.\n\n**What it does:**\n\n- List items awaiting review with their status (pending, approved, rejected, needs revision) and priority.\n- Open any item to see its full content and where it came from.\n- Approve, reject, or flag an item for revision — and attach corrections without changing the original.\n- Bulk-approve everything pending, or a whole domain at once when you trust the source.\n\n**How to use:**\n\n1. Open **Knowledge** in the sidebar, pick the **Advanced** tab, then **Review queue** (`/knowledge?view=review` opens it directly). The number on **Advanced** and on **Knowledge** in the sidebar shows how many items are waiting.\n2. On **To review**, choose **View details** in an item's **⋯** menu to read it and see where it came from.\n3. Decide:\n - **Approve** — the button on the item: the Executive can use it.\n - **Flag for revision** (in **⋯**) — mark it *needs revision* as a reminder to follow up. A flagged item stays in use until you reject it.\n - **Reject…** (in **⋯**) — keep it out; you can add a note saying why.\n - **Priority** (in **⋯**: ↑ High / Normal / ↓ Low) orders your queue.\n4. To fix a detail instead of rejecting the whole item, open **View details**, type in *Add a correction or clarification…* and click **Add**. Active corrections are given to the Executive alongside the item; toggle one to **Inactive** to retire it.\n5. Trust a source? Click **Approve all pending**, or on **All items** pick a domain and click **Approve all pending in *domain***.\n\n**Where items come from:** playbook and failure-case files you add or edit under **Built-in playbooks** on the Knowledge page, and any domain you choose to **Curate** — curating holds that domain's built-in knowledge back from the Executive until you approve it (**Stop curating** releases it). Company documents you upload go straight to **Company documents** and don't appear here.\n\n**Example:** you add a *discount-policy* playbook under finance. It shows up here as pending; open it, add the correction *\"Discounts over 15% need CFO sign-off\"*, then **Approve** — the Executive now uses the playbook with your correction attached.\n\n*Tip: when you open a playbook or failure case under **Built-in playbooks**, its review status shows under the filename, with **Approve** right there and **Flag for revision** in its **⋯** menu.*\n\n*Note: approved and flagged items feed retrieval; pending and rejected ones are kept out. Editing an approved playbook flags it for re-review without taking it out of use.*","mermaid": null,- "generated_at": "2026-09-23T00:00:00+00:00"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/settings.json b/packages/core/openexecutive/guide/prebuilt/settings.jsonindex 6f8f6164..5200c6e5 100644--- a/packages/core/openexecutive/guide/prebuilt/settings.json+++ b/packages/core/openexecutive/guide/prebuilt/settings.json@@ -1,7 +1,7 @@{"section_id": "settings","title": "Settings & Advanced",- "markdown": "**What it is:** The one page for the settings that live outside the day-to-day nav: whether the Executive is running, who Open Executive is for, letting it write email as you, and the admin and power-user tools.\n\n**What it does:**\n\n- Lays the settings out as four sections down one page — **Executive**, **Workspace**, **Act as me** (the owner, and team members once the owner lets them) and **Tools** — with a section list beside them (a row of chips on a phone) that follows as you scroll and jumps to a section when you click it. A link can land on a section directly, such as **Settings → Workspace** on your profile page.\n- **Executive** shows whether the Executive is **running** or **paused**. While it runs, the pause form stays folded behind **Pause…**; while it is paused, the section stays open so the held count and **Resume** are in view.\n- **Workspace** holds, one row each: whether you use Open Executive just for yourself or with your team, your role when it's just you, your time zone, and whether the Executive books meetings without asking.\n- **Act as me** lets you have the Executive write email drafts as you, in your own voice, from your own Gmail — when you ask, and, if you turn it on, for mail in your inbox that needs you, which you can send from the Briefing with one tap. The fields of your writing profile sit behind **Edit how I write** until you want them.\n- **Tools** lists the pages that open their own screen, grouped by what you'd use them for: **Check & diagnose** (Setup status, Audit log, Token usage), **Configure** (Agent Council, Company Simulator, Client Companies) and **Learn** (User Guide, Architecture).\n\n**How to use:**\n\n1. Click **Settings** at the bottom of the sidebar.\n2. Click a section in the list beside the page (a chip above it on a phone) to jump there, or scroll — the list highlights where you are.\n3. Under **Tools**, click a row to open that page:\n - **Setup status** — check that every part of your setup is working, and see what to do about anything that isn't.\n - **Agent Council** — change a specialist's model or prompt, or the Executive's voice.\n - **Audit log** — find out what the Executive did, and why.\n - **Token usage** — see what you're spending and where.\n - **User Guide** — this guide.\n - **Architecture** — the technical reference for how the system is built.\n - **Company Simulator** — try the Executive on a test company.\n - **Client Companies** — switch between clients if you do fractional work.\n\n**Checking your setup:**\n\n- Open **Settings → Setup status**. Each part of your setup gets a light: green is working, amber needs attention, red isn't working, grey isn't set up (and is optional).\n- It tests things for real: the AI key, and each chat app's token, with a quick call that sends nothing. It also checks the Executive's email address, the company setup, the daily schedule, when and where your daily brief goes, and whether anyone on your team list can reach each chat app.\n- Anything that isn't green says what to do in plain words, with a button when the fix is on another page. After you change a setting and restart the app, click **Check again**.\n\n**Workspace:**\n\n- **Using Open Executive** — **Just me** or **With your team**. You pick this when you first set up; change it here. Switching asks you to confirm and says what changes:\n - **Just me** pauses department check-ins and shows **Goals** (grouped by area) in the sidebar instead of Departments. Nothing is deleted — your departments stay, as the areas your goals are grouped by.\n - **With your team** brings back Departments and their daily check-ins, and the People and department cards on the Briefing.\n- **Your role** (just you) — which describes you best (**Owner / founder**, **Executive inside an organisation**, **Independent or fractional**, or **Other**), your title, who you report to, what you're responsible for and what you're measured on. Every field is optional; click **Save role** after editing. The Executive uses it to fit its advice to your job — a VP gets help making the case to their boss, an owner gets help with a call that's theirs alone to make. It stays saved if you switch to your team.\n- **Time zone** — when your morning brief, end-of-day digest and reflection arrive, and how the Executive reads \"tomorrow at 9\". It suggests the zone your browser is in; **Follow server default** uses the server's setting.\n- **Book meetings without asking** — when on, the Executive books meetings on your calendar on its own; when off, each booking waits for your approval on the Briefing. (Shown only when your install supports it.)\n- Only the principal can change the mode, role and time zone. A persona you customised in Council stays in place in either mode.\n\n**Act as me:**\n\n- Normally the Executive writes only as itself, from its own email account. **Act as me** lets it write an email *as you*: ask in chat — \"reply to Dana as me: yes to the 5th\" — and it saves a draft in **your own Gmail Drafts** for you to read, change and send. Asking in chat never sends anything, and everything else it writes stays in its own name.\n- The owner sees this card, and so does each team member once the owner turns on **Let team members use it** at the bottom of it (shown only where your install allows it). Each team member connects their own Gmail and turns it on for themselves. What it reads in their mail, the drafts it writes and their **Replies waiting** are theirs alone: the owner sees only who uses it and how many drafts and sends it made, and a conversation in which it read someone's mail can be opened only by that person. Turning the owner's switch off takes it away from the team from their next message. It works when you ask in the web app, in a direct message to the Executive on Slack or Discord, or in a verified private Telegram chat — never in a shared channel or thread, from an email, a scheduled job or anyone else's conversation.\n- **Your Gmail** — connect your own Gmail first. The card shows the command to run on a computer with a browser; sign in as yourself, put the file it writes where your install reads it, then click **Check again**. It won't connect the Executive's own address as yours.\n- **Write drafts as me** — the switch. It stays off until your Gmail is connected, and turning it off applies from your next message.\n- **Draft replies to my inbox** — a second switch, once **Write drafts as me** is on. Every few minutes the Executive looks at new mail in your inbox, and for mail that needs a personal reply from you — a question, a request, a meeting to arrange, an introduction or a follow-up — it writes a first reply in your Gmail Drafts and puts it on your Briefing under **Replies waiting**. Nothing is sent until you tap **Send** there. It only looks at mail that arrives after you turn it on, and leaves out newsletters, notifications, mailing lists, mail you've already answered and anything that doesn't need you; mail you answer within ten minutes never gets a draft. The first reply only acknowledges: it repeats only what you've already said in the thread, commits you to nothing and lists what's left for you to decide. Someone you've never written to gets a short holding reply. The line under the switch says how it's doing (for example, that your Gmail needs connecting again) and when it last looked; click **Check now** to look straight away. Turning **Write drafts as me** off turns this off too.\n- **How I write** — click **Learn from my sent mail** and it reads your recent sent emails once and describes how you write (click **Edit how I write** to open the fields): your usual **Length** and **Tone**, a **Greeting** for your team, your contacts and anyone else ({first} stands for their first name), your **Sign-off**, your **Habits**, what you **Never** do, and a few **Examples of your writing** that set the tone. Change any of them and click **Save changes**; **Lock** stops it being relearned from your mail (you can still edit it); **Reset** starts over; **Remove examples** drops the examples. Your Gmail signature is added to every draft: **Refresh from Gmail** picks up a change you made to it in Gmail, **Don't add my signature** stops adding it, and **Add my Gmail signature** brings it back.\n- In chat you get a card, \"Drafted an email as you to …\", that opens the draft in Gmail. If the Executive isn't sure about something, it asks you instead of guessing.\n\n**Setting up just for yourself:**\n\n- The first time you set up, Open Executive asks who it is for — **Just me** or **Me and my team** — before anything else, and saves your time zone from the browser. Re-running setup later skips this; change the mode here instead.\n- **Just me** is for anyone who uses Open Executive just for themselves, whatever their role: your own business, a team you lead inside an organisation, or clients you advise as an independent or fractional executive.\n- Choosing **Just me** then asks **What's your role?** — the same fields as **Your role** above. Fill in what you like, or click **Skip for now**.\n- Just for yourself, the setup conversation asks about your work rather than your team, following the role you gave: an owner about what you offer, your customers, pricing, cash and runway; an executive inside an organisation about that organisation (it becomes your company profile), what you're responsible for, who you report to and what you're measured on; an independent about your practice and clients. Everyone is asked about their goals. On **Here's what I understood** there is a single **You** card (your name and role) next to **Your sign-in email**, instead of the team and department lists.\n- The step-by-step form skips the team size, team members and fractional executives steps.\n- In the sidebar, **You** holds **Goals**, **People** and your profile: **Business profile** if you own the business, **Your work** for any other role (or none). The profile page follows the same choice: for any other role it is worded around the organisation you work in (**Where You Work** in place of Company Basics). Either way departments are listed there as **Areas**, and your title, who you report to and what you're responsible for stay under **Your role** above.\n\n**Pausing the Executive:**\n\n- Click **Executive running** at the bottom of the sidebar (or **Pause…** in the Executive section at the top of Settings), add a reason if you like, and click **Pause Executive**.\n- While paused, the Executive starts nothing on its own: no briefs, nudges, monitoring, inbox processing or workflow timers. An amber banner appears on every page.\n- Chat and direct messages (Slack, Telegram, Discord, Google Chat) still get answers.\n- Nothing is lost. Work that falls due during the pause waits, and runs when you click **Resume**. The switch shows how many actions are waiting.\n- Anyone who can sign in can pause the Executive, but only the principal can resume it.\n\n*Tip: if you're looking for a feature that isn't in the sidebar, it's probably under Tools here. This guide is also pinned next to Settings at the bottom of the nav.*",+ "markdown": "**What it is:** The settings that live outside the day-to-day nav: whether the Executive is running and how it sounds, who Open Executive is for, letting it write email as you, and the admin and power-user tools.\n\n**What it does:**\n\n- Opens on a page of tiles, one per settings page — **Your Executive**, **Act as me** (the owner, and team members once the owner lets them), **Workspace**, **Advanced** and **About**. Each tile says what's on its page and, where it can, how things stand now (running or paused, the voice, just you or your team, a newer version). Click a tile to open its page; the **Settings** link at the top of each page takes you back. Old links to a section (such as `/settings#workspace`) land on the matching page.\n- **Your Executive** shows whether the Executive is **running** or **paused**, with one button: **Pause…** opens the pause form; while it is paused, who paused it, the held count and **Resume** stay in view. Below it, **Voice** picks the voice the Executive answers you in.\n- **Workspace** holds, one card each: whether you use Open Executive just for yourself or with your team, your role when it's just you, your time zone, and whether the Executive books meetings without asking. **Company email domains** sits under **Advanced** at the bottom.\n- **Act as me** lets you have the Executive write email drafts as you, in your own voice, from your own Gmail — when you ask, and, if you turn it on, for mail in your inbox that needs you, which you can send from Home with one tap. Your mailbox and the two switches are up front; **How I write** (and, for the owner, **Let team members use it**) sit under **Advanced** at the bottom.\n- **Advanced** lists the pages that open their own screen, grouped by what you'd use them for: **Check & diagnose** (Setup status, Audit log, Token usage), **Configure** (Agent Council, Company Simulator, Client Companies) and **Learn** (User Guide, Architecture).\n- **About** shows the version this install runs, and whether a newer one is out.\n\n**How to use:**\n\n1. Click **Settings** at the bottom of the sidebar. (On a phone, open the menu with the button at the top left; Settings is at its bottom.)\n2. Click a tile to open that page.\n3. On **Advanced**, click a row to open that page:\n - **Setup status** — check that every part of your setup is working, and see what to do about anything that isn't.\n - **Agent Council** — change a specialist's model or prompt, or the Executive's voice.\n - **Audit log** — find out what the Executive did, and why.\n - **Token usage** — see what you're spending and where.\n - **User Guide** — this guide.\n - **Architecture** — the technical reference for how the system is built.\n - **Company Simulator** — try the Executive on a test company.\n - **Client Companies** — switch between clients if you do fractional work.\n\n**Checking your setup:**\n\n- Open **Settings → Advanced → Setup status**. Each part of your setup gets a light: green is working, amber needs attention, red isn't working, grey isn't set up (and is optional).\n- It tests things for real: the AI key, and each chat app's token, with a quick call that sends nothing. It also checks the Executive's email address, the company setup, the daily schedule, when and where your daily brief goes, and whether anyone on your team list can reach each chat app.\n- Anything that isn't green says what to do in plain words, with a button when the fix is on another page. After you change a setting and restart the app, click **Check again**.\n\n**Workspace:**\n\n- **Using Open Executive** — **Just me** or **With your team**. You pick this when you first set up; change it here. Switching asks you to confirm and says what changes:\n - **Just me** pauses department check-ins and renames **Company** in the sidebar to **You**, with **Goals** (grouped by area), **People** and your profile — there is no Departments tab. Nothing is deleted — your departments stay, as the areas your goals are grouped by.\n - **With your team** brings back **Company** with its **Departments** tab and their daily check-ins, and the People and Departments tiles on Home.\n- **Your role** (just you) — which describes you best (**Owner / founder**, **Executive inside an organisation**, **Independent or fractional**, or **Other**), your title, who you report to, what you're responsible for and what you're measured on. Every field is optional; click **Save role** after editing. The Executive uses it to fit its advice to your job — a VP gets help making the case to their boss, an owner gets help with a call that's theirs alone to make. It stays saved if you switch to your team.\n- **Time zone** — when your morning brief, end-of-day digest and reflection arrive, and how the Executive reads \"tomorrow at 9\". It suggests the zone your browser is in; **Follow server default** uses the server's setting.\n- **Book meetings without asking** — when on, the Executive books meetings on your calendar on its own; when off, each booking waits for your approval on Home. (Shown only when your install supports it.)\n- **Company email domains** (under **Advanced**, principal only) — mail from these domains matches a teammate by the part before the @, and a new address there is filled in as a teammate when someone writes in. It follows your own address unless you set it here.\n- Only the principal can change the mode, role and time zone. A persona you customised in Council stays in place in either mode.\n\n**Act as me:**\n\n- Normally the Executive writes only as itself, from its own email account. **Act as me** lets it write an email *as you*: ask in chat — \"reply to Dana as me: yes to the 5th\" — and it saves a draft in **your own Gmail Drafts** for you to read, change and send. Asking in chat never sends anything, and everything else it writes stays in its own name.\n- The owner sees this page, and so does each team member once the owner turns on **Let team members use it** under **Advanced** at the bottom of it (shown only where your install allows it). Each team member connects their own Gmail and turns it on for themselves. What it reads in their mail, the drafts it writes and their **Replies waiting** are theirs alone: the owner sees only who uses it and how many drafts and sends it made, and a conversation in which it read someone's mail can be opened only by that person. Turning the owner's switch off takes it away from the team from their next message. It works when you ask in the web app, in a direct message to the Executive on Slack or Discord, or in a verified private Telegram chat — never in a shared channel or thread, from an email, a scheduled job or anyone else's conversation.\n- **Your Gmail** — connect your own Gmail first. The page shows the command to run on a computer with a browser; sign in as yourself, put the file it writes where your install reads it, then click **Check again**. It won't connect the Executive's own address as yours.\n- **Write drafts as me** — the switch. It stays off until your Gmail is connected, and turning it off applies from your next message.\n- **Draft replies to my inbox** — a second switch, once **Write drafts as me** is on. Every few minutes the Executive looks at new mail in your inbox, and for mail that needs a personal reply from you — a question, a request, a meeting to arrange, an introduction or a follow-up — it writes a first reply in your Gmail Drafts and puts it at the top of **Needs you** on Home. Nothing is sent until you tap **Send** there. It only looks at mail that arrives after you turn it on, and leaves out newsletters, notifications, mailing lists, mail you've already answered and anything that doesn't need you; mail you answer within ten minutes never gets a draft. The first reply only acknowledges: it repeats only what you've already said in the thread, commits you to nothing and lists what's left for you to decide. Someone you've never written to gets a short holding reply. The line under the switch says how it's doing (for example, that your Gmail needs connecting again) and when it last looked; click **Check now** to look straight away. Turning **Write drafts as me** off turns this off too.\n- **How I write** (under **Advanced**) — click **Learn from my sent mail** and it reads your recent sent emails once and describes how you write (click **Edit how I write** to open the fields): your usual **Length** and **Tone**, a **Greeting** for your team, your contacts and anyone else ({first} stands for their first name), your **Sign-off**, your **Habits**, what you **Never** do, and a few **Examples of your writing** that set the tone. Change any of them and click **Save changes**; **Lock** stops it being relearned from your mail (you can still edit it); **Reset** starts over; **Remove examples** drops the examples. Your Gmail signature is added to every draft: **Refresh from Gmail** picks up a change you made to it in Gmail, **Don't add my signature** stops adding it, and **Add my Gmail signature** brings it back.\n- In chat you get a card, \"Drafted an email as you to …\", that opens the draft in Gmail. If the Executive isn't sure about something, it asks you instead of guessing.\n\n**Setting up just for yourself:**\n\n- The first time you set up, Open Executive asks who it is for — **Just me** or **Me and my team** — before anything else, and saves your time zone from the browser. Re-running setup later skips this; change the mode here instead.\n- **Just me** is for anyone who uses Open Executive just for themselves, whatever their role: your own business, a team you lead inside an organisation, or clients you advise as an independent or fractional executive.\n- Choosing **Just me** then asks **What's your role?** — the same fields as **Your role** above. Fill in what you like, or click **Skip for now**.\n- Just for yourself, the setup conversation asks about your work rather than your team, following the role you gave: an owner about what you offer, your customers, pricing, cash and runway; an executive inside an organisation about that organisation (it becomes your company profile), what you're responsible for, who you report to and what you're measured on; an independent about your practice and clients. Everyone is asked about their goals. On **Here's what I understood** there is a single **You** card (your name and role) next to **Your sign-in email**, instead of the team and department lists.\n- The step-by-step form skips the team size, team members and fractional executives steps.\n- In the sidebar, **You** takes the place of **Company** and holds **Goals**, **People** and your profile: **Business profile** if you own the business, **Your work** for any other role (or none). The profile page follows the same choice: for any other role it is worded around the organisation you work in (**Where You Work** in place of Company Basics). Either way departments are listed there as **Areas**, and your title, who you report to and what you're responsible for stay under **Your role** above.\n\n**Pausing the Executive:**\n\n- Open **Settings → Your Executive** (or **Pause or resume the Executive** in the account menu — the **⋯** next to your name at the bottom of the sidebar) and click **Pause…**. Add a reason if you like, and click **Pause Executive**.\n- While paused, the Executive starts nothing on its own: no briefs, nudges, monitoring, inbox processing or workflow timers. An amber banner appears on every page.\n- Chat and direct messages (Slack, Telegram, Discord, Google Chat) still get answers.\n- Nothing is lost. Work that falls due during the pause waits, and runs when you click **Resume**. The switch shows how many actions are waiting.\n- Anyone who can sign in can pause the Executive, but only the principal can resume it.\n\n*Tip: if you're looking for a feature that isn't in the sidebar, it's probably under **Settings → Advanced**. This guide is also in the account menu (the **⋯** next to your name at the bottom of the sidebar), with **Pause or resume the Executive** and, when you signed in with an account, **Sign out**.*","mermaid": null,- "generated_at": "2026-09-30T20:00:00Z"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/simulator.json b/packages/core/openexecutive/guide/prebuilt/simulator.jsonindex a20160cf..03afa9d0 100644--- a/packages/core/openexecutive/guide/prebuilt/simulator.json+++ b/packages/core/openexecutive/guide/prebuilt/simulator.json@@ -1,7 +1,7 @@{"section_id": "simulator","title": "Company Simulator",- "markdown": "**What it is:** A sandbox for loading realistic *test* companies — full profile, org chart, documents, and memory — so you can see the Executive in action before trusting it with real data.\n\n**What it does:**\n\n- Browse and load pre-built company fixtures; your real data is snapshotted before the first load.\n- Generate a brand-new scenario with AI from a short description.\n- Review and edit a generated company before saving it.\n- Unload to restore your snapshot, or reset everything to factory defaults.\n\n**How to use:**\n\n1. Open **Settings → Company Simulator**.\n2. Click **Load** on a company, then **Open chat →** and try it out. The first time you load one, your real company is snapshotted automatically. If you've changed your real data since that snapshot, click **Snapshot current as my company** before loading again.\n3. To make your own, click **✨ Create with AI**, describe the company, and click **Generate**. Check the result (you can rename it), then **Save & Load** — or just **Save** to load it later.\n4. When you're done, click **Unload to my company** in the banner to put your own data back.\n5. **Reset everything** (in the Danger zone — type `RESET` to confirm) wipes all data, including your snapshot and any custom skills, and restores the default departments. It can't be undone.\n\n**Example description:** *\"A Series A vertical-SaaS startup selling scheduling software to independent dental practices — 45 people, burning $600K a month, 14 months of runway, and a head of sales who just resigned.\"*\n\n*Note: loading a fixture replaces your live context — but your original state is saved and restorable.*",+ "markdown": "**What it is:** A sandbox for loading realistic *test* companies — full profile, org chart, documents, and memory — so you can see the Executive in action before trusting it with real data.\n\n**What it does:**\n\n- Browse and load pre-built company fixtures; your real data is snapshotted before the first load.\n- Generate a brand-new scenario with AI from a short description.\n- Review and edit a generated company before saving it.\n- Unload to restore your snapshot, or reset everything to factory defaults.\n\n**How to use:**\n\n1. Open **Settings → Advanced → Company Simulator**.\n2. Click **Load** on a company, then **Open chat →** and try it out. The first time you load one, your real company is snapshotted automatically. If you've changed your real data since that snapshot, click **Snapshot current as my company** before loading again.\n3. To make your own, click **✨ Create with AI**, describe the company, and click **Generate**. Check the result (you can rename it), then **Save & Load** — or just **Save** to load it later.\n4. When you're done, click **Unload to my company** in the banner to put your own data back.\n5. **Reset everything** (in the Danger zone — type `RESET` to confirm) wipes all data, including your snapshot and any custom skills, and restores the default departments. It can't be undone.\n\n**Example description:** *\"A Series A vertical-SaaS startup selling scheduling software to independent dental practices — 45 people, burning $600K a month, 14 months of runway, and a head of sales who just resigned.\"*\n\n*Note: loading a fixture replaces your live context — but your original state is saved and restorable.*","mermaid": null,- "generated_at": "2026-09-23T00:00:00+00:00"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/skills.json b/packages/core/openexecutive/guide/prebuilt/skills.jsonindex 6d964779..1ec57ed9 100644--- a/packages/core/openexecutive/guide/prebuilt/skills.json+++ b/packages/core/openexecutive/guide/prebuilt/skills.json@@ -1,7 +1,7 @@{"section_id": "skills","title": "Playbooks",- "markdown": "**What it is:** Playbooks are *how* the Executive does a piece of work — a method, a template, or a checklist for a recurring task. They live on the **Playbooks** tab of **Workflows**. Some ship with the app (**Built-in**); the rest are ones you and the Executive create (**Yours**).\n\n**Playbooks vs. workflows:** a *workflow* is a job that runs — it has a form, steps, an optional schedule, and it produces a document. A *playbook* has none of that: it's the know-how the Executive follows, in chat or inside a workflow step. Six built-in workflows follow a playbook — Board prep, Quarterly plan, MBR, Competitive teardown, Fundraising prep and Exec search brief — so customizing that playbook changes what the workflow writes. A playbook shows **Followed by** with links to those workflows, and each workflow page shows the playbooks it follows. Hiding or deleting one warns you first; the workflow then runs without it. In chat, the Executive runs the workflow when you want the finished deliverable, and follows the playbook directly for a quick answer or a draft.\n\n**What it does:**\n\n- Browse playbooks grouped by category, with each one's purpose and when to use it.\n- Search by meaning to find the right one.\n- Let the Executive find and follow a matching playbook mid-task: when a request looks like work a playbook covers, it loads the steps before answering.\n- Create, edit, and delete your own playbooks — on the tab, or by asking the Executive.\n- **Customize** a built-in playbook to fit your company, and **revert** to the original any time.\n- **Hide** a built-in playbook you don't want the Executive to use, and **restore** it later.\n\n**How to use:**\n\n*Browse and search*\n\n1. Open **Workflows** and pick the **Playbooks** tab. (Old links to `/skills` land here.)\n2. Describe what you need in the search box — e.g. *\"cash forecast for next quarter\"* — and click **Search**. Matching looks at each playbook's name, description and *when to use*.\n3. Click a playbook to read its steps. **Try in chat** opens a new chat with *Use the \"…\" playbook to* already typed — finish the sentence and send.\n\n*Create a playbook*\n\n1. Click **+ New playbook**.\n2. Fill in:\n - a **name** — letters, numbers, `-` and `_` only, unique, and fixed once saved;\n - a **category** — strategy, finance, hr, legal, operations, marketing, product, board, or general;\n - a one-line **description** and a **when to use** line;\n - the **steps**, written in Markdown.\n3. Click **Save**. It appears under **Yours**, and from then on the Executive follows it whenever a request matches its *when to use*.\n\nYou can also ask in chat: *\"save that as a playbook\"* right after work you liked, or describe the steps you want. The Executive saves it as a **draft** and shows a *Drafted playbook: …* chip that links to it. It may also propose one on its own after doing repeatable work. The same goes for changes and deletions it suggests: nothing changes until you review it.\n\n*Review what the Executive proposed*\n\nProposals wait under **To review** at the top of the list. Open one to see what it would add, change or delete (with the current version alongside), then **Approve**, **Edit, then save**, or **Discard**.\n\n*Edit, customize, or remove*\n\n| You pick… | Edit button | Remove button |\n|---|---|---|\n| One of **Yours** | **Edit** — replaces the whole playbook | **Delete** — removed for good |\n| A **Built-in** | **Customize** — saves your company's version, which replaces the built-in everywhere; marked *edited* in the list | **Hide** — the Executive stops using it |\n| A customized built-in | **Edit** your version | **Revert to built-in** — your version is removed and the original is back |\n| A hidden built-in (tick **Show hidden**) | — | **Restore** |\n\nThe built-in originals ship with the app and are never changed; customizing and hiding only affect your company. Built-ins, and any playbook a workflow follows, are changed **only on this tab** — workflows read them on every run, so the Executive won't change them from chat (where a crafted message could steer it). It can edit and delete your other playbooks.\n\n**Example:** type this in chat —\n\n> Create a playbook called weekly-pipeline-review in the finance category. Use it whenever I ask for a pipeline review or \"how's the pipeline looking\". Gather the pipeline snapshot and this quarter's target first, and ask me if either is missing. Then produce a 3-bullet headline, a coverage-vs-target table, the deals that slipped or are at risk, and the decisions you need from me.\n\nThe Executive saves it as a Markdown playbook like this:\n\n```markdown\n---\nname: weekly-pipeline-review\ndescription: One-page weekly pipeline review — coverage, slippage, at-risk deals, decisions\nwhen_to_use: User asks for a pipeline review, weekly sales review, or \"how's the pipeline looking\"\ncategory: finance\n---\n\n# Weekly Pipeline Review\n\n## Inputs to gather first\n1. **Pipeline snapshot** — stage, amount, and close date per deal\n2. **Target for the quarter**\nIf either is missing, stop and ask.\n\n## Output\n1. **Headline** — 3 bullets\n2. **Coverage vs. target** — this week / last week / target\n3. **Slipped or at-risk deals**\n4. **Decisions needed**\n```\n\nNext time you ask *\"how's the pipeline looking?\"*, the Executive finds this playbook and follows it.\n\n*Tip: write **when to use** the way you'd actually phrase the request — that's what the Executive matches on. Resetting the Company Simulator deletes your own playbooks and undoes every customize and hide; the built-in originals are never affected.*",+ "markdown": "**What it is:** Playbooks are *how* the Executive does a piece of work — a method, a template, or a checklist for a recurring task. They live under **Playbooks** on the **Workflows** page (in **Work**). Some ship with the app (**Built-in**); the rest are ones you and the Executive create (**Yours**).\n\n**Playbooks vs. workflows:** a *workflow* is a job that runs — it has a form, steps, an optional schedule, and it produces a document. A *playbook* has none of that: it's the know-how the Executive follows, in chat or inside a workflow step. Six built-in workflows follow a playbook — Board prep, Quarterly plan, MBR, Competitive teardown, Fundraising prep and Exec search brief — so customizing that playbook changes what the workflow writes. A playbook shows **Followed by** with links to those workflows, and each workflow page shows the playbooks it follows. Hiding or deleting one warns you first; the workflow then runs without it. In chat, the Executive runs the workflow when you want the finished deliverable, and follows the playbook directly for a quick answer or a draft.\n\n**What it does:**\n\n- Browse playbooks grouped by category, with each one's purpose and when to use it.\n- Search by meaning to find the right one.\n- Let the Executive find and follow a matching playbook mid-task: when a request looks like work a playbook covers, it loads the steps before answering.\n- Create, edit, and delete your own playbooks — on the tab, or by asking the Executive.\n- **Customize** a built-in playbook to fit your company, and **revert** to the original any time.\n- **Hide** a built-in playbook you don't want the Executive to use, and **restore** it later.\n\n**How to use:**\n\n*Browse and search*\n\n1. Open **Work** in the sidebar and click **Playbooks** in the switch beside **Your workflows**. (Old links to `/skills` land here.)\n2. Describe what you need in the search box — e.g. *\"cash forecast for next quarter\"* — and click **Search**. Matching looks at each playbook's name, description and *when to use*.\n3. Click a playbook to read its steps. **Try in chat** opens a new chat with *Use the \"…\" playbook to* already typed — finish the sentence and send.\n\n*Create a playbook*\n\n1. Click **+ New playbook**.\n2. Fill in:\n - a **name** — letters, numbers, `-` and `_` only, unique, and fixed once saved;\n - a **category** — strategy, finance, hr, legal, operations, marketing, product, board, or general;\n - a one-line **description** and a **when to use** line;\n - the **steps**, written in Markdown.\n3. Click **Save**. It appears under **Yours**, and from then on the Executive follows it whenever a request matches its *when to use*.\n\nYou can also ask in chat: *\"save that as a playbook\"* right after work you liked, or describe the steps you want. The Executive saves it as a **draft** and shows a *Drafted playbook: …* chip that links to it. It may also propose one on its own after doing repeatable work. The same goes for changes and deletions it suggests: nothing changes until you review it.\n\n*Review what the Executive proposed*\n\nProposals wait under **To review** at the top of the list. Open one to see what it would add, change or delete (with the current version alongside), then **Approve** or **Edit, then save** — or **Discard proposal** from its **⋯** menu.\n\n*Edit, customize, or remove*\n\n| You pick… | Edit button | Remove (in the playbook's **⋯** menu) |\n|---|---|---|\n| One of **Yours** | **Edit** — replaces the whole playbook | **Delete** — removed for good |\n| A **Built-in** | **Customize** — saves your company's version, which replaces the built-in everywhere; marked *edited* in the list | **Hide** — the Executive stops using it |\n| A customized built-in | **Edit** your version | **Revert to built-in** — your version is removed and the original is back |\n| A hidden built-in (tick **Show hidden**) | — | **Restore** |\n\nThe built-in originals ship with the app and are never changed; customizing and hiding only affect your company. Built-ins, and any playbook a workflow follows, are changed **only here** — workflows read them on every run, so the Executive won't change them from chat (where a crafted message could steer it). It can edit and delete your other playbooks.\n\n**Example:** type this in chat —\n\n> Create a playbook called weekly-pipeline-review in the finance category. Use it whenever I ask for a pipeline review or \"how's the pipeline looking\". Gather the pipeline snapshot and this quarter's target first, and ask me if either is missing. Then produce a 3-bullet headline, a coverage-vs-target table, the deals that slipped or are at risk, and the decisions you need from me.\n\nThe Executive saves it as a Markdown playbook like this:\n\n```markdown\n---\nname: weekly-pipeline-review\ndescription: One-page weekly pipeline review — coverage, slippage, at-risk deals, decisions\nwhen_to_use: User asks for a pipeline review, weekly sales review, or \"how's the pipeline looking\"\ncategory: finance\n---\n\n# Weekly Pipeline Review\n\n## Inputs to gather first\n1. **Pipeline snapshot** — stage, amount, and close date per deal\n2. **Target for the quarter**\nIf either is missing, stop and ask.\n\n## Output\n1. **Headline** — 3 bullets\n2. **Coverage vs. target** — this week / last week / target\n3. **Slipped or at-risk deals**\n4. **Decisions needed**\n```\n\nNext time you ask *\"how's the pipeline looking?\"*, the Executive finds this playbook and follows it.\n\n*Tip: write **when to use** the way you'd actually phrase the request — that's what the Executive matches on. Resetting the Company Simulator deletes your own playbooks and undoes every customize and hide; the built-in originals are never affected.*","mermaid": null,- "generated_at": "2026-09-23T00:00:00+00:00"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/today.json b/packages/core/openexecutive/guide/prebuilt/today.jsonindex 189fc6ae..e64720e7 100644--- a/packages/core/openexecutive/guide/prebuilt/today.json+++ b/packages/core/openexecutive/guide/prebuilt/today.json@@ -1,7 +1,7 @@{"section_id": "today","title": "Today / Morning Brief",- "markdown": "**What it is:** A single screen of *what needs you right now* — the proactive digest the Executive prepares so you're not the one chasing status. In the app it's the **Briefing**, the screen the app opens on.\n\n**What it does:**\n\n- Splits items into **Needs you** (waiting on your call) and **Across the team** (everything else in motion).\n- Shows each department's goal health — on-track, at-risk, or off-track — with the at-risk goals called out.\n- Lists people with open items, their reply counts, SLA status, and whether they're on leave.\n- If your latest morning brief, end-of-day digest or weekly review couldn't be sent to you, a line at the top says why and what to connect. It goes away once that's fixed.\n- With **Settings → Act as me → Draft replies to my inbox** on, **Replies waiting** lists the replies the Executive wrote in your Gmail Drafts for mail that needs you. Only you see it.\n- Surfaces proposals and alerts you can click to open a chat thread with full context.\n\n**How to use:**\n\n1. Click **Briefing** in the sidebar (or the Open Executive logo).\n2. Work the **Needs you** lane from the top, starting with the **Start here** card. Each card offers:\n - **✓ Approve** — accept the recommendation; a chat opens so the Executive can carry it out.\n - **✎ Edit & approve** — reword the action first, then **✓ Send approval**; your text is used exactly as written.\n - **💬 Discuss** (or click the card) — open a chat with the context already filled in.\n - **✕ Dismiss** — drop it and stay on the briefing.\n - **↪ Nudge *name*** — shown when the best move is chasing someone for a reply.\n3. Some cards are simpler: a document card has one **✓ Mark reviewed** button, and a calendar-booking card books (or declines) the meeting directly when you click Approve or Dismiss. Only the person a booking was sent to for approval, or the owner, can approve or decline it.\n4. Keep the lane tidy: **✕ Dismiss N older than 7 days** clears stale items, and **⟳ Re-check relevance** asks the Executive to review every open item now.\n5. Click a department card to ask for that department's status in chat.\n6. Work **Replies waiting**: each card shows who wrote (and whether Gmail could confirm their address), what they wrote, your draft, and **Decide before sending** — what the draft leaves for you to answer. **Send** asks you once, naming who the reply goes to, then sends the draft from your Gmail exactly as it is there. If you changed who it goes to in Gmail, or they wrote again since, it asks a second time and says what changed. To change the wording, click **Edit in Gmail**, edit the draft there, then Send here or from Gmail. **Dismiss** deletes the draft, unless you've already edited it in Gmail. On a server, Send needs signed sign-ins; until they're set up, send from Gmail. A card goes away on its own once you send or delete the draft in Gmail, or reply yourself, and after a week.\n\n**Example:** in a Discuss thread, just say *\"go ahead\"* to approve the proposal or *\"drop it\"* to dismiss it — no need to go back to the card. (Calendar bookings still need the Approve button.)\n\n**Just for yourself?** If you use Open Executive just for yourself (**Settings → Workspace → Just me**), the Briefing leaves out the team parts: there is no Departments or People card and no \"Across the team\" lane — everything that needs a decision is in **Needs you**. A **goals at risk** badge at the top opens **Goals** when one is slipping. Instead, **Your projects** lists the projects the Executive is tracking for you. Click **✓ Done** when one is finished, or **Drop** to stop tracking it (it asks first, and removes the project from Pulse). **Due soon** lists what you've promised by a date and what others have asked of you, due in the next week — say *\"I'll send Northwind the proposal by Friday\"* in the web chat or your own Slack or Discord and it shows up here, and the Executive reminds you when it's due. Click **✓ Done** once it's handled; **All open items** opens the full list. **Top three today** shows the three things to focus on today — the same three your morning brief opens with — each with a free slot in today's working hours when the Executive can read your calendar. **This week's review** shows your latest weekly review: when it ran and next week's top three. Click **Read the review** to see all of it.\n\nYour morning brief also opens with a **top three for today**, picked from what's overdue or due, goals that are slipping and the projects you're driving. When Google Workspace is connected and the Executive can read your calendar (it is your own account, or you shared your calendar with it), each of the three gets a free slot in today's working hours and the brief lists today's meetings; otherwise the three come without times. Every Friday afternoon (in your time zone) a **weekly review** arrives the same way: your goals graded by area, what's due or overdue, projects that went quiet, the week's decisions, a few older decisions to look back on, and next week's top three. Both also show up on the Briefing (see above), so you see them even when no chat app or email is connected. When it asks how an older decision turned out, just tell the Executive in the web chat or your own Slack or Discord and it records the outcome against that decision.\n\n*Note: proposals are routed to the right person automatically based on who has authority over them.*",+ "markdown": "**What it is:** A single screen of *what needs you right now* — the proactive digest the Executive prepares so you're not the one chasing status. In the app it's **Home**, the screen the app opens on.\n\n**What it does:**\n\n- Opens with a greeting, one line summing up the day (click a part of it — *2 awaiting reply*, *1 department at risk* — to open that list), and an **Ask your Executive anything…** box that starts a chat.\n- Puts what's waiting on your call up front under **Needs you**: the first card large, the next two below it, and **Show N more** for the rest.\n- Gathers everything else under **Everything else** as a row of count tiles — **Departments**, **People**, **Across the team** (waiting on someone else), **In flight**, **Handled overnight**, **Monitoring** — shown only when they have something in them. Click a tile to open its full list in a side panel.\n- The **Departments** tile shows each department's goal health — on-track, at-risk, or off-track — with the at-risk goals called out.\n- The **People** tile lists people with open items, their reply counts, SLA status, and whether they're on leave.\n- **Read today's brief** (next to **Needs you**) opens the written brief — what's going on across the company — in a side panel.\n- If your latest morning brief, end-of-day digest or weekly review couldn't be sent to you, a line at the top says why and what to connect. It goes away once that's fixed.\n- With **Settings → Act as me → Draft replies to my inbox** on, the replies the Executive wrote in your Gmail Drafts for mail that needs you come first in **Needs you**. Only you see them.\n- Surfaces proposals and alerts you can click to open a chat thread with full context.\n\n**How to use:**\n\n1. Click **Home** in the sidebar (or the Open Executive logo). On a phone, **Home** is the first button in the bar at the bottom.\n2. Work **Needs you** from the top. Each card has one main button and **Discuss**; everything else is in the card's **⋯** menu:\n - **Approve** — accept the recommendation; a chat opens so the Executive can carry it out. Usually the main button.\n - **Discuss** — open a chat with the context already filled in.\n - **Edit & approve** (in **⋯**) — reword the action first, then **Send approval**; your text is used exactly as written.\n - **Dismiss** (in **⋯**) — drop it and stay on Home. When the Executive thinks a card is stale, **Dismiss** is the main button instead.\n - **Nudge *name*** — the main button when the best move is chasing someone for a reply; **Run *workflow*** when the best move is a workflow.\n - **Open *name*'s page** (in **⋯**) — the person the item is waiting on.\n3. Some cards are simpler: a document card's main button is **Open document** (**Mark reviewed** is in its **⋯**), and a calendar-booking card books (or declines) the meeting directly when you click Approve or Dismiss. Only the person a booking was sent to for approval, or the owner, can approve or decline it.\n4. Keep it tidy from the **⋯** next to **Needs you**: **Dismiss N older than 7 days** clears stale items, and **Re-check relevance** asks the Executive to review every open item now.\n5. Open the **Departments** tile and click a department to ask for its status in chat.\n6. Work the replies waiting to be sent (they come first in **Needs you**): each card shows who wrote (and whether Gmail could confirm their address), what they wrote, your draft, and **Decide before sending** — what the draft leaves for you to answer. **Send** asks you once, naming who the reply goes to, then sends the draft from your Gmail exactly as it is there. If you changed who it goes to in Gmail, or they wrote again since, it asks a second time and says what changed. To change the wording, choose **Edit in Gmail** in the card's **⋯**, edit the draft there, then Send here or from Gmail. **Dismiss** (also in **⋯**) deletes the draft, unless you've already edited it in Gmail. On a server, Send needs signed sign-ins; until they're set up, send from Gmail. A card goes away on its own once you send or delete the draft in Gmail, or reply yourself, and after a week.\n\n**Example:** in a Discuss thread, just say *\"go ahead\"* to approve the proposal or *\"drop it\"* to dismiss it — no need to go back to the card. (Calendar bookings still need the Approve button.)\n\n**Just for yourself?** If you use Open Executive just for yourself (**Settings → Workspace → Just me**), Home leaves out the team parts: there are no Departments, People or Across the team tiles — everything that needs a decision is in **Needs you**. When a goal is slipping, the summary line at the top says how many goals are at risk; click it to open **Goals**. Instead, the tiles are **Due soon**, **Your projects** and **This week's review**, each opening its list in a side panel. **Your projects** lists the projects the Executive is tracking for you. Click **Done** when one is finished, or **Drop** to stop tracking it (it asks first, and removes the project from Pulse). **Due soon** lists what you've promised by a date and what others have asked of you, due in the next week — say *\"I'll send Northwind the proposal by Friday\"* in the web chat or your own Slack or Discord and it shows up here, and the Executive reminds you when it's due. Click **Done** once it's handled; **All open items** opens the full list. **Top three today**, right under **Needs you**, shows the three things to focus on today — the same three your morning brief opens with — each with a free slot in today's working hours when the Executive can read your calendar. **This week's review** shows your latest weekly review: when it ran and next week's top three. Click **Read the review** to see all of it.\n\nYour morning brief also opens with a **top three for today**, picked from what's overdue or due, goals that are slipping and the projects you're driving. When Google Workspace is connected and the Executive can read your calendar (it is your own account, or you shared your calendar with it), each of the three gets a free slot in today's working hours and the brief lists today's meetings; otherwise the three come without times. Every Friday afternoon (in your time zone) a **weekly review** arrives the same way: your goals graded by area, what's due or overdue, projects that went quiet, the week's decisions, a few older decisions to look back on, and next week's top three. Both also show up on Home (see above), so you see them even when no chat app or email is connected. When it asks how an older decision turned out, just tell the Executive in the web chat or your own Slack or Discord and it records the outcome against that decision.\n\n*Note: proposals are routed to the right person automatically based on who has authority over them.*","mermaid": null,- "generated_at": "2026-09-30T20:00:00Z"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/token_usage.json b/packages/core/openexecutive/guide/prebuilt/token_usage.jsonindex 6f3991f1..f61e69b5 100644--- a/packages/core/openexecutive/guide/prebuilt/token_usage.json+++ b/packages/core/openexecutive/guide/prebuilt/token_usage.json@@ -1,7 +1,7 @@{"section_id": "token_usage","title": "Token Usage",- "markdown": "**What it is:** Cost and token accounting — a breakdown of where your AI spend is going.\n\n**What it does:**\n\n- Show total tokens and cost over all time or a date range.\n- Break usage down by source, by day, and by model.\n- Compare fresh input vs cached tokens, so you can see caching paying off.\n- Drill into a single session's cost, turn by turn, from the Audit log.\n\n**How to use:**\n\n1. Open **Settings → Token usage**.\n2. Set **From / Until** to look at a date range, or leave them blank for all time. **Clear filters** resets.\n3. Read the cards at the top: **Cost (USD)**, **Calls**, **Cache hit**, **Output tokens**, **Fresh input**, **Cache read**, **Cache write**, and **Searches**. A high cache-hit rate means you're paying the discounted rate for most input.\n4. Use the **By source**, **By model** and **By day (UTC)** tables to find what's driving spend.\n5. For one conversation's cost, go **← Audit log** and open that session.\n\n**Example:** spend jumped last week? Set **From / Until** to that week, check **By day** for the spike, then **By source** and **By model** to see what drove it.\n\n*Note: cached reads cost far less than fresh input — the system is built around caching to keep spend down. Lives under the Audit area in Settings.*",+ "markdown": "**What it is:** Cost and token accounting — a breakdown of where your AI spend is going.\n\n**What it does:**\n\n- Show total tokens and cost over all time or a date range.\n- Break usage down by source, by day, and by model.\n- Compare fresh input vs cached tokens, so you can see caching paying off.\n- Drill into a single session's cost, turn by turn, from the Audit log.\n\n**How to use:**\n\n1. Open **Settings → Advanced → Token usage**.\n2. Set **From / Until** to look at a date range, or leave them blank for all time. **Clear filters** resets.\n3. Read the cards at the top: **Cost (USD)**, **Calls**, **Cache hit**, **Output tokens**, **Fresh input**, **Cache read**, **Cache write**, and **Searches**. A high cache-hit rate means you're paying the discounted rate for most input.\n4. Use the **By source**, **By model** and **By day (UTC)** tables to find what's driving spend.\n5. For one conversation's cost, go **← Audit log** and open that session.\n\n**Example:** spend jumped last week? Set **From / Until** to that week, check **By day** for the spike, then **By source** and **By model** to see what drove it.\n\n*Note: cached reads cost far less than fresh input — the system is built around caching to keep spend down. Lives under the Audit area in Settings.*","mermaid": null,- "generated_at": "2026-09-23T00:00:00+00:00"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/prebuilt/watchlist.json b/packages/core/openexecutive/guide/prebuilt/watchlist.jsonindex e921f549..95fda315 100644--- a/packages/core/openexecutive/guide/prebuilt/watchlist.json+++ b/packages/core/openexecutive/guide/prebuilt/watchlist.json@@ -1,7 +1,7 @@{"section_id": "watchlist","title": "Watch List",- "markdown": "**What it is:** A set of external monitors that watch the outside world for you — stock tickers, RSS/Atom feeds, vendor status pages, SEC filings, web-search queries, and changes to specific web pages.\n\n**What it does:**\n\n- Add a monitor, choose its type and target, and set a severity range and optional trigger.\n- Enable or disable a monitor without deleting it, and see when it last fired.\n- Let qualifying signals flow into your briefing as proposals — the same path as inbound email or Slack.\n- Review monitors the Executive suggests before they go live.\n- Edit the whole list from chat as well as here.\n\n**How to use:**\n\n1. Open **Watch list** in the sidebar and click **+ Add monitor**.\n2. Fill in:\n - **Slug** — a short id in lowercase-with-dashes, e.g. `acme-pricing-page`.\n - **Signal type** and **Target** — see the table below.\n - **Trigger (JSON, optional)** — narrows what counts as a hit; leave blank for the defaults.\n - **Mode** — `active` raises alerts; `dry_run` records signals without alerting, which is handy for trying out a noisy source.\n - **Severity floor / ceiling** — signals below the floor are logged but never become alerts.\n3. Click **Add monitor**. Untick **enabled** on a card to pause it; click **inspect →** to switch mode, edit notes, or **Delete monitor**.\n4. Check **Suggested by the Executive** now and then — **Approve** turns a suggestion on, **Decline…** removes it. Suggestions never alert until approved.\n\n| Signal type | Target | Trigger example |\n|---|---|---|\n| Stock | Ticker, e.g. `AAPL` | `{\"abs_change_pct_gte\": 5}` (default: 5% move) |\n| RSS / Atom | Feed URL | `{\"keywords\": [\"pricing\", \"launch\"]}` |\n| Vendor status | The status page's Atom/RSS feed URL | `{\"keywords\": [\"degraded\", \"outage\"]}` |\n| SEC EDGAR | Ticker or CIK, e.g. `AAPL` or `320193` | `{\"forms\": [\"8-K\"]}` (default: 8-K, 10-K, 10-Q) |\n| Page change | A public page URL | `{\"keywords\": [\"price\"]}` (default: any change) |\n| Web search (billed) | A search query, e.g. `Acme Corp layoffs OR funding` | `{\"keywords\": [\"acquisition\"]}` |\n\n**From chat:** *\"Watch Apple stock and alert me on 5% moves.\"* · *\"What are we watching right now?\"* · *\"Stop watching that competitor's blog, it's too noisy.\"* Chat is also the way to change a monitor's trigger or severity after it's created.\n\n*Note: each source type is checked on its own schedule — stock prices every 15 minutes, feeds and status pages more often than filings, web pages and web searches every 6 hours. Web-search monitors are billed per check, so use them sparingly.*",+ "markdown": "**What it is:** A set of external monitors that watch the outside world for you — stock tickers, RSS/Atom feeds, vendor status pages, SEC filings, web-search queries, and changes to specific web pages.\n\n**What it does:**\n\n- Add a monitor, choose its type and target, and set a severity range and optional trigger.\n- Enable or disable a monitor without deleting it, and see when it last fired.\n- Let qualifying signals flow into your briefing as proposals — the same path as inbound email or Slack.\n- Review monitors the Executive suggests before they go live.\n- Edit the whole list from chat as well as here.\n\n**How to use:**\n\n1. Open **Work** in the sidebar, pick the **Watch list** tab, and click **+ Add monitor**.\n2. Fill in the **Signal type** and **Target** (see the table below), and optional **Notes**. The rest is under **More options**, with sensible defaults:\n - **Slug** — a short id in lowercase-with-dashes, e.g. `acme-pricing-page`. Left empty, it is named from the type and target.\n - **Trigger (JSON, optional)** — narrows what counts as a hit; leave blank for the defaults.\n - **Cadence** — how often it is checked.\n - **Mode** — `active` raises alerts; `dry_run` records signals without alerting, which is handy for trying out a noisy source.\n - **Severity floor / ceiling** — signals below the floor are logged but never become alerts.\n3. Click **Add monitor**. Use the switch on a card to pause or resume it; click the card (or **Open details** in its **⋯**) to switch mode, edit notes, or **Delete monitor** (in the **⋯** on that page). A monitor the Executive added has **Stop watching** in its **⋯**.\n4. Check **Suggested by the Executive** now and then — **Approve** turns a suggestion on, and **Decline** in its **⋯** removes it, with a reason. Suggestions never alert until approved.\n\n| Signal type | Target | Trigger example |\n|---|---|---|\n| Stock | Ticker, e.g. `AAPL` | `{\"abs_change_pct_gte\": 5}` (default: 5% move) |\n| RSS / Atom | Feed URL | `{\"keywords\": [\"pricing\", \"launch\"]}` |\n| Vendor status | The status page's Atom/RSS feed URL | `{\"keywords\": [\"degraded\", \"outage\"]}` |\n| SEC EDGAR | Ticker or CIK, e.g. `AAPL` or `320193` | `{\"forms\": [\"8-K\"]}` (default: 8-K, 10-K, 10-Q) |\n| Page change | A public page URL | `{\"keywords\": [\"price\"]}` (default: any change) |\n| Web search (billed) | A search query, e.g. `Acme Corp layoffs OR funding` | `{\"keywords\": [\"acquisition\"]}` |\n\n**From chat:** *\"Watch Apple stock and alert me on 5% moves.\"* · *\"What are we watching right now?\"* · *\"Stop watching that competitor's blog, it's too noisy.\"* Chat is also the way to change a monitor's trigger or severity after it's created.\n\n*Note: each source type is checked on its own schedule — stock prices every 15 minutes, feeds and status pages more often than filings, web pages and web searches every 6 hours. Web-search monitors are billed per check, so use them sparingly.*","mermaid": null,- "generated_at": "2026-09-23T00:00:00+00:00"+ "generated_at": "2026-10-03T12:00:00Z"}diff --git a/packages/core/openexecutive/guide/sections.py b/packages/core/openexecutive/guide/sections.pyindex ea74b699..4cd8f489 100644--- a/packages/core/openexecutive/guide/sections.py+++ b/packages/core/openexecutive/guide/sections.py@@ -48,7 +48,7 @@ GUIDE_SECTIONS: list[GuideSection] = [GuideSection(id="review",title="Review Queue",- sub="In the Knowledge base: approve, reject, or correct knowledge before the Executive relies on it.",+ sub="On Knowledge, under Advanced: approve, reject, or correct knowledge before the Executive relies on it.",),GuideSection(id="jobs",@@ -123,7 +123,7 @@ GUIDE_SECTIONS: list[GuideSection] = [GuideSection(id="settings",title="Settings & Advanced",- sub="The hub for power-user tools that sit outside the day-to-day nav — including this guide.",+ sub="Your Executive, workspace, Act as me, and the Advanced tools outside the day-to-day nav — including this guide.",),]diff --git a/packages/ui/scripts/briefingSummary.test.mjs b/packages/ui/scripts/briefingSummary.test.mjsnew file mode 100644index 00000000..5fa08522--- /dev/null+++ b/packages/ui/scripts/briefingSummary.test.mjs@@ -0,0 +1,91 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ ageLabel,+ briefingSummary,+ daysUntil,+ greeting,+ proposalStatusChip,+} from "../src/lib/briefingSummary.ts";++// Local-time constructors, so the labels hold in any test-runner time zone.+const at = (h) => new Date(2026, 9, 3, h, 30);++test("greeting follows the time of day and drops a missing name", () => {+ assert.equal(greeting("Jordan", at(8)), "Good morning, Jordan");+ assert.equal(greeting("Jordan", at(13)), "Good afternoon, Jordan");+ assert.equal(greeting("Jordan", at(19)), "Good evening, Jordan");+ assert.equal(greeting(undefined, at(8)), "Good morning");+ assert.equal(greeting(" ", at(8)), "Good morning");+});++const zero = {+ needsYou: 0,+ handledOvernight: 0,+ peopleOverdue: 0,+ peopleNeedReply: 0,+ deptAtRisk: 0,+ inFlight: 0,+ monitoring: 0,+};++test("an all-clear day has no summary phrases", () => {+ assert.deepEqual(briefingSummary(zero), []);+});++test("the summary leads with what needs you, then what was handled", () => {+ const parts = briefingSummary({ ...zero, needsYou: 3, handledOvernight: 12, inFlight: 7, deptAtRisk: 1 });+ assert.deepEqual(+ parts.map((p) => p.text),+ ["3 things need you", "The Executive handled 12 overnight", "1 department at risk", "7 in flight"],+ );+ assert.deepEqual(parts[0].target, { kind: "needsYou" });+ assert.deepEqual(parts[1].target, { kind: "panel", panel: "handled" });+});++test("singular wording, people phrases and the solo goals link", () => {+ const parts = briefingSummary({+ ...zero,+ needsYou: 1,+ peopleOverdue: 2,+ peopleNeedReply: 1,+ goalsAtRisk: 1,+ monitoring: 1,+ });+ assert.deepEqual(+ parts.map((p) => p.text),+ ["1 thing needs you", "2 overdue", "1 awaiting reply", "1 goal at risk", "1 signal monitored"],+ );+ assert.deepEqual(parts[1].target, { kind: "panel", panel: "people" });+ assert.deepEqual(parts[3].target, { kind: "href", href: "/goals" });+});++test("ageLabel and daysUntil", () => {+ const now = new Date(2026, 9, 3, 12, 0);+ assert.equal(ageLabel(new Date(2026, 9, 3, 11, 30).toISOString(), now), "30m");+ assert.equal(ageLabel(new Date(2026, 9, 2, 12, 0).toISOString(), now), "24h");+ assert.equal(ageLabel(new Date(2026, 8, 24, 12, 0).toISOString(), now), "9d");+ assert.equal(ageLabel("nonsense", now), "");+ assert.equal(daysUntil(new Date(2026, 9, 3, 1, 0).toISOString(), now), -1);+ assert.equal(daysUntil(new Date(2026, 9, 3, 20, 0).toISOString(), now), 0);+ assert.equal(daysUntil(null, now), null);+});++test("a collapsed card keeps one status chip: deadline, then stale, then age", () => {+ const now = new Date(2026, 9, 3, 12, 0);+ const created = new Date(2026, 9, 1, 12, 0).toISOString();+ assert.deepEqual(+ proposalStatusChip({ created_at: created, due_at: new Date(2026, 9, 2, 12, 0).toISOString() }, now),+ { label: "Overdue", tone: "rose" },+ );+ assert.deepEqual(+ proposalStatusChip({ created_at: created, due_at: new Date(2026, 9, 6, 13, 0).toISOString() }, now),+ { label: "Due in 3d", tone: "amber" },+ );+ assert.deepEqual(+ proposalStatusChip({ created_at: created, review_verdict: "likely_stale" }, now),+ { label: "Likely stale", tone: "amber" },+ );+ assert.deepEqual(proposalStatusChip({ created_at: created }, now), { label: "2d old", tone: "neutral" });+ assert.equal(proposalStatusChip({ created_at: "" }, now), null);+});diff --git a/packages/ui/scripts/councilCards.test.mjs b/packages/ui/scripts/councilCards.test.mjsnew file mode 100644index 00000000..de0f7f41--- /dev/null+++ b/packages/ui/scripts/councilCards.test.mjs@@ -0,0 +1,55 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ agentArea,+ agentCardStatus,+ agentDisplayName,+ agentInitials,+ shortModelName,+} from "../src/lib/councilCards.ts";++test("display name drops the group and the note", () => {+ assert.equal(agentDisplayName("Chief Financial Officer"), "Chief Financial Officer");+ assert.equal(agentDisplayName("Utility · Fast model (gates, titles, decision parsing)"), "Fast model");+ assert.equal(agentDisplayName("Committee · Quality Judge"), "Quality Judge");+});++test("area: built-in agents get plain words", () => {+ assert.equal(agentArea({ name: "cfo", role: "Chief Financial Officer", domains: ["finance"] }), "Finance");+ assert.equal(agentArea({ name: "executive", role: "Executive", domains: [] }), "Leads every answer");+});++test("area: an unknown agent falls back to its note, domains, then group", () => {+ assert.equal(agentArea({ name: "x", role: "Utility · Thing (does stuff)", domains: [] }), "Does stuff");+ assert.equal(agentArea({ name: "y", role: "Head of Data", domains: ["data", "hr"] }), "Data and people");+ assert.equal(agentArea({ name: "z", role: "Committee · Judge", domains: [] }), "Committee");+ assert.equal(agentArea({ name: "w", role: "Someone", domains: [] }), "Specialist");+});++test("initials skip small words", () => {+ assert.equal(agentInitials("Chief Financial Officer"), "CF");+ assert.equal(agentInitials("Head of Sales"), "HS");+ assert.equal(agentInitials("Executive"), "EX");+ assert.equal(agentInitials("Chief HR/People Officer"), "CH");+ assert.equal(agentInitials(""), "?");+});++test("short model names", () => {+ assert.equal(shortModelName("claude-sonnet-5"), "Sonnet 5");+ assert.equal(shortModelName("claude-opus-5-5"), "Opus 5.5");+ assert.equal(shortModelName("anthropic/claude-opus-5.5"), "Opus 5.5");+ assert.equal(shortModelName("claude-haiku-4-5-20251001"), "Haiku 4.5");+ assert.equal(shortModelName("openai/gpt-5"), "gpt-5");+ assert.equal(shortModelName("claude-sonnet-5", "Claude Sonnet 5"), "Sonnet 5");+ assert.equal(shortModelName("llama3", "llama3"), "llama3");+});++test("status: instructions, custom model or default", () => {+ assert.equal(agentCardStatus(false, undefined, false), "default");+ assert.equal(agentCardStatus(true, undefined, false), "instructions");+ assert.equal(agentCardStatus(true, ["instructions"], false), "instructions");+ assert.equal(agentCardStatus(true, ["model", "prompt"], true), "instructions");+ // A preset's own override is not the owner's.+ assert.equal(agentCardStatus(true, ["model", "use_deep_reasoning"], false), "default");+ assert.equal(agentCardStatus(true, ["model"], true), "custom-model");+});diff --git a/packages/ui/scripts/heartbeat-vitals.test.mjs b/packages/ui/scripts/heartbeat-vitals.test.mjsindex 4fd62b8a..60570f5a 100644--- a/packages/ui/scripts/heartbeat-vitals.test.mjs+++ b/packages/ui/scripts/heartbeat-vitals.test.mjs@@ -2,6 +2,7 @@ import assert from "node:assert/strict";import test from "node:test";import {deriveVitals,+ formatNextBeat,formatTrend,formatVitalDate,} from "../src/lib/heartbeatVitals.ts";@@ -141,3 +142,20 @@ test("a window shorter than 60 days compares the halves that exist", () => {test("formatVitalDate formats in UTC", () => {assert.equal(formatVitalDate("2026-09-08"), "Tue, Sep 8");});++// --- next beat ---------------------------------------------------------------++test("formatNextBeat reads a past or imminent run time as due now", () => {+ const now = Date.UTC(2026, 9, 3, 12, 0, 0);+ assert.equal(formatNextBeat("2026-10-03T11:30:00Z", now), "Due now");+ assert.equal(formatNextBeat("2026-10-03T12:00:00Z", now), "Due now");+ assert.equal(formatNextBeat("2026-10-03T12:00:30Z", now), "Due now");+});++test("formatNextBeat counts down to a future run time", () => {+ const now = Date.UTC(2026, 9, 3, 12, 0, 0);+ assert.equal(formatNextBeat("2026-10-03T12:12:00Z", now), "in 12m");+ assert.equal(formatNextBeat("2026-10-03T15:00:00Z", now), "in 3h");+ assert.equal(formatNextBeat("2026-10-06T12:00:00Z", now), "in 3d");+ assert.equal(formatNextBeat("not a date", now), "");+});diff --git a/packages/ui/scripts/knowledgeViews.test.mjs b/packages/ui/scripts/knowledgeViews.test.mjsnew file mode 100644index 00000000..4837bd8c--- /dev/null+++ b/packages/ui/scripts/knowledgeViews.test.mjs@@ -0,0 +1,29 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ ADVANCED_VIEWS,+ isAdvancedView,+ viewForSelection,+ viewFromParam,+} from "../src/lib/knowledgeViews.ts";++test("company documents is the only view up front", () => {+ assert.equal(isAdvancedView("company"), false);+ for (const v of ADVANCED_VIEWS) assert.equal(isAdvancedView(v), true);+});++test("?view=review opens the review queue; unknown values open documents", () => {+ assert.equal(viewFromParam("review"), "review");+ assert.equal(viewFromParam("playbooks"), "playbooks");+ assert.equal(viewFromParam(null), "company");+ assert.equal(viewFromParam("company"), "company");+ assert.equal(viewFromParam("nope"), "company");+});++test("a built-in file and the new-file form sit under the playbooks view", () => {+ assert.equal(viewForSelection("file"), "playbooks");+ assert.equal(viewForSelection("new"), "playbooks");+ assert.equal(viewForSelection("playbooks"), "playbooks");+ assert.equal(viewForSelection("query"), "query");+ assert.equal(viewForSelection(null), "company");+});diff --git a/packages/ui/scripts/menuNav.test.mjs b/packages/ui/scripts/menuNav.test.mjsnew file mode 100644index 00000000..da2415c1--- /dev/null+++ b/packages/ui/scripts/menuNav.test.mjs@@ -0,0 +1,35 @@+import assert from "node:assert/strict";+import test from "node:test";+import { nextMenuIndex } from "../src/lib/menuNav.ts";++const none = [false, false, false];++test("arrow down from the button lands on the first item", () => {+ assert.equal(nextMenuIndex(-1, "ArrowDown", none), 0);+});++test("arrow up from the button lands on the last item", () => {+ assert.equal(nextMenuIndex(-1, "ArrowUp", none), 2);+});++test("arrows wrap around", () => {+ assert.equal(nextMenuIndex(2, "ArrowDown", none), 0);+ assert.equal(nextMenuIndex(0, "ArrowUp", none), 2);+});++test("disabled items are skipped", () => {+ assert.equal(nextMenuIndex(0, "ArrowDown", [false, true, false]), 2);+ assert.equal(nextMenuIndex(-1, "ArrowDown", [true, false, false]), 1);+ assert.equal(nextMenuIndex(-1, "End", [false, false, true]), 1);+});++test("Home and End go to the first and last item", () => {+ assert.equal(nextMenuIndex(1, "Home", none), 0);+ assert.equal(nextMenuIndex(1, "End", none), 2);+});++test("other keys and empty menus leave focus where it is", () => {+ assert.equal(nextMenuIndex(1, "Tab", none), 1);+ assert.equal(nextMenuIndex(-1, "ArrowDown", []), -1);+ assert.equal(nextMenuIndex(-1, "ArrowDown", [true, true]), -1);+});diff --git a/packages/ui/scripts/navConfig.test.mjs b/packages/ui/scripts/navConfig.test.mjsindex 3b6b4c1b..d2cc8102 100644--- a/packages/ui/scripts/navConfig.test.mjs+++ b/packages/ui/scripts/navConfig.test.mjs@@ -4,82 +4,104 @@ import {ADVANCED_GROUPS,ADVANCED_ITEMS,PROFILE_NAV,- SETTINGS_SECTIONS,+ SETTINGS_PAGES,advancedItemsByGroup,+ buildDestinations,+ buildHubs,buildMobilePrimary,- buildPrimaryNav,+ hubForPath,+ isDestinationActive,profileWording,+ settingsPageForHash,} from "../src/components/shell/navConfig.ts";-const shape = (groups) =>- groups.map((g) => ({ key: g.key, label: g.label, items: g.items.map((i) => `${i.label} → ${i.href}`) }));+const links = (items) => items.map((i) => `${i.label} → ${i.href}`);+const ROLE_KINDS = ["owner", "in_house", "independent", "other", null, undefined];-// Pinned so a solo change can never leak into what a team install shows.-const TEAM = [- { key: "workspace", label: "Workspace", items: ["Workflows → /jobs", "Documents → /artifacts", "Watch list → /watchlist"] },- {- key: "company",- label: "Company",- items: ["Departments → /departments", "Goals → /goals", "People → /people", "Company profile → /company-profile"],- },- { key: "knowledge", label: "Knowledge", items: ["Knowledge base → /knowledge"] },-];+test("the main menu is six places, team is the default", () => {+ assert.deepEqual(links(buildDestinations()), [+ "Home → /",+ "Chats → /chats",+ "Work → /jobs",+ "Company → /people",+ "Knowledge → /knowledge",+ "Pulse → /memories",+ ]);+ assert.deepEqual(buildDestinations({ mode: "team" }), buildDestinations());+});-const ROLE_KINDS = ["owner", "in_house", "independent", "other", null, undefined];+test("solo swaps Company for You, which opens on Goals", () => {+ const solo = links(buildDestinations({ mode: "solo", roleKind: "owner" }));+ assert.equal(solo[3], "You → /goals");+ assert.equal(solo.length, 6);+});-test("team nav is unchanged, and team is the default", () => {- assert.deepEqual(shape(buildPrimaryNav()), TEAM);- assert.deepEqual(buildPrimaryNav({ mode: "team" }), buildPrimaryNav());- const notOnboarded = shape(buildPrimaryNav({ isOnboarded: false }));- assert.deepEqual(notOnboarded[1].items, [- "Departments → /departments",- "Goals → /goals",+test("team hubs: Work and Company tabs", () => {+ const [work, company] = buildHubs();+ assert.deepEqual(links(work.tabs), ["Workflows → /jobs", "Documents → /artifacts", "Watch list → /watchlist"]);+ assert.deepEqual(links(company.tabs), ["People → /people",- "Set up company → /onboard",+ "Goals → /goals",+ "Departments → /departments",+ "Company profile → /company-profile",]);- const profile = buildPrimaryNav()[1].items[3];- assert.equal(profile.description, "Your company's identity and strategy — set up once, edited any time.");+ const notOnboarded = buildHubs({ isOnboarded: false })[1].tabs.at(-1);+ assert.deepEqual([notOnboarded.label, notOnboarded.href], ["Set up company", "/onboard"]);+ assert.equal(+ company.tabs.at(-1).description,+ "Your company's identity and strategy — set up once, edited any time.",+ );});-test("team nav ignores the role", () => {+test("team hubs ignore the role", () => {for (const roleKind of ROLE_KINDS) {- assert.deepEqual(buildPrimaryNav({ roleKind }), buildPrimaryNav());- assert.deepEqual(buildPrimaryNav({ roleKind, isOnboarded: false }), buildPrimaryNav({ isOnboarded: false }));+ assert.deepEqual(buildHubs({ roleKind }), buildHubs());+ assert.deepEqual(buildDestinations({ roleKind }), buildDestinations());}});-test("solo swaps the Company group for You: Goals, People and the profile", () => {- const solo = shape(buildPrimaryNav({ mode: "solo", roleKind: "owner" }));- assert.deepEqual(solo[1], {- key: "you",- label: "You",- items: ["Goals → /goals", "People → /people", "Business profile → /company-profile"],- });- // Everything around it is the team nav, unchanged.- assert.deepEqual([solo[0], solo[2]], [TEAM[0], TEAM[2]]);- assert.ok(!JSON.stringify(solo).includes("/departments"));-});--test("solo: an owner's profile is their business", () => {- const item = buildPrimaryNav({ mode: "solo", roleKind: "owner" })[1].items[2];- assert.equal(item.label, "Business profile");- assert.equal(item.description, "Your business — what you offer, who you serve, your priorities.");- const notOnboarded = buildPrimaryNav({ mode: "solo", roleKind: "owner", isOnboarded: false })[1].items[2];+test("solo: You holds Goals, People and the profile, and no Departments", () => {+ const you = buildHubs({ mode: "solo", roleKind: "owner" })[1];+ assert.equal(you.key, "you");+ assert.deepEqual(links(you.tabs), ["Goals → /goals", "People → /people", "Business profile → /company-profile"]);+ assert.ok(!JSON.stringify(buildHubs({ mode: "solo" })).includes("/departments"));+ const notOnboarded = buildHubs({ mode: "solo", roleKind: "owner", isOnboarded: false })[1].tabs[2];assert.deepEqual([notOnboarded.label, notOnboarded.href], ["Set up your business", "/onboard"]);});test("solo: any other role, or none, is 'Your work'", () => {// null covers an unset role and one GET /workspace hides from a non-principal.for (const roleKind of ["in_house", "independent", "other", null, undefined]) {- const item = buildPrimaryNav({ mode: "solo", roleKind })[1].items[2];+ const item = buildHubs({ mode: "solo", roleKind })[1].tabs[2];assert.deepEqual([item.label, item.href], ["Your work", "/company-profile"], String(roleKind));assert.equal(item.description, "Your work — the organisation you work in, who it serves, your priorities.");assert.ok(!/business|company/i.test(item.label + item.description), String(roleKind));- const notOnboarded = buildPrimaryNav({ mode: "solo", roleKind, isOnboarded: false })[1].items[2];+ const notOnboarded = buildHubs({ mode: "solo", roleKind, isOnboarded: false })[1].tabs[2];assert.deepEqual([notOnboarded.label, notOnboarded.href], ["Set up your work", "/onboard"]);}- // The default (no roleKind passed) is the same as an unset role.- assert.deepEqual(buildPrimaryNav({ mode: "solo" }), buildPrimaryNav({ mode: "solo", roleKind: null }));+ assert.deepEqual(buildHubs({ mode: "solo" }), buildHubs({ mode: "solo", roleKind: null }));+});++test("a hub's menu entry stays lit on every one of its tabs", () => {+ const dests = buildDestinations();+ const lit = (path) => dests.filter((d) => isDestinationActive(d, path)).map((d) => d.key);+ assert.deepEqual(lit("/"), ["home"]);+ assert.deepEqual(lit("/jobs/runs/42"), ["work"]);+ assert.deepEqual(lit("/artifacts/7"), ["work"]);+ assert.deepEqual(lit("/watchlist"), ["work"]);+ assert.deepEqual(lit("/goals"), ["company"]);+ assert.deepEqual(lit("/departments/finance"), ["company"]);+ assert.deepEqual(lit("/company-profile"), ["company"]);+ assert.deepEqual(lit("/settings"), []);+});++test("hubForPath finds the hub a page belongs to", () => {+ assert.equal(hubForPath("/jobs/new")?.key, "work");+ assert.equal(hubForPath("/people/3")?.key, "company");+ assert.equal(hubForPath("/goals", { mode: "solo" })?.key, "you");+ assert.equal(hubForPath("/departments", { mode: "solo" }), null);+ assert.equal(hubForPath("/settings"), null);+ assert.equal(hubForPath("/"), null);});test("profileWording: company for a team, business for a solo owner, work otherwise", () => {@@ -97,25 +119,27 @@ test("profileWording: company for a team, business for a solo owner, work otherw}});-test("the review badge rides along in both modes", () => {+test("the review badge rides on Knowledge in both modes", () => {for (const mode of ["team", "solo"]) {- const kb = buildPrimaryNav({ mode, reviewBadge: 4 }).at(-1).items[0];+ const kb = buildDestinations({ mode, reviewBadge: 4 }).find((d) => d.key === "knowledge");assert.equal(kb.badge, 4);}});-test("mobile bar: solo swaps People for Goals", () => {- const team = buildMobilePrimary().map((i) => i.href);- assert.deepEqual(team, ["/", "/memories", "/?new=1", "/people", "/jobs"]);- assert.deepEqual(buildMobilePrimary("team"), buildMobilePrimary());- assert.deepEqual(buildMobilePrimary("solo").map((i) => i.href), ["/", "/memories", "/?new=1", "/goals", "/jobs"]);+test("phone bar: five, with New chat in the middle", () => {+ assert.deepEqual(buildMobilePrimary().map((i) => i.href), ["/", "/chats", "/?new=1", "/jobs", "/people"]);+ assert.deepEqual(buildMobilePrimary({ mode: "solo" }).map((i) => i.href), ["/", "/chats", "/?new=1", "/jobs", "/goals"]);});-test("every destination explains itself", () => {+test("every destination and tab explains itself", () => {for (const mode of ["team", "solo"]) {for (const roleKind of ROLE_KINDS) {- const items = [...buildPrimaryNav({ mode, roleKind }).flatMap((g) => g.items), ...buildMobilePrimary(mode)];- for (const item of items) assert.ok(item.description.trim(), `${item.href} needs a description`);+ const items = [+ ...buildDestinations({ mode, roleKind }),+ ...buildHubs({ mode, roleKind }).flatMap((h) => [h, ...h.tabs]),+ ...buildMobilePrimary({ mode, roleKind }),+ ];+ for (const item of items) assert.ok(item.description.trim(), `${item.label} needs a description`);}}});@@ -153,9 +177,39 @@ test("the Settings tools are grouped by what you'd use them for", () => {assert.equal(grouped.flatMap((g) => g.items).length, ADVANCED_ITEMS.length);});-test("the Settings sections have unique ids and a label each", () => {- const ids = SETTINGS_SECTIONS.map((s) => s.id);- assert.deepEqual(ids, ["executive", "workspace", "act-as-me", "tools", "about"]);- assert.equal(new Set(ids).size, ids.length);- for (const s of SETTINGS_SECTIONS) assert.ok(s.label.trim(), s.id);+test("the Settings hub: one tile per page, each with its own route", () => {+ assert.deepEqual(+ SETTINGS_PAGES.map((p) => `${p.label} → ${p.href}`),+ [+ "Your Executive → /settings/executive",+ "Act as me → /settings/act-as-me",+ "Workspace → /settings/workspace",+ "Advanced → /settings/advanced",+ "About → /settings/about",+ ],+ );+ assert.equal(new Set(SETTINGS_PAGES.map((p) => p.id)).size, SETTINGS_PAGES.length);+ for (const p of SETTINGS_PAGES) {+ assert.ok(p.label.trim() && p.description.trim(), p.id);+ assert.ok(p.href.startsWith("/settings/"), p.id);+ }+ // Setup status keeps its own route, outside the tiles.+ assert.ok(!SETTINGS_PAGES.some((p) => p.href === "/settings/status"));+});++test("old /settings#anchors land on the matching page", () => {+ const to = (hash) => settingsPageForHash(hash)?.href ?? null;+ assert.equal(to("#executive"), "/settings/executive");+ assert.equal(to("#workspace"), "/settings/workspace");+ assert.equal(to("act-as-me"), "/settings/act-as-me");+ assert.equal(to("#tools"), "/settings/advanced");+ for (const g of ADVANCED_GROUPS) assert.equal(to(`#tools-${g.key}`), "/settings/advanced");+ assert.equal(to("#about"), "/settings/about");+ assert.equal(to(""), null);+ assert.equal(to("#"), null);+ assert.equal(to("#nope"), null);+ assert.equal(to("#%E0%A4%A"), null);+ // Every anchor belongs to exactly one page.+ const all = SETTINGS_PAGES.flatMap((p) => p.hashes);+ assert.equal(new Set(all).size, all.length);});diff --git a/packages/ui/scripts/peopleKinds.test.mjs b/packages/ui/scripts/peopleKinds.test.mjsindex f96a74ff..189f27d5 100644--- a/packages/ui/scripts/peopleKinds.test.mjs+++ b/packages/ui/scripts/peopleKinds.test.mjs@@ -6,6 +6,7 @@ import {effectiveKind,hiddenTeamCount,isContact,+ personCardStatus,peopleForTab,shouldOfferTeamMode,tabsFor,@@ -68,3 +69,16 @@ test("adding a teammate in solo offers team mode; a contact or the principal doeassert.equal(shouldOfferTeamMode("solo", "contact", true), false);assert.equal(shouldOfferTeamMode("team", "team", false), false);});++test("a card's one status: email for a contact, leave or reply time for the team", () => {+ const base = { kind: "team", email: null, on_leave_until: null, response_sla_hours: 12 };+ assert.deepEqual(personCardStatus(base, "2026-10-03"), { label: "Replies within 12h", tone: "ok" });+ assert.deepEqual(+ personCardStatus({ ...base, on_leave_until: "2026-10-10" }, "2026-10-03"),+ { label: "On leave until 2026-10-10", tone: "warn" },+ );+ // A leave that has ended no longer shows.+ assert.equal(personCardStatus({ ...base, on_leave_until: "2026-09-30" }, "2026-10-03").label, "Replies within 12h");+ assert.deepEqual(personCardStatus({ ...base, kind: "contact" }, "2026-10-03"), { label: "No email", tone: "muted" });+ assert.equal(personCardStatus({ ...base, kind: "contact", email: "[email protected]" }, "2026-10-03").label, "Email on file");+});diff --git a/packages/ui/scripts/reviewBulk.test.mjs b/packages/ui/scripts/reviewBulk.test.mjsnew file mode 100644index 00000000..a3311fed--- /dev/null+++ b/packages/ui/scripts/reviewBulk.test.mjs@@ -0,0 +1,27 @@+import assert from "node:assert/strict";+import test from "node:test";+import { domainBulkActions } from "../src/lib/reviewBulk.ts";++const shipped = (domain) => ({ domain, trusted_default: true, reviewed_at: null });+const upload = (domain) => ({ domain, trusted_default: false, reviewed_at: null });++test("a domain with shipped items and nothing queued offers Curate", () => {+ const actions = domainBulkActions("finance", [], { finance: 12 });+ assert.deepEqual(actions.map((a) => a.kind), ["curate-start"]);+ assert.equal(actions[0].label, "Curate finance (12)");+});++test("a curated domain offers Approve all pending and Stop curating", () => {+ const actions = domainBulkActions("hr", [shipped("hr"), shipped("hr")], { hr: 0 });+ assert.deepEqual(actions.map((a) => a.kind), ["approve", "curate-stop"]);+ assert.equal(actions[0].count, 2);+});++test("a user's own pending upload doesn't count toward Stop curating", () => {+ const actions = domainBulkActions("legal", [upload("legal")], { legal: 3 });+ assert.deepEqual(actions.map((a) => a.kind), ["approve", "curate-start"]);+});++test("other domains' items are ignored, and an empty domain offers nothing", () => {+ assert.deepEqual(domainBulkActions("sales", [shipped("hr")], {}), []);+});diff --git a/packages/ui/scripts/sideNav.test.mjs b/packages/ui/scripts/sideNav.test.mjsindex b1455266..93b35f81 100644--- a/packages/ui/scripts/sideNav.test.mjs+++ b/packages/ui/scripts/sideNav.test.mjs@@ -42,7 +42,7 @@ const read = (f) => readFileSync(new URL(`../src/${f}`, import.meta.url), "utf8"const users = sourceFiles("").filter((f) => f !== "components/shell/PageSideNav.tsx" && /<PageSideNav/.test(read(f)));test("PageSideNav users are found", () => {- assert.ok(users.length >= 4, `found ${users.join(", ")}`);+ assert.ok(users.length >= 3, `found ${users.join(", ")}`);});for (const user of users) {diff --git a/packages/ui/scripts/watchSlug.test.mjs b/packages/ui/scripts/watchSlug.test.mjsnew file mode 100644index 00000000..06360694--- /dev/null+++ b/packages/ui/scripts/watchSlug.test.mjs@@ -0,0 +1,28 @@+import assert from "node:assert/strict";+import test from "node:test";+import { suggestWatchSlug } from "../src/lib/watchSlug.ts";++const VALID = /^[a-z0-9][a-z0-9-]{0,60}$/;++test("suggestWatchSlug names a monitor from its type and target", () => {+ assert.equal(suggestWatchSlug("stock", "AAPL"), "stock-aapl");+ assert.equal(suggestWatchSlug("edgar", "320193"), "edgar-320193");+ assert.equal(+ suggestWatchSlug("rss", "https://www.example.com/blog/feed.xml"),+ "rss-example-com-blog-feed-xml",+ );+ assert.equal(suggestWatchSlug("query", "Acme Corp layoffs OR funding"), "search-acme-corp-layoffs-or-funding");+ assert.equal(suggestWatchSlug("vendor_status", "https://status.vendor.io/history.atom"), "status-status-vendor-io-history-atom");+});++test("suggestWatchSlug is empty without a target", () => {+ assert.equal(suggestWatchSlug("stock", " "), "");+});++test("suggestWatchSlug always fits the API's slug rule", () => {+ const long = suggestWatchSlug("page_watch", "https://example.com/" + "pricing-page/".repeat(20));+ assert.ok(long.length <= 61);+ assert.match(long, VALID);+ assert.ok(!long.endsWith("-"));+ assert.match(suggestWatchSlug("Custom_Kind", "Ünïcode — target!"), VALID);+});diff --git a/packages/ui/scripts/workflowCards.test.mjs b/packages/ui/scripts/workflowCards.test.mjsnew file mode 100644index 00000000..5eadfa5f--- /dev/null+++ b/packages/ui/scripts/workflowCards.test.mjs@@ -0,0 +1,46 @@+import assert from "node:assert/strict";+import test from "node:test";+import { cadenceLabel, cardAction, lastRunAt } from "../src/lib/workflowCards.ts";++test("cadenceLabel says the known cadences in words", () => {+ assert.equal(cadenceLabel("daily@08:30"), "Every day at 08:30 UTC");+ assert.equal(cadenceLabel("weekly@mon@09:00"), "Every Monday at 09:00 UTC");+ assert.equal(cadenceLabel("weekly@FRI@17:00"), "Every Friday at 17:00 UTC");+ assert.equal(cadenceLabel("quarterly@05-10:00"), "Quarterly, day 5 at 10:00 UTC");+});++test("cadenceLabel keeps an unknown or empty cadence readable", () => {+ assert.equal(cadenceLabel(null), "");+ assert.equal(cadenceLabel(" "), "");+ assert.equal(cadenceLabel("weekly@xyz@09:00"), "weekly@xyz@09:00");+ assert.equal(cadenceLabel("hourly"), "hourly");+});++const run = (id, name, status, updated) => ({+ run_id: id,+ workflow_name: name,+ status,+ updated_at: updated,+});++test("cardAction: off workflows are reviewed, sign-offs lead, else Run", () => {+ const runs = [+ run("a", "digest", "done", "2026-10-01T09:00:00Z"),+ run("b", "board", "awaiting_human", "2026-10-01T09:00:00Z"),+ run("c", "board", "awaiting_human", "2026-10-02T09:00:00Z"),+ ];+ assert.deepEqual(cardAction("digest", false, runs), { kind: "approve" });+ assert.deepEqual(cardAction("board", true, runs), { kind: "signoff", runId: "c" });+ assert.deepEqual(cardAction("digest", true, runs), { kind: "run" });+ assert.deepEqual(cardAction("other", true, []), { kind: "run" });+});++test("lastRunAt is the newest run of that workflow", () => {+ const runs = [+ run("a", "digest", "done", "2026-10-01T09:00:00Z"),+ run("b", "digest", "error", "2026-10-02T09:00:00Z"),+ run("c", "board", "done", "2026-10-03T09:00:00Z"),+ ];+ assert.equal(lastRunAt("digest", runs), "2026-10-02T09:00:00Z");+ assert.equal(lastRunAt("none", runs), null);+});diff --git a/packages/ui/src/app/artifacts/[id]/page.tsx b/packages/ui/src/app/artifacts/[id]/page.tsxindex 4bba80ac..982f86bb 100644--- a/packages/ui/src/app/artifacts/[id]/page.tsx+++ b/packages/ui/src/app/artifacts/[id]/page.tsx@@ -13,7 +13,8 @@ import {restoreArtifact,} from "@/lib/api";import ArtifactViewer from "@/components/ArtifactViewer";-import Icon from "@/components/Icon";+import Button, { buttonClass } from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";// Seed for "Revise in chat": opens a fresh chat with the id pre-filled so the// Executive can get_artifact → draft_artifact(supersedes=…).@@ -70,6 +71,16 @@ export default function ArtifactDetailPage() {}}, [art]);+ // Downloads come from the API; an <a download> keeps the page in place.+ const download = useCallback((url: string) => {+ const a = document.createElement("a");+ a.href = url;+ a.download = "";+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ }, []);+const handleDelete = useCallback(async () => {if (!art) return;if (@@ -93,7 +104,7 @@ export default function ArtifactDetailPage() {<div className="flex flex-col h-full bg-surface text-fg items-center justify-center"><div className="text-sm text-red-400 mb-4">Error: {error}</div><Link href="/artifacts" className="text-sm text-fg-muted hover:text-fg">- ← Back to artifacts+ ← Back to documents</Link></div>);@@ -111,80 +122,72 @@ export default function ArtifactDetailPage() {<div className="flex flex-col h-full bg-surface text-fg"><main className="flex-1 overflow-y-auto px-4 sm:px-6 py-8"><div className="max-w-4xl mx-auto space-y-6">- <div className="flex items-start justify-between gap-4">+ <Link href="/artifacts" className="text-sm text-fg-muted hover:text-fg">+ ← Documents+ </Link>+ <div className="flex flex-wrap items-start justify-between gap-4"><div className="min-w-0">- <h1 className="text-2xl font-semibold text-fg mb-1">{art.title}</h1>- <div className="text-xs text-fg-muted">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg mb-2 break-words">+ {art.title}+ </h1>+ <div className="text-sm text-fg-muted">{art.format_label} · {art.source_label} · created{" "}{formatTimestamp(art.created_at)}+ {art.archived_at && " · archived"}</div>{art.supersedes_id && (- <div className="text-xs text-fg-muted mt-1">+ <div className="text-sm text-fg-muted mt-1">Replaces an{" "}<Linkhref={`/artifacts/${encodeURIComponent(art.supersedes_id)}`}- className="text-indigo-400 hover:underline"+ className="text-accent hover:underline">earlier version</Link></div>)}</div>- <div className="flex flex-wrap items-center justify-end gap-2 flex-shrink-0">- <button- type="button"- onClick={handleCopy}- className="text-xs text-fg-muted hover:text-fg transition px-3 py-1.5 rounded-md border border-line hover:bg-surface-overlay min-h-touch"- >- {copied ? "Copied!" : "Copy"}- </button>- <Link- href={reviseHref(art)}- className="text-xs text-indigo-300 hover:text-indigo-200 transition px-3 py-1.5 rounded-md border border-indigo-500/40 hover:bg-indigo-500/10 min-h-touch"- >+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <Link href={reviseHref(art)} className={buttonClass("primary", "md")}>Revise in chat</Link>- {art.downloads.map((target, i) => (- <a- key={target}- href={artifactDownloadUrl(art.id, i === 0 ? undefined : target)}- download- className="text-xs text-fg-muted hover:text-fg transition px-3 py-1.5 rounded-md border border-line hover:bg-surface-overlay min-h-touch"- >- Download .{ARTIFACT_EXTENSIONS[target]}- </a>- ))}- <button- type="button"- onClick={handleToggleArchive}- disabled={busy}- className="inline-flex items-center gap-1.5 text-xs text-fg-muted hover:text-fg transition px-3 py-1.5 rounded-md border border-line hover:bg-surface-overlay min-h-touch disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"- >- <Icon- name={art.archived_at ? "restore" : "archive"}- size="w-3.5 h-3.5"+ <Button onClick={handleCopy}>{copied ? "Copied!" : "Copy"}</Button>+ {art.downloads.length > 0 && (+ <OverflowMenu+ trigger="Download"+ label="Download"+ items={art.downloads.map((target, i) => ({+ label: `As .${ARTIFACT_EXTENSIONS[target]}`,+ onSelect: () =>+ download(artifactDownloadUrl(art.id, i === 0 ? undefined : target)),+ }))}/>- {art.archived_at ? "Restore" : "Archive"}- </button>- <button- type="button"- onClick={handleDelete}- disabled={busy}- aria-label="Delete permanently"- className="inline-flex items-center gap-1.5 text-xs text-fg-muted hover:text-red-400 transition px-3 py-1.5 rounded-md border border-line hover:bg-red-500/10 hover:border-red-500/30 min-h-touch disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"- >- <Icon name="trash" size="w-3.5 h-3.5" />- Delete- </button>+ )}+ <OverflowMenu+ label="More actions"+ items={[+ {+ label: art.archived_at ? "Restore" : "Archive",+ disabled: busy,+ onSelect: () => void handleToggleArchive(),+ },+ {+ label: "Delete permanently",+ danger: true,+ disabled: busy,+ onSelect: () => void handleDelete(),+ },+ ]}+ /></div></div>{art.rationale && (- <div className="rounded-md border border-amber-500/30 bg-amber-500/5 px-4 py-3">- <div className="text-xs font-medium text-amber-300 mb-1">+ <div className="rounded-2xl border border-amber-500/30 bg-amber-500/5 px-5 py-4">+ <div className="text-sm font-semibold text-amber-600 dark:text-amber-300 mb-1">Why this is worth your time</div>- <div className="text-sm text-fg">{art.rationale}</div>+ <div className="text-[15px] text-fg">{art.rationale}</div></div>)}diff --git a/packages/ui/src/app/artifacts/page.tsx b/packages/ui/src/app/artifacts/page.tsxindex 28c3aca7..a9690d49 100644--- a/packages/ui/src/app/artifacts/page.tsx+++ b/packages/ui/src/app/artifacts/page.tsx@@ -13,6 +13,8 @@ import {restoreArtifact,} from "@/lib/api";import Icon from "@/components/Icon";+import Button from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";import { formatRelativeTime } from "@/lib/relativeTime";type KindFilter = "all" | "draft" | "workflow";@@ -35,48 +37,16 @@ function FilterButton({return (<buttontype="button"+ aria-pressed={active}onClick={onClick}- className={`px-3 py-1.5 text-xs rounded-md ring-1 transition cursor-pointer ${+ className={`min-h-10 flex-shrink-0 rounded-lg px-3.5 text-sm font-medium transition-colors cursor-pointer ${active- ? "bg-surface-elevated ring-indigo-500/40 text-fg"- : "ring-line text-fg-muted hover:text-fg hover:ring-line-strong"+ ? "bg-accent/10 text-accent"+ : "text-fg-muted hover:text-fg hover:bg-surface-overlay"}`}>{label}- <span className="ml-1.5 text-fg-muted">{count}</span>- </button>- );-}--/** A single small icon action on a row. Reveals on hover/focus on desktop,- * always visible on touch (no hover) so the controls are never gesture-only. */-function RowAction({- icon,- label,- onClick,- disabled,- danger,-}: {- icon: "archive" | "restore" | "trash";- label: string;- onClick: () => void;- disabled: boolean;- danger?: boolean;-}) {- return (- <button- type="button"- onClick={onClick}- disabled={disabled}- aria-label={label}- title={label}- className={`min-h-8 min-w-8 flex items-center justify-center rounded-md transition cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed ${- danger- ? "text-fg-muted hover:text-red-400 hover:bg-red-500/10"- : "text-fg-muted hover:text-fg hover:bg-surface-elevated"- }`}- >- <Icon name={icon} size="w-4 h-4" />+ <span className="ml-1.5 font-normal text-fg-subtle">{count}</span></button>);}@@ -97,47 +67,36 @@ function ArtifactRow({onDelete: (item: ArtifactSummary) => void;}) {return (- <div className="group flex items-center gap-3 rounded-md px-3 py-2.5 hover:bg-surface-elevated/50 transition">+ <div className="flex items-center gap-2 py-1.5 pl-4 pr-2 hover:bg-surface-overlay/60 transition-colors"><Linkhref={`/artifacts/${encodeURIComponent(item.id)}`}- className="flex items-center gap-3 min-w-0 flex-1 rounded focus:outline-none focus:ring-2 focus:ring-indigo-500/40"+ className="flex min-h-11 min-w-0 flex-1 flex-wrap items-center gap-x-3 gap-y-0.5 rounded-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40">- <span className="text-sm font-medium text-fg truncate">{item.title}</span>+ <span className="min-w-0 truncate text-[15px] font-medium text-fg">{item.title}</span>{item.format !== "markdown" && (- <span className="flex-shrink-0 text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded border border-line text-fg-muted">+ <span className="flex-shrink-0 rounded-full border border-line px-2 py-0.5 text-xs text-fg-muted">{item.format_label}</span>)}+ <span className="ml-auto whitespace-nowrap text-sm text-fg-subtle tabular-nums">+ {formatRelativeTime(item.created_at)}+ </span></Link>- <span className="hidden sm:block text-xs text-fg-muted whitespace-nowrap tabular-nums">- {formatRelativeTime(item.created_at)}- </span>-- <div className="flex items-center gap-0.5 opacity-100 sm:opacity-0 sm:group-hover:opacity-100 sm:group-focus-within:opacity-100 transition-opacity">- {view === "active" ? (- <RowAction- icon="archive"- label="Archive"- disabled={pending}- onClick={() => onArchive(item)}- />- ) : (- <RowAction- icon="restore"- label="Restore"- disabled={pending}- onClick={() => onRestore(item)}- />- )}- <RowAction- icon="trash"- label="Delete permanently"- danger- disabled={pending}- onClick={() => onDelete(item)}- />- </div>+ <OverflowMenu+ label={`More for ${item.title}`}+ items={[+ view === "active"+ ? { label: "Archive", disabled: pending, onSelect: () => onArchive(item) }+ : { label: "Restore", disabled: pending, onSelect: () => onRestore(item) },+ {+ label: "Delete permanently",+ danger: true,+ disabled: pending,+ onSelect: () => onDelete(item),+ },+ ]}+ /></div>);}@@ -329,6 +288,14 @@ export default function ArtifactsPage() {return Array.from(map.values());}, [visible, workflowTitleMap]);+ const switchView = useCallback(+ (v: View) => {+ setView(v);+ dismissUndo();+ },+ [dismissUndo]+ );+const emptyMessage =view === "archived"? "Nothing archived. Documents you archive will collect here, ready to restore."@@ -338,51 +305,25 @@ export default function ArtifactsPage() {<div className="flex flex-col h-full bg-surface text-fg"><main className="flex-1 overflow-y-auto px-4 sm:px-6 py-8"><div className="max-w-5xl mx-auto">- <div className="mb-6">- <h1 className="text-2xl font-semibold text-fg mb-1">- Executive Documents- </h1>- <p className="text-sm text-fg-muted">- Every deliverable the Executive has produced — memos, web- pages, Word documents, spreadsheets and links into your connected- apps, alongside completed workflow outputs.- Archive what you're done with; delete clears it for good.- </p>- </div>-- {/* Active / Archived view toggle */}- <div className="inline-flex items-center gap-1 mb-4 p-0.5 rounded-lg ring-1 ring-line bg-surface/40">- {(["active", "archived"] as const).map((v) => (- <button- key={v}- type="button"- onClick={() => {- setView(v);- dismissUndo();- }}- className={`px-3 py-1.5 text-xs rounded-md transition cursor-pointer capitalize ${- view === v- ? "bg-surface-elevated text-fg"- : "text-fg-muted hover:text-fg"- }`}+ <div className="mb-6 flex flex-wrap items-end justify-between gap-4">+ <div className="min-w-0 max-w-2xl">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg mb-2">+ {view === "archived" ? "Archived documents" : "Your documents"}+ </h1>+ <p className="text-[15px] text-fg-muted">+ Every deliverable the Executive has produced — memos, web+ pages, Word documents, spreadsheets and links into your connected+ apps, alongside completed workflow outputs.+ Archive what you're done with; delete clears it for good.+ </p>+ </div>+ {/* One filter control: the kind, with Active / Archived in its ⋯. */}+ <div className="flex items-center gap-1.5">+ <div+ role="group"+ aria-label="Show"+ className="inline-flex max-w-full overflow-x-auto rounded-xl border border-line bg-surface-elevated p-1">- {v}- </button>- ))}- </div>-- {loading && (- <div className="text-sm text-fg-muted">Loading artifacts…</div>- )}- {error && <div className="text-sm text-red-400 mb-4">Error: {error}</div>}-- {!loading && !error && artifacts.length === 0 && (- <div className="text-sm text-fg-muted">{emptyMessage}</div>- )}-- {!loading && !error && artifacts.length > 0 && (- <>- <div className="flex items-center gap-1 mb-5"><FilterButtonactive={filter === "all"}onClick={() => setFilter("all")}@@ -402,34 +343,68 @@ export default function ArtifactsPage() {count={counts.workflow}/></div>+ <OverflowMenu+ label="More filters"+ items={[+ view === "active"+ ? { label: "Show archived", onSelect: () => switchView("archived") }+ : { label: "Show active documents", onSelect: () => switchView("active") },+ ]}+ />+ </div>+ </div>- <div className="space-y-5">+ {view === "archived" && (+ <div className="mb-5 flex flex-wrap items-center justify-between gap-3 rounded-xl border border-line bg-surface-elevated px-4 py-2.5 text-[15px] text-fg-muted">+ <span>Showing archived documents. Restore one from its ⋯.</span>+ <Button onClick={() => switchView("active")}>+ Back to active+ </Button>+ </div>+ )}++ {loading && (+ <div className="text-[15px] text-fg-muted">Loading documents…</div>+ )}+ {error && <div className="text-[15px] text-red-400 mb-4">Error: {error}</div>}++ {!loading && !error && artifacts.length === 0 && (+ <div className="rounded-2xl border border-dashed border-line px-5 py-8 text-center text-[15px] text-fg-muted">+ {emptyMessage}+ </div>+ )}++ {!loading && !error && artifacts.length > 0 && (+ <>+ <div className="space-y-6">{groups.map((group) => {const isCollapsed = !!collapsed[group.key];return (<div key={group.key}><buttontype="button"+ aria-expanded={!isCollapsed}onClick={() => toggleCollapsed(group.key)}- className="w-full flex items-center gap-2 mb-2 text-left"+ className="w-full min-h-10 flex items-center gap-2 mb-2 text-left"><span+ aria-hidden="true"className={`text-fg-muted text-xs transition-transform ${isCollapsed ? "" : "rotate-90"}`}>▶</span>- <span className="text-sm font-semibold text-fg">+ <span className="text-base font-semibold text-fg">{group.label}</span>- <span className="text-xs text-fg-muted">+ <span className="text-sm text-fg-muted">{group.items.length}{" "}- {group.items.length === 1 ? "artifact" : "artifacts"}+ {group.items.length === 1 ? "document" : "documents"}</span></button>{!isCollapsed && (- <div className="rounded-lg border border-line bg-surface/40 divide-y divide-line/60">+ <div className="overflow-hidden rounded-2xl border border-line bg-surface-elevated divide-y divide-line">{group.items.map((a) => (<ArtifactRowkey={a.id}@@ -454,23 +429,19 @@ export default function ArtifactsPage() {{/* Undo toast after archive */}{undo && (- <div className="fixed bottom-4 right-4 z-50 motion-safe:animate-in motion-safe:slide-in-from-right">+ <div className="fixed bottom-4 left-4 right-4 sm:left-auto z-50 flex justify-end motion-safe:animate-in motion-safe:slide-in-from-right"><div className="flex items-center gap-3 rounded-xl border border-line-strong bg-surface-overlay backdrop-blur shadow-xl shadow-black/40 px-4 py-3">- <span className="text-sm text-fg">+ <span className="min-w-0 truncate text-[15px] text-fg">Archived <span className="font-medium">{undo.item.title}</span></span>- <button- type="button"- onClick={handleUndo}- className="text-sm font-medium text-indigo-400 hover:text-indigo-300 cursor-pointer"- >+ <Button variant="primary" onClick={handleUndo}>Undo- </button>+ </Button><buttontype="button"onClick={dismissUndo}aria-label="Dismiss"- className="min-h-8 min-w-8 -mr-1 flex items-center justify-center rounded text-fg-muted hover:text-fg cursor-pointer"+ className="h-9 w-9 -mr-1 flex flex-shrink-0 items-center justify-center rounded-lg text-fg-muted hover:text-fg hover:bg-surface-hover cursor-pointer"><Icon name="close" size="w-3.5 h-3.5" /></button>diff --git a/packages/ui/src/app/audit/page.tsx b/packages/ui/src/app/audit/page.tsxindex fb1ca3f6..b3e29d05 100644--- a/packages/ui/src/app/audit/page.tsx+++ b/packages/ui/src/app/audit/page.tsx@@ -11,6 +11,8 @@ import {type AuditEventDetail,type AuditQuery,} from "@/lib/api";+import Icon from "@/components/Icon";+import { buttonClass } from "@/components/ui/Button";const PAGE_SIZE = 100;@@ -446,6 +448,24 @@ function AuditPageInner() {<div className="flex flex-col h-full bg-surface text-fg"><main className="flex-1 overflow-y-auto"><div className="max-w-6xl mx-auto px-4 sm:px-6 py-6">+ <Link+ href="/settings/advanced"+ className="-ml-2 inline-flex min-h-touch items-center gap-1.5 rounded-lg px-2 text-[15px] text-fg-muted hover:text-fg hover:bg-surface-overlay transition-colors"+ >+ <Icon name="arrow-left" size="w-4 h-4" />+ Settings+ </Link>+ <div className="mt-2 mb-5 flex flex-wrap items-end justify-between gap-x-4 gap-y-2">+ <div className="min-w-0">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg">Audit log</h1>+ <p className="mt-1 text-[15px] text-fg-muted">+ Every chat turn, specialist consult, tool call and scheduled action, newest first.+ </p>+ </div>+ <Link href="/audit/usage" className={buttonClass("secondary", "sm")}>+ Token usage+ </Link>+ </div><div className="grid grid-cols-1 md:grid-cols-5 gap-3 mb-4"><inputtype="search"diff --git a/packages/ui/src/app/audit/session/[id]/page.tsx b/packages/ui/src/app/audit/session/[id]/page.tsxindex 83e18e72..ec96c77b 100644--- a/packages/ui/src/app/audit/session/[id]/page.tsx+++ b/packages/ui/src/app/audit/session/[id]/page.tsx@@ -3,6 +3,7 @@import "@xyflow/react/dist/style.css";import Dagre from "@dagrejs/dagre";+import Link from "next/link";import { useParams } from "next/navigation";import { useCallback, useEffect, useMemo, useState } from "react";import {@@ -18,6 +19,7 @@ import {ReactFlow,} from "@xyflow/react";+import Icon from "@/components/Icon";import {getAuditLog,getAuditSession,@@ -837,6 +839,22 @@ export default function AuditSessionPage() {return (<div className="flex flex-col h-full bg-surface text-fg">+ {/* Title row: the way back to the log, and which session this is. */}+ <div className="flex-shrink-0 border-b border-line px-4 sm:px-6 py-3 flex flex-wrap items-center gap-x-4 gap-y-1">+ <Link+ href="/audit"+ className="-ml-2 inline-flex min-h-touch items-center gap-1.5 rounded-lg px-2 text-[15px] text-fg-muted hover:text-fg hover:bg-surface-overlay transition-colors"+ >+ <Icon name="arrow-left" size="w-4 h-4" />+ Audit log+ </Link>+ <h1 className="min-w-0 text-xl sm:text-2xl font-bold tracking-tight text-fg">Session flow</h1>+ {sessionId && (+ <span className="min-w-0 truncate font-mono text-xs text-fg-subtle" title={sessionId}>+ {sessionId}+ </span>+ )}+ </div><main className="flex-1 min-h-0 flex">{loading && (<div className="flex-1 flex items-center justify-center text-fg-muted">diff --git a/packages/ui/src/app/chats/page.tsx b/packages/ui/src/app/chats/page.tsxindex 5e1812b9..922252b4 100644--- a/packages/ui/src/app/chats/page.tsx+++ b/packages/ui/src/app/chats/page.tsx@@ -2,7 +2,9 @@import { useEffect, useMemo, useState } from "react";import { useRouter } from "next/navigation";+import Link from "next/link";import Icon from "@/components/Icon";+import { buttonClass } from "@/components/ui/Button";import ChatHistory from "@/components/sessions/ChatHistory";import { useSessions } from "@/components/sessions/SessionsContext";import {@@ -15,9 +17,9 @@ import {type ChannelFilter = SessionChannel | "all";-// Full conversation history. The sidebar only lists the latest few web chats;-// this page holds everything, including conversations that arrived through-// Slack, Telegram and Discord.+// Full conversation history: every chat, including conversations that+// arrived through Slack, Telegram and Discord. Each row opens its chat;+// Delete is in the row's ⋯ menu and asks first.export default function ChatsPage() {const router = useRouter();const { sessions, loaded, error, refresh, remove } = useSessions();@@ -53,19 +55,26 @@ export default function ChatsPage() {<div className="flex flex-col h-full bg-surface text-fg"><main className="flex-1 overflow-y-auto px-4 sm:px-6 py-8"><div className="max-w-3xl mx-auto">- <div className="mb-6">- <h1 className="text-2xl font-semibold text-fg mb-1">Chats</h1>- <p className="text-sm text-fg-muted">- Every conversation with the Executive, from the web app and from connected- channels. The sidebar shows only your latest web chats.- </p>+ <div className="mb-6 flex items-start justify-between gap-4">+ <div className="min-w-0">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg mb-1">Chats</h1>+ <p className="text-[15px] text-fg-muted">+ Every conversation with the Executive, from the web app and from connected+ channels.+ </p>+ </div>+ <Link href="/?new=1" className={buttonClass("primary", "md", "flex-shrink-0")}>+ <Icon name="plus" size="w-4 h-4" />+ <span className="hidden sm:inline">New chat</span>+ <span className="sm:hidden">New</span>+ </Link></div><div className="flex flex-col sm:flex-row sm:items-center gap-3 mb-5"><divrole="tablist"aria-label="Filter by channel"- className="inline-flex flex-wrap items-center gap-1 p-0.5 rounded-lg ring-1 ring-line bg-surface/40"+ className="inline-flex flex-wrap items-center gap-1 p-1 rounded-xl ring-1 ring-line bg-surface-elevated">{tabs.map((t) => {const active = activeChannel === t;@@ -77,8 +86,8 @@ export default function ChatsPage() {role="tab"aria-selected={active}onClick={() => setChannel(t)}- className={`px-3 py-1.5 text-xs rounded-md transition cursor-pointer ${- active ? "bg-surface-elevated text-fg" : "text-fg-muted hover:text-fg"+ className={`min-h-[40px] px-4 text-[15px] font-medium rounded-lg transition cursor-pointer ${+ active ? "bg-accent/10 text-accent" : "text-fg-muted hover:text-fg hover:bg-surface-overlay"}`}>{t === "all" ? "All" : CHANNEL_LABELS[t]}@@ -87,11 +96,11 @@ export default function ChatsPage() {);})}</div>- <div className="relative sm:ml-auto sm:w-64">+ <div className="relative sm:ml-auto sm:w-72"><Iconname="search"- size="w-3.5 h-3.5"- className="absolute left-2.5 top-1/2 -translate-y-1/2 text-fg-subtle pointer-events-none"+ size="w-4 h-4"+ className="absolute left-3.5 top-1/2 -translate-y-1/2 text-fg-subtle pointer-events-none"/><inputtype="text"@@ -99,15 +108,15 @@ export default function ChatsPage() {onChange={(e) => setQuery(e.target.value)}placeholder="Search conversations"aria-label="Search conversations"- className="w-full rounded-lg bg-surface-input/60 border border-line pl-8 pr-2 py-2 text-sm text-fg placeholder:text-fg-subtle focus:outline-none focus:border-fg-subtle"+ className="w-full h-11 rounded-xl bg-surface-elevated border border-line pl-10 pr-3 text-[15px] text-fg placeholder:text-fg-subtle focus:outline-none focus:border-accent/60 focus:ring-2 focus:ring-accent/20"/></div></div>{!loaded ? (- <p className="px-3 py-6 text-sm text-fg-muted">Loading conversations…</p>+ <p className="px-1 py-6 text-[15px] text-fg-muted">Loading conversations…</p>) : error && sessions.length === 0 ? (- <p className="px-3 py-6 text-sm text-fg-muted">+ <p className="px-1 py-6 text-[15px] text-fg-muted">Couldn't load your conversations.{" "}<buttontype="button"@@ -118,7 +127,7 @@ export default function ChatsPage() {</button></p>) : sessions.length === 0 ? (- <p className="px-3 py-6 text-sm text-fg-muted">+ <p className="px-1 py-6 text-[15px] text-fg-muted">No conversations yet. Start one with New chat.</p>) : (@@ -126,7 +135,7 @@ export default function ChatsPage() {sessions={visible}searching={searching}onSelect={(id) => router.push(`/?session=${encodeURIComponent(id)}`)}- onDelete={(id) => void remove(id)}+ onDelete={remove}/>)}</div>diff --git a/packages/ui/src/app/clients/page.tsx b/packages/ui/src/app/clients/page.tsxindex 716067cd..04ba3bbb 100644--- a/packages/ui/src/app/clients/page.tsx+++ b/packages/ui/src/app/clients/page.tsx@@ -1,10 +1,13 @@"use client";-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useId, useState } from "react";import Link from "next/link";-import Icon from "@/components/Icon";+import Button, { buttonClass } from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";+import SectionTabs, { sectionPanelProps } from "@/components/ui/SectionTabs";+import SidePanel from "@/components/ui/SidePanel";import {activateClient,type ClientCockpitCard,@@ -26,6 +29,12 @@ import { clientCountsSummary, renewalBadge } from "@/lib/practice";// live at a time; switching saves the current client back to its slot and// restores the target. Single-company installs see only the intro + create// form — nothing about the default experience changes until a client exists.++const INPUT_CLS =+ "w-full px-3 rounded-xl bg-surface-input/60 border border-line text-[15px] text-fg placeholder-fg-subtle focus:outline-none focus:border-accent";+const FIELD_CLS = `${INPUT_CLS} h-11`;+const LABEL_CLS = "text-sm text-fg-muted flex flex-col gap-1.5";+// base64url-encode a prefill payload for the /jobs/{name} runner page// (mirrors decodePrefill there).function encodePrefill(payload: Record<string, string>): string {@@ -48,7 +57,10 @@ export default function ClientsPage() {const [name, setName] = useState("");const [source, setSource] = useState<"current" | "blank">("current");const [creating, setCreating] = useState(false);- const [confirmDelete, setConfirmDelete] = useState<string | null>(null);+ // The "New client" panel and which of its two ways is showing.+ const [createOpen, setCreateOpen] = useState(false);+ const [createWay, setCreateWay] = useState<"company" | "notes">("company");+ const createTabsId = useId();// Engagement-intake (AI draft) flow.const [notes, setNotes] = useState("");@@ -106,6 +118,7 @@ export default function ClientsPage() {kind: "success",});setName("");+ setCreateOpen(false);await refresh();} catch (e: unknown) {setToast({ message: e instanceof Error ? e.message : "Create failed", kind: "error" });@@ -181,6 +194,7 @@ export default function ClientsPage() {setDraft(null);setNotes("");setAttachments([]);+ setCreateOpen(false);await refresh();} catch (e: unknown) {setToast({ message: e instanceof Error ? e.message : "Create failed", kind: "error" });@@ -225,7 +239,6 @@ export default function ClientsPage() {try {await deleteClient(slug);setToast({ message: `Deleted ${slug}.`, kind: "success" });- setConfirmDelete(null);await refresh();} catch (e: unknown) {setToast({ message: e instanceof Error ? e.message : "Delete failed", kind: "error" });@@ -234,23 +247,34 @@ export default function ClientsPage() {}}+ const editingClient = status.clients.find((c) => c.slug === editingSlug) ?? null;+ const fixtureActive = !!status.fixture_active;+return (<main className="flex-1 min-h-0 overflow-y-auto">- <div className="max-w-3xl mx-auto px-4 sm:px-6 py-8">- <h1 className="text-xl font-semibold text-fg">Client companies</h1>- <p className="mt-1 text-sm text-fg-muted">- Run several client companies from one Open Executive — one active at a- time. Switching saves the current client's full state (chat,- schedule, documents, MCP tools) to its slot and- restores the target.- </p>+ <div className="max-w-4xl mx-auto px-4 sm:px-6 py-8">+ <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">+ <div className="min-w-0">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg">Client companies</h1>+ <p className="mt-2 text-[15px] text-fg-muted">+ Run several client companies from one Open Executive — one active at a+ time. Switching saves the current client's full state (chat,+ schedule, documents, MCP tools) to its slot and+ restores the target.+ </p>+ </div>+ <Button variant="primary" onClick={() => setCreateOpen(true)} className="flex-shrink-0 self-start">+ New client+ </Button>+ </div>{toast && (<div- className={`mt-4 rounded-lg border px-3 py-2 text-sm ${+ role="status"+ className={`mt-5 rounded-xl border px-4 py-3 text-[15px] ${toast.kind === "success"? "border-line bg-surface-elevated text-fg"- : "border-red-500/40 bg-red-500/10 text-red-400"+ : "border-red-500/40 bg-red-500/10 text-red-500"}`}>{toast.message}@@ -258,14 +282,14 @@ export default function ClientsPage() {)}{status.rotation_in_progress && (- <div className="mt-4 rounded-lg border border-line bg-surface-elevated px-3 py-2 text-sm text-fg-muted">+ <div className="mt-5 rounded-xl border border-line bg-surface-elevated px-4 py-3 text-[15px] text-fg-muted">Overnight rotation is running — the active client will switchbriefly while parked clients are refreshed, then return.</div>)}{status.fixture_active && (- <div className="mt-4 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm text-amber-400">+ <div className="mt-5 rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-[15px] text-amber-700 dark:text-amber-400">Demo fixture <strong>{status.fixture_active}</strong> is active —unload it on the Company Simulator page before working with clients.</div>@@ -273,29 +297,29 @@ export default function ClientsPage() {{/* Practice cockpit — only in multi-client mode (2+ slots) */}{cockpit.length >= 2 && (- <div className="mt-6 rounded-xl border border-line bg-surface-elevated p-4">- <h2 className="text-sm font-medium text-fg">Practice cockpit</h2>- <p className="mt-1 text-xs text-fg-muted">+ <section className="mt-8">+ <h2 className="text-lg font-semibold text-fg">Practice cockpit</h2>+ <p className="mt-1 text-[15px] text-fg-muted">All clients at a glance. Parked clients show their state as of thelast save point.</p>- <div className="mt-3 grid gap-2 sm:grid-cols-2">+ <div className="mt-4 grid gap-3 sm:grid-cols-2">{cockpit.map((c) => (<divkey={`cockpit-${c.slug}`}- className={`rounded-lg border p-3 ${- c.is_active ? "border-line-strong bg-surface-overlay" : "border-line"+ className={`rounded-2xl border p-4 ${+ c.is_active ? "border-line-strong bg-surface-overlay" : "border-line bg-surface-elevated"}`}><div className="flex items-center justify-between gap-2">- <div className="text-xs font-medium text-fg truncate">+ <div className="text-[15px] font-semibold text-fg truncate">{c.display_name}{c.role ? (<span className="text-fg-muted font-normal"> · {c.role}</span>) : null}</div>{c.is_active ? (- <span className="text-[10px] px-1.5 py-0.5 rounded-full border border-emerald-500/40 bg-emerald-500/10 text-emerald-400 flex-shrink-0">+ <span className="text-xs font-medium px-2 py-0.5 rounded-full border border-emerald-500/40 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 flex-shrink-0">active</span>) : (@@ -303,10 +327,10 @@ export default function ClientsPage() {const badge = renewalBadge(c.days_to_renewal);return badge ? (<span- className={`text-[10px] px-1.5 py-0.5 rounded-full border flex-shrink-0 ${+ className={`text-xs font-medium px-2 py-0.5 rounded-full border flex-shrink-0 ${badge.urgent- ? "border-red-500/40 bg-red-500/10 text-red-400"- : "border-amber-500/40 bg-amber-500/10 text-amber-400"+ ? "border-red-500/40 bg-red-500/10 text-red-500"+ : "border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-400"}`}>{badge.label}@@ -315,227 +339,69 @@ export default function ClientsPage() {})())}</div>- <div className="mt-1 text-[11px] text-fg-muted">+ <div className="mt-1.5 text-sm text-fg-muted">{clientCountsSummary(c)}</div>{c.has_state && (- <div className="mt-1.5">+ <div className="mt-3"><Linkhref={`/jobs/engagement_value_report?prefill=${encodePrefill({ client_slug: c.slug })}`}- className="text-[11px] text-indigo-400 hover:text-indigo-300"+ className={buttonClass("secondary", "sm")}>- Value report →+ Value report</Link></div>)}</div>))}</div>- </div>+ </section>)}- {/* Create */}- <div className="mt-6 rounded-xl border border-line bg-surface-elevated p-4">- <h2 className="text-sm font-medium text-fg">New client</h2>- <div className="mt-3 flex flex-col sm:flex-row gap-2">- <input- value={name}- onChange={(e) => setName(e.target.value)}- placeholder="Client company name"- className="flex-1 rounded-lg border border-line bg-surface px-3 py-2 text-sm text-fg placeholder:text-fg-muted focus:outline-none focus:border-line-strong"- />- <select- value={source}- onChange={(e) => setSource(e.target.value as "current" | "blank")}- className="rounded-lg border border-line bg-surface px-3 py-2 text-sm text-fg focus:outline-none"- >- <option value="current">From current company</option>- <option value="blank">Blank (onboard fresh)</option>- </select>- <button- onClick={() => void handleCreate()}- disabled={creating || !name.trim() || !!status.fixture_active}- className="rounded-lg border border-line bg-surface-overlay px-4 py-2 text-sm font-medium text-fg hover:border-line-strong disabled:opacity-50"- >- {creating ? "Creating…" : "Create"}- </button>- </div>- <p className="mt-2 text-xs text-fg-muted">- {source === "current"- ? "Captures the live company into the new client slot and makes it the active client."- : "Creates an empty client. Activate it, then run company onboarding and upload its documents."}- </p>- </div>-- {/* New engagement from intake notes (AI) */}- <div className="mt-4 rounded-xl border border-line bg-surface-elevated p-4">- <h2 className="text-sm font-medium text-fg">New client from intake notes</h2>- <p className="mt-1 text-xs text-fg-muted">- Paste real intake material — call notes, a brief, website copy — or- attach PDFs, Word, Excel, or CSV files, and the AI drafts the- client's profile, org, starter documents, and known history.- Attachments are also saved as company documents. It extracts only- what the material says: unknowns stay blank and become open- questions, and no contact details are ever imported.- </p>-- {!draft ? (- <>- <textarea- value={notes}- onChange={(e) => setNotes(e.target.value)}- rows={5}- placeholder="e.g. Notes from the kickoff call with Meridian Solar: 80-person commercial solar installer in Texas, CEO Dana Reyes, struggling with project-margin visibility…"- className="mt-3 w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm text-fg placeholder:text-fg-muted focus:outline-none focus:border-line-strong"- />-- <div className="mt-2 flex flex-wrap items-center gap-2">- <label className="cursor-pointer rounded-lg border border-line bg-surface-overlay px-3 py-1.5 text-xs font-medium text-fg hover:border-line-strong">- Attach files- <input- type="file"- multiple- accept=".pdf,.docx,.doc,.xlsx,.xlsm,.csv,.md,.txt"- className="hidden"- onChange={(e) => {- const picked = Array.from(e.target.files ?? []);- if (picked.length) setAttachments((prev) => [...prev, ...picked]);- e.target.value = "";- }}- />- </label>- <span className="text-xs text-fg-muted">- PDF, Word, Excel, CSV, or text- </span>- </div>-- {attachments.length > 0 && (- <ul className="mt-2 flex flex-col gap-1">- {attachments.map((f, i) => (- <li- key={`${f.name}-${i}`}- className="flex items-center justify-between gap-2 rounded-lg border border-line bg-surface px-3 py-1.5 text-xs text-fg"- >- <span className="truncate">{f.name}</span>- <button- type="button"- onClick={() =>- setAttachments((prev) => prev.filter((_, j) => j !== i))- }- aria-label={`Remove ${f.name}`}- className="shrink-0 text-fg-muted hover:text-fg"- >- ×- </button>- </li>- ))}- </ul>- )}-- <button- onClick={() => void handleGenerateDraft()}- disabled={- generating ||- (!notes.trim() && attachments.length === 0) ||- !!status.fixture_active- }- className="mt-2 rounded-lg border border-line bg-surface-overlay px-4 py-2 text-sm font-medium text-fg hover:border-line-strong disabled:opacity-50"- >- {generating ? "Drafting…" : "Draft client"}- </button>- </>- ) : (- <div className="mt-3">- <div className="flex flex-col sm:flex-row gap-2 sm:items-center">- <input- value={draftName}- onChange={(e) => setDraftName(e.target.value)}- className="flex-1 rounded-lg border border-line bg-surface px-3 py-2 text-sm text-fg focus:outline-none focus:border-line-strong"- />- <span className="text-xs text-fg-muted">- {draft.bundle.people.length} people · {draft.bundle.departments.length} departments · {draft.bundle.docs.length} docs- </span>- </div>- {draft.bundle.people.length > 0 && (- <p className="mt-2 text-xs text-fg-muted">- Roster:{" "}- {draft.bundle.people- .map((p) => `${p.full_name}${p.is_principal ? " (principal)" : ""}`)- .join(", ")}- </p>- )}- {draft.bundle.docs.length > 0 && (- <p className="mt-1 text-xs text-fg-muted">- Docs: {draft.bundle.docs.map((d) => d.filename).join(", ")}- </p>- )}- <div className="mt-3 flex flex-wrap gap-2">- <button- onClick={() => void handleCreateFromDraft(false)}- disabled={creatingDraft || !draftName.trim()}- className="rounded-lg border border-line bg-surface-overlay px-4 py-2 text-sm font-medium text-fg hover:border-line-strong disabled:opacity-50"- >- {creatingDraft ? "Creating…" : "Create client"}- </button>- <button- onClick={() => void handleCreateFromDraft(true)}- disabled={creatingDraft || !draftName.trim()}- className="rounded-lg border border-line bg-surface-overlay px-4 py-2 text-sm font-medium text-fg hover:border-line-strong disabled:opacity-50"- >- {creatingDraft ? "Creating…" : "Create & activate"}- </button>- <button- onClick={() => setDraft(null)}- disabled={creatingDraft}- className="rounded-lg border border-line px-4 py-2 text-sm text-fg-muted hover:border-line-strong disabled:opacity-50"- >- ← Edit notes- </button>- </div>- </div>- )}- </div>-{/* List */}{loading ? (- <p className="mt-6 text-sm text-fg-muted">Loading clients…</p>+ <p className="mt-8 text-[15px] text-fg-muted">Loading clients…</p>) : status.clients.length === 0 ? (- <p className="mt-6 text-sm text-fg-muted">- No clients yet. Create one from your current company to enter- multi-client mode — single-company use is unaffected until you do.- </p>+ <div className="mt-8 rounded-2xl border border-line bg-surface-elevated p-8 text-center">+ <p className="text-[15px] text-fg-muted">+ No clients yet. Create one from your current company to enter+ multi-client mode — single-company use is unaffected until you do.+ </p>+ </div>) : (- <div className="mt-6 space-y-3">+ <section className="mt-8">+ {cockpit.length >= 2 && <h2 className="text-lg font-semibold text-fg mb-3">All clients</h2>}+ <div className="space-y-3">{status.clients.map((c) => {const isActive = c.slug === status.active;const busy = busySlug === c.slug;return (<divkey={c.slug}- className={`rounded-xl border p-4 ${+ className={`rounded-2xl border p-5 ${isActive? "border-line-strong bg-surface-overlay": "border-line bg-surface-elevated"}`}>- <div className="flex items-center justify-between gap-3">- <div className="min-w-0">- <div className="flex items-center gap-2">- <h3 className="text-sm font-medium text-fg truncate">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <h3 className="text-base font-semibold text-fg truncate">{c.display_name}</h3>{isActive && (- <span className="text-[10px] font-medium px-2 py-0.5 rounded-full border border-emerald-500/40 bg-emerald-500/10 text-emerald-400">+ <span className="text-xs font-medium px-2 py-0.5 rounded-full border border-emerald-500/40 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400">active</span>)}{c.has_mcp_config && (- <span className="text-[10px] font-medium px-2 py-0.5 rounded-full border border-line text-fg-muted">+ <span className="text-xs font-medium px-2 py-0.5 rounded-full border border-line text-fg-muted">MCP tools</span>)}</div>- <p className="mt-1 text-xs text-fg-muted">+ <p className="mt-1 text-sm text-fg-muted">{[c.role, c.status, c.industry, c.stage].filter(Boolean).join(" · ") || c.slug}@@ -546,135 +412,345 @@ export default function ClientsPage() {: " · never saved"}</p></div>- <div className="flex items-center gap-2 shrink-0">+ <div className="flex items-center gap-1.5 shrink-0">{isActive ? (- <button+ <ButtononClick={() => void handleSave()}- disabled={busy || !!status.fixture_active}- className="rounded-lg border border-line px-3 py-1.5 text-xs font-medium text-fg hover:border-line-strong disabled:opacity-50"+ disabled={busy || fixtureActive}>{busy ? "Saving…" : "Save now"}- </button>+ </Button>) : (- <>- <button- onClick={() => void handleActivate(c.slug)}- disabled={busy || !!status.fixture_active}- className="rounded-lg border border-line bg-surface-overlay px-3 py-1.5 text-xs font-medium text-fg hover:border-line-strong disabled:opacity-50"- >- {busy ? "Switching…" : "Activate"}- </button>- {confirmDelete === c.slug ? (- <button- onClick={() => void handleDelete(c.slug)}- disabled={busy}- className="rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-1.5 text-xs font-medium text-red-400 disabled:opacity-50"- >- Confirm delete- </button>- ) : (- <button- onClick={() => setConfirmDelete(c.slug)}- disabled={busy}- aria-label={`Delete ${c.display_name}`}- className="rounded-lg border border-line px-2 py-1.5 text-xs text-fg-muted hover:border-line-strong disabled:opacity-50"- >- <Icon name="trash" size="w-3.5 h-3.5" />- </button>- )}- </>+ <Button+ variant="primary"+ onClick={() => void handleActivate(c.slug)}+ disabled={busy || fixtureActive}+ >+ {busy ? "Switching…" : "Activate"}+ </Button>)}+ <OverflowMenu+ label={`More actions for ${c.display_name}`}+ items={[+ { label: "Engagement details", onSelect: () => openMetaEditor(c.slug) },+ ...(isActive+ ? []+ : [{+ label: "Delete client",+ danger: true,+ disabled: busy,+ onSelect: () => {+ if (window.confirm(`Delete ${c.display_name}? Its saved slot is removed and this cannot be undone.`)) {+ void handleDelete(c.slug);+ }+ },+ }]),+ ]}+ /></div></div>- <div className="mt-2">- {editingSlug === c.slug ? (- <div className="rounded-lg border border-line bg-surface p-3 grid gap-2 sm:grid-cols-2">- <input- value={metaForm.role ?? ""}- onChange={(e) => setMetaForm({ ...metaForm, role: e.target.value })}- placeholder="Your role (e.g. Fractional CFO)"- className="rounded border border-line bg-surface-elevated px-2 py-1.5 text-xs text-fg placeholder:text-fg-muted focus:outline-none"- />- <select- value={metaForm.status ?? "active"}- onChange={(e) => setMetaForm({ ...metaForm, status: e.target.value })}- className="rounded border border-line bg-surface-elevated px-2 py-1.5 text-xs text-fg focus:outline-none"- >- <option value="active">active</option>- <option value="paused">paused</option>- <option value="winding_down">winding down</option>- <option value="completed">completed</option>- </select>- <label className="text-[11px] text-fg-muted flex items-center gap-2">- Renewal- <input- type="date"- value={metaForm.renewal_date ?? ""}- onChange={(e) =>- setMetaForm({ ...metaForm, renewal_date: e.target.value })- }- className="flex-1 rounded border border-line bg-surface-elevated px-2 py-1.5 text-xs text-fg focus:outline-none"- />- </label>- <input- value={metaForm.retainer ?? ""}- onChange={(e) => setMetaForm({ ...metaForm, retainer: e.target.value })}- placeholder="Retainer (display only)"- className="rounded border border-line bg-surface-elevated px-2 py-1.5 text-xs text-fg placeholder:text-fg-muted focus:outline-none"- />- <input- value={metaForm.primary_contact ?? ""}- onChange={(e) =>- setMetaForm({ ...metaForm, primary_contact: e.target.value })- }- placeholder="Primary contact"- className="rounded border border-line bg-surface-elevated px-2 py-1.5 text-xs text-fg placeholder:text-fg-muted focus:outline-none"- />- <input- value={metaForm.notes ?? ""}- onChange={(e) => setMetaForm({ ...metaForm, notes: e.target.value })}- placeholder="Notes"- className="rounded border border-line bg-surface-elevated px-2 py-1.5 text-xs text-fg placeholder:text-fg-muted focus:outline-none"- />- <div className="sm:col-span-2 flex gap-2">- <button- onClick={() => void handleSaveMeta()}- disabled={savingMeta}- className="rounded-lg border border-line bg-surface-overlay px-3 py-1.5 text-xs font-medium text-fg hover:border-line-strong disabled:opacity-50"- >- {savingMeta ? "Saving…" : "Save details"}- </button>- <button- onClick={() => setEditingSlug(null)}- disabled={savingMeta}- className="rounded-lg border border-line px-3 py-1.5 text-xs text-fg-muted hover:border-line-strong"- >- Cancel- </button>- </div>- </div>- ) : (- <button- onClick={() => openMetaEditor(c.slug)}- className="text-[11px] text-indigo-400 hover:text-indigo-300"- >- Engagement details- </button>- )}- </div></div>);})}- </div>+ </div>+ </section>)}- <p className="mt-8 text-xs text-fg-muted leading-relaxed">+ <p className="mt-8 text-sm text-fg-muted leading-relaxed">Only the active client is live — its scheduled actions fire and itsdocuments are indexed; parked clients sleep in their slots. Youroriginal company is preserved automatically the first time youswitch, and can be restored from the Company Simulator page.</p></div>++ {/* New client: from a company, or drafted from intake notes */}+ <SidePanel+ open={createOpen}+ onClose={() => {+ if (!creating && !generating && !creatingDraft) setCreateOpen(false);+ }}+ title="New client"+ width="lg"+ >+ {toast?.kind === "error" && (+ <div role="alert" className="mb-4 rounded-xl border border-red-500/40 bg-red-500/10 px-4 py-3 text-[15px] text-red-500">+ {toast.message}+ </div>+ )}+ <div className="mb-5">+ <SectionTabs+ idBase={createTabsId}+ label="How to create the client"+ tabs={[+ { id: "company", label: "From a company" },+ { id: "notes", label: "From intake notes" },+ ]}+ active={createWay}+ onChange={setCreateWay}+ />+ </div>+ <div {...sectionPanelProps(createTabsId, createWay)}>+ {createWay === "company" ? (+ <div className="space-y-4">+ <label className={LABEL_CLS}>+ Client company name+ <input+ value={name}+ onChange={(e) => setName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && name.trim() && !creating && !fixtureActive) void handleCreate();+ }}+ placeholder="Client company name"+ className={FIELD_CLS}+ />+ </label>+ <label className={LABEL_CLS}>+ Start from+ <select+ value={source}+ onChange={(e) => setSource(e.target.value as "current" | "blank")}+ className={FIELD_CLS}+ >+ <option value="current">From current company</option>+ <option value="blank">Blank (onboard fresh)</option>+ </select>+ </label>+ <p className="text-sm text-fg-muted">+ {source === "current"+ ? "Captures the live company into the new client slot and makes it the active client."+ : "Creates an empty client. Activate it, then run company onboarding and upload its documents."}+ </p>+ <Button+ variant="primary"+ onClick={() => void handleCreate()}+ disabled={creating || !name.trim() || fixtureActive}+ >+ {creating ? "Creating…" : "Create"}+ </Button>+ </div>+ ) : (+ <div>+ <p className="text-[15px] text-fg-muted">+ Paste real intake material — call notes, a brief, website copy — or+ attach PDFs, Word, Excel, or CSV files, and the AI drafts the+ client's profile, org, starter documents, and known history.+ Attachments are also saved as company documents. It extracts only+ what the material says: unknowns stay blank and become open+ questions, and no contact details are ever imported.+ </p>++ {!draft ? (+ <>+ <textarea+ value={notes}+ onChange={(e) => setNotes(e.target.value)}+ rows={7}+ aria-label="Intake notes"+ placeholder="e.g. Notes from the kickoff call with Meridian Solar: 80-person commercial solar installer in Texas, CEO Dana Reyes, struggling with project-margin visibility…"+ className={`mt-4 ${INPUT_CLS} py-2.5`}+ />++ <div className="mt-3 flex flex-wrap items-center gap-3">+ <label className={`${buttonClass("secondary", "md")} cursor-pointer focus-within:ring-2 focus-within:ring-accent/60`}>+ Attach files+ <input+ type="file"+ multiple+ accept=".pdf,.docx,.doc,.xlsx,.xlsm,.csv,.md,.txt"+ className="sr-only"+ onChange={(e) => {+ const picked = Array.from(e.target.files ?? []);+ if (picked.length) setAttachments((prev) => [...prev, ...picked]);+ e.target.value = "";+ }}+ />+ </label>+ <span className="text-sm text-fg-muted">+ PDF, Word, Excel, CSV, or text+ </span>+ </div>++ {attachments.length > 0 && (+ <ul className="mt-3 flex flex-col gap-1.5">+ {attachments.map((f, i) => (+ <li+ key={`${f.name}-${i}`}+ className="flex items-center justify-between gap-2 rounded-xl border border-line bg-surface pl-4 pr-1 py-1 text-sm text-fg"+ >+ <span className="truncate">{f.name}</span>+ <button+ type="button"+ onClick={() =>+ setAttachments((prev) => prev.filter((_, j) => j !== i))+ }+ aria-label={`Remove ${f.name}`}+ className="shrink-0 inline-flex h-10 w-10 items-center justify-center rounded-lg text-lg text-fg-muted hover:text-fg hover:bg-surface-overlay"+ >+ ×+ </button>+ </li>+ ))}+ </ul>+ )}++ <Button+ variant="primary"+ onClick={() => void handleGenerateDraft()}+ disabled={+ generating ||+ (!notes.trim() && attachments.length === 0) ||+ fixtureActive+ }+ className="mt-4"+ >+ {generating ? "Drafting…" : "Draft client"}+ </Button>+ </>+ ) : (+ <div className="mt-4">+ <label className={LABEL_CLS}>+ Client name+ <input+ value={draftName}+ onChange={(e) => setDraftName(e.target.value)}+ className={FIELD_CLS}+ />+ </label>+ <p className="mt-2 text-sm text-fg-muted">+ {draft.bundle.people.length} people · {draft.bundle.departments.length} departments · {draft.bundle.docs.length} docs+ </p>+ {draft.bundle.people.length > 0 && (+ <p className="mt-2 text-sm text-fg-muted">+ Roster:{" "}+ {draft.bundle.people+ .map((p) => `${p.full_name}${p.is_principal ? " (principal)" : ""}`)+ .join(", ")}+ </p>+ )}+ {draft.bundle.docs.length > 0 && (+ <p className="mt-1 text-sm text-fg-muted">+ Docs: {draft.bundle.docs.map((d) => d.filename).join(", ")}+ </p>+ )}+ <div className="mt-4 flex flex-wrap gap-2">+ <Button+ variant="primary"+ onClick={() => void handleCreateFromDraft(true)}+ disabled={creatingDraft || !draftName.trim()}+ >+ {creatingDraft ? "Creating…" : "Create & activate"}+ </Button>+ <Button+ onClick={() => void handleCreateFromDraft(false)}+ disabled={creatingDraft || !draftName.trim()}+ >+ {creatingDraft ? "Creating…" : "Create client"}+ </Button>+ <Button+ variant="ghost"+ onClick={() => setDraft(null)}+ disabled={creatingDraft}+ >+ ← Edit notes+ </Button>+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ </SidePanel>++ {/* Engagement details for one client */}+ <SidePanel+ open={editingClient !== null}+ onClose={() => {+ if (!savingMeta) setEditingSlug(null);+ }}+ title="Engagement details"+ subtitle={editingClient?.display_name}+ footer={+ <div className="flex gap-2">+ <Button variant="primary" onClick={() => void handleSaveMeta()} disabled={savingMeta} className="flex-1 sm:flex-none">+ {savingMeta ? "Saving…" : "Save details"}+ </Button>+ <Button onClick={() => setEditingSlug(null)} disabled={savingMeta}>+ Cancel+ </Button>+ </div>+ }+ >+ {toast?.kind === "error" && (+ <div role="alert" className="mb-4 rounded-xl border border-red-500/40 bg-red-500/10 px-4 py-3 text-[15px] text-red-500">+ {toast.message}+ </div>+ )}+ <div className="space-y-4">+ <label className={LABEL_CLS}>+ Your role+ <input+ value={metaForm.role ?? ""}+ onChange={(e) => setMetaForm({ ...metaForm, role: e.target.value })}+ placeholder="Your role (e.g. Fractional CFO)"+ className={FIELD_CLS}+ />+ </label>+ <label className={LABEL_CLS}>+ Status+ <select+ value={metaForm.status ?? "active"}+ onChange={(e) => setMetaForm({ ...metaForm, status: e.target.value })}+ className={FIELD_CLS}+ >+ <option value="active">active</option>+ <option value="paused">paused</option>+ <option value="winding_down">winding down</option>+ <option value="completed">completed</option>+ </select>+ </label>+ <label className={LABEL_CLS}>+ Renewal+ <input+ type="date"+ value={metaForm.renewal_date ?? ""}+ onChange={(e) =>+ setMetaForm({ ...metaForm, renewal_date: e.target.value })+ }+ className={FIELD_CLS}+ />+ </label>+ <label className={LABEL_CLS}>+ Retainer+ <input+ value={metaForm.retainer ?? ""}+ onChange={(e) => setMetaForm({ ...metaForm, retainer: e.target.value })}+ placeholder="Retainer (display only)"+ className={FIELD_CLS}+ />+ </label>+ <label className={LABEL_CLS}>+ Primary contact+ <input+ value={metaForm.primary_contact ?? ""}+ onChange={(e) =>+ setMetaForm({ ...metaForm, primary_contact: e.target.value })+ }+ placeholder="Primary contact"+ className={FIELD_CLS}+ />+ </label>+ <label className={LABEL_CLS}>+ Notes+ <input+ value={metaForm.notes ?? ""}+ onChange={(e) => setMetaForm({ ...metaForm, notes: e.target.value })}+ placeholder="Notes"+ className={FIELD_CLS}+ />+ </label>+ </div>+ </SidePanel></main>);}diff --git a/packages/ui/src/app/company-profile/page.tsx b/packages/ui/src/app/company-profile/page.tsxindex 400c5340..a7fca2b3 100644--- a/packages/ui/src/app/company-profile/page.tsx+++ b/packages/ui/src/app/company-profile/page.tsx@@ -14,6 +14,8 @@ import {} from "@/components/company-profile/ProfileSections";import { PROFILE_COPY } from "@/components/company-profile/profileCopy";import { profileWording } from "@/components/shell/navConfig";+import { buttonClass } from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";import { useWorkspace } from "@/components/workspace/WorkspaceContext";import {getCompanyProfile,@@ -127,43 +129,44 @@ export default function CompanyProfilePage() {return (<div className="flex flex-col h-full bg-surface"><main className="flex-1 overflow-y-auto">- <div className="max-w-3xl mx-auto px-4 py-6 sm:px-6 sm:py-10">+ <div className="max-w-6xl mx-auto px-4 py-8 sm:px-6">{loading && (<div className="flex items-center justify-center h-40">- <div className="w-5 h-5 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" />+ <div className="w-6 h-6 border-2 border-accent border-t-transparent rounded-full animate-spin" /></div>)}{notFound && (- <div className="bg-indigo-500/10 border border-indigo-500/20 rounded-xl px-5 py-4 flex flex-col sm:flex-row sm:items-center justify-between gap-2">- <p className="text-sm text-fg">{copy.missing}</p>- <Link href="/onboard" className="flex-shrink-0 text-xs text-indigo-400 hover:text-indigo-300 font-medium transition-colors">- Complete setup →+ <div className="max-w-3xl bg-accent/10 border border-accent/20 rounded-2xl px-5 py-5 flex flex-col sm:flex-row sm:items-center justify-between gap-3">+ <p className="text-[15px] text-fg">{copy.missing}</p>+ <Link href="/onboard" className={buttonClass("primary", "md", "flex-shrink-0")}>+ Complete setup</Link></div>)}{profile && (<>- <div className={`flex items-center justify-between ${copy.intro ? "mb-4" : "mb-8"}`}>- <div>- <h1 className="text-lg font-semibold text-fg">{profile.name}</h1>- <p className="text-sm text-fg-muted mt-0.5">{[profile.industry, profile.stage].filter(Boolean).join(" · ")}</p>+ <div className={`flex items-start justify-between gap-4 ${copy.intro ? "mb-4" : "mb-8"}`}>+ <div className="min-w-0">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg">{profile.name}</h1>+ <p className="text-[15px] text-fg-muted mt-1.5">{[profile.industry, profile.stage].filter(Boolean).join(" · ")}</p></div>- <Link href="/onboard" className="text-xs text-fg-muted hover:text-fg-muted transition-colors">- Re-run setup →- </Link>+ <OverflowMenu+ label="More profile actions"+ items={[{ label: "Re-run setup", href: "/onboard" }]}+ /></div>{copy.intro && (- <p className="text-sm text-fg-muted leading-relaxed mb-8">+ <p className="text-[15px] text-fg-muted leading-relaxed mb-8 max-w-3xl">{copy.intro}{copy.roleNote && (<>{" "}{copy.roleNote}{" "}- <Link href="/settings#workspace" className="whitespace-nowrap text-indigo-400 hover:text-indigo-300 transition-colors">+ <Link href="/settings/workspace" className="whitespace-nowrap text-accent hover:underline">Settings → Workspace</Link>.@@ -178,6 +181,7 @@ export default function CompanyProfilePage() {onSave={save}pending={pending}wording={wording}+ layout="columns"/></>)}diff --git a/packages/ui/src/app/council/page.tsx b/packages/ui/src/app/council/page.tsxindex 4b114dd3..401995df 100644--- a/packages/ui/src/app/council/page.tsx+++ b/packages/ui/src/app/council/page.tsx@@ -1,6 +1,7 @@"use client";-import { useCallback, useEffect, useMemo, useState } from "react";+import Link from "next/link";+import { useCallback, useEffect, useId, useMemo, useState } from "react";import {AgentDetail,@@ -28,8 +29,17 @@ import {savePersona,testAgent,} from "@/lib/api";-import VoicePicker from "@/components/executive/VoicePicker";-import PageSideNav from "@/components/shell/PageSideNav";+import Button from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";+import SectionTabs, { sectionPanelProps } from "@/components/ui/SectionTabs";+import SidePanel from "@/components/ui/SidePanel";+import {+ agentArea,+ agentCardStatus,+ agentDisplayName,+ agentInitials,+ shortModelName,+} from "@/lib/councilCards";interface DraftState {role: string;@@ -101,6 +111,33 @@ function personaOption(p: PersonaMeta) {// Remembers, per browser, that the owner prefers the full editor.const ADVANCED_KEY = "oe.council.advanced";+// The full editor's tabs for the selected agent. Each shows only where the+// agent has something on it: the utility and research knobs have just a+// model, and the utility one can't be test-run.+type EditorTab = "model" | "instructions" | "prompt" | "test" | "history";++const TAB_LABEL: Record<EditorTab, string> = {+ model: "Model",+ instructions: "Instructions",+ prompt: "Prompt",+ test: "Test",+ history: "History",+};++function editorTabs(d: AgentDetail): EditorTab[] {+ const knob = d.name === "utility_fast" || d.name === "research";+ const tabs: EditorTab[] = ["model"];+ if (!knob) tabs.push("instructions");+ if (!knob || d.research_focus_default !== null || d.name === "executive") tabs.push("prompt");+ if (d.name !== "utility_fast") tabs.push("test");+ tabs.push("history");+ return tabs;+}++const FIELD =+ "px-3.5 rounded-xl bg-surface border border-line text-fg focus:border-accent/60 focus:outline-none";+const FIELD_LABEL = "block text-sm font-semibold text-fg";+function detailToDraft(d: AgentDetail): DraftState {return {role: d.role,@@ -132,16 +169,21 @@ function draftIsDirty(d: AgentDetail | null, draft: DraftState | null): booleanexport default function CouncilPage() {const [agents, setAgents] = useState<AgentMeta[]>([]);+ // Which fields each customized agent overrides (from its detail), so a+ // card can tell the owner's own instructions from a Quality preset's model.+ const [overrideFields, setOverrideFields] = useState<Record<string, string[]>>({});+ // The agent open in the side panel; null when it's closed.const [selected, setSelected] = useState<string | null>(null);const [detail, setDetail] = useState<AgentDetail | null>(null);const [draft, setDraft] = useState<DraftState | null>(null);const [modelOptions, setModelOptions] = useState<ModelOption[]>([]);const [history, setHistory] = useState<AgentHistoryEntry[]>([]);- const [historyOpen, setHistoryOpen] = useState(false);+ const [tab, setTab] = useState<EditorTab>("model");const [presets, setPresets] = useState<QualityPresets | null>(null);- // The Council opens in its simple view: Quality, voice and the core- // agents with their additional instructions. "Show all agents" lists the+ // The Council opens in its simple view: Quality and the core agents with+ // their additional instructions (the voice is chosen in Settings → Your+ // Executive). "Show all agents" lists the// internal ones too; "Advanced" opens the full editor, and this browser// remembers that choice.const [showAll, setShowAll] = useState(false);@@ -175,11 +217,17 @@ export default function CouncilPage() {try {const list = await listAgents();setAgents(list);- if (selected === null && list.length > 0) setSelected(list[0].name);+ const customized = list.filter((a) => a.has_override).map((a) => a.name);+ const details = await Promise.all(+ customized.map((name) => getAgentDetail(name).catch(() => null)),+ );+ const fields: Record<string, string[]> = {};+ for (const d of details) if (d) fields[d.name] = d.overridden_fields;+ setOverrideFields(fields);} catch (err) {setError(err instanceof Error ? err.message : "Failed to load agents");}- }, [selected]);+ }, []);const loadDetail = useCallback(async (name: string) => {setError(null);@@ -187,7 +235,6 @@ export default function CouncilPage() {const d = await getAgentDetail(name);setDetail(d);setDraft(detailToDraft(d));- setHistoryOpen(false);setTestResult(null);setTestError(null);} catch (err) {@@ -217,8 +264,9 @@ export default function CouncilPage() {// Not remembered; the toggle still works for this visit.}if (!selected) return;- // The simple view's voice card saves on its own, so pick up the stored- // voice. Unsaved edits stay in the draft; only a clean draft is reloaded.+ // The voice may have changed in Settings since this page loaded, so pick+ // up the stored one. Unsaved edits stay in the draft; only a clean draft+ // is reloaded.const keepDraft = dirty;getAgentDetail(selected).then((d) => {@@ -239,6 +287,12 @@ export default function CouncilPage() {listAgentModelOptions(selected ?? undefined).then(setModelOptions).catch(() => {});}, [selected, loadDetail]);+ // The tab stays put when another agent is picked, unless that agent has no+ // such tab; then the editor opens on Model.+ const tabs = detail ? editorTabs(detail) : (["model"] as EditorTab[]);+ const activeTab = tabs.includes(tab) ? tab : "model";+ const historyOpen = advanced && activeTab === "history";+useEffect(() => {if (!selected || !historyOpen) return;listAgentHistory(selected).then(setHistory).catch(() => setHistory([]));@@ -258,6 +312,8 @@ export default function CouncilPage() {.catch(() => setPersonaError("Failed to load persona"));}, [selected, draft?.voice_persona_slug]);+ const tabIdBase = useId();+const pickerOptions = useMemo<PickerOption[]>(() => {const known = new Set(modelOptions.map((o) => o.id));const extra = Array.from(@@ -298,6 +354,33 @@ export default function CouncilPage() {const dirty = draftIsDirty(detail, draft);+ // The picker's label for a model id ("Claude Sonnet 5"), when it has one.+ const labelFor = (id: string) => modelOptions.find((o) => o.id === id)?.label;++ const openAgent = (name: string) => {+ setError(null);+ setDetail(null);+ setDraft(null);+ setSelected(name);+ };++ // Cancel drops the panel's edits, as picking another agent did when the+ // agents were a list beside the editor.+ const cancelPanel = () => {+ setSelected(null);+ setDetail(null);+ setDraft(null);+ setNewPersonaMode(false);+ setError(null);+ };++ // Escape, the close button or a click beside the panel are easy to hit by+ // accident, so they ask before throwing unsaved edits away.+ const closePanel = () => {+ if (dirty && !window.confirm("Discard your unsaved changes to this agent?")) return;+ cancelPanel();+ };+const handleSave = async () => {if (!detail || !draft || !selected) return;setSaving(true);@@ -424,734 +507,770 @@ export default function CouncilPage() {}};+ const panelOpen = selected !== null;+ const selectedMeta = agents.find((a) => a.name === selected);+ const panelTitle = agentDisplayName(detail?.role ?? selectedMeta?.role ?? "");+ const panelModel = draft ?? selectedMeta;+ const panelSubtitle = selectedMeta+ ? [+ agentArea(selectedMeta),+ panelModel ? shortModelName(panelModel.model, labelFor(panelModel.model)) : null,+ panelModel && "deep_reasoning" in panelModel && panelModel.deep_reasoning && modelSupportsDeepReasoning(panelModel.model)+ ? "deep reasoning"+ : null,+ ]+ .filter(Boolean)+ .join(" · ")+ : undefined;+ const noInstructions = detail?.name === "utility_fast" || detail?.name === "research";++ const saveButton = (+ <Button variant="primary" onClick={handleSave} disabled={saving || !dirty || !detail}>+ {saving ? "Saving…" : "Save"}+ </Button>+ );++ const panelFooter = (+ <div className="flex items-center gap-2">+ {advanced && detail && (+ <OverflowMenu+ label="More agent actions"+ placement="up"+ align="left"+ items={[+ {+ label: "Reset to default",+ onSelect: () => void handleReset(),+ disabled: resetting || !detail.has_override,+ danger: true,+ },+ ]}+ />+ )}+ <span className="flex-1" />+ <Button variant="ghost" onClick={cancelPanel}>+ Cancel+ </Button>+ {saveButton}+ </div>+ );+return (- <div className="flex flex-col md:flex-row flex-1 min-h-0 bg-surface text-fg overflow-hidden">- <PageSideNav- label="Agent"- current={listedAgents.find((a) => a.name === selected)?.role}- closeKey={selected ?? ""}- className="md:w-64 bg-surface-elevated"- >- <div className="px-3 py-4 overflow-y-auto">- <p className="px-2 text-[10px] font-semibold uppercase tracking-widest text-fg-subtle mb-2">- Agent Council+ <div className="flex-1 min-h-0 min-w-0 overflow-y-auto bg-surface text-fg">+ <div className="max-w-5xl mx-auto px-4 py-6 sm:px-8 sm:py-10 space-y-6">+ <div>+ <div className="flex items-start justify-between gap-4">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg">Agent Council</h1>+ <Button variant="secondary" size="sm" onClick={toggleAdvanced}>+ {advanced ? "Back to simple view" : "Advanced"}+ </Button>+ </div>+ <p className="mt-2 text-[15px] text-fg-muted">+ {simple+ ? "Pick how thorough answers should be and add instructions for any agent. Changes apply on the next message."+ : "Edit each specialist’s prompt, model, and behavior. Changes apply on the next specialist call — no restart needed. Resetting restores the built-in defaults."}</p>- <nav className="space-y-0.5">- {listedAgents.map((a) => (- <button- key={a.name}- data-closes-nav- onClick={() => setSelected(a.name)}- className={`w-full text-left flex items-start gap-2 px-2 py-2 md:py-1.5 rounded-lg text-sm md:text-xs transition-colors ${- selected === a.name- ? "bg-indigo-500/10 text-indigo-300"- : "text-fg-muted hover:text-fg hover:bg-surface-overlay/60"- }`}- >+ </div>++ {error && !panelOpen && (+ <div className="rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-500">+ {error}+ </div>+ )}++ {presets && (+ <section className="rounded-2xl border border-line bg-surface-elevated p-5 sm:p-6 space-y-4">+ <div className="flex items-center justify-between">+ <h2 className="text-lg font-semibold text-fg">Quality</h2>+ {presets.active === null && (<span- className={`mt-1 inline-block w-1.5 h-1.5 rounded-full flex-shrink-0 ${- a.has_override ? "bg-amber-400" : "bg-surface-input"- }`}- title={a.has_override ? "Has override" : "Default config"}- />- <span className="flex-1 min-w-0">- <span className="block font-medium text-fg uppercase tracking-wide text-[10px]">- {a.name}- </span>- <span className="block truncate text-fg-muted">{a.role}</span>+ className="text-[10px] uppercase tracking-widest px-2 py-1 rounded bg-amber-500/10 text-amber-500 border border-amber-500/20"+ title={`${presets.custom_agents.length} agent(s) differ from ${basePresetLabel ?? "the preset"}`}+ >+ Custom</span>- {customAgents.has(a.name) && (- <span- className="mt-0.5 text-[9px] uppercase tracking-widest px-1 rounded bg-surface-overlay text-fg-subtle"- title={`Differs from the ${basePresetLabel ?? ""} preset`}+ )}+ </div>+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">+ {presets.presets.map((p) => {+ const current = presets.active === p.id;+ const base = presets.active === null && presets.base === p.id;+ return (+ <button+ key={p.id}+ onClick={() => handleApplyPreset(p.id)}+ disabled={!p.available || current || applyingPreset !== null}+ aria-pressed={current}+ title={p.available ? undefined : "This install offers none of this preset's models"}+ className={`flex flex-col items-start justify-start text-left rounded-2xl border-2 p-4 transition-colors disabled:cursor-not-allowed ${+ current+ ? "border-accent bg-accent/10"+ : base+ ? "border-accent/40 border-dashed"+ : "border-line hover:border-accent/50"+ } ${p.available ? "" : "opacity-40"}`}>- Custom- </span>- )}- </button>- ))}- </nav>- {simple && (- <button- onClick={() => setShowAll((v) => !v)}- className="mt-3 px-2 text-[11px] text-fg-muted hover:text-fg underline underline-offset-2"- >- {showAll ? "Show fewer agents" : "Show all agents"}- </button>- )}- </div>- </PageSideNav>-- <main className="flex-1 min-h-0 min-w-0 overflow-y-auto">- <div className="max-w-4xl mx-auto px-4 py-6 sm:px-8 sm:py-10 space-y-6">- <div>- <div className="flex items-start justify-between gap-4">- <h1 className="text-2xl font-bold text-fg">Agent Council</h1>- <button- onClick={toggleAdvanced}- className="mt-1 text-xs text-fg-muted hover:text-fg underline underline-offset-2"- >- {advanced ? "Back to simple view" : "Advanced"}- </button>+ <span className="block text-base font-semibold text-fg">+ {applyingPreset === p.id ? "Applying…" : p.label}+ </span>+ <span className="block text-sm text-fg-muted mt-1 leading-relaxed">{p.description}</span>+ {p.model && (+ <span className="block text-[11px] text-fg-subtle mt-2 font-mono">{p.model}</span>+ )}+ </button>+ );+ })}</div>- <p className="mt-2 text-sm text-fg-muted">- {simple- ? "Pick how thorough answers should be, how your Executive sounds, and add instructions for any agent. Changes apply on the next message."- : "Edit each specialist\u2019s prompt, model, and behavior. Changes apply on the next specialist call — no restart needed. Resetting restores the built-in defaults."}+ <p className="text-[13px] text-fg-subtle">+ A preset sets every agent's model and deep reasoning at once. Changing one agent+ below marks it Custom; each agent keeps its own history.</p>- </div>+ </section>+ )}- {error && (- <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300">- {error}- </div>- )}+ {simple && (+ <Link+ href="/settings/executive"+ className="group flex items-center justify-between gap-3 rounded-2xl border border-line bg-surface-elevated px-5 py-4 text-[15px] text-fg-muted transition-colors hover:border-accent/50 hover:text-fg"+ >+ <span>+ Voice is set in <span className="font-semibold text-fg">Settings → Your Executive</span>+ </span>+ <span aria-hidden="true" className="text-fg-subtle group-hover:text-fg">+ →+ </span>+ </Link>+ )}- {presets && (- <section className="rounded-xl border border-line bg-surface px-6 py-5 space-y-3">- <div className="flex items-center justify-between">- <h2 className="text-sm font-semibold text-fg">Quality</h2>- {presets.active === null && (- <span- className="text-[10px] uppercase tracking-widest px-2 py-1 rounded bg-amber-500/10 text-amber-400 border border-amber-500/20"- title={`${presets.custom_agents.length} agent(s) differ from ${basePresetLabel ?? "the preset"}`}+ <section aria-labelledby="council-agents-heading" className="space-y-3">+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">+ <h2 id="council-agents-heading" className="text-lg font-semibold text-fg">+ Your agents+ </h2>+ <p className="text-[15px] text-fg-muted">Tap one to change how it works</p>+ </div>+ <ul className="overflow-hidden rounded-2xl border border-line bg-surface-elevated divide-y divide-line sm:grid sm:grid-cols-2 lg:grid-cols-3 sm:gap-3 sm:divide-y-0 sm:overflow-visible sm:rounded-none sm:border-0 sm:bg-transparent">+ {listedAgents.map((a) => {+ const name = agentDisplayName(a.role);+ const status = agentCardStatus(a.has_override, overrideFields[a.name], customAgents.has(a.name));+ const model = shortModelName(a.model, labelFor(a.model));+ return (+ <li key={a.name} className="min-w-0">+ <button+ type="button"+ onClick={() => openAgent(a.name)}+ aria-haspopup="dialog"+ className={`group flex h-full w-full min-w-0 items-center sm:items-start gap-3 px-4 py-3.5 sm:p-4 text-left transition-colors hover:bg-surface-overlay/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent/60 sm:rounded-2xl sm:border sm:bg-surface-elevated sm:hover:bg-surface-elevated sm:hover:border-accent/60 sm:hover:shadow-sm ${+ selected === a.name ? "sm:border-accent" : "sm:border-line"+ }`}>- Custom- </span>- )}- </div>- <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">- {presets.presets.map((p) => {- const current = presets.active === p.id;- const base = presets.active === null && presets.base === p.id;- return (- <button- key={p.id}- onClick={() => handleApplyPreset(p.id)}- disabled={!p.available || current || applyingPreset !== null}- aria-pressed={current}- title={p.available ? undefined : "This install offers none of this preset's models"}- className={`text-left rounded-lg border px-3 py-2 transition-colors disabled:cursor-not-allowed ${- current- ? "border-indigo-500/40 bg-indigo-500/10"- : base- ? "border-indigo-500/20 border-dashed"- : "border-line hover:border-line-strong"- } ${p.available ? "" : "opacity-40"}`}+ <span+ aria-hidden="true"+ className="grid h-10 w-10 flex-shrink-0 place-items-center rounded-xl bg-accent/10 text-sm font-bold text-accent sm:h-11 sm:w-11">- <span className="block text-sm font-medium text-fg">- {applyingPreset === p.id ? "Applying…" : p.label}+ {agentInitials(name)}+ </span>+ <span className="min-w-0 flex-1">+ <span className="block text-base font-semibold leading-snug text-fg">{name}</span>+ <span className="block text-sm text-fg-muted">{agentArea(a)}</span>+ <span className="mt-1.5 flex items-center gap-1.5 text-[13px] text-fg-muted">+ <span+ aria-hidden="true"+ className={`inline-block h-2 w-2 flex-shrink-0 rounded-full ${+ status === "default" ? "bg-emerald-500" : "bg-amber-500"+ }`}+ />+ {status === "instructions" ? (+ "Has your instructions"+ ) : status === "custom-model" ? (+ <span title={`Differs from the ${basePresetLabel ?? ""} preset`}>Custom · {model}</span>+ ) : (+ model+ )}</span>- <span className="block text-xs text-fg-muted mt-0.5">{p.description}</span>- {p.model && (- <span className="block text-[10px] text-fg-subtle mt-1 font-mono">{p.model}</span>- )}- </button>- );- })}- </div>- <p className="text-[11px] text-fg-subtle">- A preset sets every agent's model and deep reasoning at once. Changing one agent- below marks it Custom; each agent keeps its own history.- </p>- </section>- )}-+ </span>+ <svg+ aria-hidden="true"+ viewBox="0 0 20 20"+ fill="currentColor"+ className="h-5 w-5 flex-shrink-0 text-fg-subtle sm:hidden"+ >+ <path d="M7.3 4.3a1 1 0 0 1 1.4 0l5 5a1 1 0 0 1 0 1.4l-5 5a1 1 0 0 1-1.4-1.4L11.6 10 7.3 5.7a1 1 0 0 1 0-1.4z" />+ </svg>+ </button>+ </li>+ );+ })}+ </ul>{simple && (- <section className="rounded-xl border border-line bg-surface px-6 py-5 space-y-3">- <h2 className="text-sm font-semibold text-fg">Voice</h2>- <VoicePicker variant="card" />- </section>+ <Button variant="secondary" className="w-full sm:w-auto" onClick={() => setShowAll((v) => !v)}>+ {showAll ? "Show fewer agents" : "Show all agents"}+ </Button>)}+ </section>+ </div>- {simple && detail && draft && (- <section className="rounded-xl border border-line bg-surface px-6 py-5 space-y-4">- <div className="flex items-center justify-between gap-4">- <div className="min-w-0">- <h2 className="text-lg font-semibold text-fg">{detail.role}</h2>- <span- className="mt-1 inline-block text-[10px] px-2 py-0.5 rounded bg-surface-overlay text-fg-muted font-mono"- title="Set by the Quality choice above, or per agent under Advanced"- >- {currentModel?.label ?? draft.model}- {draft.deep_reasoning && modelSupportsDeepReasoning(draft.model) ? " · deep reasoning" : ""}- </span>- </div>- <button- onClick={handleSave}- disabled={saving || !dirty}- className="text-xs px-3 py-1.5 rounded-lg bg-indigo-500/20 border border-indigo-500/30 text-indigo-300 hover:bg-indigo-500/30 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"- >- {saving ? "Saving…" : "Save"}- </button>+ <SidePanel+ open={panelOpen}+ onClose={closePanel}+ title={panelTitle || "Agent"}+ subtitle={panelSubtitle}+ width={advanced ? "lg" : "md"}+ footer={panelFooter}+ >+ {error && (+ <div className="mb-4 rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-500">+ {error}+ </div>+ )}+ {!detail || !draft || detail.name !== selected ? (+ <p className="text-[15px] text-fg-muted">Loading…</p>+ ) : simple ? (+ noInstructions ? (+ <p className="text-[15px] text-fg-muted">+ This agent has no instructions to edit. Its model follows the Quality choice;+ change it on its own under Advanced.+ </p>+ ) : (+ <div>+ <div className="flex items-center justify-between mb-1">+ <span className={FIELD_LABEL}>Additional instructions</span>+ <span className="text-xs text-fg-subtle">+ {draft.instructions.length} / {INSTRUCTIONS_MAX_CHARS} chars+ </span></div>- {detail.name === "utility_fast" || detail.name === "research" ? (- <p className="text-xs text-fg-muted">- This agent has no instructions to edit. Its model follows the Quality choice;- change it on its own under Advanced.- </p>- ) : (+ <p className="text-[13px] text-fg-subtle mb-2 leading-relaxed">+ Added to this agent's built-in prompt on every call, so it keeps getting+ our prompt improvements.+ </p>+ <textarea+ value={draft.instructions}+ onChange={(e) => setDraft({ ...draft, instructions: e.target.value })}+ maxLength={INSTRUCTIONS_MAX_CHARS}+ rows={8}+ placeholder="e.g. Always quote figures in EUR."+ className={`w-full ${FIELD} py-2.5 text-[15px] resize-y leading-relaxed`}+ />+ </div>+ )+ ) : (+ <div className="space-y-4">+ <div className="flex flex-wrap items-center gap-2">+ <p className="min-w-0 text-[13px] text-fg-muted font-mono break-words">+ {detail.name}+ {detail.name === "executive"+ ? " · orchestrator"+ : detail.name === "utility_fast"+ ? " · utility model knob"+ : detail.name === "research"+ ? " · research model knob"+ : ` · domains: ${detail.domains.join(", ") || "—"}`}+ </p>+ {detail.has_override && (+ <span className="text-[11px] uppercase tracking-widest px-2 py-1 rounded-md bg-amber-500/10 text-amber-500 border border-amber-500/20">+ Customized+ </span>+ )}+ </div>+ {dirty && (+ <p className="text-[13px] text-amber-500">+ Unsaved changes. Save keeps every tab's edits.+ </p>+ )}++ <SectionTabs+ tabs={tabs.map((t) => ({ id: t, label: TAB_LABEL[t] }))}+ active={activeTab}+ onChange={setTab}+ label="Agent settings"+ idBase={tabIdBase}+ />++ <div {...sectionPanelProps(tabIdBase, activeTab)} className="space-y-6 pt-2">+ {activeTab === "model" && (+ <>+ <div className="grid grid-cols-1 md:grid-cols-2 gap-5">+ <label className="block">+ <span className={FIELD_LABEL}>Role</span>+ <input+ type="text"+ value={draft.role}+ onChange={(e) => setDraft({ ...draft, role: e.target.value })}+ className={`w-full ${FIELD} mt-1.5 h-11 text-[15px]`}+ />+ {detail.role_default !== draft.role && (+ <span className="text-xs text-fg-subtle mt-1 block">+ Default: {detail.role_default}+ </span>+ )}+ </label>++ <div className="block">+ <span className={FIELD_LABEL}>Model</span>+ <div className="mt-1.5 flex gap-2">+ <select+ aria-label="Model provider"+ value={currentModel?.provider ?? ""}+ onChange={(e) => selectProvider(e.target.value)}+ className={`${FIELD} h-11 w-2/5 min-w-0 text-[15px]`}+ >+ {providerGroups.map((g) => (+ <option key={g.provider} value={g.provider}>+ {g.label}+ </option>+ ))}+ </select>+ <select+ aria-label="Model"+ value={draft.model}+ onChange={(e) => selectModel(e.target.value)}+ className={`${FIELD} h-11 flex-1 min-w-0 text-[15px]`}+ >+ {pickerOptions+ .filter((o) => o.provider === currentModel?.provider)+ .map((o) => (+ <option key={o.id} value={o.id}>+ {o.label}+ {o.id === detail.model_default ? " (default)" : ""}+ </option>+ ))}+ </select>+ </div>+ {currentModel && (+ <span className="text-xs text-fg-subtle mt-1 block font-mono break-all">+ {currentModel.id} ·{" "}+ {currentModel.unlisted+ ? "not in the current allowlist"+ : ROUTE_TEXT[currentModel.route]}+ </span>+ )}+ </div>+ </div>++ {detail.name !== "utility_fast" && (+ <label+ className={`flex items-start gap-3 text-sm text-fg-muted ${+ modelSupportsDeepReasoning(draft.model) ? "" : "opacity-60"+ }`}+ title={+ modelSupportsDeepReasoning(draft.model)+ ? "Adaptive thinking on Claude Opus/Sonnet, and on any OpenRouter model whose catalog entry supports reasoning. Ignored by models that can't reason."+ : "Haiku doesn't support adaptive thinking — pick another model to enable deep reasoning."+ }+ >+ <input+ type="checkbox"+ checked={draft.deep_reasoning && modelSupportsDeepReasoning(draft.model)}+ disabled={!modelSupportsDeepReasoning(draft.model)}+ onChange={(e) => setDraft({ ...draft, deep_reasoning: e.target.checked })}+ className="mt-0.5 w-5 h-5 flex-shrink-0 rounded border-line-strong bg-surface accent-[rgb(var(--accent-strong))] disabled:cursor-not-allowed"+ />+ <span>+ <span className="font-semibold text-fg">Deep reasoning</span> (adaptive+ thinking — Claude Opus/Sonnet and reasoning-capable OpenRouter models; not+ available on Haiku)+ <span className="ml-1.5 text-xs text-fg-subtle">+ default: {detail.deep_reasoning_default ? "on" : "off"}+ </span>+ </span>+ </label>+ )}++ {detail.name === "utility_fast" && (+ <p className="text-sm text-fg-muted leading-relaxed">+ This model is used for fast, non-specialist calls: the Discord response+ gate, Discord thread title generation, parsing human approval replies+ (Slack/email), and disambiguating inbound messages when multiple+ awaiting_human runs exist. Changing it has no effect on specialist+ answers — just on these lightweight classification tasks.+ </p>+ )}+ {detail.name === "research" && (+ <p className="text-sm text-fg-muted leading-relaxed">+ This model + deep-reasoning setting drives the executive_research+ specialist fan-out (the periodic research scan and the manual+ “what should we look into?” run). It applies to all specialists’+ research turns at once and is independent of their chat models —+ lowering it cuts research cost without touching chat quality. Per-domain+ research focus is edited under each specialist’s Prompt tab.+ </p>+ )}+ </>+ )}++ {activeTab === "instructions" && (<div><div className="flex items-center justify-between mb-1">- <span className="text-fg-muted uppercase tracking-widest text-[10px] font-semibold">- Additional instructions- </span>- <span className="text-[10px] text-fg-subtle">+ <span className={FIELD_LABEL}>Additional instructions</span>+ <span className="text-xs text-fg-subtle">{draft.instructions.length} / {INSTRUCTIONS_MAX_CHARS} chars</span></div>- <p className="text-[10px] text-fg-subtle mb-1 leading-relaxed">- Added to this agent's built-in prompt on every call, so it keeps getting- our prompt improvements.+ <p className="text-[13px] text-fg-subtle mb-2 leading-relaxed">+ Added after the system prompt (Prompt tab) on every call. Use this to+ steer the agent while it keeps receiving updates to its built-in+ prompt.</p><textareavalue={draft.instructions}onChange={(e) => setDraft({ ...draft, instructions: e.target.value })}maxLength={INSTRUCTIONS_MAX_CHARS}- rows={5}- placeholder="e.g. Always quote figures in EUR."- className="w-full text-xs px-3 py-2 rounded-lg bg-surface border border-line text-fg focus:border-indigo-500/40 focus:outline-none resize-y leading-relaxed"+ rows={8}+ placeholder="e.g. Always quote figures in EUR. Keep answers under 200 words."+ className={`w-full ${FIELD} py-2.5 text-[15px] resize-y leading-relaxed`}/></div>)}- </section>- )}-- {!simple && (detail && draft ? (- <div className="space-y-6">- <div className="rounded-xl border border-line bg-surface px-6 py-5 space-y-4">- <div className="flex items-center justify-between">- <div>- <h2 className="text-lg font-semibold text-fg">- {detail.role}- </h2>- <p className="text-xs text-fg-muted mt-0.5 font-mono">- {detail.name}- {detail.name === "executive"- ? " · orchestrator"- : detail.name === "utility_fast"- ? " · utility model knob"- : detail.name === "research"- ? " · research model knob"- : ` · domains: ${detail.domains.join(", ") || "—"}`}- </p>- </div>- <div className="flex items-center gap-2">- {detail.has_override && (- <span className="text-[10px] uppercase tracking-widest px-2 py-1 rounded bg-amber-500/10 text-amber-400 border border-amber-500/20">- Customized- </span>- )}- <button- onClick={handleReset}- disabled={resetting || !detail.has_override}- className="text-xs px-3 py-1.5 rounded-lg border border-line-strong text-fg-muted hover:border-red-500/40 hover:text-red-400 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"- >- Reset to default- </button>- <button- onClick={handleSave}- disabled={saving || !dirty}- className="text-xs px-3 py-1.5 rounded-lg bg-indigo-500/20 border border-indigo-500/30 text-indigo-300 hover:bg-indigo-500/30 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"- >- {saving ? "Saving…" : "Save"}- </button>- </div>- </div>-- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- <label className="block text-xs">- <span className="text-fg-muted uppercase tracking-widest text-[10px] font-semibold">- Role- </span>- <input- type="text"- value={draft.role}- onChange={(e) => setDraft({ ...draft, role: e.target.value })}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface border border-line text-fg focus:border-indigo-500/40 focus:outline-none text-sm"- />- {detail.role_default !== draft.role && (- <span className="text-[10px] text-fg-subtle mt-1 block">- Default: {detail.role_default}- </span>- )}- </label>-- <div className="block text-xs">- <span className="text-fg-muted uppercase tracking-widest text-[10px] font-semibold">- Model- </span>- <div className="mt-1 flex gap-2">- <select- aria-label="Model provider"- value={currentModel?.provider ?? ""}- onChange={(e) => selectProvider(e.target.value)}- className="w-2/5 min-w-0 px-3 py-2 rounded-lg bg-surface border border-line text-fg focus:border-indigo-500/40 focus:outline-none text-sm"- >- {providerGroups.map((g) => (- <option key={g.provider} value={g.provider}>- {g.label}- </option>- ))}- </select>- <select- aria-label="Model"- value={draft.model}- onChange={(e) => selectModel(e.target.value)}- className="flex-1 min-w-0 px-3 py-2 rounded-lg bg-surface border border-line text-fg focus:border-indigo-500/40 focus:outline-none text-sm"- >- {pickerOptions- .filter((o) => o.provider === currentModel?.provider)- .map((o) => (- <option key={o.id} value={o.id}>- {o.label}- {o.id === detail.model_default ? " (default)" : ""}- </option>- ))}- </select>- </div>- {currentModel && (- <span className="text-[10px] text-fg-subtle mt-1 block font-mono">- {currentModel.id} ·{" "}- {currentModel.unlisted- ? "not in the current allowlist"- : ROUTE_TEXT[currentModel.route]}- </span>- )}- </div>- </div>- {detail.name !== "utility_fast" && (- <label- className={`flex items-center gap-2 text-xs text-fg-muted ${- modelSupportsDeepReasoning(draft.model) ? "" : "opacity-60"- }`}- title={- modelSupportsDeepReasoning(draft.model)- ? "Adaptive thinking on Claude Opus/Sonnet, and on any OpenRouter model whose catalog entry supports reasoning. Ignored by models that can't reason."- : "Haiku doesn't support adaptive thinking — pick another model to enable deep reasoning."- }- >- <input- type="checkbox"- checked={draft.deep_reasoning && modelSupportsDeepReasoning(draft.model)}- disabled={!modelSupportsDeepReasoning(draft.model)}- onChange={(e) => setDraft({ ...draft, deep_reasoning: e.target.checked })}- className="rounded border-line-strong bg-surface disabled:cursor-not-allowed"- />- Deep reasoning (adaptive thinking — Claude Opus/Sonnet and reasoning-capable- OpenRouter models; not available on Haiku)- <span className="text-[10px] text-fg-subtle">- default: {detail.deep_reasoning_default ? "on" : "off"}- </span>- </label>- )}-- {detail.name === "utility_fast" ? (- <p className="text-xs text-fg-muted leading-relaxed">- This model is used for fast, non-specialist calls: the Discord response- gate, Discord thread title generation, parsing human approval replies- (Slack/email), and disambiguating inbound messages when multiple- awaiting_human runs exist. Changing it has no effect on specialist- answers — just on these lightweight classification tasks.- </p>- ) : detail.name === "research" ? (- <p className="text-xs text-fg-muted leading-relaxed">- This model + deep-reasoning setting drives the executive_research- specialist fan-out (the periodic research scan and the manual- “what should we look into?” run). It applies to all specialists’- research turns at once and is independent of their chat models —- lowering it cuts research cost without touching chat quality. Per-domain- research focus is edited under each specialist below.- </p>- ) : (- <>- <div>- <div className="flex items-center justify-between mb-1">- <span className="text-fg-muted uppercase tracking-widest text-[10px] font-semibold">- Additional instructions- </span>- <span className="text-[10px] text-fg-subtle">- {draft.instructions.length} / {INSTRUCTIONS_MAX_CHARS} chars- </span>- </div>- <p className="text-[10px] text-fg-subtle mb-1 leading-relaxed">- Added after the system prompt below on every call. Use this to- steer the agent while it keeps receiving updates to its built-in- prompt.- </p>- <textarea- value={draft.instructions}- onChange={(e) => setDraft({ ...draft, instructions: e.target.value })}- maxLength={INSTRUCTIONS_MAX_CHARS}- rows={5}- placeholder="e.g. Always quote figures in EUR. Keep answers under 200 words."- className="w-full text-xs px-3 py-2 rounded-lg bg-surface border border-line text-fg focus:border-indigo-500/40 focus:outline-none resize-y leading-relaxed"- />- </div>- <div>- <div className="flex items-center justify-between mb-1">- <span className="text-fg-muted uppercase tracking-widest text-[10px] font-semibold">- System prompt- </span>- <span className="text-[10px] text-fg-subtle">- {draft.prompt.length} chars- </span>- </div>- <textarea- value={draft.prompt}- onChange={(e) => setDraft({ ...draft, prompt: e.target.value })}- rows={20}- className="w-full font-mono text-xs px-3 py-2 rounded-lg bg-surface border border-line text-fg focus:border-indigo-500/40 focus:outline-none resize-y leading-relaxed"- />- {draft.prompt !== detail.prompt_default && (- <>- <p className="mt-2 text-[10px] text-amber-400 leading-relaxed">- An edited prompt replaces the built-in one, so future updates to- it won't reach this agent. Additional instructions above- don't have that cost.- </p>- <button- onClick={() => setDraft({ ...draft, prompt: detail.prompt_default })}- className="mt-1 text-[10px] text-fg-muted hover:text-fg underline"+ {activeTab === "prompt" && (+ <>+ {/* Voice Persona card — Executive only */}+ {detail.name === "executive" && (+ <div className="rounded-2xl border border-line bg-surface p-5 space-y-4">+ <div className="flex items-start justify-between gap-3">+ <div>+ <h3 className="text-base font-semibold text-fg">Voice Persona</h3>+ <p className="text-sm text-fg-muted mt-0.5">+ Sets the Executive's tone and communication style. The structural prompt stays intact.+ </p>+ </div>+ <Button+ size="sm"+ onClick={() => { setNewPersonaMode(true); setNewPersonaName(""); setNewPersonaBody(""); }}>- Restore default prompt in editor- </button>- </>- )}- </div>- </>- )}-- {/* Research focus — specialists only (those with a default scope) */}- {detail.research_focus_default !== null && (- <div>- <div className="flex items-center justify-between mb-1">- <span className="text-fg-muted uppercase tracking-widest text-[10px] font-semibold">- Research focus- </span>- <span className="text-[10px] text-fg-subtle">- {(draft.research_focus ?? "").length} chars- </span>- </div>- <p className="text-[10px] text-fg-subtle mb-1 leading-relaxed">- The domain-scope block appended to this specialist's research- turn — what external signals it watches. The shared research- contract (output format, recency / grounding / actionability bars)- is fixed and not editable here.- </p>- <textarea- value={draft.research_focus ?? ""}- onChange={(e) =>- setDraft({ ...draft, research_focus: e.target.value })- }- rows={10}- className="w-full font-mono text-xs px-3 py-2 rounded-lg bg-surface border border-line text-fg focus:border-indigo-500/40 focus:outline-none resize-y leading-relaxed"- />- {draft.research_focus !== detail.research_focus_default && (- <button- onClick={() =>- setDraft({- ...draft,- research_focus: detail.research_focus_default,- })- }- className="mt-2 text-[10px] text-fg-muted hover:text-fg underline"- >- Restore default research focus in editor- </button>- )}- </div>- )}- </div>+ + New+ </Button>+ </div>- {/* Voice Persona card — Executive only */}- {detail.name === "executive" && (- <div className="rounded-xl border border-line bg-surface px-6 py-5 space-y-4">- <div className="flex items-center justify-between">- <div>- <h3 className="text-sm font-semibold text-fg">Voice Persona</h3>- <p className="text-xs text-fg-muted mt-0.5">- Sets the Executive's tone and communication style. The structural prompt stays intact.- </p>- </div>- <button- onClick={() => { setNewPersonaMode(true); setNewPersonaName(""); setNewPersonaBody(""); }}- className="text-xs px-3 py-1.5 rounded-lg border border-line-strong text-fg-muted hover:border-indigo-500/40 hover:text-indigo-300 transition-colors"- >- + New- </button>- </div>+ {personaError && (+ <p className="text-sm text-red-500">{personaError}</p>+ )}- {personaError && (- <p className="text-xs text-red-400">{personaError}</p>- )}+ {/* Persona selector */}+ <div>+ <label className="block text-sm font-semibold text-fg mb-1.5">+ Active persona+ </label>+ <select+ value={draft.voice_persona_slug ?? "default"}+ onChange={(e) => setDraft({ ...draft, voice_persona_slug: e.target.value === "default" ? null : e.target.value })}+ className={`w-full ${FIELD} h-11 text-[15px]`}+ >+ {personas.filter((p) => !p.is_legacy).map(personaOption)}+ {personas.some((p) => p.is_legacy) && (+ <optgroup label="Legacy voices">+ {personas.filter((p) => p.is_legacy).map(personaOption)}+ </optgroup>+ )}+ </select>+ <p className="text-[13px] text-fg-subtle mt-1">+ Selection saves with Save at the bottom of this panel.+ </p>+ </div>- {/* Persona selector */}- <div>- <label className="block text-[10px] font-semibold uppercase tracking-widest text-fg-muted mb-1">- Active persona- </label>- <select- value={draft.voice_persona_slug ?? "default"}- onChange={(e) => setDraft({ ...draft, voice_persona_slug: e.target.value === "default" ? null : e.target.value })}- className="w-full px-3 py-2 rounded-lg bg-surface border border-line text-fg focus:border-indigo-500/40 focus:outline-none text-sm"- >- {personas.filter((p) => !p.is_legacy).map(personaOption)}- {personas.some((p) => p.is_legacy) && (- <optgroup label="Legacy voices">- {personas.filter((p) => p.is_legacy).map(personaOption)}- </optgroup>+ {/* Persona body editor */}+ {activePersonaDetail && (+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <span className="text-sm font-semibold text-fg">+ Persona body+ </span>+ <div className="flex items-center gap-2">+ {activePersonaDetail.source_notes && (+ <span className="text-xs text-fg-subtle italic truncate max-w-48" title={activePersonaDetail.source_notes}>+ {activePersonaDetail.source_notes}+ </span>+ )}+ </div>+ </div>+ <input+ type="text"+ value={personaDisplayNameDraft}+ onChange={(e) => setPersonaDisplayNameDraft(e.target.value)}+ placeholder="Display name"+ className={`w-full ${FIELD} h-11 text-[15px]`}+ />+ <textarea+ value={personaBodyDraft}+ onChange={(e) => setPersonaBodyDraft(e.target.value)}+ rows={12}+ className={`w-full ${FIELD} py-2.5 font-mono text-[13px] resize-y leading-relaxed`}+ />+ <div className="flex items-center gap-2 flex-wrap">+ <Button+ variant="secondary"+ size="sm"+ onClick={async () => {+ if (!activePersonaDetail) return;+ setSavingPersona(true);+ setPersonaError(null);+ try {+ const updated = await savePersona(activePersonaDetail.slug, personaDisplayNameDraft, personaBodyDraft);+ setActivePersonaDetail(updated);+ setPersonas(await listPersonas());+ } catch (e) {+ setPersonaError(e instanceof Error ? e.message : "Save failed");+ } finally {+ setSavingPersona(false);+ }+ }}+ disabled={savingPersona || !personaBodyDraft.trim()}+ >+ {savingPersona ? "Saving…" : "Save persona"}+ </Button>+ {activePersonaDetail.is_builtin && activePersonaDetail.is_customized && (+ <Button+ variant="ghost"+ size="sm"+ onClick={async () => {+ if (!activePersonaDetail) return;+ try {+ const restored = await resetPersona(activePersonaDetail.slug);+ setActivePersonaDetail(restored);+ setPersonaBodyDraft(restored.body);+ setPersonaDisplayNameDraft(restored.display_name);+ setPersonas(await listPersonas());+ } catch (e) {+ setPersonaError(e instanceof Error ? e.message : "Reset failed");+ }+ }}+ >+ Reset to built-in+ </Button>+ )}+ <Button+ variant="ghost"+ size="sm"+ onClick={async () => {+ if (!activePersonaDetail) return;+ try {+ const duped = await savePersona(+ activePersonaDetail.slug + "-copy",+ activePersonaDetail.display_name + " (copy)",+ personaBodyDraft,+ );+ const updated = await listPersonas();+ setPersonas(updated);+ setDraft((d) => d ? { ...d, voice_persona_slug: duped.slug } : d);+ } catch (e) {+ setPersonaError(e instanceof Error ? e.message : "Duplicate failed");+ }+ }}+ >+ Duplicate+ </Button>+ {!activePersonaDetail.is_builtin && (+ <Button+ variant="danger"+ size="sm"+ onClick={async () => {+ if (!activePersonaDetail) return;+ if (!window.confirm(`Delete persona "${activePersonaDetail.display_name}"?`)) return;+ try {+ await deletePersona(activePersonaDetail.slug);+ const updated = await listPersonas();+ setPersonas(updated);+ setDraft((d) => d ? { ...d, voice_persona_slug: null } : d);+ } catch (e) {+ setPersonaError(e instanceof Error ? e.message : "Delete failed");+ }+ }}+ >+ Delete+ </Button>+ )}+ </div>+ </div>)}- </select>- <p className="text-[10px] text-fg-subtle mt-1">- Selection saves with the main Save button above.- </p>- </div>- {/* Persona body editor */}- {activePersonaDetail && (- <div className="space-y-2">- <div className="flex items-center justify-between">- <span className="text-[10px] font-semibold uppercase tracking-widest text-fg-muted">- Persona body- </span>- <div className="flex items-center gap-2">- {activePersonaDetail.source_notes && (- <span className="text-[10px] text-fg-subtle italic truncate max-w-48" title={activePersonaDetail.source_notes}>- {activePersonaDetail.source_notes}- </span>- )}+ {/* New persona inline form */}+ {newPersonaMode && (+ <div className="mt-2 p-4 rounded-xl border border-line-strong bg-surface-elevated space-y-3">+ <p className="text-sm font-semibold text-fg">New persona</p>+ <input+ type="text"+ value={newPersonaName}+ onChange={(e) => setNewPersonaName(e.target.value)}+ placeholder="Display name (e.g. Elon Musk)"+ className={`w-full ${FIELD} h-11 text-[15px]`}+ />+ <textarea+ value={newPersonaBody}+ onChange={(e) => setNewPersonaBody(e.target.value)}+ rows={6}+ placeholder="Voice and style bullets — e.g. '- Direct and engineering-first...'"+ className={`w-full ${FIELD} py-2.5 font-mono text-[13px] resize-y`}+ />+ <div className="flex gap-2">+ <Button+ variant="secondary"+ size="sm"+ onClick={async () => {+ if (!newPersonaName.trim() || !newPersonaBody.trim()) return;+ try {+ const created = await createPersona(newPersonaName, newPersonaBody);+ const updated = await listPersonas();+ setPersonas(updated);+ setDraft((d) => d ? { ...d, voice_persona_slug: created.slug } : d);+ setNewPersonaMode(false);+ } catch (e) {+ setPersonaError(e instanceof Error ? e.message : "Create failed");+ }+ }}+ disabled={!newPersonaName.trim() || !newPersonaBody.trim()}+ >+ Create+ </Button>+ <Button variant="ghost" size="sm" onClick={() => setNewPersonaMode(false)}>+ Cancel+ </Button>+ </div></div>+ )}+ </div>+ )}+ {detail.name !== "utility_fast" && detail.name !== "research" && (+ <div>+ <div className="flex items-center justify-between mb-1">+ <span className={FIELD_LABEL}>System prompt</span>+ <span className="text-xs text-fg-subtle">{draft.prompt.length} chars</span></div>- <input- type="text"- value={personaDisplayNameDraft}- onChange={(e) => setPersonaDisplayNameDraft(e.target.value)}- placeholder="Display name"- className="w-full px-3 py-2 rounded-lg bg-surface border border-line text-fg focus:border-indigo-500/40 focus:outline-none text-sm"- /><textarea- value={personaBodyDraft}- onChange={(e) => setPersonaBodyDraft(e.target.value)}- rows={12}- className="w-full font-mono text-xs px-3 py-2 rounded-lg bg-surface border border-line text-fg focus:border-indigo-500/40 focus:outline-none resize-y leading-relaxed"+ value={draft.prompt}+ onChange={(e) => setDraft({ ...draft, prompt: e.target.value })}+ rows={20}+ className={`w-full ${FIELD} mt-1 py-2.5 font-mono text-[13px] resize-y leading-relaxed`}/>- <div className="flex items-center gap-2 flex-wrap">- <button- onClick={async () => {- if (!activePersonaDetail) return;- setSavingPersona(true);- setPersonaError(null);- try {- const updated = await savePersona(activePersonaDetail.slug, personaDisplayNameDraft, personaBodyDraft);- setActivePersonaDetail(updated);- setPersonas(await listPersonas());- } catch (e) {- setPersonaError(e instanceof Error ? e.message : "Save failed");- } finally {- setSavingPersona(false);- }- }}- disabled={savingPersona || !personaBodyDraft.trim()}- className="text-xs px-3 py-1.5 rounded-lg bg-indigo-500/20 border border-indigo-500/30 text-indigo-300 hover:bg-indigo-500/30 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"- >- {savingPersona ? "Saving…" : "Save persona"}- </button>- {activePersonaDetail.is_builtin && activePersonaDetail.is_customized && (- <button- onClick={async () => {- if (!activePersonaDetail) return;- try {- const restored = await resetPersona(activePersonaDetail.slug);- setActivePersonaDetail(restored);- setPersonaBodyDraft(restored.body);- setPersonaDisplayNameDraft(restored.display_name);- setPersonas(await listPersonas());- } catch (e) {- setPersonaError(e instanceof Error ? e.message : "Reset failed");- }- }}- className="text-xs px-3 py-1.5 rounded-lg border border-line-strong text-fg-muted hover:border-amber-500/40 hover:text-amber-400 transition-colors"- >- Reset to built-in- </button>- )}- <button- onClick={async () => {- if (!activePersonaDetail) return;- try {- const duped = await savePersona(- activePersonaDetail.slug + "-copy",- activePersonaDetail.display_name + " (copy)",- personaBodyDraft,- );- const updated = await listPersonas();- setPersonas(updated);- setDraft((d) => d ? { ...d, voice_persona_slug: duped.slug } : d);- } catch (e) {- setPersonaError(e instanceof Error ? e.message : "Duplicate failed");- }- }}- className="text-xs px-3 py-1.5 rounded-lg border border-line-strong text-fg-muted hover:border-fg-muted hover:text-fg transition-colors"- >- Duplicate- </button>- {!activePersonaDetail.is_builtin && (- <button- onClick={async () => {- if (!activePersonaDetail) return;- if (!window.confirm(`Delete persona "${activePersonaDetail.display_name}"?`)) return;- try {- await deletePersona(activePersonaDetail.slug);- const updated = await listPersonas();- setPersonas(updated);- setDraft((d) => d ? { ...d, voice_persona_slug: null } : d);- } catch (e) {- setPersonaError(e instanceof Error ? e.message : "Delete failed");- }- }}- className="text-xs px-3 py-1.5 rounded-lg border border-line-strong text-red-400 hover:border-red-500/40 hover:bg-red-500/10 transition-colors"+ {draft.prompt !== detail.prompt_default && (+ <>+ <p className="mt-2 text-[13px] text-amber-500 leading-relaxed">+ An edited prompt replaces the built-in one, so future updates to+ it won't reach this agent. Additional instructions (Instructions+ tab) don't have that cost.+ </p>+ <Button+ variant="ghost"+ size="sm"+ className="mt-1 -ml-3.5"+ onClick={() => setDraft({ ...draft, prompt: detail.prompt_default })}>- Delete- </button>- )}- </div>+ Restore default prompt in editor+ </Button>+ </>+ )}</div>)}- {/* New persona inline form */}- {newPersonaMode && (- <div className="mt-2 p-4 rounded-lg border border-line-strong bg-surface space-y-3">- <p className="text-xs font-semibold text-fg">New persona</p>- <input- type="text"- value={newPersonaName}- onChange={(e) => setNewPersonaName(e.target.value)}- placeholder="Display name (e.g. Elon Musk)"- className="w-full px-3 py-2 rounded-lg bg-surface-elevated border border-line-strong text-fg text-sm focus:outline-none focus:border-indigo-500/40"- />+ {/* Research focus — specialists only (those with a default scope) */}+ {detail.research_focus_default !== null && (+ <div>+ <div className="flex items-center justify-between mb-1">+ <span className={FIELD_LABEL}>Research focus</span>+ <span className="text-xs text-fg-subtle">+ {(draft.research_focus ?? "").length} chars+ </span>+ </div>+ <p className="text-[13px] text-fg-subtle mb-2 leading-relaxed">+ The domain-scope block appended to this specialist's research+ turn — what external signals it watches. The shared research+ contract (output format, recency / grounding / actionability bars)+ is fixed and not editable here.+ </p><textarea- value={newPersonaBody}- onChange={(e) => setNewPersonaBody(e.target.value)}- rows={6}- placeholder="Voice and style bullets — e.g. '- Direct and engineering-first...'"- className="w-full font-mono text-xs px-3 py-2 rounded-lg bg-surface-elevated border border-line-strong text-fg focus:outline-none focus:border-indigo-500/40 resize-y"+ value={draft.research_focus ?? ""}+ onChange={(e) =>+ setDraft({ ...draft, research_focus: e.target.value })+ }+ rows={10}+ className={`w-full ${FIELD} py-2.5 font-mono text-[13px] resize-y leading-relaxed`}/>- <div className="flex gap-2">- <button- onClick={async () => {- if (!newPersonaName.trim() || !newPersonaBody.trim()) return;- try {- const created = await createPersona(newPersonaName, newPersonaBody);- const updated = await listPersonas();- setPersonas(updated);- setDraft((d) => d ? { ...d, voice_persona_slug: created.slug } : d);- setNewPersonaMode(false);- } catch (e) {- setPersonaError(e instanceof Error ? e.message : "Create failed");- }- }}- disabled={!newPersonaName.trim() || !newPersonaBody.trim()}- className="text-xs px-3 py-1.5 rounded-lg bg-indigo-500/20 border border-indigo-500/30 text-indigo-300 hover:bg-indigo-500/30 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"- >- Create- </button>- <button- onClick={() => setNewPersonaMode(false)}- className="text-xs px-3 py-1.5 rounded-lg border border-line-strong text-fg-muted hover:text-fg transition-colors"+ {draft.research_focus !== detail.research_focus_default && (+ <Button+ variant="ghost"+ size="sm"+ className="mt-1 -ml-3.5"+ onClick={() =>+ setDraft({+ ...draft,+ research_focus: detail.research_focus_default,+ })+ }>- Cancel- </button>- </div>+ Restore default research focus in editor+ </Button>+ )}</div>)}- </div>+ </>)}- {detail.name !== "utility_fast" && (- <div className="rounded-xl border border-line bg-surface px-6 py-5 space-y-3">- <div>- <h3 className="text-sm font-semibold text-fg">Test this draft</h3>- <p className="text-xs text-fg-muted mt-0.5">- Run a one-off query with the unsaved settings above. Nothing is persisted.- </p>- </div>- <textarea- value={testQuery}- onChange={(e) => setTestQuery(e.target.value)}- rows={3}- placeholder="Ask the specialist something…"- className="w-full text-sm px-3 py-2 rounded-lg bg-surface border border-line text-fg focus:border-indigo-500/40 focus:outline-none"- />- <div className="flex items-center gap-2">- <button- onClick={handleTest}- disabled={testing || !testQuery.trim()}- className="text-xs px-3 py-1.5 rounded-lg bg-violet-500/20 border border-violet-500/30 text-violet-300 hover:bg-violet-500/30 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"- >- {testing ? "Running…" : "Run test"}- </button>- {testError && <span className="text-xs text-red-400">{testError}</span>}- </div>- {testResult !== null && (- <div className="rounded-lg border border-line bg-surface px-4 py-3 text-sm text-fg whitespace-pre-wrap">- {testResult}+ {activeTab === "test" && (+ <div className="space-y-3">+ <div>+ <h3 className="text-base font-semibold text-fg">Test this draft</h3>+ <p className="text-sm text-fg-muted mt-0.5">+ Run a one-off query with the unsaved settings in these tabs. Nothing is+ persisted.+ </p></div>- )}- </div>+ <textarea+ value={testQuery}+ onChange={(e) => setTestQuery(e.target.value)}+ rows={3}+ placeholder="Ask the specialist something…"+ className={`w-full ${FIELD} py-2.5 text-[15px]`}+ />+ <div className="flex flex-wrap items-center gap-3">+ <Button variant="secondary" onClick={handleTest} disabled={testing || !testQuery.trim()}>+ {testing ? "Running…" : "Run test"}+ </Button>+ {testError && <span className="text-sm text-red-500">{testError}</span>}+ </div>+ {testResult !== null && (+ <div className="rounded-xl border border-line bg-surface px-4 py-3 text-[15px] text-fg whitespace-pre-wrap">+ {testResult}+ </div>+ )}+ </div>)}- <div className="rounded-xl border border-line bg-surface px-6 py-5">- <button- onClick={() => setHistoryOpen((o) => !o)}- className="flex items-center justify-between w-full text-sm font-semibold text-fg"- >- <span>Version history</span>- <span className="text-xs text-fg-muted">{historyOpen ? "Hide" : "Show"}</span>- </button>- {historyOpen && (- <div className="mt-3 space-y-2 max-h-80 overflow-y-auto">- {history.length === 0 && (- <p className="text-xs text-fg-subtle">No prior versions for this agent.</p>- )}- {history.map((h) => (- <div- key={h.id}- className="flex items-center justify-between rounded-lg border border-line px-3 py-2 text-xs text-fg-muted"- >- <div className="min-w-0">- <p className="font-mono text-[10px] text-fg-subtle">#{h.id} · {h.created_at}</p>- <p className="truncate text-fg-muted mt-0.5">- {[- h.model && `model=${h.model}`,- h.use_deep_reasoning !== null &&- `deep=${h.use_deep_reasoning ? "on" : "off"}`,- h.role && `role=${h.role}`,- h.instructions && `instructions=${h.instructions.slice(0, 60)}…`,- h.prompt && `prompt=${h.prompt.slice(0, 60)}…`,- ]- .filter(Boolean)- .join(" · ") || "(empty override)"}- </p>- </div>- <button- onClick={() => handleRollback(h.id)}- className="text-[10px] px-2 py-1 rounded border border-line-strong text-fg hover:bg-surface-overlay hover:text-fg flex-shrink-0"- >- Restore- </button>+ {activeTab === "history" && (+ <div className="space-y-2">+ <h3 className="text-base font-semibold text-fg">Version history</h3>+ {history.length === 0 && (+ <p className="text-sm text-fg-subtle">No prior versions for this agent.</p>+ )}+ {history.map((h) => (+ <div+ key={h.id}+ className="flex items-center justify-between gap-3 rounded-xl border border-line px-4 py-3 text-sm text-fg-muted"+ >+ <div className="min-w-0">+ <p className="font-mono text-xs text-fg-subtle">#{h.id} · {h.created_at}</p>+ <p className="truncate text-fg-muted mt-0.5">+ {[+ h.model && `model=${h.model}`,+ h.use_deep_reasoning !== null &&+ `deep=${h.use_deep_reasoning ? "on" : "off"}`,+ h.role && `role=${h.role}`,+ h.instructions && `instructions=${h.instructions.slice(0, 60)}…`,+ h.prompt && `prompt=${h.prompt.slice(0, 60)}…`,+ ]+ .filter(Boolean)+ .join(" · ") || "(empty override)"}+ </p></div>- ))}- </div>- )}- </div>+ <Button size="sm" onClick={() => handleRollback(h.id)} className="flex-shrink-0">+ Restore+ </Button>+ </div>+ ))}+ </div>+ )}</div>- ) : (- <p className="text-sm text-fg-muted">Select an agent to edit.</p>- ))}- </div>- </main>+ </div>+ )}+ </SidePanel></div>);}diff --git a/packages/ui/src/app/departments/[slug]/page.tsx b/packages/ui/src/app/departments/[slug]/page.tsxindex e940b8f6..22a0d23b 100644--- a/packages/ui/src/app/departments/[slug]/page.tsx+++ b/packages/ui/src/app/departments/[slug]/page.tsx@@ -1,9 +1,13 @@"use client";import { useParams, useRouter } from "next/navigation";-import { useEffect, useRef, useState } from "react";+import { useEffect, useId, useRef, useState } from "react";import { AddGoalForm, GoalRow } from "@/components/goals/GoalEditor";+import Button from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";+import SectionTabs, { sectionPanelProps } from "@/components/ui/SectionTabs";+import SidePanel from "@/components/ui/SidePanel";import {deleteDepartment,getDepartment,@@ -53,6 +57,23 @@ function cls(...parts: (string | false | undefined)[]) {return parts.filter(Boolean).join(" ");}+// The settings form, one short section at a time.+type SettingsTab = "charter" | "acts" | "numbers" | "channels" | "watched";+const SETTINGS_TABS: { id: SettingsTab; label: string }[] = [+ { id: "charter", label: "Charter" },+ { id: "acts", label: "How it acts" },+ { id: "numbers", label: "Numbers" },+ { id: "channels", label: "Channels" },+ { id: "watched", label: "Watched" },+];++const INPUT_CLS =+ "w-full px-3 rounded-xl bg-surface-input/60 border border-line text-[15px] text-fg placeholder-fg-subtle focus:outline-none focus:border-accent";+const FIELD_CLS = `${INPUT_CLS} h-11`;+const LABEL_CLS = "text-sm text-fg-muted flex flex-col gap-1.5";+const HINT_CLS = "text-[13px] text-fg-subtle";+const SECTION_INTRO_CLS = "text-[15px] text-fg-muted mb-4";+// ---------------------------------------------------------------------------// Main page// ---------------------------------------------------------------------------@@ -84,6 +105,8 @@ export default function DepartmentDetailPage() {// One entity per line in the textarea; split + trimmed on save.watched_entities: "",});+ const [settingsTab, setSettingsTab] = useState<SettingsTab>("charter");+ const settingsTabsId = useId();const [savingSettings, setSavingSettings] = useState(false);const [settingsErr, setSettingsErr] = useState<string | null>(null);@@ -189,6 +212,46 @@ export default function DepartmentDetailPage() {}}, [editingSettings]); // eslint-disable-line react-hooks/exhaustive-deps+ function openSettings() {+ setSettingsTab("charter");+ setEditingSettings(true);+ }++ // Close the settings panel, dropping unsaved changes.+ function cancelSettings() {+ if (!dept || savingSettings) return;+ setSettingsForm({+ authority_level: dept.config.authority_level,+ mission: dept.config.charter.mission,+ cadences: { ...dept.config.cadences },+ headcount: dept.headcount != null ? String(dept.headcount) : "",+ budget_usd: dept.budget_usd != null ? String(dept.budget_usd) : "",+ head_person_id: dept.config.head_person_id,+ slack_channel_id: dept.config.slack_channel_id ?? "",+ discord_channel_id: dept.config.discord_channel_id ?? "",+ telegram_chat_id: dept.config.telegram_chat_id ?? "",+ watched_entities: (dept.config.watched_entities ?? []).join("\n"),+ });+ setSettingsErr(null);+ setEditingSettings(false);+ }++ async function removeDepartment() {+ if (!dept) return;+ if (!window.confirm(+ `Delete "${dept.config.title}"? This will also remove all its Goals and cannot be undone.`+ )) return;+ setDeleting(true);+ setDeleteErr(null);+ try {+ await deleteDepartment(slug);+ router.push("/departments");+ } catch (e) {+ setDeleteErr(e instanceof Error ? e.message : "Delete failed");+ setDeleting(false);+ }+ }+async function saveSettings() {if (!dept) return;setSavingSettings(true);@@ -229,104 +292,216 @@ export default function DepartmentDetailPage() {return (<div className="flex flex-col h-full bg-surface"><main className="flex-1 overflow-y-auto">- <div className="max-w-3xl mx-auto px-4 sm:px-6 py-6">- {loading && <p className="text-fg-muted text-sm">Loading…</p>}+ <div className="max-w-3xl mx-auto px-4 sm:px-6 py-8">+ {loading && <p className="text-fg-muted text-[15px]">Loading…</p>}{error && (- <div className="p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm">+ <div className="p-4 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-500 text-[15px]">{error}</div>)}{dept && (<>{/* Header */}- <div className="flex items-start justify-between mb-6 gap-3">- <div>- <h1 className="text-xl font-semibold text-fg">{dept.config.title}</h1>- <div className="text-xs text-fg-muted mt-1">+ <div className="flex items-start justify-between mb-6 gap-4">+ <div className="min-w-0">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg">{dept.config.title}</h1>+ <div className="text-[15px] text-fg-muted mt-1.5">{dept.config.specialist_key ? (- <>Specialist: <code className="font-mono text-fg">{dept.config.specialist_key}</code></>+ <>Specialist: <code className="font-mono text-sm text-fg">{dept.config.specialist_key}</code></>) : (<span className="italic">Informational department (no specialist agent)</span>)}</div></div><div className="flex items-center gap-2 flex-shrink-0">- <button- onClick={() => {- if (editingSettings) {- // reset- setSettingsForm({- authority_level: dept.config.authority_level,- mission: dept.config.charter.mission,- cadences: { ...dept.config.cadences },- headcount: dept.headcount != null ? String(dept.headcount) : "",- budget_usd: dept.budget_usd != null ? String(dept.budget_usd) : "",- head_person_id: dept.config.head_person_id,- slack_channel_id: dept.config.slack_channel_id ?? "",- discord_channel_id: dept.config.discord_channel_id ?? "",- telegram_chat_id: dept.config.telegram_chat_id ?? "",- watched_entities: (dept.config.watched_entities ?? []).join("\n"),- });- setSettingsErr(null);- }- setEditingSettings((v) => !v);- }}- className="px-3 py-1.5 text-xs rounded-lg border border-line hover:bg-surface-overlay transition-colors"- >- {editingSettings ? "Cancel" : "Edit settings"}- </button>- <button- disabled={deleting}- onClick={async () => {- if (!window.confirm(- `Delete "${dept.config.title}"? This will also remove all its Goals and cannot be undone.`- )) return;- setDeleting(true);- setDeleteErr(null);- try {- await deleteDepartment(slug);- router.push("/departments");- } catch (e) {- setDeleteErr(e instanceof Error ? e.message : "Delete failed");- setDeleting(false);- }- }}- className="px-3 py-1.5 text-xs rounded-lg bg-rose-500/10 hover:bg-rose-500/20 border border-rose-500/30 text-rose-300 disabled:opacity-50 transition-colors"- >- {deleting ? "Deleting…" : "Delete department"}- </button>+ <Button onClick={openSettings}>Edit settings</Button>+ <OverflowMenu+ label={`More actions for ${dept.config.title}`}+ items={[+ {+ label: deleting ? "Deleting…" : "Delete department",+ danger: true,+ disabled: deleting,+ onSelect: () => void removeDepartment(),+ },+ ]}+ /></div></div>{deleteErr && (- <div className="p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm mb-4">+ <div className="p-4 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-500 text-[15px] mb-4">{deleteErr}</div>)}- {/* Settings — three stacked cards in edit mode, single summary card in read mode */}- {editingSettings ? (- <div className="space-y-4 mb-6">- {/* Card 1: Charter */}- <section className="rounded-xl border border-line bg-surface-elevated px-4 py-4">- <h3 className="text-xs font-semibold uppercase tracking-wide text-fg-muted mb-3">Charter</h3>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ {/* Settings summary; Edit settings opens the form in a side panel */}+ <section className="rounded-2xl border border-line bg-surface-elevated px-5 py-2 mb-8">+ <dl className="divide-y divide-line">+ <div className="flex flex-col sm:flex-row sm:items-baseline gap-0.5 sm:gap-4 py-3">+ <dt className="sm:w-40 flex-shrink-0 text-sm text-fg-muted">How it acts</dt>+ <dd className="min-w-0">+ <div className="text-[15px] text-fg">+ {AUTHORITY_META[dept.config.authority_level].label}+ </div>+ <div className="text-sm text-fg-muted mt-0.5">+ {AUTHORITY_META[dept.config.authority_level].hint}+ </div>+ </dd>+ </div>+ {[+ ["Mission", dept.config.charter.mission || "—"],+ ...(dept.config.head_person_id != null+ ? [["Head", people.find((p) => p.id === dept.config.head_person_id)?.full_name ?? `Person #${dept.config.head_person_id}`]]+ : []),+ ...(dept.headcount != null ? [["Headcount", String(dept.headcount)]] : []),+ ...(dept.budget_usd != null ? [["Budget", `$${dept.budget_usd.toLocaleString()}`]] : []),+ ...(dept.config.slack_channel_id ? [["Slack channel", dept.config.slack_channel_id]] : []),+ ...(dept.config.discord_channel_id ? [["Discord channel", dept.config.discord_channel_id]] : []),+ ...(dept.config.telegram_chat_id ? [["Telegram chat", dept.config.telegram_chat_id]] : []),+ ...((dept.config.watched_entities ?? []).length > 0+ ? [["Watched entities", (dept.config.watched_entities ?? []).join(", ")]]+ : []),+ ].map(([label, value]) => (+ <div key={label} className="flex flex-col sm:flex-row sm:items-baseline gap-0.5 sm:gap-4 py-3">+ <dt className="sm:w-40 flex-shrink-0 text-sm text-fg-muted">{label}</dt>+ <dd className="text-[15px] text-fg min-w-0 break-words">{value}</dd>+ </div>+ ))}+ {Object.entries(dept.config.cadences).length > 0 && (+ <div className="flex flex-col sm:flex-row sm:items-baseline gap-1 sm:gap-4 py-3">+ <dt className="sm:w-40 flex-shrink-0 text-sm text-fg-muted">Recurring check-in</dt>+ <dd className="flex flex-wrap gap-1.5 min-w-0">+ {Object.entries(dept.config.cadences).map(([n, s]) => (+ <span key={n} className="px-2.5 py-1 rounded-lg bg-surface-overlay border border-line text-sm font-mono text-fg break-all">+ {n}: {s}+ </span>+ ))}+ </dd>+ </div>+ )}+ </dl>+ </section>++ {/* Charter scope (read-only) */}+ {(dept.config.charter.scope.length > 0 || dept.config.charter.out_of_scope.length > 0) && (+ <section className="mb-8 grid grid-cols-1 sm:grid-cols-2 gap-6">+ {dept.config.charter.scope.length > 0 && (+ <div>+ <h2 className="text-lg font-semibold text-fg mb-2">In scope</h2>+ <ul className="list-disc pl-5 space-y-1.5">+ {dept.config.charter.scope.map((s, i) => (+ <li key={i} className="text-[15px] text-fg">{s}</li>+ ))}+ </ul>+ </div>+ )}+ {dept.config.charter.out_of_scope.length > 0 && (+ <div>+ <h2 className="text-lg font-semibold text-fg mb-2">Out of scope</h2>+ <ul className="list-disc pl-5 space-y-1.5">+ {dept.config.charter.out_of_scope.map((s, i) => (+ <li key={i} className="text-[15px] text-fg-muted">{s}</li>+ ))}+ </ul>+ </div>+ )}+ </section>+ )}++ {/* Goals */}+ <section>+ <div className="flex items-center justify-between gap-3 mb-3">+ <h2 className="text-lg font-semibold text-fg">+ Goals <span className="font-normal text-fg-subtle">{goals.length}</span>+ </h2>+ {!addingGoal && (+ <Button variant="primary" onClick={() => setAddingGoal(true)}>+ Add goal+ </Button>+ )}+ </div>++ <div className="rounded-2xl border border-line bg-surface-elevated px-5">+ {addingGoal && (+ <AddGoalForm+ slug={slug}+ onCreated={(goal) => {+ setGoals((prev) => [...prev, goal]);+ setAddingGoal(false);+ }}+ onCancel={() => setAddingGoal(false)}+ />+ )}+ {goals.length === 0 && !addingGoal ? (+ <p className="py-8 text-[15px] text-fg-muted text-center">+ No Goals yet. Add the first one with Add goal.+ </p>+ ) : (+ goals.map((goal) => (+ <GoalRow+ key={goal.id}+ slug={slug}+ goal={goal}+ onSaved={(updated) =>+ setGoals((prev) => prev.map((g) => (g.id === updated.id ? updated : g)))+ }+ onDeleted={(id) => setGoals((prev) => prev.filter((g) => g.id !== id))}+ onEditingChange={(editing) =>+ setEditingGoalCount((c) => Math.max(0, c + (editing ? 1 : -1)))+ }+ />+ ))+ )}+ </div>+ </section>++ <SidePanel+ open={editingSettings}+ onClose={cancelSettings}+ title="Department settings"+ subtitle={dept.config.title}+ width="lg"+ footer={+ <div className="space-y-2">+ {settingsErr && <p className="text-sm text-rose-500">{settingsErr}</p>}+ <div className="flex gap-2">+ <Button variant="primary" disabled={savingSettings} onClick={saveSettings} className="flex-1 sm:flex-none">+ {savingSettings ? "Saving…" : "Save settings"}+ </Button>+ <Button disabled={savingSettings} onClick={cancelSettings}>+ Cancel+ </Button>+ </div>+ </div>+ }+ >+ <div className="mb-5">+ <SectionTabs+ idBase={settingsTabsId}+ label="Settings sections"+ tabs={SETTINGS_TABS}+ active={settingsTab}+ onChange={setSettingsTab}+ />+ </div>+ <div {...sectionPanelProps(settingsTabsId, settingsTab)}>+ {settingsTab === "charter" && (+ <label className={LABEL_CLS}>Mission<textareavalue={settingsForm.mission}onChange={(e) =>setSettingsForm((f) => ({ ...f, mission: e.target.value }))}- rows={3}- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500 resize-none"+ rows={5}+ className={`${INPUT_CLS} py-2.5 resize-none`}/></label>- </section>+ )}- {/* Card 2: How it acts */}- <section className="rounded-xl border border-line bg-surface-elevated px-4 py-4">- <h3 className="text-xs font-semibold uppercase tracking-wide text-fg-muted mb-3">How it acts</h3>- <div className="space-y-3">- <label className="text-xs text-fg-muted flex flex-col gap-1">+ {settingsTab === "acts" && (+ <div className="space-y-6">+ <label className={LABEL_CLS}>Department head<selectvalue={settingsForm.head_person_id ?? ""}@@ -336,7 +511,7 @@ export default function DepartmentDetailPage() {head_person_id: e.target.value ? Number(e.target.value) : null,}))}- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={FIELD_CLS}><option value="">— None —</option>{people.map((p) => (@@ -345,11 +520,12 @@ export default function DepartmentDetailPage() {</option>))}</select>- <span className="text-[10px] text-fg-muted">+ <span className={HINT_CLS}>The Executive surfaces this person as the department owner in routing decisions.</span></label>- <div className="space-y-1.5">+ <fieldset className="space-y-2">+ <legend className="text-sm text-fg-muted mb-1.5">How it acts</legend>{AUTHORITY_OPTS.map((a) => {const meta = AUTHORITY_META[a];const checked = settingsForm.authority_level === a;@@ -357,10 +533,10 @@ export default function DepartmentDetailPage() {<labelkey={a}className={cls(- "flex items-start gap-2.5 p-2.5 rounded-lg border cursor-pointer transition-colors",+ "flex items-start gap-3 p-3.5 rounded-xl border cursor-pointer transition-colors",checked- ? "border-indigo-500/50 bg-indigo-600/10"- : "border-line hover:border-indigo-500/30 bg-surface-input"+ ? "border-accent/60 bg-accent/10"+ : "border-line hover:border-line-strong bg-surface-elevated")}><input@@ -371,52 +547,52 @@ export default function DepartmentDetailPage() {onChange={() =>setSettingsForm((f) => ({ ...f, authority_level: a }))}- className="mt-0.5 accent-indigo-500 flex-shrink-0"+ className="mt-1 w-4 h-4 accent-indigo-500 flex-shrink-0"/><div className="min-w-0">- <div className="text-xs font-medium text-fg">{meta.label}</div>- <div className="text-[10px] text-fg-muted mt-0.5">{meta.hint}</div>+ <div className="text-[15px] font-medium text-fg">{meta.label}</div>+ <div className="text-sm text-fg-muted mt-0.5">{meta.hint}</div></div></label>);})}- </div>+ </fieldset><div>- <div className="text-xs text-fg-muted mb-1">Recurring check-in</div>+ <div className="text-sm text-fg-muted mb-1.5">Recurring check-in</div>{Object.entries(settingsForm.cadences).map(([name, spec]) => (- <div key={name} className="flex items-center gap-2 mb-1.5">+ <div key={name} className="flex items-center gap-2 mb-2"><inputvalue={name}readOnly- className="flex-1 px-2 py-1.5 rounded-lg bg-surface-input border border-line text-xs font-mono text-fg-muted focus:outline-none"+ aria-label="Check-in name"+ className={`${FIELD_CLS} flex-1 min-w-0 font-mono text-sm text-fg-muted`}/><inputvalue={spec}+ aria-label={`Schedule for ${name}`}onChange={(e) =>setSettingsForm((f) => ({...f,cadences: { ...f.cadences, [name]: e.target.value },}))}- className="flex-1 px-2 py-1.5 rounded-lg bg-surface-input border border-line text-xs font-mono focus:outline-none focus:border-indigo-500"+ className={`${FIELD_CLS} flex-1 min-w-0 font-mono text-sm`}placeholder="daily@09:00"/></div>))}- <p className="text-[10px] text-fg-muted mt-1">- When set, the specialist posts a check-in on this schedule. You'll see it in Today.+ <p className={HINT_CLS}>+ When set, the specialist posts a check-in on this schedule. You'll see it on Home.Examples (UTC): <code className="font-mono">daily@09:00</code>, <code className="font-mono">weekly@mon@09:00</code>, <code className="font-mono">quarterly@01-09:00</code>.</p></div></div>- </section>+ )}- {/* Card 3: Numbers */}- <section className="rounded-xl border border-line bg-surface-elevated px-4 py-4">- <h3 className="text-xs font-semibold uppercase tracking-wide text-fg-muted mb-3">Numbers</h3>- <div className="grid grid-cols-2 gap-2">- <label className="text-xs text-fg-muted flex flex-col gap-1">+ {settingsTab === "numbers" && (+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">+ <label className={LABEL_CLS}>Headcount<inputtype="number"@@ -425,10 +601,10 @@ export default function DepartmentDetailPage() {onChange={(e) =>setSettingsForm((f) => ({ ...f, headcount: e.target.value }))}- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={FIELD_CLS}/></label>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Budget (USD)<inputtype="number"@@ -437,221 +613,85 @@ export default function DepartmentDetailPage() {onChange={(e) =>setSettingsForm((f) => ({ ...f, budget_usd: e.target.value }))}- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- />- </label>- </div>- </section>-- {/* Card 4: Broadcast channels — OE can post to these team rooms */}- <section className="rounded-xl border border-line bg-surface-elevated px-4 py-4">- <h3 className="text-xs font-semibold uppercase tracking-wide text-fg-muted mb-1">Team channels</h3>- <p className="text-[10px] text-fg-muted mb-3">- When set, the Executive can post department-scoped updates to these rooms via{" "}- <code className="font-mono">send_department_message</code>. Leave blank to have OE- fall back to DMing the department head.- </p>- <div className="space-y-2">- <label className="text-xs text-fg-muted flex flex-col gap-1">- Slack channel ID- <input- type="text"- value={settingsForm.slack_channel_id}- onChange={(e) =>- setSettingsForm((f) => ({ ...f, slack_channel_id: e.target.value }))- }- placeholder="C01234ABCDE"- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm font-mono focus:outline-none focus:border-indigo-500"- />- </label>- <label className="text-xs text-fg-muted flex flex-col gap-1">- Discord channel ID- <input- type="text"- value={settingsForm.discord_channel_id}- onChange={(e) =>- setSettingsForm((f) => ({ ...f, discord_channel_id: e.target.value }))- }- placeholder="123456789012345678"- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm font-mono focus:outline-none focus:border-indigo-500"- />- </label>- <label className="text-xs text-fg-muted flex flex-col gap-1">- Telegram chat ID- <input- type="text"- value={settingsForm.telegram_chat_id}- onChange={(e) =>- setSettingsForm((f) => ({ ...f, telegram_chat_id: e.target.value }))- }- placeholder="-1001234567890"- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm font-mono focus:outline-none focus:border-indigo-500"+ className={FIELD_CLS}/></label></div>- </section>-- {/* Card 5: Watched entities — strong grounding for the research watch policy */}- <section className="rounded-xl border border-line bg-surface-elevated px-4 py-4">- <h3 className="text-xs font-semibold uppercase tracking-wide text-fg-muted mb-1">Watched entities</h3>- <p className="text-[10px] text-fg-muted mb-3">- Vendors, competitors or tickers this department cares about, one per line. Named here,- the Executive will start watching their status pages, filings and feeds on its own and- route what it finds to this department and its head.- </p>- <label className="text-xs text-fg-muted flex flex-col gap-1">- Watched entities (one per line)- <textarea- value={settingsForm.watched_entities}- onChange={(e) =>- setSettingsForm((f) => ({ ...f, watched_entities: e.target.value }))- }- rows={4}- placeholder={"Brex\nStripe\nACME"}- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- />- </label>- </section>-- {settingsErr && <p className="text-xs text-rose-300">{settingsErr}</p>}- <button- disabled={savingSettings}- onClick={saveSettings}- className="px-4 py-1.5 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white disabled:opacity-50"- >- {savingSettings ? "Saving…" : "Save settings"}- </button>- </div>- ) : (- <section className="rounded-xl border border-line bg-surface-elevated px-4 py-4 mb-6">- <div className="divide-y divide-line">- <div className="flex items-start gap-3 py-2">- <div className="w-36 flex-shrink-0 text-xs text-fg-muted pt-0.5">How it acts</div>- <div>- <div className="text-sm text-fg">- {AUTHORITY_META[dept.config.authority_level].label}- </div>- <div className="text-[10px] text-fg-muted mt-0.5">- {AUTHORITY_META[dept.config.authority_level].hint}- </div>- </div>- </div>- {[- ["Mission", dept.config.charter.mission || "—"],- ...(dept.config.head_person_id != null- ? [["Head", people.find((p) => p.id === dept.config.head_person_id)?.full_name ?? `Person #${dept.config.head_person_id}`]]- : []),- ...(dept.headcount != null ? [["Headcount", String(dept.headcount)]] : []),- ...(dept.budget_usd != null ? [["Budget", `$${dept.budget_usd.toLocaleString()}`]] : []),- ...(dept.config.slack_channel_id ? [["Slack channel", dept.config.slack_channel_id]] : []),- ...(dept.config.discord_channel_id ? [["Discord channel", dept.config.discord_channel_id]] : []),- ...(dept.config.telegram_chat_id ? [["Telegram chat", dept.config.telegram_chat_id]] : []),- ...((dept.config.watched_entities ?? []).length > 0- ? [["Watched entities", (dept.config.watched_entities ?? []).join(", ")]]- : []),- ].map(([label, value]) => (- <div key={label} className="flex items-start gap-3 py-2">- <div className="w-36 flex-shrink-0 text-xs text-fg-muted pt-0.5">{label}</div>- <div className="text-sm text-fg">{value}</div>- </div>- ))}- {Object.entries(dept.config.cadences).length > 0 && (- <div className="flex items-start gap-3 py-2">- <div className="w-36 flex-shrink-0 text-xs text-fg-muted pt-0.5">Recurring check-in</div>- <div className="flex flex-wrap gap-1.5">- {Object.entries(dept.config.cadences).map(([n, s]) => (- <span key={n} className="px-2 py-0.5 rounded bg-surface-overlay border border-line text-xs font-mono text-fg">- {n}: {s}- </span>- ))}- </div>- </div>- )}- </div>- </section>- )}-- {/* Charter scope (read-only) */}- {(dept.config.charter.scope.length > 0 || dept.config.charter.out_of_scope.length > 0) && (- <section className="mb-6 grid grid-cols-1 sm:grid-cols-2 gap-4">- {dept.config.charter.scope.length > 0 && (- <div>- <h2 className="text-xs font-semibold uppercase tracking-wide text-fg-muted mb-2">In Scope</h2>- <ul className="list-disc list-inside space-y-1">- {dept.config.charter.scope.map((s, i) => (- <li key={i} className="text-sm text-fg">{s}</li>- ))}- </ul>- </div>- )}- {dept.config.charter.out_of_scope.length > 0 && (- <div>- <h2 className="text-xs font-semibold uppercase tracking-wide text-fg-muted mb-2">Out of Scope</h2>- <ul className="list-disc list-inside space-y-1">- {dept.config.charter.out_of_scope.map((s, i) => (- <li key={i} className="text-sm text-fg-muted">{s}</li>- ))}- </ul>- </div>)}- </section>- )}- {/* Goals */}- <section>- <div className="flex items-center justify-between mb-3">- <h2 className="text-xs font-semibold uppercase tracking-wide text-fg-muted">- Goals ({goals.length})- </h2>- {!addingGoal && (- <button- onClick={() => setAddingGoal(true)}- className="px-3 py-1 text-xs rounded-lg bg-indigo-600/20 hover:bg-indigo-600/30 text-indigo-300 border border-indigo-500/30"- >- + Add Goal- </button>+ {/* Broadcast channels — OE can post to these team rooms */}+ {settingsTab === "channels" && (+ <>+ <p className={SECTION_INTRO_CLS}>+ When set, the Executive can post department-scoped updates to these rooms via{" "}+ <code className="font-mono text-sm">send_department_message</code>. Leave blank to have OE+ fall back to DMing the department head.+ </p>+ <div className="space-y-4">+ <label className={LABEL_CLS}>+ Slack channel ID+ <input+ type="text"+ value={settingsForm.slack_channel_id}+ onChange={(e) =>+ setSettingsForm((f) => ({ ...f, slack_channel_id: e.target.value }))+ }+ placeholder="C01234ABCDE"+ className={`${FIELD_CLS} font-mono`}+ />+ </label>+ <label className={LABEL_CLS}>+ Discord channel ID+ <input+ type="text"+ value={settingsForm.discord_channel_id}+ onChange={(e) =>+ setSettingsForm((f) => ({ ...f, discord_channel_id: e.target.value }))+ }+ placeholder="123456789012345678"+ className={`${FIELD_CLS} font-mono`}+ />+ </label>+ <label className={LABEL_CLS}>+ Telegram chat ID+ <input+ type="text"+ value={settingsForm.telegram_chat_id}+ onChange={(e) =>+ setSettingsForm((f) => ({ ...f, telegram_chat_id: e.target.value }))+ }+ placeholder="-1001234567890"+ className={`${FIELD_CLS} font-mono`}+ />+ </label>+ </div>+ </>)}- </div>- <div className="rounded-xl border border-line bg-surface-elevated px-4">- {addingGoal && (- <AddGoalForm- slug={slug}- onCreated={(goal) => {- setGoals((prev) => [...prev, goal]);- setAddingGoal(false);- }}- onCancel={() => setAddingGoal(false)}- />- )}- {goals.length === 0 && !addingGoal ? (- <p className="py-6 text-sm text-fg-muted text-center">- No Goals yet.{" "}- <button- onClick={() => setAddingGoal(true)}- className="text-indigo-400 hover:underline"- >- Add one →- </button>- </p>- ) : (- goals.map((goal) => (- <GoalRow- key={goal.id}- slug={slug}- goal={goal}- onSaved={(updated) =>- setGoals((prev) => prev.map((g) => (g.id === updated.id ? updated : g)))- }- onDeleted={(id) => setGoals((prev) => prev.filter((g) => g.id !== id))}- onEditingChange={(editing) =>- setEditingGoalCount((c) => Math.max(0, c + (editing ? 1 : -1)))- }- />- ))+ {/* Watched entities — strong grounding for the research watch policy */}+ {settingsTab === "watched" && (+ <>+ <p className={SECTION_INTRO_CLS}>+ Vendors, competitors or tickers this department cares about, one per line. Named here,+ the Executive will start watching their status pages, filings and feeds on its own and+ route what it finds to this department and its head.+ </p>+ <label className={LABEL_CLS}>+ Watched entities (one per line)+ <textarea+ value={settingsForm.watched_entities}+ onChange={(e) =>+ setSettingsForm((f) => ({ ...f, watched_entities: e.target.value }))+ }+ rows={6}+ placeholder={"Brex\nStripe\nACME"}+ className={`${INPUT_CLS} py-2.5`}+ />+ </label>+ </>)}</div>- </section>+ </SidePanel></>)}</div>diff --git a/packages/ui/src/app/departments/page.tsx b/packages/ui/src/app/departments/page.tsxindex a9836cbb..c828d0cf 100644--- a/packages/ui/src/app/departments/page.tsx+++ b/packages/ui/src/app/departments/page.tsx@@ -3,6 +3,9 @@import Link from "next/link";import { useEffect, useRef, useState } from "react";+import { GoalStatusPill } from "@/components/goals/GoalEditor";+import Button from "@/components/ui/Button";+import SidePanel from "@/components/ui/SidePanel";import {createDepartment,listDepartments,@@ -16,25 +19,14 @@ const AUTHORITY_LABELS: Record<string, string> = {escalate: "Escalate",};-const AUTHORITY_COLORS: Record<string, string> = {- auto_execute: "bg-emerald-500/20 text-emerald-300 border-emerald-500/30",- propose_only: "bg-sky-500/20 text-sky-300 border-sky-500/30",- escalate: "bg-amber-500/20 text-amber-300 border-amber-500/30",+const AUTHORITY_DOT: Record<string, string> = {+ auto_execute: "bg-emerald-500",+ propose_only: "bg-sky-500",+ escalate: "bg-amber-500",};-function StatusPill({ status }: { status: string }) {- const cls =- status === "on_track"- ? "bg-emerald-500/20 text-emerald-300 border-emerald-500/30"- : status === "at_risk"- ? "bg-amber-500/20 text-amber-300 border-amber-500/30"- : "bg-rose-500/20 text-rose-300 border-rose-500/30";- return (- <span className={`inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium ${cls}`}>- {status.replace("_", " ")}- </span>- );-}+const INPUT_CLS =+ "w-full px-3 rounded-xl bg-surface-input/60 border border-line text-[15px] text-fg placeholder-fg-subtle focus:outline-none focus:border-accent";interface AddDepartmentModalProps {onCreated: (dept: DepartmentState) => void;@@ -48,7 +40,9 @@ function AddDepartmentModal({ onCreated, onCancel }: AddDepartmentModalProps) {const titleRef = useRef<HTMLInputElement>(null);useEffect(() => {- titleRef.current?.focus();+ // After the panel has taken focus, so closing it returns focus to the opener.+ const id = requestAnimationFrame(() => titleRef.current?.focus());+ return () => cancelAnimationFrame(id);}, []);async function handleCreate() {@@ -65,49 +59,46 @@ function AddDepartmentModal({ onCreated, onCancel }: AddDepartmentModalProps) {}return (- <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">- <div className="w-full max-w-md bg-surface-elevated rounded-xl border border-line p-6 space-y-4">- <h2 className="text-sm font-semibold text-fg">New Department</h2>- <label className="text-xs text-fg-muted flex flex-col gap-1">- <span>Name <span className="text-rose-400">*</span></span>+ <SidePanel+ open+ onClose={saving ? () => {} : onCancel}+ title="New department"+ footer={+ <div className="flex gap-2">+ <Button variant="primary" disabled={saving || !form.title.trim()} onClick={handleCreate} className="flex-1">+ {saving ? "Creating…" : "Create"}+ </Button>+ <Button disabled={saving} onClick={onCancel}>+ Cancel+ </Button>+ </div>+ }+ >+ <div className="space-y-4">+ <label className="text-sm text-fg-muted flex flex-col gap-1.5">+ <span>Name <span className="text-rose-500">*</span></span><inputref={titleRef}value={form.title}onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))}onKeyDown={(e) => { if (e.key === "Enter" && form.title.trim()) handleCreate(); }}- className="px-2 py-1.5 rounded-lg bg-surface border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={`${INPUT_CLS} h-11`}placeholder="Customer Success"/></label>- <label className="text-xs text-fg-muted flex flex-col gap-1">- <span>Mission <span className="text-fg-muted/60">(optional)</span></span>+ <label className="text-sm text-fg-muted flex flex-col gap-1.5">+ <span>Mission <span className="text-fg-subtle">(optional)</span></span><textareavalue={form.mission}onChange={(e) => setForm((f) => ({ ...f, mission: e.target.value }))}- rows={3}- className="px-2 py-1.5 rounded-lg bg-surface border border-line text-sm focus:outline-none focus:border-indigo-500 resize-none"+ rows={4}+ className={`${INPUT_CLS} py-2.5 resize-none`}placeholder="What does this department own?"/></label>- {err && <p className="text-xs text-rose-300">{err}</p>}- <div className="flex gap-2">- <button- disabled={saving || !form.title.trim()}- onClick={handleCreate}- className="px-4 py-1.5 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white disabled:opacity-50"- >- {saving ? "Creating…" : "Create"}- </button>- <button- disabled={saving}- onClick={onCancel}- className="px-3 py-1.5 text-sm rounded-lg border border-line hover:bg-surface-overlay disabled:opacity-50"- >- Cancel- </button>- </div>+ {err && <p className="text-sm text-rose-500">{err}</p>}</div>- </div>+ </SidePanel>);}@@ -127,23 +118,22 @@ export default function DepartmentsPage() {return (<div className="flex flex-col h-full bg-surface"><main className="flex-1 overflow-y-auto">- <div className="max-w-5xl mx-auto px-4 sm:px-6 py-6">- <div className="flex items-center justify-between mb-1">- <h1 className="text-xl font-semibold text-fg">Departments</h1>- <button- onClick={() => setAddingDept(true)}- className="px-3 py-1.5 text-xs rounded-lg bg-indigo-600/20 hover:bg-indigo-600/30 text-indigo-300 border border-indigo-500/30"- >- + Add department- </button>+ <div className="max-w-5xl mx-auto px-4 sm:px-6 py-8">+ <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between mb-8">+ <div className="min-w-0">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg">Departments</h1>+ <p className="text-[15px] text-fg-muted mt-2">+ Each department wraps a specialist agent with persistent Goals, authority level, and cadences.+ </p>+ </div>+ <Button variant="primary" onClick={() => setAddingDept(true)} className="flex-shrink-0 self-start">+ Add department+ </Button></div>- <p className="text-sm text-fg-muted mb-6">- Each department wraps a specialist agent with persistent Goals, authority level, and cadences.- </p>- {loading && <p className="text-fg-muted text-sm">Loading…</p>}+ {loading && <p className="text-fg-muted text-[15px]">Loading…</p>}{error && (- <div className="p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm mb-4">+ <div className="p-4 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-500 text-[15px] mb-4">{error}</div>)}@@ -153,31 +143,29 @@ export default function DepartmentsPage() {const cfg = ds.config;const atRisk = ds.goals.filter((g) => g.status === "at_risk").length;const offTrack = ds.goals.filter((g) => g.status === "off_track").length;- const authCls = AUTHORITY_COLORS[cfg.authority_level] ?? "bg-surface-input/40 text-fg border-line";return (<Linkkey={cfg.slug}href={`/departments/${cfg.slug}`}- className="block rounded-xl border border-line bg-surface-elevated hover:bg-surface-overlay transition-colors p-4 group"+ className="flex flex-col rounded-2xl border border-line bg-surface-elevated hover:bg-surface-hover hover:border-line-strong transition-colors p-5 group focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60">- <div className="flex items-start justify-between gap-2 mb-2">- <div>- <div className="text-sm font-semibold text-fg group-hover:text-indigo-300 transition-colors">- {cfg.title}- </div>- <div className="text-xs text-fg-muted mt-0.5">{cfg.charter.mission.slice(0, 80)}{cfg.charter.mission.length > 80 ? "…" : ""}</div>+ <div className="flex items-start justify-between gap-3">+ <div className="text-lg font-semibold text-fg group-hover:text-accent transition-colors min-w-0">+ {cfg.title}</div>- <span className={`flex-shrink-0 inline-block px-2 py-0.5 rounded border text-[10px] font-medium ${authCls}`}>+ <span className="flex-shrink-0 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-line text-[13px] font-medium text-fg">+ <span aria-hidden="true" className={`h-2 w-2 rounded-full ${AUTHORITY_DOT[cfg.authority_level] ?? "bg-fg-subtle"}`} />{AUTHORITY_LABELS[cfg.authority_level] ?? cfg.authority_level}</span></div>+ <div className="text-[15px] text-fg-muted mt-1.5">{cfg.charter.mission.slice(0, 80)}{cfg.charter.mission.length > 80 ? "…" : ""}</div>- <div className="flex items-center gap-3 mt-3 text-xs text-fg-muted">- <span>{ds.goals.length} Goal{ds.goals.length !== 1 ? "s" : ""}</span>- {atRisk > 0 && <StatusPill status="at_risk" />}- {offTrack > 0 && <StatusPill status="off_track" />}+ <div className="flex flex-wrap items-center gap-2 mt-4 text-sm text-fg-muted">+ <span className="mr-1">{ds.goals.length} Goal{ds.goals.length !== 1 ? "s" : ""}</span>+ {atRisk > 0 && <GoalStatusPill status="at_risk" />}+ {offTrack > 0 && <GoalStatusPill status="off_track" />}{ds.goals.length > 0 && atRisk === 0 && offTrack === 0 && (- <StatusPill status="on_track" />+ <GoalStatusPill status="on_track" />)}</div></Link>diff --git a/packages/ui/src/app/globals.css b/packages/ui/src/app/globals.cssindex 2094b327..4f2de7c2 100644--- a/packages/ui/src/app/globals.css+++ b/packages/ui/src/app/globals.css@@ -1,5 +1,3 @@-@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap');-@import "tailwindcss";@config "../../tailwind.config.ts";@@ -64,7 +62,7 @@height: 100%;background-color: rgb(var(--surface-base));color: rgb(var(--fg));- font-family: 'Inter', system-ui, sans-serif;+ font-family: var(--font-sans), system-ui, -apple-system, "Segoe UI", sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;}diff --git a/packages/ui/src/app/goals/page.tsx b/packages/ui/src/app/goals/page.tsxindex a9a484a8..0badaf65 100644--- a/packages/ui/src/app/goals/page.tsx+++ b/packages/ui/src/app/goals/page.tsx@@ -2,7 +2,8 @@import { useEffect, useMemo, useState } from "react";-import { AddGoalForm, GOAL_STATUS_COLORS, GoalRow } from "@/components/goals/GoalEditor";+import { AddGoalForm, GoalRow, GoalStatusPill, goalStatusLabel } from "@/components/goals/GoalEditor";+import Button from "@/components/ui/Button";import { useWorkspace } from "@/components/workspace/WorkspaceContext";import { listDepartments, type DepartmentState } from "@/lib/api";import { applyGoalChange, groupGoalsByArea } from "@/lib/goalAreas";@@ -13,12 +14,6 @@ import { applyGoalChange, groupGoalsByArea } from "@/lib/goalAreas";// slug-scoped goal routes a department's own page uses. Team mode links it// too, and the copy says "department" there.-const STATUS_LABEL: Record<string, string> = {- on_track: "on track",- at_risk: "at risk",- off_track: "off track",-};-export default function GoalsPage() {const [departments, setDepartments] = useState<DepartmentState[] | null>(null);const [error, setError] = useState<string | null>(null);@@ -45,7 +40,7 @@ export default function GoalsPage() {const total = grouped.withGoals.reduce((n, a) => n + a.goals.length, 0);const summary = (["off_track", "at_risk", "on_track"] as const).filter((s) => grouped.counts[s] > 0)- .map((s) => `${grouped.counts[s]} ${STATUS_LABEL[s]}`)+ .map((s) => `${grouped.counts[s]} ${goalStatusLabel(s)}`).join(" · ");// Open the form on the first area that already has goals, else the first area.@@ -54,35 +49,33 @@ export default function GoalsPage() {return (<div className="flex flex-col h-full bg-surface"><main className="flex-1 overflow-y-auto">- <div className="max-w-3xl mx-auto px-4 sm:px-6 py-6">- <div className="flex items-center justify-between gap-3 mb-1">- <h1 className="text-xl font-semibold text-fg">Goals</h1>+ <div className="max-w-3xl mx-auto px-4 sm:px-6 py-8">+ <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between mb-8">+ <div className="min-w-0">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg">Goals</h1>+ <p className="text-[15px] text-fg-muted mt-2">+ What you're working towards, grouped by {unit}. Tell the Executive how a goal is+ going in chat and it updates the goal for you.+ </p>+ </div>{departments && grouped.all.length > 0 && addingTo === null && (- <button- type="button"- onClick={() => setAddingTo(defaultArea)}- className="px-3 py-1.5 text-xs rounded-lg bg-indigo-600/20 hover:bg-indigo-600/30 text-indigo-300 border border-indigo-500/30 cursor-pointer"- >- + Add goal- </button>+ <Button variant="primary" onClick={() => setAddingTo(defaultArea)} className="flex-shrink-0 self-start">+ Add goal+ </Button>)}</div>- <p className="text-sm text-fg-muted mb-6">- What you're working towards, grouped by {unit}. Tell the Executive how a goal is- going in chat and it updates the goal for you.- </p>- {!departments && !error && <p className="text-fg-muted text-sm">Loading…</p>}+ {!departments && !error && <p className="text-fg-muted text-[15px]">Loading…</p>}{error && (- <div className="p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm mb-4">+ <div className="p-4 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-500 text-[15px] mb-4">{error}</div>)}{departments && (- <div className="space-y-6">+ <div className="space-y-8">{addingTo !== null && (- <div className="rounded-xl border border-line bg-surface-elevated px-4">+ <div className="rounded-2xl border border-line bg-surface-elevated px-5"><AddGoalFormkey={addingTo}slug={addingTo}@@ -98,29 +91,25 @@ export default function GoalsPage() {)}{grouped.all.length === 0 ? (- <p className="text-sm text-fg-muted">+ <p className="text-[15px] text-fg-muted">{mode === "solo"? "There are no areas to put goals in yet. Areas come with your profile — finish setup first.": "There are no departments to put goals in yet. Add one on the Departments page first."}</p>) : total === 0 && addingTo === null ? (- <div className="rounded-xl border border-line bg-surface-elevated p-6 text-center">- <p className="text-sm text-fg">No goals yet.</p>- <p className="text-xs text-fg-muted mt-1">+ <div className="rounded-2xl border border-line bg-surface-elevated p-8 text-center">+ <p className="text-base font-medium text-fg">No goals yet.</p>+ <p className="text-[15px] text-fg-muted mt-1">Add the first thing you're working towards — just type it; thetimeframe defaults to this quarter.</p>- <button- type="button"- onClick={() => setAddingTo(defaultArea)}- className="mt-3 text-xs text-indigo-400 hover:text-indigo-300 cursor-pointer"- >- Add a goal →- </button>+ <Button variant="primary" onClick={() => setAddingTo(defaultArea)} className="mt-5">+ Add a goal+ </Button></div>) : (total > 0 && (- <p className="text-xs text-fg-muted">+ <p className="text-[15px] text-fg-muted">{total} goal{total === 1 ? "" : "s"}{summary && <> · {summary}</>}</p>@@ -129,16 +118,14 @@ export default function GoalsPage() {{grouped.withGoals.map((area) => (<section key={area.slug}>- <div className="flex items-center justify-between gap-3 mb-2">- <h2 className="text-xs font-semibold uppercase tracking-wide text-fg-muted">+ <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-2 mb-3">+ <h2 className="text-lg font-semibold text-fg">{area.title}{" "}- <span className="font-normal normal-case tracking-normal">- ({area.goals.length})- </span>+ <span className="font-normal text-fg-subtle">{area.goals.length}</span></h2><StatusDots goals={area.goals} /></div>- <div className="rounded-xl border border-line bg-surface-elevated px-4">+ <div className="rounded-2xl border border-line bg-surface-elevated px-5">{area.goals.map((goal) => (<GoalRowkey={goal.id}@@ -160,9 +147,8 @@ export default function GoalsPage() {{grouped.empty.length > 0 && total > 0 && (<section>- <h2 className="text-xs font-semibold uppercase tracking-wide text-fg-muted mb-2">- Other {unit}s- </h2>+ <h2 className="text-lg font-semibold text-fg mb-1">Other {unit}s</h2>+ <p className="text-[15px] text-fg-muted mb-3">No goals yet. Pick one to add its first goal.</p><div className="flex flex-wrap gap-2">{grouped.empty.map((a) => (<button@@ -170,7 +156,7 @@ export default function GoalsPage() {type="button"onClick={() => setAddingTo(a.slug)}title={`Add a goal to ${a.title}`}- className="px-2.5 py-1 rounded-full border border-line text-xs text-fg-muted hover:text-fg hover:border-line-strong transition-colors cursor-pointer"+ className="h-10 px-4 rounded-full border border-line bg-surface-elevated text-[15px] text-fg-muted hover:text-fg hover:border-line-strong transition-colors cursor-pointer">+ {a.title}</button>@@ -186,24 +172,16 @@ export default function GoalsPage() {);}-// One small pill per status present in the area, worst first.+// One pill per status present in the area, worst first.function StatusDots({ goals }: { goals: DepartmentState["goals"] }) {const present = (["off_track", "at_risk", "on_track"] as const).filter((s) =>goals.some((g) => g.status === s),);return (- <div className="flex items-center gap-1.5 flex-shrink-0">- {present.map((s) => {- const n = goals.filter((g) => g.status === s).length;- return (- <span- key={s}- className={`inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium ${GOAL_STATUS_COLORS[s]}`}- >- {n} {STATUS_LABEL[s]}- </span>- );- })}+ <div className="flex flex-wrap items-center gap-1.5">+ {present.map((s) => (+ <GoalStatusPill key={s} status={s} count={goals.filter((g) => g.status === s).length} />+ ))}</div>);}diff --git a/packages/ui/src/app/guide/page.tsx b/packages/ui/src/app/guide/page.tsxindex a6e3fa10..68fd4f53 100644--- a/packages/ui/src/app/guide/page.tsx+++ b/packages/ui/src/app/guide/page.tsx@@ -13,7 +13,7 @@ const SECTIONS = [{ id: 'ask_oe', label: 'Ask OE', sub: 'The page-aware assistant panel — explains any screen and fills forms for you to review.' },{ id: 'today', label: 'Today / Morning Brief', sub: 'What needs you right now: proposals, department health, and people with open items.' },{ id: 'pulse', label: 'Pulse (Memory)', sub: "The Executive's running memory — decisions made, initiatives in flight, advice gathered, corrections kept." },- { id: 'review', label: 'Review Queue', sub: 'Now inside the Knowledge base. Built-in knowledge is trusted by default. Review what you upload or edit, or send a domain for review yourself.' },+ { id: 'review', label: 'Review Queue', sub: 'On Knowledge, under Advanced. Built-in knowledge is trusted by default. Review what you upload or edit, or send a domain for review yourself.' },{ id: 'jobs', label: 'Workflows', sub: 'Multi-step workflows that produce a deliverable — board prep, GTM plan, perf review.' },{ id: 'artifacts', label: 'Documents', sub: 'Your library of finished documents — drafts and workflow outputs in one place.' },{ id: 'watchlist', label: 'Watch List', sub: 'External monitors — stock tickers, RSS feeds, status pages, web queries — that raise alerts.' },@@ -28,7 +28,7 @@ const SECTIONS = [{ id: 'simulator', label: 'Company Simulator', sub: 'Load a realistic test company to try the Executive before trusting it with real data.' },{ id: 'clients', label: 'Client Companies', sub: 'Multi-client mode for fractional work — switch the live company between named client slots.' },{ id: 'integrations', label: 'Integrations', sub: 'Reach the Executive where you already work — Slack, Discord, Telegram, email, Google Chat, MCP.' },- { id: 'settings', label: 'Settings & Advanced', sub: 'The hub for power-user tools that sit outside the day-to-day nav — including this guide.' },+ { id: 'settings', label: 'Settings & Advanced', sub: 'Your Executive, workspace, Act as me, and the Advanced tools outside the day-to-day nav — including this guide.' },];interface SectionMeta {diff --git a/packages/ui/src/app/jobs/[name]/page.tsx b/packages/ui/src/app/jobs/[name]/page.tsxindex 8ffbb2c6..dae11b5f 100644--- a/packages/ui/src/app/jobs/[name]/page.tsx+++ b/packages/ui/src/app/jobs/[name]/page.tsx@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useParams, useSearchParams } from "next/navigation";import Link from "next/link";import WorkflowRunner from "@/components/WorkflowRunner";+import Button from "@/components/ui/Button";import ApprovedTargets from "@/components/jobs/ApprovedTargets";import PendingWorkflowReview from "@/components/jobs/PendingWorkflowReview";import {@@ -234,14 +235,17 @@ export default function JobDetailPage() {<main className="flex-1 overflow-y-auto px-4 sm:px-6 py-8"><div className="max-w-3xl mx-auto space-y-8"><div>- <h1 className="text-2xl font-semibold text-fg mb-1">+ <Link href="/jobs" className="text-sm text-fg-muted hover:text-fg">+ ← Workflows+ </Link>+ <h1 className="mt-2 mb-2 text-2xl sm:text-3xl font-bold tracking-tight text-fg">{workflow.title}</h1>- <p className="text-sm text-fg-muted leading-relaxed">+ <p className="text-[15px] text-fg-muted leading-relaxed">{workflow.description}</p>{(workflow.playbooks?.length ?? 0) > 0 && (- <p className="mt-2 text-xs text-fg-muted">+ <p className="mt-2 text-sm text-fg-muted">Follows{" "}{workflow.playbooks!.length === 1 ? "playbook" : "playbooks"}:{" "}{workflow.playbooks!.map((p, i) => (@@ -249,7 +253,7 @@ export default function JobDetailPage() {{i > 0 && ", "}<Linkhref={`/jobs?tab=playbooks&playbook=${encodeURIComponent(p)}`}- className="text-indigo-400 hover:underline"+ className="text-accent hover:underline">{p}</Link>@@ -261,19 +265,21 @@ export default function JobDetailPage() {</div>{!running && (- <form onSubmit={handleSubmit} className="space-y-5">- <div className="flex items-center justify-between rounded-md border border-line bg-surface/40 px-3 py-2">- <div className="text-xs text-fg-muted leading-relaxed">- Stuck on how to fill this out? Load a realistic sample to- see what good inputs look like. You can edit anything- before running.- </div>+ <form+ onSubmit={handleSubmit}+ className="space-y-6 rounded-2xl border border-line bg-surface-elevated p-5 shadow-sm sm:p-7"+ >+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h2 className="text-lg font-semibold text-fg">What it needs</h2>+ {/* Fills every field with a realistic sample; each field's+ own "Use example" fills just that one. */}<buttontype="button"onClick={handleLoadSample}- className="ml-3 shrink-0 text-xs text-indigo-300 hover:text-indigo-200 underline underline-offset-2"+ title="Load a realistic sample to see what good inputs look like. You can edit anything before running."+ className="min-h-10 rounded-lg px-2 text-[15px] font-semibold text-accent hover:underline underline-offset-4 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/60">- Load sample run+ Fill with an example</button></div>@@ -281,7 +287,7 @@ export default function JobDetailPage() {<divrole="status"aria-live="polite"- className="flex items-start justify-between gap-3 rounded-md border border-indigo-500/30 bg-indigo-500/10 px-3 py-2 text-xs text-indigo-200"+ className="flex items-start justify-between gap-3 rounded-xl border border-accent/30 bg-accent/10 px-4 py-2.5 text-sm text-fg"><span>{prefillBanner === "suggestion"@@ -292,7 +298,7 @@ export default function JobDetailPage() {type="button"onClick={() => setPrefillBanner(null)}aria-label="Dismiss notice"- className="shrink-0 text-indigo-300 hover:text-indigo-100 focus:outline-none focus-visible:ring-1 focus-visible:ring-indigo-300 rounded px-1"+ className="shrink-0 -my-1 h-8 w-8 rounded-lg text-fg-muted hover:text-fg hover:bg-surface-overlay focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/60">×</button>@@ -310,10 +316,10 @@ export default function JobDetailPage() {(schema.examples[0] as string).length > 0;return (<div key={fieldName}>- <div className="flex items-baseline justify-between mb-1">+ <div className="flex items-baseline justify-between gap-3 mb-1.5"><labelhtmlFor={inputId}- className="block text-sm font-medium text-fg"+ className="block text-[15px] font-semibold text-fg">{fieldLabel(fieldName, schema)}{isRequired && (@@ -325,14 +331,14 @@ export default function JobDetailPage() {type="button"onClick={() => handleInsertExample(fieldName, schema)}aria-label={`Insert example value for ${fieldLabel(fieldName, schema)}`}- className="text-[11px] text-fg-muted hover:text-indigo-300 focus:outline-none focus-visible:ring-1 focus-visible:ring-indigo-400 rounded px-1 transition"+ className="shrink-0 text-sm text-fg-muted hover:text-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/60 rounded px-1 transition">- Insert example+ Use example</button>)}</div>{schema.description && (- <p className="text-xs text-fg-muted mb-2 leading-relaxed">+ <p className="text-sm text-fg-muted mb-2 leading-relaxed">{schema.description}</p>)}@@ -348,7 +354,7 @@ export default function JobDetailPage() {? String(schema.examples[0]): ""}- className="w-full rounded-md bg-surface/60 border border-line focus:border-indigo-500 focus:outline-none text-sm text-fg px-3 py-2 placeholder:text-fg-subtle font-mono leading-relaxed"+ className="w-full rounded-xl bg-surface border border-line focus:ring-2 focus:ring-accent/40 focus:outline-none text-[15px] text-fg px-3.5 py-2.5 placeholder:text-fg-subtle leading-relaxed"/>) : (<input@@ -362,24 +368,22 @@ export default function JobDetailPage() {? String(schema.examples[0]): ""}- className="w-full rounded-md bg-surface/60 border border-line focus:border-indigo-500 focus:outline-none text-sm text-fg px-3 py-2 placeholder:text-fg-subtle"+ className="w-full h-11 rounded-xl bg-surface border border-line focus:ring-2 focus:ring-accent/40 focus:outline-none text-[15px] text-fg px-3.5 placeholder:text-fg-subtle"/>)}</div>);})}- <div className="flex items-center gap-3 pt-2">- <button- type="submit"- disabled={!allRequiredFilled}- className="px-4 py-2 rounded-md bg-indigo-600 hover:bg-indigo-500 text-white text-sm font-medium transition disabled:bg-surface-overlay disabled:text-fg-muted disabled:cursor-not-allowed"- >+ <div className="flex flex-wrap items-center gap-3 pt-1">+ <Button type="submit" variant="primary" disabled={!allRequiredFilled} className="px-7">Continue- </button>- <span className="text-xs text-fg-muted">- All fields with * are required.- </span>+ </Button>+ {Object.keys(props).length > 0 && (+ <span className="text-sm text-fg-muted">+ All fields with * are required.+ </span>+ )}</div></form>)}diff --git a/packages/ui/src/app/jobs/new/page.tsx b/packages/ui/src/app/jobs/new/page.tsxindex 38b7e6b9..deaa94c7 100644--- a/packages/ui/src/app/jobs/new/page.tsx+++ b/packages/ui/src/app/jobs/new/page.tsx@@ -4,6 +4,8 @@ import { Suspense, useCallback, useEffect, useState } from "react";import Link from "next/link";import { useRouter, useSearchParams } from "next/navigation";import { useAskOEFormContext } from "@/components/askoe/AskOEContext";+import Button, { buttonClass } from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";import ToolPicker from "@/components/jobs/ToolPicker";import WorkflowWizard from "@/components/jobs/WorkflowWizard";import {@@ -55,8 +57,13 @@ function newStep(kind: StepKind, idx: number): DynamicStep {}const inputCls =- "w-full px-3 py-1.5 text-sm rounded-md bg-surface/60 border border-line text-fg placeholder:text-fg-subtle focus:outline-none focus:ring-1 focus:ring-indigo-500/40";-const labelCls = "block text-xs font-medium text-fg-muted mb-1";+ "w-full px-3.5 py-2.5 text-[15px] rounded-xl bg-surface border border-line text-fg placeholder:text-fg-subtle focus:outline-none focus:ring-2 focus:ring-accent/40 disabled:opacity-60";+const labelCls = "block text-sm font-medium text-fg-muted mb-1.5";++// The editor's sections, shown one at a time. A new workflow walks them in+// order with Next/Back; an existing one (or a wizard draft) can jump between+// them and save from any of them.+const STAGES = ["Details", "Inputs", "Steps", "Schedule"] as const;// ---- Ask OE form descriptor helpers ---------------------------------------@@ -163,6 +170,7 @@ function BuilderInner() {const [cadence, setCadence] = useState("weekly@mon@09:00");const [cadencePersonId, setCadencePersonId] = useState<number>(0);+ const [stage, setStage] = useState(0);const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);const [loading, setLoading] = useState(!!editName || !!designerId);@@ -418,14 +426,52 @@ function BuilderInner() {}if (loading) {- return <div className="text-sm text-fg-muted">Loading…</div>;+ return <div className="text-[15px] text-fg-muted">Loading…</div>;}+ // Editing or refining a draft: every section is already filled in.+ const prefilled = !!editName || !!designerId;+ const last = STAGES.length - 1;+ const saveLabel = saving ? "Saving…" : editName ? "Save changes" : "Create workflow";+ const cancelHref = designerId+ ? `/jobs/new?session=${encodeURIComponent(designerId)}`+ : "/jobs";+return (- <div className="space-y-8">+ <div className="space-y-6">+ <nav aria-label="Sections" className="flex gap-1 overflow-x-auto">+ {STAGES.map((label, i) => (+ <button+ key={label}+ type="button"+ aria-current={stage === i ? "step" : undefined}+ onClick={() => setStage(i)}+ className={`flex min-h-10 flex-shrink-0 items-center gap-2 rounded-xl px-3 sm:px-3.5 text-[15px] font-medium transition-colors ${+ stage === i+ ? "bg-accent/10 text-accent"+ : "text-fg-muted hover:text-fg hover:bg-surface-overlay"+ }`}+ >+ {!prefilled && (+ <span+ aria-hidden="true"+ className={`hidden h-6 w-6 items-center justify-center rounded-full text-xs font-semibold sm:inline-flex ${+ stage === i ? "bg-accent-strong text-white" : "bg-surface-overlay text-fg-muted"+ }`}+ >+ {i + 1}+ </span>+ )}+ {label}+ </button>+ ))}+ </nav>++ <div className="rounded-2xl border border-line bg-surface-elevated p-5 shadow-sm sm:p-7">{/* Metadata */}+ {stage === 0 && (<section className="space-y-4">- <h2 className="text-base font-semibold text-fg">Details</h2>+ <h2 className="text-lg font-semibold text-fg">Details</h2><div className="grid sm:grid-cols-2 gap-4"><div><label className={labelCls}>Name (snake_case, unique)</label>@@ -484,17 +530,17 @@ function BuilderInner() {</div></div></section>+ )}{/* Input fields */}+ {stage === 1 && (<sectionclassName={`space-y-3 rounded-md ${suggestedCls("input_fields")}`}onInput={() => clearSuggested("input_fields")}>- <div className="flex items-center justify-between">- <h2 className="text-base font-semibold text-fg">Input fields</h2>- <button- type="button"- className="text-xs text-indigo-400 hover:text-indigo-300"+ <div className="flex items-center justify-between gap-3">+ <h2 className="text-lg font-semibold text-fg">Input fields</h2>+ <ButtononClick={() =>setFields((fs) => [...fs,@@ -503,19 +549,19 @@ function BuilderInner() {}>+ Add field- </button>+ </Button></div>- <p className="text-xs text-fg-muted">+ <p className="text-sm text-fg-muted">Free-text fields the user fills when running. Reference them in stepgoals with <code>{"{field_name}"}</code>.</p>{fields.length === 0 && (- <p className="text-xs text-fg-subtle">No input fields.</p>+ <p className="text-sm text-fg-subtle">No input fields.</p>)}{fields.map((f, i) => (<divkey={i}- className="rounded-md border border-line bg-surface/30 p-3 grid sm:grid-cols-[1fr_1fr_auto] gap-3 items-end"+ className="rounded-xl border border-line bg-surface p-4 grid sm:grid-cols-[1fr_1fr_auto] gap-3 items-end"><div><label className={labelCls}>Field name</label>@@ -535,63 +581,63 @@ function BuilderInner() {placeholder="Topic"/></div>- <div className="flex items-center gap-3 pb-1.5">- <label className="flex items-center gap-1 text-xs text-fg-muted">+ <div className="flex items-center gap-2">+ <label className="flex min-h-10 items-center gap-2 px-1 text-sm text-fg-muted"><inputtype="checkbox"+ className="h-4 w-4"checked={f.required}onChange={(e) => updateField(i, { required: e.target.checked })}/>Required</label>- <button- type="button"- className="text-xs text-fg-muted hover:text-red-400"- onClick={() => setFields((fs) => fs.filter((_, idx) => idx !== i))}- >- Remove- </button>+ <OverflowMenu+ label={`More for field ${f.label || i + 1}`}+ items={[+ {+ label: "Remove field",+ danger: true,+ onSelect: () => setFields((fs) => fs.filter((_, idx) => idx !== i)),+ },+ ]}+ /></div></div>))}</section>+ )}{/* Steps */}+ {stage === 2 && (<sectionclassName={`space-y-3 rounded-md ${suggestedCls("steps")}`}onInput={() => clearSuggested("steps")}>- <div className="flex items-center justify-between">- <h2 className="text-base font-semibold text-fg">Steps</h2>- <div className="flex gap-2">- <button- type="button"- className="text-xs text-indigo-400 hover:text-indigo-300"+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h2 className="text-lg font-semibold text-fg">Steps</h2>+ <div className="flex flex-wrap gap-2">+ <ButtononClick={() =>setSteps((ss) => [...ss, newStep("specialist", ss.length)])}>+ Specialist- </button>- <button- type="button"- className="text-xs text-indigo-400 hover:text-indigo-300"+ </Button>+ <ButtononClick={() => setSteps((ss) => [...ss, newStep("action", ss.length)])}>+ Action- </button>- <button- type="button"- className="text-xs text-indigo-400 hover:text-indigo-300"+ </Button>+ <ButtononClick={() =>setSteps((ss) => [...ss, newStep("approval_gate", ss.length)])}>+ Approval gate- </button>+ </Button></div></div>- <p className="text-xs text-fg-muted">+ <p className="text-sm text-fg-muted">Steps run in order. <b>Specialist</b> steps analyze and write;{" "}<b>action</b> steps get things done with the tools you choose. The laststep must be a <b>synthesis</b> step that assembles the result. Place any@@ -611,12 +657,16 @@ function BuilderInner() {/>))}</section>+ )}{/* Cadence */}- <section className="space-y-3">- <label className="flex items-center gap-2 text-base font-semibold text-fg">+ {stage === 3 && (+ <section className="space-y-4">+ <h2 className="text-lg font-semibold text-fg">Schedule</h2>+ <label className="flex min-h-10 items-center gap-2.5 text-[15px] font-medium text-fg"><inputtype="checkbox"+ className="h-4 w-4"checked={cadenceEnabled}onChange={(e) => setCadenceEnabled(e.target.checked)}/>@@ -650,37 +700,45 @@ function BuilderInner() {))}</select></div>- <p className="sm:col-span-2 text-xs text-fg-subtle">+ <p className="sm:col-span-2 text-sm text-fg-subtle">Scheduled runs supply no inputs, so a scheduled workflow must haveno <b>required</b> input fields.</p></div>)}+ {!cadenceEnabled && (+ <p className="text-sm text-fg-subtle">+ Off: the workflow runs when someone starts it.+ </p>+ )}</section>+ )}+ </div>{error && (- <div className="rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300">+ <div className="rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-2.5 text-[15px] text-red-500">{error}</div>)}- <div className="flex items-center gap-3 border-t border-line pt-4">- <button- type="button"- disabled={saving}- onClick={handleSave}- className="rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500 disabled:opacity-50 transition"- >- {saving ? "Saving…" : editName ? "Save changes" : "Create workflow"}- </button>- <Link- href={- designerId- ? `/jobs/new?session=${encodeURIComponent(designerId)}`- : "/jobs"- }- className="text-sm text-fg-muted hover:text-fg"- >+ <div className="flex flex-wrap items-center gap-2">+ {stage > 0 && (+ <Button onClick={() => setStage((s) => s - 1)}>Back</Button>+ )}+ {stage < last && (+ <Button+ variant={prefilled ? "secondary" : "primary"}+ onClick={() => setStage((s) => s + 1)}+ >+ Next: {STAGES[stage + 1]}+ </Button>+ )}+ {(stage === last || prefilled) && (+ <Button variant="primary" disabled={saving} onClick={handleSave}>+ {saveLabel}+ </Button>+ )}+ <Link href={cancelHref} className={buttonClass("ghost", "md", "ml-auto")}>{designerId ? "Back to conversation" : "Cancel"}</Link></div>@@ -708,30 +766,19 @@ function StepEditor({onRemove: () => void;}) {return (- <div className="rounded-md border border-line bg-surface/30 p-4 space-y-3">- <div className="flex items-center justify-between">- <span className="text-xs font-semibold uppercase tracking-wide text-fg-muted">+ <div className="rounded-xl border border-line bg-surface p-4 space-y-3">+ <div className="flex items-center justify-between gap-2">+ <span className="text-sm font-semibold uppercase tracking-wide text-fg-muted">{index + 1}. {step.kind.replace("_", " ")}</span>- <div className="flex items-center gap-2 text-xs text-fg-muted">- <button type="button" onClick={() => onMove(-1)} disabled={index === 0}>- ↑- </button>- <button- type="button"- onClick={() => onMove(1)}- disabled={index === total - 1}- >- ↓- </button>- <button- type="button"- className="hover:text-red-400"- onClick={onRemove}- >- Remove- </button>- </div>+ <OverflowMenu+ label={`More for step ${index + 1}`}+ items={[+ { label: "Move up", disabled: index === 0, onSelect: () => onMove(-1) },+ { label: "Move down", disabled: index === total - 1, onSelect: () => onMove(1) },+ { label: "Remove step", danger: true, onSelect: onRemove },+ ]}+ /></div><div className="grid sm:grid-cols-2 gap-3">@@ -948,19 +995,19 @@ function AdvancedBuilderPage() {<main className="flex-1 overflow-y-auto px-4 sm:px-6 py-8"><div className="max-w-3xl mx-auto"><div className="mb-6">- <Link href="/jobs" className="text-xs text-fg-muted hover:text-fg">+ <Link href="/jobs" className="text-sm text-fg-muted hover:text-fg">← Back to workflows</Link>- <h1 className="text-2xl font-semibold text-fg mt-2 mb-1">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg mt-2 mb-2">{editing ? "Edit workflow" : "New workflow"}</h1>- <p className="text-sm text-fg-muted">+ <p className="text-[15px] text-fg-muted">Build a reusable workflow from specialist steps, optionalapproval gates, and a final synthesis step.{!editing && (<>{" "}- <Link href="/jobs/new" className="text-indigo-400 hover:text-indigo-300">+ <Link href="/jobs/new" className="text-accent hover:underline">Describe it instead</Link>{" "}and let the assistant draft it.@@ -978,12 +1025,12 @@ function AdvancedBuilderPage() {function WizardPage() {return (<div className="flex flex-col h-full min-h-0 bg-surface text-fg">- <div className="border-b border-line px-6 py-4">+ <div className="border-b border-line px-4 sm:px-6 py-4"><div className="max-w-3xl mx-auto">- <Link href="/jobs" className="text-xs text-fg-muted hover:text-fg">+ <Link href="/jobs" className="text-sm text-fg-muted hover:text-fg">← Back to workflows</Link>- <h1 className="text-xl font-semibold text-fg mt-1">New workflow</h1>+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg mt-1">New workflow</h1></div></div><div className="flex-1 min-h-0">diff --git a/packages/ui/src/app/jobs/page.tsx b/packages/ui/src/app/jobs/page.tsxindex 2675b910..32b472bb 100644--- a/packages/ui/src/app/jobs/page.tsx+++ b/packages/ui/src/app/jobs/page.tsx@@ -24,12 +24,17 @@ import {} from "@/lib/api";import PlaybooksBrowser from "@/components/jobs/PlaybooksBrowser";import StartHere from "@/components/jobs/StartHere";+import { buttonClass } from "@/components/ui/Button";+import OverflowMenu, { type OverflowItem } from "@/components/ui/OverflowMenu";+import SidePanel from "@/components/ui/SidePanel";+import { formatRelativeTime } from "@/lib/relativeTime";import {RunBucket,runStatusBadgeColor,runStatusBucket,runStatusLabel,} from "@/lib/runStatus";+import { cadenceLabel, cardAction, lastRunAt } from "@/lib/workflowCards";const SECTION_ORDER: WorkflowSection[] = ["Board",@@ -43,7 +48,7 @@ const SECTION_ORDER: WorkflowSection[] = [// Chip labels for the ready-made list. "All" hides the background// (system-run) jobs; they get their own chip so the default view is only what-// a user starts by hand. Custom workflows have their own list above it.+// a user starts by hand. Custom workflows have their own list on the page.type SectionFilter = "all" | "system" | WorkflowSection;const SECTION_CHIP_LABEL: Record<WorkflowSection, string> = {@@ -72,8 +77,8 @@ function inSectionFilter(w: WorkflowMeta, f: SectionFilter): boolean {return w.section === f;}-// Ready-made workflows shown up front, each with a plain line on when to-// use it. The full list sits behind "Browse all".+// Ready-made workflows shown first in the ready-made panel, each with a plain+// line on when to use it. The full list sits under them.const STARTER_PICKS: { name: string; useFor: string }[] = [{name: "investor_update",@@ -108,20 +113,10 @@ function isStatus(v: string | null): v is RunStatus {);}-function formatRelativeTime(iso: string): string {- const diff = Date.now() - new Date(iso).getTime();- const mins = Math.floor(diff / 60000);- if (mins < 1) return "just now";- if (mins < 60) return `${mins}m ago`;- const hrs = Math.floor(mins / 60);- if (hrs < 24) return `${hrs}h ago`;- return `${Math.floor(hrs / 24)}d ago`;-}-function statusBadge(status: string) {return (<span- className={`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium ring-1 ${runStatusBadgeColor(status)}`}+ className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ring-1 ${runStatusBadgeColor(status)}`}>{runStatusLabel(status)}</span>@@ -160,14 +155,15 @@ function JobsPageInner() {const status: RunStatus | null = isStatus(statusParam) ? statusParam : null;const sectionParam = searchParams.get("section");const section: SectionFilter = isSectionFilter(sectionParam) ? sectionParam : "all";- // The full ready-made list is folded behind "Browse all"; a chip in the URL- // means someone was already browsing it.+ // The ready-made list opens in a side panel; a chip in the URL means+ // someone was already browsing it.const browsing = searchParams.get("browse") === "1" || section !== "all";const [workflows, setWorkflows] = useState<WorkflowMeta[]>([]);- // Custom workflows that are switched off (e.g. saved from chat with tool- // steps): not runnable, so absent from `workflows` until someone turns them on.- const [offWorkflows, setOffWorkflows] = useState<DynamicWorkflowDef[]>([]);+ // All custom workflows, for their schedule and on/off state. Switched-off+ // ones (e.g. saved from chat with tool steps) aren't runnable, so they are+ // absent from `workflows` until someone turns them on.+ const [customDefs, setCustomDefs] = useState<DynamicWorkflowDef[]>([]);const [runs, setRuns] = useState<WorkflowRunSummary[]>([]);const [playbookCount, setPlaybookCount] = useState<number | undefined>();const [loading, setLoading] = useState(true);@@ -176,7 +172,6 @@ function JobsPageInner() {const [runsQuery, setRunsQuery] = useState("");const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});const [expanded, setExpanded] = useState<Record<string, boolean>>({});- const readyMadeRef = useRef<HTMLElement>(null);const refresh = useCallback(async () => {setError(null);@@ -184,16 +179,16 @@ function JobsPageInner() {const [wfs, rs, custom, playbooks] = await Promise.all([listWorkflows(),listWorkflowRuns(),- // Optional strip — never fail the whole page over it.+ // Schedules and the switched-off list — never fail the whole page over it.listCustomWorkflows().catch(() => [] as DynamicWorkflowDef[]),- // Tab count only; the Playbooks tab loads its own list.+ // Count only; the Playbooks view loads its own list.listSkills().catch(() => undefined),]);setWorkflows(wfs);- // The Playbooks tab reports its own, fresher count once mounted.+ // The Playbooks view reports its own, fresher count once mounted.setPlaybookCount((current) => current ?? playbooks?.length);setRuns(rs);- setOffWorkflows(custom.filter((d) => !d.is_active));+ setCustomDefs(custom);} catch (e) {setError(e instanceof Error ? e.message : String(e));} finally {@@ -218,18 +213,13 @@ function JobsPageInner() {[pathname, router, searchParams]);- const browseReadyMade = useCallback(() => {- setParam({ browse: "1" });- readyMadeRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });- }, [setParam]);-const runCounts = useMemo(() => {const c = { active: 0, awaiting: 0, done: 0, error: 0 };for (const r of runs) c[runStatusBucket(r.status)]++;return c;}, [runs]);- // Default the runs sub-tab once data is loaded and ?status is missing/invalid.+ // Default the runs status once data is loaded and ?status is missing/invalid.// Ref guard ensures we only auto-set on the first eligible render, so a user// who explicitly navigates back to ?tab=runs without ?status isn't overridden// mid-interaction and StrictMode double-invocation doesn't double-write.@@ -270,137 +260,147 @@ function JobsPageInner() {[refresh]);+ const readyMade = workflows.filter((w) => !w.is_custom);+ const readyMadeCount = readyMade.filter((w) => !w.background).length;+ const offWorkflows = customDefs.filter((d) => !d.is_active);+ const ownWorkflows = workflows.filter((w) => w.is_custom && !w.background);+ const openRuns = runCounts.active + runCounts.awaiting;+return (<>- <div className="flex items-center gap-1 border-b border-line mb-4">- <TabButton- active={tab === "catalog"}- onClick={() => setParam({ tab: "catalog" })}- label="Build"- />- <TabButton- active={tab === "runs"}- onClick={() => setParam({ tab: "runs" })}- label="Runs"- count={runs.length}- />- <TabButton- active={tab === "playbooks"}- onClick={() => setParam({ tab: "playbooks", status: null, section: null })}- label="Playbooks"- count={playbookCount}- />- </div>+ {tab === "catalog" && (+ <StartHere+ readyMadeCount={readyMadeCount}+ onBrowseReadyMade={() => setParam({ browse: "1" })}+ />+ )}- {loading && tab !== "playbooks" && (- <div className="text-sm text-fg-muted">Loading workflows…</div>- )}- {error && (- <div className="text-sm text-red-400 mb-4">Error: {error}</div>- )}-- {!loading && tab === "catalog" && offWorkflows.length > 0 && (- <OffWorkflowsStrip items={offWorkflows} onDelete={handleDeleteCustom} />- )}-- {tab === "catalog" && (- <StartHere onBrowseReadyMade={browseReadyMade} />- )}-- {!loading && tab === "catalog" && (- <>- <YourWorkflows- workflows={workflows.filter((w) => w.is_custom && !w.background)}- onDeleteCustom={handleDeleteCustom}- />- <section ref={readyMadeRef} className="scroll-mt-4">- <h2 className="text-sm font-semibold text-fg">Ready-made workflows</h2>- <p className="mb-3 text-xs text-fg-muted">- Templates you can run as they are: fill in a few details and go.- </p>- {browsing ? (- <>- <CatalogView- workflows={workflows.filter((w) => !w.is_custom)}- query={catalogQuery}- onQueryChange={setCatalogQuery}- section={section}- onSectionChange={(s) =>- setParam({ browse: "1", section: s === "all" ? null : s })- }- />- <button- type="button"- onClick={() => setParam({ browse: null, section: null })}- className="mt-4 text-xs text-indigo-400 hover:text-indigo-300"- >- Show fewer- </button>- </>- ) : (- <StarterPicks- workflows={workflows}- onBrowseAll={() => setParam({ browse: "1" })}- />- )}- </section>- </>- )}-- {tab === "playbooks" && (- <PlaybooksBrowser- onCountChange={setPlaybookCount}- initialPlaybook={searchParams.get("playbook") ?? undefined}- initialDraft={searchParams.get("draft") ?? undefined}- />- )}-- {!loading && tab === "runs" && (- <RunsView- runs={runs}- counts={runCounts}- status={status ?? "active"}- onStatusChange={(s) => setParam({ status: s })}- query={runsQuery}- onQueryChange={setRunsQuery}- workflowTitleMap={workflowTitleMap}- collapsed={collapsed}- onToggleCollapsed={(key) =>- setCollapsed((c) => ({ ...c, [key]: !c[key] }))- }- expanded={expanded}- onExpand={(key) => setExpanded((c) => ({ ...c, [key]: true }))}- onDelete={handleDelete}- />- )}+ <div className="mb-4 flex flex-wrap items-center justify-between gap-3">+ <h2 className="text-xl font-bold tracking-tight text-fg">+ {tab === "runs" ? "Runs" : tab === "playbooks" ? "Playbooks" : "Your workflows"}+ </h2>+ <ViewSwitch+ tab={tab}+ runsLabel={openRuns > 0 ? `Runs (${openRuns} open)` : `Runs (${runs.length})`}+ playbookCount={playbookCount}+ onChange={(t) =>+ setParam(+ t === "playbooks"+ ? { tab: t, status: null, section: null, browse: null }+ : { tab: t === "catalog" ? null : t }+ )+ }+ />+ </div>++ {loading && tab !== "playbooks" && (+ <div className="text-[15px] text-fg-muted">Loading workflows…</div>+ )}+ {error && (+ <div className="mb-4 text-[15px] text-red-400">Error: {error}</div>+ )}++ {!loading && tab === "catalog" && (+ <YourWorkflows+ workflows={ownWorkflows}+ offWorkflows={offWorkflows}+ customDefs={customDefs}+ runs={runs}+ onDeleteCustom={handleDeleteCustom}+ onBrowse={() => setParam({ browse: "1" })}+ />+ )}++ {tab === "playbooks" && (+ <PlaybooksBrowser+ onCountChange={setPlaybookCount}+ initialPlaybook={searchParams.get("playbook") ?? undefined}+ initialDraft={searchParams.get("draft") ?? undefined}+ />+ )}++ {!loading && tab === "runs" && (+ <RunsView+ runs={runs}+ counts={runCounts}+ status={status ?? "active"}+ onStatusChange={(s) => setParam({ status: s })}+ query={runsQuery}+ onQueryChange={setRunsQuery}+ workflowTitleMap={workflowTitleMap}+ collapsed={collapsed}+ onToggleCollapsed={(key) =>+ setCollapsed((c) => ({ ...c, [key]: !c[key] }))+ }+ expanded={expanded}+ onExpand={(key) => setExpanded((c) => ({ ...c, [key]: true }))}+ onDelete={handleDelete}+ />+ )}++ <SidePanel+ open={browsing && !loading}+ onClose={() => setParam({ browse: null, section: null })}+ title="Ready-made workflows"+ subtitle="Templates you can run as they are: fill in a few details and go."+ width="lg"+ >+ <CatalogView+ workflows={readyMade}+ query={catalogQuery}+ onQueryChange={setCatalogQuery}+ section={section}+ onSectionChange={(s) =>+ setParam({ browse: "1", section: s === "all" ? null : s })+ }+ />+ </SidePanel></>);}-function TabButton({- active,- onClick,- label,- count,+/** Your workflows · Runs · Playbooks: one control, beside the list's heading. */+function ViewSwitch({+ tab,+ runsLabel,+ playbookCount,+ onChange,}: {- active: boolean;- onClick: () => void;- label: string;- count?: number;+ tab: Tab;+ runsLabel: string;+ playbookCount?: number;+ onChange: (t: Tab) => void;}) {+ const items: { key: Tab; label: string }[] = [+ { key: "catalog", label: "Your workflows" },+ { key: "runs", label: runsLabel },+ {+ key: "playbooks",+ label: playbookCount !== undefined ? `Playbooks (${playbookCount})` : "Playbooks",+ },+ ];return (- <button- type="button"- onClick={onClick}- className={`-mb-px px-4 py-2 text-sm font-medium border-b-2 transition-colors ${- active- ? "border-indigo-500 text-fg"- : "border-transparent text-fg-muted hover:text-fg"- }`}+ <div+ role="group"+ aria-label="Show"+ className="inline-flex max-w-full overflow-x-auto rounded-xl border border-line bg-surface-elevated p-1">- {label}- {count !== undefined && <span className="ml-2 text-xs text-fg-muted">{count}</span>}- </button>+ {items.map((it) => (+ <button+ key={it.key}+ type="button"+ aria-pressed={tab === it.key}+ onClick={() => onChange(it.key)}+ className={`min-h-10 flex-shrink-0 rounded-lg px-3.5 text-sm font-medium transition-colors ${+ tab === it.key+ ? "bg-accent/10 text-accent"+ : "text-fg-muted hover:text-fg hover:bg-surface-overlay"+ }`}+ >+ {it.label}+ </button>+ ))}+ </div>);}@@ -419,181 +419,167 @@ function SearchInput({value={value}onChange={(e) => onChange(e.target.value)}placeholder={placeholder}- className="w-full sm:w-80 px-3 py-1.5 text-sm rounded-md bg-surface/60 border border-line text-fg placeholder:text-fg-subtle focus:outline-none focus:ring-1 focus:ring-indigo-500/40 focus:border-line-strong"+ aria-label={placeholder.replace(/…$/, "")}+ className="h-11 w-full sm:w-80 px-4 text-[15px] rounded-xl bg-surface-elevated border border-line text-fg placeholder:text-fg-subtle focus:outline-none focus:ring-2 focus:ring-accent/40"/>);}-/** Compact list of switched-off custom workflows, each linking to its review card. */-function OffWorkflowsStrip({- items,- onDelete,+const cardCls =+ "flex min-w-0 flex-col rounded-2xl border border-line bg-surface-elevated p-5 shadow-sm";++/**+ * The user's own workflows as cards, one primary button each. Ones waiting+ * for approval (switched off) come first.+ */+function YourWorkflows({+ workflows,+ offWorkflows,+ customDefs,+ runs,+ onDeleteCustom,+ onBrowse,}: {- items: DynamicWorkflowDef[];- onDelete: (name: string) => void;+ workflows: WorkflowMeta[];+ offWorkflows: DynamicWorkflowDef[];+ customDefs: DynamicWorkflowDef[];+ runs: WorkflowRunSummary[];+ onDeleteCustom: (name: string) => void;+ onBrowse: () => void;}) {+ const cadenceByName = new Map(customDefs.map((d) => [d.name, d.cadence] as const));++ if (workflows.length === 0 && offWorkflows.length === 0) {+ return (+ <div className="rounded-2xl border border-dashed border-line px-5 py-8 text-center">+ <p className="text-[15px] text-fg-muted">+ No workflows of your own yet. Describe one above, or start from a+ ready-made one.+ </p>+ <button type="button" onClick={onBrowse} className={buttonClass("secondary", "md", "mt-4")}>+ Browse ready-made+ </button>+ </div>+ );+ }+return (- <div className="mb-4 rounded-md border border-indigo-500/30 bg-indigo-500/5 px-3 py-2">- <p className="text-[11px] uppercase tracking-wide text-indigo-300 mb-1">- Waiting for your approval- </p>- <ul className="divide-y divide-line/60">- {items.map((d) => {- const tools = new Set(d.steps.flatMap((s) => (s.kind === "action" ? s.tools : [])));- return (- <li key={d.name} className="flex items-center gap-3 py-1.5 text-sm min-w-0">- <span className="truncate text-fg min-w-0 flex-1">{d.title}</span>- <span className="shrink-0 text-[11px] text-fg-subtle">- off+ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">+ {offWorkflows.map((d) => {+ const tools = new Set(d.steps.flatMap((s) => (s.kind === "action" ? s.tools : [])));+ const href = `/jobs/${encodeURIComponent(d.name)}`;+ return (+ <div key={`off:${d.name}`} className={`${cardCls} border-amber-500/40`}>+ <h3 className="text-lg font-semibold leading-snug text-fg">{d.title}</h3>+ <div className="mt-2 flex flex-wrap items-center gap-2 text-sm text-fg-muted">+ <span className="rounded-full bg-amber-500/15 px-2.5 py-0.5 text-xs font-medium text-amber-600 dark:text-amber-300">+ Waiting for your approval+ </span>+ <span>+ Off{tools.size > 0 && ` · ${tools.size} ${tools.size === 1 ? "tool" : "tools"}`}</span>- <Link- href={`/jobs/${encodeURIComponent(d.name)}`}- className="shrink-0 text-[11px] text-indigo-400 hover:text-indigo-300"- >+ </div>+ <div className="mt-auto flex items-center gap-2 pt-5">+ <Link href={href} className={buttonClass("primary", "md")}>Review</Link>- <button- type="button"- onClick={() => onDelete(d.name)}- className="shrink-0 text-[11px] text-fg-muted hover:text-red-400 transition"- >- Delete- </button>- </li>- );- })}- </ul>+ <OverflowMenu+ label={`More for ${d.title}`}+ items={[+ { label: "Edit", href: `/jobs/new?edit=${encodeURIComponent(d.name)}` },+ { label: "Delete", danger: true, onSelect: () => onDeleteCustom(d.name) },+ ]}+ />+ </div>+ </div>+ );+ })}+ {workflows.map((w) => {+ const href = `/jobs/${encodeURIComponent(w.name)}`;+ const action = cardAction(w.name, true, runs);+ const last = lastRunAt(w.name, runs);+ const cadence = cadenceLabel(cadenceByName.get(w.name));+ const meta = [+ cadence || `${w.steps.length} steps`,+ last ? `last run ${formatRelativeTime(last)}` : "not run yet",+ ].join(" · ");+ const more: OverflowItem[] = [+ ...(action.kind === "signoff" ? [{ label: "Run again", href }] : []),+ { label: "Edit", href: `/jobs/new?edit=${encodeURIComponent(w.name)}` },+ { label: "Delete", danger: true, onSelect: () => onDeleteCustom(w.name) },+ ];+ return (+ <div key={w.name} className={cardCls}>+ <Link href={href} className="min-w-0" title={w.description}>+ <h3 className="text-lg font-semibold leading-snug text-fg hover:text-accent transition-colors">+ {w.title}+ </h3>+ </Link>+ {action.kind === "signoff" ? (+ <span className="mt-2 inline-flex w-fit rounded-full bg-amber-500/15 px-2.5 py-0.5 text-xs font-medium text-amber-600 dark:text-amber-300">+ Waiting for sign-off+ </span>+ ) : (+ <p className="mt-1.5 text-sm text-fg-muted">{meta}</p>+ )}+ {w.description && (+ <p className="mt-2 line-clamp-2 text-sm text-fg-subtle">{w.description}</p>+ )}+ <div className="mt-auto flex items-center gap-2 pt-5">+ {action.kind === "signoff" ? (+ <Link+ href={`/jobs/runs/${encodeURIComponent(action.runId)}`}+ className={buttonClass("primary", "md")}+ >+ Review+ </Link>+ ) : (+ <Link href={href} className={buttonClass("primary", "md")}>+ Run+ </Link>+ )}+ <OverflowMenu label={`More for ${w.title}`} items={more} />+ </div>+ </div>+ );+ })}</div>);}-function WorkflowCard({- workflow: w,- onDeleteCustom,-}: {- workflow: WorkflowMeta;- onDeleteCustom?: (name: string) => void;-}) {+function CatalogCard({ workflow: w, useFor }: { workflow: WorkflowMeta; useFor?: string }) {return (- <div className="group relative min-w-0 rounded-md border border-line bg-surface/40 hover:border-line-strong hover:bg-surface-elevated/40 transition">- <Link- href={`/jobs/${encodeURIComponent(w.name)}`}- className="block px-3 py-2.5"- title={w.description}- >- <h3 className="text-sm font-medium text-fg truncate pr-16">{w.title}</h3>- <p className="text-xs text-fg-muted truncate mt-0.5">{w.description}</p>- <p className="text-[11px] text-fg-subtle mt-1">- {w.steps.length} steps · ~{w.estimated_minutes} min- </p>- </Link>- {w.is_custom && onDeleteCustom && (- <div className="absolute top-2 right-2 flex items-center gap-2 text-[11px]">- <Link- href={`/jobs/new?edit=${encodeURIComponent(w.name)}`}- className="text-indigo-400 hover:text-indigo-300"- >- Edit- </Link>- <button- type="button"- onClick={() => onDeleteCustom(w.name)}- className="text-fg-muted hover:text-red-400 transition"- >- Delete- </button>- </div>- )}- </div>+ <Link+ href={`/jobs/${encodeURIComponent(w.name)}`}+ title={w.description}+ className="block min-w-0 rounded-xl border border-line bg-surface-elevated px-4 py-3.5 hover:border-line-strong hover:bg-surface-overlay transition-colors"+ >+ <span className="block text-[15px] font-semibold text-fg">{w.title}</span>+ <span className="mt-1 block line-clamp-2 text-sm text-fg-muted">+ {useFor ?? w.description}+ </span>+ <span className="mt-1.5 block text-xs text-fg-subtle">+ {w.steps.length} steps · ~{w.estimated_minutes} min+ </span>+ </Link>);}-function WorkflowGrid({- items,- onDeleteCustom,-}: {- items: WorkflowMeta[];- onDeleteCustom?: (name: string) => void;-}) {+function CatalogGrid({ items }: { items: WorkflowMeta[] }) {return (- <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-2">+ <div className="grid gap-2.5 sm:grid-cols-2">{items.map((w) => (- <WorkflowCard key={w.name} workflow={w} onDeleteCustom={onDeleteCustom} />+ <CatalogCard key={w.name} workflow={w} />))}</div>);}-/** The user's own workflows, above the ready-made list. Hidden until they have one. */-function YourWorkflows({- workflows,- onDeleteCustom,-}: {- workflows: WorkflowMeta[];- onDeleteCustom: (name: string) => void;-}) {- if (workflows.length === 0) return null;- return (- <section className="mb-6">- <h2 className="mb-2 text-sm font-semibold text-fg">- Your workflows- <span className="ml-2 text-xs font-normal text-fg-subtle">{workflows.length}</span>- </h2>- <WorkflowGrid items={workflows} onDeleteCustom={onDeleteCustom} />- </section>- );-}--/** A few ready-made workflows with a plain "use this to" line, and the way into the rest. */-function StarterPicks({- workflows,- onBrowseAll,-}: {- workflows: WorkflowMeta[];- onBrowseAll: () => void;-}) {- const byName = new Map(workflows.map((w) => [w.name, w] as const));- const picks = STARTER_PICKS.flatMap((p) => {- const w = byName.get(p.name);- return w && !w.is_custom ? [{ workflow: w, useFor: p.useFor }] : [];- });- const total = workflows.filter((w) => !w.is_custom && !w.background).length;- return (- <div>- {picks.length > 0 && (- <div className="grid gap-2 sm:grid-cols-2">- {picks.map(({ workflow: w, useFor }) => (- <Link- key={w.name}- href={`/jobs/${encodeURIComponent(w.name)}`}- className="rounded-md border border-line bg-surface/40 px-3 py-2.5 hover:border-line-strong hover:bg-surface-elevated/40 transition"- >- <span className="block text-sm font-medium text-fg">{w.title}</span>- <span className="mt-0.5 block text-xs text-fg-muted">{useFor}</span>- <span className="mt-1 block text-[11px] text-fg-subtle">- ~{w.estimated_minutes} min- </span>- </Link>- ))}- </div>- )}- {total > 0 ? (- <button- type="button"- onClick={onBrowseAll}- className="mt-3 text-sm text-indigo-400 hover:text-indigo-300"- >- Browse all {total} ready-made workflows →- </button>- ) : (- <div className="text-sm text-fg-muted">No ready-made workflows available.</div>- )}- </div>- );-}--/** The full ready-made list: search, section chips, and grouped cards. */+/**+ * The ready-made list in its panel: a few good first picks, then search,+ * section chips and every template grouped by section.+ */function CatalogView({workflows,query,@@ -607,6 +593,11 @@ function CatalogView({section: SectionFilter;onSectionChange: (s: SectionFilter) => void;}) {+ const byName = new Map(workflows.map((w) => [w.name, w] as const));+ const picks = STARTER_PICKS.flatMap((p) => {+ const w = byName.get(p.name);+ return w ? [{ workflow: w, useFor: p.useFor }] : [];+ });const matching = workflows.filter((w) =>matchesQuery(query, w.title, w.description));@@ -643,54 +634,66 @@ function CatalogView({: [];return (- <div>- <div className="mb-3">+ <div className="space-y-5">+ {picks.length > 0 && !query && section === "all" && (+ <div>+ <h3 className="mb-2 text-sm font-semibold text-fg">Good places to start</h3>+ <div className="grid gap-2.5 sm:grid-cols-2">+ {picks.map(({ workflow, useFor }) => (+ <CatalogCard key={workflow.name} workflow={workflow} useFor={useFor} />+ ))}+ </div>+ </div>+ )}++ <div className="space-y-3"><SearchInputvalue={query}onChange={onQueryChange}placeholder="Search ready-made workflows…"/>- </div>- <div className="mb-4 flex flex-wrap gap-1.5">- {chips.map((c) => (- <button- key={c.key}- type="button"- onClick={() => onSectionChange(c.key)}- className={`rounded-full px-2.5 py-1 text-xs ring-1 transition ${- section === c.key- ? "bg-surface-elevated ring-indigo-500/50 text-fg"- : "ring-line text-fg-muted hover:text-fg hover:ring-line-strong"- }`}- >- {c.label}- <span className="ml-1 text-fg-subtle">{c.count}</span>- </button>- ))}+ <div className="flex flex-wrap gap-2">+ {chips.map((c) => (+ <button+ key={c.key}+ type="button"+ aria-pressed={section === c.key}+ onClick={() => onSectionChange(c.key)}+ className={`min-h-10 rounded-full border px-3.5 text-sm transition-colors ${+ section === c.key+ ? "border-accent/50 bg-accent/10 text-accent font-medium"+ : "border-line text-fg-muted hover:text-fg hover:border-line-strong"+ }`}+ >+ {c.label}+ <span className="ml-1.5 text-fg-subtle">{c.count}</span>+ </button>+ ))}+ </div></div>{workflows.length === 0 ? (- <div className="text-sm text-fg-muted">No workflows yet.</div>+ <div className="text-[15px] text-fg-muted">No ready-made workflows available.</div>) : visible.length === 0 ? (- <div className="text-sm text-fg-muted">+ <div className="text-[15px] text-fg-muted">{query ? <>No workflows match “{query}”.</> : "Nothing here yet."}</div>) : section === "all" ? (<div className="space-y-5">{grouped.map((g) => (<div key={g.label}>- <h2 className="mb-2 text-xs font-semibold uppercase tracking-wide text-fg-subtle">+ <h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-fg-subtle">{g.label}<span className="ml-2 font-normal normal-case tracking-normal">{g.items.length}</span>- </h2>- <WorkflowGrid items={g.items} />+ </h3>+ <CatalogGrid items={g.items} /></div>))}</div>) : (- <WorkflowGrid items={visible} />+ <CatalogGrid items={visible} />)}</div>);@@ -745,36 +748,32 @@ function RunsView({return (<div>- <div className="flex flex-wrap items-center gap-1 mb-4">+ <div className="flex flex-wrap items-center gap-2 mb-5"><StatusSegmentactive={status === "active"}onClick={() => onStatusChange("active")}label="Active"count={counts.active}- tone="amber"/><StatusSegmentactive={status === "awaiting"}onClick={() => onStatusChange("awaiting")}label="Awaiting sign-off"count={counts.awaiting}- tone="amber"/><StatusSegmentactive={status === "done"}onClick={() => onStatusChange("done")}label="Done"count={counts.done}- tone="emerald"/><StatusSegmentactive={status === "error"}onClick={() => onStatusChange("error")}label="Error"count={counts.error}- tone="red"/>- <div className="w-full sm:w-auto sm:ml-auto mt-2 sm:mt-0">+ <div className="w-full sm:w-auto sm:ml-auto"><SearchInputvalue={query}onChange={onQueryChange}@@ -784,11 +783,11 @@ function RunsView({</div>{visible.length === 0 ? (- <div className="text-sm text-fg-muted">+ <div className="text-[15px] text-fg-muted">{query ? `No runs match “${query}”.` : emptyMsg}</div>) : (- <div className="space-y-4">+ <div className="space-y-6">{Array.from(groups.entries()).map(([workflowName, items]) => {const title = workflowTitleMap.get(workflowName) ?? workflowName;const isCollapsed = !!collapsed[workflowName];@@ -798,55 +797,55 @@ function RunsView({<div key={workflowName}><buttontype="button"+ aria-expanded={!isCollapsed}onClick={() => onToggleCollapsed(workflowName)}- className="w-full flex items-center gap-2 mb-2 text-left"+ className="mb-2 flex min-h-10 w-full items-center gap-2 text-left"><span+ aria-hidden="true"className={`text-fg-muted text-xs transition-transform ${isCollapsed ? "" : "rotate-90"}`}>▶</span>- <span className="text-sm font-semibold text-fg">+ <span className="text-base font-semibold text-fg">{title}</span>- <span className="text-xs text-fg-muted">+ <span className="text-sm text-fg-muted">{items.length} {items.length === 1 ? "run" : "runs"}</span></button>{!isCollapsed && (- <div className="divide-y divide-line rounded-md border border-line bg-surface/30">+ <div className="divide-y divide-line rounded-2xl border border-line bg-surface-elevated">{shown.map((r) => (<divkey={r.run_id}- className="flex items-center gap-3 px-3 py-2"+ className="flex items-center gap-2 py-1.5 pl-4 pr-2"><Linkhref={`/jobs/runs/${encodeURIComponent(r.run_id)}`}- className="flex flex-1 min-w-0 items-center gap-2"+ className="flex min-h-11 min-w-0 flex-1 flex-wrap items-center gap-x-3 gap-y-1">- <span className="text-sm text-fg truncate">{r.title}</span>+ <span className="min-w-0 truncate text-[15px] text-fg">{r.title}</span>{statusBadge(r.status)}- <span className="ml-auto shrink-0 text-xs text-fg-subtle">+ <span className="ml-auto shrink-0 text-sm text-fg-subtle">{formatRelativeTime(r.updated_at)}</span></Link>- <button- type="button"- onClick={() => onDelete(r.run_id)}- className="shrink-0 text-xs text-fg-muted hover:text-red-400 transition"- aria-label="Delete run"- >- Delete- </button>+ <OverflowMenu+ label={`More for ${r.title}`}+ items={[+ { label: "Delete run", danger: true, onSelect: () => onDelete(r.run_id) },+ ]}+ /></div>))}{hidden > 0 && (<buttontype="button"onClick={() => onExpand(workflowName)}- className="w-full px-3 py-1.5 text-left text-xs text-indigo-400 hover:text-indigo-300"+ className="min-h-11 w-full px-4 text-left text-sm font-medium text-accent hover:underline">Show {hidden} more</button>@@ -867,32 +866,25 @@ function StatusSegment({onClick,label,count,- tone,}: {active: boolean;onClick: () => void;label: string;count: number;- tone: "amber" | "emerald" | "red";}) {- const toneRing =- tone === "amber"- ? "ring-amber-500/40 text-amber-300"- : tone === "emerald"- ? "ring-emerald-500/40 text-emerald-300"- : "ring-red-500/40 text-red-300";return (<buttontype="button"+ aria-pressed={active}onClick={onClick}- className={`px-3 py-1.5 text-xs rounded-md ring-1 transition ${+ className={`min-h-10 rounded-full border px-4 text-sm transition-colors ${active- ? `bg-surface-elevated ${toneRing}`- : "ring-line text-fg-muted hover:text-fg hover:ring-line-strong"+ ? "border-accent/50 bg-accent/10 text-accent font-medium"+ : "border-line text-fg-muted hover:text-fg hover:border-line-strong"}`}>{label}- <span className="ml-1.5 text-fg-muted">{count}</span>+ <span className="ml-1.5 text-fg-subtle">{count}</span></button>);}@@ -900,23 +892,8 @@ function StatusSegment({export default function JobsPage() {return (<div className="flex flex-col h-full bg-surface text-fg">- <main className="flex-1 overflow-y-auto px-4 sm:px-6 py-6">+ <main className="flex-1 overflow-y-auto px-4 sm:px-6 py-6 sm:py-8"><div className="max-w-6xl mx-auto">- <div className="mb-4 flex items-start justify-between gap-4">- <div className="min-w-0">- <h1 className="text-xl font-semibold text-fg">Workflows</h1>- <p className="text-sm text-fg-muted">- Jobs the Executive runs for you, start to finish — each one- ends in a finished document or a task done.- </p>- </div>- <Link- href="/jobs/new"- className="shrink-0 rounded-md bg-indigo-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-indigo-500 transition"- >- + New workflow- </Link>- </div><Suspense fallback={null}><JobsPageInner /></Suspense>diff --git a/packages/ui/src/app/jobs/runs/[id]/page.tsx b/packages/ui/src/app/jobs/runs/[id]/page.tsxindex dd664d06..976c8712 100644--- a/packages/ui/src/app/jobs/runs/[id]/page.tsx+++ b/packages/ui/src/app/jobs/runs/[id]/page.tsx@@ -13,6 +13,8 @@ import {getWorkflowRun,artifactDownloadUrl,} from "@/lib/api";+import Button from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";import { runStatusLabel, runStatusTextColor } from "@/lib/runStatus";// A paused run is resumed by a background worker, so this page has to notice@@ -101,6 +103,17 @@ export default function RunDetailPage() {}}, [run]);+ // The .docx comes from the API; an <a download> keeps the page in place.+ const handleDownloadDocx = useCallback(() => {+ if (!run) return;+ const a = document.createElement("a");+ a.href = artifactDownloadUrl(`run:${run.run_id}`, "docx");+ a.download = "";+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ }, [run]);+const handleDownload = useCallback(() => {if (!run?.artifact) return;const blob = new Blob([run.artifact], { type: "text/markdown" });@@ -141,51 +154,44 @@ export default function RunDetailPage() {<div className="flex flex-col h-full bg-surface text-fg"><main className="flex-1 overflow-y-auto px-4 sm:px-6 py-8"><div className="max-w-4xl mx-auto space-y-6">- <div className="flex items-start justify-between gap-4">+ <Link href="/jobs?tab=runs" className="text-sm text-fg-muted hover:text-fg">+ ← Runs+ </Link>+ <div className="flex flex-wrap items-start justify-between gap-4"><div className="min-w-0">- <h1 className="text-2xl font-semibold text-fg mb-1">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg mb-2">{run.title}</h1>- <div className="text-xs text-fg-muted">+ <div className="text-sm text-fg-muted">{run.workflow_name} · created {formatTimestamp(run.created_at)} ·status <StatusPill status={run.status} /></div></div>{run.artifact && (<div className="flex items-center gap-2 flex-shrink-0">- <button- type="button"- onClick={handleCopy}- className="text-xs text-fg-muted hover:text-fg transition px-3 py-1.5 rounded-md border border-line hover:bg-surface-overlay min-h-touch"- >+ <Button variant="primary" onClick={handleCopy}>{copied ? "Copied!" : "Copy"}- </button>- <button- type="button"- onClick={handleDownload}- className="text-xs text-fg-muted hover:text-fg transition px-3 py-1.5 rounded-md border border-line hover:bg-surface-overlay min-h-touch"- >- Download .md- </button>- <a- href={artifactDownloadUrl(`run:${run.run_id}`, "docx")}- download- className="text-xs text-fg-muted hover:text-fg transition px-3 py-1.5 rounded-md border border-line hover:bg-surface-overlay min-h-touch"- >- Download .docx- </a>+ </Button>+ <OverflowMenu+ trigger="Download"+ label="Download"+ items={[+ { label: "Markdown (.md)", onSelect: handleDownload },+ { label: "Word (.docx)", onSelect: handleDownloadDocx },+ ]}+ /></div>)}</div>{error && (- <div className="rounded-md border border-red-500/30 bg-red-500/5 px-4 py-3 text-xs text-red-300">+ <div className="rounded-xl border border-red-500/30 bg-red-500/5 px-4 py-3 text-xs text-red-300">Couldn't refresh just now ({error}). Still retrying.</div>)}{run.status === "running" && (- <div className="rounded-md border border-amber-500/30 bg-amber-500/5 px-4 py-3 text-sm text-amber-300">+ <div className="rounded-xl border border-amber-500/30 bg-amber-500/5 px-4 py-3 text-sm text-amber-300">This run is still in progress — this page updates itself.</div>)}@@ -197,14 +203,14 @@ export default function RunDetailPage() {)}{run.status === "resolved" && (- <div className="rounded-md border border-indigo-500/30 bg-indigo-500/5 px-4 py-3 text-sm text-indigo-300">+ <div className="rounded-xl border border-indigo-500/30 bg-indigo-500/5 px-4 py-3 text-sm text-indigo-300">Answered — picking the workflow back up now. The remaining stepsare running.</div>)}{run.status === "timed_out" && (- <div className="rounded-md border border-red-500/30 bg-red-500/5 px-4 py-3 text-sm text-red-300">+ <div className="rounded-xl border border-red-500/30 bg-red-500/5 px-4 py-3 text-sm text-red-300"><div className="font-medium mb-1">No reply before the deadline</div><div className="text-xs">The step's timeout policy was applied, so this run stopped@@ -214,24 +220,24 @@ export default function RunDetailPage() {)}{run.status === "error" && (- <div className="rounded-md border border-red-500/30 bg-red-500/5 px-4 py-3 text-sm text-red-300">+ <div className="rounded-xl border border-red-500/30 bg-red-500/5 px-4 py-3 text-sm text-red-300"><div className="font-medium mb-1">Run failed</div><div className="text-xs">{run.error}</div></div>)}{run.artifact && (- <article className="prose prose-invert prose-sm max-w-none rounded-lg border border-line bg-surface/40 p-6+ <article className="prose prose-invert max-w-none rounded-2xl border border-line bg-surface-elevated p-5 sm:p-8prose-headings:text-fg prose-headings:font-semiboldprose-p:text-fg prose-p:leading-relaxedprose-strong:text-fg- prose-code:text-indigo-300 prose-code:bg-surface-overlay prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:before:content-none prose-code:after:content-none+ prose-code:text-accent prose-code:bg-surface-overlay prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:before:content-none prose-code:after:content-noneprose-pre:bg-surface-overlay prose-pre:border prose-pre:border-line-strongprose-blockquote:border-line-strong prose-blockquote:text-fg-mutedprose-ul:text-fg prose-ol:text-fgprose-li:marker:text-fg-mutedprose-hr:border-line-strong- prose-a:text-indigo-400 prose-a:no-underline hover:prose-a:underline+ prose-a:text-accent prose-a:no-underline hover:prose-a:underlineprose-table:text-fg prose-th:text-fg prose-th:border-line-strong prose-td:border-line-strong"><ReactMarkdownremarkPlugins={[remarkGfm]}@@ -246,8 +252,8 @@ export default function RunDetailPage() {</article>)}- <details className="rounded-md border border-line bg-surface/30 px-4 py-3 text-sm">- <summary className="text-xs text-fg-muted cursor-pointer">+ <details className="rounded-2xl border border-line bg-surface-elevated px-5 py-3 text-sm">+ <summary className="flex min-h-10 items-center text-[15px] font-medium text-fg-muted cursor-pointer">Inputs</summary><pre className="mt-3 text-xs text-fg whitespace-pre-wrap font-mono">@@ -309,7 +315,7 @@ function AwaitingPanel({ run }: { run: WorkflowRunDetail }) {const done = run.resume_progress?.completed_step_ids.length ?? 0;return (- <div className="rounded-md border border-amber-500/30 bg-amber-500/5 px-4 py-3 text-sm text-amber-300 space-y-2">+ <div className="rounded-xl border border-amber-500/30 bg-amber-500/5 px-4 py-3 text-sm text-amber-300 space-y-2"><div className="font-medium">Waiting for sign-off{run.awaiting_person_id ? ` from person ${run.awaiting_person_id}` : ""}@@ -321,23 +327,13 @@ function AwaitingPanel({ run }: { run: WorkflowRunDetail }) {)}{canAnswer && !answer && (<div className="flex flex-wrap items-center gap-2 pt-1">- <button- type="button"- onClick={() => void decide("approve")}- disabled={sending}- className="rounded-md bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-500 disabled:opacity-50 transition"- >+ <Button variant="primary" onClick={() => void decide("approve")} disabled={sending}>Approve- </button>- <button- type="button"- onClick={() => void decide("reject")}- disabled={sending}- className="rounded-md border border-line px-3 py-1.5 text-xs text-fg hover:bg-surface-overlay disabled:opacity-50 transition"- >+ </Button>+ <Button onClick={() => void decide("reject")} disabled={sending}>Decline- </button>- <span className="text-xs text-fg-muted">or reply in chat</span>+ </Button>+ <span className="text-sm text-fg-muted">or reply in chat</span></div>)}{answer && (diff --git a/packages/ui/src/app/layout.tsx b/packages/ui/src/app/layout.tsxindex 6efd972b..cd62ed28 100644--- a/packages/ui/src/app/layout.tsx+++ b/packages/ui/src/app/layout.tsx@@ -1,4 +1,5 @@import type { Metadata, Viewport } from "next";+import { Geist } from "next/font/google";import AuthProvider from "@/components/AuthProvider";import { ExecutiveStatusProvider } from "@/components/executive/ExecutiveStatusContext";import { SessionsProvider } from "@/components/sessions/SessionsContext";@@ -6,6 +7,10 @@ import AppShell from "@/components/shell/AppShell";import { WorkspaceProvider } from "@/components/workspace/WorkspaceContext";import "./globals.css";+// Geist, self-hosted by next/font at build time: no request to Google from+// the browser, and no layout shift while it loads.+const geist = Geist({ subsets: ["latin"], variable: "--font-sans", display: "swap" });+export const metadata: Metadata = {title: "Open Executive",description: "Your AI-powered virtual executive team",@@ -26,7 +31,7 @@ export default function RootLayout({children: React.ReactNode;}) {return (- <html lang="en" className="h-full">+ <html lang="en" className={`h-full ${geist.variable}`}><body className="h-full antialiased bg-surface text-fg"><AuthProvider><SessionsProvider>diff --git a/packages/ui/src/app/memories/page.tsx b/packages/ui/src/app/memories/page.tsxindex 96d386c4..717f7f1a 100644--- a/packages/ui/src/app/memories/page.tsx+++ b/packages/ui/src/app/memories/page.tsx@@ -1,11 +1,16 @@"use client";+import { Suspense } from "react";+import PulsePage from "@/components/memories/PulsePage";export default function MemoriesPage() {return (<main className="flex-1 min-h-0 overflow-y-auto">- <PulsePage />+ {/* useSearchParams (for ?tab=corrections) needs a Suspense boundary. */}+ <Suspense>+ <PulsePage />+ </Suspense></main>);}diff --git a/packages/ui/src/app/page.tsx b/packages/ui/src/app/page.tsxindex 24a061aa..f9607f7f 100644--- a/packages/ui/src/app/page.tsx+++ b/packages/ui/src/app/page.tsx@@ -2,7 +2,7 @@import { useCallback, useEffect, useRef, useState } from "react";import { useSession } from "next-auth/react";-import BriefDeliveryNotice from "@/components/BriefDeliveryNotice";+import BriefDeliveryNotice, { useBriefDeliveryNotice } from "@/components/BriefDeliveryNotice";import Briefing from "@/components/Briefing";import Chat from "@/components/Chat";import DebugPanel from "@/components/DebugPanel";@@ -13,7 +13,9 @@ import { MobileBottomNav } from "@/components/shell/AppShell";import AppSidebar from "@/components/shell/AppSidebar";import { profileWording } from "@/components/shell/navConfig";import { useWorkspace } from "@/components/workspace/WorkspaceContext";+import { useExecutiveStatus } from "@/components/executive/ExecutiveStatusContext";import PausedBanner from "@/components/executive/PausedBanner";+import OverflowMenu from "@/components/ui/OverflowMenu";import { ChatMessage, DebugEvent, getSessionMessages } from "@/lib/api";import Link from "next/link";import { useRouter } from "next/navigation";@@ -207,6 +209,26 @@ export default function HomePage() {const companyName = health?.company_name;const profileCopy = PROFILE_COPY[profileWording(workspaceMode, role.role_kind)];+ // The briefing's one banner slot shows the most important notice: paused,+ // then no profile, then a brief that wasn't sent. With none, the briefing+ // shows its quiet-day note there instead.+ const { status: execStatus, unknown: execStatusUnknown } = useExecutiveStatus();+ const deliveryNotice = useBriefDeliveryNotice();+ const homeBanner = execStatus?.paused && !execStatusUnknown ? (+ <div className="overflow-hidden rounded-2xl border border-amber-500/30 [&>div]:border-b-0">+ <PausedBanner />+ </div>+ ) : !isOnboarded && health ? (+ <div className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-accent/25 bg-accent/5 px-4 py-3">+ <p className="text-[15px] text-fg-muted">{profileCopy.missingBanner}</p>+ <Link href="/onboard" className="text-sm font-semibold text-accent hover:underline whitespace-nowrap">+ Set up profile →+ </Link>+ </div>+ ) : deliveryNotice ? (+ <BriefDeliveryNotice notice={deliveryNotice} />+ ) : undefined;+return (<div className="flex h-full relative">{/* Mobile backdrop */}@@ -233,7 +255,6 @@ export default function HomePage() {activeSessionId,onBriefing: handleBackToBriefing,onNewChat: handleNewChat,- onSelectSession: (id) => void handleSelectSession(id),}}/>@@ -252,46 +273,42 @@ export default function HomePage() {><Icon name="menu" size="w-5 h-5" /></button>- <span className="text-xs text-fg-muted font-medium truncate">+ <span className="text-sm text-fg-muted font-medium truncate">{isOnboarded && companyName ? `${companyName} · Executive` : "Executive"}</span></div>- <div className="flex items-center gap-2 flex-shrink-0">- <button- type="button"- onClick={() => setDebugOpen((o) => !o)}- className={`flex items-center gap-1.5 text-xs font-medium px-3 py-2 min-h-touch rounded-md transition-colors cursor-pointer ${- debugOpen- ? "bg-violet-500/20 text-violet-300 border border-violet-500/30"- : "text-fg-muted hover:text-fg hover:bg-surface-overlay"- }`}- aria-label={debugOpen ? "Hide agent activity" : "Show agent activity"}- >- <Icon name="activity" size="w-4 h-4" />- <span className="hidden sm:inline">{debugOpen ? "Hide activity" : "Agent activity"}</span>- </button>- </div>+ {/* Agent activity (the live trace of the Executive's turn) lives in+ this ⋯ menu; the panel itself opens on the right as before. */}+ <OverflowMenu+ label="Home options"+ items={[+ {+ label: debugOpen ? "Hide agent activity" : "Show agent activity",+ onSelect: () => setDebugOpen((o) => !o),+ },+ ]}+ /></div>- <PausedBanner />-- {!isOnboarded && health && (- <div className="border-b border-line bg-indigo-500/5 px-4 sm:px-6 py-2.5 flex items-center justify-between gap-3">- <p className="text-xs text-fg-muted">{profileCopy.missingBanner}</p>- <Link href="/onboard" className="text-xs text-indigo-400 hover:text-indigo-300 font-medium transition-colors whitespace-nowrap cursor-pointer">+ {/* In chat the notices stay as strips above the conversation; on+ the briefing they share one banner slot (see homeBanner). */}+ {mode === "chat" && <PausedBanner />}+ {mode === "chat" && !isOnboarded && health && (+ <div className="border-b border-line bg-accent/5 px-4 sm:px-6 py-2.5 flex items-center justify-between gap-3">+ <p className="text-sm text-fg-muted">{profileCopy.missingBanner}</p>+ <Link href="/onboard" className="text-sm text-accent hover:underline font-medium whitespace-nowrap cursor-pointer">Set up profile →</Link></div>)}- {mode === "briefing" && <BriefDeliveryNotice />}-<div className="flex-1 min-h-0">{mode === "briefing" ? (<BriefingonContinue={handleContinueFromBriefing}showHeaderfirstName={firstName ?? undefined}+ banner={homeBanner}/>) : (// No `key` here — Chat handles undefined→sid session adoption@@ -320,7 +337,7 @@ export default function HomePage() {{/* Mobile bottom nav — the chat home owns its own layout (it'sexempt from AppShell), so it renders the shared bar itself tomatch every other route. "More" opens this page's own drawer. */}- <MobileBottomNav pathname="/" hideFrom="md" onOpenDrawer={() => setMobileNavOpen(true)} />+ <MobileBottomNav pathname="/" hideFrom="md" /></main>{/* Debug panel */}diff --git a/packages/ui/src/app/people/[id]/page.tsx b/packages/ui/src/app/people/[id]/page.tsxindex 251e9af9..925926d9 100644--- a/packages/ui/src/app/people/[id]/page.tsx+++ b/packages/ui/src/app/people/[id]/page.tsx@@ -1,9 +1,12 @@"use client";import { useParams, useRouter } from "next/navigation";-import { type FormEvent, type ReactNode, useEffect, useState } from "react";+import { type FormEvent, type ReactNode, useEffect, useId, useState } from "react";import { TeamModeOffer } from "@/components/people/TeamModeOffer";+import Button from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";+import SectionTabs, { sectionPanelProps } from "@/components/ui/SectionTabs";import { useWorkspace } from "@/components/workspace/WorkspaceContext";import {archivePerson,@@ -44,6 +47,14 @@ const ALL_SCOPES = [const CHANNELS = ["any", "slack", "discord", "telegram", "email"];+const INPUT_CLS =+ "w-full h-11 px-3 rounded-xl bg-surface-input/60 border border-line text-[15px] text-fg placeholder-fg-subtle focus:outline-none focus:border-accent";+const LABEL_CLS = "text-sm text-fg-muted flex flex-col gap-1.5";+const HINT_CLS = "text-[13px] text-fg-subtle mt-1";+const SECTION_TITLE_CLS = "text-lg font-semibold text-fg";+const INTRO_CLS = "text-[15px] text-fg-muted mt-1 mb-4";+const ROW_CLS = "px-4 py-3 rounded-xl border border-line bg-surface-elevated text-[15px]";+// ---------------------------------------------------------------------------// How they respond to outreach (attunement outcome ledger)// ---------------------------------------------------------------------------@@ -57,27 +68,28 @@ function OutreachSection({ personId }: { personId: number }) {.catch(() => setRows([]));}, [personId]);- if (!rows || rows.length === 0) return null;+ if (!rows) return <p className="text-[15px] text-fg-muted">Loading…</p>;return (- <section className="mb-6">- <h2 className="text-xs font-semibold uppercase tracking-wide text-fg-muted mb-1">- How they respond- </h2>- <p className="text-xs text-fg-muted mb-3">+ <section>+ <h2 className={SECTION_TITLE_CLS}>How they respond</h2>+ <p className={INTRO_CLS}>Proactive messages over the last 30 days. Kinds they reliably ignore aresent less often.</p>- <div className="space-y-1.5">+ {rows.length === 0 && (+ <p className="text-[15px] text-fg-muted">No proactive messages to them in the last 30 days.</p>+ )}+ <div className="space-y-2">{rows.map((r) => {const answered = r.replied + r.acted;const resolved = answered + r.ignored;return (<divkey={r.source}- className="flex items-center justify-between gap-3 px-4 py-2 rounded-lg border border-line bg-surface-elevated text-sm"+ className={`flex flex-wrap items-center justify-between gap-x-3 gap-y-1 ${ROW_CLS}`}><span className="text-fg capitalize">{r.label}</span>- <span className="text-xs text-fg-muted">+ <span className="text-sm text-fg-muted">{resolved > 0 ? `${answered} of ${resolved} answered` : "no answers yet"}{r.pending > 0 ? ` · ${r.pending} pending` : ""}</span>@@ -122,104 +134,92 @@ function WorkingStyleSection({ personId }: { personId: number }) {}}- if (!style) return null;+ if (!style) return <p className="text-[15px] text-fg-muted">Loading…</p>;const rules = draft.split("\n").map((line) => line.replace(/^[-•]\s*/, "").trim()).filter(Boolean);return (- <section className="mb-6">- <div className="flex items-center justify-between mb-1">- <h2 className="text-xs font-semibold uppercase tracking-wide text-fg-muted">- How I work with them- </h2>+ <section>+ <div className="flex items-start justify-between gap-3">+ <h2 className={SECTION_TITLE_CLS}>How I work with them</h2>{!editing && (- <div className="flex gap-3 text-xs">- <button- type="button"+ <div className="flex items-center gap-1 flex-shrink-0 -mt-1.5">+ <Button+ size="md"disabled={busy}onClick={() => {setDraft(style.rules.map((r) => r.text).join("\n"));setEditing(true);}}- className="text-indigo-400 hover:text-indigo-300 disabled:opacity-50"- >- Edit- </button>- <button- type="button"- disabled={busy}- onClick={() =>- run(() => savePersonWorkingStyle(personId, null, !style.locked))- }- className="text-indigo-400 hover:text-indigo-300 disabled:opacity-50">- {style.locked ? "Unlock" : "Lock"}- </button>- {style.rules.length > 0 && (- <button- type="button"- disabled={busy}- onClick={() =>- run(async () => {- await resetPersonWorkingStyle(personId);- return getPersonWorkingStyle(personId);- })- }- className="text-fg-muted hover:text-fg disabled:opacity-50"- >- Reset- </button>- )}+ Edit rules+ </Button>+ <OverflowMenu+ label="More working-style actions"+ items={[+ {+ label: style.locked ? "Unlock (keep learning)" : "Lock (stop learning)",+ disabled: busy,+ onSelect: () => void run(() => savePersonWorkingStyle(personId, null, !style.locked)),+ },+ ...(style.rules.length > 0+ ? [{+ label: "Reset what was learned",+ danger: true,+ disabled: busy,+ onSelect: () =>+ void run(async () => {+ await resetPersonWorkingStyle(personId);+ return getPersonWorkingStyle(personId);+ }),+ }]+ : []),+ ]}+ /></div>)}</div>- <p className="text-xs text-fg-muted mb-3">+ <p className={INTRO_CLS}>How replies are written for them, learned from their own 👍/👎 and requests.{style.locked? " Locked — kept as is.": " Updated as they use it; rules you type are always kept. Lock it to stop learning."}</p>- {error && <p className="text-xs text-rose-300 mb-2">{error}</p>}+ {error && <p className="text-sm text-rose-500 mb-3">{error}</p>}{editing ? (- <div className="space-y-2">+ <div className="space-y-3"><textareavalue={draft}onChange={(e) => setDraft(e.target.value)}rows={STYLE_TEXTAREA_ROWS}placeholder="One rule per line, e.g. Lead with the recommendation, then the numbers."- className="w-full px-3 py-2 rounded-lg border border-line bg-surface-elevated text-sm text-fg"+ className="w-full px-3 py-2.5 rounded-xl border border-line bg-surface-input/60 text-[15px] text-fg focus:outline-none focus:border-accent"/>{rules.length > MAX_STYLE_RULES && (- <p className="text-xs text-amber-300">At most {MAX_STYLE_RULES} rules.</p>+ <p className="text-sm text-amber-500">At most {MAX_STYLE_RULES} rules.</p>)}- <div className="flex gap-3 text-xs">- <button- type="button"+ <div className="flex gap-2">+ <Button+ variant="primary"disabled={busy || rules.length > MAX_STYLE_RULES}onClick={() => run(() => savePersonWorkingStyle(personId, rules, style.locked))}- className="text-indigo-400 hover:text-indigo-300 disabled:opacity-50">{busy ? "Saving…" : "Save"}- </button>- <button- type="button"- disabled={busy}- onClick={() => setEditing(false)}- className="text-fg-muted hover:text-fg disabled:opacity-50"- >+ </Button>+ <Button disabled={busy} onClick={() => setEditing(false)}>Cancel- </button>+ </Button></div></div>) : style.rules.length === 0 ? (- <p className="text-sm text-fg-muted">Nothing learned yet.</p>+ <p className="text-[15px] text-fg-muted">Nothing learned yet.</p>) : (- <ul className="space-y-1.5">+ <ul className="space-y-2">{style.rules.map((r) => (<likey={r.text}- className="px-4 py-2 rounded-lg border border-line bg-surface-elevated text-sm text-fg"+ className={`${ROW_CLS} text-fg`}>{r.text}</li>@@ -305,21 +305,19 @@ function OpenLoopsSection({if (!canList && !canAssign) return null;const now = mountedAt;return (- <section className="mb-6">- <h2 className="text-xs font-semibold uppercase tracking-wide text-fg-muted mb-1">- Open loops- </h2>- <p className="text-xs text-fg-muted mb-3">+ <section className="mt-8">+ <h2 className={SECTION_TITLE_CLS}>Open loops</h2>+ <p className={INTRO_CLS}>Things they committed to, were asked for in conversation, or were assigned here.Overdue ones are followed up automatically; close one once it's done.</p>{canList && (<>- {error && <p className="text-xs text-rose-300 mb-2">{error}</p>}+ {error && <p className="text-sm text-rose-500 mb-3">{error}</p>}{loops === null ? (- !error && <p className="text-sm text-fg-muted">Loading…</p>+ !error && <p className="text-[15px] text-fg-muted">Loading…</p>) : loops.length === 0 ? (- <p className="text-sm text-fg-muted">Nothing open.</p>+ <p className="text-[15px] text-fg-muted">Nothing open.</p>) : (<div className="space-y-2">{loops.map((l) => {@@ -327,23 +325,22 @@ function OpenLoopsSection({return (<divkey={l.loop_id}- className="flex items-start justify-between gap-3 px-4 py-2.5 rounded-lg border border-line bg-surface-elevated text-sm"+ className={`flex items-center justify-between gap-3 ${ROW_CLS}`}><div className="min-w-0"><p className="text-fg">{l.description}</p>- <p className={`text-xs mt-0.5 ${overdue ? "text-amber-300" : "text-fg-muted"}`}>+ <p className={`text-sm mt-0.5 ${overdue ? "text-amber-600 dark:text-amber-400" : "text-fg-muted"}`}>{overdue ? "Overdue since " : "Due "}{new Date(l.due_at).toLocaleDateString()}</p></div>- <button- type="button"+ <Buttondisabled={closing === l.loop_id}onClick={() => close(l.loop_id)}- className="flex-shrink-0 text-xs text-indigo-400 hover:text-indigo-300 disabled:opacity-50"+ className="flex-shrink-0">{closing === l.loop_id ? "Closing…" : "Mark done"}- </button>+ </Button></div>);})}@@ -352,41 +349,39 @@ function OpenLoopsSection({</>)}{canAssign && (- <form onSubmit={assign} className="mt-3 flex flex-col sm:flex-row gap-2 sm:items-end">- <label className="flex-1 text-xs text-fg-muted flex flex-col gap-1">+ <form onSubmit={assign} className="mt-4 flex flex-col sm:flex-row gap-3 sm:items-end">+ <label className={`flex-1 ${LABEL_CLS}`}>Assign a task<inputvalue={task}onChange={(e) => setTask(e.target.value)}maxLength={200}placeholder="e.g. send the vendor quote"- className="w-full bg-surface-elevated border border-line rounded-lg px-3 py-2 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}/></label>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Due (optional)<inputtype="date"value={dueDate}onChange={(e) => setDueDate(e.target.value)}- className="bg-surface-elevated border border-line rounded-lg px-3 py-2 text-sm text-fg focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}/></label>- <button- type="submit"- disabled={assigning || !task.trim()}- className="px-3 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white text-sm disabled:opacity-50"- >+ <Button type="submit" variant="primary" disabled={assigning || !task.trim()}>{assigning ? "Assigning…" : "Assign"}- </button>+ </Button></form>)}- {assignError && <p className="text-xs text-rose-300 mt-2">{assignError}</p>}- {assigned && <p className="text-xs text-fg-muted mt-2">{assigned}</p>}+ {assignError && <p className="text-sm text-rose-500 mt-2">{assignError}</p>}+ {assigned && <p className="text-sm text-fg-muted mt-2">{assigned}</p>}</section>);}+type PersonTab = "overview" | "approvals" | "respond" | "style";+const WEEKDAY_NAMES = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];// ---------------------------------------------------------------------------@@ -410,12 +405,12 @@ function DisclosureSection({type="button"onClick={onToggle}aria-expanded={open}- className="flex items-center justify-between w-full py-1.5 text-xs font-medium text-fg-muted hover:text-fg transition-colors"+ className="flex items-center justify-between w-full min-h-11 py-2 text-[15px] font-medium text-fg hover:text-accent transition-colors"><span>{label}</span>- <span aria-hidden="true" className="text-fg-subtle text-[10px]">{open ? "▲" : "▼"}</span>+ <span aria-hidden="true" className="text-fg-subtle text-xs">{open ? "▲" : "▼"}</span></button>- {open && <div className="pt-2 space-y-3">{children}</div>}+ {open && <div className="pt-2 pb-1 space-y-4">{children}</div>}</div>);}@@ -439,65 +434,62 @@ function WindowRow({ win, onChange, onRemove }: WindowRowProps) {}return (- <div className="rounded-lg border border-line bg-surface-input p-3 space-y-2">- <div className="flex flex-wrap gap-1">+ <div className="rounded-xl border border-line bg-surface-elevated p-4 space-y-3">+ <div className="flex flex-wrap gap-1.5">{WEEKDAY_NAMES.map((name, idx) => (<buttonkey={idx}type="button"onClick={() => toggleDay(idx)}- className={`px-2 py-0.5 rounded text-xs font-medium border transition-colors ${+ aria-pressed={win.weekdays.includes(idx)}+ className={`h-10 min-w-[3rem] px-3 rounded-xl text-sm font-medium border transition-colors ${win.weekdays.includes(idx)- ? "bg-indigo-600/40 border-indigo-500/50 text-indigo-200"- : "bg-surface-overlay border-line text-fg-muted hover:border-indigo-500/40"+ ? "bg-accent/10 border-accent/60 text-fg"+ : "bg-surface-elevated border-line text-fg-muted hover:border-line-strong"}`}>{name}</button>))}</div>- <div className="grid grid-cols-3 gap-2">- <label className="text-[10px] text-fg-muted flex flex-col gap-0.5">+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">+ <label className={LABEL_CLS}>Start<inputtype="time"value={win.start_local}onChange={(e) => onChange({ ...win, start_local: e.target.value })}- className="px-2 py-1 rounded bg-surface-elevated border border-line text-xs focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}/></label>- <label className="text-[10px] text-fg-muted flex flex-col gap-0.5">+ <label className={LABEL_CLS}>End<inputtype="time"value={win.end_local}onChange={(e) => onChange({ ...win, end_local: e.target.value })}- className="px-2 py-1 rounded bg-surface-elevated border border-line text-xs focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}/></label>- <label className="text-[10px] text-fg-muted flex flex-col gap-0.5">+ <label className={LABEL_CLS}>Timezone<inputvalue={win.timezone}onChange={(e) => onChange({ ...win, timezone: e.target.value })}- className="px-2 py-1 rounded bg-surface-elevated border border-line text-xs focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}placeholder="America/Los_Angeles"/></label></div>{win.weekdays.length === 0 && (- <p className="text-[10px] text-amber-400">Select at least one day.</p>+ <p className="text-sm text-amber-600 dark:text-amber-400">Select at least one day.</p>)}{win.end_local <= win.start_local && win.start_local !== "" && win.end_local !== "" && (- <p className="text-[10px] text-amber-400">End time must be after start time.</p>+ <p className="text-sm text-amber-600 dark:text-amber-400">End time must be after start time.</p>)}- <button- type="button"- onClick={onRemove}- className="text-[10px] text-rose-400 hover:text-rose-300"- >+ <Button variant="danger" onClick={onRemove}>Remove window- </button>+ </Button></div>);}@@ -541,6 +533,9 @@ export default function PersonDetailPage() {const [saveErr, setSaveErr] = useState<string | null>(null);const [saved, setSaved] = useState(false);+ const [tab, setTab] = useState<PersonTab>("overview");+ const tabsId = useId();+// Edit-mode disclosure panelsconst [showContact, setShowContact] = useState(false);const [showAdvanced, setShowAdvanced] = useState(false);@@ -685,7 +680,7 @@ export default function PersonDetailPage() {}async function doArchive() {- if (!window.confirm("Archive this person? They won't receive new assignments but their history is preserved.")) return;+ if (!window.confirm("Archive this person? Archiving removes them from routing and the active roster: they won't receive new assignments, but their history is preserved.")) return;setArchiving(true);setSaveErr(null);try {@@ -697,14 +692,36 @@ export default function PersonDetailPage() {}}+ // Contacts get the Overview alone: they approve nothing, have no+ // availability and are never chased. An archived person keeps their+ // approvals and availability on record but nothing new is learned.+ const contactView = editing ? formContact : contact;+ const tabs: { id: PersonTab; label: string }[] = person+ ? [+ { id: "overview", label: "Overview" },+ ...(contactView ? [] : [{ id: "approvals" as const, label: "Approvals & availability" }]),+ ...(person.archived || contact+ ? []+ : [+ { id: "respond" as const, label: "How they respond" },+ { id: "style" as const, label: "How I work with them" },+ ]),+ ]+ : [];+ const activeTab: PersonTab = tabs.some((t) => t.id === tab) ? tab : "overview";+ const menuItems =+ person && !person.is_principal && !person.archived+ ? [{ label: archiving ? "Archiving…" : "Archive person", danger: true, disabled: archiving, onSelect: () => void doArchive() }]+ : [];+return (<div className="flex flex-col h-full bg-surface">{offerFor && <TeamModeOffer name={offerFor} onDone={() => setOfferFor(null)} />}<main className="flex-1 overflow-y-auto">- <div className="max-w-2xl mx-auto px-4 sm:px-6 py-6">- {loading && <p className="text-fg-muted text-sm">Loading…</p>}+ <div className="max-w-3xl mx-auto px-4 sm:px-6 py-8">+ {loading && <p className="text-fg-muted text-[15px]">Loading…</p>}{error && (- <div className="p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm">+ <div className="p-4 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-500 text-[15px]">{error}</div>)}@@ -712,106 +729,112 @@ export default function PersonDetailPage() {{person && (<>{/* Header */}- <div className="flex items-start gap-3 mb-6">- <div className="w-10 h-10 rounded-full bg-gradient-to-br from-indigo-500 to-violet-600 flex items-center justify-center flex-shrink-0">- <span className="text-white text-sm font-bold">- {person.full_name.charAt(0).toUpperCase()}- </span>+ <div className="flex flex-wrap items-start gap-4 mb-6">+ <div className="w-14 h-14 rounded-full bg-accent/10 text-accent flex items-center justify-center flex-shrink-0 text-xl font-bold">+ {person.full_name.charAt(0).toUpperCase()}</div>- <div className="flex-1 min-w-0">- <h1 className="text-xl font-semibold text-fg">+ <div className="flex-1 min-w-[12rem]">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg">{person.full_name}+ </h1>+ <div className="mt-1 flex flex-wrap items-center gap-2">+ <span className="text-[15px] text-fg-muted">{person.role || "No role set"}</span>{person.is_principal && (- <span className="ml-2 inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium bg-violet-500/20 text-violet-300 border-violet-500/30 align-middle">+ <span className="inline-block px-2 py-0.5 rounded-full text-xs font-medium bg-accent/10 text-accent">Principal</span>)}{contact && (- <span className="ml-2 inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium bg-sky-500/20 text-sky-300 border-sky-500/30 align-middle">+ <span className="inline-block px-2 py-0.5 rounded-full text-xs font-medium bg-sky-500/10 text-sky-600 dark:text-sky-400">Contact</span>)}{person.archived && (- <span className="ml-2 inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium bg-rose-500/20 text-rose-300 border-rose-500/30 align-middle">+ <span className="inline-block px-2 py-0.5 rounded-full text-xs font-medium bg-rose-500/10 text-rose-500">Archived</span>)}- </h1>- <p className="text-sm text-fg-muted">{person.role || "No role set"}</p>+ </div></div>- <div className="flex gap-2 flex-shrink-0">+ <div className="flex items-center gap-2 flex-shrink-0">{saved && (- <span className="text-xs text-emerald-400 self-center">Saved ✓</span>+ <span className="text-sm text-emerald-600 dark:text-emerald-400">Saved ✓</span>)}{editing ? (<>- <button+ <Button+ variant="primary"disabled={saving || !form.full_name.trim()}onClick={save}- className="px-3 py-1.5 text-xs rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white disabled:opacity-50">{saving ? "Saving…" : "Save"}- </button>- <button+ </Button>+ <Buttondisabled={saving}onClick={() => {resetForm(person);setEditing(false);setSaveErr(null);}}- className="px-3 py-1.5 text-xs rounded-lg border border-line hover:bg-surface-overlay disabled:opacity-50">Cancel- </button>+ </Button></>) : (- <button- onClick={() => setEditing(true)}- className="px-3 py-1.5 text-xs rounded-lg border border-line hover:bg-surface-overlay"- >+ <Button variant="primary" onClick={() => setEditing(true)}>Edit- </button>+ </Button>)}+ <OverflowMenu label={`More actions for ${person.full_name}`} items={menuItems} /></div></div>{saveErr && (- <div className="mb-4 p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm">+ <div className="mb-4 p-4 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-500 text-[15px]">{saveErr}</div>)}+ {tabs.length > 1 && (+ <div className="mb-6">+ <SectionTabs idBase={tabsId} label="About this person" tabs={tabs} active={activeTab} onChange={setTab} />+ </div>+ )}++ <div {...(tabs.length > 1 ? sectionPanelProps(tabsId, activeTab) : {})}>+ {activeTab === "overview" && (+ <>{/* Core fields */}- <section className="rounded-xl border border-line bg-surface-elevated px-4 mb-6">+ <section className="rounded-2xl border border-line bg-surface-elevated px-5">{editing ? (- <div className="py-4 space-y-3">+ <div className="py-5 space-y-4">{/* Always-visible in edit mode */}- <div className="grid grid-cols-2 gap-3">- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">+ <label className={LABEL_CLS}>Full name<inputvalue={form.full_name}onChange={(e) => setForm((f) => ({ ...f, full_name: e.target.value }))}- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}/></label>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>{formContact ? "Role and company" : "Role"}<inputvalue={form.role}onChange={(e) => setForm((f) => ({ ...f, role: e.target.value }))}- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}/></label></div>{!person.is_principal && viewerIsPrincipal && (- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Team member or contact<selectvalue={form.kind}onChange={(e) => setForm((f) => ({ ...f, kind: e.target.value as PersonKind }))}- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}><option value="team">Team member — can sign in, message the Executive and approve</option><option value="contact">Contact — outside the team and private to you, emailed only when you ask</option>@@ -825,100 +848,100 @@ export default function PersonDetailPage() {open={showContact}onToggle={() => setShowContact((v) => !v)}>- <div className="grid grid-cols-2 gap-3">+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4"><div>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Preferred channel<selectvalue={form.preferred_channel}onChange={(e) => setForm((f) => ({ ...f, preferred_channel: e.target.value }))}- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}>{CHANNELS.map((c) => (<option key={c} value={c}>{c}</option>))}</select></label>- <p className="text-[10px] text-fg-muted mt-1">+ <p className={HINT_CLS}>Proposals routed to this person are sent via {form.preferred_channel === "any" ? "any available channel" : form.preferred_channel}.</p></div>{!formContact && (<div>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Expected reply within- <div className="flex items-center gap-1.5">+ <div className="flex items-center gap-2"><inputtype="number"min={1}value={form.response_sla_hours}onChange={(e) => setForm((f) => ({ ...f, response_sla_hours: e.target.value }))}- className="flex-1 px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={`${INPUT_CLS} flex-1 min-w-0`}/>- <span className="text-xs text-fg-muted flex-shrink-0">hours</span>+ <span className="text-sm text-fg-muted flex-shrink-0">hours</span></div></label>- <p className="text-[10px] text-fg-muted mt-1">- Items overdue in Today after {form.response_sla_hours || 24}h with no reply.+ <p className={HINT_CLS}>+ Items show as overdue on Home after {form.response_sla_hours || 24}h with no reply.</p></div>)}</div>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}><inputtype="email"value={form.email}onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}/></label>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Other addresses<textareavalue={form.email_aliases}onChange={(e) => setForm((f) => ({ ...f, email_aliases: e.target.value }))}rows={2}placeholder="[email protected]"- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={`${INPUT_CLS} h-auto py-2.5`}/>- <span className="text-[10px] text-fg-subtle">+ <span className={HINT_CLS}>One per line. Mail from these reaches them, and they can be emailedhere — but only the address above signs in.</span></label>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Slack user ID<inputvalue={form.slack_user_id}onChange={(e) => setForm((f) => ({ ...f, slack_user_id: e.target.value }))}- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}placeholder="U01ABC123"/></label>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Discord user ID<inputvalue={form.discord_user_id}onChange={(e) => setForm((f) => ({ ...f, discord_user_id: e.target.value }))}- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}placeholder="123456789012345678"/>- <span className="text-[10px] text-fg-muted">+ <span className={HINT_CLS}>Right-click your Discord username and "Copy User ID" (developer mode required).</span></label>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Telegram chat ID<inputvalue={form.telegram_chat_id}onChange={(e) => setForm((f) => ({ ...f, telegram_chat_id: e.target.value }))}- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}placeholder="123456789"/></label>@@ -930,19 +953,19 @@ export default function PersonDetailPage() {open={showAdvanced}onToggle={() => setShowAdvanced((v) => !v)}>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>On leave until<inputtype="date"value={form.on_leave_until}onChange={(e) => setForm((f) => ({ ...f, on_leave_until: e.target.value }))}- className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}/></label></DisclosureSection></div>) : (- <div className="divide-y divide-line">+ <dl className="divide-y divide-line">{[["Kind", contact ? "Contact — outside the team" : "Team member"],["Preferred channel", person.preferred_channel],@@ -954,39 +977,49 @@ export default function PersonDetailPage() {["Telegram chat ID", person.telegram_chat_id ?? "—"],["On leave until", person.on_leave_until ?? "—"],].map(([label, value]) => (- <div key={label} className="flex items-start gap-3 py-2">- <div className="w-40 flex-shrink-0 text-xs text-fg-muted pt-0.5">{label}</div>- <div className="text-sm text-fg">{value}</div>+ <div key={label} className="flex flex-col sm:flex-row sm:items-baseline gap-0.5 sm:gap-4 py-3">+ <dt className="sm:w-48 flex-shrink-0 text-sm text-fg-muted">{label}</dt>+ <dd className="text-[15px] text-fg break-words min-w-0">{value}</dd></div>))}- </div>+ </dl>)}</section>- {/* Authority scope — a contact approves nothing */}- {!(editing ? formContact : contact) && (- <section className="mb-6">- <h2 className="text-xs font-semibold uppercase tracking-wide text-fg-muted mb-3">- What this person approves- </h2>+ {!person.archived && !contact && (+ <OpenLoopsSection+ personId={personId}+ canList={viewerIsPrincipal || viewerPersonId === personId}+ canAssign={viewerPersonId !== null}+ />+ )}+ </>+ )}++ {/* Authority scope and availability — a contact approves nothing and is never chased */}+ {activeTab === "approvals" && !contactView && (+ <>+ <section>+ <h2 className={SECTION_TITLE_CLS}>What this person approves</h2>+ <p className={INTRO_CLS}>Proposals in these areas are routed to them for approval.</p>{editing ? (- <div className="grid grid-cols-3 gap-2">+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">{ALL_SCOPES.map(({ value, label, hint }) => {const active = form.authority_scope.includes(value);return (<buttonkey={value}type="button"+ aria-pressed={active}onClick={() => toggleScope(value)}- title={hint}- className={`px-2 py-2 rounded-lg border text-xs transition-colors text-left ${+ className={`px-3.5 py-2.5 rounded-xl border text-left transition-colors ${active- ? "bg-indigo-600/30 border-indigo-500/50 text-indigo-300"- : "bg-surface-elevated border-line text-fg-muted hover:border-indigo-500/40"+ ? "bg-accent/10 border-accent/60 text-fg"+ : "bg-surface-elevated border-line text-fg-muted hover:border-line-strong"}`}>- <div className="font-medium">{label}</div>- <div className="text-[9px] leading-tight mt-0.5 opacity-70 line-clamp-2">{hint}</div>+ <div className="text-[15px] font-medium">{label}</div>+ <div className="text-[13px] leading-snug mt-0.5 text-fg-muted">{hint}</div></button>);})}@@ -994,17 +1027,18 @@ export default function PersonDetailPage() {) : (<div className="flex flex-wrap gap-2">{person.authority_scope.length === 0 ? (- <p className="text-sm text-fg-muted">No approval authority.</p>+ <p className="text-[15px] text-fg-muted">No approval authority.</p>) : (person.authority_scope.map((s) => {const entry = ALL_SCOPES.find((x) => x.value === s);return (<spankey={s}- className={`inline-block px-2 py-1 rounded-lg border text-xs font-medium ${+ title={entry?.hint}+ className={`inline-block px-3 py-1.5 rounded-full border text-sm font-medium ${s === "wildcard"- ? "bg-indigo-500/20 text-indigo-300 border-indigo-500/30"- : "bg-surface-input/40 text-fg border-line"+ ? "bg-accent/10 text-accent border-accent/30"+ : "bg-surface-elevated text-fg border-line"}`}>{entry?.label ?? s}@@ -1016,34 +1050,22 @@ export default function PersonDetailPage() {)}</section>- )}-- {/* Availability windows — contacts are never chased */}- {!(editing ? formContact : contact) && (- <section className="mb-6">- <div className="flex items-center justify-between mb-3">- <h2 className="text-xs font-semibold uppercase tracking-wide text-fg-muted">- Availability Windows- </h2>+ <section className="mt-8">+ <div className="flex items-start justify-between gap-3">+ <h2 className={SECTION_TITLE_CLS}>Availability windows</h2>{editing && (- <button- type="button"- onClick={addWindow}- className="text-xs text-indigo-400 hover:text-indigo-300"- >- + Add window- </button>+ <Button onClick={addWindow} className="flex-shrink-0 -mt-1.5">+ Add window+ </Button>)}</div>+ <div className="mb-4" />{editing ? (- <div className="space-y-2">+ <div className="space-y-3">{form.availability.length === 0 && (- <p className="text-sm text-fg-muted">- No windows — person is considered always available.{" "}- <button onClick={addWindow} className="text-indigo-400 hover:underline">- Add one →- </button>+ <p className="text-[15px] text-fg-muted">+ No windows — person is considered always available.</p>)}{form.availability.map((w, i) => (@@ -1058,17 +1080,17 @@ export default function PersonDetailPage() {) : (<div>{person.availability.length === 0 ? (- <p className="text-sm text-fg-muted">Always available (no windows set).</p>+ <p className="text-[15px] text-fg-muted">Always available (no windows set).</p>) : (<div className="space-y-2">{person.availability.map((w, i) => (<divkey={i}- className="flex items-center gap-3 px-4 py-2.5 rounded-lg border border-line bg-surface-elevated text-sm"+ className={`flex flex-wrap items-center gap-x-3 gap-y-2 ${ROW_CLS}`}>- <div className="flex gap-1">+ <div className="flex flex-wrap gap-1">{w.weekdays.map((d) => (- <span key={d} className="px-1.5 py-0.5 rounded bg-surface-overlay text-xs text-fg">+ <span key={d} className="px-2 py-0.5 rounded-lg bg-surface-overlay text-sm text-fg">{WEEKDAY_NAMES[d] ?? d}</span>))}@@ -1076,7 +1098,7 @@ export default function PersonDetailPage() {<span className="text-fg">{w.start_local} – {w.end_local}</span>- <span className="text-fg-muted text-xs">{w.timezone}</span>+ <span className="text-fg-muted text-sm">{w.timezone}</span></div>))}</div>@@ -1084,37 +1106,12 @@ export default function PersonDetailPage() {</div>)}</section>-+ </>)}- {!person.archived && !contact && (- <OpenLoopsSection- personId={personId}- canList={viewerIsPrincipal || viewerPersonId === personId}- canAssign={viewerPersonId !== null}- />- )}- {!person.archived && !contact && <OutreachSection personId={personId} />}- {!person.archived && !contact && <WorkingStyleSection personId={personId} />}-- {/* Archive */}- {!person.is_principal && !person.archived && (- <section className="border-t border-line pt-6">- <h2 className="text-xs font-semibold uppercase tracking-wide text-fg-muted mb-2">- Danger zone- </h2>- <p className="text-xs text-fg-muted mb-3">- Archiving removes this person from routing and the active roster. Their history is preserved.- </p>- <button- disabled={archiving}- onClick={doArchive}- className="px-4 py-2 text-sm rounded-lg bg-rose-500/10 hover:bg-rose-500/20 border border-rose-500/30 text-rose-300 disabled:opacity-50"- >- {archiving ? "Archiving…" : "Archive person"}- </button>- </section>- )}+ {activeTab === "respond" && <OutreachSection personId={personId} />}+ {activeTab === "style" && <WorkingStyleSection personId={personId} />}+ </div></>)}</div>diff --git a/packages/ui/src/app/people/page.tsx b/packages/ui/src/app/people/page.tsxindex bb3aea19..2a3d0f1a 100644--- a/packages/ui/src/app/people/page.tsx+++ b/packages/ui/src/app/people/page.tsx@@ -1,10 +1,13 @@"use client";import Link from "next/link";-import { type ReactNode, useEffect, useRef, useState } from "react";+import { type ReactNode, useEffect, useId, useRef, useState } from "react";import { useAskOEFormContext } from "@/components/askoe/AskOEContext";import { TeamModeOffer } from "@/components/people/TeamModeOffer";+import Button from "@/components/ui/Button";+import SectionTabs, { sectionPanelProps } from "@/components/ui/SectionTabs";+import SidePanel from "@/components/ui/SidePanel";import { useWorkspace } from "@/components/workspace/WorkspaceContext";import {createPerson,@@ -21,6 +24,7 @@ import {hiddenTeamCount,isContact,peopleForTab,+ personCardStatus,shouldOfferTeamMode,tabsFor,type PeopleTab,@@ -46,59 +50,47 @@ const CHANNELS = ["any", "slack", "discord", "telegram", "email"];const KINDS: PersonKind[] = ["team", "contact"];// ----------------------------------------------------------------------------// PersonCard (unchanged from read-only)+// PersonCard — name, role, channel and one status. Approval scopes are on+// the person's own page.// ----------------------------------------------------------------------------function ScopePill({ scope }: { scope: string }) {- const entry = ALL_SCOPES.find((s) => s.value === scope);- const label = entry?.label ?? scope;- const isStar = scope === "wildcard";- return (- <span- className={`inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium ${- isStar- ? "bg-indigo-500/20 text-indigo-300 border-indigo-500/30"- : "bg-surface-input/40 text-fg-muted border-line"- }`}- >- {label}- </span>- );+const TONE_DOT = { ok: "bg-emerald-500", warn: "bg-amber-500", muted: "bg-fg-subtle" } as const;++function channelLabel(channel: string): string {+ return channel === "any" ? "Any channel" : channel.charAt(0).toUpperCase() + channel.slice(1);}-function PersonCard({ person }: { person: Person }) {+function PersonCard({ person, today }: { person: Person; today: string }) {const contact = isContact(person);+ const status = personCardStatus(person, today);return (<Linkhref={`/people/${person.id}`}- className="block rounded-xl border border-line bg-surface-elevated hover:bg-surface-overlay transition-colors p-4 group"+ className="flex items-start gap-4 rounded-2xl border border-line bg-surface-elevated hover:bg-surface-hover hover:border-line-strong transition-colors p-5 group focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60">- <div className="flex items-start justify-between gap-2 mb-2">- <div>- <div className="text-sm font-semibold text-fg group-hover:text-indigo-300 transition-colors flex items-center gap-2">+ <div className="w-11 h-11 rounded-full bg-accent/10 text-accent flex items-center justify-center flex-shrink-0 text-base font-semibold">+ {person.full_name.charAt(0).toUpperCase()}+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">+ <span className="text-base font-semibold text-fg group-hover:text-accent transition-colors truncate">{person.full_name}- {person.is_principal && (- <span className="inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium bg-violet-500/20 text-violet-300 border-violet-500/30">- Principal- </span>- )}- </div>- <div className="text-xs text-fg-muted mt-0.5">{person.role || "—"}</div>+ </span>+ {person.is_principal && (+ <span className="inline-block px-2 py-0.5 rounded-full text-xs font-medium bg-accent/10 text-accent">+ Principal+ </span>+ )}</div>- {contact ? (- <div className="flex-shrink-0 text-xs text-fg-muted">{person.email ? "Email on file" : "No email"}</div>- ) : (- <div className="flex-shrink-0 text-xs text-fg-muted capitalize">{person.preferred_channel}</div>- )}- </div>- {!contact && <div className="text-xs text-fg-muted mb-2">SLA: {person.response_sla_hours}h</div>}- {!contact && person.authority_scope.length > 0 && (- <div className="flex flex-wrap gap-1">- {person.authority_scope.map((s) => (- <ScopePill key={s} scope={s} />- ))}+ <div className="text-[15px] text-fg-muted mt-0.5 truncate">{person.role || "—"}</div>+ <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-fg-muted">+ {!contact && <span>{channelLabel(person.preferred_channel)}</span>}+ <span className="inline-flex items-center gap-1.5">+ <span aria-hidden="true" className={`h-2 w-2 rounded-full ${TONE_DOT[status.tone]}`} />+ {status.label}+ </span></div>- )}+ </div></Link>);}@@ -129,6 +121,11 @@ const BLANK_FORM = {authority_scope: [] as string[],};+const INPUT_CLS =+ "w-full h-11 px-3 rounded-xl bg-surface-input/60 border border-line text-[15px] text-fg placeholder-fg-subtle focus:outline-none focus:border-accent";+const LABEL_CLS = "text-sm text-fg-muted flex flex-col gap-1.5";+const HINT_CLS = "text-[13px] text-fg-subtle mt-1";+function DisclosureSection({label,open,@@ -146,12 +143,39 @@ function DisclosureSection({type="button"onClick={onToggle}aria-expanded={open}- className="flex items-center justify-between w-full py-1.5 text-xs font-medium text-fg-muted hover:text-fg transition-colors"+ className="flex items-center justify-between w-full min-h-11 py-2 text-[15px] font-medium text-fg hover:text-accent transition-colors"><span>{label}</span>- <span aria-hidden="true" className="text-fg-subtle text-[10px]">{open ? "▲" : "▼"}</span>+ <span aria-hidden="true" className="text-fg-subtle text-xs">{open ? "▲" : "▼"}</span></button>- {open && <div className="pt-2 space-y-3">{children}</div>}+ {open && <div className="pt-2 pb-1 space-y-4">{children}</div>}+ </div>+ );+}++// The approval scopes as toggles, each with what it routes to the person.+function ScopePicker({ selected, onToggle }: { selected: string[]; onToggle: (value: string) => void }) {+ return (+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">+ {ALL_SCOPES.map(({ value, label, hint }) => {+ const active = selected.includes(value);+ return (+ <button+ key={value}+ type="button"+ aria-pressed={active}+ onClick={() => onToggle(value)}+ className={`px-3.5 py-2.5 rounded-xl border text-left transition-colors ${+ active+ ? "bg-accent/10 border-accent/60 text-fg"+ : "bg-surface-elevated border-line text-fg-muted hover:border-line-strong"+ }`}+ >+ <div className="text-[15px] font-medium">{label}</div>+ <div className="text-[13px] leading-snug mt-0.5 text-fg-muted">{hint}</div>+ </button>+ );+ })}</div>);}@@ -169,7 +193,10 @@ function AddPersonModal({ initialKind, canAddContacts, onCreated, onClose }: Addconst nameRef = useRef<HTMLInputElement>(null);useEffect(() => {- nameRef.current?.focus();+ // After the panel has taken focus on open, so it remembers the button+ // that opened it (and returns focus there on close).+ const id = requestAnimationFrame(() => nameRef.current?.focus());+ return () => cancelAnimationFrame(id);}, []);// Registered with Ask OE for the modal's lifetime — closing the modal@@ -267,7 +294,7 @@ function AddPersonModal({ initialKind, canAddContacts, onCreated, onClose }: Add}setForm(next);// Open the disclosures so the suggested values are visible to review.- if (applied.some((k) => ["email", "slack_user_id", "discord_user_id", "telegram_chat_id", "preferred_channel", "response_sla_hours"].includes(k))) {+ if (applied.some((k) => ["slack_user_id", "discord_user_id", "telegram_chat_id", "preferred_channel", "response_sla_hours"].includes(k))) {setShowContact(true);}if (applied.includes("authority_scope")) setShowAuthority(true);@@ -318,17 +345,31 @@ function AddPersonModal({ initialKind, canAddContacts, onCreated, onClose }: Add}}+ const title = contact ? "Add contact" : "Add person";return (- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60" onClick={saving ? undefined : onClose}>- <div- className="w-full max-w-lg bg-surface border border-line rounded-2xl shadow-2xl p-6 mx-4 max-h-[90vh] overflow-y-auto"- onClick={(e) => e.stopPropagation()}- >- <h2 className="text-base font-semibold text-fg mb-4">{contact ? "Add contact" : "Add person"}</h2>-- <div className="space-y-3">+ <SidePanel+ open+ onClose={saving ? () => {} : onClose}+ title={title}+ footer={+ <div className="flex gap-2">+ <Button+ variant="primary"+ disabled={saving || !form.full_name.trim()}+ onClick={submit}+ className="flex-1"+ >+ {saving ? "Creating…" : title}+ </Button>+ <Button disabled={saving} onClick={onClose}>+ Cancel+ </Button>+ </div>+ }+ >+ <div className="space-y-4">{canAddContacts && !form.is_principal && (- <div role="radiogroup" aria-label="Team member or contact" className="grid grid-cols-2 gap-2">+ <div role="radiogroup" aria-label="Team member or contact" className="grid grid-cols-1 sm:grid-cols-2 gap-2">{KINDS.map((k) => (<buttonkey={k}@@ -336,14 +377,14 @@ function AddPersonModal({ initialKind, canAddContacts, onCreated, onClose }: Addrole="radio"aria-checked={form.kind === k}onClick={() => { setForm((f) => ({ ...f, kind: k })); clearSuggested("kind"); }}- className={`px-3 py-2 rounded-lg border text-left transition-colors ${+ className={`px-4 py-3 rounded-xl border text-left transition-colors ${form.kind === k- ? "bg-indigo-600/30 border-indigo-500/50 text-indigo-300"- : "bg-surface-input border-line text-fg-muted hover:border-indigo-500/40"+ ? "bg-accent/10 border-accent/60 text-fg"+ : "bg-surface-elevated border-line text-fg-muted hover:border-line-strong"} ${suggestedCls("kind")}`}>- <div className="text-sm font-medium">{k === "team" ? "Team member" : "Contact"}</div>- <div className="text-[10px] leading-tight mt-0.5 opacity-80">+ <div className="text-[15px] font-semibold">{k === "team" ? "Team member" : "Contact"}</div>+ <div className="text-sm leading-snug mt-1 text-fg-muted">{k === "team"? "Works with you: can sign in, message the Executive and approve.": "Outside the team and private to you: emailed or invited only when you ask."}@@ -354,41 +395,40 @@ function AddPersonModal({ initialKind, canAddContacts, onCreated, onClose }: Add)}{/* Always-visible: the 10-second path */}- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Full name *<inputref={nameRef}value={form.full_name}onChange={(e) => { const v = e.target.value; setForm((f) => ({ ...f, full_name: v })); clearSuggested("full_name"); }}- className={`px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500 ${suggestedCls("full_name")}`}+ className={`${INPUT_CLS} ${suggestedCls("full_name")}`}placeholder="Sarah Chen"/></label>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>{contact ? "Role and company" : "Role"}<inputvalue={form.role}onChange={(e) => { const v = e.target.value; setForm((f) => ({ ...f, role: v })); clearSuggested("role"); }}- className={`px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500 ${suggestedCls("role")}`}+ className={`${INPUT_CLS} ${suggestedCls("role")}`}placeholder={contact ? "Head of Procurement, Acme" : "CFO (fractional)"}/></label>- {contact && (- <label className="text-xs text-fg-muted flex flex-col gap-1">- <input- value={form.email}- onChange={(e) => { const v = e.target.value; setForm((f) => ({ ...f, email: v })); clearSuggested("email"); }}- className={`px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500 ${suggestedCls("email")}`}- placeholder="[email protected]"- />- </label>- )}+ <label className={LABEL_CLS}>+ <input+ type="email"+ value={form.email}+ onChange={(e) => { const v = e.target.value; setForm((f) => ({ ...f, email: v })); clearSuggested("email"); }}+ className={`${INPUT_CLS} ${suggestedCls("email")}`}+ placeholder={contact ? "[email protected]" : "[email protected]"}+ />+ </label>{!contact && (- <label className="flex items-center gap-2.5 cursor-pointer select-none">+ <label className="flex items-start gap-3 cursor-pointer select-none rounded-xl border border-line px-4 py-3"><inputtype="checkbox"checked={form.is_principal}@@ -397,10 +437,12 @@ function AddPersonModal({ initialKind, canAddContacts, onCreated, onClose }: AddsetForm((f) => ({ ...f, is_principal: checked }));if (checked) setShowAuthority(true);}}- className="w-4 h-4 rounded accent-indigo-500"+ className="mt-0.5 w-5 h-5 rounded accent-indigo-500 flex-shrink-0"/>- <span className="text-sm text-fg">This is me — Primary</span>- <span className="text-xs text-fg-muted">— marks you as the primary decision-maker</span>+ <span>+ <span className="block text-[15px] font-medium text-fg">This is me — Primary</span>+ <span className="block text-sm text-fg-muted">Marks you as the primary decision-maker.</span>+ </span></label>)}@@ -411,86 +453,74 @@ function AddPersonModal({ initialKind, canAddContacts, onCreated, onClose }: AddonToggle={() => setShowContact((v) => !v)}>{!contact && (- <div className="grid grid-cols-2 gap-3">+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4"><div>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Preferred channel<selectvalue={form.preferred_channel}onChange={(e) => setForm((f) => ({ ...f, preferred_channel: e.target.value }))}- className="px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}>{CHANNELS.map((c) => (<option key={c} value={c}>{c}</option>))}</select></label>- <p className="text-[10px] text-fg-muted mt-1">+ <p className={HINT_CLS}>Proposals routed to this person are sent via {form.preferred_channel === "any" ? "any available channel" : form.preferred_channel}.</p></div><div>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Expected reply within- <div className="flex items-center gap-1.5">+ <div className="flex items-center gap-2"><inputtype="number"min={1}value={form.response_sla_hours}onChange={(e) => setForm((f) => ({ ...f, response_sla_hours: e.target.value }))}- className="flex-1 px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={`${INPUT_CLS} flex-1 min-w-0`}/>- <span className="text-xs text-fg-muted flex-shrink-0">hours</span>+ <span className="text-sm text-fg-muted flex-shrink-0">hours</span></div></label>- <p className="text-[10px] text-fg-muted mt-1">- Items overdue in Today after {form.response_sla_hours || 24}h with no reply.+ <p className={HINT_CLS}>+ Items show as overdue on Home after {form.response_sla_hours || 24}h with no reply.</p></div></div>)}- {!contact && (- <label className="text-xs text-fg-muted flex flex-col gap-1">- <input- value={form.email}- onChange={(e) => { const v = e.target.value; setForm((f) => ({ ...f, email: v })); clearSuggested("email"); }}- className={`px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500 ${suggestedCls("email")}`}- placeholder="[email protected]"- />- </label>- )}-- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Slack user ID<inputvalue={form.slack_user_id}onChange={(e) => setForm((f) => ({ ...f, slack_user_id: e.target.value }))}- className="px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}placeholder="U01ABC123"/></label>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Discord user ID<inputvalue={form.discord_user_id}onChange={(e) => setForm((f) => ({ ...f, discord_user_id: e.target.value }))}- className="px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}placeholder="123456789012345678"/>- <span className="text-[10px] text-fg-muted">+ <span className={HINT_CLS}>Right-click your Discord username and "Copy User ID" (developer mode required).</span></label>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Telegram chat ID<inputvalue={form.telegram_chat_id}onChange={(e) => setForm((f) => ({ ...f, telegram_chat_id: e.target.value }))}- className="px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ className={INPUT_CLS}placeholder="123456789"/></label>@@ -503,53 +533,15 @@ function AddPersonModal({ initialKind, canAddContacts, onCreated, onClose }: Addopen={showAuthority}onToggle={() => setShowAuthority((v) => !v)}>- <div className="text-[10px] text-fg-muted mb-1.5">What this person approves</div>- <div className="grid grid-cols-3 gap-1.5">- {ALL_SCOPES.map(({ value, label, hint }) => {- const active = form.authority_scope.includes(value);- return (- <button- key={value}- type="button"- onClick={() => toggleScope(value)}- title={hint}- className={`px-2 py-1.5 rounded-lg border text-xs transition-colors text-left ${- active- ? "bg-indigo-600/30 border-indigo-500/50 text-indigo-300"- : "bg-surface-input border-line text-fg-muted hover:border-indigo-500/40"- }`}- >- <div className="font-medium">{label}</div>- <div className="text-[9px] leading-tight mt-0.5 opacity-70 line-clamp-2">{hint}</div>- </button>- );- })}- </div>+ <div className="text-sm text-fg-muted">What this person approves</div>+ <ScopePicker selected={form.authority_scope} onToggle={toggleScope} /></DisclosureSection>)}</div>- {err && <p className="text-xs text-rose-300 mt-3">{err}</p>}-- <div className="flex gap-2 mt-5">- <button- disabled={saving || !form.full_name.trim()}- onClick={submit}- className="flex-1 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white disabled:opacity-50 font-medium"- >- {saving ? "Creating…" : contact ? "Add contact" : "Add person"}- </button>- <button- disabled={saving}- onClick={onClose}- className="px-4 py-2 text-sm rounded-lg border border-line hover:bg-surface-overlay disabled:opacity-50"- >- Cancel- </button>- </div>- </div>- </div>+ {err && <p className="text-sm text-rose-500 mt-4">{err}</p>}+ </SidePanel>);}@@ -562,13 +554,13 @@ const TAB_COPY: Record<PeopleTab, { label: string; blurb: string; empty: string;label: "Team",blurb: "People who work with you. They can sign in, message the Executive and approve what their authority covers.",empty: "No team members yet.",- add: "+ Add person",+ add: "Add person",},contacts: {label: "Contacts",blurb: "Clients, contractors and advisors outside the team — private to you. The Executive emails or invites them only when you ask it to; they can't sign in or message it, and nobody else on the team sees them.",empty: "No contacts yet.",- add: "+ Add contact",+ add: "Add contact",},};@@ -610,6 +602,9 @@ export default function PeoplePage() {const shown = peopleForTab(people, activeTab, mode);const hidden = activeTab === "team" ? hiddenTeamCount(people, mode) : 0;const copy = TAB_COPY[activeTab];+ const tabsId = useId();+ // Local date (YYYY-MM-DD) for "on leave until", sampled once per mount.+ const [today] = useState(() => new Date().toLocaleDateString("en-CA"));return (<div className="flex flex-col h-full bg-surface">@@ -629,76 +624,63 @@ export default function PeoplePage() {)}{offerFor && <TeamModeOffer name={offerFor} onDone={() => setOfferFor(null)} />}<main className="flex-1 overflow-y-auto">- <div className="max-w-5xl mx-auto px-4 sm:px-6 py-6">- <div className="flex items-baseline justify-between mb-4">- <div>- <h1 className="text-xl font-semibold text-fg">People</h1>- <p className="text-sm text-fg-muted mt-0.5">{copy.blurb}</p>+ <div className="max-w-5xl mx-auto px-4 sm:px-6 py-8">+ <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between mb-6">+ <div className="min-w-0">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg">People</h1>+ <p className="text-[15px] text-fg-muted mt-2 max-w-2xl">{copy.blurb}</p></div>- <button- onClick={() => setShowAdd(true)}- className="flex-shrink-0 px-4 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white font-medium"- >+ <Button variant="primary" onClick={() => setShowAdd(true)} className="flex-shrink-0 self-start">{copy.add}- </button>+ </Button></div>{tabs.length > 1 && (- <div role="tablist" aria-label="Team or contacts" className="flex gap-1 border-b border-line mb-6">- {tabs.map((t) => {- const count = peopleForTab(people, t, mode).length;- const selected = activeTab === t;- return (- <button- key={t}- role="tab"- aria-selected={selected}- disabled={(workspaceLoading || viewerLoading) && tab === null}- onClick={() => setTab(t)}- className={`px-3 py-2 text-sm -mb-px border-b-2 transition-colors ${- selected- ? "border-indigo-500 text-fg font-medium"- : "border-transparent text-fg-muted hover:text-fg"- }`}- >- {TAB_COPY[t].label}- {!loading && <span className="ml-1.5 text-xs text-fg-subtle">{count}</span>}- </button>- );- })}- </div>+ <div className="mb-6">+ <SectionTabs+ idBase={tabsId}+ label="Team or contacts"+ active={activeTab}+ onChange={setTab}+ disabled={(workspaceLoading || viewerLoading) && tab === null}+ tabs={tabs.map((t) => ({+ id: t,+ label: TAB_COPY[t].label,+ count: loading ? undefined : peopleForTab(people, t, mode).length,+ }))}+ />+ </div>)}- {loading && <p className="text-fg-muted text-sm">Loading…</p>}+ <div {...(tabs.length > 1 ? sectionPanelProps(tabsId, activeTab) : {})}>+ {loading && <p className="text-fg-muted text-[15px]">Loading…</p>}{error && (- <div className="p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm mb-4">+ <div className="p-4 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-500 text-[15px] mb-4">{error}</div>)}{!loading && !error && shown.length === 0 && (- <div className="rounded-xl border border-line bg-surface-elevated p-8 text-center">- <p className="text-fg-muted text-sm mb-3">{copy.empty}</p>- <button- onClick={() => setShowAdd(true)}- className="px-4 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white"- >- {activeTab === "contacts" ? "Add your first contact →" : "Add your first person →"}- </button>+ <div className="rounded-2xl border border-line bg-surface-elevated p-10 text-center">+ <p className="text-fg-muted text-[15px] mb-5">{copy.empty}</p>+ <Button variant="primary" onClick={() => setShowAdd(true)}>+ {activeTab === "contacts" ? "Add your first contact" : "Add your first person"}+ </Button></div>)}<div className="grid grid-cols-1 md:grid-cols-2 gap-4">{shown.map((person) => (- <PersonCard key={person.id} person={person} />+ <PersonCard key={person.id} person={person} today={today} />))}</div>{hidden > 0 && (- <p className="text-xs text-fg-muted mt-4">+ <p className="text-sm text-fg-muted mt-5">{hidden === 1 ? "1 other team member is" : `${hidden} other team members are`} hidden while youuse Open Executive just for yourself. Switch to team mode in Settings to see them.</p>)}+ </div></div></main></div>diff --git a/packages/ui/src/app/settings/about/page.tsx b/packages/ui/src/app/settings/about/page.tsxnew file mode 100644index 00000000..8bf04c5a--- /dev/null+++ b/packages/ui/src/app/settings/about/page.tsx@@ -0,0 +1,19 @@+"use client";++import AboutCard from "@/components/settings/AboutCard";+import SettingsCard from "@/components/settings/SettingsCard";+import SettingsSubpage from "@/components/settings/SettingsSubpage";++// Settings → About: the version this install runs.+export default function AboutSettingsPage() {+ return (+ <SettingsSubpage+ title="About"+ description="The version this install is running, and whether a newer release is out."+ >+ <SettingsCard>+ <AboutCard />+ </SettingsCard>+ </SettingsSubpage>+ );+}diff --git a/packages/ui/src/app/settings/act-as-me/page.tsx b/packages/ui/src/app/settings/act-as-me/page.tsxnew file mode 100644index 00000000..d0e93b3e--- /dev/null+++ b/packages/ui/src/app/settings/act-as-me/page.tsx@@ -0,0 +1,13 @@+"use client";++import ActAsMeCard, { ACT_AS_ME_INTRO } from "@/components/settings/ActAsMeCard";+import SettingsSubpage from "@/components/settings/SettingsSubpage";++// Settings → Act as me: drafts written as you, in your own mailbox.+export default function ActAsMeSettingsPage() {+ return (+ <SettingsSubpage title="Act as me" description={ACT_AS_ME_INTRO}>+ <ActAsMeCard />+ </SettingsSubpage>+ );+}diff --git a/packages/ui/src/app/settings/advanced/page.tsx b/packages/ui/src/app/settings/advanced/page.tsxnew file mode 100644index 00000000..c9e859d2--- /dev/null+++ b/packages/ui/src/app/settings/advanced/page.tsx@@ -0,0 +1,54 @@+"use client";++import Link from "next/link";++import Icon from "@/components/Icon";+import SettingsSubpage from "@/components/settings/SettingsSubpage";+import { advancedItemsByGroup } from "@/components/shell/navConfig";++// Settings → Advanced: the admin and power-user pages (ADVANCED_ITEMS),+// grouped by what you'd use them for. Each opens its own screen.+export default function AdvancedSettingsPage() {+ return (+ <SettingsSubpage+ title="Advanced"+ description="Diagnostics, configuration and reference pages. Each opens its own screen."+ >+ {advancedItemsByGroup().map((group) => (+ <section key={group.key} aria-labelledby={`tools-${group.key}`}>+ <h2+ id={`tools-${group.key}`}+ className="px-1 text-sm font-semibold uppercase tracking-wider text-fg-subtle"+ >+ {group.label}+ </h2>+ <ul className="mt-2 overflow-hidden rounded-2xl border border-line bg-surface-elevated divide-y divide-line">+ {group.items.map((item) => (+ <li key={item.href}>+ <Link+ href={item.href}+ className="group flex items-center gap-4 px-5 py-4 transition-colors hover:bg-surface-overlay/60"+ >+ <span className="flex w-10 h-10 flex-shrink-0 items-center justify-center rounded-xl bg-accent/10 text-accent">+ <Icon name={item.icon} size="w-5 h-5" />+ </span>+ <span className="min-w-0 flex-1">+ <span className="block text-base font-semibold text-fg">{item.label}</span>+ <span className="block text-sm text-fg-muted leading-relaxed">+ {item.description}+ </span>+ </span>+ <Icon+ name="chevron-right"+ size="w-5 h-5"+ className="text-fg-subtle group-hover:text-fg transition-colors"+ />+ </Link>+ </li>+ ))}+ </ul>+ </section>+ ))}+ </SettingsSubpage>+ );+}diff --git a/packages/ui/src/app/settings/executive/page.tsx b/packages/ui/src/app/settings/executive/page.tsxnew file mode 100644index 00000000..881e4a94--- /dev/null+++ b/packages/ui/src/app/settings/executive/page.tsx@@ -0,0 +1,25 @@+"use client";++import ExecutiveRunSwitch from "@/components/executive/ExecutiveRunSwitch";+import VoicePicker from "@/components/executive/VoicePicker";+import SettingsCard from "@/components/settings/SettingsCard";+import SettingsSubpage from "@/components/settings/SettingsSubpage";++// Settings → Your Executive: whether it is doing its own work or holding it,+// and the voice it answers in — the one place the voice is chosen (the Agent+// Council's advanced view keeps the persona editor for custom voices).+export default function ExecutiveSettingsPage() {+ return (+ <SettingsSubpage+ title="Your Executive"+ description="Whether the Executive is doing its own work — briefs, nudges, monitoring, inbox, workflow timers — or holding it, and the voice it answers in."+ >+ <SettingsCard>+ <ExecutiveRunSwitch />+ </SettingsCard>+ <SettingsCard title="Voice" description="How it sounds when it answers you.">+ <VoicePicker variant="card" />+ </SettingsCard>+ </SettingsSubpage>+ );+}diff --git a/packages/ui/src/app/settings/page.tsx b/packages/ui/src/app/settings/page.tsxindex 6dd10394..c8307c29 100644--- a/packages/ui/src/app/settings/page.tsx+++ b/packages/ui/src/app/settings/page.tsx@@ -1,142 +1,193 @@"use client";import Link from "next/link";-import { useEffect, useMemo, useRef, useState } from "react";+import { useRouter } from "next/navigation";+import { useEffect, useState, useSyncExternalStore } from "react";-import ExecutiveRunSwitch from "@/components/executive/ExecutiveRunSwitch";-import VoicePicker from "@/components/executive/VoicePicker";+import { useExecutiveStatus } from "@/components/executive/ExecutiveStatusContext";import Icon from "@/components/Icon";-import AboutCard from "@/components/settings/AboutCard";-import ActAsMeCard from "@/components/settings/ActAsMeCard";-import SettingsNav from "@/components/settings/SettingsNav";-import SettingsSection from "@/components/settings/SettingsSection";-import WorkspaceCard from "@/components/settings/WorkspaceCard";-import { advancedItemsByGroup, SETTINGS_SECTIONS } from "@/components/shell/navConfig";-import { useActiveSection } from "@/lib/useActiveSection";--// Settings — the configuration that lives outside the day-to-day nav, as-// one page of sections (Executive, Workspace, Act as me, Tools, About) with an-// in-page nav to jump between them. Each section id is a hash a link can-// land on; the Tools section points at the admin / power-user pages-// (ADVANCED_ITEMS), grouped by what you'd use them for.-export default function SettingsPage() {- const mainRef = useRef<HTMLElement>(null);- // Act as me decides for itself whether it is on the page (the owner, and- // team members once the owner lets them).- const [actAsMe, setActAsMe] = useState(false);- const sections = useMemo(- () => SETTINGS_SECTIONS.filter((s) => s.id !== "act-as-me" || actAsMe),- [actAsMe],- );- const ids = useMemo(() => sections.map((s) => s.id), [sections]);- const { active, jumpTo } = useActiveSection(ids, mainRef);+import { MODE_LABEL } from "@/components/settings/WorkspaceCard";+import {+ ADVANCED_ITEMS,+ SETTINGS_PAGES,+ settingsPageForHash,+ type SettingsPageDef,+ type SettingsPageId,+} from "@/components/shell/navConfig";+import { useWorkspace } from "@/components/workspace/WorkspaceContext";+import { getAgentDetail, getDelegation, getVersion, listPersonas, type DelegationSettings } from "@/lib/api";+import { versionNotice } from "@/lib/versionNotice";++// Settings — a hub of tiles, one per page (SETTINGS_PAGES): Your Executive,+// Act as me, Workspace, Advanced and About. Each tile says what's on its page+// and, where it's cheap to know, how things stand right now. The one-page+// Settings this replaces used anchors (`/settings#workspace`); a link that+// still carries one is sent on to the matching page.++function subscribeHash(onChange: () => void): () => void {+ window.addEventListener("hashchange", onChange);+ return () => window.removeEventListener("hashchange", onChange);+}++function readHash(): string {+ return window.location.hash;+}- // A link with a hash lands on its section. The browser does this itself- // for a section present at first paint; Act as me mounts after its fetch,- // so scroll to the hash once its section exists.- const scrolledToHash = useRef(false);+type Tone = "ok" | "warn" | "none";++interface TileStatus {+ text: string;+ tone: Tone;+}++export default function SettingsPage() {+ const router = useRouter();+ // The address's hash: null while rendering on the server, where there is+ // none to read. The hub is held back until it is known, and while an old+ // anchor link is on its way to its page, so the tiles don't flash.+ const hash = useSyncExternalStore(subscribeHash, readHash, () => null);+ const target = hash === null ? null : settingsPageForHash(hash);useEffect(() => {- if (scrolledToHash.current) return;- const id = window.location.hash.slice(1);- if (!id || !ids.includes(id as (typeof ids)[number])) return;- const el = document.getElementById(id);- if (!el) return;- scrolledToHash.current = true;- el.scrollIntoView({ block: "start" });- }, [ids]);+ if (target) router.replace(target.href);+ }, [router, target]);++ const statuses = useTileStatuses();+ // Act as me has a tile only for someone who can have it (GET /delegation+ // answers null for everyone else).+ const pages = SETTINGS_PAGES.filter((p) => p.id !== "act-as-me" || statuses.actAsMeOffered);++ if (hash === null || target) return <main className="flex-1" />;return (- <main ref={mainRef} className="flex-1 min-h-0 overflow-y-auto">- <div className="max-w-3xl lg:max-w-4xl mx-auto px-4 sm:px-6 pt-8 pb-16">- <h1 className="text-xl font-semibold text-fg">Settings & advanced</h1>- <p className="mt-1 text-sm text-fg-muted">- How the Executive runs, who it runs for, and the tools that sit outside the- day-to-day workspace nav.+ <main className="flex-1 min-h-0 overflow-y-auto">+ <div className="max-w-5xl mx-auto px-4 sm:px-6 pt-6 sm:pt-10 pb-16">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg">Settings</h1>+ <p className="mt-2 text-[15px] text-fg-muted">+ How the Executive runs, who it runs for, and the tools for looking under the hood.</p>-- <div className="mt-6 lg:grid lg:grid-cols-[176px_minmax(0,1fr)] lg:gap-10">- <SettingsNav sections={sections} active={active} onJump={jumpTo} />-- <div className="mt-4 lg:mt-0 space-y-8 min-w-0">- <SettingsSection- id="executive"- title="Executive"- description="Whether the Executive is doing its own work — briefs, nudges, monitoring, inbox, workflow timers — or holding it, and the voice it answers in."- >- <ExecutiveRunSwitch variant="card" />- <div className="mt-6">- <h3 className="text-[10px] font-semibold uppercase tracking-widest text-fg-subtle mb-2">- Voice- </h3>- <VoicePicker variant="card" />- </div>- </SettingsSection>-- <SettingsSection- id="workspace"- title="Workspace"- description="Who Open Executive is for, and the time zone your briefs run in."- >- <WorkspaceCard />- </SettingsSection>-- {/* Renders nothing for anyone who can't have Act as me. */}- <ActAsMeCard onVisible={setActAsMe} />-- <SettingsSection- id="tools"- title="Tools"- description="Diagnostics, configuration and reference pages. Each opens its own screen."- >- <div className="space-y-5">- {advancedItemsByGroup().map((group) => (- <div key={group.key}>- <h3- id={`tools-${group.key}`}- className="text-[10px] font-semibold uppercase tracking-widest text-fg-subtle"- >- {group.label}- </h3>- <ul className="mt-1 divide-y divide-line">- {group.items.map((item) => (- <li key={item.href}>- <Link- href={item.href}- className="group flex items-center gap-3 py-2.5 -mx-2 px-2 rounded-lg hover:bg-surface-overlay transition-colors"- >- <span className="text-fg-muted group-hover:text-fg transition-colors">- <Icon name={item.icon} size="w-4 h-4" />- </span>- <span className="min-w-0 flex-1">- <span className="block text-sm text-fg">{item.label}</span>- <span className="block text-xs text-fg-muted">- {item.description}- </span>- </span>- <Icon- name="chevron-right"- size="w-3.5 h-3.5"- className="text-fg-subtle group-hover:text-fg transition-colors"- />- </Link>- </li>- ))}- </ul>- </div>- ))}- </div>- </SettingsSection>-- <SettingsSection- id="about"- title="About"- description="The version this install is running, and whether a newer release is out."- >- <AboutCard />- </SettingsSection>- </div>- </div>+ <ul className="mt-6 sm:mt-8 grid gap-3 sm:gap-4 sm:grid-cols-2 lg:grid-cols-3">+ {pages.map((page) => (+ <li key={page.id}>+ <SettingsTile page={page} status={statuses.byPage[page.id]} />+ </li>+ ))}+ </ul></div></main>);}++function SettingsTile({ page, status }: { page: SettingsPageDef; status?: TileStatus }) {+ return (+ <Link+ href={page.href}+ className="group flex h-full items-start gap-4 rounded-2xl border border-line bg-surface-elevated p-5 sm:flex-col sm:gap-0 sm:p-6 transition-colors hover:border-accent/50 hover:bg-surface-overlay/40 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/60"+ >+ <span className="hidden sm:flex w-11 h-11 items-center justify-center rounded-xl bg-accent/10 text-accent">+ <Icon name={page.icon} size="w-5 h-5" />+ </span>+ <span className="min-w-0 flex-1 sm:mt-4">+ <span className="block text-lg font-semibold text-fg">{page.label}</span>+ <span className="hidden sm:block mt-1 text-[15px] text-fg-muted leading-relaxed">+ {page.description}+ </span>+ <span className="mt-1.5 sm:mt-3 flex min-h-[1.25rem] items-center gap-2 text-sm text-fg-muted">+ {status && (+ <>+ {status.tone !== "none" && (+ <span+ className={`w-2 h-2 rounded-full flex-shrink-0 ${+ status.tone === "ok" ? "bg-emerald-500" : "bg-amber-500"+ }`}+ aria-hidden="true"+ />+ )}+ <span className="truncate">{status.text}</span>+ </>+ )}+ </span>+ </span>+ <Icon+ name="chevron-right"+ size="w-5 h-5"+ className="sm:hidden mt-1 text-fg-subtle group-hover:text-fg transition-colors"+ />+ </Link>+ );+}++// The one-line status under each tile. Each comes from a read the app makes+// anyway (run state, workspace) or one small request; a read that fails+// leaves its tile without a status rather than guessing.+function useTileStatuses(): {+ byPage: Partial<Record<SettingsPageId, TileStatus>>;+ actAsMeOffered: boolean;+} {+ const { status: run, unknown } = useExecutiveStatus();+ const { mode, effectiveTimezone, loading: workspaceLoading } = useWorkspace();+ const [voice, setVoice] = useState<string | null>(null);+ const [delegation, setDelegation] = useState<DelegationSettings | null | "error">(null);+ const [version, setVersion] = useState<TileStatus | null>(null);++ useEffect(() => {+ const ctrl = new AbortController();+ Promise.all([listPersonas(), getAgentDetail("executive")])+ .then(([all, exec]) => {+ const slug = exec.voice_persona_slug ?? "default";+ const name = all.find((p) => p.slug === slug)?.display_name;+ if (!ctrl.signal.aborted && name) setVoice(name);+ })+ .catch(() => {});+ getDelegation(ctrl.signal)+ .then((d) => setDelegation(d))+ .catch((err) => {+ if ((err as Error)?.name !== "AbortError") setDelegation("error");+ });+ getVersion(ctrl.signal)+ .then((v) => {+ const notice = versionNotice(v);+ setVersion(+ notice.update+ ? { text: `${notice.running} · update available`, tone: "warn" }+ : { text: notice.running, tone: "none" },+ );+ })+ .catch(() => {});+ return () => ctrl.abort();+ }, []);++ const byPage: Partial<Record<SettingsPageId, TileStatus>> = {};++ if (run) {+ const state: TileStatus = unknown+ ? { text: "Status unknown", tone: "none" }+ : run.paused+ ? { text: "Paused", tone: "warn" }+ : { text: "Running", tone: "ok" };+ byPage.executive = { ...state, text: voice ? `${state.text} · ${voice} voice` : state.text };+ } else if (voice) {+ byPage.executive = { text: `${voice} voice`, tone: "none" };+ }++ if (delegation && delegation !== "error") {+ byPage["act-as-me"] =+ delegation.gmail.status === "connected"+ ? {+ text: delegation.enabled ? "Mailbox connected · drafts on" : "Mailbox connected",+ tone: "ok",+ }+ : { text: "Mailbox not connected", tone: "warn" };+ }++ if (!workspaceLoading) {+ byPage.workspace = {+ text: [MODE_LABEL[mode], effectiveTimezone].filter(Boolean).join(" · "),+ tone: "none",+ };+ }++ byPage.advanced = { text: `${ADVANCED_ITEMS.length} tools for power users`, tone: "none" };+ if (version) byPage.about = version;++ return { byPage, actAsMeOffered: delegation !== null };+}diff --git a/packages/ui/src/app/settings/workspace/page.tsx b/packages/ui/src/app/settings/workspace/page.tsxnew file mode 100644index 00000000..0f7d3f14--- /dev/null+++ b/packages/ui/src/app/settings/workspace/page.tsx@@ -0,0 +1,16 @@+"use client";++import SettingsSubpage from "@/components/settings/SettingsSubpage";+import WorkspaceCard from "@/components/settings/WorkspaceCard";++// Settings → Workspace: who Open Executive is for, and when and how it acts.+export default function WorkspaceSettingsPage() {+ return (+ <SettingsSubpage+ title="Workspace"+ description="Who Open Executive is for, the time zone your briefs run in, and whether it books meetings on its own."+ >+ <WorkspaceCard />+ </SettingsSubpage>+ );+}diff --git a/packages/ui/src/app/watchlist/[slug]/page.tsx b/packages/ui/src/app/watchlist/[slug]/page.tsxindex 2a58dd2c..3b4acec4 100644--- a/packages/ui/src/app/watchlist/[slug]/page.tsx+++ b/packages/ui/src/app/watchlist/[slug]/page.tsx@@ -4,8 +4,12 @@ import Link from "next/link";import { useParams, useRouter } from "next/navigation";import { useEffect, useState } from "react";+import Switch from "@/components/Switch";+import Button from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";import {deleteWatchlistItem,+ listDepartments,getWatchlistItem,getWatchlistSignals,patchWatchlistItem,@@ -39,6 +43,13 @@ function formatRelTime(iso: string | null): string {}}+// The research policy's "about" stamp on a watch the Executive added.+function policyEntity(item: WatchlistItem): string | undefined {+ const raw = (item.config_json as Record<string, unknown> | undefined)?._policy;+ const entity = raw && typeof raw === "object" ? (raw as { entity?: unknown }).entity : undefined;+ return typeof entity === "string" && entity ? entity : undefined;+}+function outcomeStyle(outcome: string | null): string {if (outcome === "alerted") return "bg-emerald-500/20 text-emerald-300 border-emerald-500/30";if (outcome === "failed") return "bg-rose-500/20 text-rose-300 border-rose-500/30";@@ -54,13 +65,13 @@ function outcomeLabel(outcome: string | null): string {function SignalRow({ signal }: { signal: WatchlistSignal }) {return (- <li className="border border-line rounded-lg bg-surface-elevated p-3">+ <li className="border border-line rounded-xl bg-surface p-3.5"><div className="flex items-start justify-between gap-2 mb-1"><div className="flex-1 min-w-0">- <div className="text-sm text-fg truncate" title={signal.normalized_summary}>+ <div className="text-[15px] text-fg truncate" title={signal.normalized_summary}>{signal.normalized_summary}</div>- <div className="text-[11px] text-fg-muted mt-0.5">+ <div className="text-sm text-fg-muted mt-0.5">{signal.published_at? `published ${formatRelTime(signal.published_at)} · seen ${formatRelTime(signal.captured_at)}`: formatRelTime(signal.captured_at)}@@ -73,13 +84,13 @@ function SignalRow({ signal }: { signal: WatchlistSignal }) {{outcomeLabel(signal.processed_outcome)}</span></div>- <div className="flex items-center gap-3 text-[11px]">+ <div className="flex items-center gap-3 text-sm">{signal.provenance_url && (<ahref={signal.provenance_url}target="_blank"rel="noreferrer"- className="text-indigo-300 hover:text-indigo-200 truncate max-w-xs"+ className="text-accent hover:underline truncate max-w-xs">source ↗</a>@@ -109,6 +120,16 @@ export default function WatchDetailPage() {// toggle-revert race where two clicks land in the wrong final state.const [toggling, setToggling] = useState(false);const [modeChanging, setModeChanging] = useState(false);+ // slug → title, for "for: <department>" on a routed research watch.+ const [departmentTitles, setDepartmentTitles] = useState<Record<string, string>>({});++ useEffect(() => {+ listDepartments()+ .then((states) =>+ setDepartmentTitles(Object.fromEntries(states.map((d) => [d.config.slug, d.config.title]))),+ )+ .catch(() => {});+ }, []);useEffect(() => {if (!slug) return;@@ -139,9 +160,8 @@ export default function WatchDetailPage() {}}- async function toggleMode() {- if (!item || modeChanging) return;- const nextMode = item.mode === "active" ? "dry_run" : "active";+ async function setModeTo(nextMode: "active" | "dry_run") {+ if (!item || modeChanging || item.mode === nextMode) return;setModeChanging(true);try {const updated = await patchWatchlistItem(slug, { mode: nextMode });@@ -203,49 +223,112 @@ export default function WatchDetailPage() {<div className="max-w-3xl mx-auto px-4 sm:px-6 py-6"><Linkhref="/watchlist"- className="text-xs text-indigo-300 hover:text-indigo-200 inline-block mb-4"+ className="text-sm text-fg-muted hover:text-fg inline-block mb-4">← Watch list</Link>- <div className="flex items-baseline justify-between mb-4 gap-4">+ <div className="flex items-start justify-between mb-6 gap-4"><div className="min-w-0">- <h1 className="text-xl font-mono font-semibold text-fg truncate">{item.slug}</h1>- <p className="text-sm text-fg-muted mt-0.5 truncate" title={item.target}>+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight font-mono text-fg truncate">+ {item.slug}+ </h1>+ <p className="text-[15px] text-fg-muted mt-1 truncate" title={item.target}>{item.signal_type} · {item.target}</p></div>- <div className="flex items-center gap-2">- <button- onClick={toggleEnabled}- disabled={toggling}- className={`px-3 py-1.5 text-xs rounded-lg border disabled:opacity-60 ${- item.enabled- ? "bg-indigo-500/20 text-indigo-300 border-indigo-500/30 hover:bg-indigo-500/30"- : "bg-zinc-500/20 text-zinc-400 border-zinc-500/30 hover:bg-zinc-500/30"- }`}- >- {item.enabled ? "Enabled" : "Disabled"}- </button>- <button- onClick={toggleMode}- disabled={modeChanging}- className="px-3 py-1.5 text-xs rounded-lg border border-line hover:bg-surface-overlay text-fg-muted disabled:opacity-60"+ <OverflowMenu+ label="More actions"+ items={[{ label: "Delete monitor", danger: true, onSelect: () => setConfirming(true) }]}+ />+ </div>++ {confirming && (+ <div className="rounded-2xl border border-rose-500/30 bg-rose-500/5 p-4 mb-4 flex flex-wrap items-center gap-3">+ <span className="text-[15px] text-fg flex-1 min-w-[12rem]">+ Delete this monitor? Historical signals stay in the audit log.+ </span>+ <Button variant="danger" onClick={remove}>+ Delete+ </Button>+ <Button variant="ghost" onClick={() => setConfirming(false)}>+ Cancel+ </Button>+ </div>+ )}++ <div className="rounded-2xl border border-line bg-surface-elevated p-5 mb-4 divide-y divide-line">+ <div className="flex items-center justify-between gap-4 pb-4">+ <div>+ <div id="watch-enabled-label" className="text-[15px] font-semibold text-fg">+ {item.enabled ? "Watching" : "Paused"}+ </div>+ <p className="text-sm text-fg-muted">+ {item.enabled+ ? "Polled on its cadence."+ : "Not polled until you switch it back on."}+ </p>+ </div>+ {/* The label pads the small switch out to a 40px tap target. */}+ <label className="inline-flex h-10 w-12 flex-shrink-0 cursor-pointer items-center justify-center">+ <Switch+ checked={item.enabled}+ disabled={toggling}+ labelledBy="watch-enabled-label"+ onChange={() => void toggleEnabled()}+ />+ </label>+ </div>+ <div className="flex flex-wrap items-center justify-between gap-4 pt-4">+ <div>+ <div className="text-[15px] font-semibold text-fg">When it fires</div>+ <p className="text-sm text-fg-muted">+ {item.mode === "active"+ ? "Signals can become alerts in your briefing."+ : "Shadow mode (dry_run): polls and records signals, never alerts."}+ </p>+ </div>+ <div+ role="group"+ aria-label="Mode"+ className="inline-flex rounded-xl border border-line bg-surface p-1">- mode: {item.mode}- </button>+ {(+ [+ ["active", "Alert me"],+ ["dry_run", "Shadow only"],+ ] as const+ ).map(([value, label]) => (+ <button+ key={value}+ type="button"+ aria-pressed={item.mode === value}+ disabled={modeChanging}+ onClick={() => void setModeTo(value)}+ className={`min-h-10 rounded-lg px-3.5 text-sm font-medium transition-colors disabled:opacity-60 ${+ item.mode === value+ ? "bg-accent/10 text-accent"+ : "text-fg-muted hover:text-fg hover:bg-surface-overlay"+ }`}+ >+ {label}+ </button>+ ))}+ </div></div></div>{error && (- <div className="p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm mb-4">+ <div className="px-4 py-3 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-500 text-[15px] mb-4">{error}</div>)}- <div className="rounded-xl border border-line bg-surface-elevated p-4 mb-4">- <h2 className="text-xs uppercase tracking-wide text-fg-subtle mb-3">Configuration</h2>- <dl className="grid grid-cols-2 gap-x-4 gap-y-2 text-xs">+ <div className="rounded-2xl border border-line bg-surface-elevated p-5 mb-4">+ <h2 className="text-base font-semibold text-fg mb-3">Configuration</h2>+ <dl className="grid grid-cols-2 gap-x-4 gap-y-2.5 text-sm">+ <dt className="text-fg-muted">Mode</dt>+ <dd className="text-fg">{item.mode}</dd><dt className="text-fg-muted">Cadence</dt><dd className="text-fg">{item.cadence}</dd><dt className="text-fg-muted">Severity range</dt>@@ -264,17 +347,29 @@ export default function WatchDetailPage() {<dd className="text-fg">{formatRelTime(item.last_polled_at)}</dd><dt className="text-fg-muted">Last fired</dt><dd className="text-fg">{formatRelTime(item.last_fired_at)}</dd>+ {item.origin === "research" && (+ <>+ <dt className="text-fg-muted">Added by</dt>+ <dd className="text-fg">+ The Executive+ {policyEntity(item) ? ` · about ${policyEntity(item)}` : ""}+ {item.route_to_department+ ? ` · for ${departmentTitles[item.route_to_department] ?? item.route_to_department}`+ : ""}+ </dd>+ </>+ )}</dl><div className="mt-3">- <div className="text-xs text-fg-muted mb-1">Trigger</div>- <pre className="text-[11px] font-mono bg-surface-input/40 border border-line rounded p-2 overflow-x-auto">+ <div className="text-sm text-fg-muted mb-1">Trigger</div>+ <pre className="text-xs font-mono bg-surface-input/40 border border-line rounded p-2 overflow-x-auto">{JSON.stringify(item.trigger_json, null, 2)}</pre></div></div>- <div className="rounded-xl border border-line bg-surface-elevated p-4 mb-4">- <h2 className="text-xs uppercase tracking-wide text-fg-subtle mb-2">Notes</h2>+ <div className="rounded-2xl border border-line bg-surface-elevated p-5 mb-4">+ <h2 className="text-base font-semibold text-fg mb-2">Notes</h2><textareavalue={notes}onChange={(e) => setNotes(e.target.value)}@@ -282,19 +377,20 @@ export default function WatchDetailPage() {rows={3}maxLength={500}placeholder="Why are we watching this?"- className="w-full px-3 py-2 text-sm rounded-lg bg-surface-input border border-line"+ aria-label="Notes"+ className="w-full px-3.5 py-2.5 text-[15px] rounded-xl bg-surface border border-line focus:outline-none focus:ring-2 focus:ring-accent/40"/>{savingNotes && (- <p className="text-[10px] text-fg-subtle mt-1">Saving…</p>+ <p className="text-xs text-fg-subtle mt-1">Saving…</p>)}</div>- <div className="rounded-xl border border-line bg-surface-elevated p-4 mb-4">- <h2 className="text-xs uppercase tracking-wide text-fg-subtle mb-3">+ <div className="rounded-2xl border border-line bg-surface-elevated p-5 mb-4">+ <h2 className="text-base font-semibold text-fg mb-3">Recent signals ({signals.length})</h2>{signals.length === 0 ? (- <p className="text-xs text-fg-muted">+ <p className="text-sm text-fg-muted">No signals yet. The next poll runs on cadence: {item.cadence}.</p>) : (@@ -306,35 +402,6 @@ export default function WatchDetailPage() {)}</div>- <div className="rounded-xl border border-rose-500/30 bg-rose-500/5 p-4">- <h2 className="text-xs uppercase tracking-wide text-rose-300 mb-2">Danger zone</h2>- {confirming ? (- <div className="flex items-center gap-2">- <span className="text-xs text-fg-muted">- Delete this monitor? Historical signals stay in the audit log.- </span>- <button- onClick={remove}- className="px-3 py-1.5 text-xs rounded-lg bg-rose-600 hover:bg-rose-500 text-white font-medium"- >- Delete- </button>- <button- onClick={() => setConfirming(false)}- className="px-3 py-1.5 text-xs rounded-lg border border-line hover:bg-surface-overlay"- >- Cancel- </button>- </div>- ) : (- <button- onClick={() => setConfirming(true)}- className="px-3 py-1.5 text-xs rounded-lg border border-rose-500/30 text-rose-300 hover:bg-rose-500/10"- >- Delete monitor- </button>- )}- </div></div></main></div>diff --git a/packages/ui/src/app/watchlist/page.tsx b/packages/ui/src/app/watchlist/page.tsxindex aa1cb147..714a2227 100644--- a/packages/ui/src/app/watchlist/page.tsx+++ b/packages/ui/src/app/watchlist/page.tsx@@ -1,7 +1,11 @@"use client";import Link from "next/link";-import { useEffect, useMemo, useRef, useState } from "react";+import { useEffect, useId, useMemo, useRef, useState } from "react";++import Switch from "@/components/Switch";+import Button from "@/components/ui/Button";+import OverflowMenu, { type OverflowItem } from "@/components/ui/OverflowMenu";import {approveWatchSuggestion,@@ -17,6 +21,11 @@ import {type WatchlistSeverity,type WatchlistSignalType,} from "@/lib/api";+import { suggestWatchSlug } from "@/lib/watchSlug";++const fieldCls =+ "w-full px-3.5 py-2.5 text-[15px] rounded-xl bg-surface border border-line text-fg placeholder:text-fg-subtle focus:outline-none focus:ring-2 focus:ring-accent/40";+const labelCls = "block text-sm font-medium text-fg-muted mb-1.5";// A research suggestion: the Executive wanted to watch this but was not sure// enough to add it on its own. Sits in dry_run (polls, never alerts) until@@ -91,60 +100,18 @@ function formatRelTime(iso: string | null): string {}}-function ModePill({ mode }: { mode: string }) {- const isDry = mode === "dry_run";- const cls = isDry- ? "bg-zinc-500/20 text-zinc-300 border-zinc-500/30"- : "bg-indigo-500/20 text-indigo-300 border-indigo-500/30";- return (- <span className={`inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium ${cls}`}>- {mode}- </span>- );-}--function DeclineMenu({- slug,- busy,- onPick,- label,-}: {- slug: string;- busy: boolean;- onPick: (slug: string, reason: WatchDeclineReason) => void;- label: string;-}) {- const [open, setOpen] = useState(false);- return (- <div className="relative">- <button- type="button"- disabled={busy}- onClick={() => setOpen((o) => !o)}- className="px-3 py-1.5 text-xs rounded-lg border border-line hover:bg-surface-overlay disabled:opacity-50"- >- {label}- </button>- {open && (- <div className="absolute right-0 z-20 mt-1 w-56 rounded-lg border border-line bg-surface-elevated shadow-lg p-1">- {DECLINE_REASONS.map((r) => (- <button- key={r.value}- type="button"- onClick={() => {- setOpen(false);- onPick(slug, r.value);- }}- className="w-full text-left px-2 py-1.5 rounded hover:bg-surface-overlay"- >- <div className="text-xs text-fg">{r.label}</div>- <div className="text-[10px] text-fg-subtle">{r.hint}</div>- </button>- ))}- </div>- )}- </div>- );+/** The decline reasons as ⋯ items, each saying what it does. */+function declineItems(+ verb: string,+ slug: string,+ busy: boolean,+ onPick: (slug: string, reason: WatchDeclineReason) => void,+): OverflowItem[] {+ return DECLINE_REASONS.map((r) => ({+ label: `${verb}: ${r.label.toLowerCase()} (${r.hint.charAt(0).toLowerCase()}${r.hint.slice(1)})`,+ disabled: busy,+ onSelect: () => onPick(slug, r.value),+ }));}function SuggestionCard({@@ -162,22 +129,22 @@ function SuggestionCard({}) {const stamp = policyStamp(item);return (- <div className="rounded-xl border border-amber-500/30 bg-amber-500/5 p-4">+ <div className="flex min-w-0 flex-col rounded-2xl border border-amber-500/40 bg-surface-elevated p-5 shadow-sm"><div className="flex items-start justify-between gap-2 mb-1"><div className="min-w-0">- <div className="text-sm font-semibold text-fg truncate" title={item.slug}>+ <div className="text-lg font-semibold text-fg truncate" title={item.slug}>{humanizeSlug(item.slug)}</div>- <div className="text-xs text-fg-muted truncate" title={item.target}>- {item.signal_type} · {item.target}+ <div className="text-sm text-fg-muted truncate" title={item.target}>+ {SIGNAL_TYPE_LABELS[item.signal_type] ?? item.signal_type} · {item.target}</div></div>- <span className="flex-shrink-0 inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium bg-amber-500/20 text-amber-200 border-amber-500/30">- suggested+ <span className="flex-shrink-0 rounded-full bg-amber-500/15 px-2.5 py-0.5 text-xs font-medium text-amber-600 dark:text-amber-300">+ Suggested</span></div>- {item.notes && <p className="text-xs text-fg mt-2">{item.notes}</p>}- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-fg-muted mt-2">+ {item.notes && <p className="text-[15px] text-fg mt-2">{item.notes}</p>}+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-fg-muted mt-2">{stamp.entity && <span>about: {stamp.entity}</span>}{item.route_to_department && (<span title="This department's head was asked to review it">@@ -187,21 +154,19 @@ function SuggestionCard({<span>suggested {formatRelTime(item.created_at)} ago</span><span>seen in shadow: {item.fired_count} signal{item.fired_count === 1 ? "" : "s"}</span>{stamp.source_url && (- <a href={stamp.source_url} target="_blank" rel="noreferrer" className="text-indigo-300 hover:text-indigo-200">+ <a href={stamp.source_url} target="_blank" rel="noreferrer" className="text-accent hover:underline">source ↗</a>)}</div>- <div className="flex items-center justify-end gap-2 mt-3 pt-2 border-t border-line">- <DeclineMenu slug={item.slug} busy={busy} onPick={onDecline} label="Decline…" />- <button- type="button"- disabled={busy}- onClick={() => onApprove(item.slug)}- className="px-3 py-1.5 text-xs rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white font-medium disabled:opacity-50"- >+ <div className="mt-auto flex items-center gap-2 pt-4">+ <Button variant="primary" disabled={busy} onClick={() => onApprove(item.slug)}>{busy ? "…" : "Approve"}- </button>+ </Button>+ <OverflowMenu+ label={`Decline ${humanizeSlug(item.slug)}`}+ items={declineItems("Decline", item.slug, busy, onDecline)}+ /></div></div>);@@ -212,71 +177,56 @@ function WatchCard({onToggle,toggleBusy,onStopWatching,- departmentTitle,}: {item: WatchlistItem;onToggle: (slug: string, enabled: boolean) => void;toggleBusy: boolean;onStopWatching?: (slug: string, reason: WatchDeclineReason) => void;- departmentTitle?: string;}) {+ // Mode, severity, cadence and counts live on the monitor's own page.const isResearch = item.origin === "research";- const stamp = policyStamp(item);+ const labelId = useId();+ const href = `/watchlist/${encodeURIComponent(item.slug)}`;return (- <div className="rounded-xl border border-line bg-surface-elevated hover:bg-surface-overlay transition-colors p-4 group">- <div className="flex items-start justify-between gap-2 mb-2">- <Link href={`/watchlist/${encodeURIComponent(item.slug)}`} className="flex-1 min-w-0">- <div- className="text-sm font-semibold text-fg group-hover:text-indigo-300 transition-colors truncate"- title={item.slug}- >- {humanizeSlug(item.slug)}- </div>- <div className="text-xs text-fg-muted mt-0.5 truncate" title={item.target}>- {item.target}- </div>- </Link>- <div className="flex-shrink-0 flex items-center gap-2">- <ModePill mode={item.mode} />+ <div className="flex min-w-0 items-start gap-3 rounded-2xl border border-line bg-surface-elevated p-5 shadow-sm">+ <Link href={href} className="min-w-0 flex-1 group">+ <div+ id={labelId}+ className="text-lg font-semibold text-fg group-hover:text-accent transition-colors truncate"+ title={item.slug}+ >+ {humanizeSlug(item.slug)}</div>- </div>- {isResearch && (- <p className="text-[11px] text-fg-muted mb-2">- <span className="text-indigo-300">Added by the Executive</span>- {stamp.entity ? ` · about ${stamp.entity}` : ""}- {item.route_to_department ? ` · for ${departmentTitle ?? item.route_to_department}` : ""}- {item.notes ? ` · ${item.notes}` : ""}- </p>- )}- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-fg-muted mb-2">- <span>cadence: {item.cadence}</span>- <span>severity: {item.severity_floor}→{item.severity_ceiling}</span>- <span>fired: {item.fired_count}</span>- {item.dismiss_count > 0 && <span>dismissed: {item.dismiss_count}</span>}- <span>last: {formatRelTime(item.last_fired_at)}</span>- </div>- <div className="flex items-center justify-between gap-2 pt-2 border-t border-line">- <label className="flex items-center gap-1.5 text-xs text-fg-muted cursor-pointer">- <input- type="checkbox"+ <div className="text-sm text-fg-muted mt-0.5 truncate" title={item.target}>+ {item.target}+ </div>+ <div className="text-sm text-fg-subtle mt-1.5">+ {item.last_fired_at+ ? `Last fired ${formatRelTime(item.last_fired_at)} ago`+ : "Hasn't fired yet"}+ {isResearch && " · added by the Executive"}+ </div>+ </Link>+ <div className="flex flex-shrink-0 items-center gap-1 pt-1">+ <span className="sr-only">{item.enabled ? "On" : "Off"}</span>+ {/* The label pads the small switch out to a 40px tap target. */}+ <label className="inline-flex h-10 w-12 cursor-pointer items-center justify-center">+ <Switchchecked={item.enabled}disabled={toggleBusy}- onChange={(e) => onToggle(item.slug, e.target.checked)}- className="accent-indigo-500 disabled:opacity-50"+ labelledBy={labelId}+ onChange={(on) => onToggle(item.slug, on)}/>- enabled</label>- <div className="flex items-center gap-2">- {isResearch && onStopWatching && (- <DeclineMenu slug={item.slug} busy={toggleBusy} onPick={onStopWatching} label="Stop watching…" />- )}- <Link- href={`/watchlist/${encodeURIComponent(item.slug)}`}- className="text-xs text-indigo-300 hover:text-indigo-200"- >- inspect →- </Link>- </div>+ <OverflowMenu+ label={`More for ${humanizeSlug(item.slug)}`}+ items={[+ { label: "Open details", href },+ ...(isResearch && onStopWatching+ ? declineItems("Stop watching", item.slug, toggleBusy, onStopWatching)+ : []),+ ]}+ /></div></div>);@@ -299,13 +249,26 @@ function AddWatchModal({ onCreated, onClose }: AddModalProps) {const [notes, setNotes] = useState("");const [saving, setSaving] = useState(false);const [err, setErr] = useState<string | null>(null);- const slugRef = useRef<HTMLInputElement>(null);+ // Slug, trigger, cadence, mode and severity sit under "More options" with+ // their defaults; it opens by itself when an error points into it.+ const [moreOpen, setMoreOpen] = useState(false);+ const typeRef = useRef<HTMLSelectElement>(null);useEffect(() => {- slugRef.current?.focus();+ typeRef.current?.focus();}, []);+ useEffect(() => {+ if (saving) return;+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape") onClose();+ };+ document.addEventListener("keydown", onKey);+ return () => document.removeEventListener("keydown", onKey);+ }, [saving, onClose]);+const targetHint = SIGNAL_TYPES.find((s) => s.value === signalType)?.hint ?? "";+ const slugSuggestion = suggestWatchSlug(signalType, target);async function submit() {setSaving(true);@@ -316,13 +279,14 @@ function AddWatchModal({ onCreated, onClose }: AddModalProps) {parsedTrigger = JSON.parse(trigger);} catch {setErr("Trigger must be valid JSON, e.g. {\"abs_change_pct_gte\": 5}");+ setMoreOpen(true);setSaving(false);return;}}try {const created = await createWatchlistItem({- slug: slug.trim(),+ slug: slug.trim() || slugSuggestion,signal_type: signalType,target: target.trim(),trigger: parsedTrigger,@@ -334,7 +298,9 @@ function AddWatchModal({ onCreated, onClose }: AddModalProps) {});onCreated(created);} catch (e) {- setErr(e instanceof Error ? e.message : "Create failed");+ const message = e instanceof Error ? e.message : "Create failed";+ setErr(message);+ if (/slug|trigger|cadence|severity|mode/i.test(message)) setMoreOpen(true);} finally {setSaving(false);}@@ -342,31 +308,26 @@ function AddWatchModal({ onCreated, onClose }: AddModalProps) {return (<div- className="fixed inset-0 z-50 flex items-center justify-center bg-black/60"+ className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black/60"onClick={saving ? undefined : onClose}><div- className="bg-surface-elevated border border-line rounded-xl w-full max-w-lg max-h-[90vh] overflow-y-auto p-6"+ role="dialog"+ aria-modal="true"+ aria-label="Add monitor"+ className="bg-surface-elevated border border-line rounded-t-2xl sm:rounded-2xl w-full sm:max-w-lg max-h-[92vh] overflow-y-auto p-5 sm:p-7 shadow-2xl"onClick={(e) => e.stopPropagation()}>- <h2 className="text-lg font-semibold text-fg mb-4">Add monitor</h2>- <div className="space-y-3">+ <h2 className="text-xl font-bold tracking-tight text-fg mb-5">Add monitor</h2>+ <div className="space-y-4"><div>- <label className="block text-xs text-fg-muted mb-1">Slug (kebab-case)</label>- <input- ref={slugRef}- value={slug}- onChange={(e) => setSlug(e.target.value)}- placeholder="stock-aapl"- className="w-full px-3 py-2 text-sm rounded-lg bg-surface-input border border-line"- />- </div>- <div>- <label className="block text-xs text-fg-muted mb-1">Signal type</label>+ <label htmlFor="watch-signal-type" className={labelCls}>Signal type</label><select+ id="watch-signal-type"+ ref={typeRef}value={signalType}onChange={(e) => setSignalType(e.target.value as WatchlistSignalType)}- className="w-full px-3 py-2 text-sm rounded-lg bg-surface-input border border-line"+ className={fieldCls}>{SIGNAL_TYPES.map((s) => (<option key={s.value} value={s.value}>@@ -376,130 +337,160 @@ function AddWatchModal({ onCreated, onClose }: AddModalProps) {</select></div><div>- <label className="block text-xs text-fg-muted mb-1">Target</label>+ <label htmlFor="watch-target" className={labelCls}>Target</label><input+ id="watch-target"value={target}onChange={(e) => setTarget(e.target.value)}placeholder={targetHint}- className="w-full px-3 py-2 text-sm rounded-lg bg-surface-input border border-line"+ className={fieldCls}/>- <p className="text-[10px] text-fg-subtle mt-1">{targetHint}</p>+ <p className="text-sm text-fg-subtle mt-1.5">{targetHint}</p>{BILLED_SIGNAL_TYPES.has(signalType) && (- <p className="text-[10px] text-amber-300/90 mt-1">+ <p className="text-sm text-amber-600 dark:text-amber-300 mt-1.5">⚠ Billed: runs an LLM web search on every poll. Prefer a slowercadence (daily / weekly) and a tight query.</p>)}</div><div>- <label className="block text-xs text-fg-muted mb-1">Trigger (JSON, optional)</label>- <textarea- value={trigger}- onChange={(e) => setTrigger(e.target.value)}- placeholder={- signalType === "stock"- ? '{"abs_change_pct_gte": 5}'- : signalType === "edgar"- ? '{"forms": ["8-K", "10-K"]}'- : signalType === "rss" ||- signalType === "query" ||- signalType === "page_watch"- ? '{"keywords": ["layoffs", "downtime"]}'- : "{}"- }- rows={3}- className="w-full px-3 py-2 text-sm font-mono rounded-lg bg-surface-input border border-line"- />- </div>- <div className="grid grid-cols-2 gap-3">- <div>- <label className="block text-xs text-fg-muted mb-1">Cadence</label>- <select- value={cadence}- onChange={(e) => setCadence(e.target.value as WatchlistCadence)}- className="w-full px-3 py-2 text-sm rounded-lg bg-surface-input border border-line"- >- {CADENCES.map((c) => (- <option key={c} value={c}>- {c}- </option>- ))}- </select>- </div>- <div>- <label className="block text-xs text-fg-muted mb-1">Mode</label>- <select- value={mode}- onChange={(e) => setMode(e.target.value as "active" | "dry_run")}- className="w-full px-3 py-2 text-sm rounded-lg bg-surface-input border border-line"- >- <option value="active">active</option>- <option value="dry_run">dry_run</option>- </select>- </div>- <div>- <label className="block text-xs text-fg-muted mb-1">Severity floor</label>- <select- value={severityFloor}- onChange={(e) => setSeverityFloor(e.target.value as WatchlistSeverity)}- className="w-full px-3 py-2 text-sm rounded-lg bg-surface-input border border-line"- >- {SEVERITIES.map((s) => (- <option key={s} value={s}>- {s}- </option>- ))}- </select>- </div>- <div>- <label className="block text-xs text-fg-muted mb-1">Severity ceiling</label>- <select- value={severityCeiling}- onChange={(e) => setSeverityCeiling(e.target.value as WatchlistSeverity)}- className="w-full px-3 py-2 text-sm rounded-lg bg-surface-input border border-line"- >- {SEVERITIES.map((s) => (- <option key={s} value={s}>- {s}- </option>- ))}- </select>- </div>- </div>- <div>- <label className="block text-xs text-fg-muted mb-1">Notes</label>+ <label htmlFor="watch-notes" className={labelCls}>Notes</label><input+ id="watch-notes"value={notes}onChange={(e) => setNotes(e.target.value)}maxLength={500}- className="w-full px-3 py-2 text-sm rounded-lg bg-surface-input border border-line"+ placeholder="Why watch this?"+ className={fieldCls}/></div>++ <details+ className="rounded-xl border border-line px-4 py-2"+ open={moreOpen}+ onToggle={(e) => setMoreOpen((e.target as HTMLDetailsElement).open)}+ >+ <summary className="flex min-h-10 cursor-pointer items-center text-[15px] font-medium text-fg">+ More options+ <span className="ml-2 text-sm font-normal text-fg-subtle">+ {slug.trim() || slugSuggestion || "name"} · {cadence} · {mode} · {severityFloor}→{severityCeiling}+ </span>+ </summary>+ <div className="space-y-4 py-3">+ <div>+ <label htmlFor="watch-slug" className={labelCls}>Slug (kebab-case)</label>+ <input+ id="watch-slug"+ value={slug}+ onChange={(e) => setSlug(e.target.value)}+ placeholder={slugSuggestion || "stock-aapl"}+ className={fieldCls}+ />+ <p className="text-sm text-fg-subtle mt-1.5">+ Left empty, it is named {slugSuggestion ? <code>{slugSuggestion}</code> : "from the type and target"}.+ </p>+ </div>+ <div>+ <label htmlFor="watch-trigger" className={labelCls}>Trigger (JSON, optional)</label>+ <textarea+ id="watch-trigger"+ value={trigger}+ onChange={(e) => setTrigger(e.target.value)}+ placeholder={+ signalType === "stock"+ ? '{"abs_change_pct_gte": 5}'+ : signalType === "edgar"+ ? '{"forms": ["8-K", "10-K"]}'+ : signalType === "rss" ||+ signalType === "query" ||+ signalType === "page_watch"+ ? '{"keywords": ["layoffs", "downtime"]}'+ : "{}"+ }+ rows={3}+ className={`${fieldCls} font-mono text-sm`}+ />+ </div>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">+ <div>+ <label htmlFor="watch-cadence" className={labelCls}>Cadence</label>+ <select+ id="watch-cadence"+ value={cadence}+ onChange={(e) => setCadence(e.target.value as WatchlistCadence)}+ className={fieldCls}+ >+ {CADENCES.map((c) => (+ <option key={c} value={c}>+ {c}+ </option>+ ))}+ </select>+ </div>+ <div>+ <label htmlFor="watch-mode" className={labelCls}>Mode</label>+ <select+ id="watch-mode"+ value={mode}+ onChange={(e) => setMode(e.target.value as "active" | "dry_run")}+ className={fieldCls}+ >+ <option value="active">active</option>+ <option value="dry_run">dry_run</option>+ </select>+ </div>+ <div>+ <label htmlFor="watch-floor" className={labelCls}>Severity floor</label>+ <select+ id="watch-floor"+ value={severityFloor}+ onChange={(e) => setSeverityFloor(e.target.value as WatchlistSeverity)}+ className={fieldCls}+ >+ {SEVERITIES.map((s) => (+ <option key={s} value={s}>+ {s}+ </option>+ ))}+ </select>+ </div>+ <div>+ <label htmlFor="watch-ceiling" className={labelCls}>Severity ceiling</label>+ <select+ id="watch-ceiling"+ value={severityCeiling}+ onChange={(e) => setSeverityCeiling(e.target.value as WatchlistSeverity)}+ className={fieldCls}+ >+ {SEVERITIES.map((s) => (+ <option key={s} value={s}>+ {s}+ </option>+ ))}+ </select>+ </div>+ </div>+ </div>+ </details></div>{err && (- <div className="mt-3 p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm">+ <div className="mt-4 px-4 py-3 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-500 text-[15px]">{err}</div>)}- <div className="flex justify-end gap-2 mt-4">- <button- type="button"- disabled={saving}- onClick={onClose}- className="px-4 py-2 text-sm rounded-lg border border-line hover:bg-surface-overlay disabled:opacity-50"- >+ <div className="flex justify-end gap-2 mt-5">+ <Button variant="ghost" disabled={saving} onClick={onClose}>Cancel- </button>- <button- type="button"- disabled={saving || !slug.trim() || !target.trim()}+ </Button>+ <Button+ variant="primary"+ disabled={saving || !(slug.trim() || slugSuggestion) || !target.trim()}onClick={submit}- className="px-4 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white font-medium disabled:opacity-50">{saving ? "Adding…" : "Add monitor"}- </button>+ </Button></div></div></div>@@ -658,56 +649,52 @@ export default function WatchlistPage() {/>)}<main className="flex-1 overflow-y-auto">- <div className="max-w-5xl mx-auto px-4 sm:px-6 py-6">- <div className="flex flex-col sm:flex-row sm:items-baseline justify-between gap-3 mb-6">- <div>- <h1 className="text-xl font-semibold text-fg">Watch list</h1>- <p className="text-sm text-fg-muted mt-0.5">+ <div className="max-w-5xl mx-auto px-4 sm:px-6 py-6 sm:py-8">+ <div className="flex flex-col sm:flex-row sm:items-end justify-between gap-4 mb-8">+ <div className="max-w-2xl">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg">+ What the Executive watches+ </h1>+ <p className="text-[15px] text-fg-muted mt-2">External conditions the Executive is monitoring. Signals that surviveseverity + triage become proposals in your briefing.</p></div>- <button- onClick={() => setShowAdd(true)}- className="self-start flex-shrink-0 px-4 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white font-medium"- >+ <Button variant="primary" className="self-start sm:self-auto flex-shrink-0" onClick={() => setShowAdd(true)}>+ Add monitor- </button>+ </Button></div>- {loading && <p className="text-fg-muted text-sm">Loading…</p>}+ {loading && <p className="text-fg-muted text-[15px]">Loading…</p>}{error && (- <div className="p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm mb-4">+ <div className="px-4 py-3 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-500 text-[15px] mb-4">{error}</div>)}{!loading && !error && items.length === 0 && (- <div className="rounded-xl border border-line bg-surface-elevated p-8 text-center">- <p className="text-fg-muted text-sm mb-3">Nothing being watched yet.</p>- <p className="text-xs text-fg-subtle mb-4">+ <div className="rounded-2xl border border-dashed border-line p-8 text-center">+ <p className="text-fg-muted text-[15px] mb-3">Nothing being watched yet.</p>+ <p className="text-sm text-fg-subtle mb-4">Ask the Executive in chat:{" "}<span className="italic">Watch Apple stock, alert me on 5% moves.</span></p>- <button- onClick={() => setShowAdd(true)}- className="px-4 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white"- >+ <Button variant="primary" onClick={() => setShowAdd(true)}>Add a monitor →- </button>+ </Button></div>)}{suggestions.length > 0 && (- <div className="mb-8">- <div className="flex items-baseline gap-2 mb-1">- <span className="text-sm font-semibold text-fg">Suggested by the Executive</span>- <span className="text-xs text-fg-muted">+ <div className="mb-10">+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1 mb-1">+ <h2 className="text-xl font-bold tracking-tight text-fg">Suggested by the Executive</h2>+ <span className="text-[15px] text-fg-muted">{suggestions.length} waiting for you</span></div>- <p className="text-xs text-fg-subtle mb-3">+ <p className="text-sm text-fg-subtle mb-4 max-w-3xl">Sources the research council thought worth monitoring but couldn't tiefirmly enough to your company data to add on its own. They poll inshadow mode and never alert until you approve. Declines are remembered.@@ -734,20 +721,22 @@ export default function WatchlistPage() {<div key={group.key}><buttontype="button"+ aria-expanded={!isCollapsed}onClick={() => toggleCollapsed(group.key)}- className="w-full flex items-center gap-2 mb-3 text-left"+ className="w-full min-h-10 flex items-center gap-2 mb-3 text-left"><span+ aria-hidden="true"className={`text-fg-muted text-xs transition-transform ${isCollapsed ? "" : "rotate-90"}`}>▶</span>- <span className="text-sm font-semibold text-fg">+ <span className="text-base font-semibold text-fg">{group.label}</span>- <span className="text-xs text-fg-muted">+ <span className="text-sm text-fg-muted">{group.items.length}{" "}{group.items.length === 1 ? "monitor" : "monitors"}</span>@@ -761,7 +750,6 @@ export default function WatchlistPage() {onToggle={toggle}toggleBusy={busySlugs.has(item.slug)}onStopWatching={stopWatching}- departmentTitle={departmentTitles[item.route_to_department]}/>))}</div>diff --git a/packages/ui/src/components/ArtifactViewer.tsx b/packages/ui/src/components/ArtifactViewer.tsxindex 438bc031..fcef953a 100644--- a/packages/ui/src/components/ArtifactViewer.tsx+++ b/packages/ui/src/components/ArtifactViewer.tsx@@ -4,6 +4,7 @@ import ReactMarkdown from "react-markdown";import remarkGfm from "remark-gfm";import type { ArtifactFormat } from "@/lib/api";+import { buttonClass } from "@/components/ui/Button";import { hostOf } from "@/lib/url";// Blocks every network fetch and all script from inside an HTML artifact.@@ -20,17 +21,17 @@ function withCsp(html: string): string {export function MarkdownArticle({ markdown }: { markdown: string }) {return (<article- className="prose prose-invert prose-sm max-w-none rounded-lg border border-line bg-surface/40 p-6+ className="prose prose-invert max-w-none rounded-2xl border border-line bg-surface-elevated p-5 sm:p-8prose-headings:text-fg prose-headings:font-semiboldprose-p:text-fg prose-p:leading-relaxedprose-strong:text-fg- prose-code:text-indigo-300 prose-code:bg-surface-overlay prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:before:content-none prose-code:after:content-none+ prose-code:text-accent prose-code:bg-surface-overlay prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:before:content-none prose-code:after:content-noneprose-pre:bg-surface-overlay prose-pre:border prose-pre:border-line-strongprose-blockquote:border-line-strong prose-blockquote:text-fg-mutedprose-ul:text-fg prose-ol:text-fgprose-li:marker:text-fg-mutedprose-hr:border-line-strong- prose-a:text-indigo-400 prose-a:no-underline hover:prose-a:underline+ prose-a:text-accent prose-a:no-underline hover:prose-a:underlineprose-table:text-fg prose-th:text-fg prose-th:border-line-strong prose-td:border-line-strong"><ReactMarkdown@@ -69,7 +70,7 @@ export default function ArtifactViewer({ format, body, title, externalUrl, linkLsandbox="allow-popups allow-popups-to-escape-sandbox"referrerPolicy="no-referrer"srcDoc={withCsp(body)}- className="w-full h-[75vh] rounded-lg border border-line bg-white"+ className="w-full h-[75vh] rounded-2xl border border-line bg-white"/>);}@@ -82,10 +83,10 @@ export default function ArtifactViewer({ format, body, title, externalUrl, linkLhref={externalUrl}target="_blank"rel="noopener noreferrer nofollow"- className="inline-flex items-center gap-2 rounded-md border border-indigo-500/40 bg-indigo-500/10 px-4 py-2 text-sm text-indigo-300 hover:bg-indigo-500/20"+ className={buttonClass("primary", "md")}>Open {linkLabel || "link"} ↗- <span className="text-xs text-fg-muted">({hostOf(externalUrl)})</span>+ <span className="text-sm font-normal opacity-80">({hostOf(externalUrl)})</span></a>)}{body && <MarkdownArticle markdown={body} />}@@ -96,12 +97,12 @@ export default function ArtifactViewer({ format, body, title, externalUrl, linkLreturn (<div className="space-y-2">{format === "xlsx" && (- <div className="text-xs text-fg-muted">+ <div className="text-sm text-fg-muted">Preview of the workbook. Download it for every row and native Excel formatting.</div>)}{format === "docx" && (- <div className="text-xs text-fg-muted">+ <div className="text-sm text-fg-muted">Preview of the Word document. Download it for the .docx file.</div>)}diff --git a/packages/ui/src/components/BriefDeliveryNotice.tsx b/packages/ui/src/components/BriefDeliveryNotice.tsxindex 5417b51b..8e36d91c 100644--- a/packages/ui/src/components/BriefDeliveryNotice.tsx+++ b/packages/ui/src/components/BriefDeliveryNotice.tsx@@ -6,12 +6,11 @@ import { useEffect, useState } from "react";import { getBriefDelivery, type BriefDeliveryNotice as Notice } from "@/lib/api";/**- * Above the Briefing: the latest morning brief or end-of-day digest that- * wasn't sent, why, and what fixes it. The API only tells the owner, and- * says nothing while briefs are going out, so most of the time this renders- * nothing.+ * The latest morning brief or end-of-day digest that wasn't sent, why, and+ * what fixes it. The API only tells the owner, and says nothing while+ * briefs are going out, so most of the time this is null.*/-export default function BriefDeliveryNotice() {+export function useBriefDeliveryNotice(): Notice | null {const [notice, setNotice] = useState<Notice | null>(null);useEffect(() => {@@ -22,7 +21,11 @@ export default function BriefDeliveryNotice() {return () => controller.abort();}, []);- if (!notice) return null;+ return notice;+}++/** Home's banner for a brief that wasn't sent (see useBriefDeliveryNotice). */+export default function BriefDeliveryNotice({ notice }: { notice: Notice }) {const day = new Date(notice.at);const when = Number.isNaN(day.getTime())? ""@@ -30,25 +33,25 @@ export default function BriefDeliveryNotice() {return (<divrole="status"- className="border-b border-line bg-amber-500/5 px-4 sm:px-6 py-2.5 flex items-start gap-2 flex-shrink-0"+ className="flex items-start gap-3 rounded-2xl border border-amber-500/30 bg-amber-500/5 px-4 py-3">{/* Themed text with an amber marker: amber text is too faint on the light theme. */}- <span className="mt-1.5 inline-block w-1.5 h-1.5 rounded-full bg-amber-400 flex-shrink-0" aria-hidden="true" />- <p className="flex-1 min-w-0 text-xs text-fg-muted leading-snug">- <span className="font-medium text-fg">+ <span className="mt-2 inline-block h-2 w-2 flex-shrink-0 rounded-full bg-amber-400" aria-hidden="true" />+ <p className="min-w-0 flex-1 text-[15px] leading-snug text-fg-muted">+ <span className="font-semibold text-fg">Your {notice.brief}{when} wasn't sent:</span>{" "}{notice.problem}. {notice.fix}{" "}{notice.readable ? (<>- <Link href="/artifacts" className="text-indigo-400 hover:text-indigo-300 font-medium whitespace-nowrap">+ <Link href="/artifacts" className="font-medium text-accent hover:underline whitespace-nowrap">Read it</Link><span aria-hidden="true"> · </span></>) : null}- <Link href="/settings/status" className="text-indigo-400 hover:text-indigo-300 font-medium whitespace-nowrap">+ <Link href="/settings/status" className="font-medium text-accent hover:underline whitespace-nowrap">Setup status</Link></p>diff --git a/packages/ui/src/components/Briefing.tsx b/packages/ui/src/components/Briefing.tsxindex 7a788393..130a71f8 100644--- a/packages/ui/src/components/Briefing.tsx+++ b/packages/ui/src/components/Briefing.tsx@@ -1,1902 +1,139 @@"use client";import Link from "next/link";-import { Children, useCallback, useEffect, useRef, useState } from "react";-import ReactMarkdown from "react-markdown";-import remarkGfm from "remark-gfm";+import { useCallback, useEffect, useRef, useState } from "react";import {ackAlert,approveDecision,bulkAckAlerts,- closeOpenLoop,- deleteInitiative,- getPersonOpenLoops,getToday,- getTopThree,- getWeeklyReview,- listInitiatives,rejectDecision,reopenAlert,reviewAlerts,- updateInitiative,- type DepartmentBriefItem,- type HandledItem,- type InFlightItem,- type Initiative,- type OpenLoop,- type PersonBriefItem,- type ClientCockpitCard,type ProposalItem,type Today,- type TopThreeToday,- type WeeklyReviewSummary,} from "@/lib/api";-import { MEMORY_ACTIONS, briefingMemoryLine, nudgeAction } from "@/lib/briefing-memory";-import { clientCountsSummary, renewalBadge } from "@/lib/practice";-import { dueSoon, loopText, principalIdOf } from "@/lib/dueSoon";+import { MEMORY_ACTIONS, briefingMemoryLine } from "@/lib/briefing-memory";+import { briefingSummary, greeting, type SummaryPart } from "@/lib/briefingSummary";+import { principalIdOf } from "@/lib/dueSoon";+import { groupHandled } from "@/lib/handled";import {BRIEFING_REFRESH_INTERVAL_MS,narrativeRepollDelay,narrativeUpdatedLabel,shouldRefreshOnFocus,} from "@/lib/narrativeFreshness";-import { reviewExcerpt, reviewRanLabel, topThreeSlot, topThreeWhy } from "@/lib/rhythmCards";-import {- HANDLED_REOPENABLE,- groupHandled,- handledAlsoLine,- handledHeadline,- handledKey,- handledProofHref,- isCloseKind,- type HandledRow,-} from "@/lib/handled";+import { reviewRanLabel } from "@/lib/rhythmCards";import InfoTip from "./InfoTip";-import RepliesWaiting from "./RepliesWaiting";-import RosterRequestCard from "./RosterRequestCard";-import { hostOf } from "@/lib/url";-import { SectionHeading } from "./memories/shared";+import { REPLIES_WAITING_TIP, ReplyCardItem, useReplyCards } from "./RepliesWaiting";+import Icon from "./Icon";+import {+ HandledPanelBody,+ InFlightPanelBody,+ MonitoringPanelBody,+ PracticeClientsPanelBody,+ inFlightNext,+} from "./briefing/AwarenessPanels";+import NarrativeBody from "./briefing/Narrative";+import ProposalCard from "./briefing/ProposalCard";+import {+ NEEDS_YOU_DISMISS_OLDER_THAN_DAYS,+ TONE_TEXT,+ olderThan,+ type ContinueHandler,+} from "./briefing/shared";+import {+ DueSoonPanelBody,+ ProjectsPanelBody,+ TopThreeList,+ WeeklyReviewPanelBody,+ useActiveProjects,+ useOpenLoops,+ useWeeklyReview,+} from "./briefing/SoloPanels";+import { DepartmentsPanelBody, PeoplePanelBody, peopleSummary } from "./briefing/TeamPanels";+import { buttonClass } from "./ui/Button";+import OverflowMenu from "./ui/OverflowMenu";+import SidePanel from "./ui/SidePanel";import { useWorkspace } from "./workspace/WorkspaceContext";-// Future-relative label for a pending run time ("in 8h"). Past/blank →-// "soon" (the caller renders "overdue" separately via the backend flag).-// Badge text for an artifact card: the format when it isn't plain Markdown.-function artifactBadge(format: ProposalItem["artifact_format"]): string {- switch (format) {- case "html":- return "Web page";- case "docx":- return "Word doc";- case "xlsx":- return "Spreadsheet";- case "link":- return "Link";- default:- return "Document";- }-}--function formatFuture(iso: string): string {- const then = new Date(iso).getTime();- if (Number.isNaN(then)) return "soon";- const mins = Math.round((then - Date.now()) / 60000);- if (mins <= 0) return "soon";- if (mins < 60) return `in ${mins}m`;- const hrs = Math.round(mins / 60);- if (hrs < 24) return `in ${hrs}h`;- return `in ${Math.round(hrs / 24)}d`;-}--// High-volume sections render their full list inside a fixed-height scroll-// (max-h-[32rem] — like the Pulse "Recent activity" card) instead of capping-// at a "Show N more" expander, so no section grows the page. Count badges-// still reflect the full totals.-// Narrative bullets kept on screen before the rest fold into "Show N more".-const NARRATIVE_HEAD_BULLETS = 2;-// A proposal body longer than this (chars) is clamped to a few lines at rest-// with a Show more/less toggle, so the "Needs you" queue stays scannable.-const LONG_BODY_CHARS = 180;--// "Needs you" shows this many cards after "Start here" before a Show-more-// toggle takes over — a queue, not a wall.-const NEEDS_YOU_VISIBLE = 8;-// Bulk-dismiss cutoffs (days) offered under each lane.-const NEEDS_YOU_DISMISS_OLDER_THAN_DAYS = 7;-const MONITORING_DISMISS_OLDER_THAN_DAYS = 3;--// Compact age label ("3h", "9d") for a card chip; "" for an unparseable stamp.-function ageLabel(iso: string | null | undefined, now: Date = new Date()): string {- if (!iso) return "";- const t = Date.parse(iso);- if (Number.isNaN(t)) return "";- const mins = Math.max(0, Math.round((now.getTime() - t) / 60000));- if (mins < 60) return `${mins}m`;- const hours = Math.round(mins / 60);- if (hours < 48) return `${hours}h`;- return `${Math.round(hours / 24)}d`;-}--// Whole days between now and an ISO stamp: 0 = due within the day, negative =-// past (floor, so an 11-hour-old deadline is -1 → "overdue", never "due today").-// null if unparseable.-function daysUntil(iso: string | null | undefined, now: Date = new Date()): number | null {- if (!iso) return null;- const t = Date.parse(iso);- if (Number.isNaN(t)) return null;- return Math.floor((t - now.getTime()) / 86400000);-}--// Ids of proposals older than `days` — what the bulk "Dismiss older than"-// footer sends: explicit ids from the caller's own lane (visible cards and-// those behind "Show more" alike), never a server-side age sweep, which would-// also hit teammates' routed items.-function olderThan(proposals: ProposalItem[], days: number, now: Date = new Date()): number[] {- const cutoff = now.getTime() - days * 86400000;- return proposals- .filter((p) => {- // Same age anchor as the server's TTL: a re-firing situation is not old.- const t = Date.parse(p.last_seen_at ?? p.created_at);- return !Number.isNaN(t) && t < cutoff;- })- .map((p) => p.alert_id);+// The card pieces stay importable from here for pages that show them alone.+export { ProposalCard };+export { DeptCard } from "./briefing/TeamPanels";++// Home, the briefing: a greeting and one summary line, the Ask box, the+// "Needs you" queue as large cards, then a row of count tiles — one per+// awareness section with something in it — each opening its full list in a+// side panel. Today's written brief ("What's going on") opens in a panel too.++// "Needs you" shows this many cards before a "Show N more" toggle.+const NEEDS_YOU_VISIBLE = 3;++const NEEDS_YOU_ID = "sec-needs-you";++type PanelKey =+ | "brief"+ | "departments"+ | "people"+ | "inFlight"+ | "handled"+ | "monitoring"+ | "team"+ | "clients"+ | "projects"+ | "dueSoon"+ | "weeklyReview";++interface Tile {+ key: PanelKey;+ value: string;+ label: string;+ sub: string;+ subTone?: keyof typeof TONE_TEXT;}interface BriefingProps {// Called when the user clicks a briefing item to continue the thread- // in chat. The parent (usually the root page) is expected to switch- // its main view from briefing → chat and seed the input with `prompt`.- // When omitted, items render as plain navigation links so the standalone- // /today page still works.+ // in chat. The parent (the root page) switches its main view from+ // briefing → chat and seeds the input with `prompt`. When omitted, items+ // render as plain navigation links.onContinue?: ContinueHandler;- // Set to true when this Briefing is the root landing surface — adds a- // "Here's where we are" header. The standalone /today page already- // gets the global AppShell breadcrumb, so it omits this prop.+ // Set to true when this Briefing is the root landing surface — adds the+ // greeting header.showHeader?: boolean;- // Personalises the header greeting when showHeader is true.+ // Personalises the greeting when showHeader is true.firstName?: string;+ // Home's one banner slot: the most important notice the page has (paused,+ // no profile, a brief that wasn't sent). When empty, the quiet-day note+ // takes the slot.+ banner?: React.ReactNode;}-function formatRelTime(iso: string): string {- try {- const diff = new Date(iso).getTime() - Date.now();- const abs = Math.abs(diff);- if (abs < 60_000) return "now";- if (abs < 3_600_000) return `${Math.round(abs / 60_000)}m`;- if (abs < 86_400_000) return `${Math.round(abs / 3_600_000)}h`;- return `${Math.round(abs / 86_400_000)}d`;- } catch {- return "—";- }-}--interface ClickableProps {- onContinue?: ContinueHandler;- prompt: string;- href: string;- className: string;- children: React.ReactNode;-}--// Either a button (when onContinue is provided — seeds chat with prompt)-// or a Link (standalone /today behavior). Same visual styling either way.-function ClickableBriefingItem({ onContinue, prompt, href, className, children }: ClickableProps) {- if (onContinue) {- return (- <button- type="button"- onClick={() => onContinue(prompt)}- className={`${className} text-left w-full cursor-pointer`}- >- {children}- </button>- );- }- return (- <Link href={href} className={className}>- {children}- </Link>- );-}--// Flatten a react-markdown AST node to its plain text. Bullets in the-// "What's going on" narrative are `**Headline** — text`; this reads the-// underlying text nodes (recursing through bold/em/links) so a clicked bullet-// can be handed to the Executive as one clean string.-function nodeToPlainText(node: unknown): string {- if (!node || typeof node !== "object") return "";- const n = node as { value?: string; children?: unknown[] };- if (typeof n.value === "string") return n.value;- if (Array.isArray(n.children)) return n.children.map(nodeToPlainText).join("");- return "";-}--// Hands a briefing item to chat. `memoryText` is what peer memory records as-// the user's words for that turn; omit it when `prompt` is already just the-// user's own ask.-type ContinueHandler = (prompt: string, memoryText?: string) => void;--// Seed prompt for a clicked narrative bullet. The Executive receives the-// open-alert digest as a <briefing> block on every chat turn, so the seed only-// needs to name the item — the exec matches it by headline. No alert_id is-// carried (the bullet has none); acking stays on the proposal card.-function buildNarrativeSeed(text: string): string {- return (- `Let's dig into this from today's briefing:\n\n"${text}"\n\n` +- `[Discuss mode] Walk me through what's going on, why it matters, and what ` +- `you'd recommend. The full details are in your briefing context. Answer ` +- `conversationally — don't take any action unless I explicitly ask.`- );-}--// Discuss-handoff seed for a passive monitoring signal — shared by the-// ProposalCard monitoring branch and the rail's MonitoringPanel so the two-// entry points stay in sync (don't approve, just interpret the signal).-function buildMonitoringSeed(proposal: ProposalItem): string {- const body = proposal.body || proposal.headline;- return (- `Help me understand this signal we're monitoring:\n\n${body}\n\n` +- `[Discuss mode — alert_id=${proposal.alert_id}] This is a passive ` +- `monitoring signal, not a proposal to approve. Explain why it matters, ` +- `whether it warrants any action, and what you'd recommend. Answer ` +- `conversationally. Only if I explicitly ask you to act should you do ` +- `more than advise; do not ack or dismiss the alert yourself.`- );-}--function DeptCard({ dept, onContinue, dimmed = false }: { dept: DepartmentBriefItem; onContinue?: ContinueHandler; dimmed?: boolean }) {- const hasIssues = dept.at_risk_count > 0 || dept.off_track_count > 0;- const prompt = `Tell me about ${dept.title} — what's the current status?`;- // Problem goals beyond the inline cap fall to the department page.- const attentionGoalOverflow =- dept.at_risk_count + dept.off_track_count - (dept.attention_goals?.length ?? 0);- return (- <ClickableBriefingItem- onContinue={onContinue}- prompt={prompt}- href={`/departments/${dept.slug}`}- className={`block group py-3 hover:bg-surface-overlay/30 transition-colors${dimmed ? " opacity-60 hover:opacity-100" : ""}`}- >- <div className="flex items-start justify-between gap-2 mb-3">- <div className="text-sm font-semibold text-fg group-hover:text-indigo-300 transition-colors" title={dept.title}>- {dept.title}- </div>- <span className="flex-shrink-0 text-[10px] text-fg-muted">{dept.authority_level.replace("_", " ")}</span>- </div>- <div className="flex items-center gap-3 text-xs">- <span className="text-fg-muted">{dept.goal_count} Goal{dept.goal_count !== 1 ? "s" : ""}</span>- {dept.at_risk_count > 0 && (- <span className="inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium bg-amber-500/20 text-amber-300 border-amber-500/30">- {dept.at_risk_count} at risk- </span>- )}- {dept.off_track_count > 0 && (- <span className="inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium bg-rose-500/20 text-rose-300 border-rose-500/30">- {dept.off_track_count} off track- </span>- )}- {!hasIssues && dept.goal_count > 0 && (- <span className="inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium bg-emerald-500/20 text-emerald-300 border-emerald-500/30">- on track- </span>- )}- {dept.awaiting_count > 0 && (- <span className="ml-auto inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium bg-sky-500/20 text-sky-300 border-sky-500/30">- {dept.awaiting_count} awaiting- </span>- )}- </div>- {/* The actual off-track / at-risk goals, inline — so the card is- insightful at rest instead of a count you have to click into.- Healthy / inactive departments carry no attention_goals. */}- {dept.attention_goals && dept.attention_goals.length > 0 && (- <div className="mt-3 space-y-1.5 border-t border-line pt-2.5">- {dept.attention_goals.map((g, i) => (- <div key={i} className="flex items-start gap-1.5 text-[11px] leading-snug">- <span- aria-hidden="true"- className={`mt-1 h-1.5 w-1.5 flex-shrink-0 rounded-full ${g.status === "off_track" ? "bg-rose-400" : "bg-amber-400"}`}- />- <span className="min-w-0">- <span className="text-fg">{g.key_result}</span>- {(g.current || g.target) && (- <span className="text-fg-subtle"> — {g.current || "—"} vs {g.target || "—"}</span>- )}- </span>- </div>- ))}- {attentionGoalOverflow > 0 && (- <div className="text-[10px] text-fg-subtle pl-3">+{attentionGoalOverflow} more</div>- )}- </div>- )}- </ClickableBriefingItem>- );-}--// Compact label for an authority-scope token (see people/models.py).-const AUTHORITY_LABELS: Record<string, string> = {- spend_lt_2k: "spend<2k",- spend_lt_10k: "spend<10k",- spend_gt_10k: "spend>10k",- hiring_signoff: "hiring",- vendor_onboarding: "vendors",- customer_credit: "credit",- legal_sign: "legal",- board_comms: "board",- wildcard: "all",-};--function authorityLabel(token: string): string {- return AUTHORITY_LABELS[token] ?? token;-}--// Status chip text + colour. `overdue` repaints the attention states red.-function personStatusChip(person: PersonBriefItem): { label: string; cls: string } | null {- const red = "bg-rose-500/20 text-rose-300 border-rose-500/30";- const amber = "bg-amber-500/20 text-amber-300 border-amber-500/30";- const sky = "bg-sky-500/20 text-sky-300 border-sky-500/30";- const slate = "bg-slate-500/20 text-slate-300 border-slate-500/30";- switch (person.status) {- case "needs_reply":- return {- label: person.awaiting_reply_count > 1 ? `${person.awaiting_reply_count} awaiting reply` : "Awaiting reply",- cls: person.overdue ? red : amber,- };- case "awaiting":- return {- label: `${person.awaiting_count} to action`,- cls: person.overdue ? red : sky,- };- case "on_leave":- return { label: "On leave", cls: slate };- default:- return null; // "clear" — no chip, shown as subtle text instead- }-}--function PersonRow({ person }: { person: PersonBriefItem }) {- const chip = personStatusChip(person);- const pills = person.authority_scope.slice(0, 2);- const extraPills = person.authority_scope.length - pills.length;- return (- <Link- href={`/people/${person.id}`}- className="block group py-3 hover:bg-surface-overlay/30 transition-colors"- >- <div className="flex items-center justify-between gap-2">- <div className="flex items-center gap-2 min-w-0">- <div className="w-6 h-6 rounded-full bg-gradient-to-br from-indigo-500 to-violet-600 flex items-center justify-center flex-shrink-0">- <span className="text-white text-[9px] font-bold">{person.full_name.charAt(0)}</span>- </div>- <div className="min-w-0">- <div className="text-xs font-medium text-fg truncate">{person.full_name}</div>- <div className="text-[10px] text-fg-muted truncate">{person.role}</div>- </div>- </div>- <div className="flex-shrink-0 text-right">- {chip ? (- <span className={`inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium ${chip.cls}`}>- {chip.label}- </span>- ) : (- <span className="text-[10px] text-fg-subtle">Clear</span>- )}- {chip && person.status === "awaiting" && person.soonest_sla_at && (- <div className={`text-[10px] mt-0.5 ${person.overdue ? "text-rose-300" : "text-fg-muted"}`}>- SLA {person.overdue ? "overdue" : `in ${formatRelTime(person.soonest_sla_at)}`}- </div>- )}- </div>- </div>-- {person.insight && (- <p className="mt-1.5 text-[10px] leading-snug text-fg-muted line-clamp-2">{person.insight}</p>- )}-- <div className="mt-1.5 flex items-center gap-1.5 flex-wrap">- {person.status !== "on_leave" && (- <span className="inline-flex items-center gap-1 text-[10px] text-fg-subtle">- <span className={`w-1.5 h-1.5 rounded-full ${person.reachable_now ? "bg-emerald-400" : "bg-slate-500"}`} />- {person.reachable_now- ? "Available"- : person.next_window_at- ? `Back in ${formatRelTime(person.next_window_at)}`- : "Away"}- </span>- )}- {pills.map((tok) => (- <span key={tok} className="inline-block px-1 py-px rounded bg-surface-overlay text-[9px] text-fg-subtle border border-line">- {authorityLabel(tok)}- </span>- ))}- {extraPills > 0 && (- <span className="text-[9px] text-fg-subtle">+{extraPills}</span>- )}- </div>- </Link>- );-}--// One-line roster summary shown under the People header.-function peopleSummary(people: PersonBriefItem[]): { text: string; hasOverdue: boolean } {- const needsReply = people.filter((p) => p.status === "needs_reply").length;- const awaiting = people.filter((p) => p.status === "awaiting").length;- const onLeave = people.filter((p) => p.status === "on_leave").length;- const overdue = people.filter((p) => p.overdue).length;- const parts: string[] = [];- if (needsReply > 0) parts.push(`${needsReply} to reply`);- if (awaiting > 0) parts.push(`${awaiting} to action`);- if (overdue > 0) parts.push(`${overdue} overdue`);- if (onLeave > 0) parts.push(`${onLeave} on leave`);- return { text: parts.length > 0 ? parts.join(" · ") : "All clear", hasOverdue: overdue > 0 };-}--// Section header label. `primary` makes a section visually dominant (the-// things that need the user's action); `ambient` is the quieter uppercase-// style used for awareness sections (in flight, monitoring, departments,-// activity). Count renders inline and only when non-zero.-function SectionLabel({- variant,- count,- children,-}: {- variant: "primary" | "ambient";- count?: number;- children: React.ReactNode;-}) {- if (variant === "primary") {- return (- <span className="text-sm font-semibold text-fg">- {children}- {count != null && count > 0 && (- <span className="ml-1.5 font-normal text-fg-muted">({count})</span>- )}- </span>- );- }- return (- <span className="text-xs font-semibold uppercase tracking-wide text-fg-muted group-open:text-fg">- {children}- {count != null && count > 0 && (- <span className="ml-1 font-normal normal-case tracking-normal">({count})</span>- )}- </span>- );-}--type StatTone = "indigo" | "rose" | "amber" | "sky" | "slate";-// `targetIds` are the section element ids a pill jumps to, in priority order-// (the first one that's actually present wins). Each section now renders once-// (the responsive grid stacks instead of duplicating into a mobile block), so-// these are effectively single-element, but the list shape is kept for headroom.-// `href` (solo's goals pill) navigates instead: its detail lives on /goals.-interface StatPill { label: string; tone: StatTone; targetIds: string[]; href?: string }--const STAT_TONES: Record<StatTone, string> = {- indigo: "bg-indigo-500/15 text-indigo-300 border-indigo-500/30",- rose: "bg-rose-500/15 text-rose-300 border-rose-500/30",- amber: "bg-amber-500/15 text-amber-300 border-amber-500/30",- sky: "bg-sky-500/15 text-sky-300 border-sky-500/30",- // Quietest tone — passive monitoring signals, not something demanding action.- slate: "bg-slate-500/15 text-slate-300 border-slate-500/30",-};--// Section ids the status pills scroll to. Kept beside the pill builder so the-// ids and the `id={…}` attributes on the sections stay in sync.-const SECTION_IDS = {- needsYou: "sec-needs-you",- handled: "sec-handled",- inFlight: "sec-in-flight",- monitoring: "sec-monitoring",- departments: "sec-departments",- people: "sec-people",- practice: "sec-practice",- projects: "sec-projects",- dueSoon: "sec-due-soon",- topThree: "sec-top-three",- weeklyReview: "sec-weekly-review",- repliesWaiting: "sec-replies-waiting",-} as const;--// Smooth-scroll to the first rendered (visible) section in `ids`, popping open-// a collapsed <details> so the pill "shows the detail". No-ops gracefully when-// none of the targets are on the page (e.g. a 1-person org has no People block).-function scrollToFirstVisible(ids: string[]): void {- for (const id of ids) {- const el = document.getElementById(id);- if (el && el.offsetParent !== null) {- el.querySelector("details")?.setAttribute("open", "");- el.scrollIntoView({ behavior: "smooth", block: "start" });- return;- }- }-}--// Glanceable status pills shown under the header — a one-second read of-// what needs attention, ordered most-urgent first. Zero counts are-// dropped; an empty result renders an "All clear" pill at the call site.-function briefingStats(args: {- needsYou: number;- handledOvernight: number;- peopleOverdue: number;- peopleNeedReply: number;- deptAtRisk: number;- /** Solo only: at-risk + off-track goals, which have no card on the page. */- goalsAtRisk?: number;- inFlight: number;- monitoring: number;-}): StatPill[] {- const pills: StatPill[] = [];- const peopleTargets = [SECTION_IDS.people];- if (args.needsYou > 0)- pills.push({ label: `${args.needsYou} need${args.needsYou === 1 ? "s" : ""} you`, tone: "indigo", targetIds: [SECTION_IDS.needsYou] });- // What the Executive already did on its own — shown right after the ask,- // so the first read is "N need you, it handled M" (trust + relief).- if (args.handledOvernight > 0)- pills.push({ label: `Executive handled ${args.handledOvernight} overnight`, tone: "sky", targetIds: [SECTION_IDS.handled] });- if (args.peopleOverdue > 0)- pills.push({ label: `${args.peopleOverdue} overdue`, tone: "rose", targetIds: peopleTargets });- if (args.peopleNeedReply > 0)- pills.push({ label: `${args.peopleNeedReply} awaiting reply`, tone: "amber", targetIds: peopleTargets });- if (args.deptAtRisk > 0)- pills.push({ label: `${args.deptAtRisk} dept${args.deptAtRisk === 1 ? "" : "s"} at risk`, tone: "amber", targetIds: [SECTION_IDS.departments] });- if (args.goalsAtRisk && args.goalsAtRisk > 0)- pills.push({ label: `${args.goalsAtRisk} goal${args.goalsAtRisk === 1 ? "" : "s"} at risk`, tone: "amber", targetIds: [], href: "/goals" });- if (args.inFlight > 0)- pills.push({ label: `${args.inFlight} in flight`, tone: "sky", targetIds: [SECTION_IDS.inFlight] });- // Passive watchlist signals — quietest pill, last, so it never crowds the- // action-oriented ones but the lane is still reachable in one click.- if (args.monitoring > 0)- pills.push({ label: `${args.monitoring} monitoring`, tone: "slate", targetIds: [SECTION_IDS.monitoring] });- return pills;-}--// Lifecycle presentation for one proposal card — the review-driven pieces the-// card composes: the one-line "what changed since you last looked", the chip-// row (age, seen ×N, why-now / due, likely-stale, folded-in, draft-ready), the-// muted "Reviewed <ago>" footer, and the single recommended move as a control.-// A pure builder (no hooks) so ProposalCard stays a layout function.-function buildProposalLifecycle({- proposal,- assignee,- onContinue,- busy,-}: {- proposal: ProposalItem;- assignee: PersonBriefItem | null | undefined;- onContinue?: ContinueHandler;- busy: boolean;-}): {- reviewLine: React.ReactNode;- lifecycleRow: React.ReactNode;- reviewedFooter: React.ReactNode;- moveButton: React.ReactNode;-} {-// Lifecycle signals from the Executive's review (alerts/review.py) and the-// coalescing pipeline: the one-line "what changed since you last looked",-// then chips — age, seen ×N, why-now / deadline, likely-stale, folded-in,-// updated — and a muted "Reviewed <ago>" footer.-const verdict = proposal.review_verdict ?? "";-const isLikelyStale = verdict === "likely_stale";-const age = ageLabel(proposal.created_at);-const dueIn = daysUntil(proposal.due_at);-const reviewLine = proposal.review_note ? (- <p className={`mb-1.5 text-xs leading-snug ${isLikelyStale ? "text-amber-300" : "text-fg-muted"}`}>- <span className="text-[10px] uppercase tracking-wide mr-1">- {isLikelyStale ? "Likely stale" : verdict === "changed" ? "Updated" : "Since you last looked"}- </span>- {proposal.review_note}- </p>-) : null;-const lifecycleChips: { label: string; cls: string; title?: string }[] = [];-if (age) lifecycleChips.push({ label: age, cls: "text-fg-subtle border-line", title: `Raised ${new Date(proposal.created_at).toLocaleString()}` });-if ((proposal.occurrence_count ?? 1) > 1)- lifecycleChips.push({- label: `seen ×${proposal.occurrence_count}`,- cls: "text-fg-muted border-line",- title: proposal.last_seen_at ? `Last seen ${ageLabel(proposal.last_seen_at)} ago` : undefined,- });-if (proposal.why_now || dueIn != null) {- const due = dueIn == null ? "" : dueIn < 0 ? "overdue" : dueIn === 0 ? "due today" : `due in ${dueIn}d`;- lifecycleChips.push({- label: [proposal.why_now, due].filter(Boolean).join(" · "),- cls: "bg-amber-500/15 text-amber-300 border-amber-500/30",- });-}-if (isLikelyStale && !proposal.review_note)- lifecycleChips.push({ label: "Likely stale", cls: "bg-amber-500/15 text-amber-300 border-amber-500/30" });-if ((proposal.superseded_count ?? 0) > 0)- lifecycleChips.push({ label: `${proposal.superseded_count} folded in`, cls: "text-fg-muted border-line" });-if (verdict === "changed" && !proposal.review_note)- lifecycleChips.push({ label: "Updated by the Executive", cls: "text-sky-300 border-sky-500/30" });-if (verdict === "drafted")- lifecycleChips.push({ label: "Draft ready in your queue", cls: "bg-amber-500/15 text-amber-300 border-amber-500/30" });-const lifecycleRow = lifecycleChips.length > 0 ? (- <div className="mb-1.5 flex flex-wrap gap-1">- {lifecycleChips.map((c) => (- <span key={c.label} title={c.title} className={`inline-block px-1.5 py-0.5 rounded border text-[10px] ${c.cls}`}>- {c.label}- </span>- ))}- </div>-) : null;-const reviewedFooter = proposal.last_reviewed_at ? (- <p className="mt-1 text-[10px] text-fg-subtle">- Reviewed {ageLabel(proposal.last_reviewed_at)} ago- {verdict && verdict !== "likely_stale" ? ` · ${verdict}` : ""}- </p>-) : null;-// The single recommended move, as the primary control on the card. Route /-// escalate / draft already happened server-side (the card shows their-// trace); nudge and a suggested workflow are the two the user completes.-const moveButton = (() => {- const move = proposal.recommended_move ?? "";- if (move === "nudge" && onContinue) {- const who = assignee?.full_name ?? "the owner";- return (- <button- type="button"- onClick={() => onContinue(- `Nudge ${who} about this item — it has gone quiet: ${proposal.headline}\n\n` +- `Send a short, friendly check-in via message_person and tell me what you sent.`,- briefingMemoryLine(nudgeAction(who), proposal.headline),- )}- disabled={busy}- className="text-xs font-medium text-indigo-300 hover:text-indigo-200 px-2 py-1 rounded border border-indigo-500/30 transition-colors disabled:opacity-50"- >- ↪ Nudge {assignee?.full_name?.split(" ")[0] ?? "owner"}- </button>- );- }- if (move === "suggest_workflow" && proposal.suggested_workflow) {- return (- <Link- href={`/jobs/${proposal.suggested_workflow}`}- onClick={(e) => e.stopPropagation()}- className="text-xs font-medium text-indigo-300 hover:text-indigo-200 px-2 py-1 rounded border border-indigo-500/30 transition-colors"- >- ▶ Run {proposal.suggested_workflow.replace(/_/g, " ")}- </Link>- );- }- return null;-})();- return { reviewLine, lifecycleRow, reviewedFooter, moveButton };-}--function ProposalCard({- proposal,- people,- onContinue,- onApprove,- onDismiss,- onApproveWithEdits,- busy = false,- defaultBodyExpanded = false,- emphasized = false,-}: {- proposal: ProposalItem;- people: PersonBriefItem[];- onContinue?: ContinueHandler;- onApprove?: (p: ProposalItem) => void;- onDismiss?: (p: ProposalItem) => void;- onApproveWithEdits?: (p: ProposalItem, editedBody: string) => void;- busy?: boolean;- // Start the long-body expander open (no clamp) — used by the elevated- // "Start here" card so its body shows in full without a click.- defaultBodyExpanded?: boolean;- // Adds a left indigo accent to the flattened row — used for the- // "Start here" proposal so the single sharpest item stands out without- // breaking the divider-row rhythm.- emphasized?: boolean;-}) {- // Local edit-mode state. Entering edit mode replaces the body display- // with a textarea pre-filled with the proposal body; the action row- // simplifies to Cancel / Send approval. Exiting (Cancel) restores the- // normal layout without acking anything. Send approval pipes the- // edited text up through onApproveWithEdits so Briefing can ack the- // alert + seed the chat with a verbatim-send instruction.- const [editing, setEditing] = useState(false);- const [editedBody, setEditedBody] = useState("");- // Body expand/collapse for long action bodies (see isLongBody below). The- // elevated "Start here" card opts out of clamping via defaultBodyExpanded.- const [bodyOpen, setBodyOpen] = useState(defaultBodyExpanded);- // A roster request ("who is this new sender?") is answered on its own- // card (add / someone already on the list / ignore) — never through chat,- // so what a stranger wrote never seeds a turn. The card calls the- // /people/requests endpoints itself, then onDismiss drops it here. Below- // the hooks, which must run on every render.- if (proposal.roster_request) {- return (- <RosterRequestCard- request={proposal.roster_request}- emphasized={emphasized}- onResolved={() => onDismiss?.(proposal)}- />- );- }- function startEditing() {- setEditedBody(proposal.body || proposal.headline);- setEditing(true);- }- function cancelEditing() {- setEditing(false);- setEditedBody("");- }- function submitEdit() {- if (!onApproveWithEdits) return;- const text = editedBody.trim();- if (!text) return;- onApproveWithEdits(proposal, text);- }- const assignee = proposal.routed_to_person_id != null- ? people.find((p) => p.id === proposal.routed_to_person_id)- : null;- // Research artifacts (the Executive's `draft_artifact` tool) are full- // authored documents, not terse proposals. The `artifact` topic tag is- // the discriminator (mirrors the `external:*` tag convention). They get- // a document layout: title heading + Markdown body + a "why this is- // worth your time" block, and a review-not-approve action set.- const isArtifact = proposal.topic_tags?.includes("artifact") ?? false;- // Show the full body whenever the backend supplies it; fall back to- // headline for older payloads that didn't carry body. Visible card- // text wraps naturally and we no longer truncate mid-word.- const displayText = proposal.body || proposal.headline;- // Monitoring items are passive external/watchlist signals — there's nothing- // to approve, so the card reframes the body as a "why it's on your radar"- // rationale and drops the suggested-action ("If you approve:") block.- const isMonitoring = proposal.category === "monitoring";- // Decision-backed proposals (gated calendar bookings) execute server-side via- // the /decisions endpoints — Approve books the meeting, Dismiss rejects it.- // The verbatim-DM "Edit & approve" flow doesn't map to a calendar booking, so- // it's hidden for these cards.- const isDecision = proposal.decision_instance_id != null;- // Long free-text action bodies are the briefing's other "wall of text".- // Clamp them to a few lines at rest, with a Show more/less toggle, so the- // "Needs you" queue stays scannable. Monitoring (bounded rationale) and- // artifacts (their own scroll region) keep their existing treatment.- const isLongBody = !isMonitoring && !isArtifact && displayText.length > LONG_BODY_CHARS;- // Chat handoff prompt — seed the Executive with the FULL body PLUS- // the suggested_action so it has the entire card's worth of context- // (the "Reply to X: confirm Y..." instructions live in suggested_action- // and previously got dropped on Discuss → the model would have to ask- // the user to re-supply them).- //- // We also include a Discuss-mode primer telling the exec: stay- // conversational until the user explicitly approves, then execute +- // call ack_alert with the alert_id below. alert_id is needed so the- // exec can clear the card from the briefing once approval lands.- const handoffPrompt = (() => {- if (isArtifact) {- // Artifacts aren't approved/executed — they're read. Seed the chat- // with the full document + rationale so the Executive can discuss- // it, and let it clear the card via ack_alert when the user is done.- const rationale = proposal.suggested_action- ? `\n\nWhy you flagged it: ${proposal.suggested_action}`- : "";- return (- `Let's discuss this artifact you flagged for my review:\n\n` +- `# ${proposal.headline}\n\n${proposal.body || ""}${rationale}\n\n` +- `[Discuss mode — alert_id=${proposal.alert_id}, artifact id ` +- `alert:${proposal.alert_id}; to revise it, publish a new version with ` +- `draft_artifact(supersedes="alert:${proposal.alert_id}")] This is a document ` +- `for review, not an action to approve. Answer my questions about it ` +- `conversationally. When I say I'm done ("got it", "reviewed", "thanks"), ` +- `call ack_alert(alert_id=${proposal.alert_id}, status="ack") to clear ` +- `it from my queue. Take no other action.`- );- }- if (isMonitoring) {- // Monitoring signals are passive — there's nothing to approve, so the- // Discuss handoff asks the Executive to interpret the signal rather than- // framing it as an approvable proposal. Dismiss is still available via- // the card button (which acks "dismissed").- return buildMonitoringSeed(proposal);- }- if (isDecision) {- // Gated calendar booking. Approval/rejection happens via the card's- // Approve/Dismiss buttons (which call the /decisions endpoints and book- // or cancel the event server-side) — NOT via chat. So the Discuss- // handoff is read-only: help the user decide, but take no action and do- // not ack/approve from chat.- const body = proposal.body || proposal.headline;- return (- `Let's talk through this meeting I've proposed:\n\n${body}\n\n` +- `[Discuss mode] This booking is awaiting your approval on the ` +- `briefing. Help me decide whether the time, attendees, and purpose ` +- `make sense. Do NOT book, cancel, or ack anything from chat — I'll ` +- `approve or dismiss it from the card itself.`- );- }- const text = proposal.body || proposal.headline;- const suggested = proposal.suggested_action- ? `\n\nIf I approve, you will:\n${proposal.suggested_action}`- : "";- const primer = (- `\n\n[Discuss mode — alert_id=${proposal.alert_id}] ` +- `This proposal is NOT YET approved. Answer my questions conversationally. ` +- `When I explicitly approve ("ok", "approve", "go ahead", "do it"), switch to ` +- `execute mode: actually attempt the work (use web_search and your other tools — ` +- `don't just promise), reply inline with the deliverable, schedule a fresh ` +- `follow-up via schedule_followup if it's time-bound, and call ` +- `ack_alert(alert_id=${proposal.alert_id}, status="ack"). ` +- `If I dismiss it ("never mind", "drop it"), call ` +- `ack_alert(alert_id=${proposal.alert_id}, status="dismissed") and stop. ` +- `Until explicit approval/dismissal, take no action and do not ack.`- );- return `Tell me about this proposal:\n\n${text}${suggested}${primer}`;- })();- const handoffMemory = briefingMemoryLine(- isArtifact- ? MEMORY_ACTIONS.artifact- : isMonitoring- ? MEMORY_ACTIONS.monitoring- : isDecision- ? MEMORY_ACTIONS.meeting- : MEMORY_ACTIONS.proposal,- proposal.headline,- );- // Suggested-action block: visually promoted so the user reads it as a- // commitment ("if I approve, the exec will do THIS") rather than a- // footnote. Renders only when suggested_action is non-empty — and never- // for monitoring items, where there's nothing to approve (the body is- // reframed as a rationale in the content area instead).- const suggestedActionBlock = (!isMonitoring && proposal.suggested_action) ? (- <div className="mb-2 rounded-lg border border-indigo-500/30 bg-indigo-500/5 px-3 py-2">- <div className="text-[10px] uppercase tracking-wide text-indigo-300 mb-1">- {isArtifact ? "Why this is worth your time:" : "If you approve:"}- </div>- <p className="text-xs text-fg leading-snug whitespace-pre-wrap break-words">- {proposal.suggested_action}- </p>- </div>- ) : null;- // Note explaining why an external/watchlist signal (large stock move) was- // pulled into "Needs you" instead of Monitoring — set by the backend- // (briefing/ranking.py) only for the severity-promoted case, so it reads- // as deliberate rather than a routing bug.- const surfacedNote = proposal.surfaced_reason ? (- <p className="text-[10px] text-fg-muted leading-snug">- {proposal.surfaced_reason}- </p>- ) : null;- // The `artifact` tag is an internal UI discriminator (it drives the- // document layout + amber badge), not a user-meaningful topic — hide it- // from the tag pills so it doesn't double up with the "Artifact" badge.- const visibleTags = proposal.topic_tags.filter((t) => t !== "artifact");- const { reviewLine, lifecycleRow, reviewedFooter, moveButton } = buildProposalLifecycle({- proposal, assignee, onContinue, busy,- });- const isLikelyStale = (proposal.review_verdict ?? "") === "likely_stale";- const meta = (- <>- {reviewLine}- {lifecycleRow}- {suggestedActionBlock}- {surfacedNote}- {visibleTags.length > 0 && (- <div className="flex flex-wrap gap-1">- {visibleTags.map((t) => {- // `external:*` tags come from the external-monitoring layer- // — render in sky so the principal spots externally-sourced- // proposals at a glance. Sky deliberately differs from the- // amber elsewhere in the briefing (department at-risk,- // awaiting-person chips) — those mean "action stalled on a- // human"; this means "outside-world provenance".- const isExternal = t.startsWith("external:");- const cls = isExternal- ? "inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium bg-sky-500/20 text-sky-300 border-sky-500/30"- : "inline-block px-1.5 py-0.5 rounded border text-[10px] text-fg-muted border-line";- return (- <span key={t} className={cls}>- {t}- </span>- );- })}- </div>- )}- {reviewedFooter}- </>- );- // Card splits into a content area and an action row living as siblings- // inside a wrapper div so the explicit buttons don't nest inside the- // outer click target (HTML disallows interactive-inside-interactive).- //- // Three render variants:- // 1. `editing === true`: body becomes a textarea; action row is- // Cancel / Send approval only.- // 2. `editing === false` + `onContinue`: body is a click target that- // seeds chat (Discuss); action row carries the explicit buttons.- // 3. `editing === false` + no onContinue (standalone /today): body is- // static text; the explicit Discuss button is hidden.- const showActions = Boolean(onApprove || onDismiss || onApproveWithEdits);- // Left indigo accent for the "Start here" row (replaces the old ring on the- // wrapper); applied to the flat row container in every render variant.- const rowAccent = emphasized ? " border-l-2 border-indigo-500 pl-3" : "";- if (editing) {- return (- <div className={`group py-3 hover:bg-surface-overlay/30 transition-colors${rowAccent}`}>- <div className="flex items-start justify-between gap-2 mb-2">- <span className="text-[10px] uppercase tracking-wide text-fg-subtle">Editing proposal — send verbatim</span>- {assignee && (- <span className="flex-shrink-0 text-xs text-indigo-300">- → {assignee.full_name}- </span>- )}- </div>- {/* Show what the exec will do on approval so the user sees what- they're authorizing while editing the message body. */}- {suggestedActionBlock}- <textarea- value={editedBody}- onChange={(e) => setEditedBody(e.target.value)}- rows={6}- disabled={busy}- className="w-full text-sm text-fg bg-surface border border-line rounded-lg p-3 font-normal leading-snug whitespace-pre-wrap focus:outline-none focus:ring-1 focus:ring-indigo-500/40 disabled:opacity-50"- autoFocus- />- <div className="mt-2 flex justify-end gap-2">- <button- type="button"- onClick={cancelEditing}- disabled={busy}- className="text-xs text-fg-muted hover:text-fg px-2 py-1 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"- >- Cancel- </button>- <button- type="button"- onClick={submitEdit}- disabled={busy || !editedBody.trim()}- className="text-xs font-medium text-emerald-300 hover:text-emerald-200 px-2 py-1 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"- >- ✓ Send approval- </button>- </div>- </div>- );- }- const assigneeBadge = assignee && (- onContinue ? (- <span className="flex-shrink-0 text-xs text-indigo-300">- → {assignee.full_name}- </span>- ) : (- <Link- href={`/people/${assignee.id}`}- className="flex-shrink-0 text-xs text-indigo-300 hover:underline"- onClick={(e) => e.stopPropagation()}- >- → {assignee.full_name}- </Link>- )- );- const content = isArtifact ? (- <>- <div className="flex items-start justify-between gap-2 mb-1">- <div className="flex items-center gap-2 min-w-0">- <span className="flex-shrink-0 text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded border bg-amber-500/15 text-amber-300 border-amber-500/30">- {artifactBadge(proposal.artifact_format)}- </span>- <div className="text-sm font-medium text-fg break-words">{proposal.headline}</div>- </div>- {assigneeBadge}- </div>- {meta}- {/* Full authored document, rendered as Markdown in a bounded,- scrollable region so a long brief can't blow out the card. */}- <div className="mt-2 max-h-72 overflow-y-auto rounded-lg border border-line bg-surface/40 px-3 py-2 prose prose-invert prose-sm max-w-none text-xs text-fg-muted leading-relaxed [&_*]:break-words">- <ReactMarkdown remarkPlugins={[remarkGfm]}>- {proposal.body || proposal.headline}- </ReactMarkdown>- </div>- </>- ) : (- <>- <div className="flex items-start justify-between gap-2 mb-2">- <div className="min-w-0">- {isMonitoring ? (- <>- {/* Terse description first (headline), then the rationale the- triage body carries — only when it adds something beyond the- headline, so we don't render the same text twice. */}- <div className="text-sm font-medium text-fg whitespace-pre-wrap break-words">- {proposal.headline}- </div>- {proposal.body && proposal.body !== proposal.headline && (- <>- <div className="mt-2 text-[10px] uppercase tracking-wide text-sky-300 mb-1">- Why this is on your radar- </div>- <div className="text-xs text-fg-muted whitespace-pre-wrap break-words">- {proposal.body}- </div>- </>- )}- </>- ) : (- <div className={`text-sm font-medium text-fg whitespace-pre-wrap break-words${isLongBody && !bodyOpen ? " line-clamp-3" : ""}`} title={isLongBody && !bodyOpen ? displayText : undefined}>{displayText}</div>- )}- </div>- {assigneeBadge}- </div>- {meta}- </>- );- const contentArea = onContinue ? (- <button- type="button"- onClick={() => onContinue(handoffPrompt, handoffMemory)}- className="block w-full text-left cursor-pointer transition-colors"- >- {content}- </button>- ) : (- <div>{content}</div>- );- return (- <div id={`alert-${proposal.alert_id}`} className={`group py-3 hover:bg-surface-overlay/30 transition-colors${rowAccent}`}>- {contentArea}- {/* Artifact links sit outside the Discuss click target (a <button>),- which can't legally contain links. */}- {isArtifact && (- <div className="pb-1 flex flex-wrap gap-3 text-xs">- <Link- href={`/artifacts/${encodeURIComponent(`alert:${proposal.alert_id}`)}`}- className="text-indigo-400 hover:underline"- >- Open document →- </Link>- {proposal.artifact_format === "link" && proposal.artifact_url && (- <a- href={proposal.artifact_url}- target="_blank"- rel="noopener noreferrer nofollow"- className="text-indigo-400 hover:underline"- >- Open in app ({hostOf(proposal.artifact_url)}) ↗- </a>- )}- </div>- )}- {/* Body expander — a sibling of the content area (never nested inside the- Discuss click target, which HTML disallows) so a clamped long body can- still be read in full without leaving the briefing. */}- {isLongBody && (- <button- type="button"- onClick={() => setBodyOpen((v) => !v)}- aria-expanded={bodyOpen}- className="pb-2 -mt-1 text-[11px] text-fg-muted hover:text-fg transition-colors cursor-pointer focus:outline-none focus:ring-1 focus:ring-indigo-500/40 rounded"- >- {bodyOpen ? "Show less" : "Show more"}- </button>- )}- {showActions && (- <div className="mt-2 flex items-center justify-between gap-2">- {/* Discuss on the left — same handoff the body tap fires, but- explicit so the affordance is discoverable. Hidden on the- standalone /today route (no onContinue). */}- <div className="flex items-center gap-2">- {moveButton}- {onContinue && (- <button- type="button"- onClick={() => onContinue(handoffPrompt, handoffMemory)}- disabled={busy}- className="text-xs text-fg-muted hover:text-indigo-300 px-2 py-1 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"- >- 💬 Discuss- </button>- )}- </div>- {/* Right-side actions. Artifacts are documents you review, not- proposals you approve/execute — so they get a single- "Mark reviewed" control (clears the card, no follow-on work)- instead of the Dismiss / Edit / Approve trio. */}- <div className="flex items-center gap-2">- {isArtifact ? (- onDismiss && (- <button- type="button"- onClick={() => onDismiss(proposal)}- disabled={busy}- className="text-xs font-medium text-emerald-300 hover:text-emerald-200 px-2 py-1 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"- >- ✓ Mark reviewed- </button>- )- ) : (- <>- {onDismiss && (- <button- type="button"- onClick={() => onDismiss(proposal)}- disabled={busy}- className={`text-xs px-2 py-1 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${- isLikelyStale- ? "font-medium text-amber-300 hover:text-amber-200 border border-amber-500/30"- : "text-fg-muted hover:text-rose-300"- }`}- >- ✕ Dismiss- </button>- )}- {/* Monitoring items are passive signals with no proposed- action to execute — only Discuss + Dismiss apply, so the- approve controls are hidden for them. */}- {!isMonitoring && !isDecision && onApproveWithEdits && (- <button- type="button"- onClick={startEditing}- disabled={busy}- className="text-xs text-fg-muted hover:text-emerald-300 px-2 py-1 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"- >- ✎ Edit & approve- </button>- )}- {!isMonitoring && onApprove && (- <button- type="button"- onClick={() => onApprove(proposal)}- disabled={busy}- className="text-xs font-medium text-emerald-300 hover:text-emerald-200 px-2 py-1 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"- >- ✓ Approve- </button>- )}- </>- )}- </div>- </div>- )}- </div>- );-}--// In flight — what the Executive is about to do (scheduled follow-ups &-// nudges). Ambient/awareness content in the right column, always visible (no-// approval needed). Takes its anchor `id` as a prop (set by the caller).-function InFlightPanel({ inFlight, id }: { inFlight: InFlightItem[]; id?: string }) {- if (inFlight.length === 0) return null;- return (- <section id={id} className="rounded-xl border border-line bg-surface-elevated p-4">- <div className="flex items-center gap-1.5 mb-1">- <SectionHeading title="In flight" count={inFlight.length} icon="bolt" />- <InfoTip align="left">- What the Executive is about to do (scheduled follow-ups &- nudges). Nothing here needs your approval — it's a heads-up.- </InfoTip>- </div>- <div className="max-h-[32rem] overflow-y-auto pr-1 divide-y divide-line">- {inFlight.map((f) => (- <div- key={`if-${f.action_id}`}- className={`group py-3 pl-2 border-l-2 hover:bg-surface-overlay/30 transition-colors ${f.overdue ? "border-amber-500/40" : "border-transparent"}`}- >- <div className="text-xs text-fg break-words" title={f.intent}>{f.intent}</div>- <div className="mt-0.5 text-[11px] text-fg-muted">- {f.target ? <span>→ {f.target}</span> : null}- {f.department ? <span> · {f.department}</span> : null}- <span>- {" · "}- {f.overdue ? (- <span className="text-amber-400">overdue</span>- ) : (- formatFuture(f.run_at)- )}- </span>- </div>- </div>- ))}- </div>- </section>- );-}--// Solo only: the projects (initiatives) the Executive is tracking as active —-// the solo stand-in for the Departments card. "Done" marks one completed-// (PATCH), which is what takes it out of the Executive's active context;-// "Drop" deletes it after a confirm, since there is no "dropped" status the-// rest of the system treats as closed.-function ProjectsPanel({ id }: { id?: string }) {- const [projects, setProjects] = useState<Initiative[] | null>(null);- const [busyId, setBusyId] = useState<number | null>(null);- const [error, setError] = useState<string | null>(null);-- useEffect(() => {- let cancelled = false;- listInitiatives()- .then((all) => {- if (!cancelled) setProjects(all.filter((i) => i.status === "active"));- })- .catch(() => {- if (!cancelled) setError("Couldn't load your projects.");- });- return () => {- cancelled = true;- };- }, []);-- const close = async (project: Initiative, how: "done" | "drop") => {- if (- how === "drop" &&- !window.confirm(- `Drop "${project.title}"? The Executive stops tracking it, and it is removed from Pulse.`,- )- ) {- return;- }- setBusyId(project.id);- setError(null);- try {- if (how === "done") await updateInitiative(project.id, { status: "completed" });- else await deleteInitiative(project.id);- setProjects((prev) => (prev ?? []).filter((p) => p.id !== project.id));- } catch {- setError(how === "done" ? "Couldn't mark it done — try again." : "Couldn't drop it — try again.");- } finally {- setBusyId(null);- }- };-- return (- <section id={id} className="rounded-xl border border-line bg-surface-elevated p-4">- <div className="flex items-start justify-between gap-2">- <div className="flex items-center gap-1.5">- <SectionHeading title="Your projects" count={projects?.length} icon="flag" />- <InfoTip align="left">- The projects you're running that the Executive is keeping track of. Mention a- new one in chat and it appears here.- </InfoTip>- </div>- <Link href="/goals" className="flex-shrink-0 text-xs text-indigo-400 hover:text-indigo-300">- Goals →- </Link>- </div>- {error && <p className="text-xs text-rose-300 mb-2">{error}</p>}- {projects === null ? (- !error && <p className="text-sm text-fg-muted py-2">Loading…</p>- ) : projects.length === 0 ? (- <p className="text-sm text-fg-muted py-2">- No active projects. Tell the Executive about one you're running and it will- keep track of it here.- </p>- ) : (- <div className="max-h-[32rem] overflow-y-auto pr-1 divide-y divide-line">- {projects.map((p) => (- <div key={p.id} className="py-3 flex items-start gap-3">- <div className="min-w-0 flex-1">- <div className="text-sm text-fg font-medium break-words">{p.title}</div>- {p.summary && (- <div className="text-xs text-fg-muted mt-0.5 line-clamp-2" title={p.summary}>- {p.summary}- </div>- )}- </div>- <div className="flex items-center gap-1.5 flex-shrink-0">- <button- type="button"- onClick={() => void close(p, "done")}- disabled={busyId !== null}- className="px-2 py-1 text-xs rounded-lg bg-emerald-500/15 text-emerald-300 hover:bg-emerald-500/25 transition-colors cursor-pointer disabled:opacity-50"- >- ✓ Done- </button>- <button- type="button"- onClick={() => void close(p, "drop")}- disabled={busyId !== null}- className="px-2 py-1 text-xs rounded-lg text-fg-muted hover:text-rose-300 hover:bg-rose-500/10 transition-colors cursor-pointer disabled:opacity-50"- >- Drop- </button>- </div>- </div>- ))}- </div>- )}- </section>- );-}--// Solo only: what you own that is due within a week or overdue — what you-// promised by a date (the Executive starts tracking one when you say "I'll-// send it by Friday") and what others asked of you. Read from your open loops-// (GET /people/{id}/open-loops); "Done" closes one (POST /open-loops/{id}/close),-// which also stops the Executive reminding you about it.-function DueSoonPanel({ principalId, id }: { principalId: number; id?: string }) {- const [loops, setLoops] = useState<OpenLoop[] | null>(null);- const [busyId, setBusyId] = useState<number | null>(null);- const [error, setError] = useState<string | null>(null);-- useEffect(() => {- let cancelled = false;- getPersonOpenLoops(principalId)- .then((all) => {- if (!cancelled) setLoops(all);- })- .catch(() => {- if (!cancelled) setError("Couldn't load what's due.");- });- return () => {- cancelled = true;- };- }, [principalId]);-- const markDone = async (loopId: number) => {- setBusyId(loopId);- setError(null);- try {- await closeOpenLoop(loopId, "done");- setLoops((prev) => (prev ?? []).filter((l) => l.loop_id !== loopId));- } catch {- setError("Couldn't mark it done — try again.");- } finally {- setBusyId(null);- }- };-- const view = loops === null ? null : dueSoon(loops);- return (- <section id={id} className="rounded-xl border border-line bg-surface-elevated p-4">- <div className="flex items-start justify-between gap-2">- <div className="flex items-center gap-1.5">- <SectionHeading title="Due soon" count={view?.items.length} icon="bell" />- <InfoTip align="left">- What you've promised by a date, and what others have asked of you, due in- the next week. Tell the Executive “I'll send it by Friday” and it- shows up here; the Executive reminds you when it's due.- </InfoTip>- </div>- <Link- href={`/people/${principalId}`}- className="flex-shrink-0 text-xs text-indigo-400 hover:text-indigo-300"- >- All open items →- </Link>- </div>- {error && <p className="text-xs text-rose-300 mb-2">{error}</p>}- {view === null ? (- !error && <p className="text-sm text-fg-muted py-2">Loading…</p>- ) : view.items.length === 0 ? (- <p className="text-sm text-fg-muted py-2">- Nothing due this week.- {view.later > 0 && ` ${view.later} due later.`}- </p>- ) : (- <>- <div className="max-h-[32rem] overflow-y-auto pr-1 divide-y divide-line">- {view.items.map((item) => (- <div key={item.loop.loop_id} className="py-3 flex items-start gap-3">- <div className="min-w-0 flex-1">- <div className="text-sm text-fg break-words">{item.text}</div>- <div- className={`text-xs mt-0.5 ${item.overdue ? "text-amber-300" : "text-fg-muted"}`}- >- {item.dueLabel}- </div>- </div>- <button- type="button"- onClick={() => void markDone(item.loop.loop_id)}- disabled={busyId !== null}- className="flex-shrink-0 px-2 py-1 text-xs rounded-lg bg-emerald-500/15 text-emerald-300 hover:bg-emerald-500/25 transition-colors cursor-pointer disabled:opacity-50"- >- {busyId === item.loop.loop_id ? "Closing…" : "✓ Done"}- </button>- </div>- ))}- </div>- {view.later > 0 && (- <p className="text-xs text-fg-muted pt-2">{view.later} more due later.</p>- )}- </>- )}- </section>- );-}--// A numbered row's number, shared by the two solo focus cards below.-function RankBadge({ n }: { n: number }) {- return (- <span- aria-hidden="true"- className="mt-0.5 flex-shrink-0 w-5 h-5 rounded-full bg-indigo-500/15 text-indigo-300 text-[11px] font-semibold tabular-nums flex items-center justify-center"- >- {n}- </span>- );-}--// Solo only: the three things to focus on today — the same pick, order and-// free slots as the morning brief (GET /today/top-three), so a user no-// channel reaches still sees them. It loads on its own after the Briefing,-// since it may wait on the calendar (up to 4 s), and hides when there is-// nothing to pick or the viewer isn't the owner (the API returns null).-// `ownerName` turns a commitment's stored text into "you" wording, as the-// Due soon card does.-function TopThreePanel({ ownerName, id }: { ownerName: string; id?: string }) {- const [top, setTop] = useState<TopThreeToday | null>(null);-- useEffect(() => {- const controller = new AbortController();- getTopThree(controller.signal)- .then(setTop)- .catch(() => { /* no card is better than a broken one */ });- return () => controller.abort();- }, []);-- if (!top || top.items.length === 0) return null;- return (- <section id={id} className="rounded-xl border border-line bg-surface-elevated p-4">- <div className="flex items-center gap-1.5">- <SectionHeading title="Top three today" icon="bolt" />- <InfoTip align="left">- The three things to focus on today, picked from what's overdue or due, goals- that are slipping and your active projects — the same three your morning brief- opens with. When the Executive can read your calendar, each gets a free slot in- today's working hours.- </InfoTip>- </div>- <ol className="divide-y divide-line">- {top.items.map((item, i) => {- const text =- item.kind === "commitment" && ownerName- ? loopText({ description: item.text, owner_name: ownerName })- : item.text;- const slot = topThreeSlot(item);- return (- <li key={item.key} className="py-3 flex items-start gap-3">- <RankBadge n={i + 1} />- <div className="min-w-0 flex-1">- <div className="text-sm text-fg break-words">{text}</div>- <div className="text-xs text-fg-muted mt-0.5">{topThreeWhy(item)}</div>- </div>- {slot && (- <span- className={`flex-shrink-0 mt-0.5 text-xs tabular-nums ${- item.slot ? "text-indigo-300" : "text-fg-muted"- }`}- >- {slot}- </span>- )}- </li>- );- })}- </ol>- </section>- );-}--// Solo only: the latest weekly review (GET /today/weekly-review) — when it-// ran and next week's top three, with a link to the whole review on its run-// page. The scheduler only sends it by chat or email, so without either this-// is where a solo user finds it. Loads on its own; hidden until a review has-// run, and for anyone but the owner.-function WeeklyReviewPanel({ id }: { id?: string }) {- const [review, setReview] = useState<WeeklyReviewSummary | null>(null);-- useEffect(() => {- const controller = new AbortController();- getWeeklyReview(controller.signal)- .then(setReview)- .catch(() => { /* no card is better than a broken one */ });- return () => controller.abort();- }, []);-- if (!review) return null;- const excerpt = reviewExcerpt(review);- const meta = [review.period, reviewRanLabel(review.completed_at)].filter(Boolean).join(" · ");- return (- <section id={id} className="rounded-xl border border-line bg-surface-elevated p-4">- <div className="flex items-start justify-between gap-2">- <div className="flex items-center gap-1.5">- <SectionHeading title="This week's review" icon="clipboard" />- <InfoTip align="left">- Once a week the Executive looks back on your week — your goals by area, what's- due, projects that went quiet and the decisions you made — and picks next- week's top three. It's also sent to you when a chat app or email is- connected.- </InfoTip>- </div>- <Link- href={`/jobs/runs/${encodeURIComponent(review.run_id)}`}- className="flex-shrink-0 text-xs text-indigo-400 hover:text-indigo-300"- >- Read the review →- </Link>- </div>- {meta && <p className="-mt-2 mb-2 text-xs text-fg-muted">{meta}</p>}- {excerpt.heading && (- <div className="mb-1 text-[10px] font-semibold uppercase tracking-wide text-fg-muted">- {excerpt.heading}- </div>- )}- {excerpt.numbered ? (- <ol className="divide-y divide-line">- {excerpt.lines.map((line, i) => (- <li key={i} className="py-2 flex items-start gap-3">- <RankBadge n={i + 1} />- <span className="min-w-0 flex-1 text-sm text-fg break-words">{line}</span>- </li>- ))}- </ol>- ) : (- excerpt.lines.map((line, i) => (- <p key={i} className="py-0.5 text-sm text-fg-muted break-words">- {line}- </p>- ))- )}- </section>- );-}--// Multi-client practice mode only: rollup cards for PARKED client slots so-// the operator sees the whole practice from the active client's brief. The-// backend sends [] for single-company installs (0-1 slots), so this renders-// nothing in the default experience.-function PracticeClientsPanel({- clients,- id,-}: {- clients: ClientCockpitCard[];- id?: string;-}) {- if (clients.length === 0) return null;- return (- <section id={id} className="rounded-xl border border-line bg-surface-elevated p-4">- <div className="flex items-center justify-between gap-2 mb-1">- <div className="flex items-center gap-1.5">- <SectionHeading title="Across your clients" count={clients.length} icon="building" />- <InfoTip align="left">- Your parked client companies. Counts reflect each client's last- save point; switch to a client on the Clients page to work in it.- </InfoTip>- </div>- <Link- href="/clients"- className="flex-shrink-0 text-xs text-indigo-400 hover:text-indigo-300"- >- Manage clients- </Link>- </div>- <div className="max-h-[32rem] overflow-y-auto pr-1 divide-y divide-line">- {clients.map((c) => (- <div key={`practice-${c.slug}`} className="py-3">- <div className="flex items-center justify-between gap-2">- <div className="text-xs font-medium text-fg truncate">- {c.display_name}- {c.role ? <span className="text-fg-muted font-normal"> · {c.role}</span> : null}- </div>- {(() => {- const badge = renewalBadge(c.days_to_renewal);- return badge ? (- <span className={`text-[10px] px-1.5 py-0.5 rounded-full border flex-shrink-0 ${- badge.urgent- ? "border-red-500/40 bg-red-500/10 text-red-400"- : "border-amber-500/40 bg-amber-500/10 text-amber-400"- }`}>- {badge.label}- </span>- ) : null;- })()}- </div>- <div className="mt-0.5 text-[11px] text-fg-muted">- {clientCountsSummary(c)}- </div>- </div>- ))}- </div>- </section>- );-}--// A single passive monitoring signal as a compact rail row: headline +-// optional body excerpt, click-to-discuss, and a small dismiss affordance.-// Full ProposalCard is too wide for the rail, so this is the slimmed-down-// presentation; the Discuss handoff reuses buildMonitoringSeed so it behaves-// exactly like the card did.-function MonitoringRow({- proposal,- onContinue,- onDismiss,-}: {- proposal: ProposalItem;- onContinue?: ContinueHandler;- onDismiss?: (p: ProposalItem) => void;-}) {- const seed = buildMonitoringSeed(proposal);- const inner = (- <>- <div className="text-xs font-medium text-fg group-hover:text-indigo-300 transition-colors line-clamp-2" title={proposal.headline}>- {proposal.headline}- </div>- {proposal.body && proposal.body !== proposal.headline && (- <div className="mt-0.5 text-[11px] leading-snug text-fg-muted line-clamp-2">- {proposal.body}- </div>- )}- </>- );- return (- <div id={`alert-${proposal.alert_id}`} className="relative group py-3 hover:bg-surface-overlay/30 transition-colors">- {onContinue ? (- <button- type="button"- onClick={() => onContinue(seed, briefingMemoryLine(MEMORY_ACTIONS.monitoring, proposal.headline))}- className="block w-full text-left pr-8 cursor-pointer focus:outline-none focus:ring-1 focus:ring-indigo-500/40"- >- {inner}- </button>- ) : (- <Link href="/watchlist" className="block pr-8">- {inner}- </Link>- )}- {onDismiss && (- <button- type="button"- aria-label="Dismiss signal"- onClick={() => onDismiss(proposal)}- className="absolute top-1.5 right-1.5 flex h-6 w-6 items-center justify-center rounded text-fg-subtle hover:text-fg hover:bg-surface-overlay cursor-pointer transition-colors opacity-0 group-hover:opacity-100 focus-within:opacity-100 focus:opacity-100 focus:outline-none focus:ring-1 focus:ring-indigo-500/40"- >- <span aria-hidden="true" className="text-sm leading-none">×</span>- </button>- )}- </div>- );-}--// Monitoring — passive signals (watchlist tickers, vendor status, external-// news) the Executive is tracking. An ambient right-column card; the full-// list scrolls inside the card. Takes its anchor `id` as a prop.-function MonitoringPanel({- proposals,- onContinue,- onDismiss,- onBulkDismiss,- id,-}: {- proposals: ProposalItem[];- onContinue?: ContinueHandler;- onDismiss?: (p: ProposalItem) => void;- onBulkDismiss?: (ids: number[]) => void;- id?: string;-}) {- const staleIds = olderThan(proposals, MONITORING_DISMISS_OLDER_THAN_DAYS);- if (proposals.length === 0) return null;- return (- <section id={id} className="rounded-xl border border-line bg-surface-elevated p-4">- <div className="flex items-center gap-1.5 mb-1">- <SectionHeading title="Monitoring" count={proposals.length} icon="eye" />- <InfoTip align="left">- Passive signals (watchlist tickers, vendor status, external news)- the Executive is tracking. Nothing here needs a decision — tap one- to talk it through.- </InfoTip>- </div>- <div className="max-h-[32rem] overflow-y-auto pr-1 divide-y divide-line">- {proposals.map((p) => (- <MonitoringRow key={p.alert_id} proposal={p} onContinue={onContinue} onDismiss={onDismiss} />- ))}- </div>- {onBulkDismiss && staleIds.length > 0 && (- <button- type="button"- onClick={() => onBulkDismiss(staleIds)}- className="mt-2 text-[11px] text-fg-muted hover:text-rose-300 transition-colors"- >- ✕ Dismiss {staleIds.length} older than {MONITORING_DISMISS_OLDER_THAN_DAYS} days- </button>- )}- </section>- );-}--// Handled rail — pure logic lives in @/lib/handled (tested by `npm test`);-// only rendering stays here.--// First-person sentence for one row. Falls back to the audit summary when the-// row predates the structured fields (no headline / target to compose from).-function handledSentence(h: HandledItem): React.ReactNode {- const headline = h.headline ?? "";- const target = h.target ?? "";- const H = <span className="text-fg">{headline}</span>;- const T = <span className="text-fg">{target}</span>;- const why = h.detail ? <span className="text-fg-subtle"> — {h.detail}</span> : null;- if (!headline) return h.summary;- switch (h.kind) {- case "closed":- return h.outcome === "dismissed" ? <>Dismissed {H} as stale{why}</> : <>Resolved {H}{why}</>;- case "routed":- if (!target) return h.summary;- return h.outcome === "proposed"- ? <>Proposed {H} to {T} <span className="text-fg-subtle">(awaiting their approval)</span></>- : <>Handed {H} to {T}</>;- case "nudged":- return target ? <>Chased {T} on {H}</> : h.summary;- case "escalated":- return target ? <>Raised {H} to {T}{why}</> : <>Raised {H}{why}</>;- case "drafted":- return target ? <>Drafted {T} from {H}</> : h.summary;- case "merged":- return target ? <>Folded {H} into {T}</> : h.summary;- case "suggested_workflow":- return target ? <>Suggested running {T} on {H}</> : h.summary;- case "watching":- return <>Started watching {H}{why}</>;- case "stopped_watching":- return <>Stopped watching {H}{why}</>;- default:- return h.summary;- }-}--// Jump to the alert's card; when it is folded behind "Show more" (no element-// yet), land on the queue section instead of clicking dead.-function scrollToAlertCard(alertId: number) {- const target = document.getElementById(`alert-${alertId}`) ?? document.getElementById(SECTION_IDS.needsYou);- target?.scrollIntoView({ behavior: "smooth", block: "center" });-}--function HandledTrailerLink({ href, label }: { href: string; label: string }) {- return (- <>- <span aria-hidden="true">·</span>- <Link href={href} className="hover:text-indigo-300 transition-colors">{label}</Link>- </>- );-}--function HandledRowView({- row,- reverted,- onReopen,-}: {- row: HandledRow;- reverted: boolean;- onReopen?: (rowKey: string, alertId: number) => void;-}) {- const h = row.item;- // Undo only while the close still stands and the server would accept a- // reopen (resolved / dismissed / expired / merged; "" = status unknown).- const canUndo =- Boolean(onReopen) && h.alert_id != null && isCloseKind(h) && !reverted && HANDLED_REOPENABLE.has(h.status ?? "");- // "open" means live in the queue right now — the only state with a card to- // jump to (an acked or snoozed alert has none).- const stillOpen = h.alert_id != null && h.status === "open" && !isCloseKind(h);- const proofHref = handledProofHref(h);- const alsoLine = handledAlsoLine(row);- return (- <div className="py-2 flex items-start justify-between gap-3">- <div className="min-w-0">- <p className={`text-xs leading-snug ${reverted ? "line-through text-fg-subtle" : "text-fg-muted"}`}>- {handledSentence(h)}- </p>- <p className="mt-0.5 text-[10px] text-fg-subtle flex flex-wrap items-center gap-x-1.5">- {alsoLine && <span>{alsoLine}</span>}- {alsoLine && <span aria-hidden="true">·</span>}- <span>{ageLabel(h.at)} ago</span>- {proofHref && <HandledTrailerLink href={proofHref} label={h.evidence_ref || "evidence"} />}- {h.kind === "drafted" && <HandledTrailerLink href="/artifacts" label="read the draft" />}- {(h.kind === "watching" || h.kind === "stopped_watching") && (- <HandledTrailerLink href="/watchlist" label="watchlist" />- )}- {reverted && (- <>- <span aria-hidden="true">·</span>- <span className="text-sky-300">Reopened</span>- </>- )}- </p>- </div>- {canUndo && (- <button- type="button"- onClick={() => onReopen?.(handledKey(h), h.alert_id as number)}- className="flex-shrink-0 text-[11px] text-fg-muted hover:text-indigo-300 transition-colors"- >- ↶ Undo- </button>- )}- {stillOpen && (- <button- type="button"- onClick={() => scrollToAlertCard(h.alert_id as number)}- className="flex-shrink-0 text-[11px] text-fg-muted hover:text-indigo-300 transition-colors"- title="Jump to it in your queue"- >- still open ↓- </button>- )}- </div>- );-}--const HANDLED_DETAILS_ID = "sec-handled-details";--function HandledOvernightPanel({- items,- onReopen,- undone,-}: {- items: HandledItem[];- onReopen?: (rowKey: string, alertId: number) => void;- undone: Set<string>;-}) {- const [open, setOpen] = useState(false);- // The rail is rebuilt from the audit log on every fetch, so a close the- // principal already undid still has its row: `status === "open"` (server- // truth after a reload) or the in-session set marks it reverted.- const reverted = (h: HandledItem) => isCloseKind(h) && (h.status === "open" || undone.has(handledKey(h)));-- // Guard on the grouped rows, not the raw items: a merge folded into a- // listed survivor leaves no row of its own.- const rows = groupHandled(items);- if (rows.length === 0) return null;-- return (- <section id={SECTION_IDS.handled} className="rounded-xl border border-line bg-surface-elevated px-4 py-2.5">- <div className="flex items-start gap-1.5">- <p className="min-w-0 flex-1 text-sm text-fg">{handledHeadline(rows, reverted)}</p>- <InfoTip align="left">- Moves I completed on my own since your last delivered brief — routed,- chased, escalated, drafted, folded, or closed with cited evidence.- Rewrites of open alerts show on the card itself, not here. Undo puts a- closed item back in your queue.- </InfoTip>- <button- type="button"- onClick={() => setOpen((v) => !v)}- aria-expanded={open}- aria-controls={HANDLED_DETAILS_ID}- className="flex-shrink-0 mt-0.5 text-[11px] text-fg-muted hover:text-fg transition-colors"- >- {open ? "hide" : "details"} <span aria-hidden="true">{open ? "▾" : "▸"}</span>- </button>- </div>- {/* Always in the DOM so aria-controls resolves while collapsed. */}- <div id={HANDLED_DETAILS_ID} hidden={!open} className="mt-1.5 divide-y divide-line border-t border-line">- {open &&- rows.map((row) => (- <HandledRowView key={handledKey(row.item)} row={row} reverted={reverted(row.item)} onReopen={onReopen} />- ))}- </div>- </section>- );-}--export default function Briefing({ onContinue, showHeader = false, firstName }: BriefingProps) {+export default function Briefing({ onContinue, showHeader = false, firstName, banner }: BriefingProps) {// Solo (one person, just for themselves): no departments, roster or- // cross-team lanes — see the `solo` branches below. Team rendering is- // unchanged.+ // cross-team lanes — see the `solo` branches below.const { mode } = useWorkspace();const solo = mode === "solo";const [today, setToday] = useState<Today | null>(null);const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);- // The healthy ("on track") and inactive departments collapse into a single- // quiet toggle so the section has one disclosure pattern instead of three.- const [showAllDeptsOpen, setShowAllDeptsOpen] = useState(false);// Alerts the user has acted on this session. We optimistically drop- // them from the rendered "Needs you" / "Across the team" lists so- // the click feels instant; the canonical state will be picked up by- // the next /today fetch.+ // them from the rendered lists so the click feels instant; the canonical+ // state is picked up by the next /today fetch.const [actedAlertIds, setActedAlertIds] = useState<Set<number>>(new Set());- // "Needs you" shows NEEDS_YOU_VISIBLE cards after "Start here"; the rest- // sit behind one toggle so a long queue reads as a queue, not a wall.+ // "Needs you" shows NEEDS_YOU_VISIBLE cards; the rest sit behind one toggle.const [showAllNeedsYou, setShowAllNeedsYou] = useState(false);// "Re-check relevance" runs the Executive's review on demand.const [recheckBusy, setRecheckBusy] = useState(false);// Handled-rail rows undone this session (keyed per row, see handledKey).const [undoneRows, setUndoneRows] = useState<Set<string>>(new Set());+ // Which tile's side panel (or the brief) is open.+ const [openPanel, setOpenPanel] = useState<PanelKey | null>(null);+ const [askText, setAskText] = useState("");// Re-pull /today after a server-side mutation (e.g. a decision approve/reject)- // so derived data — the narrative header, per-person and department counts —+ // so derived data — the narrative, per-person and department counts —// re-syncs. The optimistic actedAlertIds set already hides the card; this// refreshes everything computed from it. Best-effort: a failed refresh leaves// the stale-but-still-usable view rather than erroring the briefing.@@ -1985,13 +222,9 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:// Dismiss is a record-and-forget decision: the card disappears// immediately, the backend marks the alert ``dismissed`` (so the- // Executive sees it on the next /today / alerts read and stops- // re-surfacing the same thread), and the user stays on the briefing.- // Unlike Approve, there is no follow-on work for the LLM to carry- // out, so we deliberately do NOT seed a chat turn — that would- // navigate away from the briefing for no benefit. On failure we- // revert the optimistic removal so the user can see the card came- // back and retry.+ // Executive stops re-surfacing the same thread), and the user stays on+ // the briefing — no chat turn is seeded. On failure we revert the+ // optimistic removal so the user can see the card came back and retry.const handleDismiss = useCallback(async (proposal: ProposalItem) => {const prev = actedAlertIds;setActedAlertIds(new Set(prev).add(proposal.alert_id));@@ -2016,9 +249,9 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:}}, [actedAlertIds, refreshToday]);- // Bulk dismiss: the footer under a lane sends explicit ids (the cards the- // caller can see), never a server-side age sweep. Same optimistic-removal- // + rollback pattern as the single-card handlers.+ // Bulk dismiss: sends explicit ids (the cards the caller can see), never a+ // server-side age sweep. Same optimistic-removal + rollback pattern as the+ // single-card handlers.const handleBulkDismiss = useCallback(async (ids: number[]) => {if (ids.length === 0) return;const prev = actedAlertIds;@@ -2049,9 +282,9 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:}}, [refreshToday]);- // Undo an autonomous close from the handled rail (HandledOvernightPanel). The rail is- // rebuilt from the audit log on every fetch (the "closed" row persists after- // a reopen), so a 409 "already open" after a reload counts as done.+ // Undo an autonomous close from the Handled panel. The rail is rebuilt+ // from the audit log on every fetch (the "closed" row persists after a+ // reopen), so a 409 "already open" after a reload counts as done.const handleReopen = useCallback(async (rowKey: string, alertId: number) => {try {await reopenAlert(alertId);@@ -2099,57 +332,64 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:return () => { cancelled = true; };}, []);+ // Replies the Executive drafted in the owner's own mailbox (Act as me):+ // cards in Needs you. Empty for everyone else.+ const replies = useReplyCards();+ // Solo's own sections load on their own, so their tiles can count them.+ const principalId = solo ? principalIdOf(today?.people ?? []) : null;+ const projects = useActiveProjects(solo);+ const openLoops = useOpenLoops(principalId);+ const weeklyReview = useWeeklyReview(solo);++ // Hand an Ask-box question to chat as the user's own words.+ const submitAsk = () => {+ const text = askText.trim();+ if (!text || !onContinue) return;+ onContinue(text);+ };++ // Jump from the Handled panel to the alert's card; when it is folded+ // behind "Show more" open the queue first, and land on the queue when the+ // card isn't on the page at all.+ const jumpToAlert = (alertId: number) => {+ setOpenPanel(null);+ setShowAllNeedsYou(true);+ setTimeout(() => {+ const target = document.getElementById(`alert-${alertId}`) ?? document.getElementById(NEEDS_YOU_ID);+ target?.scrollIntoView({ behavior: "smooth", block: "center" });+ }, 120);+ };+const dateLabel = new Date().toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" });- const activeDepts = today?.departments.filter(- (d) => d.goal_count > 0 || d.awaiting_count > 0- ) ?? [];- const inactiveDepts = today?.departments.filter(- (d) => d.goal_count === 0 && d.awaiting_count === 0- ) ?? [];- // Within active departments, only the ones with a problem (at risk /- // off track / awaiting) earn a card at rest. Healthy departments fold- // into a quiet "N on track" toggle so the briefing isn't a wall of- // green "on track" cards.+ const departments = today?.departments ?? [];+ const activeDepts = departments.filter((d) => d.goal_count > 0 || d.awaiting_count > 0);+ // Only the departments with a problem (at risk / off track / awaiting)+ // count as needing attention; healthy ones fold into a quiet toggle in+ // the panel.const attentionDepts = activeDepts.filter(- (d) => d.at_risk_count > 0 || d.off_track_count > 0 || d.awaiting_count > 0+ (d) => d.at_risk_count > 0 || d.off_track_count > 0 || d.awaiting_count > 0,);- const onTrackDepts = activeDepts.filter(- (d) => d.at_risk_count === 0 && d.off_track_count === 0 && d.awaiting_count === 0- );- // Healthy + inactive departments fold into one quiet toggle. Summary text- // reflects both buckets so the single control is self-describing.- const quietDeptCount = onTrackDepts.length + inactiveDepts.length;- const quietDeptSummary = [- onTrackDepts.length > 0 ? `${onTrackDepts.length} on track` : null,- inactiveDepts.length > 0 ? `${inactiveDepts.length} inactive` : null,- ]- .filter(Boolean)- .join(" · ");const isQuiet =today !== null &&today.proposals.length === 0 &&+ replies.cards.length === 0 &&activeDepts.every((d) => d.at_risk_count === 0 && d.off_track_count === 0 && d.awaiting_count === 0) &&today.people.every((p) => p.awaiting_count === 0);- const showPeopleSidebar = (today?.people.length ?? 0) > 1;+ const showPeople = !solo && (today?.people.length ?? 0) > 1;- // Bucket proposals once (previously an inline IIFE in the JSX) so the- // status strip and the section lists work off the same split. "Needs- // you" = action proposals routed to the caller, plus unrouted catch-all- // items when the caller is the principal. When the caller can't be- // resolved (caller_person_id null — e.g. a direct curl), fall back to- // the legacy single bucket so the queue still renders. Optimistically-- // acted alerts are dropped first so counts reflect the click.+ // Bucket proposals once so the summary line, the queue and the tiles work+ // off the same split. "Needs you" = action proposals routed to the caller,+ // plus unrouted catch-all items when the caller is the principal. When the+ // caller can't be resolved (caller_person_id null — e.g. a direct curl),+ // fall back to the legacy single bucket so the queue still renders.+ // Optimistically-acted alerts are dropped first so counts reflect the click.const callerId = today?.caller_person_id ?? null;const isPrincipalCaller =- callerId == null- ? false- : today?.people.find((p) => p.id === callerId)?.is_principal ?? false;- const liveProposals = (today?.proposals ?? []).filter(- (p) => !actedAlertIds.has(p.alert_id),- );+ callerId == null ? false : today?.people.find((p) => p.id === callerId)?.is_principal ?? false;+ const liveProposals = (today?.proposals ?? []).filter((p) => !actedAlertIds.has(p.alert_id));const monitoringProposals = liveProposals.filter((p) => p.category === "monitoring");const actionProposals = liveProposals.filter((p) => p.category !== "monitoring");// Solo: everything is yours, so nothing goes to an "Across the team" lane.@@ -2157,490 +397,494 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:callerId == null || solo? actionProposals: actionProposals.filter(- (p) =>- p.routed_to_person_id === callerId ||- (p.routed_to_person_id == null && isPrincipalCaller),+ (p) => p.routed_to_person_id === callerId || (p.routed_to_person_id == null && isPrincipalCaller),);const mineIds = new Set(mineProposals.map((p) => p.alert_id));const otherProposals =callerId == null || solo ? [] : actionProposals.filter((p) => !mineIds.has(p.alert_id));- // "Needs you" splits into the single highest-priority item (rendered as an- // elevated "Start here" card so there's one obvious first action) and the- // rest (the scrolling queue below). Backend sorts action proposals by score,- // so mineProposals[0] is the sharpest.- const startHereProposal = mineProposals[0] ?? null;- const restProposals = mineProposals.slice(1);// A roster request is answered on its card, never swept (the server skips// it too), so it is not counted here.const staleNeedsYouIds = olderThan(- mineProposals.filter((p) => !p.roster_request), NEEDS_YOU_DISMISS_OLDER_THAN_DAYS,+ mineProposals.filter((p) => !p.roster_request),+ NEEDS_YOU_DISMISS_OLDER_THAN_DAYS,);const handledOvernight = today?.handled_overnight ?? [];+ const handledRows = groupHandled(handledOvernight);+ const inFlight = today?.in_flight ?? [];+ const practiceClients = today?.practice_clients ?? [];- // Status-strip inputs, all from data already computed above.- const inFlightCount = today?.in_flight?.length ?? 0;- // Solo hides the Departments and People cards, so it drops the pills that- // would jump to them.+ // Summary-line inputs. Solo has no Departments or People tiles, so it says+ // how many goals need attention instead, linking to /goals.const deptAtRiskCount = solo? 0: attentionDepts.filter((d) => d.at_risk_count > 0 || d.off_track_count > 0).length;- const peopleNeedReply = solo- ? 0- : (today?.people ?? []).filter((p) => p.status === "needs_reply").length;+ const peopleNeedReply = solo ? 0 : (today?.people ?? []).filter((p) => p.status === "needs_reply").length;const peopleOverdue = solo ? 0 : (today?.people ?? []).filter((p) => p.overdue).length;- // …and says how many goals need attention instead, linking to /goals.- const goalsAtRisk = solo- ? (today?.departments ?? []).reduce((n, d) => n + d.at_risk_count + d.off_track_count, 0)- : 0;- // Solo's "Due soon" card reads the principal's own open loops.- const principalId = solo ? principalIdOf(today?.people ?? []) : null;- // …and the top three words a commitment as theirs ("you").+ const goalsAtRisk = solo ? departments.reduce((n, d) => n + d.at_risk_count + d.off_track_count, 0) : 0;+ // The top three words a commitment as the owner's ("you").const principalName =(principalId != null && today?.people.find((p) => p.id === principalId)?.full_name) || "";- const statPills: StatPill[] = today- ? briefingStats({- needsYou: mineProposals.length,- handledOvernight: groupHandled(handledOvernight).length,+ const needsYouCount = mineProposals.length + replies.cards.length;+ const summary: SummaryPart[] = today+ ? briefingSummary({+ needsYou: needsYouCount,+ handledOvernight: handledRows.length,peopleOverdue,peopleNeedReply,deptAtRisk: deptAtRiskCount,goalsAtRisk,- inFlight: inFlightCount,+ inFlight: inFlight.length,monitoring: monitoringProposals.length,}): [];+ // The count tiles — only those with something to show.+ const tiles: Tile[] = [];+ if (today) {+ if (solo) {+ const view = openLoops.view;+ if (principalId != null && (openLoops.error || (view && (view.items.length > 0 || view.later > 0)))) {+ const overdue = view?.items.filter((i) => i.overdue).length ?? 0;+ tiles.push({+ key: "dueSoon",+ value: String(view?.items.length ?? "–"),+ label: "Due soon",+ sub: overdue > 0 ? `${overdue} overdue` : view && view.items.length > 0 ? "this week" : `${view?.later ?? 0} later`,+ subTone: overdue > 0 ? "amber" : undefined,+ });+ }+ if (projects.error || (projects.projects && projects.projects.length > 0)) {+ tiles.push({+ key: "projects",+ value: String(projects.projects?.length ?? "–"),+ label: "Your projects",+ sub: "active",+ });+ }+ if (weeklyReview) {+ tiles.push({+ key: "weeklyReview",+ value: "Ready",+ label: "This week's review",+ sub: reviewRanLabel(weeklyReview.completed_at) || weeklyReview.period || "",+ });+ }+ } else {+ const deptValue = attentionDepts.length > 0 ? attentionDepts.length : activeDepts.length || departments.length;+ tiles.push({+ key: "departments",+ value: String(deptValue),+ label: "Departments",+ sub:+ attentionDepts.length > 0+ ? deptAtRiskCount > 0+ ? "at risk"+ : "need attention"+ : activeDepts.length > 0+ ? "on track"+ : "not set up yet",+ subTone: attentionDepts.length > 0 ? "amber" : activeDepts.length > 0 ? "emerald" : undefined,+ });+ if (showPeople && today) {+ const people = today.people;+ const busy = people.filter((p) => p.status === "needs_reply" || p.status === "awaiting").length;+ const s = peopleSummary(people);+ tiles.push({+ key: "people",+ value: String(busy > 0 ? busy : people.length),+ label: "People",+ sub: busy > 0 ? s.text : "all clear",+ subTone: s.hasOverdue ? "rose" : busy > 0 ? "amber" : "emerald",+ });+ }+ }+ if (otherProposals.length > 0)+ tiles.push({ key: "team", value: String(otherProposals.length), label: "Across the team", sub: "with teammates" });+ if (inFlight.length > 0)+ tiles.push({+ key: "inFlight",+ value: String(inFlight.length),+ label: "In flight",+ sub: inFlightNext(inFlight),+ subTone: inFlight.some((f) => f.overdue) ? "amber" : undefined,+ });+ if (handledRows.length > 0)+ tiles.push({+ key: "handled",+ value: String(handledRows.length),+ label: "Handled overnight",+ sub: "by the Executive",+ subTone: "emerald",+ });+ if (monitoringProposals.length > 0)+ tiles.push({+ key: "monitoring",+ value: String(monitoringProposals.length),+ label: "Monitoring",+ sub: monitoringProposals.length === 1 ? "signal" : "signals",+ });+ if (practiceClients.length > 0)+ tiles.push({+ key: "clients",+ value: String(practiceClients.length),+ label: "Across your clients",+ sub: "parked clients",+ });+ }++ // The Needs you queue: replies waiting first (they came in first, as their+ // own section did), then the proposals in score order.+ type QueueItem = { key: string; render: (emphasized: boolean) => React.ReactNode };+ const queue: QueueItem[] = [+ ...replies.cards.map((card) => ({+ key: `reply-${card.decision_id}`,+ render: (emphasized: boolean) => (+ <ReplyCardItem card={card} onGone={replies.gone} onRefresh={replies.refresh} emphasized={emphasized} />+ ),+ })),+ ...mineProposals.map((p) => ({+ key: `alert-${p.alert_id}`,+ render: (emphasized: boolean) => (+ <ProposalCard+ proposal={p}+ people={today?.people ?? []}+ onContinue={onContinue}+ onApprove={handleApprove}+ onDismiss={handleDismiss}+ onApproveWithEdits={handleApproveWithEdits}+ defaultBodyExpanded={emphasized}+ emphasized={emphasized}+ />+ ),+ })),+ ];+ const visibleQueue = showAllNeedsYou ? queue : queue.slice(0, NEEDS_YOU_VISIBLE);+ const hiddenCount = queue.length - visibleQueue.length;++ const needsYouMenu = [+ ...(staleNeedsYouIds.length > 0+ ? [+ {+ label: `Dismiss ${staleNeedsYouIds.length} older than ${NEEDS_YOU_DISMISS_OLDER_THAN_DAYS} days`,+ onSelect: () => void handleBulkDismiss(staleNeedsYouIds),+ },+ ]+ : []),+ {+ label: recheckBusy ? "Re-checking…" : "Re-check relevance",+ onSelect: () => void handleRecheck(),+ disabled: recheckBusy,+ },+ ];+ const showNeedsYouMenu = staleNeedsYouIds.length > 0 || mineProposals.length > 0;++ const hasBrief = Boolean(today && (today.narrative || today.narrative_stale));+ const briefFreshness = today+ ? today.narrative_stale+ ? "Refreshing…"+ : narrativeUpdatedLabel(today.narrative_generated_at, new Date())+ : null;++ const quietBanner =+ isQuiet && activeDepts.length > 0 ? (+ <div className="flex flex-wrap items-center justify-between gap-2 rounded-2xl border border-emerald-500/25 bg-emerald-500/5 px-4 py-3">+ <span className={`text-[15px] ${TONE_TEXT.emerald}`}>Quiet day — nothing needs your attention.</span>+ {!solo && (+ <Link href="/departments" className="text-sm font-medium text-accent hover:underline">+ Set up a check-in →+ </Link>+ )}+ </div>+ ) : null;+ const bannerSlot = banner ?? quietBanner;++ const onSummaryPart = (part: SummaryPart) => {+ if (part.target.kind === "needsYou") {+ document.getElementById(NEEDS_YOU_ID)?.scrollIntoView({ behavior: "smooth", block: "start" });+ } else if (part.target.kind === "panel") {+ setOpenPanel(part.target.panel);+ }+ };++ const panelFooterLink = (href: string, label: string) => (+ <Link href={href} className={buttonClass("secondary", "md", "w-full sm:w-auto")}>+ {label}+ </Link>+ );+return (<div className="flex flex-col h-full bg-surface"><main className="flex-1 overflow-y-auto">- <div className="max-w-6xl mx-auto px-4 sm:px-6 py-6">- <div className="flex items-baseline gap-3 mb-3">- <h1 className="text-xl font-semibold text-fg">- {showHeader- ? (firstName ? `Here's where we are, ${firstName}.` : "Here's where we are.")- : "Today"}+ <div className="max-w-3xl mx-auto px-4 sm:px-6 py-6 sm:py-10">+ <header className="mb-6">+ <p className="text-sm font-medium text-fg-muted">{dateLabel}</p>+ <h1 className="mt-1 text-2xl sm:text-3xl font-bold tracking-tight text-fg">+ {showHeader ? greeting(firstName) : "Today"}</h1>- <span className="text-sm text-fg-muted">{dateLabel}</span>- </div>+ {today && (+ <p className="mt-2 text-base sm:text-lg text-fg-muted leading-snug">+ {summary.length === 0+ ? "All clear — nothing needs you right now."+ : summary.map((part, i) => (+ <span key={part.text}>+ {part.target.kind === "href" ? (+ <Link href={part.target.href} className="hover:text-fg hover:underline underline-offset-4">+ {part.text}+ </Link>+ ) : (+ <button+ type="button"+ onClick={() => onSummaryPart(part)}+ className="cursor-pointer text-left hover:text-fg hover:underline underline-offset-4"+ >+ {part.text}+ </button>+ )}+ {i < summary.length - 1 ? ". " : "."}+ </span>+ ))}+ </p>+ )}+ </header>++ {onContinue && (+ <form+ onSubmit={(e) => {+ e.preventDefault();+ submitAsk();+ }}+ className="mb-6 flex items-center gap-2 rounded-2xl border border-line bg-surface-elevated p-2 pl-4 shadow-sm focus-within:border-accent/60 focus-within:ring-2 focus-within:ring-accent/20"+ >+ <input+ type="text"+ value={askText}+ onChange={(e) => setAskText(e.target.value)}+ placeholder="Ask your Executive anything…"+ aria-label="Ask your Executive"+ className="min-w-0 flex-1 bg-transparent py-2 text-base text-fg placeholder:text-fg-muted focus:outline-none"+ />+ <button+ type="submit"+ disabled={!askText.trim()}+ aria-label="Ask"+ className="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl bg-accent-strong text-white transition-colors hover:bg-accent-strong/90 disabled:opacity-40 disabled:cursor-not-allowed"+ >+ <Icon name="arrow-send" size="w-4 h-4" />+ </button>+ </form>+ )}- {loading && <p className="text-fg-muted text-sm">Loading…</p>}+ {loading && <p className="text-fg-muted text-[15px]">Loading…</p>}{error && (- <div className="p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm mb-4">+ <div className="mb-4 rounded-xl border border-rose-500/30 bg-rose-500/10 p-3 text-[15px] text-rose-700 dark:text-rose-300">{error}</div>)}+ {bannerSlot && <div className="mb-6">{bannerSlot}</div>}+{today && (<>- {/* Glanceable status strip — a one-second read of what needs- attention, built from the buckets computed above. */}- <div className="flex flex-wrap items-center gap-2 mb-6">- {statPills.length === 0 ? (- <span className="inline-flex items-center rounded-full border border-emerald-500/30 bg-emerald-500/15 px-2.5 py-1 text-xs font-medium text-emerald-300">- All clear- </span>- ) : (- statPills.map((pill) => {- const pillClass = `inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-medium cursor-pointer transition hover:brightness-110 focus:outline-none focus:ring-1 focus:ring-indigo-500/40 ${STAT_TONES[pill.tone]}`;- return pill.href ? (- <Link key={pill.label} href={pill.href} className={pillClass}>- {pill.label}- </Link>- ) : (+ {/* Needs you — decisions routed to the caller, and replies+ waiting to be sent. */}+ <section id={NEEDS_YOU_ID} className="mb-8 scroll-mt-4">+ <div className="mb-3 flex items-center gap-2">+ <h2 className="text-lg font-semibold text-fg">+ Needs you+ {needsYouCount > 0 && <span className="ml-1.5 font-normal text-fg-muted">({needsYouCount})</span>}+ </h2>+ {replies.cards.length > 0 && <InfoTip align="left">{REPLIES_WAITING_TIP}</InfoTip>}+ <div className="ml-auto flex items-center gap-1">+ {hasBrief && (<button- key={pill.label}type="button"- onClick={() => scrollToFirstVisible(pill.targetIds)}- className={pillClass}+ onClick={() => setOpenPanel("brief")}+ className={`min-h-[40px] rounded-xl px-3 text-sm font-medium text-accent hover:bg-accent/10 transition-colors${+ !today.narrative ? " animate-pulse" : ""+ }`}>- {pill.label}+ {today.narrative ? "Read today's brief" : "Catching up on today…"}</button>- );- })+ )}+ {showNeedsYouMenu && <OverflowMenu size="sm" label="Needs you options" items={needsYouMenu} />}+ </div>+ </div>+ {replies.notice && (+ <p className={`mb-3 text-sm ${TONE_TEXT.emerald}`} role="status">+ {replies.notice}+ </p>)}- </div>-- {!today.narrative && today.narrative_stale && (- <section className="mb-6" aria-live="polite">- <h2 className="text-xs font-semibold uppercase tracking-wide text-fg-muted mb-3">- What's going on- </h2>- <div className="rounded-xl border border-indigo-500/20 bg-indigo-500/5 px-5 py-4 text-sm text-fg-muted animate-pulse">- Catching up on today…+ {queue.length > 0 ? (+ <div className="space-y-4">+ {visibleQueue.map((item, i) => (+ <div key={item.key}>{item.render(i === 0)}</div>+ ))}+ {(hiddenCount > 0 || (showAllNeedsYou && queue.length > NEEDS_YOU_VISIBLE)) && (+ <div className="flex justify-center">+ <button+ type="button"+ onClick={() => setShowAllNeedsYou((v) => !v)}+ className={buttonClass("secondary", "md")}+ >+ {showAllNeedsYou ? "Show fewer" : `Show ${hiddenCount} more`}+ </button>+ </div>+ )}</div>- </section>+ ) : !isQuiet ? (+ <p className="rounded-2xl border border-dashed border-line px-4 py-5 text-[15px] text-fg-muted">+ Nothing waiting on you.+ </p>+ ) : null}+ </section>++ {solo && (+ <div className="mb-8">+ <TopThreeList ownerName={principalName} id="sec-top-three" />+ </div>)}- {today.narrative && (- <section className="mb-6">- <div className="flex items-center gap-1.5 mb-3">- <h2 className="text-xs font-semibold uppercase tracking-wide text-fg-muted">- What's going on- </h2>- <InfoTip align="left">- The Executive's read on {solo ? "your work" : "the company"} right- now — what came in today, what's stuck, what's next on- your calendar, plus proposals and at-risk goals. Rewritten- as the picture changes.- </InfoTip>- <span className="ml-auto text-[11px] text-fg-muted" aria-live="polite">- {today.narrative_stale- ? "Refreshing…"- : narrativeUpdatedLabel(today.narrative_generated_at, new Date())}- </span>- </div>- <div className="rounded-xl border border-indigo-500/20 bg-indigo-500/5 px-5 py-4">- <div className="prose prose-invert prose-sm max-w-none prose-p:my-1 prose-ul:my-1 prose-headings:text-fg prose-strong:text-fg">- <ReactMarkdown- remarkPlugins={[remarkGfm]}- components={- onContinue- ? {- // Drop the default disc + marker padding so our- // 💬 acts as the bullet. Tailwind utilities beat- // the `prose` plugin's zero-specificity :where(ul)- // rules, so list-none/pl-0 win here.- //- // Hybrid declutter: keep the top 2 signals on- // screen and fold the rest into a quiet "Show N- // more" disclosure so the narrative stops being a- // wall of text. Each bullet — visible or revealed- // — still routes through the `li` override below,- // so the 💬 discuss handoff is unchanged.- ul: ({ children }) => {- // remark inserts whitespace text nodes between- // <li>s; drop them so the slice counts real- // bullets, not newlines.- const items = Children.toArray(children).filter(- (c) => typeof c !== "string" || c.trim() !== "",- );- const head = items.slice(0, NARRATIVE_HEAD_BULLETS);- const tail = items.slice(NARRATIVE_HEAD_BULLETS);- return (- <ul className="list-none pl-0 my-1 space-y-0.5">- {head}- {tail.length > 0 && (- <li className="list-none">- <details className="group mt-0.5">- <summary className="flex items-center gap-1.5 py-0.5 cursor-pointer list-none text-xs text-fg-muted hover:text-fg transition-colors focus:outline-none focus:ring-1 focus:ring-indigo-500/40 rounded">- <span aria-hidden className="text-[10px] transition-transform group-open:rotate-90">▸</span>- <span>Show {tail.length} more signal{tail.length === 1 ? "" : "s"}</span>- </summary>- <ul className="list-none pl-0 mt-1 space-y-0.5">{tail}</ul>- </details>- </li>- )}- </ul>- );- },- // Each narrative bullet is its own click target →- // hands off to chat to discuss that item, reusing- // the same 💬 "Discuss" affordance as the proposal- // cards. The bottom-line and "Move today:" lines are- // paragraphs/strong text, so they stay non-interactive.- li: ({ node, children }) => {- const text = nodeToPlainText(node).trim();- // No extractable text (empty bullet, or a- // react-markdown version that doesn't forward- // `node`) → render a plain, non-clickable item- // rather than a button that seeds an empty prompt.- if (!text) return <li className="list-none">{children}</li>;- return (- <li className="list-none">- <button- type="button"- onClick={() => onContinue(buildNarrativeSeed(text), briefingMemoryLine(MEMORY_ACTIONS.narrative, text))}- aria-label={`Discuss: ${text}`}- className="group flex w-full items-start gap-2 text-left cursor-pointer rounded -mx-1.5 px-1.5 py-0.5 transition hover:bg-indigo-500/10 focus:outline-none focus:ring-1 focus:ring-indigo-500/40"- >- {/* 💬 stands in for the bullet and signals- "click to discuss"; items-start keeps it on- the first line with the text hanging beside it.- opacity lifts on hover as the click cue. */}- <span aria-hidden className="mt-0.5 flex-shrink-0 select-none opacity-70 transition group-hover:opacity-100">💬</span>- <span className="min-w-0">{children}</span>- </button>- </li>- );- },- }- : undefined- }+ {tiles.length > 0 && (+ <section aria-labelledby="sec-everything-else" className="mb-8">+ <h2 id="sec-everything-else" className="mb-3 text-lg font-semibold text-fg">+ Everything else+ </h2>+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">+ {tiles.map((t) => (+ <button+ key={t.key}+ type="button"+ onClick={() => setOpenPanel(t.key)}+ aria-haspopup="dialog"+ className="flex min-h-[7.5rem] flex-col items-start rounded-2xl border border-line bg-surface-elevated p-4 text-left transition-colors hover:border-line-strong hover:bg-surface-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/50">- {today.narrative}- </ReactMarkdown>- </div>+ <span className="text-2xl sm:text-3xl font-bold tracking-tight text-fg tabular-nums">+ {t.value}+ </span>+ <span className="mt-1 text-[15px] font-medium text-fg">{t.label}</span>+ {t.sub && (+ <span className={`mt-0.5 text-sm ${t.subTone ? TONE_TEXT[t.subTone] : "text-fg-muted"}`}>+ {t.sub}+ </span>+ )}+ </button>+ ))}</div></section>)}- {isQuiet && activeDepts.length > 0 && (- <div className="mb-6 flex items-center justify-between rounded-xl border border-emerald-500/20 bg-emerald-500/5 px-4 py-3">- <span className="text-sm text-emerald-300">Quiet day — nothing needs your attention.</span>- {!solo && (- <Link href="/departments" className="text-xs text-indigo-400 hover:text-indigo-300 flex-shrink-0">- Set up a check-in →- </Link>- )}- </div>- )}-- {/* Pulse card system — a symmetric two-column grid beneath the- narrative. Stacks to one column below xl, so each section- renders exactly once at every breakpoint (no mobile/desktop- duplicates). Left = action queue; right = awareness. */}- <div className="grid gap-8 xl:grid-cols-[1.05fr_0.95fr]">- {/* LEFT — action queue */}- <div className="min-w-0 space-y-8">- {/* Replies the Executive drafted in the owner's own Gmail- (Act as me). Hidden for everyone else and when none wait. */}- <RepliesWaiting id={SECTION_IDS.repliesWaiting} />-- {/* Needs you — decisions routed to the caller. Primary- section: visually dominant so the eye lands here first.- Buckets (mineProposals / otherProposals / monitoring)- are computed once above so the status strip and these- lists stay in sync. */}- <section id="sec-needs-you" className="rounded-xl border border-line bg-surface-elevated p-4">- <details open className="group">- <summary className="flex items-center gap-2 mb-3 cursor-pointer list-none border-l-2 border-indigo-500 pl-2">- <span className="text-[10px] text-fg-muted transition-transform group-open:rotate-90">▸</span>- <SectionLabel variant="primary" count={mineProposals.length}>- Needs you- </SectionLabel>- </summary>- {startHereProposal ? (- // Full queue inside a fixed-height scroll (like the Pulse- // Recent activity card) — no cap, no "Show more"; the list- // scrolls internally instead of growing the page.- <div className="max-h-[32rem] overflow-y-auto pr-1 divide-y divide-line">- {/* Start here — the single sharpest item, emphasized- (indigo left accent + label) and expanded so there's- one obvious first move instead of a flat queue. The- ProposalCard supplies the row's own py-3, so this- wrapper adds none (avoids a double pad that would- break the divider-row rhythm). */}- <div>- <div className="mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-indigo-300">- Start here- </div>- <ProposalCard- proposal={startHereProposal}- people={today.people}- onContinue={onContinue}- onApprove={handleApprove}- onDismiss={handleDismiss}- onApproveWithEdits={handleApproveWithEdits}- defaultBodyExpanded- emphasized- />- </div>- {(showAllNeedsYou ? restProposals : restProposals.slice(0, NEEDS_YOU_VISIBLE)).map((p) => (- <ProposalCard- key={p.alert_id}- proposal={p}- people={today.people}- onContinue={onContinue}- onApprove={handleApprove}- onDismiss={handleDismiss}- onApproveWithEdits={handleApproveWithEdits}- />- ))}- {restProposals.length > NEEDS_YOU_VISIBLE && (- <button- type="button"- onClick={() => setShowAllNeedsYou((v) => !v)}- className="w-full py-2 text-[11px] text-fg-muted hover:text-fg transition-colors"- >- {showAllNeedsYou- ? "Show fewer"- : `Show ${restProposals.length - NEEDS_YOU_VISIBLE} more`}- </button>- )}- </div>- ) : !isQuiet ? (- <p className="text-sm text-fg-muted py-3">Nothing waiting on you.</p>- ) : null}- {/* Relief valves: clear the old tail in one click, or ask- the Executive to re-judge everything right now. */}- {(staleNeedsYouIds.length > 0 || mineProposals.length > 0) && (- <div className="mt-2 flex flex-wrap items-center gap-3">- {staleNeedsYouIds.length > 0 && (- <button- type="button"- onClick={() => handleBulkDismiss(staleNeedsYouIds)}- className="text-[11px] text-fg-muted hover:text-rose-300 transition-colors"- >- ✕ Dismiss {staleNeedsYouIds.length} older than {NEEDS_YOU_DISMISS_OLDER_THAN_DAYS} days- </button>- )}- <button- type="button"- onClick={handleRecheck}- disabled={recheckBusy}- className="text-[11px] text-fg-muted hover:text-indigo-300 transition-colors disabled:opacity-50"- >- {recheckBusy ? "⟳ Re-checking…" : "⟳ Re-check relevance"}- </button>- </div>- )}- </details>- </section>-- {solo && <TopThreePanel ownerName={principalName} id={SECTION_IDS.topThree} />}-- {solo && principalId != null && (- <DueSoonPanel principalId={principalId} id={SECTION_IDS.dueSoon} />- )}-- {otherProposals.length > 0 && (- <section className="rounded-xl border border-line bg-surface-elevated p-4">- <SectionHeading title="Across the team" count={otherProposals.length} />- <div className="max-h-[32rem] overflow-y-auto pr-1 divide-y divide-line">- {otherProposals.map((p) => (- <ProposalCard- key={p.alert_id}- proposal={p}- people={today.people}- onContinue={onContinue}- onApprove={handleApprove}- onDismiss={handleDismiss}- onApproveWithEdits={handleApproveWithEdits}- />- ))}- </div>- </section>+ <SidePanel+ open={openPanel === "brief"}+ onClose={() => setOpenPanel(null)}+ title="Today's brief"+ subtitle={<span aria-live="polite">{briefFreshness ?? dateLabel}</span>}+ width="lg"+ >+ <NarrativeBody+ narrative={today.narrative}+ stale={today.narrative_stale ?? false}+ solo={solo}+ onContinue={onContinue}+ />+ </SidePanel>+ <SidePanel+ open={openPanel === "departments"}+ onClose={() => setOpenPanel(null)}+ title="Departments"+ width="lg"+ footer={panelFooterLink("/departments", "View all departments")}+ >+ <DepartmentsPanelBody departments={departments} onContinue={onContinue} />+ </SidePanel>+ <SidePanel+ open={openPanel === "people"}+ onClose={() => setOpenPanel(null)}+ title="People"+ width="lg"+ footer={panelFooterLink("/people", "View all people")}+ >+ <PeoplePanelBody people={today.people} />+ </SidePanel>+ <SidePanel+ open={openPanel === "team"}+ onClose={() => setOpenPanel(null)}+ title="Across the team"+ subtitle="Waiting on someone else"+ width="lg"+ >+ <div className="space-y-4">+ {otherProposals.map((p) => (+ <ProposalCard+ key={p.alert_id}+ proposal={p}+ people={today.people}+ onContinue={onContinue}+ onApprove={handleApprove}+ onDismiss={handleDismiss}+ onApproveWithEdits={handleApproveWithEdits}+ />+ ))}+ {otherProposals.length === 0 && (+ <p className="text-[15px] text-fg-muted">Nothing waiting on anyone else.</p>)}</div>-- {/* RIGHT — awareness (org health + ambient signals) */}- <div className="min-w-0 space-y-8">- {solo && <WeeklyReviewPanel id={SECTION_IDS.weeklyReview} />}-- {solo && <ProjectsPanel id={SECTION_IDS.projects} />}-- {/* Departments — only those needing attention get a row;- healthy + inactive ones fold into one quiet toggle. */}- {!solo && (- <section id="sec-departments" className="rounded-xl border border-line bg-surface-elevated p-4">- <div className="flex items-center justify-between mb-3">- <div className="flex items-center gap-1.5">- <SectionLabel variant="ambient">Departments</SectionLabel>- <InfoTip align="left">- <span className="text-amber-300">At risk</span> /{" "}- <span className="text-rose-300">off track</span> = goal- health. <span className="text-sky-300">Awaiting</span> =- items waiting on the department head.{" "}- <span className="text-fg">Inactive</span> = no goals or- check-ins set up yet.- </InfoTip>- </div>- <Link href="/departments" className="text-xs text-indigo-400 hover:text-indigo-300">- View all →- </Link>- </div>-- {activeDepts.length === 0 && (- <div className="py-3">- <p className="text-sm text-fg-muted mb-2">- No department has a check-in set up yet.- </p>- <Link href="/departments" className="text-xs text-indigo-400 hover:text-indigo-300">- Pick one to activate →- </Link>- </div>- )}-- {/* Attention departments (full, no cap) + the quiet toggle- all share one fixed-height scroll, like the Pulse cards —- the section never grows the page. */}- {(attentionDepts.length > 0 || quietDeptCount > 0) && (- <div className="max-h-[32rem] overflow-y-auto pr-1">- {attentionDepts.length > 0 && (- <div className="divide-y divide-line">- {attentionDepts.map((d) => (- <DeptCard key={d.slug} dept={d} onContinue={onContinue} />- ))}- </div>- )}-- {/* One quiet toggle for the rest — on-track and inactive- departments revealed together in a single column. */}- {quietDeptCount > 0 && (- <div className={attentionDepts.length > 0 ? "mt-3" : ""}>- <button- type="button"- onClick={() => setShowAllDeptsOpen((v) => !v)}- aria-expanded={showAllDeptsOpen}- className="flex items-center gap-1.5 min-h-[44px] text-xs text-fg-muted hover:text-fg transition-colors"- >- <span aria-hidden="true">{showAllDeptsOpen ? "▲" : "▼"}</span>- {quietDeptSummary}- </button>- {showAllDeptsOpen && (- <div className="divide-y divide-line mt-3">- {onTrackDepts.map((d) => (- <DeptCard key={d.slug} dept={d} onContinue={onContinue} />- ))}- {inactiveDepts.map((d) => (- <DeptCard key={d.slug} dept={d} onContinue={onContinue} dimmed />- ))}- </div>- )}- </div>- )}- </div>- )}- </section>- )}-- {/* People — full roster, scrolling inside the card. */}- {showPeopleSidebar && !solo && (- <section id="sec-people" className="rounded-xl border border-line bg-surface-elevated p-4">- {(() => {- const summary = peopleSummary(today.people);- return (- <div className="flex items-start justify-between gap-2 mb-3">- <div>- <h3 className="text-sm font-semibold text-fg">People</h3>- <p className={`text-xs mt-0.5 ${summary.hasOverdue ? "text-rose-300" : "text-fg-muted"}`}>- {summary.text}- </p>- </div>- <Link href="/people" className="flex-shrink-0 text-xs text-indigo-400 hover:text-indigo-300">View all</Link>- </div>- );- })()}- <div className="max-h-[32rem] overflow-y-auto pr-1 divide-y divide-line">- {today.people.map((p) => (- <PersonRow key={p.id} person={p} />- ))}- </div>- </section>+ </SidePanel>+ <SidePanel open={openPanel === "inFlight"} onClose={() => setOpenPanel(null)} title="In flight">+ <InFlightPanelBody inFlight={inFlight} />+ </SidePanel>+ <SidePanel open={openPanel === "handled"} onClose={() => setOpenPanel(null)} title="Handled overnight">+ <HandledPanelBody+ items={handledOvernight}+ onReopen={handleReopen}+ undone={undoneRows}+ onJumpToAlert={jumpToAlert}+ />+ </SidePanel>+ <SidePanel open={openPanel === "monitoring"} onClose={() => setOpenPanel(null)} title="Monitoring">+ <MonitoringPanelBody+ proposals={monitoringProposals}+ onContinue={onContinue}+ onDismiss={handleDismiss}+ onBulkDismiss={handleBulkDismiss}+ />+ </SidePanel>+ <SidePanel+ open={openPanel === "clients"}+ onClose={() => setOpenPanel(null)}+ title="Across your clients"+ footer={panelFooterLink("/clients", "Manage clients")}+ >+ <PracticeClientsPanelBody clients={practiceClients} />+ </SidePanel>+ {solo && (+ <>+ <SidePanel+ open={openPanel === "projects"}+ onClose={() => setOpenPanel(null)}+ title="Your projects"+ footer={panelFooterLink("/goals", "Goals")}+ >+ <ProjectsPanelBody state={projects} />+ </SidePanel>+ <SidePanel+ open={openPanel === "dueSoon"}+ onClose={() => setOpenPanel(null)}+ title="Due soon"+ footer={principalId != null ? panelFooterLink(`/people/${principalId}`, "All open items") : undefined}+ >+ <DueSoonPanelBody state={openLoops} />+ </SidePanel>+ {weeklyReview && (+ <SidePanel+ open={openPanel === "weeklyReview"}+ onClose={() => setOpenPanel(null)}+ title="This week's review"+ >+ <WeeklyReviewPanelBody review={weeklyReview} />+ </SidePanel>)}-- {/* Ambient — In flight (commitments with run times) and- Monitoring (live signals). Both render once; each is its- own Pulse card. */}- <InFlightPanel inFlight={today.in_flight ?? []} id={SECTION_IDS.inFlight} />- <PracticeClientsPanel- clients={today.practice_clients ?? []}- id={SECTION_IDS.practice}- />- <HandledOvernightPanel- items={handledOvernight}- onReopen={handleReopen}- undone={undoneRows}- />- <MonitoringPanel- proposals={monitoringProposals}- onContinue={onContinue}- onDismiss={handleDismiss}- onBulkDismiss={handleBulkDismiss}- id={SECTION_IDS.monitoring}- />- </div>- </div>+ </>+ )}</>)}</div>diff --git a/packages/ui/src/components/Chat.tsx b/packages/ui/src/components/Chat.tsxindex 59e98c6e..6fc2cf4a 100644--- a/packages/ui/src/components/Chat.tsx+++ b/packages/ui/src/components/Chat.tsx@@ -7,6 +7,7 @@ import BrandMark from "./BrandMark";import TurnStatusRow, { useTurnClock } from "./TurnStatusRow";import Icon from "./Icon";import InfoTip from "./InfoTip";+import OverflowMenu from "./ui/OverflowMenu";import {MAX_FILES_PER_TURN,mergePickedFiles,@@ -505,12 +506,11 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,<div className="mb-6"><BrandMark size="lg" /></div>- <h2 className="text-xl font-semibold text-fg mb-2">- {firstName- ? `Here's where we are, ${firstName}.`- : "Here's where we are."}+ {/* Not the briefing's headline: Home already greets you. */}+ <h2 className="text-2xl font-bold tracking-tight text-fg mb-2">+ {firstName ? `What's on your mind, ${firstName}?` : "What's on your mind?"}</h2>- <p className="text-fg-muted text-sm max-w-sm mb-10">+ <p className="text-fg-muted text-[15px] max-w-md mb-10">{subtitle}</p>@@ -525,7 +525,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,<divkey={i}aria-hidden- className="min-h-touch rounded-xl bg-surface-overlay/60 border border-line animate-pulse motion-reduce:animate-none"+ className="min-h-[52px] rounded-2xl bg-surface-overlay/60 border border-line animate-pulse motion-reduce:animate-none"/>)): suggested.map((prompt) => (@@ -533,7 +533,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,type="button"key={prompt}onClick={() => handleSend(prompt)}- className="text-left px-4 py-3 min-h-touch rounded-xl bg-surface-overlay/60 border border-line hover:border-line-strong hover:bg-surface-overlay text-fg-muted hover:text-fg text-sm transition-all duration-150 cursor-pointer"+ className="text-left px-4 py-3.5 min-h-[52px] rounded-2xl bg-surface-elevated border border-line hover:border-line-strong hover:bg-surface-hover text-fg-muted hover:text-fg text-[15px] transition-all duration-150 cursor-pointer">{prompt}</button>@@ -593,6 +593,24 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,{/* Input */}<div className="border-t border-line bg-surface px-4 sm:px-6 py-3 sm:py-4"><div className="max-w-3xl mx-auto">+ {/* Committee review is switched in the + menu; while it is on, this+ chip says so and turns it off. */}+ {committeeEnabled && (+ <div className="mb-2">+ <button+ type="button"+ onClick={() => setCommitteeEnabled(false)}+ disabled={isLoading}+ aria-pressed+ title="Committee review: slower, higher-quality response — adversarial review pass before sending. Click to turn off."+ className="inline-flex min-h-[32px] items-center gap-1.5 rounded-lg border border-accent/40 bg-accent/10 px-2.5 text-xs font-medium text-accent hover:bg-accent/15 disabled:opacity-50 cursor-pointer"+ >+ <Icon name="users" size="w-3.5 h-3.5" />+ Committee review on+ <Icon name="close" size="w-3 h-3" />+ </button>+ </div>+ )}{pendingFiles.length > 0 && (<div className="flex flex-wrap gap-2 mb-2" aria-label="Pending attachments">{pendingFiles.map((f, i) => (@@ -620,7 +638,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,{fileError}</p>)}- <div className="relative flex items-end gap-1.5 sm:gap-3 bg-surface-overlay/50 border border-line-strong rounded-2xl px-2 sm:px-4 py-2 sm:py-3 focus-within:border-fg-muted transition-colors">+ <div className="relative flex items-end gap-1.5 sm:gap-2 bg-surface-elevated border border-line-strong rounded-2xl p-1.5 sm:p-2 shadow-sm focus-within:border-accent/60 transition-colors"><inputref={fileInputRef}type="file"@@ -630,26 +648,34 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,className="hidden"aria-hidden="true"/>- <button- type="button"- onClick={() => fileInputRef.current?.click()}- disabled={isLoading || pendingFiles.length >= MAX_FILES_PER_TURN}- title={- pendingFiles.length >= MAX_FILES_PER_TURN- ? `Limit ${MAX_FILES_PER_TURN} files per message`- : "Attach files or photos (PDF, DOCX, TXT, MD, CSV, images)"- }- aria-label="Attach files"- className="flex-shrink-0 min-h-touch min-w-touch w-10 h-10 rounded-xl bg-surface-overlay border border-line-strong text-fg-muted hover:text-fg hover:border-line-strong disabled:opacity-30 disabled:cursor-not-allowed transition-all duration-150 flex items-center justify-center cursor-pointer"- >- <Icon name="paperclip" size="w-4 h-4" />- </button>+ {/* The + menu: attach files, and committee review (on/off). */}+ <OverflowMenu+ label="Add to your message"+ align="left"+ placement="up"+ icon={<Icon name="plus" size="w-5 h-5" />}+ items={[+ {+ label:+ pendingFiles.length >= MAX_FILES_PER_TURN+ ? `Attach files (limit ${MAX_FILES_PER_TURN} per message)`+ : "Attach files or photos",+ onSelect: () => fileInputRef.current?.click(),+ disabled: isLoading || pendingFiles.length >= MAX_FILES_PER_TURN,+ },+ {+ label: committeeEnabled ? "Turn off committee review" : "Committee review (slower, reviewed)",+ onSelect: () => setCommitteeEnabled((v) => !v),+ disabled: isLoading,+ },+ ]}+ />{/* The suggestion is drawn by a ghost layer sharing the textarea'sgrid cell rather than by the native placeholder, which aone-row textarea clips to its first line. The cell grows tothe ghost's wrapped height; the placeholder attribute stillcarries the text for screen readers, just painted transparent. */}- <div className="grid flex-1 min-w-0">+ <div className="grid flex-1 min-w-0 self-center py-2">{showFollowup && (<divaria-hidden@@ -674,37 +700,6 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,style={{ minHeight: "24px" }}/></div>- {showFollowup && (- <button- type="button"- onClick={acceptFollowup}- title="Use the suggested follow-up (Tab)"- aria-label={`Use suggested follow-up: ${followup}`}- className="hidden sm:flex flex-shrink-0 min-h-touch px-2.5 rounded-lg border border-line bg-surface-overlay text-xs font-mono text-fg-muted hover:text-fg hover:border-line-strong transition-all duration-150 items-center cursor-pointer"- >- Tab ↹- </button>- )}- <button- type="button"- onClick={() => setCommitteeEnabled((v) => !v)}- disabled={isLoading}- title="Committee review: slower, higher-quality response — adversarial review pass before sending"- aria-pressed={committeeEnabled}- aria-label="Committee review"- className={- "flex-shrink-0 min-h-touch min-w-touch sm:px-3 flex items-center justify-center rounded-xl text-xs font-medium transition-all duration-150 border cursor-pointer " +- (committeeEnabled- ? "bg-indigo-500/15 border-indigo-500/60 text-indigo-300 hover:bg-indigo-500/20"- : "bg-surface-overlay border-line-strong text-fg-muted hover:text-fg hover:border-line-strong") +- " disabled:opacity-30 disabled:cursor-not-allowed"- }- >- {/* An icon on phones, where the word would take most of the- row the message box needs. */}- <Icon name="users" size="w-4 h-4" className="sm:hidden" />- <span className="hidden sm:inline">Committee</span>- </button>{isLoading ? (<buttontype="button"@@ -712,7 +707,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,disabled={isStopping}aria-label="Stop the executive"title="Stop — whatever has been written so far is kept"- className="flex-shrink-0 min-h-touch min-w-touch w-10 h-10 rounded-xl bg-surface-overlay border border-line-strong text-fg hover:border-fg-muted disabled:opacity-30 disabled:cursor-not-allowed transition-all duration-150 flex items-center justify-center cursor-pointer"+ className="flex-shrink-0 w-11 h-11 rounded-xl bg-surface-overlay border border-line-strong text-fg hover:border-fg-muted disabled:opacity-30 disabled:cursor-not-allowed transition-all duration-150 flex items-center justify-center cursor-pointer"><Icon name="stop" size="w-3.5 h-3.5" fill="currentColor" /></button>@@ -722,28 +717,27 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,onClick={() => handleSend()}disabled={!input.trim() && pendingFiles.length === 0}aria-label="Send message"- className="flex-shrink-0 min-h-touch min-w-touch w-10 h-10 rounded-xl bg-indigo-500 hover:bg-indigo-400 disabled:opacity-30 disabled:cursor-not-allowed transition-all duration-150 flex items-center justify-center cursor-pointer"+ className="flex-shrink-0 w-11 h-11 rounded-xl bg-accent-strong hover:bg-accent-strong/90 disabled:opacity-30 disabled:cursor-not-allowed transition-all duration-150 flex items-center justify-center cursor-pointer"><Icon name="arrow-send" size="w-4 h-4" className="text-white" /></button>)}</div><p className="text-center text-xs text-fg-muted mt-2 inline-flex items-center justify-center gap-1.5 w-full">- <span className="hidden sm:inline">- Enter to send · Shift+Enter for new line- {showFollowup && " · Tab to use suggestion"}- </span>+ <span className="hidden sm:inline">Enter to send · Shift+Enter for new line</span><span className="sm:hidden">Tap send</span>- {/* Phones have no Tab key and no room in the input row, so the- tap target for the suggestion lives on this line instead. */}+ {/* The suggestion's hint is also its button: Tab on a keyboard,+ a tap or click anywhere else. */}{showFollowup && (<buttontype="button"onClick={acceptFollowup}+ title="Use the suggested follow-up (Tab)"aria-label={`Use suggested follow-up: ${followup}`}- className="sm:hidden min-h-touch px-1 text-indigo-400 hover:text-indigo-300 font-medium cursor-pointer"+ className="min-h-touch px-1 text-accent hover:underline font-medium cursor-pointer">- · Use suggestion+ <span className="hidden sm:inline">· Tab ↹ to use suggestion</span>+ <span className="sm:hidden">· Use suggestion</span></button>)}<InfoTip align="right">diff --git a/packages/ui/src/components/Icon.tsx b/packages/ui/src/components/Icon.tsxindex f2b66795..1ed75e97 100644--- a/packages/ui/src/components/Icon.tsx+++ b/packages/ui/src/components/Icon.tsx@@ -4,6 +4,9 @@ import { SVGProps } from "react";// rather than introducing inline <svg> elements in pages/components.export const ICON_PATHS = {plus: "M12 4.5v15m7.5-7.5h-15",+ home: "M2.25 12l8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h8.25",+ chat: "M8.625 12a.375.375 0 11-.75 0 .375.375 0 01.75 0zm4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zM2.25 12.76c0 1.6 1.123 2.994 2.707 3.227 1.087.16 2.185.283 3.293.369V21l4.184-4.183a1.14 1.14 0 01.778-.332 48.294 48.294 0 005.83-.498c1.585-.233 2.708-1.626 2.708-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0012 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018z",+ briefcase: "M20.25 14.15v4.25c0 1.094-.787 2.036-1.872 2.18-2.087.277-4.216.42-6.378.42s-4.291-.143-6.378-.42c-1.085-.144-1.872-1.086-1.872-2.18v-4.25m16.5 0a2.18 2.18 0 00.75-1.661V8.706c0-1.081-.768-2.015-1.837-2.175a48.114 48.114 0 00-3.413-.387m4.5 8.006c-.194.165-.42.295-.673.38A23.978 23.978 0 0112 15.75c-2.648 0-5.195-.429-7.577-1.22a2.016 2.016 0 01-.673-.38m0 0A2.18 2.18 0 013 12.489V8.706c0-1.081.768-2.015 1.837-2.175a48.111 48.111 0 013.413-.387m7.5 0V5.25A2.25 2.25 0 0013.5 3h-3a2.25 2.25 0 00-2.25 2.25v.894m7.5 0a48.667 48.667 0 00-7.5 0",check: "M5 13l4 4L19 7","check-circle": "M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z",close: "M6 18L18 6M6 6l12 12",diff --git a/packages/ui/src/components/RepliesWaiting.tsx b/packages/ui/src/components/RepliesWaiting.tsxindex d24c0af3..4bb7aa39 100644--- a/packages/ui/src/components/RepliesWaiting.tsx+++ b/packages/ui/src/components/RepliesWaiting.tsx@@ -2,8 +2,8 @@import { useCallback, useEffect, useState } from "react";-import InfoTip from "./InfoTip";-import { SectionHeading } from "./memories/shared";+import Button from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";import {dismissReplyCard,getReplyCards,@@ -22,20 +22,24 @@ import {senderLine,} from "@/lib/replyCards";-// Today: the replies the Executive drafted in your own Gmail for mail that-// needs you (Settings → Act as me → Draft replies to my inbox). Each card-// shows who wrote, what they wrote, the draft, what it leaves you to decide-// and anything to check. Send sends that draft from your Gmail exactly as it-// is there, after you confirm who it goes to; Edit in Gmail opens it there;-// Dismiss deletes it unless you edited it. GET /delegation/replies answers-// only the owner, so this hides itself for everyone else, on a backend-// without it, and when nothing is waiting.+// Home: the replies the Executive drafted in your own Gmail for mail that+// needs you (Settings → Act as me → Draft replies to my inbox), shown as+// cards in "Needs you". Each card shows who wrote, what they wrote, the+// draft, what it leaves you to decide and anything to check. Send (the+// card's primary) sends that draft from your Gmail exactly as it is there,+// after you confirm who it goes to; Edit in Gmail and Dismiss (deletes it+// unless you edited it) are in its ⋯ menu. GET /delegation/replies answers+// only the owner, so nothing shows for everyone else, on a backend without+// it, and when nothing is waiting.// While a send Gmail hasn't confirmed is being settled (the card is// "executing"), how often the cards are read again.const SETTLE_POLL_MS = 20_000;-export default function RepliesWaiting({ id }: { id?: string }) {+// The cards and their refresh, for the Home "Needs you" list, which shows+// each one as a card among the proposals. `cards` stays null for anyone but+// the owner, on a backend without the route, and until the first read.+export function useReplyCards() {const [cards, setCards] = useState<ReplyCard[] | null>(null);const [notice, setNotice] = useState<string | null>(null);@@ -63,32 +67,21 @@ export default function RepliesWaiting({ id }: { id?: string }) {return () => clearInterval(timer);}, [settling, refresh]);- if (!cards || (cards.length === 0 && !notice)) return null;- const gone = (decisionId: number, note?: string) => {+ const gone = useCallback((decisionId: number, note?: string) => {setCards((prev) => (prev ?? []).filter((c) => c.decision_id !== decisionId));setNotice(note ?? null);- };- return (- <section id={id} className="rounded-xl border border-line bg-surface-elevated p-4">- <div className="flex items-center gap-1.5">- <SectionHeading title="Replies waiting" count={cards.length} icon="mail" />- <InfoTip align="left">- Mail that needs you, with a first reply the Executive wrote in your voice. Each- draft is in your own Drafts, and nothing is sent until you tap Send: it sends that- draft exactly as it is in your mailbox, so edit it there first if you want to change it.- Dismiss deletes the draft, unless you've edited it there. Only you see these.- </InfoTip>- </div>- {notice && <p className="mb-2 text-xs text-emerald-300">{notice}</p>}- <div className="max-h-[40rem] overflow-y-auto pr-1 divide-y divide-line">- {cards.map((card) => (- <ReplyCardRow key={card.decision_id} card={card} onGone={gone} onRefresh={refresh} />- ))}- </div>- </section>- );+ }, []);++ return { cards: cards ?? [], notice, gone, refresh };}+// What the Replies-waiting cards are, for the Needs you header's tip.+export const REPLIES_WAITING_TIP =+ "Mail that needs you, with a first reply the Executive wrote in your voice. Each " ++ "draft is in your own Drafts, and nothing is sent until you tap Send: it sends that " ++ "draft exactly as it is in your mailbox, so edit it there first if you want to change it. " ++ "Dismiss deletes the draft, unless you've edited it there. Only you see these.";+// What the row is doing: idle, asking before sending (first or second// time), or waiting on the backend.type Step =@@ -97,12 +90,14 @@ type Step =| { kind: "confirm"; message: string; recipients: string[]; threadMovedOn: boolean }| { kind: "busy"; label: string };-function ReplyCardRow({+export function ReplyCardItem({card,onGone,onRefresh,+ emphasized = false,}: {card: ReplyCard;+ emphasized?: boolean;onGone: (id: number, note?: string) => void;onRefresh: () => Promise<void>;}) {@@ -158,45 +153,55 @@ function ReplyCardRow({}};+ const busy = step.kind === "busy";+ const label = "text-xs font-semibold uppercase tracking-wide text-fg-muted";return (- <article className="py-3 first:pt-0 last:pb-0">- <div className="flex items-start justify-between gap-3">- <div className="min-w-0">- <div className="text-sm text-fg break-words">{senderLine(card)}</div>- <div className="text-xs text-fg-muted mt-0.5">- {[relation, card.sender_verified ? "" : "Address not verified"].filter(Boolean).join(" · ")}- </div>- </div>- {received && <span className="flex-shrink-0 text-xs text-fg-subtle tabular-nums">{received}</span>}+ <article+ className={`rounded-2xl border bg-surface-elevated p-4 sm:p-5 ${+ emphasized ? "border-accent/60 ring-1 ring-accent/25 shadow-sm" : "border-line"+ }`}+ >+ <div className="mb-2 flex items-center gap-2">+ <span className="inline-flex items-center rounded-lg bg-accent/10 px-2 py-0.5 text-[13px] font-medium text-accent">+ Reply waiting+ </span>+ {received && <span className="text-sm text-fg-subtle tabular-nums">{received}</span>}+ </div>+ <div className="text-base sm:text-[17px] font-semibold leading-snug text-fg break-words">+ {card.subject || "(no subject)"}+ </div>+ <div className="mt-1 text-sm text-fg-muted break-words">+ {senderLine(card)}+ {[relation, card.sender_verified ? "" : "Address not verified"]+ .filter(Boolean)+ .map((part) => ` · ${part}`)+ .join("")}</div>- <div className="mt-1.5 text-sm font-medium text-fg break-words">{card.subject || "(no subject)"}</div>{card.they_wrote && (- <details className="mt-2 group">- <summary className="cursor-pointer list-none text-[10px] font-semibold uppercase tracking-wide text-fg-muted">+ <details className="mt-3 group">+ <summary className={`cursor-pointer list-none ${label}`}><span className="inline-block transition-transform group-open:rotate-90">▸</span> They wrote</summary>{/* Plain text: what a stranger wrote is never rendered as markup. */}- <p className="mt-1 max-h-48 overflow-y-auto whitespace-pre-wrap break-words rounded-md border border-line bg-surface px-2 py-1.5 text-xs text-fg-muted">+ <p className="mt-1.5 max-h-48 overflow-y-auto whitespace-pre-wrap break-words rounded-xl border border-line bg-surface px-3 py-2 text-sm text-fg-muted">{card.they_wrote}</p></details>)}- <div className="mt-2">- <div className="text-[10px] font-semibold uppercase tracking-wide text-fg-muted">Your draft</div>- <div className="mt-1 rounded-md border border-line bg-surface px-2 py-1.5">- <div className="text-[11px] text-fg-subtle break-words">To: {card.draft_to.join(", ")}</div>- <p className="mt-1 whitespace-pre-wrap break-words text-xs text-fg">{card.draft_body}</p>+ <div className="mt-3">+ <div className={label}>Your draft</div>+ <div className="mt-1.5 rounded-xl border border-line bg-surface px-3 py-2">+ <div className="text-xs text-fg-subtle break-words">To: {card.draft_to.join(", ")}</div>+ <p className="mt-1 whitespace-pre-wrap break-words text-sm text-fg">{card.draft_body}</p></div></div>{card.open_questions.length > 0 && (- <div className="mt-2">- <div className="text-[10px] font-semibold uppercase tracking-wide text-indigo-300">- Decide before sending- </div>- <ul className="mt-1 list-disc pl-4 space-y-0.5 text-xs text-fg">+ <div className="mt-3">+ <div className="text-xs font-semibold uppercase tracking-wide text-accent">Decide before sending</div>+ <ul className="mt-1 list-disc pl-5 space-y-0.5 text-sm text-fg">{card.open_questions.map((q, i) => (<li key={i} className="break-words">{q}</li>))}@@ -205,7 +210,7 @@ function ReplyCardRow({)}{warnings.length > 0 && (- <ul className="mt-2 space-y-0.5 text-xs text-amber-300">+ <ul className="mt-3 space-y-0.5 text-sm text-amber-700 dark:text-amber-300">{warnings.map((w) => (<li key={w} className="break-words">⚠ {w}</li>))}@@ -213,17 +218,19 @@ function ReplyCardRow({)}{unconfirmed ? (- <p className="mt-2.5 text-xs text-fg-muted">+ <p className="mt-3 text-sm text-fg-muted">{mailbox} hasn't confirmed this was sent. Check your Sent folder in {mailbox}; this cardupdates on its own within a few minutes.</p>) : step.kind === "ask" || step.kind === "confirm" ? (- <div className="mt-2.5 rounded-md border border-indigo-500/30 bg-indigo-500/5 px-2.5 py-2">- {step.kind === "confirm" && <p className="text-xs text-amber-300">{step.message}</p>}- <p className="text-xs text-fg">{sendQuestion(step.recipients, mailbox)}</p>- <div className="mt-2 flex flex-wrap items-center gap-3">- <button- type="button"+ <div className="mt-4 rounded-xl border border-accent/30 bg-accent/5 px-3.5 py-3">+ {step.kind === "confirm" && (+ <p className="text-sm text-amber-700 dark:text-amber-300">{step.message}</p>+ )}+ <p className="text-sm text-fg">{sendQuestion(step.recipients, mailbox)}</p>+ <div className="mt-3 flex flex-wrap items-center gap-2">+ <Button+ variant="primary"onClick={() =>void send(step.kind === "confirm"@@ -231,50 +238,35 @@ function ReplyCardRow({: { recipients: step.recipients },)}- className="rounded-md bg-indigo-500 px-2.5 py-1 text-xs font-medium text-white hover:bg-indigo-400">{step.kind === "confirm" ? "Send anyway" : "Send now"}- </button>- <button- type="button"- onClick={() => setStep({ kind: "idle" })}- className="text-xs text-fg-muted hover:text-fg"- >+ </Button>+ <Button variant="ghost" onClick={() => setStep({ kind: "idle" })}>Cancel- </button>+ </Button></div></div>) : (- <div className="mt-2.5 flex flex-wrap items-center gap-3">- <button- type="button"+ <div className="mt-4 flex flex-wrap items-center gap-2">+ <Button+ variant="primary"onClick={() => setStep({ kind: "ask", recipients: card.draft_to })}- disabled={step.kind === "busy"}- className="rounded-md bg-indigo-500 px-2.5 py-1 text-xs font-medium text-white hover:bg-indigo-400 disabled:opacity-50"- >- {step.kind === "busy" ? step.label : "Send"}- </button>- {gmailLink && (- <a- href={gmailLink}- target="_blank"- rel="noopener noreferrer"- className="text-xs text-indigo-400 hover:text-indigo-300"- >- Edit in {mailbox} ↗- </a>- )}- <button- type="button"- onClick={() => void dismiss()}- disabled={step.kind === "busy"}- className="text-xs text-fg-muted hover:text-rose-300 transition-colors disabled:opacity-50"+ disabled={busy}>- Dismiss- </button>+ {busy ? step.label : "Send"}+ </Button>+ <OverflowMenu+ label="More actions for this reply"+ items={[+ ...(gmailLink+ ? [{ label: `Edit in ${mailbox}`, href: gmailLink, external: true }]+ : []),+ { label: "Dismiss", onSelect: () => void dismiss(), disabled: busy },+ ]}+ /></div>)}- {error && <p className="mt-1 text-xs text-red-400">{error}</p>}+ {error && <p className="mt-2 text-sm text-red-500">{error}</p>}</article>);}diff --git a/packages/ui/src/components/ReviewQueue.tsx b/packages/ui/src/components/ReviewQueue.tsxindex 6ff76d6b..19afa718 100644--- a/packages/ui/src/components/ReviewQueue.tsx+++ b/packages/ui/src/components/ReviewQueue.tsx@@ -24,26 +24,66 @@ import {updateBuiltinFile,} from "@/lib/api";import StatusPill from "@/components/ReviewStatusPill";+import Button from "@/components/ui/Button";+import OverflowMenu, { type OverflowItem } from "@/components/ui/OverflowMenu";+import SidePanel from "@/components/ui/SidePanel";+import SectionTabs from "@/components/ui/SectionTabs";+import Icon from "@/components/Icon";+import { domainBulkActions, type BulkAction } from "@/lib/reviewBulk";// ---------------------------------------------------------------------------// Helpers// ---------------------------------------------------------------------------const PRIORITY_CLASSES: Record<ReviewPriority, string> = {- high: "bg-blue-950/60 text-blue-400 border border-blue-900/60",+ high: "text-blue-500",normal: "",- low: "bg-surface-overlay/60 text-fg-muted border border-line-strong/60",+ low: "text-fg-subtle",};function PriorityPill({ priority }: { priority: ReviewPriority }) {if (priority === "normal") return null;return (- <span className={`text-[10px] font-medium px-1.5 py-0.5 rounded-full ${PRIORITY_CLASSES[priority]}`}>+ <span className={`text-xs font-medium ${PRIORITY_CLASSES[priority]}`}>{priority === "high" ? "↑ High priority" : "↓ Low priority"}</span>);}+const PRIORITY_LABELS: Record<ReviewPriority, string> = {+ high: "↑ High",+ normal: "Normal",+ low: "↓ Low",+};++/** The status actions an item offers besides Approve, plus its priority+ * choices; shared by a row's ⋯ menu and the item panel's. */+function itemMenu(+ item: ReviewItem,+ actions: {+ onView?: () => void;+ onFlag: () => void;+ onReject: () => void;+ onPriorityChange: (p: ReviewPriority) => void;+ },+): OverflowItem[] {+ const menu: OverflowItem[] = [];+ if (actions.onView) menu.push({ label: "View details", onSelect: actions.onView });+ if (item.status !== "needs_revision") menu.push({ label: "Flag for revision", onSelect: actions.onFlag });+ for (const p of ["high", "normal", "low"] as ReviewPriority[]) {+ menu.push({+ label: `Priority: ${PRIORITY_LABELS[p]}${item.priority === p ? " ✓" : ""}`,+ disabled: item.priority === p,+ onSelect: () => actions.onPriorityChange(p),+ });+ }+ if (item.status !== "rejected") menu.push({ label: "Reject…", danger: true, onSelect: actions.onReject });+ return menu;+}++const SELECT_CLASS =+ "h-10 rounded-xl border border-line-strong bg-surface-elevated px-3 text-sm text-fg focus:outline-none focus:ring-2 focus:ring-accent/50";+function formatDate(iso: string): string {return new Date(iso).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" });}@@ -56,10 +96,18 @@ function ItemSlideOver({itemId,onClose,onUpdated,+ onApprove,+ onFlag,+ onReject,+ onPriorityChange,}: {itemId: string;onClose: () => void;onUpdated: (item: ReviewItem) => void;+ onApprove: (item: ReviewItem) => Promise<void>;+ onFlag: (item: ReviewItem) => Promise<ReviewItem>;+ onReject: (item: ReviewItem) => void;+ onPriorityChange: (item: ReviewItem, p: ReviewPriority) => Promise<ReviewItem>;}) {const [detail, setDetail] = useState<{ item: ReviewItem; annotations: ReviewAnnotation[] } | null>(null);const [content, setContent] = useState<string | null>(null);@@ -179,57 +227,82 @@ function ItemSlideOver({onUpdated(updated);};- if (!detail) {- return (- <div className="fixed inset-0 z-50 flex justify-end">- <div className="absolute inset-0 bg-black/50" onClick={onClose} />- <div className="relative w-[560px] bg-surface-elevated border-l border-line flex items-center justify-center">- <span className="text-fg-muted text-sm">Loading…</span>- </div>- </div>- );- }-- const { item, annotations } = detail;- const isBuiltin = item.content_type === "builtin" || item.content_type === "failure";- const isExternal = item.content_type === "external";+ const item = detail?.item;+ const annotations = detail?.annotations ?? [];+ const isBuiltin = item?.content_type === "builtin" || item?.content_type === "failure";+ const isExternal = item?.content_type === "external";return (- <div className="fixed inset-0 z-50 flex justify-end">- <div className="absolute inset-0 bg-black/50" onClick={onClose} />- <div className="relative w-[600px] bg-surface-elevated border-l border-line flex flex-col overflow-hidden">- {/* Header */}- <div className="flex items-start justify-between px-5 py-4 border-b border-line flex-shrink-0">- <div>- <p className="text-sm font-medium text-fg">{item.filename}</p>- <div className="flex items-center gap-1.5 mt-1.5 flex-wrap">- <span className="text-[10px] bg-surface-overlay text-fg-muted border border-line-strong rounded px-1.5 py-0.5">{item.domain}</span>- <span className="text-[10px] bg-surface-overlay text-fg-muted border border-line-strong rounded px-1.5 py-0.5">{item.content_type}</span>- <StatusPill- status={item.status}- reviewedAt={item.reviewed_at}- trustedDefault={item.trusted_default}- />- <PriorityPill priority={item.priority} />- </div>+ <SidePanel+ open+ onClose={onClose}+ width="lg"+ title={<span className="block break-words">{item ? item.filename : "Loading…"}</span>}+ subtitle={+ item && (+ <span className="flex items-center gap-2 flex-wrap">+ <span className="capitalize">{item.domain}</span>+ <span aria-hidden>·</span>+ <span>{item.content_type}</span>+ <StatusPill+ status={item.status}+ reviewedAt={item.reviewed_at}+ trustedDefault={item.trusted_default}+ />+ <PriorityPill priority={item.priority} />+ </span>+ )+ }+ footer={+ item && (+ <div className="flex items-center gap-2">+ {item.status !== "approved" && (+ <Button+ variant="primary"+ onClick={async () => {+ await onApprove(item);+ onClose();+ }}+ >+ Approve+ </Button>+ )}+ <OverflowMenu+ placement="up"+ align="left"+ label="More review actions"+ items={itemMenu(item, {+ onFlag: async () => {+ const updated = await onFlag(item);+ setDetail((prev) => (prev ? { ...prev, item: updated } : prev));+ },+ onReject: () => {+ onReject(item);+ onClose();+ },+ onPriorityChange: async (p) => {+ const updated = await onPriorityChange(item, p);+ setDetail((prev) => (prev ? { ...prev, item: updated } : prev));+ },+ })}+ /></div>- <button onClick={onClose} className="text-fg-muted hover:text-fg p-1">- <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>- <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />- </svg>- </button>- </div>-- <div className="flex-1 overflow-y-auto p-5 space-y-6">+ )+ }+ >+ {!item ? (+ <p className="text-[15px] text-fg-muted">Loading…</p>+ ) : (+ <div className="space-y-7">{/* Builtin file content */}{isBuiltin && (<section><div className="flex items-center justify-between mb-2">- <p className="text-xs font-medium text-fg-muted uppercase tracking-wide">Document content</p>+ <p className="text-base font-semibold text-fg">Document content</p>{!editing && content != null && (<buttononClick={() => { setEditDraft(content); setEditing(true); }}- className="text-xs text-indigo-400 hover:text-indigo-300 transition-colors"+ className="h-9 px-2 text-sm font-medium text-accent hover:underline">Edit</button>@@ -240,30 +313,23 @@ function ItemSlideOver({<textareavalue={editDraft}onChange={(e) => setEditDraft(e.target.value)}- className="w-full h-72 bg-surface-elevated border border-line-strong rounded-lg px-3 py-2 text-xs text-fg font-mono resize-y focus:outline-none focus:border-indigo-500"+ className="w-full h-72 bg-surface-elevated border border-line-strong rounded-xl px-3 py-2 text-sm text-fg font-mono resize-y focus:outline-none focus:ring-2 focus:ring-accent/50"/><div className="flex gap-2">- <button- onClick={handleSaveEdit}- disabled={saving}- className="text-xs bg-indigo-600 hover:bg-indigo-500 text-white px-3 py-1.5 rounded-lg transition-colors disabled:opacity-50"- >+ <Button variant="primary" size="sm" className="!h-10" onClick={handleSaveEdit} disabled={saving}>{saving ? "Saving…" : "Save"}- </button>- <button- onClick={() => setEditing(false)}- className="text-xs text-fg-muted hover:text-fg px-3 py-1.5 rounded-lg transition-colors"- >+ </Button>+ <Button variant="ghost" size="sm" className="!h-10" onClick={() => setEditing(false)}>Cancel- </button>+ </Button></div></div>) : contentLoading ? (- <p className="text-xs text-fg-subtle">Loading…</p>+ <p className="text-sm text-fg-subtle">Loading…</p>) : contentError ? (- <p className="text-xs text-red-500/70">Could not load file content.</p>+ <p className="text-sm text-red-500">Could not load file content.</p>) : content != null ? (- <pre className="text-xs text-fg bg-surface-elevated/60 border border-line rounded-lg p-3 overflow-x-auto whitespace-pre-wrap font-mono max-h-96">{content}</pre>+ <pre className="text-sm text-fg bg-surface-overlay/50 border border-line rounded-xl p-3.5 overflow-x-auto whitespace-pre-wrap font-mono max-h-96">{content}</pre>) : null}</section>)}@@ -272,30 +338,30 @@ function ItemSlideOver({{isExternal && (<section><div className="flex items-center justify-between mb-2">- <p className="text-xs font-medium text-fg-muted uppercase tracking-wide">+ <p className="text-base font-semibold text-fg">Source content</p>- {loadingChunks && <span className="text-[10px] text-fg-subtle">Loading…</span>}+ {loadingChunks && <span className="text-sm text-fg-subtle">Loading…</span>}</div>- <p className="text-[11px] text-fg-subtle mb-3">+ <p className="text-sm text-fg-subtle mb-3">Indexed chunks from <span className="text-fg-muted">{item.filename}</span> — this is the text the AI retrieves from this source.</p>{!loadingChunks && externalChunks.length === 0 && (- <div className="bg-surface-elevated/60 border border-line rounded-lg p-4 text-center">- <p className="text-xs text-fg-muted mb-1">No indexed chunks found.</p>- <p className="text-[11px] text-fg-subtle">+ <div className="bg-surface-overlay/50 border border-line rounded-xl p-4 text-center">+ <p className="text-sm text-fg-muted mb-1">No indexed chunks found.</p>+ <p className="text-sm text-fg-subtle">Run <code className="bg-surface-overlay px-1 rounded font-mono">openexecutive ingest-oer</code> to index this source.</p></div>)}<div className="space-y-2">{externalChunks.map((chunk) => (- <div key={`${chunk.filename}:${chunk.chunk_index}`} className="bg-surface-elevated/60 border border-line rounded-lg p-3">+ <div key={`${chunk.filename}:${chunk.chunk_index}`} className="bg-surface-overlay/50 border border-line rounded-xl p-3.5"><div className="flex items-center gap-2 mb-1.5">- <span className="text-[10px] bg-surface-overlay text-fg-muted border border-line-strong rounded px-1.5 py-0.5">{chunk.domain}</span>- <span className="text-[10px] text-fg-subtle font-mono">{chunk.filename} · chunk {chunk.chunk_index}</span>+ <span className="text-xs text-fg-muted capitalize">{chunk.domain}</span>+ <span className="text-xs text-fg-subtle font-mono">{chunk.filename} · chunk {chunk.chunk_index}</span></div>- <p className="text-xs text-fg leading-relaxed">{chunk.text}</p>+ <p className="text-sm text-fg leading-relaxed">{chunk.text}</p></div>))}</div>@@ -303,7 +369,7 @@ function ItemSlideOver({<buttononClick={() => setExternalChunkLimit((n) => n + 10)}disabled={loadingChunks}- className="mt-3 text-xs text-fg-muted hover:text-fg transition-colors disabled:opacity-40"+ className="mt-3 h-10 text-sm font-medium text-accent hover:underline disabled:opacity-40">Load 10 more chunks…</button>@@ -313,42 +379,51 @@ function ItemSlideOver({{/* Notes */}<section>- <p className="text-xs font-medium text-fg-muted uppercase tracking-wide mb-2">Reviewer notes</p>+ <p className="text-base font-semibold text-fg mb-2">Reviewer notes</p><textareavalue={notes}onChange={(e) => setNotes(e.target.value)}onBlur={handleSaveNotes}placeholder="Add your review notes here…"- className="w-full h-20 bg-surface-elevated border border-line-strong rounded-lg px-3 py-2 text-xs text-fg resize-none focus:outline-none focus:border-indigo-500 placeholder:text-fg-subtle"+ className="w-full h-24 bg-surface-elevated border border-line-strong rounded-xl px-3 py-2 text-[15px] text-fg resize-none focus:outline-none focus:ring-2 focus:ring-accent/50 placeholder:text-fg-subtle"/></section>{/* Annotations */}<section>- <p className="text-xs font-medium text-fg-muted uppercase tracking-wide mb-2">- SME corrections- <span className="text-fg-subtle ml-1 normal-case font-normal">— injected into AI retrieval context</span>- </p>+ <p className="text-base font-semibold text-fg">SME corrections</p>+ <p className="text-sm text-fg-subtle mb-2">Injected into AI retrieval context.</p><div className="space-y-2">{annotations.map((ann) => (- <div key={ann.annotation_id} className={`flex items-start gap-2 p-2 rounded-lg border ${ann.is_active ? "bg-surface-elevated/60 border-line" : "bg-surface-elevated/20 border-line/40 opacity-50"}`}>- <p className="flex-1 text-xs text-fg">{ann.correction}</p>- <div className="flex items-center gap-1 flex-shrink-0">- <button- onClick={() => handleToggleAnnotation(ann)}- className={`text-[10px] px-1.5 py-0.5 rounded-full border transition-colors ${ann.is_active ? "bg-emerald-950/60 text-emerald-400 border-emerald-900/60 hover:bg-red-950/60 hover:text-red-400 hover:border-red-900/60" : "bg-surface-overlay/60 text-fg-muted border-line-strong/60 hover:bg-emerald-950/60 hover:text-emerald-400 hover:border-emerald-900/60"}`}- >+ <div+ key={ann.annotation_id}+ className={`flex items-start gap-3 px-3.5 py-2.5 rounded-xl border ${ann.is_active ? "bg-surface-overlay/50 border-line" : "border-line/60 opacity-60"}`}+ >+ <div className="flex-1 min-w-0">+ <p className="text-[15px] text-fg">{ann.correction}</p>+ <p className="mt-1 flex items-center gap-1.5 text-xs text-fg-muted">+ <span+ aria-hidden+ className={`h-2 w-2 rounded-full ${ann.is_active ? "bg-emerald-500" : "bg-fg-subtle"}`}+ />{ann.is_active ? "Active" : "Inactive"}- </button>- <button- onClick={() => handleDeleteAnnotation(ann.annotation_id)}- className="text-fg-subtle hover:text-red-400 transition-colors p-0.5"- >- <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>- <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />- </svg>- </button>+ </p></div>+ <OverflowMenu+ size="sm"+ label="Correction actions"+ items={[+ {+ label: ann.is_active ? "Turn off" : "Turn on",+ onSelect: () => void handleToggleAnnotation(ann),+ },+ {+ label: "Delete",+ danger: true,+ onSelect: () => void handleDeleteAnnotation(ann.annotation_id),+ },+ ]}+ /></div>))}<div className="flex gap-2">@@ -357,21 +432,21 @@ function ItemSlideOver({onChange={(e) => setNewCorrection(e.target.value)}onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); void handleAddAnnotation(); } }}placeholder="Add a correction or clarification…"- className="flex-1 bg-surface-elevated border border-line-strong rounded-lg px-3 py-1.5 text-xs text-fg focus:outline-none focus:border-indigo-500 placeholder:text-fg-subtle"+ aria-label="New correction"+ className="flex-1 min-w-0 h-11 bg-surface-elevated border border-line-strong rounded-xl px-3 text-[15px] text-fg focus:outline-none focus:ring-2 focus:ring-accent/50 placeholder:text-fg-subtle"/>- <button+ <ButtononClick={handleAddAnnotation}disabled={addingAnnotation || !newCorrection.trim()}- className="text-xs bg-surface-overlay hover:bg-surface-input text-fg px-3 py-1.5 rounded-lg transition-colors disabled:opacity-40">Add- </button>+ </Button></div></div></section></div>- </div>- </div>+ )}+ </SidePanel>);}@@ -395,6 +470,8 @@ export default function ReviewQueue() {const [rejectModal, setRejectModal] = useState<RejectModalState>(null);const [trustedDefaults, setTrustedDefaults] = useState<Record<string, number>>({});const [pendingItems, setPendingItems] = useState<ReviewItem[]>([]);+ // The domain the "Bulk actions" menu acts on ("" until one is picked).+ const [bulkDomain, setBulkDomain] = useState("");const loadQueue = useCallback(async () => {setLoading(true);@@ -462,6 +539,7 @@ export default function ReviewQueue() {const updated = await patchReviewItem(item.item_id, { status: "needs_revision" });setItems((prev) => prev.map((i) => (i.item_id === updated.item_id ? updated : i)));setAllItems((prev) => prev.map((i) => (i.item_id === updated.item_id ? updated : i)));+ return updated;};const handleRejectConfirm = async () => {@@ -479,6 +557,7 @@ export default function ReviewQueue() {const updated = await patchReviewItem(item.item_id, { priority });setItems((prev) => prev.map((i) => (i.item_id === updated.item_id ? updated : i)));setAllItems((prev) => prev.map((i) => (i.item_id === updated.item_id ? updated : i)));+ return updated;};const handleBulkApprove = async (domain?: string) => {@@ -520,79 +599,102 @@ export default function ReviewQueue() {]),).sort();+ const runBulk = (action: BulkAction) => {+ if (action.kind === "approve") void handleBulkApprove(action.domain);+ else void handleCurate(action.domain, action.kind === "curate-start" ? "start" : "stop");+ };++ const rowProps = (item: ReviewItem) => ({+ item,+ onApprove: () => handleApprove(item),+ onReject: () => setRejectModal({ itemId: item.item_id, notes: "" }),+ onFlag: () => void handleFlag(item),+ onView: () => setSelectedItemId(item.item_id),+ onPriorityChange: (p: ReviewPriority) => void handlePriorityChange(item, p),+ });++ // The bulk menu's domain: the picked one, else the list's domain filter,+ // else the first domain.+ const activeBulkDomain =+ (bulkDomain && domains.includes(bulkDomain) && bulkDomain) ||+ (filterDomain && domains.includes(filterDomain) && filterDomain) ||+ domains[0] ||+ "";+ const bulkActions = activeBulkDomain+ ? domainBulkActions(activeBulkDomain, pendingItems, trustedDefaults)+ : [];+ const curatable = Object.keys(trustedDefaults).sort((a, b) => a.localeCompare(b));+ const curateDomainPick = curatable.includes(bulkDomain) ? bulkDomain : curatable[0] ?? "";+// Rendered inside the Knowledge base workspace, which supplies the padding.return (- <div>- <div className="mb-4 max-w-2xl">- <h1 className="text-lg font-semibold text-fg">Review queue</h1>- <p className="text-sm text-fg-muted mt-1">+ <div className="max-w-4xl">+ <div className="mb-5 max-w-2xl">+ <p className="text-[15px] text-fg-muted">Approve, reject, or correct knowledge before the Executive relies on it.Pending and rejected items are withheld from retrieval.</p></div>- {/* Tabs */}- <div className="flex gap-1 border-b border-line mb-6">- {(["queue", "all", "annotations"] as Tab[]).map((t) => (- <button- key={t}- onClick={() => setTab(t)}- className={`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${- tab === t- ? "text-fg border-indigo-500"- : "text-fg-muted border-transparent hover:text-fg"- }`}- >- {t === "queue" ? "Review queue" : t === "all" ? "All items" : "Annotations"}- </button>- ))}- </div>+ <SectionTabs+ label="Review"+ className="mb-6"+ active={tab}+ onChange={setTab}+ tabs={[+ { id: "queue", label: "To review" },+ { id: "all", label: "All items" },+ { id: "annotations", label: "Annotations" },+ ]}+ />{/* Queue tab */}{tab === "queue" && (<div>- <div className="flex items-center justify-between mb-4">- <p className="text-sm text-fg-muted">+ <div className="flex items-center justify-between gap-3 mb-4">+ <p className="text-[15px] text-fg-muted">{loading ? "Loading…" : `${items.length} item${items.length !== 1 ? "s" : ""} need review`}</p>{items.length > 0 && (- <button- onClick={() => handleBulkApprove()}- className="text-xs bg-emerald-900/40 hover:bg-emerald-900/60 text-emerald-400 border border-emerald-900/60 px-3 py-1.5 rounded-lg transition-colors"- >- Approve all pending- </button>+ <Button onClick={() => handleBulkApprove()}>Approve all pending</Button>)}</div>{!loading && items.length === 0 && (- <div className="py-12 max-w-2xl mx-auto text-center">- <p className="text-sm text-fg">Nothing waiting on you.</p>- <p className="text-xs text-fg-muted mt-2 leading-relaxed">- The knowledge that ships with Open Executive is trusted by default — the- Executive can use it right away, and it does not sit here waiting for- sign-off. Items appear in this queue when you upload something new, edit an- existing file, or deliberately send a domain for review.- </p>- {Object.keys(trustedDefaults).length > 0 && (- <div className="mt-6 text-left">- <p className="text-[11px] uppercase tracking-wide text-fg-subtle mb-2">- Review a domain yourself- </p>- <p className="text-xs text-fg-muted mb-3 leading-relaxed">+ <div className="rounded-2xl border border-line bg-surface-elevated px-5 py-10 sm:px-8">+ <div className="max-w-xl mx-auto text-center">+ <p className="text-lg font-semibold text-fg">Nothing waiting on you.</p>+ <p className="text-[15px] text-fg-muted mt-2 leading-relaxed">+ The knowledge that ships with Open Executive is trusted by default — the+ Executive can use it right away, and it does not sit here waiting for+ sign-off. Items appear in this queue when you upload something new, edit an+ existing file, or deliberately send a domain for review.+ </p>+ </div>+ {curatable.length > 0 && (+ <div className="mt-8 max-w-xl mx-auto border-t border-line pt-6">+ <p className="text-base font-semibold text-fg">Review a domain yourself</p>+ <p className="text-sm text-fg-muted mt-1 mb-3 leading-relaxed">Sending a domain for review withholds it from the Executive until youwork through it.</p>- <div className="flex gap-2 flex-wrap">- {Object.entries(trustedDefaults)- .sort(([a], [b]) => a.localeCompare(b))- .map(([domain, count]) => (- <button- key={domain}- onClick={() => handleCurate(domain, "start")}- className="text-[11px] text-fg-muted hover:text-amber-400 bg-surface-elevated border border-line-strong hover:border-amber-900/60 px-2.5 py-1.5 rounded-lg transition-colors"- >- Curate {domain} ({count})- </button>+ <div className="flex flex-col sm:flex-row gap-2">+ <select+ value={curateDomainPick}+ onChange={(e) => setBulkDomain(e.target.value)}+ aria-label="Domain to review"+ className={`${SELECT_CLASS} !h-11 flex-1 capitalize`}+ >+ {curatable.map((domain) => (+ <option key={domain} value={domain}>+ {domain} ({trustedDefaults[domain]})+ </option>))}+ </select>+ <Button+ onClick={() => curateDomainPick && handleCurate(curateDomainPick, "start")}+ disabled={!curateDomainPick}+ >+ Curate {curateDomainPick}+ </Button></div></div>)}@@ -600,15 +702,7 @@ export default function ReviewQueue() {)}<div className="space-y-2">{items.map((item) => (- <ItemRow- key={item.item_id}- item={item}- onApprove={() => handleApprove(item)}- onReject={() => setRejectModal({ itemId: item.item_id, notes: "" })}- onFlag={() => handleFlag(item)}- onView={() => setSelectedItemId(item.item_id)}- onPriorityChange={(p) => handlePriorityChange(item, p)}- />+ <ItemRow key={item.item_id} {...rowProps(item)} />))}</div></div>@@ -622,7 +716,8 @@ export default function ReviewQueue() {<selectvalue={filterStatus}onChange={(e) => setFilterStatus(e.target.value as ReviewStatus | "")}- className="bg-surface-elevated border border-line-strong rounded-lg px-3 py-1.5 text-xs text-fg focus:outline-none focus:border-indigo-500"+ aria-label="Status"+ className={SELECT_CLASS}><option value="">All statuses</option><option value="pending">Pending</option>@@ -633,7 +728,8 @@ export default function ReviewQueue() {<selectvalue={filterDomain}onChange={(e) => setFilterDomain(e.target.value)}- className="bg-surface-elevated border border-line-strong rounded-lg px-3 py-1.5 text-xs text-fg focus:outline-none focus:border-indigo-500"+ aria-label="Domain"+ className={SELECT_CLASS}><option value="">All domains</option>{domains.map((d) => <option key={d} value={d}>{d}</option>)}@@ -641,7 +737,8 @@ export default function ReviewQueue() {<selectvalue={filterType}onChange={(e) => setFilterType(e.target.value as "builtin" | "external" | "")}- className="bg-surface-elevated border border-line-strong rounded-lg px-3 py-1.5 text-xs text-fg focus:outline-none focus:border-indigo-500"+ aria-label="Type"+ className={SELECT_CLASS}><option value="">All types</option><option value="builtin">Built-in</option>@@ -650,69 +747,40 @@ export default function ReviewQueue() {</select></div>- {/* Per-domain actions: approve what's queued, or start/stop curating. */}+ {/* Bulk actions for one domain at a time: approve what's queued, or+ start / stop curating it. */}{domains.length > 0 && (- <div className="flex gap-2 mb-4 flex-wrap">- {domains.map((d) => {- const pendingInDomain = pendingItems.filter((i) => i.domain === d);- // "Stop curating" reverses queue_for_curation, whose selector is- // `trusted_default = 1 AND reviewed_at IS NULL`. Mirror BOTH: a- // user's own upload is pending with no timestamp too, and- // counting it would render a button that does nothing.- const untouchedPending = pendingInDomain.filter(- (i) => i.trusted_default && i.reviewed_at == null,- ).length;- const defaultsInDomain = trustedDefaults[d] ?? 0;- return (- <div key={d} className="flex gap-1">- {pendingInDomain.length > 0 && (- <button- onClick={() => handleBulkApprove(d)}- className="text-[10px] text-fg-muted hover:text-emerald-400 bg-surface-elevated border border-line-strong hover:border-emerald-900/60 px-2 py-1 rounded-lg transition-colors"- >- Approve all pending in {d}- </button>- )}- {untouchedPending > 0 ? (- <button- onClick={() => handleCurate(d, "stop")}- className="text-[10px] text-fg-muted hover:text-fg bg-surface-elevated border border-line-strong px-2 py-1 rounded-lg transition-colors"- title={`Return ${untouchedPending} unreviewed item(s) in ${d} to trusted default`}- >- Stop curating {d}- </button>- ) : (- defaultsInDomain > 0 && (- <button- onClick={() => handleCurate(d, "start")}- className="text-[10px] text-fg-muted hover:text-amber-400 bg-surface-elevated border border-line-strong hover:border-amber-900/60 px-2 py-1 rounded-lg transition-colors"- title={`Send ${defaultsInDomain} shipped item(s) in ${d} for review — they will be withheld from the Executive until approved`}- >- Curate {d} ({defaultsInDomain})- </button>- )- )}- </div>- );- })}+ <div className="mb-5 flex flex-col sm:flex-row sm:items-center gap-2 rounded-2xl border border-line bg-surface-overlay/50 px-4 py-3">+ <span className="text-sm font-semibold text-fg">Bulk actions</span>+ <select+ value={activeBulkDomain}+ onChange={(e) => setBulkDomain(e.target.value)}+ aria-label="Domain for bulk actions"+ className={`${SELECT_CLASS} capitalize`}+ >+ {domains.map((d) => <option key={d} value={d}>{d}</option>)}+ </select>+ <div className="flex items-center gap-2 flex-wrap sm:ml-auto">+ {bulkActions.length === 0 ? (+ <span className="text-sm text-fg-subtle">Nothing to do in {activeBulkDomain}.</span>+ ) : (+ bulkActions.map((a) => (+ <Button key={a.kind} size="sm" className="!h-10" title={a.detail} onClick={() => runBulk(a)}>+ {a.label}+ </Button>+ ))+ )}+ </div></div>)}- {loading && <p className="text-sm text-fg-subtle">Loading…</p>}+ {loading && <p className="text-[15px] text-fg-subtle">Loading…</p>}<div className="space-y-2">{allItems.map((item) => (- <ItemRow- key={item.item_id}- item={item}- onApprove={() => handleApprove(item)}- onReject={() => setRejectModal({ itemId: item.item_id, notes: "" })}- onFlag={() => handleFlag(item)}- onView={() => setSelectedItemId(item.item_id)}- onPriorityChange={(p) => handlePriorityChange(item, p)}- />+ <ItemRow key={item.item_id} {...rowProps(item)} />))}{!loading && allItems.length === 0 && (- <p className="text-sm text-fg-subtle py-8 text-center">No items match the filters.</p>+ <p className="text-[15px] text-fg-subtle py-8 text-center">No items match the filters.</p>)}</div></div>@@ -721,39 +789,41 @@ export default function ReviewQueue() {{/* Annotations tab */}{tab === "annotations" && (<div>- <p className="text-sm text-fg-muted mb-4">+ <p className="text-[15px] text-fg-muted mb-4">{loading ? "Loading…" : `${annotations.length} active SME correction${annotations.length !== 1 ? "s" : ""}`}</p><div className="space-y-2">{annotations.map((ann) => (- <div key={ann.annotation_id} className="bg-surface-elevated/40 border border-line rounded-lg p-3 flex items-start gap-3">- <div className="flex-1">- <div className="flex items-center gap-2 mb-1">- <span className="text-[10px] bg-surface-overlay text-fg-muted border border-line-strong rounded px-1.5 py-0.5">{ann.domain}</span>- <span className="text-[10px] text-fg-subtle">{ann.item_id}</span>+ <div key={ann.annotation_id} className="bg-surface-elevated border border-line rounded-2xl px-4 py-3.5 flex items-start gap-3">+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 mb-1 flex-wrap text-xs text-fg-muted">+ <span className="capitalize font-medium">{ann.domain}</span>+ <span className="text-fg-subtle break-all">{ann.item_id}</span></div>- <p className="text-xs text-fg">{ann.correction}</p>- </div>- <div className="flex items-center gap-1 flex-shrink-0">- <button- onClick={() => void patchAnnotation(ann.annotation_id, { is_active: false }).then(loadAnnotations)}- className="text-[10px] bg-emerald-950/60 text-emerald-400 border border-emerald-900/60 px-1.5 py-0.5 rounded-full hover:bg-red-950/60 hover:text-red-400 hover:border-red-900/60 transition-colors"- >+ <p className="text-[15px] text-fg">{ann.correction}</p>+ <p className="mt-1 flex items-center gap-1.5 text-xs text-fg-muted">+ <span aria-hidden className="h-2 w-2 rounded-full bg-emerald-500" />Active- </button>- <button- onClick={() => void deleteAnnotation(ann.annotation_id).then(loadAnnotations)}- className="text-fg-subtle hover:text-red-400 p-0.5"- >- <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>- <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />- </svg>- </button>+ </p></div>+ <OverflowMenu+ label="Correction actions"+ items={[+ {+ label: "Turn off",+ onSelect: () => void patchAnnotation(ann.annotation_id, { is_active: false }).then(loadAnnotations),+ },+ {+ label: "Delete",+ danger: true,+ onSelect: () => void deleteAnnotation(ann.annotation_id).then(loadAnnotations),+ },+ ]}+ /></div>))}{!loading && annotations.length === 0 && (- <p className="text-sm text-fg-subtle py-8 text-center">No active corrections. Open a review item to add one.</p>+ <p className="text-[15px] text-fg-subtle py-8 text-center">No active corrections. Open a review item to add one.</p>)}</div></div>@@ -761,40 +831,45 @@ export default function ReviewQueue() {{/* Reject modal */}{rejectModal && (- <div className="fixed inset-0 z-50 flex items-center justify-center">+ <div className="fixed inset-0 z-[60] flex items-center justify-center p-4"><div className="absolute inset-0 bg-black/60" onClick={() => setRejectModal(null)} />- <div className="relative bg-surface-elevated border border-line-strong rounded-xl p-5 w-[400px] shadow-2xl">- <p className="text-sm font-medium text-fg mb-3">Reject item</p>+ <div+ role="dialog"+ aria-modal="true"+ aria-label="Reject item"+ className="relative bg-surface-elevated border border-line rounded-2xl p-5 w-full max-w-md shadow-2xl"+ >+ <p className="text-lg font-semibold text-fg mb-3">Reject item</p><textareavalue={rejectModal.notes}onChange={(e) => setRejectModal({ ...rejectModal, notes: e.target.value })}placeholder="Optional notes about why this is rejected…"- className="w-full h-24 bg-surface-elevated border border-line-strong rounded-lg px-3 py-2 text-xs text-fg resize-none focus:outline-none focus:border-red-500 placeholder:text-fg-subtle mb-3"+ aria-label="Why it is rejected"+ autoFocus+ className="w-full h-28 bg-surface-elevated border border-line-strong rounded-xl px-3 py-2 text-[15px] text-fg resize-none focus:outline-none focus:ring-2 focus:ring-red-500/40 placeholder:text-fg-subtle mb-4"/><div className="flex gap-2 justify-end">- <button- onClick={() => setRejectModal(null)}- className="text-xs text-fg-muted hover:text-fg px-3 py-1.5 rounded-lg transition-colors"- >+ <Button variant="ghost" onClick={() => setRejectModal(null)}>Cancel- </button>- <button- onClick={handleRejectConfirm}- className="text-xs bg-red-900/40 hover:bg-red-900/60 text-red-400 border border-red-900/60 px-3 py-1.5 rounded-lg transition-colors"- >+ </Button>+ <Button variant="danger" onClick={handleRejectConfirm}>Reject- </button>+ </Button></div></div></div>)}- {/* Slide-over */}+ {/* Item panel */}{selectedItemId && (<ItemSlideOveritemId={selectedItemId}onClose={() => setSelectedItemId(null)}onUpdated={handleItemUpdated}+ onApprove={handleApprove}+ onFlag={handleFlag}+ onReject={(item) => setRejectModal({ itemId: item.item_id, notes: "" })}+ onPriorityChange={handlePriorityChange}/>)}</div>@@ -820,80 +895,51 @@ function ItemRow({onView: () => void;onPriorityChange: (p: ReviewPriority) => void;}) {+ const fileBacked = item.content_type === "builtin" || item.content_type === "failure";return (- <div className="bg-surface-elevated/40 border border-line rounded-lg px-4 py-3 flex items-center gap-3">- {/* Icon */}- <div className="flex-shrink-0 text-fg-subtle">- {item.content_type === "builtin" || item.content_type === "failure" ? (- <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>- <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />- </svg>- ) : (- <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>- <path strokeLinecap="round" strokeLinejoin="round" d="M12 6.042A8.967 8.967 0 006 3.75c-1.052 0-2.062.18-3 .512v14.25A8.987 8.987 0 016 18c2.305 0 4.408.867 6 2.292m0-14.25a8.966 8.966 0 016-2.292c1.052 0 2.062.18 3 .512v14.25A8.987 8.987 0 0018 18a8.967 8.967 0 00-6 2.292m0-14.25v14.25" />- </svg>- )}- </div>+ <div className="bg-surface-elevated border border-line rounded-2xl px-4 py-3.5 sm:px-5 flex items-center gap-3 sm:gap-4">+ <span className="hidden sm:flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-surface-overlay text-fg-muted">+ <Icon name={fileBacked ? "doc" : "book"} size="w-5 h-5" />+ </span>- {/* Info */}<div className="flex-1 min-w-0">- <div className="flex items-center gap-2 flex-wrap">- <span className="text-sm text-fg font-medium truncate">{item.filename}</span>- <span className="text-[10px] bg-surface-overlay text-fg-muted border border-line-strong rounded px-1.5 py-0.5">{item.domain}</span>+ <button+ onClick={onView}+ className="block max-w-full truncate text-left text-[15px] font-semibold text-fg hover:text-accent transition-colors"+ >+ {item.filename}+ </button>+ <div className="mt-1 flex items-center gap-2 flex-wrap text-sm text-fg-muted">+ <span className="capitalize">{item.domain}</span><StatusPill- status={item.status}- reviewedAt={item.reviewed_at}- trustedDefault={item.trusted_default}- />+ status={item.status}+ reviewedAt={item.reviewed_at}+ trustedDefault={item.trusted_default}+ /><PriorityPill priority={item.priority} />+ <span className="text-fg-subtle">Added {formatDate(item.registered_at)}</span></div>- <p className="text-[11px] text-fg-subtle mt-0.5">Added {formatDate(item.registered_at)}</p></div>- {/* Priority selector */}- <select- value={item.priority}- onChange={(e) => onPriorityChange(e.target.value as ReviewPriority)}- className="bg-surface-elevated border border-line-strong rounded-lg px-2 py-1 text-[10px] text-fg-muted focus:outline-none focus:border-indigo-500"- title="Set priority"- >- <option value="low">↓ Low</option>- <option value="normal">Normal</option>- <option value="high">↑ High</option>- </select>-- {/* Actions */}<div className="flex items-center gap-1 flex-shrink-0">- <button- onClick={onView}- className="text-[10px] text-fg-muted hover:text-fg bg-surface-overlay hover:bg-surface-input border border-line-strong px-2 py-1 rounded-lg transition-colors"- >- View- </button>- {item.status !== "approved" && (- <button- onClick={onApprove}- className="text-[10px] text-emerald-400 hover:text-emerald-300 bg-emerald-950/40 hover:bg-emerald-950/60 border border-emerald-900/60 px-2 py-1 rounded-lg transition-colors"- >+ {item.status !== "approved" ? (+ <Button variant="primary" size="sm" className="!h-10" onClick={onApprove}>Approve- </button>- )}- {item.status !== "needs_revision" && (- <button- onClick={onFlag}- className="text-[10px] text-violet-400 hover:text-violet-300 bg-violet-950/40 hover:bg-violet-950/60 border border-violet-900/60 px-2 py-1 rounded-lg transition-colors"- >- Flag- </button>- )}- {item.status !== "rejected" && (- <button- onClick={onReject}- className="text-[10px] text-red-400 hover:text-red-300 bg-red-950/40 hover:bg-red-950/60 border border-red-900/60 px-2 py-1 rounded-lg transition-colors"- >- Reject- </button>+ </Button>+ ) : (+ <Button size="sm" className="!h-10" onClick={onView}>+ View+ </Button>)}+ <OverflowMenu+ label={`More actions for ${item.filename}`}+ items={itemMenu(item, {+ onView: item.status !== "approved" ? onView : undefined,+ onFlag,+ onReject,+ onPriorityChange,+ })}+ /></div></div>);diff --git a/packages/ui/src/components/ReviewStatusPill.tsx b/packages/ui/src/components/ReviewStatusPill.tsxindex f6b8d0c1..81818114 100644--- a/packages/ui/src/components/ReviewStatusPill.tsx+++ b/packages/ui/src/components/ReviewStatusPill.tsx@@ -10,15 +10,15 @@ const STATUS_LABELS: Record<ReviewStatus, string> = {needs_revision: "Needs revision",};-const STATUS_CLASSES: Record<ReviewStatus, string> = {- pending: "bg-amber-950/60 text-amber-400 border border-amber-900/60",- approved: "bg-emerald-950/60 text-emerald-400 border border-emerald-900/60",- rejected: "bg-red-950/60 text-red-400 border border-red-900/60",- needs_revision: "bg-violet-950/60 text-violet-400 border border-violet-900/60",+// Status is a coloured dot plus a word.+const STATUS_DOT: Record<ReviewStatus, string> = {+ pending: "bg-amber-500",+ approved: "bg-emerald-500",+ rejected: "bg-red-500",+ needs_revision: "bg-violet-500",};-const TRUSTED_DEFAULT_CLASS =- "bg-surface-overlay/60 text-fg-muted border border-line-strong/60";+const TRUSTED_DEFAULT_DOT = "bg-fg-subtle";export default function ReviewStatusPill({status,@@ -35,15 +35,17 @@ export default function ReviewStatusPill({const trusted = trustedDefault === true && status === "approved" && reviewedAt == null;return (<span- className={`text-[10px] font-medium px-1.5 py-0.5 rounded-full ${- trusted ? TRUSTED_DEFAULT_CLASS : STATUS_CLASSES[status]- }`}+ className="inline-flex items-center gap-1.5 text-sm font-medium text-fg-muted"title={trusted? "Ships with Open Executive. Available to the Executive, but nobody here has reviewed it.": undefined}>+ <span+ aria-hidden+ className={`h-2 w-2 rounded-full ${trusted ? TRUSTED_DEFAULT_DOT : STATUS_DOT[status]}`}+ />{trusted ? "Default" : STATUS_LABELS[status]}</span>);diff --git a/packages/ui/src/components/RosterRequestCard.tsx b/packages/ui/src/components/RosterRequestCard.tsxindex 558ffad6..b15967f5 100644--- a/packages/ui/src/components/RosterRequestCard.tsx+++ b/packages/ui/src/components/RosterRequestCard.tsx@@ -2,12 +2,16 @@// A roster request on the briefing: someone not on the People list wrote in,// was told their message arrived, and is held until the principal says who-// they are. Answered here (never through chat): add them as a new person,-// say they are someone already on the list, or ignore them. Their held-// messages are answered once they are added.+// they are. Answered here (never through chat): "Add them" opens a side+// panel to add them as a new person or say they are someone already on the+// list; Ignore is in the card's ⋯ menu. Their held messages are answered+// once they are added.import { useEffect, useState } from "react";+import Button from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";+import SidePanel from "@/components/ui/SidePanel";import {approveRosterRequest,declineRosterRequest,@@ -46,6 +50,8 @@ export default function RosterRequestCard({const [replace, setReplace] = useState(false);const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);+ // The answer (add new / link to someone listed) is given in a side panel.+ const [panelOpen, setPanelOpen] = useState(false);const channel = CHANNEL_LABEL[request.channel] ?? request.channel;const isChat = request.channel !== "email";@@ -90,142 +96,158 @@ export default function RosterRequestCard({);}- const rowAccent = emphasized ? " border-l-2 border-indigo-500 pl-3" : "";+ const ignore = () => void run(() => declineRosterRequest(request.id));+ const title = request.display_name ? `Who is ${request.display_name}?` : "Someone new wrote in";+ const fieldClass =+ "min-h-[44px] rounded-xl border border-line bg-surface px-3 text-[15px] text-fg focus:outline-none focus:ring-2 focus:ring-accent/40 disabled:opacity-50";+return (- <div className={`py-3${rowAccent}`}>- <div className="flex items-start justify-between gap-2 mb-1">- <div className="min-w-0">- <div className="text-sm font-medium text-fg break-words">- {request.display_name ? `Who is ${request.display_name}?` : "Someone new wrote in"}- </div>- <div className="mt-0.5 text-xs text-fg-muted break-all">- {channel} · {request.channel_ref}- {request.profile_email ? ` · ${request.profile_email}` : ""}- </div>- </div>- <div className="flex flex-shrink-0 flex-wrap justify-end gap-1">- {request.on_company_domain && (- <span className="inline-block px-1.5 py-0.5 rounded border text-[10px] bg-emerald-500/15 text-emerald-300 border-emerald-500/30">- your domain- </span>- )}- <span className="inline-block px-1.5 py-0.5 rounded border text-[10px] text-fg-muted border-line">- {request.message_count} waiting+ <div+ className={`rounded-2xl border bg-surface-elevated p-4 sm:p-5 ${+ emphasized ? "border-accent/60 ring-1 ring-accent/25 shadow-sm" : "border-line"+ }`}+ >+ <div className="text-base sm:text-[17px] font-semibold leading-snug text-fg break-words">{title}</div>+ <div className="mt-1 text-sm text-fg-muted break-all">+ {channel} · {request.channel_ref}+ {request.profile_email ? ` · ${request.profile_email}` : ""}+ </div>+ <div className="mt-2 flex flex-wrap gap-1.5">+ <span className="inline-flex items-center rounded-lg bg-surface-overlay px-2 py-0.5 text-[13px] font-medium text-fg-muted">+ {request.message_count} waiting+ </span>+ {request.on_company_domain && (+ <span className="inline-flex items-center rounded-lg bg-emerald-500/15 px-2 py-0.5 text-[13px] font-medium text-emerald-700 dark:text-emerald-300">+ your domain</span>- </div>+ )}</div>-- <p className="text-xs text-fg-muted leading-snug mb-2">- Not on your People list.{" "}- {request.ack_sent- ? "They were told their message arrived and is waiting for you."- : "They haven't been answered."}{" "}- The name is the one they gave — not verified.- </p>-- {request.previews.length > 0 && (- <div className="mb-2 rounded-lg border border-line bg-surface/40 px-3 py-2 space-y-1">- {request.previews.slice(0, 3).map((line, i) => (- <p key={i} className="text-xs text-fg-muted whitespace-pre-wrap break-words">- {line}- </p>- ))}- </div>- )}-- <div className="flex gap-3 text-xs mb-2" role="radiogroup" aria-label="Who they are">- <label className="flex items-center gap-1 text-fg">- <input- type="radio"- checked={mode === "new"}- onChange={() => setMode("new")}- disabled={busy}- />- Add as a new person- </label>- <label className="flex items-center gap-1 text-fg">- <input- type="radio"- checked={mode === "link"}- onChange={() => setMode("link")}- disabled={busy}- />- Someone already on the list- </label>+ {error && !panelOpen && <p className="mt-2 text-sm text-rose-600 dark:text-rose-300">{error}</p>}+ <div className="mt-4 flex flex-wrap items-center gap-2">+ <Button variant="primary" onClick={() => setPanelOpen(true)} disabled={busy}>+ Add them+ </Button>+ <OverflowMenu+ label="More actions for this request"+ items={[+ {+ label: "Someone already on the list",+ onSelect: () => {+ setMode("link");+ setPanelOpen(true);+ },+ disabled: busy,+ },+ { label: "Ignore", onSelect: ignore, disabled: busy },+ ]}+ /></div>- {mode === "new" ? (- <div className="flex flex-wrap items-center gap-2 mb-2">- <input- type="text"- value={name}- onChange={(e) => setName(e.target.value)}- placeholder="Their name"- maxLength={200}- disabled={busy}- className="min-w-0 flex-1 text-xs text-fg bg-surface border border-line rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-indigo-500/40"- />- <select- value={kind}- onChange={(e) => setKind(e.target.value as PersonKind | "")}- disabled={busy}- className="text-xs text-fg bg-surface border border-line rounded px-2 py-1"- >- <option value="">Team or contact?</option>- <option value="team">Team — can sign in and message you</option>- <option value="contact">Contact — emailed only when you ask</option>- </select>- </div>- ) : (- <div className="flex flex-wrap items-center gap-2 mb-2">- <select- value={linkId}- onChange={(e) => setLinkId(e.target.value === "" ? "" : Number(e.target.value))}- disabled={busy || people === null}- className="min-w-0 flex-1 text-xs text-fg bg-surface border border-line rounded px-2 py-1"- >- <option value="">{people === null ? "Loading…" : "Choose who they are"}</option>- {(people ?? []).map((p) => (- <option key={p.id} value={p.id}>- {p.full_name}- {p.kind === "contact" ? " (contact)" : ""}- </option>+ {/* Who they are — add as new or link to someone on the list — is+ answered in a side panel, with what they wrote. */}+ <SidePanel+ open={panelOpen}+ onClose={() => setPanelOpen(false)}+ title={title}+ subtitle={`${channel} · ${request.channel_ref}`}+ footer={+ <div className="flex flex-wrap justify-end gap-2">+ <Button variant="ghost" onClick={ignore} disabled={busy}>+ Ignore+ </Button>+ <Button variant="primary" onClick={approve} disabled={busy || !canAdd}>+ {mode === "new" ? "Add them" : "That's them"}+ </Button>+ </div>+ }+ >+ <p className="mb-3 text-sm leading-relaxed text-fg-muted">+ Not on your People list.{" "}+ {request.ack_sent+ ? "They were told their message arrived and is waiting for you."+ : "They haven't been answered."}{" "}+ The name is the one they gave — not verified. Once they are added, their {request.message_count}{" "}+ waiting message{request.message_count === 1 ? " is" : "s are"} answered.+ </p>++ {request.previews.length > 0 && (+ <div className="mb-4 space-y-1.5 rounded-xl border border-line bg-surface/40 px-3.5 py-2.5">+ {request.previews.slice(0, 3).map((line, i) => (+ <p key={i} className="text-sm text-fg-muted whitespace-pre-wrap break-words">+ {line}+ </p>))}- </select>- {isChat && (- <label className="flex items-center gap-1 text-[11px] text-fg-muted">- <input- type="checkbox"- checked={replace}- onChange={(e) => setReplace(e.target.checked)}- disabled={busy}- />- Replace their current {channel} account- </label>- )}+ </div>+ )}++ <div className="mb-4 flex flex-col gap-2" role="radiogroup" aria-label="Who they are">+ <label className="flex min-h-[44px] items-center gap-2.5 rounded-xl border border-line px-3 text-[15px] text-fg">+ <input type="radio" checked={mode === "new"} onChange={() => setMode("new")} disabled={busy} />+ Add as a new person+ </label>+ <label className="flex min-h-[44px] items-center gap-2.5 rounded-xl border border-line px-3 text-[15px] text-fg">+ <input type="radio" checked={mode === "link"} onChange={() => setMode("link")} disabled={busy} />+ Someone already on the list+ </label></div>- )}-- {error && <p className="text-xs text-rose-300 mb-2">{error}</p>}-- <div className="flex justify-end gap-2">- <button- type="button"- onClick={() => void run(() => declineRosterRequest(request.id))}- disabled={busy}- className="text-xs text-fg-muted hover:text-fg px-2 py-1 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"- >- Ignore- </button>- <button- type="button"- onClick={approve}- disabled={busy || !canAdd}- className="text-xs font-medium text-emerald-300 hover:text-emerald-200 px-2 py-1 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"- >- {mode === "new" ? "✓ Add them" : "✓ That's them"}- </button>- </div>++ {mode === "new" ? (+ <div className="flex flex-col gap-2">+ <input+ type="text"+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="Their name"+ aria-label="Their name"+ maxLength={200}+ disabled={busy}+ className={fieldClass}+ />+ <select+ value={kind}+ onChange={(e) => setKind(e.target.value as PersonKind | "")}+ disabled={busy}+ aria-label="Team or contact"+ className={fieldClass}+ >+ <option value="">Team or contact?</option>+ <option value="team">Team — can sign in and message you</option>+ <option value="contact">Contact — emailed only when you ask</option>+ </select>+ </div>+ ) : (+ <div className="flex flex-col gap-2">+ <select+ value={linkId}+ onChange={(e) => setLinkId(e.target.value === "" ? "" : Number(e.target.value))}+ disabled={busy || people === null}+ aria-label="Who they are"+ className={fieldClass}+ >+ <option value="">{people === null ? "Loading…" : "Choose who they are"}</option>+ {(people ?? []).map((p) => (+ <option key={p.id} value={p.id}>+ {p.full_name}+ {p.kind === "contact" ? " (contact)" : ""}+ </option>+ ))}+ </select>+ {isChat && (+ <label className="flex min-h-[44px] items-center gap-2 text-sm text-fg-muted">+ <input+ type="checkbox"+ checked={replace}+ onChange={(e) => setReplace(e.target.checked)}+ disabled={busy}+ />+ Replace their current {channel} account+ </label>+ )}+ </div>+ )}++ {error && <p className="mt-3 text-sm text-rose-600 dark:text-rose-300">{error}</p>}+ </SidePanel></div>);}diff --git a/packages/ui/src/components/TimeframePicker.tsx b/packages/ui/src/components/TimeframePicker.tsxindex 5d628852..ba707d09 100644--- a/packages/ui/src/components/TimeframePicker.tsx+++ b/packages/ui/src/components/TimeframePicker.tsx@@ -85,11 +85,11 @@ export function TimeframeChips({onChange: (periodType: PeriodType, periodValue: string) => void;}) {return (- <div className="flex flex-col gap-1">- <span className="text-xs text-fg-muted" id="timeframe-chips-label">+ <div className="flex flex-col gap-1.5">+ <span className="text-sm text-fg-muted" id="timeframe-chips-label">Timeframe</span>- <div role="radiogroup" aria-labelledby="timeframe-chips-label" className="flex flex-wrap gap-1.5">+ <div role="radiogroup" aria-labelledby="timeframe-chips-label" className="flex flex-wrap gap-2">{PERIOD_TYPES.map((p) => {const selected = p.value === periodType;return (@@ -101,9 +101,9 @@ export function TimeframeChips({onClick={() => onChange(p.value, suggestPeriodValue(p.value))}title={p.value === "ongoing" ? undefined : suggestPeriodValue(p.value)}className={- "px-2.5 py-1 rounded-full border text-xs transition-colors cursor-pointer focus:outline-none focus:ring-2 focus:ring-indigo-500/50 " ++ "h-10 px-4 rounded-full border text-[15px] transition-colors cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/60 " +(selected- ? "border-indigo-500/70 bg-indigo-500/10 text-fg font-medium"+ ? "border-accent/70 bg-accent/10 text-fg font-medium": "border-line text-fg-muted hover:text-fg hover:border-line-strong")}>@@ -134,12 +134,12 @@ export default function TimeframePicker({PERIOD_TYPES.find((p) => p.value === periodType)?.placeholder ?? "";const inputCls =size === "compact"- ? "px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- : "px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500";+ ? "h-11 px-3 rounded-xl bg-surface-input/60 border border-line text-[15px] text-fg focus:outline-none focus:border-accent"+ : "h-11 px-3 rounded-xl bg-surface-input/60 border border-line text-[15px] text-fg focus:outline-none focus:border-accent";return (- <div className="grid grid-cols-2 gap-2">- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <div className="grid grid-cols-2 gap-3">+ <label className="text-sm text-fg-muted flex flex-col gap-1.5">Timeframe<selectvalue={periodType}@@ -157,7 +157,7 @@ export default function TimeframePicker({</select></label>{periodType !== "ongoing" && (- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className="text-sm text-fg-muted flex flex-col gap-1.5">Period<inputvalue={periodValue}diff --git a/packages/ui/src/components/UserBadge.tsx b/packages/ui/src/components/UserBadge.tsxindex 745d8b89..fc135bac 100644--- a/packages/ui/src/components/UserBadge.tsx+++ b/packages/ui/src/components/UserBadge.tsx@@ -2,8 +2,19 @@import { signOut, useSession } from "next-auth/react";+import { GUIDE_NAV_ITEM } from "@/components/shell/navConfig";+import OverflowMenu, { type OverflowItem } from "@/components/ui/OverflowMenu";++// The account menu at the foot of the sidebar: help, the Executive's+// pause switch (on Settings → Your Executive) and signing out, kept off+// the main menu.+const ACCOUNT_ITEMS: OverflowItem[] = [+ { label: GUIDE_NAV_ITEM.label, href: GUIDE_NAV_ITEM.href },+ { label: "Pause or resume the Executive", href: "/settings/executive" },+];+interface UserBadgeProps {- /** "sidebar" (vertical, with sign-out below name) or "compact" (single row, name only). */+ /** "sidebar" (name, email and the account menu) or "compact" (single row, name only). */variant?: "sidebar" | "compact";}@@ -40,13 +51,16 @@ export default function UserBadge({ variant = "compact" }: UserBadgeProps) {}title="Local login: only this computer can reach Open Executive">- <Avatar name="ME" size={variant === "sidebar" ? "w-7 h-7" : "w-6 h-6"} />+ <Avatar name="ME" size={variant === "sidebar" ? "w-8 h-8" : "w-6 h-6"} /><div className="flex-1 min-w-0">- <p className="text-xs font-medium text-fg truncate">You (owner)</p>+ <p className="text-sm font-medium text-fg truncate">You (owner)</p>{variant === "sidebar" && (- <p className="text-[10px] text-fg-muted truncate">On this computer</p>+ <p className="text-xs text-fg-muted truncate">On this computer</p>)}</div>+ {variant === "sidebar" && (+ <OverflowMenu items={ACCOUNT_ITEMS} label="Account menu" size="sm" placement="up" />+ )}</div>);}@@ -66,19 +80,20 @@ export default function UserBadge({ variant = "compact" }: UserBadgeProps) {if (variant === "sidebar") {return (<div className="px-3 py-3 border-t border-line flex items-center gap-2.5 flex-shrink-0">- <Avatar name={initials} image={user.image} />+ <Avatar name={initials} image={user.image} size="w-8 h-8" /><div className="flex-1 min-w-0">- <p className="text-xs font-medium text-fg truncate">{name}</p>- <p className="text-[10px] text-fg-muted truncate">{user.email}</p>+ <p className="text-sm font-medium text-fg truncate">{name}</p>+ <p className="text-xs text-fg-muted truncate">{user.email}</p></div>- <button- type="button"- onClick={() => signOut({ callbackUrl: "/signin" })}- className="text-[10px] text-fg-muted hover:text-fg transition-colors cursor-pointer flex-shrink-0"- title="Sign out"- >- Sign out- </button>+ <OverflowMenu+ items={[+ ...ACCOUNT_ITEMS,+ { label: "Sign out", onSelect: () => void signOut({ callbackUrl: "/signin" }) },+ ]}+ label="Account menu"+ size="sm"+ placement="up"+ /></div>);}diff --git a/packages/ui/src/components/WorkflowRunner.tsx b/packages/ui/src/components/WorkflowRunner.tsxindex eb7bef3b..15782c7f 100644--- a/packages/ui/src/components/WorkflowRunner.tsx+++ b/packages/ui/src/components/WorkflowRunner.tsx@@ -3,6 +3,7 @@import { useState } from "react";import { useRouter } from "next/navigation";import Link from "next/link";+import Button from "@/components/ui/Button";import {WorkflowEvent,WorkflowMeta,@@ -119,31 +120,23 @@ export default function WorkflowRunner({return (<div className="space-y-6">{!started && (- <div className="flex items-center gap-3">- <button- type="button"- onClick={handleStart}- className="px-4 py-2 rounded-md bg-indigo-600 hover:bg-indigo-500 text-white text-sm font-medium transition"- >+ <div className="flex flex-wrap items-center gap-3 rounded-2xl border border-line bg-surface-elevated p-5 shadow-sm">+ <Button variant="primary" onClick={handleStart} className="px-7">Run workflow- </button>- <button- type="button"- onClick={onCancel}- className="px-4 py-2 rounded-md border border-line-strong text-fg hover:text-fg hover:border-line-strong text-sm transition"- >- Cancel- </button>- <span className="text-xs text-fg-muted ml-auto">+ </Button>+ <Button variant="ghost" onClick={onCancel}>+ Back to the details+ </Button>+ <span className="text-sm text-fg-muted sm:ml-auto">~{workflow.estimated_minutes} min · {workflow.steps.length} steps</span></div>)}{started && (- <div className="rounded-lg border border-line bg-surface/40 p-5">+ <div className="rounded-2xl border border-line bg-surface-elevated p-5 shadow-sm sm:p-6"><div className="flex items-center justify-between mb-4">- <h3 className="text-sm font-semibold text-fg">Progress</h3>+ <h3 className="text-lg font-semibold text-fg">Progress</h3>{streaming && (<span className="text-xs text-amber-400 flex items-center gap-1.5"><span className="inline-block w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse" />@@ -164,14 +157,14 @@ export default function WorkflowRunner({<StepIndicator state={s.state} index={i + 1} /><div className="flex-1 min-w-0"><div className="flex items-baseline justify-between gap-3">- <div className="text-sm text-fg font-medium">+ <div className="text-[15px] text-fg font-medium">{s.def.title}</div><div className="text-[10px] text-fg-muted uppercase tracking-wide">{s.state}</div></div>- <div className="text-xs text-fg-muted mt-0.5">+ <div className="text-sm text-fg-muted mt-0.5">{s.def.description}</div>{s.summary && (@@ -234,7 +227,7 @@ function PausedNotice({{runId && (<Linkhref={`/jobs/runs/${encodeURIComponent(runId)}`}- className="inline-block text-xs text-indigo-400 hover:underline"+ className="inline-block text-sm font-medium text-accent hover:underline">Follow this run →</Link>diff --git a/packages/ui/src/components/architecture/MermaidDiagram.tsx b/packages/ui/src/components/architecture/MermaidDiagram.tsxindex 911c417a..bccabfbd 100644--- a/packages/ui/src/components/architecture/MermaidDiagram.tsx+++ b/packages/ui/src/components/architecture/MermaidDiagram.tsx@@ -38,6 +38,15 @@ export default function MermaidDiagram({ definition, id }: Props) {useEffect(() => {let cancelled = false;+ // mermaid.render appends a temporary <div id="d{id}"> to <body> while+ // rendering, and on a parse error leaves it there holding its "Syntax+ // error" graphic, which then shows on every page after this one. Remove+ // it (and the svg it may hold) whatever happens, including on unmount.+ const uniqueId = `mermaid-${id}-${Math.random().toString(36).slice(2, 10)}`;+ const cleanup = () => {+ document.getElementById(`d${uniqueId}`)?.remove();+ document.getElementById(uniqueId)?.remove();+ };async function render() {try {@@ -90,10 +99,7 @@ export default function MermaidDiagram({ definition, id }: Props) {},});- // mermaid.render appends a temporary <div id="…"> to <body> while- // rendering. Use a uniqueid per call so concurrent renders on a- // remount don't collide.- const uniqueId = `mermaid-${id}-${Math.random().toString(36).slice(2, 10)}`;+ // A unique id per call so concurrent renders on a remount don't collide.const result = await mermaid.render(uniqueId, withSharedStyles(definition));if (!cancelled) {setSvg(result.svg);@@ -109,12 +115,15 @@ export default function MermaidDiagram({ definition, id }: Props) {// Keep the console error for devs; users see the inline fallback.console.error('Mermaid render failed:', e);}+ } finally {+ cleanup();}}render();return () => {cancelled = true;+ cleanup();};}, [definition, id]);diff --git a/packages/ui/src/components/askoe/AskOEContext.tsx b/packages/ui/src/components/askoe/AskOEContext.tsxindex 74adb358..a3ce2ff0 100644--- a/packages/ui/src/components/askoe/AskOEContext.tsx+++ b/packages/ui/src/components/askoe/AskOEContext.tsx@@ -63,7 +63,7 @@ const ROUTE_GUIDE_MAP: Array<{ prefix: string; guideId: string; title: string }>{ prefix: "/goals", guideId: "departments", title: "Goals" },{ prefix: "/people", guideId: "people", title: "People" },{ prefix: "/company-profile", guideId: "company_profile", title: "Company profile" },- { prefix: "/knowledge", guideId: "knowledge", title: "Knowledge base" },+ { prefix: "/knowledge", guideId: "knowledge", title: "Knowledge" },{ prefix: "/council", guideId: "council", title: "Agent Council" },{ prefix: "/demo", guideId: "simulator", title: "Company Simulator" },{ prefix: "/settings", guideId: "settings", title: "Settings" },diff --git a/packages/ui/src/components/briefing/AwarenessPanels.tsx b/packages/ui/src/components/briefing/AwarenessPanels.tsxnew file mode 100644index 00000000..ff39a19a--- /dev/null+++ b/packages/ui/src/components/briefing/AwarenessPanels.tsx@@ -0,0 +1,360 @@+"use client";++import Link from "next/link";++import Button from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";+import type { ClientCockpitCard, HandledItem, InFlightItem, ProposalItem } from "@/lib/api";+import { MEMORY_ACTIONS, briefingMemoryLine } from "@/lib/briefing-memory";+import { ageLabel } from "@/lib/briefingSummary";+import {+ HANDLED_REOPENABLE,+ groupHandled,+ handledAlsoLine,+ handledHeadline,+ handledKey,+ handledProofHref,+ isCloseKind,+ type HandledRow,+} from "@/lib/handled";+import { clientCountsSummary, renewalBadge } from "@/lib/practice";++import {+ Chip,+ MONITORING_DISMISS_OLDER_THAN_DAYS,+ PanelIntro,+ TONE_TEXT,+ buildMonitoringSeed,+ formatFuture,+ olderThan,+ type ContinueHandler,+} from "./shared";++// The side panels behind Home's awareness tiles: In flight, Across your+// clients, Monitoring and Handled overnight. Each holds the section's full+// list and every button it had on the page.++// In flight — what the Executive is about to do (scheduled follow-ups &+// nudges). Nothing here needs approval; it's a heads-up.+export function InFlightPanelBody({ inFlight }: { inFlight: InFlightItem[] }) {+ return (+ <>+ <PanelIntro>+ What the Executive is about to do (scheduled follow-ups & nudges). Nothing here needs your approval —+ it's a heads-up.+ </PanelIntro>+ <div className="divide-y divide-line">+ {inFlight.map((f) => (+ <div+ key={`if-${f.action_id}`}+ className={`py-3.5 pl-3 border-l-2 ${f.overdue ? "border-amber-500/60" : "border-transparent"}`}+ >+ <div className="text-[15px] text-fg break-words" title={f.intent}>+ {f.intent}+ </div>+ <div className="mt-1 text-sm text-fg-muted">+ {f.target ? <span>→ {f.target}</span> : null}+ {f.department ? <span> · {f.department}</span> : null}+ <span>+ {" · "}+ {f.overdue ? <span className={TONE_TEXT.amber}>overdue</span> : formatFuture(f.run_at)}+ </span>+ </div>+ </div>+ ))}+ </div>+ </>+ );+}++// The In flight tile's sub-line: overdue first, else when the next one runs.+export function inFlightNext(inFlight: InFlightItem[]): string {+ const overdue = inFlight.filter((f) => f.overdue).length;+ if (overdue > 0) return `${overdue} overdue`;+ const next = inFlight+ .map((f) => Date.parse(f.run_at))+ .filter((t) => !Number.isNaN(t))+ .sort((a, b) => a - b)[0];+ return next == null ? "scheduled" : `next ${formatFuture(new Date(next).toISOString())}`;+}++// Multi-client practice mode only: rollup rows for PARKED client slots so+// the operator sees the whole practice from the active client's brief. The+// backend sends [] for single-company installs, so the tile never shows there.+export function PracticeClientsPanelBody({ clients }: { clients: ClientCockpitCard[] }) {+ return (+ <>+ <PanelIntro>+ Your parked client companies. Counts reflect each client's last save point; switch to a client on the+ Clients page to work in it.+ </PanelIntro>+ <div className="divide-y divide-line">+ {clients.map((c) => {+ const badge = renewalBadge(c.days_to_renewal);+ return (+ <div key={`practice-${c.slug}`} className="py-3.5">+ <div className="flex items-center justify-between gap-2">+ <div className="truncate text-[15px] font-medium text-fg">+ {c.display_name}+ {c.role ? <span className="font-normal text-fg-muted"> · {c.role}</span> : null}+ </div>+ {badge && <Chip tone={badge.urgent ? "rose" : "amber"}>{badge.label}</Chip>}+ </div>+ <div className="mt-1 text-sm text-fg-muted">{clientCountsSummary(c)}</div>+ </div>+ );+ })}+ </div>+ </>+ );+}++// One passive monitoring signal: headline + body excerpt, tap to discuss, and+// Dismiss signal in its ⋯ menu. The Discuss handoff reuses+// buildMonitoringSeed so it behaves exactly like the card does.+function MonitoringRow({+ proposal,+ onContinue,+ onDismiss,+}: {+ proposal: ProposalItem;+ onContinue?: ContinueHandler;+ onDismiss?: (p: ProposalItem) => void;+}) {+ const seed = buildMonitoringSeed(proposal);+ const inner = (+ <>+ <div className="text-[15px] font-medium text-fg group-hover:text-accent transition-colors line-clamp-2" title={proposal.headline}>+ {proposal.headline}+ </div>+ {proposal.body && proposal.body !== proposal.headline && (+ <div className="mt-1 text-sm leading-snug text-fg-muted line-clamp-2">{proposal.body}</div>+ )}+ </>+ );+ return (+ <div id={`alert-${proposal.alert_id}`} className="group flex items-start gap-2 py-3">+ {onContinue ? (+ <button+ type="button"+ onClick={() => onContinue(seed, briefingMemoryLine(MEMORY_ACTIONS.monitoring, proposal.headline))}+ className="block min-w-0 flex-1 cursor-pointer rounded-lg text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40"+ >+ {inner}+ </button>+ ) : (+ <Link href="/watchlist" className="block min-w-0 flex-1">+ {inner}+ </Link>+ )}+ {onDismiss && (+ <OverflowMenu+ size="sm"+ label="More actions for this signal"+ items={[{ label: "Dismiss signal", onSelect: () => onDismiss(proposal) }]}+ />+ )}+ </div>+ );+}++// Monitoring — passive signals (watchlist tickers, vendor status, external+// news) the Executive is tracking.+export function MonitoringPanelBody({+ proposals,+ onContinue,+ onDismiss,+ onBulkDismiss,+}: {+ proposals: ProposalItem[];+ onContinue?: ContinueHandler;+ onDismiss?: (p: ProposalItem) => void;+ onBulkDismiss?: (ids: number[]) => void;+}) {+ const staleIds = olderThan(proposals, MONITORING_DISMISS_OLDER_THAN_DAYS);+ return (+ <>+ <PanelIntro>+ Passive signals (watchlist tickers, vendor status, external news) the Executive is tracking. Nothing here+ needs a decision — tap one to talk it through.+ </PanelIntro>+ {proposals.length === 0 ? (+ <p className="py-3 text-[15px] text-fg-muted">No signals right now.</p>+ ) : (+ <div className="divide-y divide-line">+ {proposals.map((p) => (+ <MonitoringRow key={p.alert_id} proposal={p} onContinue={onContinue} onDismiss={onDismiss} />+ ))}+ </div>+ )}+ {onBulkDismiss && staleIds.length > 0 && (+ <Button variant="secondary" size="sm" className="mt-3" onClick={() => onBulkDismiss(staleIds)}>+ Dismiss {staleIds.length} older than {MONITORING_DISMISS_OLDER_THAN_DAYS} days+ </Button>+ )}+ </>+ );+}++// First-person sentence for one handled row. Falls back to the audit summary+// when the row predates the structured fields.+function handledSentence(h: HandledItem): React.ReactNode {+ const headline = h.headline ?? "";+ const target = h.target ?? "";+ const H = <span className="text-fg">{headline}</span>;+ const T = <span className="text-fg">{target}</span>;+ const why = h.detail ? <span className="text-fg-subtle"> — {h.detail}</span> : null;+ if (!headline) return h.summary;+ switch (h.kind) {+ case "closed":+ return h.outcome === "dismissed" ? <>Dismissed {H} as stale{why}</> : <>Resolved {H}{why}</>;+ case "routed":+ if (!target) return h.summary;+ return h.outcome === "proposed" ? (+ <>+ Proposed {H} to {T} <span className="text-fg-subtle">(awaiting their approval)</span>+ </>+ ) : (+ <>+ Handed {H} to {T}+ </>+ );+ case "nudged":+ return target ? <>Chased {T} on {H}</> : h.summary;+ case "escalated":+ return target ? <>Raised {H} to {T}{why}</> : <>Raised {H}{why}</>;+ case "drafted":+ return target ? <>Drafted {T} from {H}</> : h.summary;+ case "merged":+ return target ? <>Folded {H} into {T}</> : h.summary;+ case "suggested_workflow":+ return target ? <>Suggested running {T} on {H}</> : h.summary;+ case "watching":+ return <>Started watching {H}{why}</>;+ case "stopped_watching":+ return <>Stopped watching {H}{why}</>;+ default:+ return h.summary;+ }+}++function HandledTrailerLink({ href, label }: { href: string; label: string }) {+ return (+ <>+ <span aria-hidden="true">·</span>+ <Link href={href} className="hover:text-accent transition-colors underline-offset-2 hover:underline">+ {label}+ </Link>+ </>+ );+}++function HandledRowView({+ row,+ reverted,+ onReopen,+ onJumpToAlert,+}: {+ row: HandledRow;+ reverted: boolean;+ onReopen?: (rowKey: string, alertId: number) => void;+ onJumpToAlert: (alertId: number) => void;+}) {+ const h = row.item;+ // Undo only while the close still stands and the server would accept a+ // reopen (resolved / dismissed / expired / merged; "" = status unknown).+ const canUndo =+ Boolean(onReopen) && h.alert_id != null && isCloseKind(h) && !reverted && HANDLED_REOPENABLE.has(h.status ?? "");+ // "open" means live in the queue right now — the only state with a card to+ // jump to (an acked or snoozed alert has none).+ const stillOpen = h.alert_id != null && h.status === "open" && !isCloseKind(h);+ const proofHref = handledProofHref(h);+ const alsoLine = handledAlsoLine(row);+ return (+ <div className="flex items-start justify-between gap-3 py-3">+ <div className="min-w-0">+ <p className={`text-[15px] leading-snug ${reverted ? "line-through text-fg-subtle" : "text-fg-muted"}`}>+ {handledSentence(h)}+ </p>+ <p className="mt-1 flex flex-wrap items-center gap-x-1.5 text-xs text-fg-subtle">+ {alsoLine && <span>{alsoLine}</span>}+ {alsoLine && <span aria-hidden="true">·</span>}+ <span>{ageLabel(h.at)} ago</span>+ {proofHref && <HandledTrailerLink href={proofHref} label={h.evidence_ref || "evidence"} />}+ {h.kind === "drafted" && <HandledTrailerLink href="/artifacts" label="read the draft" />}+ {(h.kind === "watching" || h.kind === "stopped_watching") && (+ <HandledTrailerLink href="/watchlist" label="watchlist" />+ )}+ {reverted && (+ <>+ <span aria-hidden="true">·</span>+ <span className={TONE_TEXT.sky}>Reopened</span>+ </>+ )}+ </p>+ </div>+ {canUndo && (+ <Button variant="secondary" size="sm" onClick={() => onReopen?.(handledKey(h), h.alert_id as number)}>+ Undo+ </Button>+ )}+ {stillOpen && (+ <Button+ variant="ghost"+ size="sm"+ title="Jump to it in your queue"+ onClick={() => onJumpToAlert(h.alert_id as number)}+ >+ Still open+ </Button>+ )}+ </div>+ );+}++// Handled overnight — moves the Executive completed on its own since the+// last delivered brief. The rail is rebuilt from the audit log on every+// fetch, so a close the principal already undid still has its row:+// `status === "open"` (server truth after a reload) or the in-session set+// marks it reverted.+export function handledReverted(undone: Set<string>) {+ return (h: HandledItem) => isCloseKind(h) && (h.status === "open" || undone.has(handledKey(h)));+}++export function HandledPanelBody({+ items,+ onReopen,+ undone,+ onJumpToAlert,+}: {+ items: HandledItem[];+ onReopen?: (rowKey: string, alertId: number) => void;+ undone: Set<string>;+ onJumpToAlert: (alertId: number) => void;+}) {+ const reverted = handledReverted(undone);+ // Grouped rows, not raw items: a merge folded into a listed survivor+ // leaves no row of its own.+ const rows = groupHandled(items);+ return (+ <>+ <p className="mb-1 text-[15px] font-medium text-fg">{handledHeadline(rows, reverted)}</p>+ <PanelIntro>+ Moves I completed on my own since your last delivered brief — routed, chased, escalated, drafted, folded, or+ closed with cited evidence. Rewrites of open alerts show on the card itself, not here. Undo puts a closed item+ back in your queue.+ </PanelIntro>+ <div className="divide-y divide-line border-t border-line">+ {rows.map((row) => (+ <HandledRowView+ key={handledKey(row.item)}+ row={row}+ reverted={reverted(row.item)}+ onReopen={onReopen}+ onJumpToAlert={onJumpToAlert}+ />+ ))}+ </div>+ </>+ );+}diff --git a/packages/ui/src/components/briefing/Narrative.tsx b/packages/ui/src/components/briefing/Narrative.tsxnew file mode 100644index 00000000..ca445685--- /dev/null+++ b/packages/ui/src/components/briefing/Narrative.tsx@@ -0,0 +1,99 @@+"use client";++import ReactMarkdown from "react-markdown";+import remarkGfm from "remark-gfm";++import { MEMORY_ACTIONS, briefingMemoryLine } from "@/lib/briefing-memory";++import { PanelIntro, buildNarrativeSeed, type ContinueHandler } from "./shared";++// Flatten a react-markdown AST node to its plain text. Bullets in the+// "What's going on" narrative are `**Headline** — text`; this reads the+// underlying text nodes (recursing through bold/em/links) so a clicked bullet+// can be handed to the Executive as one clean string.+function nodeToPlainText(node: unknown): string {+ if (!node || typeof node !== "object") return "";+ const n = node as { value?: string; children?: unknown[] };+ if (typeof n.value === "string") return n.value;+ if (Array.isArray(n.children)) return n.children.map(nodeToPlainText).join("");+ return "";+}++// "What's going on" — the Executive's read on things right now, shown in the+// side panel "Read today's brief" opens. While the first one is still being+// written (`narrative` empty, `stale` true) it says so.+export default function NarrativeBody({+ narrative,+ stale,+ solo,+ onContinue,+}: {+ narrative: string | null | undefined;+ stale: boolean;+ solo: boolean;+ onContinue?: ContinueHandler;+}) {+ if (!narrative) {+ return (+ <div aria-live="polite" className="rounded-xl bg-accent/5 px-4 py-3 text-[15px] text-fg-muted animate-pulse">+ {stale ? "Catching up on today…" : "No brief yet today."}+ </div>+ );+ }+ return (+ <>+ <PanelIntro>+ The Executive's read on {solo ? "your work" : "the company"} right now — what came in today, what's+ stuck, what's next on your calendar, plus proposals and at-risk goals. Rewritten as the picture changes.+ {onContinue && " Tap a point to talk it through."}+ </PanelIntro>+ <div className="prose prose-invert max-w-none text-[15px] prose-p:my-2 prose-ul:my-2 prose-headings:text-fg prose-strong:text-fg">+ <ReactMarkdown+ remarkPlugins={[remarkGfm]}+ components={+ onContinue+ ? {+ // Drop the default disc + marker padding so 💬 acts as the+ // bullet. Tailwind utilities beat the `prose` plugin's+ // zero-specificity :where(ul) rules, so list-none/pl-0 win.+ ul: ({ children }) => <ul className="list-none pl-0 my-2 space-y-1">{children}</ul>,+ // Each narrative bullet is its own click target → hands off+ // to chat to discuss that item. The bottom-line and "Move+ // today:" lines are paragraphs/strong text, so they stay+ // non-interactive.+ li: ({ node, children }) => {+ const text = nodeToPlainText(node).trim();+ // No extractable text (empty bullet, or a react-markdown+ // version that doesn't forward `node`) → a plain item+ // rather than a button that seeds an empty prompt.+ if (!text) return <li className="list-none">{children}</li>;+ return (+ <li className="list-none pl-0 my-0">+ <button+ type="button"+ onClick={() =>+ onContinue(buildNarrativeSeed(text), briefingMemoryLine(MEMORY_ACTIONS.narrative, text))+ }+ aria-label={`Discuss: ${text}`}+ className="group -mx-2 flex w-full items-start gap-2.5 rounded-xl px-2 py-2 text-left cursor-pointer transition hover:bg-accent/10 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40"+ >+ {/* 💬 stands in for the bullet and signals "tap to+ discuss"; it lifts on hover as the click cue. */}+ <span aria-hidden className="mt-0.5 flex-shrink-0 select-none opacity-70 transition group-hover:opacity-100">+ 💬+ </span>+ <span className="min-w-0">{children}</span>+ </button>+ </li>+ );+ },+ }+ : undefined+ }+ >+ {narrative}+ </ReactMarkdown>+ </div>+ </>+ );+}diff --git a/packages/ui/src/components/briefing/ProposalCard.tsx b/packages/ui/src/components/briefing/ProposalCard.tsxnew file mode 100644index 00000000..70c662fa--- /dev/null+++ b/packages/ui/src/components/briefing/ProposalCard.tsx@@ -0,0 +1,542 @@+"use client";++import Link from "next/link";+import { useState } from "react";+import ReactMarkdown from "react-markdown";+import remarkGfm from "remark-gfm";++import RosterRequestCard from "@/components/RosterRequestCard";+import Button, { buttonClass } from "@/components/ui/Button";+import OverflowMenu, { type OverflowItem } from "@/components/ui/OverflowMenu";+import type { PersonBriefItem, ProposalItem } from "@/lib/api";+import { MEMORY_ACTIONS, briefingMemoryLine, nudgeAction } from "@/lib/briefing-memory";+import { ageLabel, daysUntil, proposalStatusChip } from "@/lib/briefingSummary";+import { hostOf } from "@/lib/url";++import { Chip, TONE_TEXT, buildMonitoringSeed, type ContinueHandler } from "./shared";++// A proposal body longer than about half this (chars) is clamped to two+// lines under the headline while the card is closed, so the "Needs you"+// queue stays scannable.+const LONG_BODY_CHARS = 180;++// Badge text for an artifact card: the format when it isn't plain Markdown.+function artifactBadge(format: ProposalItem["artifact_format"]): string {+ switch (format) {+ case "html":+ return "Web page";+ case "docx":+ return "Word doc";+ case "xlsx":+ return "Spreadsheet";+ case "link":+ return "Link";+ default:+ return "Document";+ }+}++// Lifecycle presentation for one proposal card — the review-driven pieces+// the opened card shows: the one-line "what changed since you last looked",+// the chip row (age, seen ×N, why-now / due, likely-stale, folded-in,+// draft-ready) and the muted "Reviewed <ago>" footer. A pure builder (no+// hooks) so ProposalCard stays a layout function.+function buildProposalLifecycle(proposal: ProposalItem): {+ reviewLine: React.ReactNode;+ lifecycleRow: React.ReactNode;+ reviewedFooter: React.ReactNode;+} {+ const verdict = proposal.review_verdict ?? "";+ const isLikelyStale = verdict === "likely_stale";+ const age = ageLabel(proposal.created_at);+ const dueIn = daysUntil(proposal.due_at);+ const reviewLine = proposal.review_note ? (+ <p className={`text-sm leading-snug ${isLikelyStale ? TONE_TEXT.amber : "text-fg-muted"}`}>+ <span className="mr-1.5 text-xs font-semibold uppercase tracking-wide">+ {isLikelyStale ? "Likely stale" : verdict === "changed" ? "Updated" : "Since you last looked"}+ </span>+ {proposal.review_note}+ </p>+ ) : null;+ const chips: { label: string; tone: "neutral" | "amber" | "sky"; title?: string }[] = [];+ if (age) chips.push({ label: age, tone: "neutral", title: `Raised ${new Date(proposal.created_at).toLocaleString()}` });+ if ((proposal.occurrence_count ?? 1) > 1)+ chips.push({+ label: `seen ×${proposal.occurrence_count}`,+ tone: "neutral",+ title: proposal.last_seen_at ? `Last seen ${ageLabel(proposal.last_seen_at)} ago` : undefined,+ });+ if (proposal.why_now || dueIn != null) {+ const due = dueIn == null ? "" : dueIn < 0 ? "overdue" : dueIn === 0 ? "due today" : `due in ${dueIn}d`;+ chips.push({ label: [proposal.why_now, due].filter(Boolean).join(" · "), tone: "amber" });+ }+ if (isLikelyStale && !proposal.review_note) chips.push({ label: "Likely stale", tone: "amber" });+ if ((proposal.superseded_count ?? 0) > 0)+ chips.push({ label: `${proposal.superseded_count} folded in`, tone: "neutral" });+ if (verdict === "changed" && !proposal.review_note)+ chips.push({ label: "Updated by the Executive", tone: "sky" });+ if (verdict === "drafted") chips.push({ label: "Draft ready in your queue", tone: "amber" });+ const lifecycleRow = chips.length > 0 ? (+ <div className="flex flex-wrap gap-1.5">+ {chips.map((c) => (+ <Chip key={c.label} tone={c.tone} title={c.title}>+ {c.label}+ </Chip>+ ))}+ </div>+ ) : null;+ const reviewedFooter = proposal.last_reviewed_at ? (+ <p className="text-xs text-fg-subtle">+ Reviewed {ageLabel(proposal.last_reviewed_at)} ago+ {verdict && verdict !== "likely_stale" ? ` · ${verdict}` : ""}+ </p>+ ) : null;+ return { reviewLine, lifecycleRow, reviewedFooter };+}++// The chat seed for Discuss: the FULL body plus the suggested_action, so the+// Executive has the entire card's worth of context, and a mode primer (what+// it may and may not do from chat) that depends on the kind of card.+function buildHandoffPrompt(+ proposal: ProposalItem,+ kind: { isArtifact: boolean; isMonitoring: boolean; isDecision: boolean },+): string {+ if (kind.isArtifact) {+ // Artifacts aren't approved/executed — they're read. Seed the chat+ // with the full document + rationale so the Executive can discuss+ // it, and let it clear the card via ack_alert when the user is done.+ const rationale = proposal.suggested_action+ ? `\n\nWhy you flagged it: ${proposal.suggested_action}`+ : "";+ return (+ `Let's discuss this artifact you flagged for my review:\n\n` ++ `# ${proposal.headline}\n\n${proposal.body || ""}${rationale}\n\n` ++ `[Discuss mode — alert_id=${proposal.alert_id}, artifact id ` ++ `alert:${proposal.alert_id}; to revise it, publish a new version with ` ++ `draft_artifact(supersedes="alert:${proposal.alert_id}")] This is a document ` ++ `for review, not an action to approve. Answer my questions about it ` ++ `conversationally. When I say I'm done ("got it", "reviewed", "thanks"), ` ++ `call ack_alert(alert_id=${proposal.alert_id}, status="ack") to clear ` ++ `it from my queue. Take no other action.`+ );+ }+ if (kind.isMonitoring) {+ // Monitoring signals are passive — there's nothing to approve, so the+ // Discuss handoff asks the Executive to interpret the signal.+ return buildMonitoringSeed(proposal);+ }+ if (kind.isDecision) {+ // Gated calendar booking. Approval/rejection happens via the card's+ // Approve/Dismiss (the /decisions endpoints book or cancel the event+ // server-side) — NOT via chat. So the Discuss handoff is read-only.+ const body = proposal.body || proposal.headline;+ return (+ `Let's talk through this meeting I've proposed:\n\n${body}\n\n` ++ `[Discuss mode] This booking is awaiting your approval on the ` ++ `briefing. Help me decide whether the time, attendees, and purpose ` ++ `make sense. Do NOT book, cancel, or ack anything from chat — I'll ` ++ `approve or dismiss it from the card itself.`+ );+ }+ // alert_id is carried so the exec can clear the card once approval lands.+ const text = proposal.body || proposal.headline;+ const suggested = proposal.suggested_action+ ? `\n\nIf I approve, you will:\n${proposal.suggested_action}`+ : "";+ const primer =+ `\n\n[Discuss mode — alert_id=${proposal.alert_id}] ` ++ `This proposal is NOT YET approved. Answer my questions conversationally. ` ++ `When I explicitly approve ("ok", "approve", "go ahead", "do it"), switch to ` ++ `execute mode: actually attempt the work (use web_search and your other tools — ` ++ `don't just promise), reply inline with the deliverable, schedule a fresh ` ++ `follow-up via schedule_followup if it's time-bound, and call ` ++ `ack_alert(alert_id=${proposal.alert_id}, status="ack"). ` ++ `If I dismiss it ("never mind", "drop it"), call ` ++ `ack_alert(alert_id=${proposal.alert_id}, status="dismissed") and stop. ` ++ `Until explicit approval/dismissal, take no action and do not ack.`;+ return `Tell me about this proposal:\n\n${text}${suggested}${primer}`;+}++// One action a card can offer; the card shows one as its primary button and+// the rest in its ⋯ menu.+interface CardAction {+ label: string;+ onSelect?: () => void;+ href?: string;+ external?: boolean;+ danger?: boolean;+}++// A card in "Needs you" (and in the Across-the-team panel). Closed, it shows+// the proposal, one status chip and who it is routed to, with one primary+// button (the recommended move, or Approve) beside Discuss; the rest sit in+// ⋯. A click on the card opens it to show the review line, the lifecycle+// chips, what approving does, the tags and when it was last reviewed.+export default function ProposalCard({+ proposal,+ people,+ onContinue,+ onApprove,+ onDismiss,+ onApproveWithEdits,+ busy = false,+ defaultBodyExpanded = false,+ emphasized = false,+}: {+ proposal: ProposalItem;+ people: PersonBriefItem[];+ onContinue?: ContinueHandler;+ onApprove?: (p: ProposalItem) => void;+ onDismiss?: (p: ProposalItem) => void;+ onApproveWithEdits?: (p: ProposalItem, editedBody: string) => void;+ busy?: boolean;+ // Show the whole body while closed (no clamp) — the first card in the+ // queue, so its full text reads without a click.+ defaultBodyExpanded?: boolean;+ // The first card in the queue: an accent border so the single sharpest+ // item stands out.+ emphasized?: boolean;+}) {+ // Local edit-mode state. Entering edit mode replaces the body with a+ // textarea pre-filled with the proposal body; the action row becomes+ // Cancel / Send approval. Send approval pipes the edited text up through+ // onApproveWithEdits so Briefing can ack the alert + seed the chat with a+ // verbatim-send instruction.+ const [editing, setEditing] = useState(false);+ const [editedBody, setEditedBody] = useState("");+ const [expanded, setExpanded] = useState(false);+ // A roster request ("who is this new sender?") is answered on its own+ // card — never through chat, so what a stranger wrote never seeds a turn.+ // Below the hooks, which must run on every render.+ if (proposal.roster_request) {+ return (+ <RosterRequestCard+ request={proposal.roster_request}+ emphasized={emphasized}+ onResolved={() => onDismiss?.(proposal)}+ />+ );+ }+ function startEditing() {+ setEditedBody(proposal.body || proposal.headline);+ setEditing(true);+ }+ function cancelEditing() {+ setEditing(false);+ setEditedBody("");+ }+ function submitEdit() {+ if (!onApproveWithEdits) return;+ const text = editedBody.trim();+ if (!text) return;+ onApproveWithEdits(proposal, text);+ }+ const assignee =+ proposal.routed_to_person_id != null+ ? people.find((p) => p.id === proposal.routed_to_person_id)+ : null;+ // Research artifacts (the Executive's `draft_artifact` tool) are full+ // authored documents, not terse proposals; the `artifact` topic tag is the+ // discriminator. They are read and marked reviewed, not approved.+ const isArtifact = proposal.topic_tags?.includes("artifact") ?? false;+ // Monitoring items are passive external/watchlist signals — nothing to+ // approve, so the body reads as "why it's on your radar".+ const isMonitoring = proposal.category === "monitoring";+ // Decision-backed proposals (gated calendar bookings) execute server-side+ // via the /decisions endpoints. The verbatim-DM "Edit & approve" flow+ // doesn't map to a calendar booking, so it's not offered for these.+ const isDecision = proposal.decision_instance_id != null;+ const isLikelyStale = (proposal.review_verdict ?? "") === "likely_stale";+ // The card's title is the headline; under it, the rest of the body — what+ // follows the headline when the body opens with it, else the whole body.+ // Monitoring signals show their body as "why it's on your radar" when+ // opened, and artifacts show the document.+ const description = (() => {+ if (isMonitoring || isArtifact) return "";+ const body = proposal.body.trim();+ const headline = proposal.headline.trim();+ if (!body || body === headline) return "";+ if (headline && body.startsWith(headline)) {+ const rest = body.slice(headline.length).replace(/^[\s.:;,—–-]+/, "");+ return rest.charAt(0).toUpperCase() + rest.slice(1);+ }+ return body;+ })();+ const isLongBody = description.length > LONG_BODY_CHARS / 2;+ const clamp = isLongBody && !expanded && !defaultBodyExpanded;+ const handoffPrompt = buildHandoffPrompt(proposal, { isArtifact, isMonitoring, isDecision });+ const handoffMemory = briefingMemoryLine(+ isArtifact+ ? MEMORY_ACTIONS.artifact+ : isMonitoring+ ? MEMORY_ACTIONS.monitoring+ : isDecision+ ? MEMORY_ACTIONS.meeting+ : MEMORY_ACTIONS.proposal,+ proposal.headline,+ );+ // What approving commits the Executive to ("if I approve, the exec will+ // do THIS"); for an artifact, why it's worth reading. Never for monitoring.+ const suggestedActionBlock =+ !isMonitoring && proposal.suggested_action ? (+ <div className="rounded-xl border border-accent/30 bg-accent/5 px-3.5 py-2.5">+ <div className="mb-1 text-xs font-semibold uppercase tracking-wide text-accent">+ {isArtifact ? "Why this is worth your time" : "If you approve"}+ </div>+ <p className="text-sm leading-snug text-fg whitespace-pre-wrap break-words">+ {proposal.suggested_action}+ </p>+ </div>+ ) : null;++ if (editing) {+ return (+ <div+ id={`alert-${proposal.alert_id}`}+ className="rounded-2xl border border-accent/50 bg-surface-elevated p-4 sm:p-5"+ >+ <div className="mb-3 flex items-start justify-between gap-2">+ <span className="text-xs font-semibold uppercase tracking-wide text-fg-muted">+ Editing proposal — sent word for word+ </span>+ {assignee && <span className="flex-shrink-0 text-sm text-accent">→ {assignee.full_name}</span>}+ </div>+ {/* What the exec will do on approval, so the user sees what they're+ authorizing while editing the message body. */}+ {suggestedActionBlock && <div className="mb-3">{suggestedActionBlock}</div>}+ <textarea+ value={editedBody}+ onChange={(e) => setEditedBody(e.target.value)}+ rows={6}+ disabled={busy}+ aria-label="Proposal text to send"+ className="w-full rounded-xl border border-line bg-surface p-3 text-[15px] leading-snug text-fg whitespace-pre-wrap focus:outline-none focus:ring-2 focus:ring-accent/40 disabled:opacity-50"+ autoFocus+ />+ <div className="mt-3 flex flex-wrap justify-end gap-2">+ <Button variant="ghost" onClick={cancelEditing} disabled={busy}>+ Cancel+ </Button>+ <Button variant="primary" onClick={submitEdit} disabled={busy || !editedBody.trim()}>+ Send approval+ </Button>+ </div>+ </div>+ );+ }++ // The actions this card offers, then the pick of one as the primary.+ const firstName = assignee?.full_name?.split(" ")[0];+ const move = proposal.recommended_move ?? "";+ const nudge: CardAction | null =+ move === "nudge" && onContinue && !isArtifact && !isMonitoring+ ? {+ label: `Nudge ${firstName ?? "owner"}`,+ onSelect: () => {+ const who = assignee?.full_name ?? "the owner";+ onContinue(+ `Nudge ${who} about this item — it has gone quiet: ${proposal.headline}\n\n` ++ `Send a short, friendly check-in via message_person and tell me what you sent.`,+ briefingMemoryLine(nudgeAction(who), proposal.headline),+ );+ },+ }+ : null;+ const workflow: CardAction | null =+ move === "suggest_workflow" && proposal.suggested_workflow && !isArtifact && !isMonitoring+ ? {+ label: `Run ${proposal.suggested_workflow.replace(/_/g, " ")}`,+ href: `/jobs/${proposal.suggested_workflow}`,+ }+ : null;+ const approve: CardAction | null =+ !isMonitoring && !isArtifact && onApprove ? { label: "Approve", onSelect: () => onApprove(proposal) } : null;+ const editApprove: CardAction | null =+ !isMonitoring && !isArtifact && !isDecision && onApproveWithEdits+ ? { label: "Edit & approve", onSelect: startEditing }+ : null;+ const dismiss: CardAction | null = onDismiss+ ? isArtifact+ ? { label: "Mark reviewed", onSelect: () => onDismiss(proposal) }+ : { label: isMonitoring ? "Dismiss signal" : "Dismiss", onSelect: () => onDismiss(proposal) }+ : null;+ const openDoc: CardAction | null = isArtifact+ ? { label: "Open document", href: `/artifacts/${encodeURIComponent(`alert:${proposal.alert_id}`)}` }+ : null;+ const openInApp: CardAction | null =+ isArtifact && proposal.artifact_format === "link" && proposal.artifact_url+ ? { label: `Open in app (${hostOf(proposal.artifact_url)})`, href: proposal.artifact_url, external: true }+ : null;+ const personPage: CardAction | null = assignee+ ? { label: `Open ${firstName ?? assignee.full_name}'s page`, href: `/people/${assignee.id}` }+ : null;++ // The primary: the review's recommended move when it is one the user+ // completes (nudge, run a workflow); Dismiss when the review thinks the+ // card is stale; Open for a document; otherwise Approve.+ let primary: CardAction | null;+ if (isArtifact) primary = openDoc;+ else if (isMonitoring) primary = null; // Discuss leads+ else if (isLikelyStale && dismiss) primary = dismiss;+ else primary = nudge ?? workflow ?? approve;+ const menu = [nudge, workflow, approve, editApprove, dismiss, openInApp, personPage].filter(+ (a): a is CardAction => a != null && a !== primary,+ );+ const showActions = Boolean(onApprove || onDismiss || onApproveWithEdits);++ const status = isMonitoring ? null : proposalStatusChip(proposal);+ const visibleTags = proposal.topic_tags.filter((t) => t !== "artifact");+ const { reviewLine, lifecycleRow, reviewedFooter } = buildProposalLifecycle(proposal);+ const surfacedNote = proposal.surfaced_reason ? (+ <p className="text-sm text-fg-muted leading-snug">{proposal.surfaced_reason}</p>+ ) : null;+ const radarBody =+ isMonitoring && proposal.body && proposal.body !== proposal.headline ? proposal.body : null;+ const hasDetails = Boolean(+ reviewLine ||+ lifecycleRow ||+ suggestedActionBlock ||+ surfacedNote ||+ visibleTags.length > 0 ||+ reviewedFooter ||+ isArtifact ||+ radarBody ||+ isLongBody,+ );++ const header = (+ <>+ {isArtifact && (+ <div className="mb-1.5">+ <Chip tone="amber">{artifactBadge(proposal.artifact_format)}</Chip>+ </div>+ )}+ <div+ className={`text-base sm:text-[17px] font-semibold leading-snug text-fg whitespace-pre-wrap break-words${+ expanded ? "" : " line-clamp-3"+ }`}+ >+ {proposal.headline}+ </div>+ {description && (+ <p+ className={`mt-1.5 text-[15px] leading-relaxed text-fg-muted whitespace-pre-wrap break-words${+ clamp ? " line-clamp-2" : ""+ }`}+ title={clamp ? description : undefined}+ >+ {description}+ </p>+ )}+ {(status || assignee || hasDetails) && (+ <div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1.5 text-sm text-fg-muted">+ {status && <Chip tone={status.tone}>{status.label}</Chip>}+ {assignee && <span>→ {assignee.full_name}</span>}+ {hasDetails && (+ <span className="inline-flex items-center gap-1 text-fg-subtle">+ {expanded ? "Less" : "Details"}+ <span aria-hidden="true" className={`text-[10px] transition-transform ${expanded ? "rotate-90" : ""}`}>+ ▸+ </span>+ </span>+ )}+ </div>+ )}+ </>+ );++ return (+ <div+ id={`alert-${proposal.alert_id}`}+ className={`rounded-2xl border bg-surface-elevated p-4 sm:p-5 transition-colors ${+ emphasized ? "border-accent/60 ring-1 ring-accent/25 shadow-sm" : "border-line"+ }`}+ >+ {hasDetails ? (+ <button+ type="button"+ onClick={() => setExpanded((v) => !v)}+ aria-expanded={expanded}+ className="block w-full cursor-pointer rounded-lg text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40"+ >+ {header}+ </button>+ ) : (+ <div>{header}</div>+ )}++ {expanded && (+ <div className="mt-3 space-y-2.5">+ {radarBody && (+ <div>+ <div className="mb-1 text-xs font-semibold uppercase tracking-wide text-sky-700 dark:text-sky-300">+ Why this is on your radar+ </div>+ <p className="text-sm text-fg-muted whitespace-pre-wrap break-words">{radarBody}</p>+ </div>+ )}+ {reviewLine}+ {lifecycleRow}+ {suggestedActionBlock}+ {surfacedNote}+ {visibleTags.length > 0 && (+ <div className="flex flex-wrap gap-1.5">+ {visibleTags.map((t) => (+ // `external:*` tags come from the external-monitoring layer —+ // sky marks outside-world provenance at a glance.+ <Chip key={t} tone={t.startsWith("external:") ? "sky" : "neutral"}>+ {t}+ </Chip>+ ))}+ </div>+ )}+ {isArtifact && (+ // Full authored document, rendered as Markdown in a bounded,+ // scrollable region so a long brief can't blow out the card.+ <div className="max-h-80 overflow-y-auto rounded-xl border border-line bg-surface/40 px-3.5 py-2.5 prose prose-invert prose-sm max-w-none text-sm text-fg-muted leading-relaxed [&_*]:break-words">+ <ReactMarkdown remarkPlugins={[remarkGfm]}>{proposal.body || proposal.headline}</ReactMarkdown>+ </div>+ )}+ {reviewedFooter}+ </div>+ )}++ {showActions && (+ <div className="mt-4 flex flex-wrap items-center gap-2">+ {primary &&+ (primary.href ? (+ <Link href={primary.href} className={buttonClass("primary", "md")}>+ {primary.label}+ </Link>+ ) : (+ <Button variant="primary" onClick={primary.onSelect} disabled={busy}>+ {primary.label}+ </Button>+ ))}+ {onContinue && (+ <Button+ variant={primary ? "secondary" : "primary"}+ onClick={() => onContinue(handoffPrompt, handoffMemory)}+ disabled={busy}+ >+ Discuss+ </Button>+ )}+ <OverflowMenu+ label="More actions for this item"+ items={menu.map(+ (a): OverflowItem => ({+ label: a.label,+ onSelect: a.onSelect,+ href: a.href,+ external: a.external,+ danger: a.danger,+ disabled: busy && !a.href,+ }),+ )}+ />+ </div>+ )}+ </div>+ );+}diff --git a/packages/ui/src/components/briefing/SoloPanels.tsx b/packages/ui/src/components/briefing/SoloPanels.tsxnew file mode 100644index 00000000..c236ac14--- /dev/null+++ b/packages/ui/src/components/briefing/SoloPanels.tsx@@ -0,0 +1,341 @@+"use client";++import Link from "next/link";+import { useEffect, useState } from "react";++import Button from "@/components/ui/Button";+import InfoTip from "@/components/InfoTip";+import {+ closeOpenLoop,+ deleteInitiative,+ getPersonOpenLoops,+ getTopThree,+ getWeeklyReview,+ listInitiatives,+ updateInitiative,+ type Initiative,+ type OpenLoop,+ type TopThreeToday,+ type WeeklyReviewSummary,+} from "@/lib/api";+import { dueSoon, loopText } from "@/lib/dueSoon";+import { reviewExcerpt, reviewRanLabel, topThreeSlot, topThreeWhy } from "@/lib/rhythmCards";++import { PanelIntro, RankBadge, TONE_TEXT } from "./shared";++// Solo-only parts of Home. Each loads its own data through a hook here, so+// the tile row can count it before its side panel is opened.++// ── Your projects ─────────────────────────────────────────────────────────+// The projects (initiatives) the Executive is tracking as active — the solo+// stand-in for Departments. "Done" marks one completed (PATCH), which is what+// takes it out of the Executive's active context; "Drop" deletes it after a+// confirm, since there is no "dropped" status the rest of the system treats+// as closed.+export function useActiveProjects(enabled: boolean) {+ const [projects, setProjects] = useState<Initiative[] | null>(null);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ if (!enabled) return;+ let cancelled = false;+ listInitiatives()+ .then((all) => {+ if (!cancelled) setProjects(all.filter((i) => i.status === "active"));+ })+ .catch(() => {+ if (!cancelled) setError("Couldn't load your projects.");+ });+ return () => {+ cancelled = true;+ };+ }, [enabled]);++ return { projects, setProjects, error, setError };+}++export function ProjectsPanelBody({ state }: { state: ReturnType<typeof useActiveProjects> }) {+ const { projects, setProjects, error, setError } = state;+ const [busyId, setBusyId] = useState<number | null>(null);+ // Drop asks first, in the row itself.+ const [confirmDrop, setConfirmDrop] = useState<number | null>(null);++ const close = async (project: Initiative, how: "done" | "drop") => {+ setBusyId(project.id);+ setError(null);+ try {+ if (how === "done") await updateInitiative(project.id, { status: "completed" });+ else await deleteInitiative(project.id);+ setProjects((prev) => (prev ?? []).filter((p) => p.id !== project.id));+ } catch {+ setError(how === "done" ? "Couldn't mark it done — try again." : "Couldn't drop it — try again.");+ } finally {+ setBusyId(null);+ setConfirmDrop(null);+ }+ };++ return (+ <>+ <PanelIntro>+ The projects you're running that the Executive is keeping track of. Mention a new one in chat and it+ appears here.+ </PanelIntro>+ {error && <p className={`mb-2 text-sm ${TONE_TEXT.rose}`}>{error}</p>}+ {projects === null ? (+ !error && <p className="py-2 text-[15px] text-fg-muted">Loading…</p>+ ) : projects.length === 0 ? (+ <p className="py-2 text-[15px] text-fg-muted">+ No active projects. Tell the Executive about one you're running and it will keep track of it here.+ </p>+ ) : (+ <div className="divide-y divide-line">+ {projects.map((p) => (+ <div key={p.id} className="py-3.5">+ <div className="flex items-start gap-3">+ <div className="min-w-0 flex-1">+ <div className="text-[15px] font-medium text-fg break-words">{p.title}</div>+ {p.summary && (+ <div className="mt-0.5 text-sm text-fg-muted line-clamp-2" title={p.summary}>+ {p.summary}+ </div>+ )}+ </div>+ {confirmDrop !== p.id && (+ <div className="flex flex-shrink-0 items-center gap-1.5">+ <Button size="sm" variant="secondary" onClick={() => void close(p, "done")} disabled={busyId !== null}>+ Done+ </Button>+ <Button size="sm" variant="ghost" onClick={() => setConfirmDrop(p.id)} disabled={busyId !== null}>+ Drop+ </Button>+ </div>+ )}+ </div>+ {confirmDrop === p.id && (+ <div role="alert" className="mt-2 rounded-xl border border-rose-500/30 bg-rose-500/5 px-3 py-2.5">+ <p className="text-sm text-fg">+ Drop “{p.title}”? The Executive stops tracking it, and it is removed from Pulse.+ </p>+ <div className="mt-2 flex gap-2">+ <Button size="sm" variant="danger" onClick={() => void close(p, "drop")} disabled={busyId !== null}>+ {busyId === p.id ? "Dropping…" : "Drop it"}+ </Button>+ <Button size="sm" variant="ghost" onClick={() => setConfirmDrop(null)} disabled={busyId !== null}>+ Cancel+ </Button>+ </div>+ </div>+ )}+ </div>+ ))}+ </div>+ )}+ </>+ );+}++// ── Due soon ──────────────────────────────────────────────────────────────+// What you own that is due within a week or overdue — what you promised by a+// date and what others asked of you. Read from your open loops+// (GET /people/{id}/open-loops); "Done" closes one (POST+// /open-loops/{id}/close), which also stops the Executive reminding you.+export function useOpenLoops(principalId: number | null) {+ const [loops, setLoops] = useState<OpenLoop[] | null>(null);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ if (principalId == null) return;+ let cancelled = false;+ getPersonOpenLoops(principalId)+ .then((all) => {+ if (!cancelled) setLoops(all);+ })+ .catch(() => {+ if (!cancelled) setError("Couldn't load what's due.");+ });+ return () => {+ cancelled = true;+ };+ }, [principalId]);++ return { loops, setLoops, error, setError, view: loops === null ? null : dueSoon(loops) };+}++export function DueSoonPanelBody({ state }: { state: ReturnType<typeof useOpenLoops> }) {+ const { setLoops, error, setError, view } = state;+ const [busyId, setBusyId] = useState<number | null>(null);++ const markDone = async (loopId: number) => {+ setBusyId(loopId);+ setError(null);+ try {+ await closeOpenLoop(loopId, "done");+ setLoops((prev) => (prev ?? []).filter((l) => l.loop_id !== loopId));+ } catch {+ setError("Couldn't mark it done — try again.");+ } finally {+ setBusyId(null);+ }+ };++ return (+ <>+ <PanelIntro>+ What you've promised by a date, and what others have asked of you, due in the next week. Tell the+ Executive “I'll send it by Friday” and it shows up here; the Executive reminds you when+ it's due.+ </PanelIntro>+ {error && <p className={`mb-2 text-sm ${TONE_TEXT.rose}`}>{error}</p>}+ {view === null ? (+ !error && <p className="py-2 text-[15px] text-fg-muted">Loading…</p>+ ) : view.items.length === 0 ? (+ <p className="py-2 text-[15px] text-fg-muted">+ Nothing due this week.+ {view.later > 0 && ` ${view.later} due later.`}+ </p>+ ) : (+ <>+ <div className="divide-y divide-line">+ {view.items.map((item) => (+ <div key={item.loop.loop_id} className="flex items-start gap-3 py-3.5">+ <div className="min-w-0 flex-1">+ <div className="text-[15px] text-fg break-words">{item.text}</div>+ <div className={`mt-0.5 text-sm ${item.overdue ? TONE_TEXT.amber : "text-fg-muted"}`}>+ {item.dueLabel}+ </div>+ </div>+ <Button+ size="sm"+ variant="secondary"+ onClick={() => void markDone(item.loop.loop_id)}+ disabled={busyId !== null}+ >+ {busyId === item.loop.loop_id ? "Closing…" : "Done"}+ </Button>+ </div>+ ))}+ </div>+ {view.later > 0 && <p className="pt-2 text-sm text-fg-muted">{view.later} more due later.</p>}+ </>+ )}+ </>+ );+}++// ── This week's review ────────────────────────────────────────────────────+// The latest weekly review (GET /today/weekly-review) — when it ran and next+// week's top three, with a link to the whole review on its run page. Null+// until a review has run, and for anyone but the owner.+export function useWeeklyReview(enabled: boolean) {+ const [review, setReview] = useState<WeeklyReviewSummary | null>(null);+ useEffect(() => {+ if (!enabled) return;+ const controller = new AbortController();+ getWeeklyReview(controller.signal)+ .then(setReview)+ .catch(() => { /* no card is better than a broken one */ });+ return () => controller.abort();+ }, [enabled]);+ return review;+}++export function weeklyReviewMeta(review: WeeklyReviewSummary): string {+ return [review.period, reviewRanLabel(review.completed_at)].filter(Boolean).join(" · ");+}++export function WeeklyReviewPanelBody({ review }: { review: WeeklyReviewSummary }) {+ const excerpt = reviewExcerpt(review);+ const meta = weeklyReviewMeta(review);+ return (+ <>+ <PanelIntro>+ Once a week the Executive looks back on your week — your goals by area, what's due, projects that went+ quiet and the decisions you made — and picks next week's top three. It's also sent to you when a+ chat app or email is connected.+ </PanelIntro>+ {meta && <p className="mb-3 text-sm text-fg-muted">{meta}</p>}+ {excerpt.heading && (+ <div className="mb-1 text-xs font-semibold uppercase tracking-wide text-fg-muted">{excerpt.heading}</div>+ )}+ {excerpt.numbered ? (+ <ol className="divide-y divide-line">+ {excerpt.lines.map((line, i) => (+ <li key={i} className="flex items-start gap-3 py-3">+ <RankBadge n={i + 1} />+ <span className="min-w-0 flex-1 text-[15px] text-fg break-words">{line}</span>+ </li>+ ))}+ </ol>+ ) : (+ excerpt.lines.map((line, i) => (+ <p key={i} className="py-0.5 text-[15px] text-fg-muted break-words">+ {line}+ </p>+ ))+ )}+ <Link+ href={`/jobs/runs/${encodeURIComponent(review.run_id)}`}+ className="mt-4 inline-block text-sm font-medium text-accent hover:underline"+ >+ Read the review →+ </Link>+ </>+ );+}++// ── Top three today ───────────────────────────────────────────────────────+// The three things to focus on today — the same pick, order and free slots+// as the morning brief (GET /today/top-three). Solo's main job, so it stays+// on Home as a short list under Needs you. Loads on its own after the+// briefing, since it may wait on the calendar (up to 4 s), and hides when+// there is nothing to pick or the viewer isn't the owner (the API returns+// null). `ownerName` turns a commitment's stored text into "you" wording.+export function TopThreeList({ ownerName, id }: { ownerName: string; id?: string }) {+ const [top, setTop] = useState<TopThreeToday | null>(null);++ useEffect(() => {+ const controller = new AbortController();+ getTopThree(controller.signal)+ .then(setTop)+ .catch(() => { /* no card is better than a broken one */ });+ return () => controller.abort();+ }, []);++ if (!top || top.items.length === 0) return null;+ return (+ <section id={id}>+ <div className="mb-3 flex items-center gap-1.5">+ <h2 className="text-lg font-semibold text-fg">Top three today</h2>+ <InfoTip align="left">+ The three things to focus on today, picked from what's overdue or due, goals that are slipping and+ your active projects — the same three your morning brief opens with. When the Executive can read your+ calendar, each gets a free slot in today's working hours.+ </InfoTip>+ </div>+ <ol className="divide-y divide-line rounded-2xl border border-line bg-surface-elevated px-4 sm:px-5">+ {top.items.map((item, i) => {+ const text =+ item.kind === "commitment" && ownerName+ ? loopText({ description: item.text, owner_name: ownerName })+ : item.text;+ const slot = topThreeSlot(item);+ return (+ <li key={item.key} className="flex items-start gap-3 py-3.5">+ <RankBadge n={i + 1} />+ <div className="min-w-0 flex-1">+ <div className="text-[15px] text-fg break-words">{text}</div>+ <div className="mt-0.5 text-sm text-fg-muted">{topThreeWhy(item)}</div>+ </div>+ {slot && (+ <span className={`mt-0.5 flex-shrink-0 text-sm tabular-nums ${item.slot ? "text-accent" : "text-fg-muted"}`}>+ {slot}+ </span>+ )}+ </li>+ );+ })}+ </ol>+ </section>+ );+}diff --git a/packages/ui/src/components/briefing/TeamPanels.tsx b/packages/ui/src/components/briefing/TeamPanels.tsxnew file mode 100644index 00000000..91a0ac14--- /dev/null+++ b/packages/ui/src/components/briefing/TeamPanels.tsx@@ -0,0 +1,259 @@+"use client";++import Link from "next/link";+import { useState } from "react";++import type { DepartmentBriefItem, PersonBriefItem } from "@/lib/api";++import { Chip, ClickableBriefingItem, PanelIntro, TONE_TEXT, formatRelTime, type ContinueHandler } from "./shared";++// The team-only side panels behind Home's Departments and People tiles.++export function DeptCard({+ dept,+ onContinue,+ dimmed = false,+}: {+ dept: DepartmentBriefItem;+ onContinue?: ContinueHandler;+ dimmed?: boolean;+}) {+ const hasIssues = dept.at_risk_count > 0 || dept.off_track_count > 0;+ const prompt = `Tell me about ${dept.title} — what's the current status?`;+ // Problem goals beyond the inline cap fall to the department page.+ const attentionGoalOverflow =+ dept.at_risk_count + dept.off_track_count - (dept.attention_goals?.length ?? 0);+ return (+ <ClickableBriefingItem+ onContinue={onContinue}+ prompt={prompt}+ href={`/departments/${dept.slug}`}+ className={`block group rounded-xl -mx-2 px-2 py-3.5 hover:bg-surface-overlay transition-colors${dimmed ? " opacity-60 hover:opacity-100" : ""}`}+ >+ <div className="flex items-start justify-between gap-2 mb-2">+ <div className="text-base font-semibold text-fg group-hover:text-accent transition-colors" title={dept.title}>+ {dept.title}+ </div>+ <span className="flex-shrink-0 text-xs text-fg-muted">{dept.authority_level.replace("_", " ")}</span>+ </div>+ <div className="flex flex-wrap items-center gap-2 text-sm">+ <span className="text-fg-muted">+ {dept.goal_count} goal{dept.goal_count !== 1 ? "s" : ""}+ </span>+ {dept.at_risk_count > 0 && <Chip tone="amber">{dept.at_risk_count} at risk</Chip>}+ {dept.off_track_count > 0 && <Chip tone="rose">{dept.off_track_count} off track</Chip>}+ {!hasIssues && dept.goal_count > 0 && <Chip tone="emerald">on track</Chip>}+ {dept.awaiting_count > 0 && <Chip tone="sky">{dept.awaiting_count} awaiting</Chip>}+ </div>+ {/* The actual off-track / at-risk goals, inline — so the row is+ insightful at rest instead of a count you have to click into. */}+ {dept.attention_goals && dept.attention_goals.length > 0 && (+ <div className="mt-3 space-y-1.5 border-t border-line pt-2.5">+ {dept.attention_goals.map((g, i) => (+ <div key={i} className="flex items-start gap-2 text-sm leading-snug">+ <span+ aria-hidden="true"+ className={`mt-1.5 h-2 w-2 flex-shrink-0 rounded-full ${g.status === "off_track" ? "bg-rose-400" : "bg-amber-400"}`}+ />+ <span className="min-w-0">+ <span className="text-fg">{g.key_result}</span>+ {(g.current || g.target) && (+ <span className="text-fg-subtle"> — {g.current || "—"} vs {g.target || "—"}</span>+ )}+ </span>+ </div>+ ))}+ {attentionGoalOverflow > 0 && <div className="pl-4 text-xs text-fg-subtle">+{attentionGoalOverflow} more</div>}+ </div>+ )}+ </ClickableBriefingItem>+ );+}++// Departments: those needing attention first; healthy and inactive ones fold+// into one quiet toggle.+export function DepartmentsPanelBody({+ departments,+ onContinue,+}: {+ departments: DepartmentBriefItem[];+ onContinue?: ContinueHandler;+}) {+ const [showQuiet, setShowQuiet] = useState(false);+ const active = departments.filter((d) => d.goal_count > 0 || d.awaiting_count > 0);+ const inactive = departments.filter((d) => d.goal_count === 0 && d.awaiting_count === 0);+ const attention = active.filter((d) => d.at_risk_count > 0 || d.off_track_count > 0 || d.awaiting_count > 0);+ const onTrack = active.filter((d) => d.at_risk_count === 0 && d.off_track_count === 0 && d.awaiting_count === 0);+ const quietCount = onTrack.length + inactive.length;+ const quietSummary = [+ onTrack.length > 0 ? `${onTrack.length} on track` : null,+ inactive.length > 0 ? `${inactive.length} inactive` : null,+ ]+ .filter(Boolean)+ .join(" · ");+ return (+ <>+ <PanelIntro>+ <span className={TONE_TEXT.amber}>At risk</span> / <span className={TONE_TEXT.rose}>off track</span> = goal+ health. <span className={TONE_TEXT.sky}>Awaiting</span> = items waiting on the department head.{" "}+ <span className="text-fg">Inactive</span> = no goals or check-ins set up yet. Tap a department to talk it+ through.+ </PanelIntro>+ {active.length === 0 && (+ <div className="py-3">+ <p className="mb-2 text-[15px] text-fg-muted">No department has a check-in set up yet.</p>+ <Link href="/departments" className="text-sm font-medium text-accent hover:underline">+ Pick one to activate →+ </Link>+ </div>+ )}+ {attention.length > 0 && (+ <div className="divide-y divide-line">+ {attention.map((d) => (+ <DeptCard key={d.slug} dept={d} onContinue={onContinue} />+ ))}+ </div>+ )}+ {quietCount > 0 && (+ <div className={attention.length > 0 ? "mt-3 border-t border-line pt-2" : ""}>+ <button+ type="button"+ onClick={() => setShowQuiet((v) => !v)}+ aria-expanded={showQuiet}+ className="flex min-h-[44px] items-center gap-2 text-sm font-medium text-fg-muted hover:text-fg transition-colors"+ >+ <span aria-hidden="true" className={`text-xs transition-transform ${showQuiet ? "rotate-90" : ""}`}>+ ▸+ </span>+ {quietSummary}+ </button>+ {showQuiet && (+ <div className="divide-y divide-line">+ {onTrack.map((d) => (+ <DeptCard key={d.slug} dept={d} onContinue={onContinue} />+ ))}+ {inactive.map((d) => (+ <DeptCard key={d.slug} dept={d} onContinue={onContinue} dimmed />+ ))}+ </div>+ )}+ </div>+ )}+ </>+ );+}++// Compact label for an authority-scope token (see people/models.py).+const AUTHORITY_LABELS: Record<string, string> = {+ spend_lt_2k: "spend<2k",+ spend_lt_10k: "spend<10k",+ spend_gt_10k: "spend>10k",+ hiring_signoff: "hiring",+ vendor_onboarding: "vendors",+ customer_credit: "credit",+ legal_sign: "legal",+ board_comms: "board",+ wildcard: "all",+};++function authorityLabel(token: string): string {+ return AUTHORITY_LABELS[token] ?? token;+}++// Status chip text + tone. `overdue` repaints the attention states red.+function personStatusChip(person: PersonBriefItem): { label: string; tone: "rose" | "amber" | "sky" | "neutral" } | null {+ switch (person.status) {+ case "needs_reply":+ return {+ label: person.awaiting_reply_count > 1 ? `${person.awaiting_reply_count} awaiting reply` : "Awaiting reply",+ tone: person.overdue ? "rose" : "amber",+ };+ case "awaiting":+ return { label: `${person.awaiting_count} to action`, tone: person.overdue ? "rose" : "sky" };+ case "on_leave":+ return { label: "On leave", tone: "neutral" };+ default:+ return null; // "clear" — no chip, shown as subtle text instead+ }+}++function PersonRow({ person }: { person: PersonBriefItem }) {+ const chip = personStatusChip(person);+ const pills = person.authority_scope.slice(0, 2);+ const extraPills = person.authority_scope.length - pills.length;+ return (+ <Link+ href={`/people/${person.id}`}+ className="block group rounded-xl -mx-2 px-2 py-3.5 hover:bg-surface-overlay transition-colors"+ >+ <div className="flex items-center justify-between gap-3">+ <div className="flex min-w-0 items-center gap-3">+ <div className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-indigo-500 to-violet-600">+ <span className="text-sm font-bold text-white">{person.full_name.charAt(0)}</span>+ </div>+ <div className="min-w-0">+ <div className="truncate text-[15px] font-medium text-fg">{person.full_name}</div>+ <div className="truncate text-sm text-fg-muted">{person.role}</div>+ </div>+ </div>+ <div className="flex-shrink-0 text-right">+ {chip ? <Chip tone={chip.tone}>{chip.label}</Chip> : <span className="text-sm text-fg-subtle">Clear</span>}+ {chip && person.status === "awaiting" && person.soonest_sla_at && (+ <div className={`mt-0.5 text-xs ${person.overdue ? TONE_TEXT.rose : "text-fg-muted"}`}>+ SLA {person.overdue ? "overdue" : `in ${formatRelTime(person.soonest_sla_at)}`}+ </div>+ )}+ </div>+ </div>++ {person.insight && <p className="mt-2 text-sm leading-snug text-fg-muted line-clamp-2">{person.insight}</p>}++ <div className="mt-2 flex flex-wrap items-center gap-1.5">+ {person.status !== "on_leave" && (+ <span className="inline-flex items-center gap-1.5 text-xs text-fg-subtle">+ <span className={`h-2 w-2 rounded-full ${person.reachable_now ? "bg-emerald-400" : "bg-slate-500"}`} />+ {person.reachable_now+ ? "Available"+ : person.next_window_at+ ? `Back in ${formatRelTime(person.next_window_at)}`+ : "Away"}+ </span>+ )}+ {pills.map((tok) => (+ <span key={tok} className="rounded-md border border-line bg-surface-overlay px-1.5 py-px text-[11px] text-fg-subtle">+ {authorityLabel(tok)}+ </span>+ ))}+ {extraPills > 0 && <span className="text-[11px] text-fg-subtle">+{extraPills}</span>}+ </div>+ </Link>+ );+}++// One-line roster summary: the People tile's sub-line and the panel's.+export function peopleSummary(people: PersonBriefItem[]): { text: string; hasOverdue: boolean } {+ const needsReply = people.filter((p) => p.status === "needs_reply").length;+ const awaiting = people.filter((p) => p.status === "awaiting").length;+ const onLeave = people.filter((p) => p.status === "on_leave").length;+ const overdue = people.filter((p) => p.overdue).length;+ const parts: string[] = [];+ if (needsReply > 0) parts.push(`${needsReply} to reply`);+ if (awaiting > 0) parts.push(`${awaiting} to action`);+ if (overdue > 0) parts.push(`${overdue} overdue`);+ if (onLeave > 0) parts.push(`${onLeave} on leave`);+ return { text: parts.length > 0 ? parts.join(" · ") : "All clear", hasOverdue: overdue > 0 };+}++export function PeoplePanelBody({ people }: { people: PersonBriefItem[] }) {+ const summary = peopleSummary(people);+ return (+ <>+ <p className={`mb-2 text-[15px] ${summary.hasOverdue ? TONE_TEXT.rose : "text-fg-muted"}`}>{summary.text}</p>+ <div className="divide-y divide-line">+ {people.map((p) => (+ <PersonRow key={p.id} person={p} />+ ))}+ </div>+ </>+ );+}diff --git a/packages/ui/src/components/briefing/shared.tsx b/packages/ui/src/components/briefing/shared.tsxnew file mode 100644index 00000000..09fe7179--- /dev/null+++ b/packages/ui/src/components/briefing/shared.tsx@@ -0,0 +1,174 @@+"use client";++import Link from "next/link";++import type { ProposalItem } from "@/lib/api";++// Pieces every part of the Home briefing shares: the chat hand-off type, the+// seeds it sends, the bulk-dismiss cutoffs and a few small renderers.++// Hands a briefing item to chat. `memoryText` is what peer memory records as+// the user's words for that turn; omit it when `prompt` is already just the+// user's own ask.+export type ContinueHandler = (prompt: string, memoryText?: string) => void;++// Bulk-dismiss cutoffs (days): Needs you's ⋯ menu and the Monitoring panel.+export const NEEDS_YOU_DISMISS_OLDER_THAN_DAYS = 7;+export const MONITORING_DISMISS_OLDER_THAN_DAYS = 3;++// Ids of proposals older than `days` — what a bulk "Dismiss older than"+// sends: explicit ids from the caller's own lane (visible cards and those+// behind "Show more" alike), never a server-side age sweep, which would also+// hit teammates' routed items.+export function olderThan(proposals: ProposalItem[], days: number, now: Date = new Date()): number[] {+ const cutoff = now.getTime() - days * 86400000;+ return proposals+ .filter((p) => {+ // Same age anchor as the server's TTL: a re-firing situation is not old.+ const t = Date.parse(p.last_seen_at ?? p.created_at);+ return !Number.isNaN(t) && t < cutoff;+ })+ .map((p) => p.alert_id);+}++// Future-relative label for a pending run time ("in 8h"). Past/blank →+// "soon" (the caller renders "overdue" separately via the backend flag).+export function formatFuture(iso: string): string {+ const then = new Date(iso).getTime();+ if (Number.isNaN(then)) return "soon";+ const mins = Math.round((then - Date.now()) / 60000);+ if (mins <= 0) return "soon";+ if (mins < 60) return `in ${mins}m`;+ const hrs = Math.round(mins / 60);+ if (hrs < 24) return `in ${hrs}h`;+ return `in ${Math.round(hrs / 24)}d`;+}++export function formatRelTime(iso: string): string {+ try {+ const diff = new Date(iso).getTime() - Date.now();+ const abs = Math.abs(diff);+ if (abs < 60_000) return "now";+ if (abs < 3_600_000) return `${Math.round(abs / 60_000)}m`;+ if (abs < 86_400_000) return `${Math.round(abs / 3_600_000)}h`;+ return `${Math.round(abs / 86_400_000)}d`;+ } catch {+ return "—";+ }+}++// Seed prompt for a clicked narrative bullet. The Executive receives the+// open-alert digest as a <briefing> block on every chat turn, so the seed only+// needs to name the item — the exec matches it by headline. No alert_id is+// carried (the bullet has none); acking stays on the proposal card.+export function buildNarrativeSeed(text: string): string {+ return (+ `Let's dig into this from today's briefing:\n\n"${text}"\n\n` ++ `[Discuss mode] Walk me through what's going on, why it matters, and what ` ++ `you'd recommend. The full details are in your briefing context. Answer ` ++ `conversationally — don't take any action unless I explicitly ask.`+ );+}++// Discuss-handoff seed for a passive monitoring signal — shared by the+// ProposalCard monitoring branch and the Monitoring panel so the two entry+// points stay in sync (don't approve, just interpret the signal).+export function buildMonitoringSeed(proposal: ProposalItem): string {+ const body = proposal.body || proposal.headline;+ return (+ `Help me understand this signal we're monitoring:\n\n${body}\n\n` ++ `[Discuss mode — alert_id=${proposal.alert_id}] This is a passive ` ++ `monitoring signal, not a proposal to approve. Explain why it matters, ` ++ `whether it warrants any action, and what you'd recommend. Answer ` ++ `conversationally. Only if I explicitly ask you to act should you do ` ++ `more than advise; do not ack or dismiss the alert yourself.`+ );+}++// Status colours that read on both themes: the light theme gets the darker+// shade, the dark theme the lighter one.+export const TONE = {+ amber: "bg-amber-500/15 text-amber-700 dark:text-amber-300",+ rose: "bg-rose-500/15 text-rose-700 dark:text-rose-300",+ emerald: "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300",+ sky: "bg-sky-500/15 text-sky-700 dark:text-sky-300",+ neutral: "bg-surface-overlay text-fg-muted",+} as const;++export const TONE_TEXT = {+ amber: "text-amber-700 dark:text-amber-300",+ rose: "text-rose-700 dark:text-rose-300",+ emerald: "text-emerald-700 dark:text-emerald-300",+ sky: "text-sky-700 dark:text-sky-300",+} as const;++// A small status chip: a word on a soft tint.+export function Chip({+ tone = "neutral",+ title,+ children,+}: {+ tone?: keyof typeof TONE;+ title?: string;+ children: React.ReactNode;+}) {+ return (+ <span+ title={title}+ className={`inline-flex items-center rounded-lg px-2 py-0.5 text-[13px] font-medium ${TONE[tone]}`}+ >+ {children}+ </span>+ );+}++// Either a button (when onContinue is provided — seeds chat with prompt)+// or a Link (no chat to hand to). Same visual styling either way.+export function ClickableBriefingItem({+ onContinue,+ prompt,+ href,+ className,+ children,+}: {+ onContinue?: ContinueHandler;+ prompt: string;+ href: string;+ className: string;+ children: React.ReactNode;+}) {+ if (onContinue) {+ return (+ <button+ type="button"+ onClick={() => onContinue(prompt)}+ className={`${className} text-left w-full cursor-pointer`}+ >+ {children}+ </button>+ );+ }+ return (+ <Link href={href} className={className}>+ {children}+ </Link>+ );+}++// The muted explainer at the top of a side panel (what an InfoTip used to say+// next to the section heading).+export function PanelIntro({ children }: { children: React.ReactNode }) {+ return <p className="mb-4 text-sm leading-relaxed text-fg-muted">{children}</p>;+}++// A numbered row's number, shared by the solo focus lists.+export function RankBadge({ n }: { n: number }) {+ return (+ <span+ aria-hidden="true"+ className="mt-0.5 flex-shrink-0 w-6 h-6 rounded-full bg-accent/15 text-accent text-xs font-semibold tabular-nums flex items-center justify-center"+ >+ {n}+ </span>+ );+}diff --git a/packages/ui/src/components/company-profile/ProfileSections.tsx b/packages/ui/src/components/company-profile/ProfileSections.tsxindex 38271561..6c547d6e 100644--- a/packages/ui/src/components/company-profile/ProfileSections.tsx+++ b/packages/ui/src/components/company-profile/ProfileSections.tsx@@ -10,6 +10,7 @@import { useEffect, useState, useRef } from "react";import { PROFILE_COPY, type ProfileCopy } from "@/components/company-profile/profileCopy";+import Button from "@/components/ui/Button";import type { ProfileWording } from "@/components/shell/navConfig";import { type CompanyProfile } from "@/lib/api";@@ -91,22 +92,22 @@ export function snapshotProfile(profile: CompanyProfile): Record<string, unknownfunction FieldLabel({ children }: { children: React.ReactNode }) {return (- <p className="text-xs text-fg-muted font-medium uppercase tracking-wide mb-1">+ <p className="text-sm text-fg-muted font-medium mb-1.5">{children}</p>);}function FieldValue({ children }: { children: React.ReactNode }) {- return <p className="text-sm text-fg">{children || <span className="text-fg-subtle italic">Not set</span>}</p>;+ return <p className="text-[15px] text-fg leading-relaxed">{children || <span className="text-fg-subtle italic">Not set</span>}</p>;}function Pills({ items }: { items: string[] }) {- if (!items.length) return <span className="text-sm text-fg-subtle italic">Not set</span>;+ if (!items.length) return <span className="text-[15px] text-fg-subtle italic">Not set</span>;return (<div className="flex flex-wrap gap-1.5">{items.map((item, i) => (- <span key={i} className="inline-block px-2 py-0.5 bg-surface-overlay text-fg text-xs rounded-md">+ <span key={i} className="inline-block px-2.5 py-1 bg-surface-overlay text-fg text-sm rounded-lg">{item}</span>))}@@ -131,7 +132,7 @@ function Input({value={value}onChange={(e) => onChange(e.target.value)}placeholder={placeholder}- className="w-full rounded-lg border border-line-strong bg-surface-overlay px-3 py-2 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500/50 transition-colors"+ className="w-full h-11 rounded-xl border border-line-strong bg-surface-overlay px-3 text-[15px] text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-accent/50 focus:border-accent/50 transition-colors"/>);}@@ -153,7 +154,7 @@ function Textarea({onChange={(e) => onChange(e.target.value)}rows={rows}placeholder={placeholder}- className="w-full rounded-lg border border-line-strong bg-surface-overlay px-3 py-2 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500/50 resize-none transition-colors"+ className="w-full rounded-xl border border-line-strong bg-surface-overlay px-3 py-2.5 text-[15px] text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-accent/50 focus:border-accent/50 resize-none transition-colors"/>);}@@ -195,16 +196,13 @@ function Section({}return (- <div className="bg-surface-elevated border border-line rounded-xl p-5">- <div className="flex items-center justify-between mb-4">- <h2 className="text-sm font-semibold text-fg">{title}</h2>+ <div className="bg-surface-elevated border border-line rounded-2xl p-5 sm:p-6 min-w-0">+ <div className="flex items-center justify-between gap-3 mb-4 min-h-11">+ <h2 className="text-lg font-semibold text-fg">{title}</h2>{!editing && (- <button- onClick={() => setEditing(true)}- className="text-xs text-indigo-400 hover:text-indigo-300 transition-colors"- >+ <Button onClick={() => setEditing(true)} aria-label={`Edit ${title}`}>Edit- </button>+ </Button>)}</div>@@ -212,22 +210,14 @@ function Section({{editing && (<>- {error && <p className="text-xs text-red-400 mt-3">{error}</p>}- <div className="flex gap-2 mt-4">- <button- onClick={handleSave}- disabled={saving}- className="px-3 py-1.5 bg-indigo-500 hover:bg-indigo-600 disabled:opacity-40 text-white text-xs font-medium rounded-lg transition-colors"- >+ {error && <p className="text-sm text-red-500 mt-3">{error}</p>}+ <div className="flex gap-2 mt-5">+ <Button variant="primary" onClick={handleSave} disabled={saving}>{saving ? "Saving…" : "Save"}- </button>- <button- onClick={() => { setEditing(false); setError(null); }}- disabled={saving}- className="px-3 py-1.5 border border-line-strong text-fg-muted hover:text-fg text-xs rounded-lg transition-colors disabled:opacity-40"- >+ </Button>+ <Button onClick={() => { setEditing(false); setError(null); }} disabled={saving}>Cancel- </button>+ </Button></div></>)}@@ -300,7 +290,7 @@ function CompanyBasicsSection({ profile, saving, onSave, pending, copy }: Sectioannual_revenue_arr: arr ? parseFloat(arr) : null,})}viewContent={- <div className="grid grid-cols-2 gap-x-8 gap-y-4">+ <div className="grid grid-cols-2 gap-x-6 gap-y-4"><div><FieldLabel>Name</FieldLabel><FieldValue>{profile.name}</FieldValue></div><div><FieldLabel>Industry</FieldLabel><FieldValue>{profile.industry}</FieldValue></div><div><FieldLabel>Stage</FieldLabel><FieldValue>{profile.stage}</FieldValue></div>@@ -310,7 +300,7 @@ function CompanyBasicsSection({ profile, saving, onSave, pending, copy }: Sectio</div>}editContent={- <div className="grid grid-cols-2 gap-3">+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3"><div><FieldLabel>Name</FieldLabel><Input value={name} onChange={setName} placeholder="Acme Corp" /></div><div><FieldLabel>Industry</FieldLabel><Input value={industry} onChange={setIndustry} placeholder="B2B SaaS" /></div><div><FieldLabel>Stage</FieldLabel><Input value={stage} onChange={setStage} placeholder="Series A" /></div>@@ -450,7 +440,7 @@ function ExternalDependenciesSection({ profile, saving, onSave, pending, copy }:onSave={() => onSave({ vendors: textToList(vendors), tickers: textToList(tickers) })}viewContent={<div className="space-y-4">- <p className="text-xs text-fg-subtle">{copy.dependenciesNote}</p>+ <p className="text-sm text-fg-subtle">{copy.dependenciesNote}</p><div><FieldLabel>Vendors & dependencies</FieldLabel><Pills items={profile.vendors ?? []} /></div><div><FieldLabel>Tracked tickers</FieldLabel><Pills items={profile.tickers ?? []} /></div></div>@@ -600,13 +590,13 @@ function FinancialsSection({ profile, saving, onSave, pending }: SectionComponen}})}viewContent={- <div className="grid grid-cols-2 gap-x-8 gap-y-4">+ <div className="grid grid-cols-2 gap-x-6 gap-y-4"><div><FieldLabel>Monthly Burn</FieldLabel><FieldValue>{profile.financials.burn_rate_monthly != null ? `$${profile.financials.burn_rate_monthly.toLocaleString()}/mo` : undefined}</FieldValue></div><div><FieldLabel>Runway</FieldLabel><FieldValue>{profile.financials.runway_months != null ? `${profile.financials.runway_months} months` : undefined}</FieldValue></div></div>}editContent={- <div className="grid grid-cols-2 gap-3">+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3"><div><FieldLabel>Monthly Burn ($)</FieldLabel><Input value={burn} onChange={setBurn} type="number" placeholder="50000" /></div><div><FieldLabel>Runway (months)</FieldLabel><Input value={runway} onChange={setRunway} type="number" placeholder="18" /></div></div>@@ -667,6 +657,9 @@ export interface ProfileSectionsProps {/** What the profile is called: "company" (team, the default), or in solo* "business" (an owner) or "work" (anyone else). Copy only. */wording?: ProfileWording;+ /** "columns" lays the cards out two across on wide screens (the profile+ * page); "stack" (the default) is one column, as onboarding shows them. */+ layout?: "stack" | "columns";}export function ProfileSections({@@ -676,11 +669,12 @@ export function ProfileSections({pending = null,omit = [],wording = "company",+ layout = "stack",}: ProfileSectionsProps) {const hidden = new Set(omit);const copy = PROFILE_COPY[wording];return (- <div className="flex flex-col gap-4">+ <div className={layout === "columns" ? "grid grid-cols-1 xl:grid-cols-2 gap-5 items-start" : "flex flex-col gap-4"}>{SECTION_ORDER.filter(({ id }) => !hidden.has(id)).map(({ id, Component }) => (<Componentkey={id}diff --git a/packages/ui/src/components/executive/ExecutiveRunSwitch.tsx b/packages/ui/src/components/executive/ExecutiveRunSwitch.tsxindex 0c27eb34..5de5c7f4 100644--- a/packages/ui/src/components/executive/ExecutiveRunSwitch.tsx+++ b/packages/ui/src/components/executive/ExecutiveRunSwitch.tsx@@ -4,6 +4,7 @@ import { useState } from "react";import Icon from "@/components/Icon";import { formatPausedAt, useExecutiveStatus } from "@/components/executive/ExecutiveStatusContext";+import Button from "@/components/ui/Button";// What a pause does and does not stop — shown before pausing so the// principal knows chat stays live.@@ -16,37 +17,31 @@ function heldLabel(n: number): string {}/**- * Pause / resume the Executive's autonomous work.- *- * - `sidebar`: a one-line status row in the shared sidebar footer that- * expands into the pause/resume panel.- * - `card`: the body of the Settings page's Executive section — a status- * row that opens into the pause form on request, and stays open while- * paused so the held count and Resume are always in view.+ * Pause / resume the Executive's autonomous work: the body of the run card+ * on Settings → Your Executive. A status row with one button — Pause… opens+ * the pause form (scope and an optional reason); while paused, who paused it+ * and the held count stay in view with Resume as the button.*/-export default function ExecutiveRunSwitch({ variant }: { variant: "sidebar" | "card" }) {+export default function ExecutiveRunSwitch() {const { status, unknown, busy, error, pause, resume } = useExecutiveStatus();const [expanded, setExpanded] = useState(false);const [reason, setReason] = useState("");- if (!status) return null;+ if (!status) return <p className="text-[15px] text-fg-muted">Loading…</p>;if (unknown) {// The last status read failed: say so rather than show a stale state,// and offer no action whose effect we can't confirm.return (- <div className={variant === "card" ? "" : "pb-1"} title="Couldn't reach the backend — retrying">- <div- className={`flex items-center gap-2.5 text-sm text-fg-muted ${variant === "card" ? "" : "px-3 py-2"}`}- >- <span className="inline-block w-2 h-2 rounded-full flex-shrink-0 bg-fg-subtle" aria-hidden="true" />- <span className="truncate">Executive status unknown</span>- </div>+ <div+ className="flex items-center gap-2.5 text-[15px] text-fg-muted"+ title="Couldn't reach the backend — retrying"+ >+ <span className="inline-block w-2.5 h-2.5 rounded-full flex-shrink-0 bg-fg-subtle" aria-hidden="true" />+ <span>Executive status unknown</span></div>);}const paused = status.paused;- // The card opens on request while running and always while paused.- const open = variant === "card" ? paused || expanded : expanded;// Collapse only on success so a failure's error stays visible.const onPause = async () => {@@ -55,25 +50,43 @@ export default function ExecutiveRunSwitch({ variant }: { variant: "sidebar" | "setExpanded(false);}};- const onResume = async () => {- if (await resume()) setExpanded(false);- };- const dot = (- <span- className={`inline-block w-2 h-2 rounded-full flex-shrink-0 ${- paused ? "bg-amber-400" : "bg-emerald-400"- }`}- aria-hidden="true"- />- );- const label = paused ? "Executive paused" : "Executive running";+ return (+ <div>+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="flex items-center gap-2.5 text-base font-semibold text-fg">+ <span+ className={`inline-block w-2.5 h-2.5 rounded-full flex-shrink-0 ${+ paused ? "bg-amber-400" : "bg-emerald-500"+ }`}+ aria-hidden="true"+ />+ <span>{paused ? "Paused" : "Running"}</span>+ </div>+ {paused ? (+ status.can_resume && (+ <Button variant="primary" onClick={() => void resume()} disabled={busy}>+ <Icon name="play" size="w-4 h-4" />+ {busy ? "Resuming…" : "Resume"}+ </Button>+ )+ ) : (+ !expanded && (+ <Button+ onClick={() => setExpanded(true)}+ aria-expanded={false}+ aria-controls="executive-pause-panel"+ >+ <Icon name="pause" size="w-4 h-4" />+ Pause…+ </Button>+ )+ )}+ </div>- const panel = (- <div className="space-y-2.5">{paused ? (- <>- <p className="text-xs text-fg-muted leading-relaxed">+ <div className="mt-3 space-y-1.5">+ <p className="text-sm text-fg-muted leading-relaxed">Paused{status.paused_at && <> since {formatPausedAt(status.paused_at)}</>}{status.paused_by && <> by {status.paused_by}</>}.@@ -84,24 +97,14 @@ export default function ExecutiveRunSwitch({ variant }: { variant: "sidebar" | "</>)}</p>- <p className="text-xs text-amber-300">{heldLabel(status.held_actions)}</p>- {!status.can_resume ? (- <p className="text-xs text-fg-muted">Only the principal can resume the Executive.</p>- ) : (- <button- type="button"- onClick={onResume}- disabled={busy}- className="w-full flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium bg-emerald-500/15 text-emerald-200 hover:bg-emerald-500/25 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"- >- <Icon name="play" size="w-3.5 h-3.5" />- {busy ? "Resuming…" : "Resume Executive"}- </button>+ <p className="text-sm text-amber-500">{heldLabel(status.held_actions)}</p>+ {!status.can_resume && (+ <p className="text-sm text-fg-muted">Only the principal can resume the Executive.</p>)}- </>- ) : (- <>- <p className="text-xs text-fg-muted leading-relaxed">{PAUSE_SCOPE}</p>+ </div>+ ) : expanded ? (+ <div id="executive-pause-panel" className="mt-4 space-y-3">+ <p className="text-sm text-fg-muted leading-relaxed">{PAUSE_SCOPE}</p><inputtype="text"value={reason}@@ -112,75 +115,24 @@ export default function ExecutiveRunSwitch({ variant }: { variant: "sidebar" | "}}placeholder="Reason (optional)"aria-label="Reason for pausing (optional)"- className="w-full px-2.5 py-1.5 rounded-lg text-xs bg-surface border border-line text-fg placeholder:text-fg-subtle focus:outline-none focus:border-line-strong"+ className="w-full h-11 px-3.5 rounded-xl text-[15px] bg-surface border border-line text-fg placeholder:text-fg-subtle focus:outline-none focus:border-line-strong"/>- <button- type="button"- onClick={onPause}- disabled={busy}- className="w-full flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium bg-amber-500/15 text-amber-200 hover:bg-amber-500/25 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"- >- <Icon name="pause" size="w-3.5 h-3.5" />- {busy ? "Pausing…" : "Pause Executive"}- </button>- </>- )}- {error && <p className="text-xs text-red-400">{error}</p>}- </div>- );-- if (variant === "card") {- return (- <div className="max-w-md">- <div className="flex items-center justify-between gap-3">- <div className="flex items-center gap-2.5 text-sm font-medium text-fg">- {dot}- <span>{label}</span>+ <div className="flex flex-wrap items-center gap-2">+ <Button variant="primary" onClick={() => void onPause()} disabled={busy}>+ <Icon name="pause" size="w-4 h-4" />+ {busy ? "Pausing…" : "Pause Executive"}+ </Button>+ <Button variant="ghost" onClick={() => setExpanded(false)} disabled={busy}>+ Cancel+ </Button></div>- {!paused && (- <button- type="button"- onClick={() => setExpanded((v) => !v)}- aria-expanded={open}- aria-controls="executive-pause-panel"- className="flex items-center gap-1 text-xs text-fg-muted hover:text-fg transition-colors cursor-pointer"- >- Pause…- <Icon- name="chevron-right"- size="w-3.5 h-3.5"- className={`transition-transform ${open ? "rotate-90" : ""}`}- />- </button>- )}</div>- {open && (- <div id="executive-pause-panel" className="mt-3">- {panel}- </div>- )}- </div>- );- }-- return (- <div className="pb-1">- <button- type="button"- onClick={() => setExpanded((v) => !v)}- aria-expanded={open}- title={paused ? "Autonomous work is on hold — click to resume" : "Pause the Executive's autonomous work"}- className={`w-full flex items-center gap-2.5 px-3 py-2 rounded-lg text-sm transition-colors cursor-pointer ${- paused- ? "text-amber-200 bg-amber-500/10 hover:bg-amber-500/15"- : "text-fg-muted hover:text-fg hover:bg-surface-overlay"- }`}- >- {dot}- <span className="flex-1 text-left truncate">{label}</span>- <Icon name={paused ? "play" : "pause"} size="w-4 h-4" />- </button>- {open && <div className="px-3 pt-2 pb-1">{panel}</div>}+ ) : (+ <p className="mt-2 text-sm text-fg-muted leading-relaxed">+ Doing its own work — briefs, nudges, monitoring, inbox and workflow timers.+ </p>+ )}+ {error && <p className="mt-2 text-sm text-red-500">{error}</p>}</div>);}diff --git a/packages/ui/src/components/executive/VoicePicker.tsx b/packages/ui/src/components/executive/VoicePicker.tsxindex d130d514..e9861b92 100644--- a/packages/ui/src/components/executive/VoicePicker.tsx+++ b/packages/ui/src/components/executive/VoicePicker.tsx@@ -2,10 +2,12 @@import { useEffect, useState } from "react";+import Icon from "@/components/Icon";import { getAgentDetail, listPersonas, patchAgent, type PersonaMeta } from "@/lib/api";// The Executive's voice, picked from the three general voices. Shared by the-// setup flow (/onboard) and Settings; both save through PATCH+// setup flow (/onboard) and Settings → Your Executive, the one place it is+// chosen after setup; both save through PATCH// /agents/executive, the same field the Agent Council edits.//// Named built-in voices are legacy: hidden here, but an install that already@@ -99,22 +101,25 @@ export default function VoicePicker({ variant, onDone }: Props) {aria-checked={selected}onClick={() => void pick(v.slug)}disabled={saving || !loaded}- className={`flex flex-col justify-start text-left rounded-xl border p-4 transition-colors cursor-pointer disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-indigo-500/50 ${+ className={`flex flex-col justify-start text-left rounded-2xl border-2 p-4 transition-colors cursor-pointer disabled:cursor-not-allowed focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/60 ${selected- ? "border-indigo-500/60 bg-indigo-500/10"- : "border-line bg-surface-elevated hover:border-indigo-500/40"+ ? "border-accent bg-accent/10"+ : "border-line bg-surface-elevated hover:border-accent/50"}`}>- <span className="block text-sm font-semibold text-fg">{v.display_name}</span>+ <span className="flex items-center justify-between gap-2 text-base font-semibold text-fg">+ {v.display_name}+ {selected && <Icon name="check" size="w-4 h-4" className="text-accent" />}+ </span>{v.description ? (- <span className="block text-xs text-fg-muted mt-1 leading-relaxed">+ <span className="block text-sm text-fg-muted mt-1 leading-relaxed">{v.description}</span>) : (- <span className="block text-xs text-fg-muted mt-1">Your current voice</span>+ <span className="block text-sm text-fg-muted mt-1">Your current voice</span>)}{v.sample && (- <span className="block text-xs text-fg-subtle italic mt-3 leading-relaxed">+ <span className="block text-[13px] text-fg-subtle italic mt-3 leading-relaxed">“{v.sample}”</span>)}@@ -123,11 +128,13 @@ export default function VoicePicker({ variant, onDone }: Props) {})}</div>- {error && <p className="mt-3 text-xs text-red-400">{error}</p>}+ {error && <p className="mt-3 text-sm text-red-500">{error}</p>}{variant === "card" && (- <p className="mt-3 text-xs text-fg-subtle">- {saving ? "Saving…" : "Applies from the next message. The Agent Council has more voices."}+ <p className="mt-3 text-sm text-fg-subtle">+ {saving+ ? "Saving…"+ : "Applies from the next message. Custom voices are made under Agent Council → Advanced."}</p>)}diff --git a/packages/ui/src/components/goals/GoalEditor.tsx b/packages/ui/src/components/goals/GoalEditor.tsxindex 6500cd2a..ffdb0ec3 100644--- a/packages/ui/src/components/goals/GoalEditor.tsx+++ b/packages/ui/src/components/goals/GoalEditor.tsx@@ -3,6 +3,8 @@import { useEffect, useRef, useState } from "react";import TimeframePicker, { TimeframeChips, suggestPeriodValue } from "@/components/TimeframePicker";+import Button from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";import {createGoal,deleteGoal,@@ -32,14 +34,31 @@ function isStaleReview(lastReviewedAt: string): boolean {export const GOAL_STATUS_OPTS = ["on_track", "at_risk", "off_track"] as const;export type GoalStatus = (typeof GOAL_STATUS_OPTS)[number];-export const GOAL_STATUS_COLORS: Record<string, string> = {- on_track: "bg-emerald-500/20 text-emerald-300 border-emerald-500/30",- at_risk: "bg-amber-500/20 text-amber-300 border-amber-500/30",- off_track: "bg-rose-500/20 text-rose-300 border-rose-500/30",+// A goal's status as a dot and a word, the one status pill the goal screens+// share (a goal row, an area's summary on /goals, a department card).+const GOAL_STATUS_DOT: Record<string, string> = {+ on_track: "bg-emerald-500",+ at_risk: "bg-amber-500",+ off_track: "bg-rose-500",};+export function goalStatusLabel(status: string): string {+ return status.replace("_", " ");+}++export function GoalStatusPill({ status, count }: { status: string; count?: number }) {+ return (+ <span className="inline-flex flex-shrink-0 items-center gap-1.5 rounded-full border border-line bg-surface-elevated px-2.5 py-1 text-[13px] font-medium text-fg whitespace-nowrap">+ <span aria-hidden="true" className={cls("h-2 w-2 rounded-full", GOAL_STATUS_DOT[status] ?? "bg-fg-subtle")} />+ {count !== undefined && <span>{count}</span>}+ {goalStatusLabel(status)}+ </span>+ );+}+const INPUT_CLS =- "px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500";+ "h-11 px-3 rounded-xl bg-surface-input/60 border border-line text-[15px] text-fg placeholder-fg-subtle focus:outline-none focus:border-accent";+const LABEL_CLS = "text-sm text-fg-muted flex flex-col gap-1.5";const GOAL_PLACEHOLDER = "e.g. Close Series A";const TARGET_PLACEHOLDER = "How will you know it's done? e.g. $5M raised";@@ -133,25 +152,30 @@ export function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: Goaif (!editing) {const progress = formatGoalProgress(goal);+ async function remove() {+ if (!window.confirm("Delete this goal?")) return;+ setDeleting(true);+ setErr(null);+ try {+ await deleteGoal(slug, goal.id!);+ onDeleted(goal.id!);+ } catch (e) {+ setErr(e instanceof Error ? e.message : "Delete failed");+ setDeleting(false);+ }+ }return (<divclassName={cls(- "flex items-start gap-3 py-3 border-b border-line last:border-0 group",+ "flex items-start gap-3 sm:gap-4 py-4 border-b border-line last:border-0",stale && "border-l-2 border-l-amber-500/60 pl-3 -ml-3")}>- <span- className={cls(- "mt-0.5 flex-shrink-0 inline-block px-2 py-0.5 rounded border text-[10px] font-medium",- GOAL_STATUS_COLORS[goal.status]- )}- >- {goal.status.replace("_", " ")}- </span><div className="flex-1 min-w-0">- <div className="text-sm text-fg font-medium">{goal.key_result}</div>- {progress && <div className="text-xs text-fg-muted mt-0.5">{progress}</div>}- <div className="text-xs text-fg-subtle mt-0.5 flex items-center gap-2 flex-wrap">+ <div className="text-base text-fg font-medium leading-snug">{goal.key_result}</div>+ {progress && <div className="text-[15px] text-fg-muted mt-1">{progress}</div>}+ <div className="text-sm text-fg-subtle mt-2 flex items-center gap-x-2 gap-y-1.5 flex-wrap">+ <GoalStatusPill status={goal.status} /><span>{formatGoalPeriod(goal)}</span><span aria-hidden="true">·</span>{goal.last_reviewed_at ? (@@ -163,36 +187,15 @@ export function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: Goa)}</div></div>- {/* Always shown on small screens (no hover on touch); revealed on- hover or keyboard focus from md up. */}- <div className="flex flex-col items-end gap-1 opacity-100 md:opacity-0 md:group-hover:opacity-100 md:focus-within:opacity-100 transition-opacity flex-shrink-0">- <div className="flex gap-1">- <button- onClick={() => setEditingAndNotify(true)}- className="px-2 py-1 text-xs rounded bg-surface-overlay hover:bg-surface-input border border-line"- >- Edit- </button>- <button- disabled={deleting}- onClick={async () => {- if (!window.confirm("Delete this goal?")) return;- setDeleting(true);- setErr(null);- try {- await deleteGoal(slug, goal.id!);- onDeleted(goal.id!);- } catch (e) {- setErr(e instanceof Error ? e.message : "Delete failed");- setDeleting(false);- }- }}- className="px-2 py-1 text-xs rounded bg-rose-500/10 hover:bg-rose-500/20 border border-rose-500/30 text-rose-300 disabled:opacity-50"- >- {deleting ? "…" : "Delete"}- </button>- </div>- {err && <span className="text-[10px] text-rose-300">{err}</span>}+ <div className="flex flex-col items-end gap-1 flex-shrink-0 -mr-2 -mt-1.5">+ <OverflowMenu+ label={`Actions for goal: ${goal.key_result}`}+ items={[+ { label: "Edit goal", onSelect: () => setEditingAndNotify(true) },+ { label: deleting ? "Deleting…" : "Delete goal", danger: true, disabled: deleting, onSelect: () => void remove() },+ ]}+ />+ {err && <span className="text-xs text-rose-500">{err}</span>}</div></div>);@@ -237,8 +240,8 @@ export function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: Goaconst onKeyDown = formKeys(save, cancel, saving);return (- <div className="py-3 border-b border-line last:border-0 space-y-2">- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <div className="py-4 border-b border-line last:border-0 space-y-3">+ <label className={LABEL_CLS}>Goal<inputvalue={form.key_result}@@ -254,7 +257,7 @@ export function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: GoaonChange={(pt, pv) => setForm((f) => ({ ...f, period_type: pt, period_value: pv }))}size="compact"/>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Status<selectvalue={form.status}@@ -268,7 +271,7 @@ export function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: Goa))}</select></label>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Target (optional)<inputvalue={form.target}@@ -278,7 +281,7 @@ export function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: Goaplaceholder={TARGET_PLACEHOLDER}/></label>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Where it stands now (optional)<inputvalue={form.current}@@ -288,22 +291,14 @@ export function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: Goaplaceholder={CURRENT_PLACEHOLDER}/></label>- {err && <p className="text-xs text-rose-300">{err}</p>}+ {err && <p className="text-sm text-rose-500">{err}</p>}<div className="flex gap-2">- <button- disabled={!canSave}- onClick={save}- className="px-3 py-1.5 text-xs rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white disabled:opacity-50"- >+ <Button variant="primary" disabled={!canSave} onClick={save}>{saving ? "Saving…" : "Save"}- </button>- <button- disabled={saving}- onClick={cancel}- className="px-3 py-1.5 text-xs rounded-lg border border-line hover:bg-surface-overlay disabled:opacity-50"- >+ </Button>+ <Button disabled={saving} onClick={cancel}>Cancel- </button>+ </Button></div></div>);@@ -377,9 +372,9 @@ export function AddGoalForm({ slug, areas, areaLabel = "Area", onCreated, onCancconst onKeyDown = formKeys(submit, onCancel, saving);return (- <div className="py-3 border-b border-line space-y-3 bg-surface-overlay/30 px-4 -mx-4 rounded-lg">- <div className="text-xs font-semibold text-fg-muted uppercase tracking-wide">New goal</div>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <div className="py-5 space-y-4">+ <div className="text-base font-semibold text-fg">New goal</div>+ <label className={LABEL_CLS}>What's the goal?<inputref={firstRef}@@ -392,7 +387,7 @@ export function AddGoalForm({ slug, areas, areaLabel = "Area", onCreated, onCanc/></label>{areas && areas.length > 1 && (- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>{areaLabel}<selectvalue={areaSlug}@@ -411,8 +406,8 @@ export function AddGoalForm({ slug, areas, areaLabel = "Area", onCreated, onCancperiodType={form.period_type}onChange={(pt, pv) => setForm((f) => ({ ...f, period_type: pt, period_value: pv }))}/>- <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <label className={LABEL_CLS}>Target (optional)<inputvalue={form.target}@@ -423,7 +418,7 @@ export function AddGoalForm({ slug, areas, areaLabel = "Area", onCreated, onCancplaceholder={TARGET_PLACEHOLDER}/></label>- <label className="text-xs text-fg-muted flex flex-col gap-1">+ <label className={LABEL_CLS}>Where it stands now (optional)<inputvalue={form.current}@@ -435,22 +430,14 @@ export function AddGoalForm({ slug, areas, areaLabel = "Area", onCreated, onCanc/></label></div>- {err && <p className="text-xs text-rose-300">{err}</p>}+ {err && <p className="text-sm text-rose-500">{err}</p>}<div className="flex gap-2">- <button- disabled={!canSubmit}- onClick={submit}- className="px-3 py-1.5 text-xs rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white disabled:opacity-50"- >+ <Button variant="primary" disabled={!canSubmit} onClick={submit}>{saving ? "Adding…" : "Add goal"}- </button>- <button- disabled={saving}- onClick={onCancel}- className="px-3 py-1.5 text-xs rounded-lg border border-line hover:bg-surface-overlay disabled:opacity-50"- >+ </Button>+ <Button disabled={saving} onClick={onCancel}>Cancel- </button>+ </Button></div></div>);diff --git a/packages/ui/src/components/jobs/ApprovedTargets.tsx b/packages/ui/src/components/jobs/ApprovedTargets.tsxindex 7b656a95..30b0d4e7 100644--- a/packages/ui/src/components/jobs/ApprovedTargets.tsx+++ b/packages/ui/src/components/jobs/ApprovedTargets.tsx@@ -1,6 +1,7 @@"use client";import { useEffect, useState } from "react";+import Button from "@/components/ui/Button";import { ApprovedTarget, forgetApprovedTarget, listApprovedTargets } from "@/lib/api";/**@@ -39,32 +40,28 @@ export default function ApprovedTargets({ name }: { name: string }) {if (!targets || targets.length === 0) return null;return (- <details className="rounded-md border border-line bg-surface/40 px-3 py-2 text-sm">- <summary className="cursor-pointer text-fg">+ <details className="rounded-2xl border border-line bg-surface-elevated px-5 py-3 text-[15px]">+ <summary className="flex min-h-10 cursor-pointer items-center gap-1 font-medium text-fg">Approved targets <span className="text-fg-muted">({targets.length})</span></summary>- <p className="mt-2 text-xs text-fg-muted">+ <p className="mt-2 text-sm text-fg-muted">This workflow can write to these without asking. Remove one and the nextwrite there asks again.</p><ul className="mt-2 divide-y divide-line/60">{targets.map((t) => (- <li key={t.value} className="flex items-center gap-3 py-1.5 min-w-0">- <span className="shrink-0 text-[11px] text-fg-subtle">{t.key}</span>- <code className="min-w-0 flex-1 truncate text-xs text-fg" title={t.value}>+ <li key={t.value} className="flex items-center gap-3 py-2 min-w-0">+ <span className="shrink-0 text-xs text-fg-subtle">{t.key}</span>+ <code className="min-w-0 flex-1 truncate text-sm text-fg" title={t.value}>{t.value}</code>- <button- type="button"- onClick={() => void remove(t.value)}- className="shrink-0 text-[11px] text-fg-muted hover:text-red-400 transition"- >+ <Button variant="ghost" onClick={() => void remove(t.value)}>Remove- </button>+ </Button></li>))}</ul>- {error && <p className="mt-1 text-xs text-red-300">{error}</p>}+ {error && <p className="mt-1 text-sm text-red-400">{error}</p>}</details>);}diff --git a/packages/ui/src/components/jobs/PlaybooksBrowser.tsx b/packages/ui/src/components/jobs/PlaybooksBrowser.tsxindex 39cf7ffb..47789c1f 100644--- a/packages/ui/src/components/jobs/PlaybooksBrowser.tsx+++ b/packages/ui/src/components/jobs/PlaybooksBrowser.tsx@@ -2,6 +2,8 @@import { useCallback, useEffect, useRef, useState } from "react";import Link from "next/link";+import Button, { buttonClass } from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";import ReactMarkdown from "react-markdown";import remarkGfm from "remark-gfm";import {@@ -340,68 +342,64 @@ export default function PlaybooksBrowser({return (<div>- <p className="mb-4 text-sm text-fg-muted max-w-3xl">+ <p className="mb-5 text-[15px] text-fg-muted max-w-3xl">Playbooks are <span className="text-fg">how</span> the Executive does apiece of work: a method, format, or checklist. In chat it looks one upwhen your request matches its “When to use”, and some workflows followthem too. Create one here, or ask the Executive to save one from chat.</p>- <div className="mb-4 flex flex-wrap items-center gap-2">- <form onSubmit={handleSearch} className="flex flex-1 min-w-[16rem] gap-2">+ <div className="mb-5 flex flex-wrap items-center gap-2">+ <form onSubmit={handleSearch} className="flex flex-1 min-w-0 basis-full sm:basis-auto gap-2"><inputvalue={searchQuery}onChange={(e) => setSearchQuery(e.target.value)}placeholder="Search playbooks (e.g. 'cash forecast for next quarter')"- className="flex-1 rounded-lg border border-line-strong bg-surface-elevated px-3 py-2 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-indigo-500/50"+ aria-label="Search playbooks"+ className="h-11 min-w-0 flex-1 rounded-xl border border-line bg-surface-elevated px-4 text-[15px] text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-accent/40"/>- <button- type="submit"- disabled={isSearching}- className="px-4 py-2 rounded-lg border border-line-strong text-fg-muted hover:text-fg disabled:opacity-40 text-sm transition-colors"- >+ <Button type="submit" disabled={isSearching}>{isSearching ? "Searching…" : "Search"}- </button>+ </Button>{searchHits !== null && (- <button- type="button"+ <Button+ variant="ghost"onClick={() => {setSearchQuery("");setSearchHits(null);submittedQueryRef.current = null;}}- className="px-3 py-2 border border-line-strong text-fg-muted hover:text-fg text-sm rounded-lg transition-colors">Clear- </button>+ </Button>)}</form>- <button- type="button"+ <Button+ variant="primary"+ className="shrink-0"onClick={() => {setSelected(null);setNotice(null);openEditor({ mode: "create", customizing: false, initial: EMPTY_INPUT });}}- className="shrink-0 rounded-md bg-indigo-600 px-3 py-2 text-sm font-medium text-white hover:bg-indigo-500 transition">+ New playbook- </button>+ </Button></div>{error && (- <p className="mb-4 text-xs text-red-400 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2">+ <p className="mb-4 text-sm text-red-400 bg-red-500/10 border border-red-500/20 rounded-xl px-4 py-2.5">{error}</p>)}{notice && (- <p className="mb-4 text-xs text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 rounded-lg px-3 py-2">+ <p className="mb-4 text-sm text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 rounded-xl px-4 py-2.5">{notice}</p>)}<div className="flex flex-col md:flex-row gap-6">- <div className="md:w-60 flex-shrink-0 space-y-5">+ <div className="md:w-64 flex-shrink-0 space-y-5">{searchHits !== null ? (<div><SectionLabel>Results</SectionLabel>@@ -466,7 +464,7 @@ export default function PlaybooksBrowser({emptyMessage="No hidden playbooks."/>)}- <label className="flex items-center gap-2 px-1 text-xs text-fg-muted cursor-pointer">+ <label className="flex min-h-10 items-center gap-2 px-1 text-sm text-fg-muted cursor-pointer"><inputtype="checkbox"checked={showHidden}@@ -548,9 +546,9 @@ function ListButton({<buttontype="button"onClick={onClick}- className={`w-full text-left px-2.5 py-1.5 rounded-lg text-sm transition-colors flex items-center justify-between gap-2 ${+ className={`w-full min-h-10 text-left px-3 py-2 rounded-xl text-[15px] transition-colors flex items-center justify-between gap-2 ${active- ? "bg-surface-input text-fg"+ ? "bg-accent/10 text-accent font-medium": "text-fg-muted hover:text-fg hover:bg-surface-overlay"}`}>@@ -623,8 +621,6 @@ function PlaybookView({onDelete: () => void;onRestore: () => void;}) {- const btn =- "px-3 py-1.5 rounded-lg border text-xs transition-colors disabled:opacity-40";const deleteLabel = skill.customized? "Revert to built-in": skill.source === "builtin"@@ -642,11 +638,11 @@ function PlaybookView({{sourceLabel(skill)}</span></div>- <h2 className="text-base font-semibold text-fg mt-1 break-words">{skill.name}</h2>- <p className="text-sm text-fg-muted mt-1">{skill.description}</p>- <p className="text-xs text-fg-muted italic mt-1">When to use: {skill.when_to_use}</p>+ <h2 className="text-xl font-bold tracking-tight text-fg mt-1 break-words">{skill.name}</h2>+ <p className="text-[15px] text-fg-muted mt-1">{skill.description}</p>+ <p className="text-sm text-fg-muted italic mt-1">When to use: {skill.when_to_use}</p>{skill.used_by.length > 0 && (- <p className="text-xs text-fg-muted mt-1">+ <p className="text-sm text-fg-muted mt-1">Followed by{" "}{skill.used_by.map((w, i) => (<span key={w.name}>@@ -661,40 +657,23 @@ function PlaybookView({</p>)}</div>- <div className="flex flex-wrap gap-2 flex-shrink-0">+ <div className="flex min-w-0 flex-wrap items-center gap-2">{skill.hidden ? (- <button- type="button"- disabled={busy}- onClick={onRestore}- className={`${btn} border-line-strong text-fg hover:bg-surface-overlay`}- >+ <Button variant="primary" disabled={busy} onClick={onRestore}>Restore- </button>+ </Button>) : (<>- <Link- href={tryInChatHref(skill.name)}- className={`${btn} border-line-strong text-fg-muted hover:text-fg`}- >+ <Button variant="primary" disabled={busy} onClick={onEdit}>+ {skill.source === "builtin" ? "Customize" : "Edit"}+ </Button>+ <Link href={tryInChatHref(skill.name)} className={buttonClass("secondary", "md")}>Try in chat</Link>- <button- type="button"- disabled={busy}- onClick={onEdit}- className={`${btn} border-line-strong text-fg hover:bg-surface-overlay`}- >- {skill.source === "builtin" ? "Customize" : "Edit"}- </button>- <button- type="button"- disabled={busy}- onClick={onDelete}- className={`${btn} border-red-500/20 text-red-400 hover:bg-red-500/10`}- >- {deleteLabel}- </button>+ <OverflowMenu+ label={`More for ${skill.name}`}+ items={[{ label: deleteLabel, danger: true, disabled: busy, onSelect: onDelete }]}+ /></>)}</div>@@ -704,13 +683,13 @@ function PlaybookView({prose-p:text-fg prose-p:leading-relaxedprose-headings:text-fg prose-headings:font-semiboldprose-strong:text-fg prose-strong:font-semibold- prose-code:text-indigo-300 prose-code:bg-surface-overlay prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-xs prose-code:before:content-none prose-code:after:content-none+ prose-code:text-accent prose-code:bg-surface-overlay prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-xs prose-code:before:content-none prose-code:after:content-noneprose-pre:bg-surface-overlay prose-pre:border prose-pre:border-line-strongprose-blockquote:border-line-strong prose-blockquote:text-fg-mutedprose-ul:text-fg prose-ol:text-fgprose-li:marker:text-fg-mutedprose-hr:border-line-strong- prose-a:text-indigo-400 prose-a:no-underline hover:prose-a:underline+ prose-a:text-accent prose-a:no-underline hover:prose-a:underlineprose-table:text-fg prose-th:text-fg prose-th:border-line-strong prose-td:border-line-strong"><ReactMarkdown remarkPlugins={[remarkGfm]}>{skill.body}</ReactMarkdown></div>@@ -719,7 +698,7 @@ function PlaybookView({}const MARKDOWN_BOX =- "rounded-xl border border-line-strong bg-surface-elevated px-6 py-5 max-h-[420px] overflow-y-auto prose prose-invert prose-sm max-w-none prose-p:text-fg prose-headings:text-fg prose-strong:text-fg prose-ul:text-fg prose-ol:text-fg prose-li:marker:text-fg-muted prose-code:text-indigo-300 prose-a:text-indigo-400";+ "rounded-xl border border-line-strong bg-surface-elevated px-6 py-5 max-h-[420px] overflow-y-auto prose prose-invert prose-sm max-w-none prose-p:text-fg prose-headings:text-fg prose-strong:text-fg prose-ul:text-fg prose-ol:text-fg prose-li:marker:text-fg-muted prose-code:text-accent prose-a:text-accent";function DraftView({draft,@@ -734,7 +713,6 @@ function DraftView({onDiscard: () => void;onEdit: () => void;}) {- const btn = "px-3 py-1.5 rounded-lg border text-xs transition-colors disabled:opacity-40";const heading =draft.action === "create"? "New playbook"@@ -749,53 +727,39 @@ function DraftView({<span className="text-[10px] uppercase tracking-wider text-amber-400 px-2 py-0.5 border border-amber-500/30 rounded">Proposed by the Executive · {heading}</span>- <h2 className="text-base font-semibold text-fg mt-2 break-words">{draft.name}</h2>+ <h2 className="text-xl font-bold tracking-tight text-fg mt-2 break-words">{draft.name}</h2>{draft.action !== "delete" && (<>- <p className="text-sm text-fg-muted mt-1">{draft.description}</p>- <p className="text-xs text-fg-muted italic mt-1">+ <p className="text-[15px] text-fg-muted mt-1">{draft.description}</p>+ <p className="text-sm text-fg-muted italic mt-1">When to use: {draft.when_to_use} · {draft.category}</p></>)}- <p className="text-[11px] text-fg-subtle mt-1">+ <p className="text-xs text-fg-subtle mt-1">Proposed {new Date(draft.proposed_at).toLocaleString()}. Nothing changes until youapprove it.</p>{followers.length > 0 && (- <p className="text-xs text-amber-300 mt-1">+ <p className="text-sm text-amber-600 dark:text-amber-300 mt-1">Followed by {followers.map((w) => w.title).join(", ")} — approving changes what{followers.length === 1 ? " that workflow" : " those workflows"} follow.</p>)}</div>- <div className="flex flex-wrap gap-2 flex-shrink-0">- <button- type="button"- disabled={busy}- onClick={onApprove}- className={`${btn} border-emerald-500/30 text-emerald-300 hover:bg-emerald-500/10`}- >+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <Button variant="primary" disabled={busy} onClick={onApprove}>{draft.action === "delete" ? "Approve delete" : "Approve"}- </button>+ </Button>{draft.action !== "delete" && (- <button- type="button"- disabled={busy}- onClick={onEdit}- className={`${btn} border-line-strong text-fg hover:bg-surface-overlay`}- >+ <Button disabled={busy} onClick={onEdit}>Edit, then save- </button>+ </Button>)}- <button- type="button"- disabled={busy}- onClick={onDiscard}- className={`${btn} border-red-500/20 text-red-400 hover:bg-red-500/10`}- >- Discard- </button>+ <OverflowMenu+ label={`More for ${draft.name}`}+ items={[{ label: "Discard proposal", danger: true, disabled: busy, onSelect: onDiscard }]}+ /></div></div>@@ -840,7 +804,7 @@ function PlaybookEditor({form.body.trim() !== "";const input =- "w-full rounded-lg border border-line-strong bg-surface-elevated px-3 py-2 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-indigo-500/50";+ "w-full rounded-xl border border-line bg-surface-elevated px-3.5 py-2.5 text-[15px] text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-accent/40";return (<form@@ -850,7 +814,7 @@ function PlaybookEditor({if (complete) onSave(form);}}>- <h2 className="text-base font-semibold text-fg">+ <h2 className="text-xl font-bold tracking-tight text-fg">{editor.mode === "create"? "New playbook": editor.customizing@@ -919,20 +883,12 @@ function PlaybookEditor({</Field><div className="flex gap-2">- <button- type="submit"- disabled={!complete || busy}- className="rounded-md bg-indigo-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-indigo-500 disabled:opacity-40 transition"- >+ <Button type="submit" variant="primary" disabled={!complete || busy}>{busy ? "Saving…" : "Save"}- </button>- <button- type="button"- onClick={onCancel}- className="rounded-md border border-line-strong px-3 py-1.5 text-sm text-fg-muted hover:text-fg transition"- >+ </Button>+ <Button variant="ghost" onClick={onCancel}>Cancel- </button>+ </Button></div></form>);@@ -949,9 +905,9 @@ function Field({}) {return (<label className="flex flex-col gap-1">- <span className="text-xs font-medium text-fg">{label}</span>+ <span className="text-sm font-medium text-fg">{label}</span>{children}- {hint && <span className="text-[11px] text-fg-subtle">{hint}</span>}+ {hint && <span className="text-xs text-fg-subtle">{hint}</span>}</label>);}diff --git a/packages/ui/src/components/jobs/StartHere.tsx b/packages/ui/src/components/jobs/StartHere.tsxindex 861e52e2..9b207e7d 100644--- a/packages/ui/src/components/jobs/StartHere.tsx+++ b/packages/ui/src/components/jobs/StartHere.tsx@@ -1,18 +1,29 @@"use client";import { useRef, useState } from "react";-import Link from "next/link";import { useRouter } from "next/navigation";-import { WORKFLOW_STARTERS, stashWorkflowDescription } from "@/lib/workflowStarters";+import Button from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";+import { WORKFLOW_STARTER_CHIPS, stashWorkflowDescription } from "@/lib/workflowStarters";const CHAT_DRAFT = "Help me set up a workflow that ";+const chipCls =+ "inline-flex min-h-10 items-center rounded-full border border-line bg-surface-elevated px-4 text-sm font-medium text-fg-muted hover:text-fg hover:border-line-strong hover:bg-surface-overlay transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60";+/**- * The front door of /jobs: ask what the user wants done, and offer the ways- * to build it — describe it (the wizard), step by step (the advanced- * editor), in chat, or from a ready-made workflow further down the page.+ * The front door of /jobs: ask what the user wants done. Start hands the+ * sentence to the wizard; the ⋯ beside it holds the other ways to build one+ * (the wizard empty, the step-by-step editor, chat), and the last chip opens+ * the ready-made list.*/-export default function StartHere({ onBrowseReadyMade }: { onBrowseReadyMade: () => void }) {+export default function StartHere({+ readyMadeCount,+ onBrowseReadyMade,+}: {+ readyMadeCount: number;+ onBrowseReadyMade: () => void;+}) {const router = useRouter();const [text, setText] = useState("");const inputRef = useRef<HTMLTextAreaElement>(null);@@ -28,18 +39,16 @@ export default function StartHere({ onBrowseReadyMade }: { onBrowseReadyMade: ()};return (- <section className="mb-6 rounded-xl border border-line bg-surface-elevated p-5 sm:p-6">- <p className="text-[10px] font-semibold uppercase tracking-wide text-indigo-300">- Start here- </p>- <h2 className="mt-1 text-lg font-semibold text-fg">What do you want to get done?</h2>- <p className="mt-1 text-sm text-fg-muted">- A workflow is a job you want done regularly or on demand — a report, a- review, a check-in. Describe it in a sentence; I’ll ask a few- questions and set it up for you to review.+ <section className="mb-8 rounded-2xl border border-line bg-surface-elevated p-5 shadow-sm sm:p-7">+ <h1 className="text-2xl font-bold tracking-tight text-fg sm:text-3xl">+ What do you want to get done?+ </h1>+ <p className="mt-2 text-[15px] text-fg-muted">+ A report, a review, a check-in — regularly or on demand. Describe it in a+ sentence; I’ll ask a few questions and set it up for you to review.</p>- <div className="mt-4">+ <div className="mt-5 flex flex-col gap-3 rounded-2xl border border-line bg-surface p-2 focus-within:ring-2 focus-within:ring-accent/40 sm:flex-row sm:items-end"><textarearef={inputRef}value={text}@@ -53,71 +62,45 @@ export default function StartHere({ onBrowseReadyMade }: { onBrowseReadyMade: ()rows={2}aria-label="Describe the workflow you want"placeholder="e.g. Every Monday, send me what our top competitors shipped"- className="w-full rounded-lg border border-line-strong bg-surface-overlay px-3 py-2 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500/50 resize-none transition-colors"+ className="min-h-[3.5rem] w-full flex-1 resize-none bg-transparent px-3 py-2.5 text-base text-fg placeholder-fg-subtle focus:outline-none"/>- <div className="mt-2 flex flex-wrap items-center gap-2">- <button- type="button"- onClick={start}- disabled={!text.trim()}- className="rounded-md bg-indigo-600 px-4 py-1.5 text-sm font-medium text-white hover:bg-indigo-500 disabled:opacity-40 transition-colors"- >+ <div className="flex items-center justify-end gap-1.5">+ <Button variant="primary" onClick={start} disabled={!text.trim()} className="px-6">Start- </button>- <span className="text-xs text-fg-subtle">or try one:</span>- {WORKFLOW_STARTERS.map((s) => (- <button- key={s}- type="button"- onClick={() => {- setText(s);- inputRef.current?.focus();- }}- className="rounded-full border border-line px-3 py-1 text-left text-xs text-fg-muted hover:text-fg hover:border-line-strong transition"- >- {s}- </button>- ))}+ </Button>+ <OverflowMenu+ label="Other ways to build a workflow"+ items={[+ { label: "New workflow", href: "/jobs/new" },+ { label: "New workflow, step by step", href: "/jobs/new?mode=advanced" },+ {+ label: "Talk it through in chat",+ href: `/?new=1&draft=${encodeURIComponent(CHAT_DRAFT)}`,+ },+ ]}+ /></div></div>- <p className="mt-5 mb-2 text-xs font-semibold uppercase tracking-wide text-fg-subtle">- Or build it another way- </p>- <div className="grid gap-2 sm:grid-cols-3">- <WayCard- href="/jobs/new?mode=advanced"- title="Step by step"- body="Pick each step yourself: which specialist, which tools, where you sign off."- />- <WayCard- href={`/?new=1&draft=${encodeURIComponent(CHAT_DRAFT)}`}- title="Talk it through in chat"- body="Explain it to the Executive in your own words and it will draft the workflow."- />- <button- type="button"- onClick={onBrowseReadyMade}- className="rounded-lg border border-line bg-surface/40 px-3 py-2.5 text-left hover:border-line-strong hover:bg-surface-elevated/40 transition"- >- <span className="block text-sm font-medium text-fg">Start from a ready-made one</span>- <span className="mt-0.5 block text-xs text-fg-muted">- Board decks, investor updates, business reviews and more — run as-is.- </span>+ <div className="mt-4 flex flex-wrap gap-2">+ {WORKFLOW_STARTER_CHIPS.map((s) => (+ <button+ key={s.label}+ type="button"+ title={s.text}+ onClick={() => {+ setText(s.text);+ inputRef.current?.focus();+ }}+ className={chipCls}+ >+ {s.label}+ </button>+ ))}+ <button type="button" onClick={onBrowseReadyMade} className={chipCls}>+ {readyMadeCount > 0 ? `Browse ${readyMadeCount} ready-made` : "Browse ready-made"}</button></div></section>);}--function WayCard({ href, title, body }: { href: string; title: string; body: string }) {- return (- <Link- href={href}- className="rounded-lg border border-line bg-surface/40 px-3 py-2.5 hover:border-line-strong hover:bg-surface-elevated/40 transition"- >- <span className="block text-sm font-medium text-fg">{title}</span>- <span className="mt-0.5 block text-xs text-fg-muted">{body}</span>- </Link>- );-}diff --git a/packages/ui/src/components/jobs/WorkflowWizard.tsx b/packages/ui/src/components/jobs/WorkflowWizard.tsxindex d1aaa250..0eeb0170 100644--- a/packages/ui/src/components/jobs/WorkflowWizard.tsx+++ b/packages/ui/src/components/jobs/WorkflowWizard.tsx@@ -13,6 +13,7 @@ import {startWorkflowDesigner,} from "@/lib/api";import { WORKFLOW_STARTERS, takeWorkflowDescription } from "@/lib/workflowStarters";+import Button from "@/components/ui/Button";import WorkflowDraftReview from "./WorkflowDraftReview";// Same cap chat applies to its `?draft=` prefill.@@ -161,7 +162,7 @@ export default function WorkflowWizard() {<div className="max-w-3xl mx-auto space-y-4">{!started && (<div className="space-y-3">- <p className="text-sm text-fg">+ <p className="text-base text-fg">Describe the job you want done — what it should produce, who it’sfor, and how often. I’ll ask about anything I need, then draft theworkflow for you to review.@@ -175,7 +176,7 @@ export default function WorkflowWizard() {setInput(s);inputRef.current?.focus();}}- className="rounded-full border border-line px-3 py-1 text-left text-xs text-fg-muted hover:text-fg hover:border-line-strong transition"+ className="min-h-10 rounded-full border border-line bg-surface-elevated px-4 py-2 text-left text-sm text-fg-muted hover:text-fg hover:border-line-strong hover:bg-surface-overlay transition">{s}</button>@@ -190,7 +191,7 @@ export default function WorkflowWizard() {className={t.role === "user" ? "flex justify-end" : "flex justify-start"}><div- className={`max-w-[85%] rounded-xl px-4 py-2.5 text-sm whitespace-pre-wrap ${+ className={`max-w-[85%] rounded-2xl px-4 py-3 text-[15px] whitespace-pre-wrap ${t.role === "user"? "bg-indigo-600/20 text-fg": "bg-surface-elevated border border-line text-fg"@@ -198,7 +199,7 @@ export default function WorkflowWizard() {>{t.text}{i === lastIndex && t.role === "assistant" && turn?.hint && (- <p className="text-xs text-fg-muted mt-1.5">{turn.hint}</p>+ <p className="text-sm text-fg-muted mt-1.5">{turn.hint}</p>)}</div></div>@@ -211,7 +212,7 @@ export default function WorkflowWizard() {key={o}type="button"onClick={() => send(o)}- className="rounded-full border border-indigo-500/40 px-3 py-1 text-xs text-indigo-300 hover:bg-indigo-500/10 transition"+ className="min-h-10 rounded-full border border-accent/40 px-4 py-2 text-sm font-medium text-accent hover:bg-accent/10 transition">{o}</button>@@ -231,19 +232,19 @@ export default function WorkflowWizard() {{pending && (<div className="flex justify-end">- <div className="max-w-[85%] rounded-xl px-4 py-2.5 text-sm whitespace-pre-wrap bg-indigo-600/20 text-fg opacity-70">+ <div className="max-w-[85%] rounded-2xl px-4 py-3 text-[15px] whitespace-pre-wrap bg-indigo-600/20 text-fg opacity-70">{pending}</div></div>)}- {busy && <p className="text-xs text-fg-muted">Thinking…</p>}+ {busy && <p className="text-sm text-fg-muted">Thinking…</p>}<div ref={bottomRef} /></div></div>- <div className="border-t border-line bg-surface px-6 py-3">- <div className="max-w-3xl mx-auto space-y-2">- {error && <p className="text-xs text-red-400">{error}</p>}+ <div className="border-t border-line bg-surface px-4 sm:px-6 py-4">+ <div className="max-w-3xl mx-auto space-y-3">+ {error && <p className="text-sm text-red-400">{error}</p>}<textarearef={inputRef}value={input}@@ -264,28 +265,23 @@ export default function WorkflowWizard() {? "Your answer… (Enter to send, Shift+Enter for a new line)": "e.g. Every Monday, pull together what our top three competitors shipped and send it to me."}- className="w-full rounded-lg border border-line-strong bg-surface-overlay px-3 py-2 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500/50 resize-none transition-colors disabled:opacity-50"+ className="w-full rounded-2xl border border-line bg-surface-elevated px-4 py-3 text-base text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-accent/40 resize-none transition-colors disabled:opacity-50"/>- <div className="flex items-center gap-3">- <button- type="button"+ <div className="flex flex-wrap items-center gap-3">+ <Button+ variant="primary"onClick={() => send(input)}disabled={busy || !input.trim()}- className="px-4 py-1.5 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-40 text-white text-sm font-medium rounded-md transition-colors"+ className="px-6">{busy ? "Thinking…" : started ? "Send" : "Start"}- </button>+ </Button>{started && !isDraft && (- <button- type="button"- onClick={draftNow}- disabled={busy}- className="text-xs text-fg-muted hover:text-fg disabled:opacity-40 transition-colors"- >+ <Button variant="ghost" onClick={draftNow} disabled={busy}>Draft it now- </button>+ </Button>)}- <span className="ml-auto flex items-center gap-3 text-xs text-fg-subtle">+ <span className="ml-auto flex items-center gap-3 text-sm text-fg-subtle">{started && (<span>{turn!.questions_asked} of {turn!.max_questions} questionsdiff --git a/packages/ui/src/components/knowledge/CompanyPanel.tsx b/packages/ui/src/components/knowledge/CompanyPanel.tsxindex 3c447075..a4321f34 100644--- a/packages/ui/src/components/knowledge/CompanyPanel.tsx+++ b/packages/ui/src/components/knowledge/CompanyPanel.tsx@@ -29,9 +29,12 @@ import {} from "@/lib/companyDocs";import { formatRelativeTime } from "@/lib/relativeTime";import Icon from "@/components/Icon";+import Button, { buttonClass } from "@/components/ui/Button";+import OverflowMenu, { type OverflowItem } from "@/components/ui/OverflowMenu";+import SidePanel from "@/components/ui/SidePanel";interface CompanyPanelProps {- /** Reports how many documents are listed, for the sidebar count. */+ /** Reports how many documents are listed, for the tab's count. */onCountChange?: (count: number) => void;}@@ -46,13 +49,14 @@ const ACCEPT = ".pdf,.docx,.doc,.xlsx,.xlsm,.csv,.md,.txt";const POLL_MS = 3000;const PROSE_CLASS =- "prose prose-invert prose-sm max-w-none prose-p:text-fg prose-headings:text-fg prose-strong:text-fg prose-code:text-indigo-300 prose-code:bg-surface-overlay prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-xs prose-code:before:content-none prose-code:after:content-none prose-pre:bg-surface-overlay prose-pre:border prose-pre:border-line-strong prose-blockquote:border-line-strong prose-blockquote:text-fg-muted prose-ul:text-fg prose-ol:text-fg prose-li:marker:text-fg-muted prose-hr:border-line-strong prose-a:text-indigo-400 prose-a:no-underline hover:prose-a:underline prose-table:text-fg prose-th:text-fg prose-th:border-line-strong prose-td:border-line-strong";+ "prose prose-sm sm:prose-base max-w-none prose-p:text-fg prose-headings:text-fg prose-strong:text-fg prose-code:text-accent prose-code:bg-surface-overlay prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-xs prose-code:before:content-none prose-code:after:content-none prose-pre:bg-surface-overlay prose-pre:border prose-pre:border-line-strong prose-blockquote:border-line-strong prose-blockquote:text-fg-muted prose-ul:text-fg prose-ol:text-fg prose-li:marker:text-fg-muted prose-hr:border-line-strong prose-a:text-accent prose-a:no-underline hover:prose-a:underline prose-table:text-fg prose-th:text-fg prose-th:border-line-strong prose-td:border-line-strong";-const BADGE_CLASS: Record<DocSource, string> = {- upload: "bg-surface-input text-fg-muted border-line-strong",- drive: "bg-emerald-500/15 text-emerald-400 border-emerald-500/40",- onedrive: "bg-blue-500/15 text-blue-400 border-blue-500/40",- notion: "bg-sky-500/15 text-sky-400 border-sky-500/40",+// The dot beside a document's source name.+const SOURCE_DOT: Record<DocSource, string> = {+ upload: "bg-fg-subtle",+ drive: "bg-emerald-500",+ onedrive: "bg-blue-500",+ notion: "bg-sky-500",};export default function CompanyPanel({ onCountChange }: CompanyPanelProps) {@@ -135,16 +139,6 @@ export default function CompanyPanel({ onCountChange }: CompanyPanelProps) {return () => window.clearInterval(timer);}, [syncingKey, loadSynced]);- // Close the viewer on Escape.- useEffect(() => {- if (!viewing) return;- const onKey = (e: KeyboardEvent) => {- if (e.key === "Escape") setViewing(null);- };- window.addEventListener("keydown", onKey);- return () => window.removeEventListener("keydown", onKey);- }, [viewing]);-async function handleFiles(files: File[]) {if (!files.length) return;setError(null);@@ -216,23 +210,25 @@ export default function CompanyPanel({ onCountChange }: CompanyPanelProps) {];return (- <div className="space-y-5 max-w-3xl">- <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-3 sm:gap-4">- <div>- <h1 className="text-lg font-semibold text-fg">Company documents</h1>- <p className="text-sm text-fg-muted mt-1">- Everything here is read by the Executive when it answers questions about your- company.- </p>- </div>- <label className="self-start flex-shrink-0 cursor-pointer inline-flex items-center gap-1.5 px-3.5 py-2 rounded-lg bg-indigo-500 hover:bg-indigo-400 text-white text-sm font-medium transition-colors">- <Icon name="plus" size="w-4 h-4" />+ <div className="space-y-6 max-w-4xl">+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">+ <p className="text-[15px] text-fg-muted max-w-xl">+ Your own files, plus anything synced from a connected source.+ </p>+ <label+ className={buttonClass(+ "primary",+ "md",+ "self-start sm:self-auto flex-shrink-0 cursor-pointer focus-within:ring-2 focus-within:ring-accent/60"+ )}+ >+ <Icon name="plus" size="w-5 h-5" />Add documents<inputref={fileInputRef}type="file"multiple- className="hidden"+ className="sr-only"accept={ACCEPT}onChange={(e) => handleFiles(Array.from(e.target.files ?? []))}/>@@ -240,7 +236,7 @@ export default function CompanyPanel({ onCountChange }: CompanyPanelProps) {</div>{error && (- <p className="text-xs text-red-400 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2">+ <p className="text-sm text-red-500 bg-red-500/10 border border-red-500/20 rounded-xl px-4 py-3">{error}</p>)}@@ -263,18 +259,18 @@ export default function CompanyPanel({ onCountChange }: CompanyPanelProps) {setDragOver(false);handleFiles(Array.from(e.dataTransfer.files));}}- className={`rounded-xl border-2 border-dashed transition-colors text-center ${- rows.length === 0 && loaded ? "p-10" : "px-4 py-4"- } ${dragOver ? "border-indigo-500 bg-indigo-500/5" : "border-line-strong"}`}+ className={`rounded-2xl border-2 border-dashed transition-colors text-center ${+ rows.length === 0 && loaded ? "p-10" : "px-4 py-5"+ } ${dragOver ? "border-accent bg-accent/5" : "border-line-strong/70"}`}>{uploadProgress ? (- <p className="text-sm text-indigo-400 animate-pulse">{uploadProgress}</p>+ <p className="text-[15px] text-accent animate-pulse">{uploadProgress}</p>) : (- <p className="text-sm text-fg-muted">+ <p className="text-[15px] text-fg-muted">{rows.length === 0 && loaded? "No documents yet. Drop files here to add your first ones.": "Drop files here to add them"}- <span className="block text-xs text-fg-subtle mt-1">+ <span className="block text-sm text-fg-subtle mt-1">PDF, Word, Excel, CSV, Markdown or text, up to 50 MB each</span></p>@@ -283,32 +279,36 @@ export default function CompanyPanel({ onCountChange }: CompanyPanelProps) {{rows.length > 0 && (<div className="space-y-3">- <div className="flex items-center gap-2 flex-wrap">- {filterOptions.length > 2 &&- filterOptions.map((opt) => (- <button- key={opt}- onClick={() => setSourceFilter(opt)}- className={`text-xs px-2.5 py-1 rounded-full border transition-colors ${- sourceFilter === opt- ? "bg-surface-input text-fg border-line-strong"- : "text-fg-muted border-transparent hover:text-fg"- }`}- >- {opt === "all" ? `All (${rows.length})` : SOURCE_LABELS[opt]}- </button>- ))}- {rows.length > 8 && (- <input- value={query}- onChange={(e) => setQuery(e.target.value)}- placeholder="Search by name…"- className="ml-auto w-48 rounded-lg border border-line bg-surface-elevated px-2.5 py-1 text-xs text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-indigo-500/40"- />- )}- </div>+ {(filterOptions.length > 2 || rows.length > 8) && (+ <div className="flex items-center gap-2 flex-wrap">+ {filterOptions.length > 2 &&+ filterOptions.map((opt) => (+ <button+ key={opt}+ onClick={() => setSourceFilter(opt)}+ aria-pressed={sourceFilter === opt}+ className={`h-10 text-sm font-medium px-4 rounded-xl border transition-colors ${+ sourceFilter === opt+ ? "bg-accent/10 text-accent border-accent/30"+ : "text-fg-muted border-line hover:text-fg hover:bg-surface-overlay"+ }`}+ >+ {opt === "all" ? `All (${rows.length})` : SOURCE_LABELS[opt]}+ </button>+ ))}+ {rows.length > 8 && (+ <input+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search by name…"+ aria-label="Search documents by name"+ className="w-full sm:w-60 sm:ml-auto h-10 rounded-xl border border-line bg-surface-elevated px-3 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-accent/40"+ />+ )}+ </div>+ )}- <ul className="divide-y divide-line-strong/50 rounded-xl border border-line-strong/50 bg-surface-overlay/40">+ <ul className="divide-y divide-line rounded-2xl border border-line bg-surface-elevated">{shown.map((row) => (<DocListRowkey={row.key}@@ -319,7 +319,7 @@ export default function CompanyPanel({ onCountChange }: CompanyPanelProps) {/>))}{shown.length === 0 && (- <li className="px-4 py-6 text-sm text-fg-subtle text-center">+ <li className="px-5 py-8 text-[15px] text-fg-subtle text-center">No documents match.</li>)}@@ -327,7 +327,7 @@ export default function CompanyPanel({ onCountChange }: CompanyPanelProps) {</div>)}- {viewing && <Viewer doc={viewing} onClose={() => setViewing(null)} />}+ <Viewer doc={viewing} onClose={() => setViewing(null)} /></div>);}@@ -346,42 +346,46 @@ function SourcesStrip({if (!anyKnown) return null;if (connected.length === 0) {return (- <p className="text-xs text-fg-subtle">- Connect Google Drive, OneDrive or Notion to bring documents in automatically.{" "}- <Link href="/settings/integrations" className="text-indigo-400 hover:underline">- Set up in Settings+ <div className="flex flex-col sm:flex-row sm:items-center gap-3 rounded-2xl border border-line bg-surface-overlay/50 px-5 py-4">+ <p className="flex-1 text-[15px] text-fg-muted">+ Connect Google Drive, OneDrive or Notion to bring documents in automatically.+ </p>+ {/* Sources are connected with environment settings; the guide says how. */}+ <Link+ href="/guide#knowledge"+ className={buttonClass("secondary", "md", "self-start sm:self-auto")}+ >+ How to connect</Link>- </p>+ </div>);}return (- <div className="grid gap-2 sm:grid-cols-2">+ <div className="grid gap-3 sm:grid-cols-2">{connected.map((s) => {const dot = s.syncing- ? "bg-indigo-400 animate-pulse"+ ? "bg-accent animate-pulse": s.last_error- ? "bg-red-400"+ ? "bg-red-500": s.last_run- ? "bg-emerald-400"+ ? "bg-emerald-500": "bg-fg-subtle";const message = messages[s.id];return (- <div- key={s.id}- className="rounded-xl border border-line-strong/60 bg-surface-overlay/40 px-3.5 py-2.5"- >- <div className="flex items-center gap-2">- <span className={`h-2 w-2 rounded-full ${dot}`} aria-hidden />- <span className="text-sm font-medium text-fg">{s.label}</span>- <button+ <div key={s.id} className="rounded-2xl border border-line bg-surface-elevated px-4 py-3.5">+ <div className="flex items-center gap-2.5">+ <span className={`h-2.5 w-2.5 rounded-full flex-shrink-0 ${dot}`} aria-hidden />+ <span className="text-base font-semibold text-fg truncate">{s.label}</span>+ <Button+ size="sm"+ className="ml-auto !h-10"onClick={() => onSyncNow(s.id)}disabled={s.syncing}- className="ml-auto text-xs px-2.5 py-1 rounded-lg border border-line-strong text-fg hover:bg-surface-input disabled:opacity-60 disabled:cursor-default transition-colors">{s.syncing ? "Syncing…" : "Sync now"}- </button>+ </Button></div>- <p className="text-xs text-fg-muted mt-1">+ <p className="text-sm text-fg-muted mt-1.5">{s.syncing? "Checking for new and changed files…": s.last_run@@ -392,11 +396,11 @@ function SourcesStrip({<span className="text-fg-subtle"> · syncs {formatInterval(s.interval_minutes)}</span></p>{(s.last_error || message) && (- <p className="text-xs text-red-400 mt-1">+ <p className="text-sm text-red-500 mt-1.5">{message ?? s.last_error}{" "}{!message && (- <Link href="/settings/integrations" className="underline">- Check settings+ <Link href="/guide#knowledge" className="underline">+ How to fix</Link>)}</p>@@ -431,114 +435,84 @@ function DocListRow({`edited in ${SOURCE_LABELS[row.source]} ${new Date(row.editedAt).toLocaleDateString()}`);}+ const source = SOURCE_LABELS[row.source];+ const menu: OverflowItem[] = [];+ if (row.url) menu.push({ label: `Open in ${source} ↗`, href: row.url, external: true });+ if (row.source === "upload") {+ menu.push({ label: "Delete", danger: true, onSelect: onDelete });+ } else {+ // Synced files are removed at their source; say so where Delete would be.+ menu.push({ label: `Managed in ${source}: remove it there`, disabled: true });+ }return (- <li className="flex items-center gap-3 px-4 py-3">- <Icon name="doc" size="w-4 h-4" className="text-fg-subtle flex-shrink-0" />+ <li className="flex items-center gap-3 sm:gap-4 px-4 sm:px-5 py-3.5">+ <span className="hidden sm:flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-surface-overlay text-fg-muted">+ <Icon name="doc" size="w-5 h-5" />+ </span><div className="min-w-0 flex-1">- <div className="flex items-center gap-2 min-w-0">- <button- onClick={onView}- disabled={!row.indexed}- className="text-sm text-fg font-medium truncate hover:text-indigo-300 disabled:hover:text-fg text-left transition-colors"- >- {row.name}- </button>- <span- className={`flex-shrink-0 text-[10px] font-medium px-1.5 py-0.5 rounded border ${BADGE_CLASS[row.source]}`}- >- {SOURCE_LABELS[row.source]}- </span>+ <button+ onClick={onView}+ disabled={!row.indexed}+ className="block max-w-full text-[15px] text-fg font-semibold truncate hover:text-accent disabled:hover:text-fg text-left transition-colors"+ >+ {row.name}+ </button>+ <p className="text-sm text-fg-muted mt-0.5 flex items-center gap-1.5 min-w-0">+ <span className={`h-2 w-2 rounded-full flex-shrink-0 ${SOURCE_DOT[row.source]}`} aria-hidden />+ <span className="flex-shrink-0">{source}</span>{row.domain && (- <span className="flex-shrink-0 text-[10px] text-fg-subtle capitalize">- {row.domain}- </span>+ <span className="hidden sm:inline flex-shrink-0 capitalize text-fg-subtle">· {row.domain}</span>)}- </div>- <p className="text-xs text-fg-muted mt-0.5 truncate">{details.join(" · ")}</p>+ {details.length > 0 && <span className="truncate">· {details.join(" · ")}</span>}+ </p></div><div className="flex items-center gap-1 flex-shrink-0">{row.indexed && (- <button- onClick={onView}- disabled={loading}- className="text-xs text-indigo-400 hover:text-indigo-300 disabled:opacity-50 px-2 py-1 rounded transition-colors"- >+ <Button size="sm" className="!h-10" onClick={onView} disabled={loading}>{loading ? "Loading…" : "View"}- </button>- )}- {row.url && (- <a- href={row.url}- target="_blank"- rel="noopener noreferrer"- className="text-xs text-fg-muted hover:text-fg px-2 py-1 rounded transition-colors"- >- Open in {SOURCE_LABELS[row.source]} ↗- </a>- )}- {row.source === "upload" ? (- <button- onClick={onDelete}- className="text-xs text-red-400 hover:text-red-300 px-2 py-1 rounded transition-colors"- >- Delete- </button>- ) : (- <span- className="text-[11px] text-fg-subtle px-2"- title={`Remove it from ${SOURCE_LABELS[row.source]} and it drops off on the next sync.`}- >- Managed in {SOURCE_LABELS[row.source]}- </span>+ </Button>)}+ <OverflowMenu items={menu} label={`More actions for ${row.name}`} /></div></li>);}-function Viewer({ doc, onClose }: { doc: Viewing; onClose: () => void }) {+function Viewer({ doc, onClose }: { doc: Viewing | null; onClose: () => void }) {return (- <div- className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"- onClick={onClose}+ <SidePanel+ open={doc !== null}+ onClose={onClose}+ width="lg"+ title={<span className="block truncate">{doc?.name}</span>}+ subtitle={+ doc+ ? doc.source === "upload"+ ? "Uploaded document"+ : `From ${SOURCE_LABELS[doc.source]}`+ : undefined+ }+ footer={+ doc?.url ? (+ <a+ href={doc.url}+ target="_blank"+ rel="noopener noreferrer"+ className={buttonClass("secondary", "md")}+ >+ Open original ↗+ </a>+ ) : undefined+ }>- <div- className="flex max-h-[85vh] w-full max-w-3xl flex-col rounded-2xl border border-line-strong bg-surface-elevated shadow-2xl"- onClick={(e) => e.stopPropagation()}- >- <div className="flex items-center justify-between gap-3 border-b border-line-strong/60 px-6 py-4">- <div className="min-w-0">- <p className="text-xs font-semibold uppercase tracking-widest text-indigo-400">- {doc.source === "upload" ? "Uploaded document" : `From ${SOURCE_LABELS[doc.source]}`}- </p>- <h3 className="truncate text-base font-semibold text-fg">{doc.name}</h3>- </div>- <div className="flex items-center gap-1 flex-shrink-0">- {doc.url && (- <a- href={doc.url}- target="_blank"- rel="noopener noreferrer"- className="rounded-lg px-3 py-1.5 text-xs text-fg-muted hover:bg-surface-overlay hover:text-fg transition-colors"- >- Open original ↗- </a>- )}- <button- onClick={onClose}- className="rounded-lg px-3 py-1.5 text-xs text-fg-muted hover:bg-surface-overlay hover:text-fg transition-colors"- >- Close- </button>- </div>- </div>- <div className={`flex-1 overflow-y-auto px-6 py-5 ${PROSE_CLASS}`}>+ {doc && (+ <div className={PROSE_CLASS}><ReactMarkdown remarkPlugins={[remarkGfm]} components={SAFE_MARKDOWN}>{doc.content}</ReactMarkdown></div>- </div>- </div>+ )}+ </SidePanel>);}diff --git a/packages/ui/src/components/knowledge/FileEditor.tsx b/packages/ui/src/components/knowledge/FileEditor.tsxindex 95307dc7..45e5ab69 100644--- a/packages/ui/src/components/knowledge/FileEditor.tsx+++ b/packages/ui/src/components/knowledge/FileEditor.tsx@@ -5,6 +5,8 @@ import ReactMarkdown from "react-markdown";import remarkGfm from "remark-gfm";import type { BuiltinFileContent, ReviewItem, ReviewStatus } from "@/lib/api";import ReviewStatusPill from "@/components/ReviewStatusPill";+import Button from "@/components/ui/Button";+import OverflowMenu, { type OverflowItem } from "@/components/ui/OverflowMenu";interface FileEditorProps {file: BuiltinFileContent;@@ -21,7 +23,7 @@ interface FileEditorProps {}const PROSE_CLASS =- "prose prose-invert prose-sm max-w-none prose-p:text-fg prose-headings:text-fg prose-strong:text-fg prose-code:text-indigo-300 prose-code:bg-surface-overlay prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-xs prose-code:before:content-none prose-code:after:content-none prose-pre:bg-surface-overlay prose-pre:border prose-pre:border-line-strong prose-blockquote:border-line-strong prose-blockquote:text-fg-muted prose-ul:text-fg prose-ol:text-fg prose-li:marker:text-fg-muted prose-hr:border-line-strong prose-a:text-indigo-400 prose-a:no-underline hover:prose-a:underline prose-table:text-fg prose-th:text-fg prose-th:border-line-strong prose-td:border-line-strong";+ "prose prose-sm sm:prose-base max-w-none prose-p:text-fg prose-headings:text-fg prose-strong:text-fg prose-code:text-accent prose-code:bg-surface-overlay prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-xs prose-code:before:content-none prose-code:after:content-none prose-pre:bg-surface-overlay prose-pre:border prose-pre:border-line-strong prose-blockquote:border-line-strong prose-blockquote:text-fg-muted prose-ul:text-fg prose-ol:text-fg prose-li:marker:text-fg-muted prose-hr:border-line-strong prose-a:text-accent prose-a:no-underline hover:prose-a:underline prose-table:text-fg prose-th:text-fg prose-th:border-line-strong prose-td:border-line-strong";export default function FileEditor({file,@@ -37,72 +39,63 @@ export default function FileEditor({}: FileEditorProps) {const [mode, setMode] = useState<"edit" | "preview">("preview");const isFailure = variant === "failure";- const accent = isFailure ? "text-rose-400" : "text-indigo-400";+ const accent = isFailure ? "text-rose-500" : "text-accent";++ // Approve stays on the card while the file is unapproved; the rarer review+ // flag and Delete sit in the ⋯ menu.+ const menu: OverflowItem[] = [];+ if (review && review.status !== "needs_revision") {+ menu.push({ label: "Flag for revision", onSelect: () => onSetReviewStatus("needs_revision") });+ }+ menu.push({ label: "Delete file", danger: true, onSelect: onDelete });return (- <div className="flex flex-col gap-3 h-full">- <div className="flex items-center justify-between gap-3 flex-wrap">- <div>- <span className={`text-xs font-semibold uppercase tracking-widest ${accent}`}>+ <div className="flex flex-col gap-4 h-full">+ <div className="flex items-start justify-between gap-3 flex-wrap">+ <div className="min-w-0">+ <span className={`text-sm font-semibold capitalize ${accent}`}>{isFailure ? "Failure · " : ""}{file.domain}</span>- <h2 className="text-base font-semibold text-fg mt-0.5">{file.filename}</h2>+ <h2 className="text-lg sm:text-xl font-bold text-fg mt-0.5 break-words">{file.filename}</h2>{review && (- <div className="flex items-center gap-2 mt-1">+ <div className="flex items-center gap-2 mt-2"><ReviewStatusPillstatus={review.status}reviewedAt={review.reviewed_at}trustedDefault={review.trusted_default}/>{review.status !== "approved" && (- <button- onClick={() => onSetReviewStatus("approved")}- className="text-[11px] text-emerald-400 hover:text-emerald-300 transition-colors"- >+ <Button size="sm" onClick={() => onSetReviewStatus("approved")}>Approve- </button>- )}- {review.status !== "needs_revision" && (- <button- onClick={() => onSetReviewStatus("needs_revision")}- className="text-[11px] text-violet-400 hover:text-violet-300 transition-colors"- >- Flag- </button>+ </Button>)}</div>)}</div><div className="flex items-center gap-2">- <div className="flex gap-0.5 p-0.5 bg-surface-overlay rounded-lg border border-line-strong/50">+ <div+ role="group"+ aria-label="Mode"+ className="flex gap-1 p-1 bg-surface-overlay rounded-xl border border-line"+ >{(["edit", "preview"] as const).map((m) => (<buttonkey={m}onClick={() => setMode(m)}- className={`px-3 py-1 rounded-md text-xs font-medium transition-colors capitalize ${- mode === m- ? "bg-surface-input text-fg"- : "text-fg-muted hover:text-fg"+ aria-pressed={mode === m}+ className={`h-9 px-3.5 rounded-lg text-sm font-medium transition-colors capitalize ${+ mode === m ? "bg-surface-elevated text-fg shadow-sm" : "text-fg-muted hover:text-fg"}`}>{m}</button>))}</div>- <button- onClick={onDelete}- className="px-3 py-1.5 rounded-lg border border-red-500/20 text-red-400 text-xs hover:bg-red-500/10 transition-colors"- >- Delete- </button>- <button- onClick={onSave}- disabled={!isDirty || isSaving}- className="px-3 py-1.5 rounded-lg bg-indigo-500 hover:bg-indigo-400 disabled:opacity-40 text-white text-xs font-medium transition-colors"- >+ <Button variant="primary" onClick={onSave} disabled={!isDirty || isSaving}>{isSaving ? "Saving…" : isDirty ? "Save" : "Saved"}- </button>+ </Button>+ <OverflowMenu items={menu} label="More file actions" /></div></div>@@ -110,13 +103,13 @@ export default function FileEditor({<textareavalue={content}onChange={(e) => onChange(e.target.value)}- className="flex-1 min-h-[520px] w-full rounded-xl border border-line-strong bg-surface-elevated px-4 py-3 text-sm text-fg font-mono leading-relaxed focus:outline-none focus:ring-2 focus:ring-indigo-500/50 resize-none"+ className="flex-1 min-h-[520px] w-full rounded-2xl border border-line-strong bg-surface-elevated px-4 py-3 text-sm text-fg font-mono leading-relaxed focus:outline-none focus:ring-2 focus:ring-accent/50 resize-none"spellCheck={false}/>) : (<div- className={`flex-1 h-[520px] rounded-xl border bg-surface-elevated px-6 py-5 overflow-y-auto ${PROSE_CLASS} ${- isFailure ? "border-rose-900/40" : "border-line-strong"+ className={`flex-1 min-h-[520px] rounded-2xl border bg-surface-elevated px-5 py-5 sm:px-6 ${PROSE_CLASS} ${+ isFailure ? "border-rose-500/30" : "border-line"}`}><ReactMarkdown remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>diff --git a/packages/ui/src/components/knowledge/KnowledgeWorkspace.tsx b/packages/ui/src/components/knowledge/KnowledgeWorkspace.tsxindex 85349187..1c49f0ce 100644--- a/packages/ui/src/components/knowledge/KnowledgeWorkspace.tsx+++ b/packages/ui/src/components/knowledge/KnowledgeWorkspace.tsx@@ -23,6 +23,16 @@ import {} from "@/lib/api";import ReviewQueue from "@/components/ReviewQueue";import PageSideNav from "@/components/shell/PageSideNav";+import Button from "@/components/ui/Button";+import SectionTabs from "@/components/ui/SectionTabs";+import {+ ADVANCED_VIEWS,+ VIEW_LABELS,+ isAdvancedView,+ viewForSelection,+ viewFromParam,+ type KnowledgeView,+} from "@/lib/knowledgeViews";import CompanyPanel from "./CompanyPanel";import FileEditor from "./FileEditor";import NewFileForm from "./NewFileForm";@@ -30,24 +40,15 @@ import QueryPanel from "./QueryPanel";import ReferencePanel from "./ReferencePanel";import SourceTree, { type FileKind, type Selection } from "./SourceTree";-// What the phone bar above the source tree names as open.-function selectionLabel(selection: Selection): string | undefined {- switch (selection?.kind) {- case "file":- return selection.filename;- case "new":- return "New file";- case "company":- return "Company documents";- case "reference":- return "Reference library";- case "query":- return "Query mode";- case "review":- return "Review queue";- default:- return undefined;- }+// What the phone bar above the playbooks tree names as open.+function fileLabel(selection: Selection): string | undefined {+ if (selection?.kind === "file") return selection.filename;+ if (selection?.kind === "new") return "New file";+ return undefined;+}++function selectionForView(view: KnowledgeView): Selection {+ return { kind: view };}const DOMAINS = [@@ -73,10 +74,10 @@ export default function KnowledgeWorkspace() {const [builtinFiles, setBuiltinFiles] = useState<BuiltinFileMeta[]>([]);const [failureFiles, setFailureFiles] = useState<BuiltinFileMeta[]>([]);// `/knowledge?view=review` (and the old `/review` route, which redirects- // here) opens straight onto the review queue.- // Everything else opens on the company documents.+ // here) opens straight onto the review queue; `?view=` also takes the other+ // Advanced views. Everything else opens on the company documents.const [selection, setSelection] = useState<Selection>(() =>- searchParams.get("view") === "review" ? { kind: "review" } : { kind: "company" }+ selectionForView(viewFromParam(searchParams.get("view"))));const [companyCount, setCompanyCount] = useState<number | null>(null);const [reviewCount, setReviewCount] = useState(0);@@ -86,12 +87,19 @@ export default function KnowledgeWorkspace() {// overwrite a newer one.const reviewSeq = useRef(0);- // Also follow `?view=review` on in-app navigation, where the page is not+ // Also follow `?view=` on in-app navigation, where the page is not// remounted and the initializer above doesn't run again.- const view = searchParams.get("view");+ const viewParam = searchParams.get("view");useEffect(() => {- if (view === "review") setSelection({ kind: "review" });- }, [view]);+ const wanted = viewFromParam(viewParam);+ if (isAdvancedView(wanted)) setSelection(selectionForView(wanted));+ }, [viewParam]);+ const view = viewForSelection(selection?.kind);+ // The Advanced view last open, so "Advanced" returns to it.+ const [lastAdvanced, setLastAdvanced] = useState<KnowledgeView>(+ isAdvancedView(view) ? view : "review"+ );+ if (isAdvancedView(view) && view !== lastAdvanced) setLastAdvanced(view);const [selectedContent, setSelectedContent] = useState<BuiltinFileContent | null>(null);const [editContent, setEditContent] = useState("");const [isDirty, setIsDirty] = useState(false);@@ -206,7 +214,7 @@ export default function KnowledgeWorkspace() {selection.fileKind === "builtin" ? deleteBuiltinFile : deleteFailureFile;try {await deleter(selection.domain, selection.filename);- setSelection({ kind: "company" });+ setSelection({ kind: "playbooks" });await loadIndex();} catch {setError("Failed to delete file");@@ -232,75 +240,148 @@ export default function KnowledgeWorkspace() {[]);+ function openView(next: KnowledgeView) {+ if (next === view) return;+ setSelection(selectionForView(next));+ }+return (- <div className="flex flex-col md:flex-row h-full">- <PageSideNav- label="Showing"- current={selectionLabel(selection)}- closeKey={JSON.stringify(selection)}- className="md:w-64 bg-surface-elevated md:bg-surface/40 px-4 py-5"- >- <SourceTree- domains={DOMAINS}- builtinFiles={builtinFiles}- failureFiles={failureFiles}- selection={selection}- filter={filter}- onFilterChange={setFilter}- reviewCount={reviewCount}- companyCount={companyCount}- onSelect={setSelection}+ <div className="h-full overflow-y-auto">+ <div className="mx-auto max-w-6xl px-4 py-6 sm:px-8 sm:py-8">+ <div className="mb-6">+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg">Knowledge</h1>+ <p className="mt-1.5 text-[15px] text-fg-muted max-w-2xl">+ Everything here is read by the Executive when it answers questions about your+ company.+ </p>+ </div>++ <SectionTabs+ label="Knowledge"+ active={isAdvancedView(view) ? "advanced" : "company"}+ onChange={(t) => openView(t === "advanced" ? lastAdvanced : "company")}+ tabs={[+ { id: "company", label: VIEW_LABELS.company, badge: companyCount },+ {+ id: "advanced",+ label: "Advanced",+ // The review count rides on "Advanced" so pending items show+ // from the documents view too.+ badge: !isAdvancedView(view) && reviewCount > 0 ? reviewCount : null,+ badgeTone: "attention",+ },+ ]}/>- </PageSideNav>- <main className="flex-1 min-h-0 min-w-0 overflow-y-auto px-4 py-5 sm:px-8 sm:py-6">- {error && (- <div className="mb-4 text-xs text-red-400 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2">- {error}+ {isAdvancedView(view) && (+ <div className="mt-3 flex items-center gap-1 overflow-x-auto border-b border-line">+ {ADVANCED_VIEWS.map((v) => {+ const active = v === view;+ return (+ <button+ key={v}+ onClick={() => openView(v)}+ aria-current={active ? "page" : undefined}+ className={`-mb-px inline-flex h-11 flex-shrink-0 items-center gap-2 whitespace-nowrap border-b-2 px-3 text-[15px] font-medium transition-colors ${+ active+ ? "border-accent text-fg"+ : "border-transparent text-fg-muted hover:text-fg"+ }`}+ >+ {VIEW_LABELS[v]}+ {v === "review" && reviewCount > 0 && (+ <span className="rounded-full bg-amber-500/15 px-2 py-0.5 text-xs font-semibold tabular-nums text-amber-500">+ {reviewCount}+ </span>+ )}+ </button>+ );+ })}</div>)}- {selection?.kind === "file" && selectedContent && (- <FileEditor- file={selectedContent}- content={editContent}- isDirty={isDirty}- isSaving={isSaving}- variant={selection.fileKind === "failures" ? "failure" : "playbook"}- review={fileReview}- onSetReviewStatus={handleSetReviewStatus}- onChange={(v) => {- setEditContent(v);- setIsDirty(true);- }}- onSave={handleSave}- onDelete={handleDelete}- />- )}-- {selection?.kind === "file" && !selectedContent && !error && (- <p className="text-sm text-fg-muted">Loading…</p>- )}-- {selection?.kind === "new" && (- <NewFileForm- domains={DOMAINS}- initialDomain={DOMAINS[0]}- variant={selection.fileKind === "failures" ? "failure" : "playbook"}- onSave={(domain, filename, content) =>- handleCreate(selection.fileKind, domain, filename, content)- }- onCancel={() => setSelection({ kind: "company" })}- />+ {error && (+ <div className="mt-5 text-sm text-red-500 bg-red-500/10 border border-red-500/20 rounded-xl px-4 py-3">+ {error}+ </div>)}- {selection?.kind === "review" && <ReviewQueue />}- {selection?.kind === "company" && <CompanyPanel onCountChange={setCompanyCount} />}- {selection?.kind === "reference" && <ReferencePanel />}- {selection?.kind === "query" && (- <QueryPanel domains={DOMAINS} onOpenFile={openFile} />- )}- </main>+ <div className="mt-6">+ {view === "company" && <CompanyPanel onCountChange={setCompanyCount} />}+ {view === "review" && <ReviewQueue />}+ {view === "reference" && <ReferencePanel />}+ {view === "query" && <QueryPanel domains={DOMAINS} onOpenFile={openFile} />}+ {view === "playbooks" && (+ <div className="flex flex-col md:flex-row md:gap-6">+ <PageSideNav+ label="File"+ current={fileLabel(selection)}+ closeKey={JSON.stringify(selection)}+ className="md:w-64 md:max-h-[calc(100vh-14rem)] md:sticky md:top-0 bg-surface-elevated md:bg-transparent p-4 md:p-0 md:pr-4"+ >+ <SourceTree+ domains={DOMAINS}+ builtinFiles={builtinFiles}+ failureFiles={failureFiles}+ selection={selection}+ filter={filter}+ onFilterChange={setFilter}+ onSelect={setSelection}+ />+ </PageSideNav>+ <div className="min-w-0 flex-1 pt-4 md:pt-0">+ {selection?.kind === "file" && selectedContent && (+ <FileEditor+ file={selectedContent}+ content={editContent}+ isDirty={isDirty}+ isSaving={isSaving}+ variant={selection.fileKind === "failures" ? "failure" : "playbook"}+ review={fileReview}+ onSetReviewStatus={handleSetReviewStatus}+ onChange={(v) => {+ setEditContent(v);+ setIsDirty(true);+ }}+ onSave={handleSave}+ onDelete={handleDelete}+ />+ )}+ {selection?.kind === "file" && !selectedContent && !error && (+ <p className="text-[15px] text-fg-muted">Loading…</p>+ )}+ {selection?.kind === "new" && (+ <NewFileForm+ domains={DOMAINS}+ initialDomain={DOMAINS[0]}+ variant={selection.fileKind === "failures" ? "failure" : "playbook"}+ onSave={(domain, filename, content) =>+ handleCreate(selection.fileKind, domain, filename, content)+ }+ onCancel={() => setSelection({ kind: "playbooks" })}+ />+ )}+ {selection?.kind === "playbooks" && (+ <div className="rounded-2xl border border-dashed border-line-strong px-6 py-12 text-center">+ <p className="text-base font-semibold text-fg">Built-in playbooks</p>+ <p className="mt-1.5 text-[15px] text-fg-muted max-w-md mx-auto">+ The frameworks and failure case studies each specialist draws on.+ Pick a file to read or edit it, or add your own.+ </p>+ <Button+ variant="primary"+ className="mt-5"+ onClick={() => setSelection({ kind: "new", fileKind: "builtin" })}+ >+ New playbook+ </Button>+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ </div></div>);}diff --git a/packages/ui/src/components/knowledge/NewFileForm.tsx b/packages/ui/src/components/knowledge/NewFileForm.tsxindex b18ce3cc..bac92040 100644--- a/packages/ui/src/components/knowledge/NewFileForm.tsx+++ b/packages/ui/src/components/knowledge/NewFileForm.tsx@@ -1,6 +1,7 @@"use client";import { useState } from "react";+import Button from "@/components/ui/Button";interface NewFileFormProps {domains: string[];@@ -48,17 +49,18 @@ export default function NewFileForm({return (<div className="flex flex-col gap-4">- <h2 className="text-base font-semibold text-fg">{title}</h2>+ <h2 className="text-lg sm:text-xl font-bold text-fg">{title}</h2>{error && (- <p className="text-xs text-red-400 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2">+ <p className="text-sm text-red-500 bg-red-500/10 border border-red-500/20 rounded-xl px-4 py-3">{error}</p>)}- <div className="flex gap-3">+ <div className="flex flex-col sm:flex-row gap-3"><selectvalue={domain}onChange={(e) => setDomain(e.target.value)}- className="rounded-lg border border-line-strong bg-surface-elevated px-3 py-2 text-sm text-fg focus:outline-none focus:ring-2 focus:ring-indigo-500/50"+ aria-label="Domain"+ className="h-11 rounded-xl border border-line-strong bg-surface-elevated px-3 text-[15px] text-fg capitalize focus:outline-none focus:ring-2 focus:ring-accent/50">{domains.map((d) => (<option key={d} value={d}>@@ -70,29 +72,27 @@ export default function NewFileForm({value={filename}onChange={(e) => setFilename(e.target.value)}placeholder={variant === "failure" ? "my-failure-case.md" : "my_topic.md"}- className="flex-1 rounded-lg border border-line-strong bg-surface-elevated px-3 py-2 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-indigo-500/50"+ aria-label="Filename"+ className="flex-1 h-11 rounded-xl border border-line-strong bg-surface-elevated px-3 text-[15px] text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-accent/50"/></div><textareavalue={content}onChange={(e) => setContent(e.target.value)}placeholder={placeholder}- className="min-h-[400px] w-full rounded-xl border border-line-strong bg-surface-elevated px-4 py-3 text-sm text-fg font-mono focus:outline-none focus:ring-2 focus:ring-indigo-500/50 resize-none"+ className="min-h-[400px] w-full rounded-2xl border border-line-strong bg-surface-elevated px-4 py-3 text-sm text-fg font-mono focus:outline-none focus:ring-2 focus:ring-accent/50 resize-none"/><div className="flex gap-3">- <button+ <Button+ variant="primary"onClick={handleSubmit}disabled={!filename.trim() || !content.trim() || isSaving}- className="px-4 py-2 bg-indigo-500 hover:bg-indigo-400 disabled:opacity-40 text-white text-sm font-medium rounded-xl transition-colors">{isSaving ? "Creating…" : "Create file"}- </button>- <button- onClick={onCancel}- className="px-4 py-2 border border-line-strong text-fg-muted hover:text-fg text-sm rounded-xl transition-colors"- >+ </Button>+ <Button variant="ghost" onClick={onCancel}>Cancel- </button>+ </Button></div></div>);diff --git a/packages/ui/src/components/knowledge/QueryPanel.tsx b/packages/ui/src/components/knowledge/QueryPanel.tsxindex a37379b3..eb705c44 100644--- a/packages/ui/src/components/knowledge/QueryPanel.tsx+++ b/packages/ui/src/components/knowledge/QueryPanel.tsx@@ -7,6 +7,7 @@ import {type KnowledgeSearchResponse,type KnowledgeSourceType,} from "@/lib/api";+import Button from "@/components/ui/Button";interface QueryPanelProps {domains: string[];@@ -77,15 +78,14 @@ export default function QueryPanel({ domains, onOpenFile }: QueryPanelProps) {return (<div className="flex flex-col gap-5 max-w-4xl"><div>- <h2 className="text-base font-semibold text-fg">Query mode</h2>- <p className="text-xs text-fg-muted mt-1">+ <p className="text-[15px] text-fg-muted">Test what the Executive would retrieve for a given question. Distances arecosine — lower is closer.</p></div>- <div className="space-y-3 rounded-xl border border-line bg-surface-elevated/40 p-4">- <div className="flex gap-2">+ <div className="space-y-4 rounded-2xl border border-line bg-surface-elevated p-4 sm:p-5">+ <div className="flex flex-col sm:flex-row gap-2"><inputvalue={query}onChange={(e) => setQuery(e.target.value)}@@ -96,26 +96,23 @@ export default function QueryPanel({ domains, onOpenFile }: QueryPanelProps) {}}}placeholder="e.g. how should we think about pricing for a new SaaS product?"- className="flex-1 rounded-lg border border-line-strong bg-surface-elevated px-3 py-2 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-indigo-500/50"+ aria-label="Question to test"+ className="w-full sm:flex-1 h-11 rounded-xl border border-line-strong bg-surface-elevated px-3.5 text-[15px] text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-accent/50"/>- <button- onClick={run}- disabled={!query.trim() || running}- className="px-4 py-2 rounded-lg bg-indigo-500 hover:bg-indigo-400 disabled:opacity-40 text-white text-sm font-medium transition-colors"- >+ <Button variant="primary" onClick={run} disabled={!query.trim() || running}>{running ? "Running…" : "Run"}- </button>+ </Button></div><div className="flex flex-wrap gap-4">- <div className="flex items-center gap-2">- <label className="text-[11px] uppercase tracking-widest text-fg-muted">+ <div className="flex items-center gap-2 min-w-0 w-full sm:w-auto">+ <label className="text-sm font-medium text-fg-muted flex-shrink-0">Specialist</label><selectvalue={specialist}onChange={(e) => setSpecialist(e.target.value)}- className="rounded-lg border border-line-strong bg-surface-elevated px-2 py-1 text-xs text-fg focus:outline-none focus:ring-2 focus:ring-indigo-500/50"+ className="h-10 min-w-0 flex-1 sm:flex-none rounded-xl border border-line-strong bg-surface-elevated px-3 text-sm text-fg focus:outline-none focus:ring-2 focus:ring-accent/50">{SPECIALISTS.map((s) => (<option key={s.id || "all"} value={s.id}>@@ -126,17 +123,18 @@ export default function QueryPanel({ domains, onOpenFile }: QueryPanelProps) {</div><div className="flex items-center gap-2 flex-wrap">- <label className="text-[11px] uppercase tracking-widest text-fg-muted">+ <label className="text-sm font-medium text-fg-muted">Include</label>{ALL_SOURCES.map((t) => (<buttonkey={t}onClick={() => toggleInclude(t)}- className={`text-xs px-2 py-1 rounded border transition-colors ${+ aria-pressed={includes.has(t)}+ className={`h-10 text-sm px-3.5 rounded-xl border transition-colors ${includes.has(t)- ? "bg-indigo-500/15 text-indigo-300 border-indigo-500/40"- : "bg-surface-overlay/40 text-fg-muted border-line-strong"+ ? "bg-accent/10 text-accent border-accent/30"+ : "bg-surface-overlay/40 text-fg-muted border-line"}`}>{t}@@ -146,17 +144,18 @@ export default function QueryPanel({ domains, onOpenFile }: QueryPanelProps) {</div><div className="flex items-center gap-2 flex-wrap">- <label className="text-[11px] uppercase tracking-widest text-fg-muted">+ <label className="text-sm font-medium text-fg-muted">Domains</label>{domains.map((d) => (<buttonkey={d}onClick={() => toggleDomain(d)}- className={`text-xs px-2 py-1 rounded border transition-colors ${+ aria-pressed={selectedDomains.has(d)}+ className={`h-10 text-sm px-3.5 rounded-xl border transition-colors ${selectedDomains.has(d)- ? "bg-surface-input text-fg border-line-strong"- : "bg-surface-overlay/40 text-fg-muted border-line-strong hover:text-fg"+ ? "bg-accent/10 text-accent border-accent/30"+ : "bg-surface-overlay/40 text-fg-muted border-line hover:text-fg"}`}>{d}@@ -165,23 +164,23 @@ export default function QueryPanel({ domains, onOpenFile }: QueryPanelProps) {{selectedDomains.size > 0 && (<buttononClick={() => setSelectedDomains(new Set())}- className="text-xs text-fg-muted hover:text-fg underline-offset-2 hover:underline"+ className="h-10 px-2 text-sm text-fg-muted hover:text-fg underline-offset-2 hover:underline">- clear+ Clear</button>)}</div></div>{error && (- <div className="text-sm text-red-400 px-4 py-3 rounded-xl bg-red-950/40 border border-red-900/60">+ <div className="text-sm text-red-500 px-4 py-3 rounded-xl bg-red-500/10 border border-red-500/20">{error}</div>)}{result && (<div className="space-y-5">- <div className="text-xs text-fg-muted space-y-1">+ <div className="text-sm text-fg-muted space-y-1">{result.effective_domains && result.effective_domains.length > 0 ? (<p><span className="text-fg-muted">Domain filter:</span>{" "}@@ -244,7 +243,7 @@ function ResultGroup({onOpenFile?: (kind: "builtin" | "failures", domain: string, filename: string) => void;}) {const accentClass = {- indigo: "text-indigo-400 border-l-indigo-500/40",+ indigo: "text-accent border-l-accent/40",rose: "text-rose-400 border-l-rose-500/50",emerald: "text-emerald-400 border-l-emerald-500/40",amber: "text-amber-400 border-l-amber-500/40",@@ -254,22 +253,22 @@ function ResultGroup({return (<div><div className="flex items-baseline justify-between mb-2">- <h3 className={`text-xs font-semibold uppercase tracking-widest ${accentClass.split(" ")[0]}`}>+ <h3 className={`text-sm font-semibold ${accentClass.split(" ")[0]}`}>{title}</h3>- <span className="text-[10px] text-fg-subtle">{hits.length} hit{hits.length === 1 ? "" : "s"}</span>+ <span className="text-xs text-fg-subtle">{hits.length} hit{hits.length === 1 ? "" : "s"}</span></div>{hits.length === 0 ? (- <p className="text-xs text-fg-subtle">No matches.</p>+ <p className="text-sm text-fg-subtle">No matches.</p>) : (<div className="space-y-2">{hits.map((h, i) => (<divkey={`${kind}-${h.filename}-${h.chunk_index ?? i}`}- className={`rounded-lg bg-surface-elevated/60 border border-line border-l-2 px-3 py-2 ${accentClass}`}+ className={`rounded-xl bg-surface-elevated border border-line border-l-2 px-4 py-3 ${accentClass}`}><div className="flex items-baseline justify-between gap-3 flex-wrap">- <div className="flex items-baseline gap-2 flex-wrap text-xs">+ <div className="flex items-baseline gap-2 flex-wrap text-sm"><span className="text-fg font-medium">{h.filename}</span><span className="text-fg-muted">·</span><span className="text-fg-muted">{h.domain}</span>@@ -285,13 +284,13 @@ function ResultGroup({{isOpenable && onOpenFile && (<buttononClick={() => onOpenFile(kind, h.domain, h.filename)}- className="text-[10px] text-fg-muted hover:text-fg transition-colors"+ className="h-9 px-2 text-sm font-medium text-accent hover:underline">- open →+ Open →</button>)}</div>- <p className="text-xs text-fg mt-1.5 whitespace-pre-wrap leading-relaxed">+ <p className="text-sm text-fg mt-1.5 whitespace-pre-wrap leading-relaxed">{h.text}</p></div>diff --git a/packages/ui/src/components/knowledge/ReferencePanel.tsx b/packages/ui/src/components/knowledge/ReferencePanel.tsxindex 44d24e0a..8a4af77c 100644--- a/packages/ui/src/components/knowledge/ReferencePanel.tsx+++ b/packages/ui/src/components/knowledge/ReferencePanel.tsx@@ -7,6 +7,7 @@ import {type ExternalPeekChunk,type ExternalSourceInfo,} from "@/lib/api";+import { buttonClass } from "@/components/ui/Button";export default function ReferencePanel() {const [sources, setSources] = useState<ExternalSourceInfo[] | null>(null);@@ -44,7 +45,7 @@ export default function ReferencePanel() {if (error) {return (- <div className="text-sm text-red-400 px-4 py-3 rounded-xl bg-red-950/40 border border-red-900/60">+ <div className="text-sm text-red-500 px-4 py-3 rounded-xl bg-red-500/10 border border-red-500/20">{error}</div>);@@ -59,19 +60,18 @@ export default function ReferencePanel() {return (<div className="space-y-6"><div>- <h2 className="text-base font-semibold text-fg">Reference Library</h2>- <p className="text-sm text-fg-muted mt-1">+ <p className="text-[15px] text-fg-muted max-w-2xl">Open-licensed textbooks and handbooks the Executive draws on. Declared in{" "}<code className="text-fg">knowledge/sources.yaml</code>. To add orrefresh: run <code className="text-fg">openexecutive ingest-oer</code>.</p>- <p className="text-xs text-fg-muted mt-2">+ <p className="text-sm text-fg-muted mt-2">{ingested.length} ingested · {pending.length} pending ·{" "}{totalChunks.toLocaleString()} indexed chunks</p></div>- <div className="space-y-2">+ <div className="space-y-3">{sources.map((src) => (<SourceCardkey={src.id}@@ -112,25 +112,25 @@ function SourceCard({: "never";return (- <div className="rounded-xl bg-surface-overlay/60 border border-line-strong/50 overflow-hidden">- <div className="flex items-start justify-between gap-4 px-4 py-3">+ <div className="rounded-2xl bg-surface-elevated border border-line overflow-hidden">+ <div className="flex items-start justify-between gap-4 px-4 py-4 sm:px-5"><div className="min-w-0 flex-1"><div className="flex items-center gap-2 flex-wrap">- <p className="text-sm text-fg font-medium">{source.title}</p>+ <p className="text-base text-fg font-semibold">{source.title}</p><span- className={`text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded ${- source.is_ingested- ? "bg-emerald-950/60 text-emerald-400 border border-emerald-900/60"- : "bg-surface-input/60 text-fg-muted border border-line-strong/60"- }`}+ className="inline-flex items-center gap-1.5 text-sm text-fg-muted">- {source.is_ingested ? "ingested" : "pending"}+ <span+ aria-hidden+ className={`h-2 w-2 rounded-full ${source.is_ingested ? "bg-emerald-500" : "bg-fg-subtle"}`}+ />+ {source.is_ingested ? "Ingested" : "Pending"}</span>- <span className="text-[10px] uppercase tracking-wide text-fg-muted border border-line-strong px-1.5 py-0.5 rounded">- phase {source.phase}+ <span className="text-sm text-fg-subtle">+ · phase {source.phase}</span></div>- <p className="text-xs text-fg-muted mt-1">+ <p className="text-sm text-fg-muted mt-1">{source.publisher} · {source.license} ·{" "}<ahref={source.url}@@ -145,13 +145,13 @@ function SourceCard({{source.domains.map((d) => (<spankey={d}- className="text-[10px] text-fg-muted bg-surface-input/60 border border-line-strong/60 px-1.5 py-0.5 rounded"+ className="text-xs text-fg-muted bg-surface-overlay border border-line px-2 py-0.5 rounded-lg">{d}</span>))}</div>- <p className="text-xs text-fg-muted mt-2">+ <p className="text-sm text-fg-muted mt-2">{source.chunks.toLocaleString()} chunks · {source.files} file{source.files === 1 ? "" : "s"} · fetched {fetchedLabel}</p>@@ -159,20 +159,20 @@ function SourceCard({<buttononClick={isExpanded ? onCollapse : onPeek}disabled={!source.is_ingested}- className="text-xs px-3 py-1.5 rounded-lg bg-surface-input/60 border border-line-strong/60 text-fg hover:bg-surface-input disabled:opacity-40 disabled:cursor-not-allowed transition-colors flex-shrink-0"+ className={buttonClass("secondary", "sm", "!h-10 flex-shrink-0")}>{isExpanded ? "Hide" : "Peek"}</button></div>{isExpanded && (- <div className="border-t border-line-strong/50 px-4 py-3 space-y-2 bg-surface-elevated/40">- {peekError && <p className="text-xs text-fg-muted">{peekError}</p>}+ <div className="border-t border-line px-4 py-3 sm:px-5 space-y-2 bg-surface-overlay/40">+ {peekError && <p className="text-sm text-fg-muted">{peekError}</p>}{chunks.map((c) => (<divkey={`${c.filename}-${c.chunk_index}-${c.domain}`}- className="text-xs text-fg bg-surface-overlay/60 border border-line-strong/50 rounded-lg px-3 py-2"+ className="text-sm text-fg bg-surface-elevated border border-line rounded-xl px-3.5 py-2.5">- <p className="text-[10px] text-fg-muted mb-1">+ <p className="text-xs text-fg-muted mb-1">{c.domain} · {c.filename} · chunk #{c.chunk_index}</p><p className="whitespace-pre-wrap leading-relaxed">diff --git a/packages/ui/src/components/knowledge/SourceTree.tsx b/packages/ui/src/components/knowledge/SourceTree.tsxindex d23f6224..4f68c89e 100644--- a/packages/ui/src/components/knowledge/SourceTree.tsx+++ b/packages/ui/src/components/knowledge/SourceTree.tsx@@ -1,14 +1,15 @@"use client";-import { useEffect, useMemo, useState } from "react";+import { useMemo, useState } from "react";import type { BuiltinFileMeta } from "@/lib/api";-import Icon, { type IconName } from "@/components/Icon";+import Icon from "@/components/Icon";export type FileKind = "builtin" | "failures";export type Selection =| { kind: "file"; fileKind: FileKind; domain: string; filename: string }| { kind: "new"; fileKind: FileKind }+ | { kind: "playbooks" }| { kind: "company" }| { kind: "reference" }| { kind: "query" }@@ -22,16 +23,12 @@ interface SourceTreeProps {selection: Selection;filter: string;onFilterChange: (value: string) => void;- /** Pending + needs-revision items, shown on the Review queue entry. */- reviewCount: number;- /** Listed company documents; null until the panel has loaded them. */- companyCount: number | null;onSelect: (sel: Selection) => void;}-/** Views that live under "Advanced"; landing on one opens the group. */-const ADVANCED_KINDS = new Set(["file", "new", "reference", "query", "review"]);-+// The built-in playbooks file tree: one group per domain, each with its+// playbooks and failure case studies. Lives in the "Built-in playbooks" view+// under Advanced on the Knowledge page.export default function SourceTree({domains,builtinFiles,@@ -39,15 +36,13 @@ export default function SourceTree({selection,filter,onFilterChange,- reviewCount,- companyCount,onSelect,}: SourceTreeProps) {- const [advancedOpen, setAdvancedOpen] = useState(- () => selection !== null && ADVANCED_KINDS.has(selection.kind)+ // Domains start folded so the tree reads as a short list; the open file's+ // domain starts open.+ const [openDomains, setOpenDomains] = useState<Set<string>>(+ () => new Set(selection?.kind === "file" ? [selection.domain] : []));- const [collapsedBuiltin, setCollapsedBuiltin] = useState(true);- const [collapsedDomains, setCollapsedDomains] = useState<Set<string>>(new Set());const builtinByDomain = useMemo(() => groupByDomain(builtinFiles), [builtinFiles]);const failuresByDomain = useMemo(() => groupByDomain(failureFiles), [failureFiles]);@@ -57,7 +52,7 @@ export default function SourceTree({!normalizedFilter || s.toLowerCase().includes(normalizedFilter);function toggleDomain(d: string) {- setCollapsedDomains((prev) => {+ setOpenDomains((prev) => {const next = new Set(prev);if (next.has(d)) next.delete(d);else next.add(d);@@ -74,147 +69,82 @@ export default function SourceTree({);}- // Follow navigation into an advanced view (e.g. `?view=review`).- const selectedKind = selection?.kind;- useEffect(() => {- if (selectedKind && ADVANCED_KINDS.has(selectedKind)) setAdvancedOpen(true);- }, [selectedKind]);-return (- <nav className="text-sm space-y-4">- <button- data-closes-nav- onClick={() => onSelect({ kind: "company" })}- className={`w-full flex items-center gap-2 text-left px-2.5 py-2 rounded-lg text-sm font-semibold transition-colors ${- selection?.kind === "company"- ? "bg-surface-input text-fg"- : "text-fg hover:bg-surface-overlay"- }`}- >- <Icon name="building" size="w-4 h-4" />- Company documents- {companyCount !== null && (- <span className="ml-auto text-xs font-normal text-fg-muted">{companyCount}</span>- )}- </button>-- <div className="border-t border-line pt-3">+ <nav aria-label="Built-in playbooks" className="space-y-4">+ <div className="grid grid-cols-2 gap-2"><button- onClick={() => setAdvancedOpen((v) => !v)}- className="w-full flex items-center gap-1.5 px-1 text-[11px] font-semibold text-fg-muted uppercase tracking-widest hover:text-fg transition-colors"+ data-closes-nav+ onClick={() => onSelect({ kind: "new", fileKind: "builtin" })}+ className="inline-flex h-10 items-center justify-center gap-1 whitespace-nowrap rounded-xl border border-line bg-surface-elevated px-2 text-sm font-medium text-fg hover:bg-surface-hover transition-colors">- <span className="text-fg-subtle w-3 inline-block">{advancedOpen ? "▾" : "▸"}</span>- Advanced- {!advancedOpen && reviewCount > 0 && (- <span className="ml-auto text-[10px] font-semibold normal-case tracking-normal px-1.5 rounded-full bg-amber-950/60 text-amber-400 border border-amber-900/60">- {reviewCount} to review- </span>- )}+ <Icon name="plus" size="w-4 h-4" />+ Playbook</button>- {!advancedOpen ? (- <p className="px-1 mt-1.5 text-[11px] text-fg-subtle leading-snug">- Built-in playbooks, reference library, retrieval testing and review.- </p>- ) : (- <div className="mt-3 space-y-3">- <RootButton- active={selection?.kind === "review"}- onClick={() => onSelect({ kind: "review" })}- icon="check-circle"- badge={reviewCount}- >- Review queue- </RootButton>- <Section- label="Built-in playbooks"- icon="grid"- collapsed={collapsedBuiltin}- onToggle={() => setCollapsedBuiltin((v) => !v)}+ <button+ data-closes-nav+ onClick={() => onSelect({ kind: "new", fileKind: "failures" })}+ className="inline-flex h-10 items-center justify-center gap-1 whitespace-nowrap rounded-xl border border-line bg-surface-elevated px-2 text-sm font-medium text-fg hover:bg-surface-hover transition-colors"+ >+ <Icon name="plus" size="w-4 h-4" />+ Failure case+ </button>+ </div>+ <input+ value={filter}+ onChange={(e) => onFilterChange(e.target.value)}+ placeholder="Filter files…"+ aria-label="Filter files"+ className="w-full h-10 rounded-xl border border-line bg-surface-elevated px-3 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-accent/40"+ />+ {domains.map((domain) => {+ const playbooks = (builtinByDomain[domain] ?? []).filter((f) => matches(f.filename));+ const failures = (failuresByDomain[domain] ?? []).filter((f) => matches(f.filename));+ if (normalizedFilter && playbooks.length === 0 && failures.length === 0) {+ return null;+ }+ const isCollapsed = !openDomains.has(domain) && !normalizedFilter;+ return (+ <div key={domain}>+ <button+ onClick={() => toggleDomain(domain)}+ aria-expanded={!isCollapsed}+ className="w-full flex items-center gap-2 h-10 px-1 text-sm font-semibold text-fg capitalize hover:text-accent transition-colors">- <input- value={filter}- onChange={(e) => onFilterChange(e.target.value)}- placeholder="Filter files…"- className="w-full rounded-lg border border-line bg-surface-elevated px-2.5 py-1.5 text-xs text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-indigo-500/40"+ <Icon+ name="chevron-right"+ size="w-4 h-4"+ className={`text-fg-subtle transition-transform ${isCollapsed ? "" : "rotate-90"}`}/>- {domains.map((domain) => {- const playbooks = (builtinByDomain[domain] ?? []).filter((f) =>- matches(f.filename)- );- const failures = (failuresByDomain[domain] ?? []).filter((f) =>- matches(f.filename)- );- if (normalizedFilter && playbooks.length === 0 && failures.length === 0) {- return null;- }- const isCollapsed = collapsedDomains.has(domain) && !normalizedFilter;- return (- <div key={domain}>- <button- onClick={() => toggleDomain(domain)}- className="w-full flex items-center gap-1.5 px-1 text-[11px] font-semibold text-fg-muted uppercase tracking-widest hover:text-fg transition-colors"- >- <span className="text-fg-subtle w-3 inline-block">- {isCollapsed ? "▸" : "▾"}- </span>- {domain}- </button>- {!isCollapsed && (- <div className="ml-3 mt-1 space-y-2">- <FileGroup- label="Playbooks"- files={playbooks}- accent="indigo"- onClickFile={(f) =>- onSelect({- kind: "file",- fileKind: "builtin",- domain,- filename: f.filename,- })- }- onAdd={() => onSelect({ kind: "new", fileKind: "builtin" })}- isActive={(f) => isActiveFile("builtin", domain, f.filename)}- />- <FileGroup- label="Failures"- files={failures}- accent="rose"- onClickFile={(f) =>- onSelect({- kind: "file",- fileKind: "failures",- domain,- filename: f.filename,- })- }- onAdd={() => onSelect({ kind: "new", fileKind: "failures" })}- isActive={(f) => isActiveFile("failures", domain, f.filename)}- />- </div>- )}- </div>- );- })}- </Section>- <RootButton- active={selection?.kind === "reference"}- onClick={() => onSelect({ kind: "reference" })}- icon="book"- >- Reference Library- </RootButton>- <RootButton- active={selection?.kind === "query"}- onClick={() => onSelect({ kind: "query" })}- accent="indigo"- icon="doc-search"- >- Query mode- </RootButton>+ {domain}+ <span className="ml-auto text-xs font-normal text-fg-subtle tabular-nums">+ {playbooks.length + failures.length}+ </span>+ </button>+ {!isCollapsed && (+ <div className="ml-3 mt-1 space-y-2 border-l border-line pl-2">+ <FileGroup+ label="Playbooks"+ files={playbooks}+ tone="default"+ onClickFile={(f) =>+ onSelect({ kind: "file", fileKind: "builtin", domain, filename: f.filename })+ }+ isActive={(f) => isActiveFile("builtin", domain, f.filename)}+ />+ <FileGroup+ label="Failures"+ files={failures}+ tone="rose"+ onClickFile={(f) =>+ onSelect({ kind: "file", fileKind: "failures", domain, filename: f.filename })+ }+ isActive={(f) => isActiveFile("failures", domain, f.filename)}+ />+ </div>+ )}</div>- )}- </div>+ );+ })}</nav>);}@@ -226,67 +156,25 @@ function groupByDomain(files: BuiltinFileMeta[]): Record<string, BuiltinFileMeta}, {});}-function Section({- label,- icon,- collapsed,- onToggle,- children,-}: {- label: string;- icon?: IconName;- collapsed: boolean;- onToggle: () => void;- children: React.ReactNode;-}) {- return (- <div>- <button- onClick={onToggle}- className="flex items-center gap-1.5 text-xs font-bold text-fg uppercase tracking-widest hover:text-white transition-colors mb-2"- >- <span className="text-fg-muted w-3 inline-block">{collapsed ? "▸" : "▾"}</span>- {icon && <Icon name={icon} size="w-3.5 h-3.5" className="text-fg-muted" />}- {label}- </button>- {!collapsed && <div className="space-y-3">{children}</div>}- </div>- );-}-function FileGroup({label,files,- accent,+ tone,onClickFile,- onAdd,isActive,}: {label: string;files: BuiltinFileMeta[];- accent: "indigo" | "rose";+ tone: "default" | "rose";onClickFile: (f: BuiltinFileMeta) => void;- onAdd: () => void;isActive: (f: BuiltinFileMeta) => boolean;}) {- const labelClass = accent === "rose" ? "text-rose-400/80" : "text-fg-muted";+ const labelClass = tone === "rose" ? "text-rose-500" : "text-fg-subtle";return (<div>- <div className="flex items-center justify-between px-1">- <span className={`text-[10px] uppercase tracking-widest font-semibold ${labelClass}`}>- {label}- </span>- <button- data-closes-nav- onClick={onAdd}- className="text-[10px] text-fg-subtle hover:text-fg transition-colors px-1"- title={`Add ${label.toLowerCase()} file`}- >- +- </button>- </div>+ <div className={`px-2 text-xs font-medium ${labelClass}`}>{label}</div>{files.length === 0 ? (- <p className="text-[11px] text-fg-subtle px-1 mt-0.5">none</p>+ <p className="text-xs text-fg-subtle px-2 mt-0.5">None</p>) : (<div className="mt-0.5">{files.map((f) => {@@ -296,11 +184,10 @@ function FileGroup({key={f.filename}data-closes-navonClick={() => onClickFile(f)}- className={`w-full text-left px-2 py-0.5 rounded text-xs transition-colors truncate ${+ aria-current={active ? "true" : undefined}+ className={`w-full text-left px-2 py-2.5 rounded-lg text-sm transition-colors truncate ${active- ? accent === "rose"- ? "bg-rose-500/15 text-rose-200"- : "bg-surface-input text-fg"+ ? "bg-accent/10 text-accent font-medium": "text-fg-muted hover:text-fg hover:bg-surface-overlay"}`}>@@ -313,38 +200,3 @@ function FileGroup({</div>);}--function RootButton({- active,- onClick,- accent,- icon,- badge = 0,- children,-}: {- active: boolean;- onClick: () => void;- accent?: "indigo";- icon?: IconName;- badge?: number;- children: React.ReactNode;-}) {- const activeClass = accent === "indigo" ? "bg-indigo-500/15 text-indigo-200" : "bg-surface-input text-fg";- return (- <button- data-closes-nav- onClick={onClick}- className={`w-full flex items-center gap-2 text-left px-2 py-1.5 rounded-lg text-xs font-bold uppercase tracking-widest transition-colors ${- active ? activeClass : "text-fg hover:text-white hover:bg-surface-overlay"- }`}- >- {icon && <Icon name={icon} size="w-3.5 h-3.5" />}- {children}- {badge > 0 && (- <span className="ml-auto text-[10px] font-semibold normal-case tracking-normal px-1.5 rounded-full bg-amber-950/60 text-amber-400 border border-amber-900/60">- {badge}- </span>- )}- </button>- );-}diff --git a/packages/ui/src/components/memories/CadenceSection.tsx b/packages/ui/src/components/memories/CadenceSection.tsxindex c323dc79..dc8fd006 100644--- a/packages/ui/src/components/memories/CadenceSection.tsx+++ b/packages/ui/src/components/memories/CadenceSection.tsx@@ -9,8 +9,10 @@ import {type ScheduledAction,} from "@/lib/api";import Icon, { type IconName } from "@/components/Icon";+import OverflowMenu from "@/components/ui/OverflowMenu";import { useWorkspace } from "@/components/workspace/WorkspaceContext";import {+ EmptyState,LivePulse,STATUS_PILL,SectionHeading,@@ -26,9 +28,11 @@ import {// metaFor / groupByRhythm) now lives in ./shared so the header stat strip and// these cards agree on how raw scheduled_actions `kind`s map to human groups.//-// The rhythm card shows the *pending* queue only (the upcoming cadence),-// fetched soonest-first. Follow-ups (ad_hoc one-offs) are pulled out of this-// card into their own `FollowUpsCard`, rendered under Memory on the Pulse page.+// The Heartbeat tab of the Pulse page has three views, each its own export:+// Activity (`RecentActivity`), Rhythm (the default export) and Follow-ups+// (`FollowUpsCard`). The rhythm card shows the *pending* queue only (the+// upcoming cadence), fetched soonest-first; follow-ups (ad_hoc one-offs) are+// their own view.// Over-fetch cap. The backend can't filter by `kind`, so we pull a generous// slice and group client-side; high-frequency system scans are capped at render@@ -39,7 +43,7 @@ const FETCH_LIMIT = 500;// Section shell// ----------------------------------------------------------------------------export default function CadenceSection() {+export default function RhythmSection() {// Solo hides the department check-ins and the awaiting-people block.const { mode } = useWorkspace();const [rows, setRows] = useState<ScheduledAction[]>([]);@@ -80,22 +84,20 @@ export default function CadenceSection() {groups.system.length > 0;return (- <div className="space-y-8">- <RecentActivity />-- <div className="rounded-xl border border-line bg-surface-elevated p-4">+ <div>+ <div className="rounded-2xl border border-line bg-surface-elevated p-4 sm:p-5">{loading ? (<div className="space-y-2"><Skeleton className="h-16 w-full" /><Skeleton className="h-16 w-full" /></div>) : !hasRhythm ? (- <div className="rounded-lg border border-line bg-surface-elevated/40 px-4 py-6 text-sm text-fg-muted">+ <div className="px-2 py-8 text-center text-[15px] text-fg-muted">No recurring cadence is scheduled yet. The heartbeat starts once thescheduler is running and a company profile is set.</div>) : (- <div className="max-h-[32rem] overflow-y-auto pr-1 space-y-6">+ <div className="space-y-8"><RhythmBlocktitle="Daily rhythm"subtitle="Your daily briefing cycle — the morning brief and end-of-day digest are sent to you by email or chat (Settings → Setup status shows where); the reflection sets up the morning brief."@@ -192,7 +194,7 @@ const SUMMARY_KINDS = new Set([// is read-only and the payload is small.const ACTIVITY_POLL_INTERVAL_MS = 20_000;-function RecentActivity() {+export function RecentActivity() {const [items, setItems] = useState<ActivityItem[]>([]);const [loading, setLoading] = useState(true);@@ -228,29 +230,33 @@ function RecentActivity() {if (loading) {return (- <div className="rounded-xl border border-line bg-surface-elevated p-4 space-y-2">+ <div className="rounded-2xl border border-line bg-surface-elevated p-4 sm:p-5 space-y-2"><Skeleton className="h-4 w-32" /><Skeleton className="h-4 w-full" /><Skeleton className="h-4 w-5/6" /></div>);}- if (items.length === 0) return null;+ if (items.length === 0) {+ return (+ <div className="rounded-2xl border border-line bg-surface-elevated">+ <EmptyState message="Nothing yet. Actions the Executive takes on its own show up here as they happen." />+ </div>+ );+ }return (- <div className="rounded-xl border border-line bg-surface-elevated p-4">- <div className="flex items-center justify-between gap-2 mb-3">+ <div className="rounded-2xl border border-line bg-surface-elevated p-4 sm:p-5">+ <div className="flex items-center justify-between gap-2 mb-4"><div className="flex items-center gap-2">- <Icon name="activity" size="w-4 h-4" className="text-emerald-400" />- <h3 className="text-sm font-semibold text-fg">Recent activity</h3>+ <Icon name="activity" size="w-5 h-5" className="text-emerald-500" />+ <h3 className="text-base font-semibold text-fg">Recent activity</h3></div><LivePulse /></div>- {/* Fixed-height scroll region so the feed scrolls internally instead of- growing the page. The timeline line lives on the inner <ol> (sized to- the full list) so it scrolls with the rows rather than clipping. */}- <div className="max-h-[32rem] overflow-y-auto pr-1">- <ol className="relative space-y-3 before:absolute before:left-[3px] before:top-1.5 before:bottom-1.5 before:w-px before:bg-line">+ {/* The timeline line lives on the <ol> (sized to the full list). */}+ <div>+ <ol className="relative space-y-4 before:absolute before:left-[3px] before:top-1.5 before:bottom-1.5 before:w-px before:bg-line">{items.map((it, i) => {const { relative } = formatRunAt(it.at);const { verb, subject } = activityLine(it);@@ -260,25 +266,25 @@ function RecentActivity() {return (<li key={`${it.at}-${it.kind}-${i}`} className="relative pl-5"><span- className="absolute left-0 top-1.5 h-[7px] w-[7px] rounded-full bg-emerald-400/80 ring-2 ring-surface-elevated"+ className="absolute left-0 top-2 h-[7px] w-[7px] rounded-full bg-emerald-500/80 ring-2 ring-surface-elevated"aria-hidden="true"/><div className="flex items-baseline gap-2 flex-wrap">{relative && (- <span className="text-[11px] text-fg-subtle tabular-nums">{relative}</span>+ <span className="text-xs text-fg-subtle tabular-nums">{relative}</span>)}- <span className="text-xs text-fg-muted">{verb}</span>+ <span className="text-sm text-fg-muted">{verb}</span>{!subjectIsSummary && (- <span className="text-xs text-fg" title={subject}>{subject}</span>+ <span className="text-sm text-fg" title={subject}>{subject}</span>)}{it.department && (- <span className="ml-auto text-[10px] text-fg-subtle hidden sm:inline">+ <span className="ml-auto text-xs text-fg-subtle hidden sm:inline capitalize">{it.department}</span>)}</div>{it.summary && (- <p className="text-xs text-fg-muted leading-snug break-words line-clamp-2 mt-0.5" title={it.summary}>+ <p className="text-[15px] text-fg leading-snug break-words line-clamp-2 mt-0.5" title={it.summary}>{it.summary}</p>)}@@ -343,30 +349,30 @@ function RhythmCard({const { absolute, relative } = formatRunAt(action.run_at);const isPending = action.status === "pending";return (- <div className="group py-2.5 hover:bg-surface-overlay/30 transition-colors flex items-start justify-between gap-3">+ <div className="py-3 flex items-start justify-between gap-3"><div className="min-w-0"><div className="flex items-center gap-2 flex-wrap">- <span className="text-sm text-fg font-medium" title={meta.label}>{meta.label}</span>+ <span className="text-[15px] text-fg font-semibold" title={meta.label}>{meta.label}</span>{showDepartment && action.department && (- <span className="px-2 py-0.5 rounded bg-surface-overlay text-fg text-[11px] font-medium capitalize">+ <span className="px-2 py-0.5 rounded-lg bg-surface-overlay text-fg text-xs font-medium capitalize">{action.department}</span>)}</div>{meta.blurb && (- <div className="text-xs text-fg-muted mt-0.5 line-clamp-2" title={meta.blurb}>+ <div className="text-sm text-fg-muted mt-0.5 line-clamp-2" title={meta.blurb}>{meta.blurb}</div>)}{action.last_error && action.status === "failed" && (- <div className="text-xs text-red-400 mt-1 font-mono break-words">+ <div className="text-sm text-red-500 mt-1 font-mono break-words">{action.last_error}</div>)}</div><div className="text-right whitespace-nowrap shrink-0">{isPending ? (- <div className="text-xs text-sky-300" title={absolute}>+ <div className="text-sm font-medium text-sky-500" title={absolute}>{relative ? `next ${relative}` : absolute}</div>) : (@@ -417,17 +423,16 @@ function SystemPulse({ actions }: { actions: ScheduledAction[] }) {))}</div>{hidden > 0 && (- <div className="text-xs text-fg-subtle mt-2">+{hidden} more not shown</div>+ <div className="text-sm text-fg-subtle mt-2">+{hidden} more not shown</div>)}</section>);}// ----------------------------------------------------------------------------// Follow-ups — one-off ad_hoc commitments, surfaced as their own card under-// Memory on the Pulse page. Self-contained: fetches the pending queue itself-// (independent of the rhythm card) and owns the per-row cancel. Hidden when-// there are no pending follow-ups, like the rhythm blocks.+// Follow-ups — one-off ad_hoc commitments, the Follow-ups view of the Pulse+// page's Heartbeat tab. Self-contained: fetches the pending queue itself+// (independent of the rhythm card) and owns the per-row cancel.// ---------------------------------------------------------------------------export function FollowUpsCard() {const [rows, setRows] = useState<ScheduledAction[]>([]);@@ -481,23 +486,29 @@ export function FollowUpsCard() {if (loading) {return (- <div className="rounded-xl border border-line bg-surface-elevated p-4 space-y-2">+ <div className="rounded-2xl border border-line bg-surface-elevated p-4 sm:p-5 space-y-2"><Skeleton className="h-4 w-32" /><Skeleton className="h-16 w-full" /></div>);}- if (followups.length === 0) return null;+ if (followups.length === 0) {+ return (+ <div className="rounded-2xl border border-line bg-surface-elevated">+ <EmptyState message="No follow-ups scheduled. When the Executive commits to come back to you, it shows up here." />+ </div>+ );+ }return (- <div className="rounded-xl border border-line bg-surface-elevated p-4">+ <div className="rounded-2xl border border-line bg-surface-elevated p-4 sm:p-5"><SectionHeadingtitle="Follow-ups"count={followups.length}icon="flag"subtitle="One-off commitments the Executive scheduled for you."/>- <div className="max-h-[32rem] overflow-y-auto pr-1 divide-y divide-line">+ <div className="divide-y divide-line">{followups.map((a) => (<FollowUpRowkey={a.id}@@ -523,42 +534,43 @@ function FollowUpRow({const { absolute, relative } = formatRunAt(action.run_at);const pill = STATUS_PILL[action.status] ?? STATUS_PILL.cancelled;return (- <div className="group py-3 hover:bg-surface-overlay/30 transition-colors">- <div className="flex items-start justify-between gap-3 mb-2">- <div className="flex items-center gap-2 text-xs text-fg-muted flex-wrap min-w-0">+ <div className="py-3">+ <div className="flex items-start justify-between gap-3 mb-1">+ <div className="flex items-center gap-2 text-sm text-fg-muted flex-wrap min-w-0 pt-2"><span className={`px-2 py-0.5 rounded border font-medium capitalize ${pill}`}>{action.status}</span>- <span className="px-2 py-0.5 rounded bg-surface-overlay text-fg font-medium">+ <span className="px-2 py-0.5 rounded-lg bg-surface-overlay text-fg font-medium">{action.channel}</span><span className="text-fg-subtle">→</span>- <span className="text-fg-muted font-mono text-[11px] truncate max-w-[12rem]" title={action.channel_ref}>{action.channel_ref}</span>+ <span className="text-fg-muted font-mono text-xs truncate max-w-[12rem]" title={action.channel_ref}>{action.channel_ref}</span><span title={absolute}>{relative || absolute}</span>{action.attempts > 0 && (<span className="text-amber-400">{action.attempts} attempt{action.attempts === 1 ? "" : "s"}</span>)}</div>- {action.status === "pending" && (- <button- onClick={onCancel}- disabled={cancelling}- className="text-xs text-red-400 hover:text-red-300 disabled:opacity-50 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity shrink-0"- >- {cancelling ? "Cancelling…" : "Cancel"}- </button>- )}+ {action.status === "pending" &&+ (cancelling ? (+ <span className="shrink-0 h-10 inline-flex items-center text-sm text-fg-muted">Cancelling…</span>+ ) : (+ <OverflowMenu+ size="sm"+ label="Follow-up actions"+ items={[{ label: "Cancel follow-up", danger: true, onSelect: onCancel }]}+ />+ ))}</div>- <div className="text-sm text-fg break-words line-clamp-2" title={action.intent_text}>+ <div className="text-[15px] text-fg break-words line-clamp-2" title={action.intent_text}>{action.intent_text}</div>{action.last_error && (- <div className="text-xs text-red-400 mt-2 font-mono break-words line-clamp-2" title={action.last_error}>+ <div className="text-sm text-red-500 mt-2 font-mono break-words line-clamp-2" title={action.last_error}>{action.last_error}</div>)}{action.originating_session_id && (- <div className="text-[11px] text-fg-subtle mt-2 font-mono truncate" title={`session: ${action.originating_session_id}`}>+ <div className="text-xs text-fg-subtle mt-2 font-mono truncate" title={`session: ${action.originating_session_id}`}>session: {action.originating_session_id}</div>)}diff --git a/packages/ui/src/components/memories/CorrectionsTab.tsx b/packages/ui/src/components/memories/CorrectionsTab.tsxindex 6c3bc41e..9c33bbb1 100644--- a/packages/ui/src/components/memories/CorrectionsTab.tsx+++ b/packages/ui/src/components/memories/CorrectionsTab.tsx@@ -11,6 +11,8 @@ import {type FactApprovalRule,type StandingFact,} from "@/lib/api";+import Button from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";import { EmptyState, formatDate } from "./shared";// The "what stuck" view: facts and corrections the principal or a teammate@@ -34,9 +36,9 @@ const KIND_LABEL: Record<StandingFact["kind"], string> = {};const KIND_PILL: Record<StandingFact["kind"], string> = {- fact: "bg-sky-500/15 text-sky-300 border-sky-500/30",- correction: "bg-amber-500/15 text-amber-300 border-amber-500/30",- profile: "bg-emerald-500/15 text-emerald-300 border-emerald-500/30",+ fact: "bg-sky-500/15 text-sky-500 border-sky-500/30",+ correction: "bg-amber-500/15 text-amber-500 border-amber-500/30",+ profile: "bg-emerald-500/15 text-emerald-500 border-emerald-500/30",};const HISTORY_STATUSES = new Set<StandingFact["status"]>(["superseded", "retired", "declined"]);@@ -117,7 +119,7 @@ export default function CorrectionsTab({ onCount }: { onCount: (n: number) => vo}}, []);- if (loading) return <div className="text-fg-muted text-sm">Loading…</div>;+ if (loading) return <div className="text-fg-muted text-[15px] py-4">Loading…</div>;if (failed) return <EmptyState message="Corrections are unavailable right now." />;const proposed = facts.filter((f) => f.status === "proposed");@@ -126,17 +128,17 @@ export default function CorrectionsTab({ onCount }: { onCount: (n: number) => voconst byId = new Map(facts.map((f) => [f.id, f]));return (- <div className="space-y-3">+ <div className="space-y-3 py-3">{facts.length === 0 ? (<EmptyState message={EMPTY} />) : (- <p className="text-xs text-fg-muted">+ <p className="text-sm text-fg-muted">These hold in every conversation, brief, scheduled run and alert review.</p>)}{proposed.length > 0 && (- <div className="rounded border border-amber-500/30 bg-amber-500/5 px-3">- <div className="pt-2 text-xs font-medium text-amber-300">+ <div className="rounded-xl border border-amber-500/30 bg-amber-500/5 px-4">+ <div className="pt-3 text-sm font-semibold text-amber-500">{canReview ? "Waiting for your approval" : "Waiting for the owner's approval"}</div><div className="divide-y divide-line">@@ -154,7 +156,7 @@ export default function CorrectionsTab({ onCount }: { onCount: (n: number) => vo)}{facts.length > 0 &&(active.length === 0 ? (- <div className="text-sm text-fg-muted py-4">Nothing active — every correction has been replaced or retired.</div>+ <div className="text-[15px] text-fg-muted py-4">Nothing active — every correction has been replaced or retired.</div>) : (<div className="divide-y divide-line">{active.map((f) => (@@ -170,7 +172,7 @@ export default function CorrectionsTab({ onCount }: { onCount: (n: number) => vo<div><buttononClick={() => setShowHistory((v) => !v)}- className="text-xs text-fg-muted hover:text-fg"+ className="h-10 text-sm font-medium text-accent hover:underline">{showHistory ? "Hide" : "Show"} history ({history.length})</button>@@ -185,8 +187,8 @@ export default function CorrectionsTab({ onCount }: { onCount: (n: number) => vo)}{canReview && rules.length > 0 && (<div className="border-t border-line pt-3">- <div className="text-xs font-medium text-fg">Teammates' corrections</div>- <p className="text-xs text-fg-muted mb-2">+ <div className="text-base font-semibold text-fg">Teammates' corrections</div>+ <p className="text-sm text-fg-muted mb-2">Teammates can correct facts too; theirs are marked with their name and wait for yourapproval. Untick “needs my approval” to trust a teammate's corrections straightaway (one that would replace yours still waits).@@ -194,14 +196,15 @@ export default function CorrectionsTab({ onCount }: { onCount: (n: number) => vo<ul className="space-y-1">{rules.map((r) => (<li key={r.person_id}>- <label className="flex items-center gap-2 text-sm text-fg cursor-pointer">+ <label className="flex items-center gap-3 min-h-10 text-[15px] text-fg cursor-pointer"><inputtype="checkbox"+ className="h-5 w-5 accent-[rgb(var(--accent-strong))]"checked={r.needs_approval}onChange={() => void handleRule(r)}/><span>{r.full_name}</span>- <span className="text-xs text-fg-muted">— needs my approval</span>+ <span className="text-sm text-fg-muted">— needs my approval</span></label></li>))}@@ -228,9 +231,9 @@ function FactRow({replaces?: StandingFact;}) {return (- <div className="group py-3 hover:bg-surface-overlay/30 transition-colors">+ <div className="py-3.5"><div className="flex items-start justify-between gap-3 mb-1.5">- <div className="flex flex-wrap items-center gap-2 text-xs text-fg-muted min-w-0">+ <div className="flex flex-wrap items-center gap-2 text-sm text-fg-muted min-w-0 pt-1.5"><span className={`px-2 py-0.5 rounded border font-medium ${KIND_PILL[fact.kind]}`}>{KIND_LABEL[fact.kind]}</span>@@ -241,54 +244,56 @@ function FactRow({)}</div>{(onApprove || onDecline) && (- <div className="shrink-0 flex gap-3 text-xs">+ <div className="shrink-0 flex gap-2">{onApprove && (- <button onClick={onApprove} className="text-emerald-400 hover:text-emerald-300">+ <Button variant="primary" size="sm" className="!h-10" onClick={onApprove}>Approve- </button>+ </Button>)}{onDecline && (- <button onClick={onDecline} className="text-red-400 hover:text-red-300">+ <Button variant="danger" size="sm" className="!h-10" onClick={onDecline}>Decline- </button>+ </Button>)}</div>)}{onRetire && (- <button- onClick={onRetire}- className="shrink-0 text-xs text-red-400 hover:text-red-300 opacity-0 group-hover:opacity-100 focus:opacity-100 transition-opacity"- >- Retire- </button>+ <OverflowMenu+ size="sm"+ label="Correction actions"+ items={[{ label: "Retire (stop using it)", danger: true, onSelect: onRetire }]}+ />)}{fact.kind === "profile" && fact.status === "active" && (- <Link href="/company-profile" className="shrink-0 text-xs text-fg-muted hover:text-fg">+ <Link+ href="/company-profile"+ className="shrink-0 h-9 inline-flex items-center text-sm font-medium text-accent hover:underline"+ >Company profile</Link>)}</div>- <div className="text-sm text-fg">{fact.statement}</div>+ <div className="text-[15px] text-fg">{fact.statement}</div>{fact.previous_statement && (- <div className="text-xs text-fg-muted mt-0.5">+ <div className="text-sm text-fg-muted mt-0.5"><span className="line-through">{fact.previous_statement}</span></div>)}{fact.source_quote && (- <div className="text-xs text-fg-subtle italic mt-1 line-clamp-2" title={fact.source_quote}>+ <div className="text-sm text-fg-subtle italic mt-1 line-clamp-2" title={fact.source_quote}>“{fact.source_quote}”</div>)}{fact.status === "proposed" && replaces && (- <div className="text-xs text-fg-subtle mt-1">Would replace: {replaces.statement}</div>+ <div className="text-sm text-fg-subtle mt-1">Would replace: {replaces.statement}</div>)}{fact.status === "superseded" && (- <div className="text-xs text-fg-subtle mt-1">+ <div className="text-sm text-fg-subtle mt-1">Replaced{replacedBy ? ` by: ${replacedBy.statement}` : ""}</div>)}{(fact.status === "retired" || fact.status === "declined") && (- <div className="text-xs text-fg-subtle mt-1">+ <div className="text-sm text-fg-subtle mt-1">{fact.status === "declined" ? "Declined" : "Retired"} {fact.retired_at ? formatDate(fact.retired_at) : ""}{fact.retired_reason ? ` — ${fact.retired_reason}` : ""}</div>diff --git a/packages/ui/src/components/memories/MemorySection.tsx b/packages/ui/src/components/memories/MemorySection.tsxindex 475bc79a..150f8af7 100644--- a/packages/ui/src/components/memories/MemorySection.tsx+++ b/packages/ui/src/components/memories/MemorySection.tsx@@ -20,12 +20,15 @@ import {type PersonConclusion,type PersonMemory,} from "@/lib/api";+import Button from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";+import SectionTabs from "@/components/ui/SectionTabs";import CorrectionsTab from "./CorrectionsTab";import { DOMAINS, STATUSES, EmptyState, formatDate } from "./shared";type MemoryTab = "decisions" | "initiatives" | "advice" | "corrections" | "people";-const MEMORY_TABS: readonly MemoryTab[] = ["decisions", "initiatives", "advice", "corrections", "people"];+export const MEMORY_TABS: readonly MemoryTab[] = ["decisions", "initiatives", "advice", "corrections", "people"];const MEMORY_EMPTY = "No memories yet — they're extracted automatically after chats.";const PEOPLE_EMPTY =@@ -92,33 +95,21 @@ export default function MemorySection() {: [...MEMORY_TABS];return (- <div className="rounded-xl border border-line bg-surface-elevated p-4">- <div className="mb-3">- <div className="flex flex-wrap gap-1 p-1 bg-surface-overlay/60 rounded-xl w-fit max-w-full border border-line-strong/50">- {tabs.map((t) => (- <button- key={t}- onClick={() => setTab(t)}- className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors capitalize ${- tab === t- ? "bg-surface-input text-fg shadow-sm"- : "text-fg-muted hover:text-fg"- }`}- >- {t}- {counts[t] != null && (- <span className="ml-1.5 text-xs font-normal tabular-nums text-fg-subtle">- {counts[t]}- </span>- )}- </button>- ))}- </div>- </div>-- {/* One scroll region shared by all (always-mounted) tabs, mirroring- the Recent activity card — the list scrolls instead of growing. */}- <div className="max-h-[32rem] overflow-y-auto pr-1">+ <div>+ <SectionTabs+ label="Memory"+ className="mb-4"+ active={tab}+ onChange={setTab}+ tabs={tabs.map((t) => ({+ id: t,+ label: t.charAt(0).toUpperCase() + t.slice(1),+ badge: counts[t],+ }))}+ />++ {/* All tabs stay mounted (inactive ones hidden) so every count loads. */}+ <div className="rounded-2xl border border-line bg-surface-elevated px-4 sm:px-5 py-1"><div className={tab === "decisions" ? "" : "hidden"}><DecisionsTab onCount={onCountDecisions} /></div>@@ -174,7 +165,7 @@ function DecisionsTab({ onCount }: { onCount: (n: number) => void }) {void refresh();}, [refresh]);- if (loading) return <div className="text-fg-muted text-sm">Loading…</div>;+ if (loading) return <div className="text-fg-muted text-[15px] py-4">Loading…</div>;if (items.length === 0) return <EmptyState message={MEMORY_EMPTY} />;return (@@ -235,17 +226,21 @@ function DecisionRow({}, [editing, decision]);return (- <div className="group py-3 hover:bg-surface-overlay/30 transition-colors">- <div className="flex items-start justify-between gap-3 mb-2">- <div className="flex items-center gap-2 text-xs text-fg-muted">- <span className="px-2 py-0.5 rounded bg-surface-overlay text-fg font-medium">{editing ? domain : decision.domain}</span>+ <div className="py-3.5">+ <div className="flex items-center justify-between gap-3 mb-1">+ <div className="flex items-center gap-2 text-sm text-fg-muted">+ <span className="px-2 py-0.5 rounded-lg bg-surface-overlay text-fg font-medium capitalize">{editing ? domain : decision.domain}</span><span>{formatDate(decision.timestamp)}</span></div>{!editing && (- <div className="flex gap-2 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity">- <button onClick={onEdit} className="text-xs text-fg-muted hover:text-fg">Edit</button>- <button onClick={onDelete} className="text-xs text-red-400 hover:text-red-300">Delete</button>- </div>+ <OverflowMenu+ size="sm"+ label="Memory actions"+ items={[+ { label: "Edit", onSelect: onEdit },+ { label: "Delete", danger: true, onSelect: onDelete },+ ]}+ />)}</div>{editing ? (@@ -253,7 +248,7 @@ function DecisionRow({<selectvalue={domain}onChange={(e) => setDomain(e.target.value)}- className="w-full bg-surface border border-line rounded px-2 py-1.5 text-sm text-fg"+ className="w-full bg-surface border border-line rounded-xl px-3 py-2.5 text-[15px] text-fg focus:outline-none focus:ring-2 focus:ring-accent/40">{DOMAINS.map((d) => <option key={d} value={d}>{d}</option>)}</select>@@ -262,45 +257,42 @@ function DecisionRow({value={summary}onChange={(e) => setSummary(e.target.value)}placeholder="Summary"- className="w-full bg-surface border border-line rounded px-2 py-1.5 text-sm text-fg"+ className="w-full bg-surface border border-line rounded-xl px-3 py-2.5 text-[15px] text-fg focus:outline-none focus:ring-2 focus:ring-accent/40"/><textareavalue={rationale}onChange={(e) => setRationale(e.target.value)}placeholder="Rationale"rows={2}- className="w-full bg-surface border border-line rounded px-2 py-1.5 text-sm text-fg"+ className="w-full bg-surface border border-line rounded-xl px-3 py-2.5 text-[15px] text-fg focus:outline-none focus:ring-2 focus:ring-accent/40"/><inputtype="text"value={outcome}onChange={(e) => setOutcome(e.target.value)}placeholder="Outcome"- className="w-full bg-surface border border-line rounded px-2 py-1.5 text-sm text-fg"+ className="w-full bg-surface border border-line rounded-xl px-3 py-2.5 text-[15px] text-fg focus:outline-none focus:ring-2 focus:ring-accent/40"/><inputtype="text"value={tags}onChange={(e) => setTags(e.target.value)}placeholder="Tags"- className="w-full bg-surface border border-line rounded px-2 py-1.5 text-sm text-fg"+ className="w-full bg-surface border border-line rounded-xl px-3 py-2.5 text-[15px] text-fg focus:outline-none focus:ring-2 focus:ring-accent/40"/><div className="flex gap-2 justify-end">- <button onClick={onCancel} className="text-xs px-3 py-1.5 rounded text-fg-muted hover:text-fg">Cancel</button>- <button- onClick={() => onSave({ domain, summary, rationale, outcome, tags })}- className="text-xs px-3 py-1.5 rounded bg-indigo-600 hover:bg-indigo-500 text-white"- >+ <Button variant="ghost" size="sm" className="!h-10" onClick={onCancel}>Cancel</Button>+ <Button variant="primary" size="sm" className="!h-10" onClick={() => onSave({ domain, summary, rationale, outcome, tags })}>Save- </button>+ </Button></div></div>) : (<div className="space-y-1">- <div className="text-sm text-fg line-clamp-2" title={decision.summary}>{decision.summary}</div>- {decision.rationale && <div className="text-xs text-fg-muted line-clamp-2" title={`Rationale: ${decision.rationale}`}><span className="text-fg-muted">Rationale: </span>{decision.rationale}</div>}- {decision.outcome && <div className="text-xs text-fg-muted line-clamp-2" title={`Outcome: ${decision.outcome}`}><span className="text-fg-muted">Outcome: </span>{decision.outcome}</div>}- {decision.tags && <div className="text-xs text-fg-muted truncate" title={`Tags: ${decision.tags}`}>Tags: {decision.tags}</div>}+ <div className="text-[15px] font-medium text-fg line-clamp-2" title={decision.summary}>{decision.summary}</div>+ {decision.rationale && <div className="text-sm text-fg-muted line-clamp-2" title={`Rationale: ${decision.rationale}`}><span className="text-fg-muted">Rationale: </span>{decision.rationale}</div>}+ {decision.outcome && <div className="text-sm text-fg-muted line-clamp-2" title={`Outcome: ${decision.outcome}`}><span className="text-fg-muted">Outcome: </span>{decision.outcome}</div>}+ {decision.tags && <div className="text-sm text-fg-subtle truncate" title={`Tags: ${decision.tags}`}>Tags: {decision.tags}</div>}</div>)}</div>@@ -342,7 +334,7 @@ function InitiativesTab({ onCount }: { onCount: (n: number) => void }) {void refresh();}, [refresh]);- if (loading) return <div className="text-fg-muted text-sm">Loading…</div>;+ if (loading) return <div className="text-fg-muted text-[15px] py-4">Loading…</div>;if (items.length === 0) return <EmptyState message={MEMORY_EMPTY} />;return (@@ -399,17 +391,21 @@ function InitiativeRow({}, [editing, initiative]);return (- <div className="group py-3 hover:bg-surface-overlay/30 transition-colors">- <div className="flex items-start justify-between gap-3 mb-2">- <div className="flex items-center gap-2 text-xs text-fg-muted">- <span className="px-2 py-0.5 rounded bg-surface-overlay text-fg font-medium capitalize">{editing ? status : initiative.status}</span>+ <div className="py-3.5">+ <div className="flex items-center justify-between gap-3 mb-1">+ <div className="flex items-center gap-2 text-sm text-fg-muted">+ <span className="px-2 py-0.5 rounded-lg bg-surface-overlay text-fg font-medium capitalize">{editing ? status : initiative.status}</span><span>updated {formatDate(initiative.updated_at)}</span></div>{!editing && (- <div className="flex gap-2 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity">- <button onClick={onEdit} className="text-xs text-fg-muted hover:text-fg">Edit</button>- <button onClick={onDelete} className="text-xs text-red-400 hover:text-red-300">Delete</button>- </div>+ <OverflowMenu+ size="sm"+ label="Memory actions"+ items={[+ { label: "Edit", onSelect: onEdit },+ { label: "Delete", danger: true, onSelect: onDelete },+ ]}+ />)}</div>{editing ? (@@ -419,12 +415,12 @@ function InitiativeRow({value={title}onChange={(e) => setTitle(e.target.value)}placeholder="Title"- className="w-full bg-surface border border-line rounded px-2 py-1.5 text-sm text-fg"+ className="w-full bg-surface border border-line rounded-xl px-3 py-2.5 text-[15px] text-fg focus:outline-none focus:ring-2 focus:ring-accent/40"/><selectvalue={status}onChange={(e) => setStatus(e.target.value)}- className="w-full bg-surface border border-line rounded px-2 py-1.5 text-sm text-fg"+ className="w-full bg-surface border border-line rounded-xl px-3 py-2.5 text-[15px] text-fg focus:outline-none focus:ring-2 focus:ring-accent/40">{STATUSES.map((s) => <option key={s} value={s}>{s}</option>)}</select>@@ -433,22 +429,19 @@ function InitiativeRow({onChange={(e) => setSummary(e.target.value)}placeholder="Summary"rows={2}- className="w-full bg-surface border border-line rounded px-2 py-1.5 text-sm text-fg"+ className="w-full bg-surface border border-line rounded-xl px-3 py-2.5 text-[15px] text-fg focus:outline-none focus:ring-2 focus:ring-accent/40"/><div className="flex gap-2 justify-end">- <button onClick={onCancel} className="text-xs px-3 py-1.5 rounded text-fg-muted hover:text-fg">Cancel</button>- <button- onClick={() => onSave({ title, status, summary })}- className="text-xs px-3 py-1.5 rounded bg-indigo-600 hover:bg-indigo-500 text-white"- >+ <Button variant="ghost" size="sm" className="!h-10" onClick={onCancel}>Cancel</Button>+ <Button variant="primary" size="sm" className="!h-10" onClick={() => onSave({ title, status, summary })}>Save- </button>+ </Button></div></div>) : (<div className="space-y-1">- <div className="text-sm text-fg font-medium line-clamp-2" title={initiative.title}>{initiative.title}</div>- {initiative.summary && <div className="text-xs text-fg-muted line-clamp-2" title={initiative.summary}>{initiative.summary}</div>}+ <div className="text-[15px] text-fg font-semibold line-clamp-2" title={initiative.title}>{initiative.title}</div>+ {initiative.summary && <div className="text-sm text-fg-muted line-clamp-2" title={initiative.summary}>{initiative.summary}</div>}</div>)}</div>@@ -490,7 +483,7 @@ function AdviceTab({ onCount }: { onCount: (n: number) => void }) {void refresh();}, [refresh]);- if (loading) return <div className="text-fg-muted text-sm">Loading…</div>;+ if (loading) return <div className="text-fg-muted text-[15px] py-4">Loading…</div>;if (items.length === 0) return <EmptyState message={MEMORY_EMPTY} />;return (@@ -547,17 +540,21 @@ function AdviceRow({}, [editing, advice]);return (- <div className="group py-3 hover:bg-surface-overlay/30 transition-colors">- <div className="flex items-start justify-between gap-3 mb-2">- <div className="flex items-center gap-2 text-xs text-fg-muted">- <span className="px-2 py-0.5 rounded bg-surface-overlay text-fg font-medium">{editing ? domain : advice.domain}</span>+ <div className="py-3.5">+ <div className="flex items-center justify-between gap-3 mb-1">+ <div className="flex items-center gap-2 text-sm text-fg-muted">+ <span className="px-2 py-0.5 rounded-lg bg-surface-overlay text-fg font-medium capitalize">{editing ? domain : advice.domain}</span><span>{formatDate(advice.timestamp)}</span></div>{!editing && (- <div className="flex gap-2 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity">- <button onClick={onEdit} className="text-xs text-fg-muted hover:text-fg">Edit</button>- <button onClick={onDelete} className="text-xs text-red-400 hover:text-red-300">Delete</button>- </div>+ <OverflowMenu+ size="sm"+ label="Memory actions"+ items={[+ { label: "Edit", onSelect: onEdit },+ { label: "Delete", danger: true, onSelect: onDelete },+ ]}+ />)}</div>{editing ? (@@ -565,7 +562,7 @@ function AdviceRow({<selectvalue={domain}onChange={(e) => setDomain(e.target.value)}- className="w-full bg-surface border border-line rounded px-2 py-1.5 text-sm text-fg"+ className="w-full bg-surface border border-line rounded-xl px-3 py-2.5 text-[15px] text-fg focus:outline-none focus:ring-2 focus:ring-accent/40">{DOMAINS.map((d) => <option key={d} value={d}>{d}</option>)}</select>@@ -574,29 +571,26 @@ function AdviceRow({value={querySummary}onChange={(e) => setQuerySummary(e.target.value)}placeholder="What the user asked"- className="w-full bg-surface border border-line rounded px-2 py-1.5 text-sm text-fg"+ className="w-full bg-surface border border-line rounded-xl px-3 py-2.5 text-[15px] text-fg focus:outline-none focus:ring-2 focus:ring-accent/40"/><textareavalue={adviceSummary}onChange={(e) => setAdviceSummary(e.target.value)}placeholder="Advice given"rows={3}- className="w-full bg-surface border border-line rounded px-2 py-1.5 text-sm text-fg"+ className="w-full bg-surface border border-line rounded-xl px-3 py-2.5 text-[15px] text-fg focus:outline-none focus:ring-2 focus:ring-accent/40"/><div className="flex gap-2 justify-end">- <button onClick={onCancel} className="text-xs px-3 py-1.5 rounded text-fg-muted hover:text-fg">Cancel</button>- <button- onClick={() => onSave({ domain, query_summary: querySummary, advice_summary: adviceSummary })}- className="text-xs px-3 py-1.5 rounded bg-indigo-600 hover:bg-indigo-500 text-white"- >+ <Button variant="ghost" size="sm" className="!h-10" onClick={onCancel}>Cancel</Button>+ <Button variant="primary" size="sm" className="!h-10" onClick={() => onSave({ domain, query_summary: querySummary, advice_summary: adviceSummary })}>Save- </button>+ </Button></div></div>) : (<div className="space-y-1">- <div className="text-xs text-fg-muted line-clamp-2" title={`Q: ${advice.query_summary}`}>Q: {advice.query_summary}</div>- <div className="text-sm text-fg line-clamp-2" title={advice.advice_summary}>{advice.advice_summary}</div>+ <div className="text-sm text-fg-muted line-clamp-2" title={`Q: ${advice.query_summary}`}>Q: {advice.query_summary}</div>+ <div className="text-[15px] text-fg line-clamp-2" title={advice.advice_summary}>{advice.advice_summary}</div></div>)}</div>@@ -645,7 +639,7 @@ function PeopleTab({void refresh();}, [refresh]);- if (loading) return <div className="text-fg-muted text-sm">Loading…</div>;+ if (loading) return <div className="text-fg-muted text-[15px] py-4">Loading…</div>;if (failed || !data || data.status === "error") {return <div className="text-fg-muted text-sm">{PEOPLE_UNAVAILABLE}</div>;}@@ -653,7 +647,7 @@ function PeopleTab({if (data.people.length === 0) return <EmptyState message={PEOPLE_EMPTY} />;return (- <div className="space-y-3">+ <div className="space-y-3 py-3">{data.people.map((p) => (<PersonMemoryRow key={p.person_id} item={p} />))}@@ -673,12 +667,12 @@ function PersonMemoryRow({ item }: { item: PersonMemory }) {const learned = item.last_observed_at ? ` · learned ${formatDate(item.last_observed_at)}` : "";const nothingYet = !item.error && item.conclusion_count === 0 && item.card.length === 0;return (- <div className="rounded-lg border border-line bg-surface-overlay/30 p-4">+ <div className="rounded-xl border border-line bg-surface-overlay/30 p-4"><div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1"><div className="flex items-center gap-2 min-w-0">- <span className="text-sm font-semibold text-fg truncate">{item.full_name}</span>+ <span className="text-base font-semibold text-fg truncate">{item.full_name}</span>{item.is_principal && (- <span className="inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium bg-violet-500/20 text-violet-300 border-violet-500/30">+ <span className="inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium bg-violet-500/15 text-violet-500 border-violet-500/30">Principal</span>)}@@ -703,13 +697,13 @@ function PersonCard({ lines }: { lines: string[] }) {return (<div className="mt-3"><div className="text-[10px] uppercase tracking-wide text-fg-subtle mb-1">Profile</div>- <ul className="space-y-0.5 text-xs text-fg-muted list-disc pl-4 marker:text-fg-subtle">+ <ul className="space-y-0.5 text-sm text-fg-muted list-disc pl-4 marker:text-fg-subtle">{shown.map((line, i) => (<li key={i} className="break-words">{line}</li>))}</ul>{hidden > 0 && (- <button onClick={() => setOpen((o) => !o)} className="mt-1 text-xs text-fg-muted hover:text-fg">+ <button onClick={() => setOpen((o) => !o)} className="mt-1 h-9 text-sm font-medium text-accent hover:underline">{open ? "Show less" : `Show ${hidden} more`}</button>)}@@ -789,7 +783,7 @@ function PersonNotes({ item }: { item: PersonMemory }) {))}</ul>{(loading || failed || (hasMore && nextPage === null)) && (- <div className="px-3 py-2 text-xs text-fg-muted border-t border-line/60">+ <div className="px-3 py-2 text-sm text-fg-muted border-t border-line/60">{loading ? ("Loading…") : failed ? (diff --git a/packages/ui/src/components/memories/PulseHeader.tsx b/packages/ui/src/components/memories/PulseHeader.tsxindex bbd55ba5..988257e7 100644--- a/packages/ui/src/components/memories/PulseHeader.tsx+++ b/packages/ui/src/components/memories/PulseHeader.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useMemo, useState } from "react";+import { useEffect, useId, useMemo, useState } from "react";import {getActivityDaily,listAdvice,@@ -12,9 +12,11 @@ import {type ScheduledAction,type WorkspaceMode,} from "@/lib/api";+import Icon from "@/components/Icon";import { useWorkspace } from "@/components/workspace/WorkspaceContext";import {deriveVitals,+ formatNextBeat,formatTrend,formatVitalDate,type TrendDirection,@@ -24,22 +26,22 @@ import {STAT_VALUE_TONE,Skeleton,StatTile,- formatRunAt,groupByRhythm,metaFor,type StatTone,} from "./shared";-// The Pulse header is the page's at-a-glance band: a strip of headline metrics-// plus the "heartbeat" — a GitHub-contributions-style heatmap of the-// Executive's self-initiated activity over the last 90 days, with a vitals-// panel (streaks, totals, trend) derived from the same counts. Every metric is-// derived from data the page already needs (pending scheduled actions + the-// three memory lists); only the per-day heatmap requires its own endpoint,-// since /today/activity returns the last-N items, not a daily timeline. Peer-// memory is optional and remote, so it is fetched apart from the gating-// batch: the strip renders from local data and the tile folds the peer notes-// in when (and only if) they arrive.+// The Pulse page's at-a-glance numbers and its "heartbeat" — a+// GitHub-contributions-style heatmap of the Executive's self-initiated+// activity over the last 90 days. Up front sit three headline numbers (beats+// today, next beat, memories); the rest (rhythm counts and the vitals derived+// from the heatmap: streaks, totals, trend) sit under "More stats". Every+// metric is derived from data the page already needs (pending scheduled+// actions + the three memory lists); only the per-day heatmap requires its own+// endpoint, since /today/activity returns the last-N items, not a daily+// timeline. Peer memory is optional and remote, so it is fetched apart from+// the gating batch: the numbers render from local data and the Memories tile+// folds the peer notes in when (and only if) they arrive.const HEATMAP_DAYS = 90;@@ -51,7 +53,15 @@ interface HeaderData {heatmap: DailyActivityCount[];}-export default function PulseHeader() {+export interface PulseData {+ data: HeaderData | null;+ loading: boolean;+ /** Headline numbers first, then the ones under "More stats". */+ stats: { headline: Stat[]; more: Stat[] } | null;+}++/** Loads everything the Pulse numbers and heatmap need, once per page. */+export function usePulseData(): PulseData {const { mode } = useWorkspace();const [data, setData] = useState<HeaderData | null>(null);const [loading, setLoading] = useState(true);@@ -111,62 +121,94 @@ export default function PulseHeader() {() => (data ? deriveStats(data, peerNotes, mode) : null),[data, peerNotes, mode],);+ return { data, loading, stats };+}- return (- <header className="space-y-6">- <div>- <h1 className="text-2xl font-semibold text-fg">Pulse</h1>- <p className="text-sm text-fg-muted mt-1 max-w-2xl">- What the Executive knows, and the rhythm it runs on — the briefs,- reflections, and check-ins that fire on their own while you're away.- </p>- </div>+/** The three headline numbers, with the rest folded under "More stats". */+export function PulseSummary({ pulse }: { pulse: PulseData }) {+ const { data, loading, stats } = pulse;+ const [open, setOpen] = useState(false);+ const moreId = useId();- {/* Stat strip */}- <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">+ return (+ <section aria-label="At a glance" className="space-y-3">+ <div className="grid grid-cols-3 gap-2 sm:gap-4">{loading || !stats- ? Array.from({ length: 6 }).map((_, i) => (- <div key={i} className="rounded-xl border border-line bg-surface-elevated px-4 py-3">- <Skeleton className="h-3 w-16" />- <Skeleton className="h-7 w-10 mt-2" />+ ? Array.from({ length: 3 }).map((_, i) => (+ <div key={i} className="rounded-2xl border border-line bg-surface-elevated px-4 py-4 sm:px-5">+ <Skeleton className="h-4 w-20" />+ <Skeleton className="h-8 w-12 mt-2" /></div>))- : stats.map((s) => (- <StatTile- key={s.label}- label={s.label}- value={s.value}- hint={s.hint}- tone={s.tone}- />+ : stats.headline.map((s) => (+ <StatTile key={s.label} label={s.label} value={s.value} hint={s.hint} tone={s.tone} />))}</div>- {/* Heartbeat heatmap */}- <section className="rounded-xl border border-line bg-surface-elevated p-4">- <div className="flex items-center justify-between gap-3 mb-3">- <div className="flex items-center gap-2">- <h2 className="text-sm font-semibold text-fg">Heartbeat</h2>- <span className="text-xs text-fg-subtle">last {HEATMAP_DAYS} days</span>- </div>- <LivePulse />- </div>- {/* The heatmap is fixed-width (~14 week columns), so the vitals panel- takes the rest of the row on md+ and stacks beneath it below. */}- <div className="flex flex-col md:flex-row gap-6">- <div className="shrink-0 min-w-0">- {loading || !data ? (- <Skeleton className="h-32 w-56" />- ) : (- <Heatmap days={data.heatmap} />- )}+ <button+ type="button"+ onClick={() => setOpen((o) => !o)}+ aria-expanded={open}+ aria-controls={moreId}+ className="inline-flex h-10 items-center gap-1.5 rounded-xl px-2 text-sm font-medium text-fg-muted hover:text-fg hover:bg-surface-overlay transition-colors"+ >+ <Icon+ name="chevron-right"+ size="w-4 h-4"+ className={`transition-transform ${open ? "rotate-90" : ""}`}+ />+ {open ? "Fewer stats" : "More stats"}+ </button>++ {open && (+ <div id={moreId} className="rounded-2xl border border-line bg-surface-elevated p-4 sm:p-5 space-y-5">+ <div className={VITALS_GRID}>+ {loading || !stats+ ? Array.from({ length: 3 }).map((_, i) => <VitalSkeleton key={i} />)+ : stats.more.map((s) => (+ <Vital key={s.label} label={s.label} value={String(s.value)} hint={s.hint} tone={s.tone} />+ ))}</div>- <div className="flex-1 min-w-0 md:border-l md:border-line md:pl-6">+ <div className="border-t border-line pt-5">+ <h3 className="text-sm font-semibold text-fg mb-3">+ Heartbeat, last {HEATMAP_DAYS} days+ </h3>{loading || !data ? <VitalsSkeleton /> : <Vitals days={data.heatmap} />}</div></div>- </section>- </header>+ )}+ </section>+ );+}++/** The heatmap card at the top of the Heartbeat tab. */+export function HeartbeatCard({ pulse }: { pulse: PulseData }) {+ const { data, loading } = pulse;+ const vitals = useMemo(() => (data ? deriveVitals(data.heatmap) : null), [data]);+ return (+ <section className="rounded-2xl border border-line bg-surface-elevated p-4 sm:p-5">+ <div className="flex items-center justify-between gap-3 mb-4">+ <div className="flex items-baseline gap-2 flex-wrap">+ <h2 className="text-base font-semibold text-fg">Heartbeat</h2>+ <span className="text-sm text-fg-subtle">last {HEATMAP_DAYS} days</span>+ </div>+ <LivePulse />+ </div>+ <div className="flex flex-col md:flex-row md:items-center gap-5 md:gap-8">+ <div className="shrink-0 min-w-0">+ {loading || !data ? <Skeleton className="h-32 w-60" /> : <Heatmap days={data.heatmap} />}+ </div>+ {vitals && data && (+ <p className="text-[15px] text-fg-muted leading-relaxed">+ <span className="text-fg font-semibold">{plural(vitals.total, "beat")}</span> on{" "}+ {vitals.activeDays} of {data.heatmap.length} days.+ <br />+ Current streak:{" "}+ <span className="text-fg font-semibold">{plural(vitals.currentStreak.days, "day")}</span>+ </p>+ )}+ </div>+ </section>);}@@ -174,7 +216,7 @@ export default function PulseHeader() {// Stat derivation// --------------------------------------------------------------------------- #-interface Stat {+export interface Stat {label: string;value: string | number;hint?: string;@@ -185,45 +227,52 @@ function deriveStats({ pending, memoriesTotal, activeProjects, heatmap }: HeaderData,peerNotes: number | null,mode: WorkspaceMode,-): Stat[] {+): { headline: Stat[]; more: Stat[] } {const groups = groupByRhythm(pending);const followups = pending.filter((a) => a.kind === "ad_hoc").length;- // Soonest pending fire = the literal "next beat".+ // Soonest pending fire = the literal "next beat". One whose time has+ // passed is waiting for the scheduler's next tick, so it reads "Due now".const soonest = pending.reduce<ScheduledAction | null>((best, a) => {if (!best) return a;return a.run_at.localeCompare(best.run_at) < 0 ? a : best;}, null);const nextBeat = soonest- ? { value: formatRunAt(soonest.run_at).relative || "soon", hint: metaFor(soonest).label }+ ? { value: formatNextBeat(soonest.run_at) || "soon", hint: metaFor(soonest).label }: { value: "—", hint: "nothing scheduled" };// The heatmap is oldest → newest, so the last entry is today.const beatsToday = heatmap.length > 0 ? heatmap[heatmap.length - 1].count : 0;- return [- { label: "Beats today", value: beatsToday, tone: "emerald", hint: "actions fired" },- { label: "Next beat", value: nextBeat.value, tone: "accent", hint: nextBeat.hint },- { label: "Daily rhythms", value: groups.daily.length },- // Solo has no department check-ins; the projects it tracks take the slot.- mode === "solo"- ? { label: "Projects", value: activeProjects, hint: "active" }- : { label: "Dept check-ins", value: groups.departments.length },- { label: "Follow-ups", value: followups },- // Three episodic lists plus what peer memory has learned about people;- // the hint says how much of the number is peer notes so it reconciles- // with the tabs (the People tab badge counts people, not notes).- {- label: "Memories",- value: memoriesTotal + (peerNotes ?? 0),- hint:- peerNotes === null- ? undefined- : peerNotes > 0- ? `incl. ${peerNotes} peer notes`- : "no peer notes yet",- },- ];+ // Three episodic lists plus what peer memory has learned about people;+ // the hint says how much of the number is peer notes so it reconciles+ // with the tabs (the People tab badge counts people, not notes).+ const memories: Stat = {+ label: "Memories",+ value: memoriesTotal + (peerNotes ?? 0),+ hint:+ peerNotes === null+ ? undefined+ : peerNotes > 0+ ? `incl. ${peerNotes} peer notes`+ : "no peer notes yet",+ };++ return {+ headline: [+ { label: "Beats today", value: beatsToday, tone: "emerald", hint: "actions fired" },+ { label: "Next beat", value: nextBeat.value, tone: "accent", hint: nextBeat.hint },+ memories,+ ],+ more: [+ { label: "Daily rhythms", value: groups.daily.length },+ // Solo has no department check-ins; the projects it tracks take the slot.+ mode === "solo"+ ? { label: "Projects", value: activeProjects, hint: "active" }+ : { label: "Dept check-ins", value: groups.departments.length },+ { label: "Follow-ups", value: followups },+ ],+ };}// --------------------------------------------------------------------------- #@@ -257,13 +306,11 @@ function Vital({}) {return (<div className="min-w-0">- <div className="text-[11px] font-medium uppercase tracking-wide text-fg-subtle truncate">- {label}- </div>- <div className={`mt-1 text-xl font-semibold tabular-nums truncate ${STAT_VALUE_TONE[tone]}`}>+ <div className="text-sm font-medium text-fg-muted truncate">{label}</div>+ <div className={`mt-1 text-xl font-bold tabular-nums truncate ${STAT_VALUE_TONE[tone]}`}>{value}</div>- {hint && <div className="text-[11px] text-fg-muted mt-0.5 truncate">{hint}</div>}+ {hint && <div className="text-sm text-fg-subtle mt-0.5 truncate">{hint}</div>}</div>);}@@ -313,14 +360,20 @@ function Vitals({ days }: { days: DailyActivityCount[] }) {);}+function VitalSkeleton() {+ return (+ <div>+ <Skeleton className="h-3 w-20" />+ <Skeleton className="h-6 w-14 mt-2" />+ </div>+ );+}+function VitalsSkeleton() {return (<div className={VITALS_GRID}>{Array.from({ length: VITALS_COUNT }).map((_, i) => (- <div key={i}>- <Skeleton className="h-3 w-20" />- <Skeleton className="h-6 w-14 mt-2" />- </div>+ <VitalSkeleton key={i} />))}</div>);@@ -384,11 +437,11 @@ function Heatmap({ days }: { days: DailyActivityCount[] }) {<div key={wi} className="flex flex-col gap-1">{week.map((cell, di) =>cell === null ? (- <div key={di} className="h-3 w-3" />+ <div key={di} className="h-3.5 w-3.5" />) : (<divkey={di}- className={`h-3 w-3 rounded-[3px] ${LEVEL_BG[intensity(cell.count)]}`}+ className={`h-3.5 w-3.5 rounded-[4px] ${LEVEL_BG[intensity(cell.count)]}`}title={`${cell.date}: ${cell.count} ${cell.count === 1 ? "action" : "actions"}`}aria-label={`${cell.date}: ${cell.count} ${cell.count === 1 ? "action" : "actions"}`}/>@@ -399,7 +452,7 @@ function Heatmap({ days }: { days: DailyActivityCount[] }) {</div>{/* Legend */}- <div className="flex items-center justify-end gap-1.5 mt-2 text-[11px] text-fg-subtle">+ <div className="flex items-center justify-end gap-1.5 mt-2 text-xs text-fg-subtle"><span>less</span>{LEVEL_BG.map((bg, i) => (<span key={i} className={`h-3 w-3 rounded-[3px] ${bg}`} aria-hidden="true" />diff --git a/packages/ui/src/components/memories/PulsePage.tsx b/packages/ui/src/components/memories/PulsePage.tsxindex 321719e8..9e66e5ca 100644--- a/packages/ui/src/components/memories/PulsePage.tsx+++ b/packages/ui/src/components/memories/PulsePage.tsx@@ -1,8 +1,12 @@"use client";-import CadenceSection, { FollowUpsCard } from "./CadenceSection";-import MemorySection from "./MemorySection";-import PulseHeader from "./PulseHeader";+import { useState } from "react";+import { useSearchParams } from "next/navigation";++import SectionTabs from "@/components/ui/SectionTabs";+import RhythmSection, { FollowUpsCard, RecentActivity } from "./CadenceSection";+import MemorySection, { MEMORY_TABS } from "./MemorySection";+import { HeartbeatCard, PulseSummary, usePulseData } from "./PulseHeader";// The Pulse page is the Executive's memory + heartbeat: what it knows// (durable episodic memory) and the rhythm it runs on (recurring briefs,@@ -10,35 +14,75 @@ import PulseHeader from "./PulseHeader";// built from data that already exists — episodic memory rows and the// scheduled_actions queue grouped by `kind`.//-// Layout: an at-a-glance header (stat strip + heartbeat heatmap) spans the-// full width, then Cadence ("Heartbeat") and Memory ("What it knows") sit-// side by side on wide screens and stack on smaller ones.+// Layout: three headline numbers (the rest under "More stats"), then two+// tabs. Heartbeat holds the heatmap and Activity · Rhythm · Follow-ups;+// Memory holds what it knows (decisions, initiatives, advice, corrections,+// people).++type PulseTab = "heartbeat" | "memory";+type BeatView = "activity" | "rhythm" | "followups";export default function PulsePage() {+ const pulse = usePulseData();+ // `/memories?tab=corrections` (the chat chip after remember_fact) and the+ // other memory tab names open the Memory tab; MemorySection picks the+ // inner tab from the same parameter.+ const wanted = useSearchParams().get("tab");+ const [tab, setTab] = useState<PulseTab>(() =>+ wanted === "memory" || (MEMORY_TABS as readonly string[]).includes(wanted ?? "")+ ? "memory"+ : "heartbeat",+ );+ const [beatView, setBeatView] = useState<BeatView>("activity");++ const pending = pulse.data?.pending;+ const followups = pending ? pending.filter((a) => a.kind === "ad_hoc").length : null;+return (- <div className="max-w-6xl mx-auto px-4 sm:px-6 py-8 space-y-10">- <PulseHeader />-- {/* `min-w-0` on each grid child: fr tracks default to min-width:auto, so- a long unbreakable line (e.g. an activity summary) would otherwise- force the track — and the whole page — wider than the viewport. */}- <div className="grid gap-8 xl:grid-cols-[1.05fr_0.95fr]">- <section className="min-w-0">- <h2 className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-fg-subtle mb-4">- Heartbeat — the rhythm it runs on- </h2>- <CadenceSection />- </section>-- <section className="min-w-0 space-y-8">- <div>- <h2 className="text-xs font-semibold uppercase tracking-wide text-fg-subtle mb-4">- Memory — what it knows- </h2>- <MemorySection />- </div>- <FollowUpsCard />- </section>+ <div className="max-w-5xl mx-auto px-4 sm:px-6 py-6 sm:py-8 space-y-6">+ <header>+ <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg">Pulse</h1>+ <p className="text-[15px] text-fg-muted mt-1.5 max-w-2xl">+ What the Executive knows, and the rhythm it runs on — the briefs,+ reflections, and check-ins that fire on their own while you're away.+ </p>+ </header>++ <PulseSummary pulse={pulse} />++ <SectionTabs+ label="Pulse"+ active={tab}+ onChange={setTab}+ tabs={[+ { id: "heartbeat", label: "Heartbeat" },+ { id: "memory", label: "Memory" },+ ]}+ />++ {tab === "heartbeat" && (+ <div className="space-y-5">+ <HeartbeatCard pulse={pulse} />+ <SectionTabs+ label="Heartbeat"+ active={beatView}+ onChange={setBeatView}+ tabs={[+ { id: "activity", label: "Activity" },+ { id: "rhythm", label: "Rhythm" },+ { id: "followups", label: "Follow-ups", badge: followups },+ ]}+ />+ {beatView === "activity" && <RecentActivity />}+ {beatView === "rhythm" && <RhythmSection />}+ {beatView === "followups" && <FollowUpsCard />}+ </div>+ )}++ {/* Kept mounted while hidden so its tab counts load once and its+ `?tab=` deep link is read on first render. */}+ <div className={tab === "memory" ? "" : "hidden"}>+ <MemorySection /></div></div>);diff --git a/packages/ui/src/components/memories/shared.tsx b/packages/ui/src/components/memories/shared.tsxindex 48dceb52..84564bdc 100644--- a/packages/ui/src/components/memories/shared.tsx+++ b/packages/ui/src/components/memories/shared.tsx@@ -46,16 +46,16 @@ export function formatRunAt(iso: string): { absolute: string; relative: string }}export const STATUS_PILL: Record<string, string> = {- pending: "bg-sky-500/15 text-sky-300 border-sky-500/30",- running: "bg-amber-500/15 text-amber-300 border-amber-500/30",- done: "bg-emerald-500/15 text-emerald-300 border-emerald-500/30",- failed: "bg-red-500/15 text-red-300 border-red-500/30",+ pending: "bg-sky-500/15 text-sky-500 border-sky-500/30",+ running: "bg-amber-500/15 text-amber-500 border-amber-500/30",+ done: "bg-emerald-500/15 text-emerald-500 border-emerald-500/30",+ failed: "bg-red-500/15 text-red-500 border-red-500/30",cancelled: "bg-surface-input/40 text-fg-muted border-line-strong/40",};export function EmptyState({ message }: { message: string }) {return (- <div className="text-center py-16 text-fg-muted text-sm">{message}</div>+ <div className="text-center py-14 px-4 text-fg-muted text-[15px]">{message}</div>);}@@ -168,12 +168,12 @@ export type StatTone = "default" | "accent" | "emerald" | "amber";export const STAT_VALUE_TONE: Record<StatTone, string> = {default: "text-fg",- accent: "text-indigo-300",- emerald: "text-emerald-300",- amber: "text-amber-300",+ accent: "text-accent",+ emerald: "text-emerald-500",+ amber: "text-amber-500",};-/** A single at-a-glance metric: small label, big number, optional hint. */+/** A single at-a-glance metric: label, big number, optional hint. */export function StatTile({label,value,@@ -186,14 +186,12 @@ export function StatTile({tone?: StatTone;}) {return (- <div className="rounded-xl border border-line bg-surface-elevated px-4 py-3 min-w-0">- <div className="text-[11px] font-medium uppercase tracking-wide text-fg-subtle truncate">- {label}- </div>- <div className={`mt-1 text-2xl font-semibold tabular-nums truncate ${STAT_VALUE_TONE[tone]}`}>+ <div className="rounded-2xl border border-line bg-surface-elevated px-3 py-3 sm:px-5 sm:py-4 min-w-0">+ <div className="text-sm font-medium text-fg-muted leading-snug">{label}</div>+ <div className={`mt-1 text-2xl sm:text-3xl font-bold tracking-tight tabular-nums leading-tight break-words ${STAT_VALUE_TONE[tone]}`}>{value}</div>- {hint && <div className="text-[11px] text-fg-muted mt-0.5 truncate">{hint}</div>}+ {hint && <div className="text-sm text-fg-subtle mt-0.5 leading-snug line-clamp-2">{hint}</div>}</div>);}@@ -218,7 +216,7 @@ export function LivePulse({<span className="relative inline-flex h-2 w-2 rounded-full bg-emerald-400" /></span>{label && (- <span className="text-[11px] font-medium uppercase tracking-wide text-emerald-300">+ <span className="text-xs font-medium uppercase tracking-wide text-emerald-500">{label}</span>)}@@ -229,14 +227,14 @@ export function LivePulse({export type TagTone = "info" | "muted";const TAG_TONE: Record<TagTone, string> = {- info: "bg-sky-500/15 text-sky-300 border-sky-500/30",+ info: "bg-sky-500/15 text-sky-500 border-sky-500/30",muted: "bg-surface-input/40 text-fg-subtle border-line",};/** Small categorical pill (e.g. "Once a day · for you"). Reuses the app's pill recipe. */export function Tag({ label, tone = "muted" }: { label: string; tone?: TagTone }) {return (- <span className={`px-1.5 py-0.5 rounded border text-[10px] font-medium ${TAG_TONE[tone]}`}>+ <span className={`px-2 py-0.5 rounded-lg border text-xs font-medium ${TAG_TONE[tone]}`}>{label}</span>);@@ -262,13 +260,13 @@ export function SectionHeading({<div className="mb-3"><div className="flex items-center gap-2 flex-wrap">{icon && <Icon name={icon} size="w-4 h-4" className="text-fg-subtle" />}- <h3 className="text-sm font-semibold text-fg">{title}</h3>+ <h3 className="text-base font-semibold text-fg">{title}</h3>{count != null && (- <span className="text-xs font-normal tabular-nums text-fg-subtle">{count}</span>+ <span className="text-sm font-normal tabular-nums text-fg-subtle">{count}</span>)}{tag && <Tag label={tag} tone={tagTone} />}</div>- {subtitle && <p className="text-xs text-fg-muted mt-0.5">{subtitle}</p>}+ {subtitle && <p className="text-sm text-fg-muted mt-1">{subtitle}</p>}</div>);}diff --git a/packages/ui/src/components/sessions/ChatHistory.tsx b/packages/ui/src/components/sessions/ChatHistory.tsxindex da1b0d20..2ff568ab 100644--- a/packages/ui/src/components/sessions/ChatHistory.tsx+++ b/packages/ui/src/components/sessions/ChatHistory.tsx@@ -2,6 +2,8 @@import { useMemo, useState } from "react";import Icon from "@/components/Icon";+import Button from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";import type { SessionSummary } from "@/lib/api";import { formatRelativeTime } from "@/lib/relativeTime";import { CHANNEL_LABELS, sessionChannel, sessionTitle } from "@/lib/sessionChannel";@@ -16,7 +18,8 @@ interface ChatHistoryProps {/** While a search is active every group is forced open so no match is hidden. */searching: boolean;onSelect: (sessionId: string) => void;- onDelete: (sessionId: string) => void;+ /** Deletes after the row has asked; resolves false when it failed. */+ onDelete: (sessionId: string) => Promise<boolean>;}// Date-grouped conversation list for /chats — the full history the sidebar's@@ -28,7 +31,7 @@ export default function ChatHistory({ sessions, searching, onSelect, onDelete }:const groups = useMemo(() => groupSessionsByDate(sessions), [sessions]);if (groups.length === 0) {- return <p className="px-3 py-6 text-sm text-fg-muted">No conversations match.</p>;+ return <p className="px-1 py-6 text-[15px] text-fg-muted">No conversations match.</p>;}// Stored collapse state (default-collapsed unless the user toggled it). While@@ -54,18 +57,18 @@ export default function ChatHistory({ sessions, searching, onSelect, onDelete }:type="button"onClick={() => toggleCollapse(group.key)}aria-expanded={!collapsed}- className="w-full flex items-center gap-1.5 px-3 py-1.5 text-fg-subtle hover:text-fg transition-colors cursor-pointer"+ className="w-full flex items-center gap-2 min-h-[40px] px-1 text-fg-muted hover:text-fg transition-colors cursor-pointer"><Iconname="chevron-right"- size="w-3 h-3"+ size="w-3.5 h-3.5"className={`transition-transform ${collapsed ? "" : "rotate-90"}`}/>- <span className="text-[11px] font-medium uppercase tracking-wide">{group.label}</span>- <span className="text-[10px] text-fg-subtle/70">{group.items.length}</span>+ <span className="text-sm font-semibold">{group.label}</span>+ <span className="text-sm text-fg-subtle">{group.items.length}</span></button>{!collapsed && (- <div className="mt-1 space-y-0.5">+ <div className="mt-1 space-y-2">{visible.map((s) => (<ChatRow key={s.session_id} session={s} onSelect={onSelect} onDelete={onDelete} />))}@@ -73,7 +76,7 @@ export default function ChatHistory({ sessions, searching, onSelect, onDelete }:<buttontype="button"onClick={() => revealAll(group.key)}- className="w-full text-left px-3 py-1.5 text-xs text-fg-subtle hover:text-fg cursor-pointer"+ className="w-full text-left min-h-[40px] px-4 text-sm font-medium text-fg-muted hover:text-fg cursor-pointer">Show {hiddenCount} more</button>@@ -94,39 +97,72 @@ function ChatRow({}: {session: SessionSummary;onSelect: (sessionId: string) => void;- onDelete: (sessionId: string) => void;+ onDelete: (sessionId: string) => Promise<boolean>;}) {+ // Delete is in the row's ⋯ menu and asks here, in the row, first.+ const [confirming, setConfirming] = useState(false);+ const [deleting, setDeleting] = useState(false);+ const [failed, setFailed] = useState(false);const channel = sessionChannel(session.session_id);const messages = `${session.message_count} message${session.message_count === 1 ? "" : "s"}`;++ const confirmDelete = async () => {+ setDeleting(true);+ setFailed(false);+ const ok = await onDelete(session.session_id);+ // On success the row leaves the list; on failure it stays and says so.+ if (!ok) {+ setDeleting(false);+ setFailed(true);+ }+ };+return (- <div className="group flex items-center gap-2 rounded-lg hover:bg-surface-elevated/60 transition-colors">- <button- type="button"- onClick={() => onSelect(session.session_id)}- className="flex-1 min-w-0 text-left px-3 py-2.5 cursor-pointer"- >- <span className="flex items-center gap-2 min-w-0">- <span className="text-sm text-fg truncate">{sessionTitle(session)}</span>- {channel !== "web" && (- <span className="flex-shrink-0 text-[10px] font-medium uppercase tracking-wide text-fg-muted ring-1 ring-line rounded px-1.5 py-0.5 leading-none">- {CHANNEL_LABELS[channel]}- </span>- )}- </span>- <span className="block text-xs text-fg-subtle mt-0.5">- {formatRelativeTime(session.updated_at)} · {messages}- </span>- </button>- {/* Always visible on touch (no hover); revealed on hover/focus on desktop. */}- <button- type="button"- aria-label="Delete chat"- title="Delete chat"- onClick={() => onDelete(session.session_id)}- className="mr-1 min-h-touch min-w-touch flex items-center justify-center rounded-md text-fg-muted hover:text-red-400 hover:bg-red-500/10 opacity-100 sm:opacity-0 sm:group-hover:opacity-100 sm:group-focus-within:opacity-100 focus:opacity-100 transition-opacity cursor-pointer"- >- <Icon name="trash" size="w-4 h-4" />- </button>+ <div className="rounded-2xl border border-line bg-surface-elevated transition-colors hover:border-line-strong">+ <div className="flex items-center gap-1 pr-2">+ <button+ type="button"+ onClick={() => onSelect(session.session_id)}+ className="flex-1 min-w-0 text-left px-4 py-3.5 cursor-pointer rounded-2xl focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/50"+ >+ <span className="flex items-center gap-2 min-w-0">+ <span className="text-base font-medium text-fg truncate">{sessionTitle(session)}</span>+ {channel !== "web" && (+ <span className="flex-shrink-0 text-[11px] font-medium uppercase tracking-wide text-fg-muted ring-1 ring-line rounded-md px-1.5 py-0.5 leading-none">+ {CHANNEL_LABELS[channel]}+ </span>+ )}+ </span>+ <span className="block text-sm text-fg-subtle mt-0.5">+ {formatRelativeTime(session.updated_at)} · {messages}+ </span>+ </button>+ <OverflowMenu+ label="More actions for this chat"+ items={[{ label: "Delete chat", danger: true, onSelect: () => setConfirming(true) }]}+ />+ </div>+ {(confirming || failed) && (+ <div role="alert" className="flex flex-wrap items-center gap-2 border-t border-line px-4 py-3">+ <p className="mr-auto text-sm text-fg">+ {failed ? "Couldn't delete this chat. Try again?" : "Delete this chat? This cannot be undone."}+ </p>+ <Button size="sm" variant="danger" onClick={() => void confirmDelete()} disabled={deleting}>+ {deleting ? "Deleting…" : "Delete"}+ </Button>+ <Button+ size="sm"+ variant="ghost"+ onClick={() => {+ setConfirming(false);+ setFailed(false);+ }}+ disabled={deleting}+ >+ Cancel+ </Button>+ </div>+ )}</div>);}diff --git a/packages/ui/src/components/sessions/SessionsContext.tsx b/packages/ui/src/components/sessions/SessionsContext.tsxindex a95ae58b..00d00aad 100644--- a/packages/ui/src/components/sessions/SessionsContext.tsx+++ b/packages/ui/src/components/sessions/SessionsContext.tsx@@ -51,14 +51,14 @@ export function SessionsProvider({ children }: { children: React.ReactNode }) {if (status === "authenticated") refresh();}, [status, refresh]);+ // Deletes without asking: the caller confirms first (the Chats page asks+ // in the row) and says so when this returns false.const remove = useCallback(async (sessionId: string) => {- if (!window.confirm("Delete this chat? This cannot be undone.")) return false;try {await deleteSession(sessionId);} catch (err) {console.error(err);- window.alert("Failed to delete chat.");return false;}refresh();diff --git a/packages/ui/src/components/settings/AboutCard.tsx b/packages/ui/src/components/settings/AboutCard.tsxindex 2ef76058..e575024a 100644--- a/packages/ui/src/components/settings/AboutCard.tsx+++ b/packages/ui/src/components/settings/AboutCard.tsx@@ -26,17 +26,17 @@ export default function AboutCard() {}, []);if (failed) {- return <p className="text-sm text-fg-muted">Couldn't load the version.</p>;+ return <p className="text-[15px] text-fg-muted">Couldn't load the version.</p>;}if (!notice) {- return <p className="text-sm text-fg-muted">Loading…</p>;+ return <p className="text-[15px] text-fg-muted">Loading…</p>;}return (- <div className="space-y-1">- <p className="text-sm text-fg">{notice.running}</p>- <p className="text-xs text-fg-muted">{notice.status}</p>+ <div className="space-y-1.5">+ <p className="text-lg font-semibold text-fg">{notice.running}</p>+ <p className="text-[15px] text-fg-muted">{notice.status}</p>{notice.update && (- <p className="text-xs">+ <p className="pt-1 text-[15px] font-medium"><ahref={notice.update.releaseUrl}target="_blank"diff --git a/packages/ui/src/components/settings/ActAsMeCard.tsx b/packages/ui/src/components/settings/ActAsMeCard.tsxindex a9d68537..51b5b658 100644--- a/packages/ui/src/components/settings/ActAsMeCard.tsx+++ b/packages/ui/src/components/settings/ActAsMeCard.tsx@@ -3,8 +3,10 @@import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";import Icon from "@/components/Icon";-import SettingsSection from "@/components/settings/SettingsSection";+import AdvancedFold from "@/components/settings/AdvancedFold";+import SettingsCard from "@/components/settings/SettingsCard";import Switch from "@/components/Switch";+import Button from "@/components/ui/Button";import {checkInboxNow,getDelegation,@@ -26,13 +28,15 @@ import { formatAgo } from "@/lib/setupStatus";// Settings → Act as me: let the Executive draft email AS you, in your own// Gmail Drafts, when you ask it to — and, with Draft replies to my inbox on,// for mail that needs you, which it sends only when you tap Send on Today.-// Backed by GET/PUT /delegation, /delegation/inbox and /delegation/voice. Hidden for anyone who can't have it-// (the owner can, and team members once the owner lets them: PUT-// /delegation/team) and on a backend without it — so, unlike the other-// sections, this one renders its own heading and tells the page (via-// `onVisible`) whether it is on the page at all.--const INTRO =+// Backed by GET/PUT /delegation, /delegation/inbox 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, Write drafts as me and Draft replies to my+// inbox up front; How I write and Let team members use it under Advanced.++export const ACT_AS_ME_INTRO ="Let the Executive write email as you, in your own voice. When you ask it to reply to or write an email as you, it saves a draft in your own mailbox (Gmail or Outlook) for you to review and send. Nothing goes out as you unless you send it, from your mailbox or with Send on a reply waiting on Today. Everything else it writes stays in its own name.";const LENGTHS = ["short", "medium", "long"] as const;@@ -62,7 +66,7 @@ function greetingFields(p: VoiceProfile): Record<string, string> {return Object.fromEntries(AUDIENCES.map((a) => [a, p.greetings[a] ?? ""]));}-export default function ActAsMeCard({ onVisible }: { onVisible?: (visible: boolean) => void }) {+export default function ActAsMeCard() {const [settings, setSettings] = useState<DelegationSettings | null>(null);const [state, setState] = useState<"loading" | "hidden" | "ready" | "error">("loading");const [busy, setBusy] = useState(false);@@ -89,12 +93,6 @@ export default function ActAsMeCard({ onVisible }: { onVisible?: (visible: boolereturn () => controller.abort();}, [load]);- // The page lists the section in its nav only while it is on the page, and- // scrolls a `#act-as-me` link here once it is.- useEffect(() => {- onVisible?.(state === "ready" || state === "error");- }, [state, onVisible]);-// 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.@@ -123,12 +121,22 @@ export default function ActAsMeCard({ onVisible }: { onVisible?: (visible: boolereturn () => clearTimeout(timer);}, [checking, pollTick]);- if (state === "hidden" || state === "loading") return null;+ 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'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 (- <SettingsSection id="act-as-me" title="Act as me" description={INTRO}>- <p className="text-xs text-fg-subtle">Couldn't load this setting.</p>- </SettingsSection>+ <SettingsCard>+ <p className="text-[15px] text-fg-muted">Couldn't load this setting.</p>+ </SettingsCard>);}@@ -156,93 +164,93 @@ export default function ActAsMeCard({ onVisible }: { onVisible?: (visible: boolesetBusy(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 (- <SettingsSection id="act-as-me" title="Act as me" description={INTRO}>- <div className="max-w-md divide-y divide-line">- {/* Your mailbox */}- <div className="py-4 first:pt-0 last:pb-0">- <div className="text-xs font-medium text-fg">{connected ? `Your ${mailbox}` : "Your mailbox"}</div>- <p className="text-xs text-fg-muted mt-0.5 leading-relaxed">- {connected ? `Connected to ${settings.gmail.email}.` : settings.gmail.message}- </p>- {!connected && settings.gmail.status === "not_configured" && (- <div className="mt-2">- <p className="text-xs text-fg-muted leading-relaxed">- For Gmail, on a computer with a browser, with the Executive'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="mt-1.5 whitespace-pre-wrap break-all rounded-md border border-line bg-surface px-2 py-1.5 text-[11px] text-fg">- {settings.gmail.connect_command}- </pre>- {settings.gmail.outlook_connect_command && (- <>- <p className="mt-2 text-xs text-fg-muted leading-relaxed">- For Outlook, with the Executive's Microsoft 365 app exported, run this instead- and sign in as yourself with the code it prints:- </p>- <pre className="mt-1.5 whitespace-pre-wrap break-all rounded-md border border-line bg-surface px-2 py-1.5 text-[11px] text-fg">- {settings.gmail.outlook_connect_command}- </pre>- </>- )}- </div>- )}- {!connected && (- <button- type="button"- onClick={() => void recheck()}- disabled={busy}- className="mt-2 text-xs text-indigo-400 hover:text-indigo-300 disabled:opacity-50"- >- Check again- </button>- )}- </div>-- {/* The switch */}- <div className="py-4 first:pt-0 last:pb-0">- <div className="flex items-start justify-between gap-3">- <div>- <div className="text-xs font-medium text-fg" id="act-as-me-label">- Write drafts as me+ <>+ <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'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'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>- <p className="text-xs text-fg-muted mt-0.5 leading-relaxed">- {on- ? `On: ask it in chat — “reply to Dana as me: yes to the 5th” — and the draft waits in your ${mailbox} Drafts.`- : connected- ? "Off: the Executive only ever writes as itself."- : "Connect your mailbox first."}- </p>- </div>- <Switch- checked={on}- onChange={() => void toggle()}- disabled={busy || (!on && !connected)}- labelledBy="act-as-me-label"- />+ )}+ <Button variant="primary" onClick={() => void recheck()} disabled={busy}>+ {busy ? "Checking…" : "Check again"}+ </Button></div>- {error && <p className="mt-1 text-xs text-red-400">{error}</p>}- </div>-- {settings.inbox && (- <InboxSection- inbox={stoppedWaiting ? { ...settings.inbox, checking: false } : settings.inbox}- actAsMeOn={on}- onSettings={setSettings}- onInbox={(inbox) => {- setStoppedWaiting(false);- polls.current = 0;- setSettings((prev) => (prev ? { ...prev, inbox } : prev));- }}- />)}+ </SettingsCard>++ <SettingsCard+ title="Write drafts as me"+ titleId="act-as-me-label"+ description={+ on+ ? `On: ask it in chat — “reply to Dana as me: yes to the 5th” — and the draft waits in your ${mailbox} Drafts.`+ : connected+ ? "Off: the Executive only ever writes as itself."+ : "Connect your mailbox first."+ }+ action={+ <Switch+ checked={on}+ onChange={() => void toggle()}+ disabled={busy || (!on && !connected)}+ labelledBy="act-as-me-label"+ />+ }+ >+ {error && <p className="text-sm text-red-500">{error}</p>}+ </SettingsCard>++ {settings.inbox && (+ <InboxSection+ inbox={stoppedWaiting ? { ...settings.inbox, checking: false } : settings.inbox}+ actAsMeOn={on}+ onSettings={setSettings}+ onInbox={(inbox) => {+ setStoppedWaiting(false);+ polls.current = 0;+ setSettings((prev) => (prev ? { ...prev, inbox } : prev));+ }}+ />+ )}+ <AdvancedFold+ id="act-as-me-advanced"+ summary={settings.team ? "How I write · Let team members use it" : "How I write"}+ ><VoiceSection connected={connected} outlook={outlook} />-{settings.team && <TeamSection team={settings.team} onSettings={setSettings} />}- </div>- </SettingsSection>+ </AdvancedFold>+ </>);}@@ -273,38 +281,36 @@ function TeamSection({};return (- <div className="py-4 first:pt-0 last:pb-0">- <div className="flex items-start justify-between gap-3">- <div>- <div className="text-xs font-medium text-fg" id="act-as-me-team-label">- Let team members use it- </div>- <p className="text-xs text-fg-muted mt-0.5 leading-relaxed">- {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."}- </p>- </div>+ <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={<Switchchecked={team.enabled}onChange={() => void toggle()}disabled={busy}labelledBy="act-as-me-team-label"/>- </div>+ }+ >{team.enabled && team.members.length > 0 && (- <ul className="mt-2 space-y-1">+ <ul className="divide-y divide-line">{team.members.map((m) => (- <li key={m.person_id} className="text-xs text-fg-muted">- <span className="text-fg">{m.name}</span>+ <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-1 text-xs text-red-400">{error}</p>}- </div>+ {error && <p className="mt-2 text-sm text-red-500">{error}</p>}+ </SettingsCard>);}@@ -351,45 +357,38 @@ function InboxSection({const last = inbox.last_poll_at && !inbox.checking ? ` Last checked ${formatAgo(inbox.last_poll_at)}.` : "";return (- <div className="py-4 first:pt-0 last:pb-0">- <div className="flex items-start justify-between gap-3">- <div>- <div className="text-xs font-medium text-fg" id="act-as-me-inbox-label">- Draft replies to my inbox- </div>- <p className="text-xs text-fg-muted mt-0.5 leading-relaxed">- {on- ? "When mail comes in that needs you, it writes a first reply in your Drafts and puts it on Today, where you send it, edit it in your mailbox or dismiss it. Nothing is sent until you tap Send."- : actAsMeOn- ? "Off: it only drafts when you ask it to in chat."- : "Turn on Write drafts as me first."}- </p>- </div>+ <SettingsCard+ title="Draft replies to my inbox"+ titleId="act-as-me-inbox-label"+ description={+ on+ ? "When mail comes in that needs you, it writes a first reply in your Drafts and puts it on Today, where you send it, edit it in your mailbox or dismiss it. Nothing is sent until you tap Send."+ : actAsMeOn+ ? "Off: it only drafts when you ask it to in chat."+ : "Turn on Write drafts as me first."+ }+ action={<Switchchecked={on}onChange={() => void toggle()}disabled={busy || (!on && !actAsMeOn)}labelledBy="act-as-me-inbox-label"/>- </div>+ }+ >{on && (- <div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1">- <span className="text-xs text-fg-muted">+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">+ <span className="text-sm text-fg-muted">{inbox.message}{last}</span>- <button- type="button"- onClick={() => void checkNow()}- disabled={busy || inbox.checking}- className="text-xs text-indigo-400 hover:text-indigo-300 disabled:opacity-50"- >+ <Button size="sm" onClick={() => void checkNow()} disabled={busy || inbox.checking}>{inbox.checking ? "Checking…" : "Check now"}- </button>+ </Button></div>)}- {error && <p className="mt-1 text-xs text-red-400">{error}</p>}- </div>+ {error && <p className="mt-2 text-sm text-red-500">{error}</p>}+ </SettingsCard>);}@@ -432,7 +431,11 @@ function VoiceSection({ connected, outlook = false }: { connected: boolean; outl}, [adopt]);if (loadFailed) {- return <p className="text-xs text-fg-subtle">Couldn't load how you write.</p>;+ return (+ <SettingsCard title="How I write">+ <p className="text-sm text-fg-muted">Couldn't load how you write.</p>+ </SettingsCard>+ );}if (!profile) return null;@@ -490,57 +493,56 @@ function VoiceSection({ connected, outlook = false }: { connected: boolean; outlsignOff !== profile.sign_off ||length !== profile.length ||formality !== profile.formality;- const linkButton = "text-xs text-indigo-400 hover:text-indigo-300 disabled:opacity-50";+ 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;return (- <div className="py-4 first:pt-0 last:pb-0">- <div className="text-xs font-medium text-fg">How I write</div>- <p className="text-xs text-fg-muted mt-0.5 leading-relaxed">- {learned+ <SettingsCard+ title="How I write"+ description={+ learned? `Learned from ${profile.sample_count} of your sent emails${profile.locked ? " — locked, so it won't be relearned" : ""}. Drafts follow it; edit anything that isn't you.`- : "Not learned yet. It reads your recent sent mail once, keeps only what you wrote, and describes your style — you can edit or lock it."}- </p>-- <div className="mt-2 flex flex-wrap items-center gap-2">+ : "Not learned yet. It reads your recent sent mail once, keeps only what you wrote, and describes your style — you can edit or lock it."+ }+ >+ <div className="flex flex-wrap items-center gap-2">{!profile.locked && (- <button- type="button"+ <Button+ variant={learned ? "secondary" : "primary"}+ size="sm"disabled={busy || !connected}onClick={() => void run(learnVoiceProfile)}- className="rounded-md border border-line px-2.5 py-1 text-xs text-fg hover:bg-surface-overlay disabled:opacity-50">{busy ? "Working…" : learned ? "Learn again from my sent mail" : "Learn from my sent mail"}- </button>+ </Button>)}{learned && !dirty && (- <button- type="button"+ <Button+ variant="ghost"+ size="sm"onClick={() => setEditing((v) => !v)}aria-expanded={showForm}aria-controls="voice-editor"- className="flex items-center gap-1 rounded-md px-2 py-1 text-xs text-fg-muted hover:text-fg disabled:opacity-50">{showForm ? "Done editing" : "Edit how I write"}<Iconname="chevron-right"- size="w-3.5 h-3.5"+ size="w-4 h-4"className={`transition-transform ${showForm ? "rotate-90" : ""}`}/>- </button>+ </Button>)}</div>{learned && showForm && (- <div id="voice-editor" className="mt-3 space-y-4">- <div className="flex gap-3">- <label className="text-xs text-fg-muted">+ <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="ml-1.5 rounded border border-line bg-surface px-1 py-0.5 text-xs text-fg"- >+ <select value={length} onChange={(e) => setLength(e.target.value)} className={`${field} h-10`}><option value="">—</option>{LENGTHS.map((l) => (<option key={l} value={l}>@@ -549,12 +551,12 @@ function VoiceSection({ connected, outlook = false }: { connected: boolean; outl))}</select></label>- <label className="text-xs text-fg-muted">+ <label className="flex items-center gap-2 text-sm text-fg-muted">Tone<selectvalue={formality}onChange={(e) => setFormality(e.target.value)}- className="ml-1.5 rounded border border-line bg-surface px-1 py-0.5 text-xs text-fg"+ className={`${field} h-10`}><option value="">—</option>{FORMALITIES.map((f) => (@@ -567,42 +569,45 @@ function VoiceSection({ connected, outlook = false }: { connected: boolean; outl</div><fieldset>- <legend className="text-xs text-fg-muted">Greeting</legend>- <p className="text-[11px] text-fg-subtle leading-relaxed">+ <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-1.5 space-y-1.5">+ <div className="mt-2 space-y-2">{AUDIENCES.map((audience) => (- <label key={audience} className="flex items-center gap-2 text-xs text-fg-muted">- <span className="w-28 flex-shrink-0">{AUDIENCE_LABEL[audience]}</span>+ <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><inputtype="text"value={greetings[audience] ?? ""}onChange={(e) => setGreetings((g) => ({ ...g, [audience]: e.target.value }))}placeholder="Not set"maxLength={GREETING_MAX_CHARS}- className="min-w-0 flex-1 rounded border border-line bg-surface px-2 py-1 text-xs text-fg"+ className={`${field} h-10 min-w-0 flex-1`}/></label>))}</div></fieldset>- <label className="block text-xs text-fg-muted">+ <label className="block text-sm font-medium text-fg">Sign-off<GrowingTextarea value={signOff} onChange={setSignOff} minRows={2} /></label>- <label className="block text-xs text-fg-muted">+ <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-xs text-fg-muted">+ <label className="block text-sm font-medium text-fg">Never (one per line)<GrowingTextarea value={avoid} onChange={setAvoid} minRows={2} /></label>- <div className="text-xs text-fg-muted">- <div>Signature</div>+ <div className="text-sm text-fg-muted">+ <div className="font-medium text-fg">Signature</div>{profile.signature ? (<><p className="mt-0.5 leading-relaxed">@@ -610,10 +615,10 @@ function VoiceSection({ connected, outlook = false }: { connected: boolean; outl? "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-1 whitespace-pre-wrap break-words border-l-2 border-line pl-2 leading-relaxed text-fg">+ <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-3">+ <div className="mt-1 flex flex-wrap gap-x-4">{!outlook && (<buttontype="button"@@ -646,7 +651,7 @@ function VoiceSection({ connected, outlook = false }: { connected: boolean; outltype="button"disabled={busy || !connected}onClick={takeGmailSignature}- className={`mt-1 ${linkButton}`}+ className={linkButton}>Add my Gmail signature</button>@@ -656,16 +661,16 @@ function VoiceSection({ connected, outlook = false }: { connected: boolean; outl</div>{profile.exemplars.length > 0 && (- <div className="text-xs text-fg-muted">- <div>Examples of your writing</div>+ <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-1 space-y-1.5">+ <ul className="mt-2 space-y-2">{profile.exemplars.map((example, i) => (<likey={i}- className="whitespace-pre-wrap break-words border-l-2 border-line pl-2 leading-relaxed text-fg"+ className="whitespace-pre-wrap break-words border-l-2 border-line pl-3 leading-relaxed text-fg">{example}</li>@@ -675,16 +680,16 @@ function VoiceSection({ connected, outlook = false }: { connected: boolean; outltype="button"disabled={busy}onClick={() => void run(() => updateVoiceProfile({ clear_exemplars: true }), true)}- className={`mt-1 ${linkButton}`}+ className={linkButton}>Remove examples</button></div>)}- <div className="flex flex-wrap items-center gap-2">- <button- type="button"+ <div className="flex flex-wrap items-center gap-2 border-t border-line pt-4">+ <Button+ variant="primary"disabled={busy || !dirty}onClick={() =>void run(() =>@@ -700,32 +705,24 @@ function VoiceSection({ connected, outlook = false }: { connected: boolean; outl}),)}- className="rounded-md bg-indigo-500 px-2.5 py-1 text-xs text-white hover:bg-indigo-400 disabled:opacity-50">Save changes- </button>- <button- type="button"+ </Button>+ <Buttondisabled={busy}onClick={() => void run(() => updateVoiceProfile({ locked: !profile.locked }), true)}- className="rounded-md border border-line px-2.5 py-1 text-xs text-fg hover:bg-surface-overlay disabled:opacity-50">{profile.locked ? "Unlock" : "Lock"}- </button>- <button- type="button"- disabled={busy}- onClick={() => void run(resetVoiceProfile)}- className="rounded-md px-2.5 py-1 text-xs text-fg-muted hover:text-fg disabled:opacity-50"- >+ </Button>+ <Button variant="ghost" disabled={busy} onClick={() => void run(resetVoiceProfile)}>Reset- </button>+ </Button></div></div>)}- {notice && <p className="mt-1 text-xs text-fg-muted">{notice}</p>}- {error && <p className="mt-1 text-xs text-red-400">{error}</p>}- </div>+ {notice && <p className="mt-2 text-sm text-fg-muted">{notice}</p>}+ {error && <p className="mt-2 text-sm text-red-500">{error}</p>}+ </SettingsCard>);}@@ -760,7 +757,7 @@ function GrowingTextarea({value={value}onChange={(e) => onChange(e.target.value)}rows={minRows}- className="mt-1 block w-full resize-none overflow-hidden rounded border border-line bg-surface px-2 py-1 text-xs leading-relaxed text-fg"+ 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"/>);}diff --git a/packages/ui/src/components/settings/AdvancedFold.tsx b/packages/ui/src/components/settings/AdvancedFold.tsxnew file mode 100644index 00000000..8131b717--- /dev/null+++ b/packages/ui/src/components/settings/AdvancedFold.tsx@@ -0,0 +1,45 @@+"use client";++import { useState, type ReactNode } from "react";++import Icon from "@/components/Icon";++// The fold at the foot of a Settings page that holds its rarer settings.+// Closed by default; `summary` says what is inside without opening it.+export default function AdvancedFold({+ id,+ summary,+ children,+}: {+ id: string;+ summary: string;+ children: ReactNode;+}) {+ const [open, setOpen] = useState(false);+ return (+ <div>+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ aria-expanded={open}+ aria-controls={id}+ className="flex w-full min-h-[3rem] items-center gap-3 rounded-2xl border border-line bg-surface-elevated px-5 py-3 text-left transition-colors hover:bg-surface-overlay cursor-pointer"+ >+ <span className="min-w-0 flex-1">+ <span className="block text-base font-semibold text-fg">Advanced</span>+ <span className="block text-sm text-fg-muted truncate">{summary}</span>+ </span>+ <Icon+ name="chevron-right"+ size="w-5 h-5"+ className={`text-fg-muted transition-transform ${open ? "rotate-90" : ""}`}+ />+ </button>+ {open && (+ <div id={id} className="mt-4 space-y-5">+ {children}+ </div>+ )}+ </div>+ );+}diff --git a/packages/ui/src/components/settings/SettingsCard.tsx b/packages/ui/src/components/settings/SettingsCard.tsxnew file mode 100644index 00000000..93142d63--- /dev/null+++ b/packages/ui/src/components/settings/SettingsCard.tsx@@ -0,0 +1,42 @@+import { Children, type ReactNode } from "react";++// One card on a Settings page: an optional title and line of explanation,+// then the controls. `titleId` lets a switch in the card name itself by the+// card's title.+export default function SettingsCard({+ title,+ titleId,+ description,+ action,+ children,+}: {+ title?: ReactNode;+ titleId?: string;+ description?: ReactNode;+ /** A control beside the title, such as a switch. */+ action?: ReactNode;+ children?: ReactNode;+}) {+ return (+ <section className="rounded-2xl border border-line bg-surface-elevated p-5 sm:p-6">+ {(title || action) && (+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ {title && (+ <h2 id={titleId} className="text-base sm:text-lg font-semibold text-fg">+ {title}+ </h2>+ )}+ {description && (+ <p className="mt-1 text-sm text-fg-muted leading-relaxed">{description}</p>+ )}+ </div>+ {action && <div className="flex-shrink-0 pt-1">{action}</div>}+ </div>+ )}+ {Children.toArray(children).length > 0 && (+ <div className={title || action ? "mt-4" : ""}>{children}</div>+ )}+ </section>+ );+}diff --git a/packages/ui/src/components/settings/SettingsNav.tsx b/packages/ui/src/components/settings/SettingsNav.tsxdeleted file mode 100644index 7c397ac2..00000000--- a/packages/ui/src/components/settings/SettingsNav.tsx+++ /dev/null@@ -1,53 +0,0 @@-"use client";--import type { SettingsSectionDef } from "@/components/shell/navConfig";--// The Settings page's section nav: a sticky list beside the sections on-// `lg` and up, a sticky row of chips under the heading below that. Links-// are real `#id` anchors, so they work without JavaScript; with it, the-// page scrolls smoothly and keeps the hash in the address bar.-export default function SettingsNav({- sections,- active,- onJump,-}: {- sections: SettingsSectionDef[];- active: string | null;- onJump: (id: string) => void;-}) {- const link = (section: SettingsSectionDef, className: string) => {- const current = active === section.id;- return (- <a- key={section.id}- href={`#${section.id}`}- aria-current={current ? "location" : undefined}- onClick={(e) => {- e.preventDefault();- onJump(section.id);- }}- className={`${className} transition-colors ${- current ? "bg-indigo-500/10 text-indigo-400" : "text-fg-muted hover:text-fg hover:bg-surface-overlay/60"- }`}- >- {section.label}- </a>- );- };-- return (- <>- <aside className="hidden lg:block lg:sticky lg:top-6 lg:self-start">- <nav aria-label="Settings sections" className="space-y-0.5">- {sections.map((s) => link(s, "block px-2.5 py-1.5 rounded-lg text-xs"))}- </nav>- </aside>- <nav- aria-label="Settings sections"- className="lg:hidden sticky top-0 z-10 -mx-4 sm:-mx-6 px-4 sm:px-6 py-2 bg-surface border-b border-line flex gap-1.5 overflow-x-auto"- >- {sections.map((s) => link(s, "flex-shrink-0 px-3 py-1.5 rounded-md text-xs whitespace-nowrap"))}- </nav>- </>- );-}diff --git a/packages/ui/src/components/settings/SettingsSection.tsx b/packages/ui/src/components/settings/SettingsSection.tsxdeleted file mode 100644index 23382945..00000000--- a/packages/ui/src/components/settings/SettingsSection.tsx+++ /dev/null@@ -1,28 +0,0 @@-import type { ReactNode } from "react";--// One section of the Settings page: a heading the in-page nav can land on-// (`id` is the hash), an optional one-line description, and a card body.-// `scroll-mt` keeps the heading clear of the sticky chip row that sits at-// the top of the scroller below `lg`; on `lg` nothing overlaps it.-export default function SettingsSection({- id,- title,- description,- children,-}: {- id: string;- title: string;- description?: ReactNode;- children: ReactNode;-}) {- const titleId = `${id}-title`;- return (- <section id={id} aria-labelledby={titleId} className="scroll-mt-16 lg:scroll-mt-6">- <h2 id={titleId} className="text-sm font-medium text-fg">- {title}- </h2>- {description && <p className="mt-1 text-xs text-fg-muted leading-relaxed">{description}</p>}- <div className="mt-3 rounded-xl border border-line bg-surface-elevated p-4">{children}</div>- </section>- );-}diff --git a/packages/ui/src/components/settings/SettingsSubpage.tsx b/packages/ui/src/components/settings/SettingsSubpage.tsxnew file mode 100644index 00000000..febf250a--- /dev/null+++ b/packages/ui/src/components/settings/SettingsSubpage.tsx@@ -0,0 +1,35 @@+import Link from "next/link";+import type { ReactNode } from "react";++import Icon from "@/components/Icon";++// The frame of each page the Settings hub opens: a way back to the hub, a+// big title, an optional line under it, and the page's cards.+export default function SettingsSubpage({+ title,+ description,+ children,+}: {+ title: string;+ description?: ReactNode;+ children: ReactNode;+}) {+ return (+ <main className="flex-1 min-h-0 overflow-y-auto">+ <div className="max-w-3xl mx-auto px-4 sm:px-6 pt-6 sm:pt-8 pb-16">+ <Link+ href="/settings"+ className="-ml-2 inline-flex min-h-touch items-center gap-1.5 rounded-lg px-2 text-[15px] text-fg-muted hover:text-fg hover:bg-surface-overlay transition-colors"+ >+ <Icon name="arrow-left" size="w-4 h-4" />+ Settings+ </Link>+ <h1 className="mt-2 text-2xl sm:text-3xl font-bold tracking-tight text-fg">{title}</h1>+ {description && (+ <p className="mt-2 text-[15px] text-fg-muted leading-relaxed">{description}</p>+ )}+ <div className="mt-6 space-y-5">{children}</div>+ </div>+ </main>+ );+}diff --git a/packages/ui/src/components/settings/WorkspaceCard.tsx b/packages/ui/src/components/settings/WorkspaceCard.tsxindex 2905ca24..03f037b9 100644--- a/packages/ui/src/components/settings/WorkspaceCard.tsx+++ b/packages/ui/src/components/settings/WorkspaceCard.tsx@@ -2,7 +2,10 @@import { useEffect, useMemo, useState } from "react";+import AdvancedFold from "@/components/settings/AdvancedFold";+import SettingsCard from "@/components/settings/SettingsCard";import Switch from "@/components/Switch";+import Button from "@/components/ui/Button";import RoleFields from "@/components/workspace/RoleFields";import { useWorkspace } from "@/components/workspace/WorkspaceContext";import {@@ -19,12 +22,12 @@ import { roleFormErrors, roleFormFrom, roleUpdate, type RoleForm } from "@/lib/p// Settings → Workspace: who Open Executive is for (just you, or you and your// team), your role when it's just you, the time zone its briefs run in, and-// whether it books meetings without asking, as one row each. Mode, role and-// zone go through PUT /workspace and then the app-wide WorkspaceProvider is-// refreshed so the nav and pages follow. The page supplies the section-// heading; this is the body.+// whether it books meetings without asking, as one card each, with company+// email domains under Advanced. Mode, role and zone go through PUT+// /workspace and then the app-wide WorkspaceProvider is refreshed so the nav+// and pages follow. The page supplies the title; this is the body.-const MODE_LABEL: Record<WorkspaceMode, string> = {+export const MODE_LABEL: Record<WorkspaceMode, string> = {solo: "Just me",team: "With your team",};@@ -83,123 +86,125 @@ export default function WorkspaceCard() {}}+ const select =+ "w-full h-11 px-3 rounded-xl text-[15px] bg-surface border border-line text-fg focus:outline-none focus:border-line-strong disabled:opacity-60";return (- <div className="max-w-md">- <div className="divide-y divide-line">- {/* Mode */}- <div className="py-4 first:pt-0 last:pb-0">- <div className="text-xs font-medium text-fg mb-1.5" id="ws-mode-label">- Using Open Executive- </div>- <div role="radiogroup" aria-labelledby="ws-mode-label" className="inline-flex rounded-lg border border-line p-0.5 bg-surface">- {(["solo", "team"] as const).map((m) => {- const selected = mode === m;- return (- <button- key={m}- type="button"- role="radio"- aria-checked={selected}- disabled={loading || busy}- onClick={() => {- setError(null);- setPendingMode(selected ? null : m);- }}- className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 ${- selected ? "bg-surface-overlay text-fg" : "text-fg-muted hover:text-fg"- }`}- >- {MODE_LABEL[m]}- </button>- );- })}- </div>+ <>+ {error && (+ <p className="rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-500">+ {error}+ </p>+ )}++ <SettingsCard+ title="Using Open Executive"+ titleId="ws-mode-label"+ description="Just for you, or for you and your team."+ >+ <div+ role="radiogroup"+ aria-labelledby="ws-mode-label"+ className="inline-flex w-full sm:w-auto rounded-xl border border-line p-1 bg-surface"+ >+ {(["solo", "team"] as const).map((m) => {+ const selected = mode === m;+ return (+ <button+ key={m}+ type="button"+ role="radio"+ aria-checked={selected}+ disabled={loading || busy}+ onClick={() => {+ setError(null);+ setPendingMode(selected ? null : m);+ }}+ className={`flex-1 sm:flex-none h-10 px-5 rounded-lg text-[15px] font-medium transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 ${+ selected ? "bg-surface-elevated text-fg shadow-sm" : "text-fg-muted hover:text-fg"+ }`}+ >+ {MODE_LABEL[m]}+ </button>+ );+ })}+ </div>- {pendingMode && pendingMode !== mode && (- <div className="mt-3 rounded-lg border border-amber-500/30 bg-amber-500/10 p-3">- <p className="text-xs text-fg leading-relaxed">- Switch to <span className="font-medium">{MODE_LABEL[pendingMode]}</span>?{" "}- {SWITCH_EFFECT[pendingMode]}- </p>- <div className="mt-2.5 flex items-center gap-2">- <button- type="button"- disabled={busy}- onClick={async () => {- if (await save({ mode: pendingMode })) setPendingMode(null);- }}- className="px-3 py-1.5 rounded-lg text-xs font-medium bg-indigo-500 hover:bg-indigo-600 text-white transition-colors cursor-pointer disabled:opacity-50"- >- {busy ? "Switching…" : `Switch to ${MODE_LABEL[pendingMode]}`}- </button>- <button- type="button"- disabled={busy}- onClick={() => setPendingMode(null)}- className="px-3 py-1.5 rounded-lg text-xs text-fg-muted hover:text-fg transition-colors cursor-pointer disabled:opacity-50"- >- Cancel- </button>- </div>+ {pendingMode && pendingMode !== mode && (+ <div className="mt-4 rounded-xl border border-amber-500/30 bg-amber-500/10 p-4">+ <p className="text-sm text-fg leading-relaxed">+ Switch to <span className="font-semibold">{MODE_LABEL[pendingMode]}</span>?{" "}+ {SWITCH_EFFECT[pendingMode]}+ </p>+ <div className="mt-3 flex flex-wrap items-center gap-2">+ <Button+ variant="primary"+ disabled={busy}+ onClick={async () => {+ if (await save({ mode: pendingMode })) setPendingMode(null);+ }}+ >+ {busy ? "Switching…" : `Switch to ${MODE_LABEL[pendingMode]}`}+ </Button>+ <Button variant="ghost" disabled={busy} onClick={() => setPendingMode(null)}>+ Cancel+ </Button></div>- )}- </div>+ </div>+ )}+ <p className="mt-4 text-[13px] text-fg-subtle">+ A persona you customised in Council stays in place in either mode.+ </p>+ </SettingsCard>- {mode === "solo" && <RoleSection />}+ {mode === "solo" && <RoleSection />}- {/* Time zone */}- <div className="py-4 first:pt-0 last:pb-0">- <label htmlFor="ws-timezone" className="text-xs font-medium text-fg">- Time zone- </label>- <p className="text-xs text-fg-muted mt-0.5 mb-1.5">- When your morning brief, end-of-day digest and reflection arrive, and how the- Executive reads “tomorrow at 9”.+ <SettingsCard+ title={<label htmlFor="ws-timezone">Time zone</label>}+ description={+ <>+ When your morning brief, end-of-day digest and reflection arrive, and how the Executive+ reads “tomorrow at 9”.{effectiveTimezone && <> Now: {effectiveTimezone}.</>}- </p>- <select- id="ws-timezone"- value={timezone ?? ""}- disabled={loading || busy}- onChange={(e) => void save({ timezone: e.target.value || null })}- className="w-full px-2.5 py-1.5 rounded-lg text-sm bg-surface border border-line text-fg focus:outline-none focus:border-line-strong disabled:opacity-60"- >- <option value="">Follow server default</option>- {browserZone && (- <optgroup label="Suggested">- <option value={browserZone}>{browserZone} (this browser)</option>- </optgroup>- )}- <optgroup label="All time zones">- {zones.map((z) => (- <option key={z} value={z}>- {z}- </option>- ))}+ </>+ }+ >+ <select+ id="ws-timezone"+ value={timezone ?? ""}+ disabled={loading || busy}+ onChange={(e) => void save({ timezone: e.target.value || null })}+ className={select}+ >+ <option value="">Follow server default</option>+ {browserZone && (+ <optgroup label="Suggested">+ <option value={browserZone}>{browserZone} (this browser)</option></optgroup>- </select>- {browserZone && timezone !== browserZone && (- <button- type="button"- disabled={loading || busy}- onClick={() => void save({ timezone: browserZone })}- className="mt-1.5 text-xs text-indigo-400 hover:text-indigo-300 cursor-pointer disabled:opacity-50"- >- Use this browser's time zone ({browserZone})- </button>)}- </div>-- <CompanyDomainsSection />+ <optgroup label="All time zones">+ {zones.map((z) => (+ <option key={z} value={z}>+ {z}+ </option>+ ))}+ </optgroup>+ </select>+ {browserZone && timezone !== browserZone && (+ <button+ type="button"+ disabled={loading || busy}+ onClick={() => void save({ timezone: browserZone })}+ className="mt-2 min-h-touch text-left text-[15px] font-medium text-accent hover:underline cursor-pointer disabled:opacity-50"+ >+ Use this browser's time zone ({browserZone})+ </button>+ )}+ </SettingsCard>- <MeetingAutonomySwitch />- </div>+ <MeetingAutonomySwitch />- {error && <p className="mt-3 text-xs text-red-400">{error}</p>}- <p className="mt-4 text-xs text-fg-subtle">- A persona you customised in Council stays in place in either mode.- </p>- </div>+ <CompanyDomainsSection />+ </>);}@@ -245,46 +250,43 @@ function CompanyDomainsSection() {if (domains === null) return null;const parsed = draft.split(/[\s,;]+/).map((d) => d.trim().toLowerCase()).filter(Boolean);return (- <div className="py-4 first:pt-0 last:pb-0">- <label htmlFor="ws-domains" className="text-xs font-medium text-fg">- Company email domains- </label>- <p className="text-xs text-fg-muted mt-0.5 mb-1.5">- Mail from these domains matches a teammate by the part before the @, so- anna+invoices@ reaches the Anna already on your People list. Someone new- writing from one is suggested as a teammate — you still confirm them.- {!custom && " Taken from your own address until you set them."}- </p>- <div className="flex gap-2">+ <AdvancedFold id="ws-advanced" summary="Company email domains">+ <SettingsCard+ title={<label htmlFor="ws-domains">Company email domains</label>}+ description={+ <>+ Mail from these domains matches a teammate by the part before the @, so+ anna+invoices@ reaches the Anna already on your People list. Someone new writing from+ one is suggested as a teammate — you still confirm them.+ {!custom && " Taken from your own address until you set them."}+ </>+ }+ ><inputid="ws-domains"value={draft}disabled={busy}onChange={(e) => setDraft(e.target.value)}placeholder="acme.com, acme.io"- className="min-w-0 flex-1 px-2.5 py-1.5 rounded-lg text-sm bg-surface border border-line text-fg focus:outline-none focus:border-line-strong disabled:opacity-60"+ className="w-full h-11 px-3.5 rounded-xl text-[15px] bg-surface border border-line text-fg focus:outline-none focus:border-line-strong disabled:opacity-60"/>- <button- type="button"- disabled={busy || parsed.join(",") === domains.join(",")}- onClick={() => void save(parsed.length ? parsed : null)}- className="text-xs text-indigo-400 hover:text-indigo-300 cursor-pointer disabled:opacity-50"- >- Save- </button>- {custom && (- <button- type="button"- disabled={busy}- onClick={() => void save(null)}- className="text-xs text-fg-muted hover:text-fg cursor-pointer disabled:opacity-50"+ <div className="mt-3 flex flex-wrap items-center gap-2">+ <Button+ variant="primary"+ disabled={busy || parsed.join(",") === domains.join(",")}+ onClick={() => void save(parsed.length ? parsed : null)}>- Use my address- </button>- )}- </div>- {error && <p className="mt-1.5 text-xs text-red-400">{error}</p>}- </div>+ Save+ </Button>+ {custom && (+ <Button variant="ghost" disabled={busy} onClick={() => void save(null)}>+ Use my address+ </Button>+ )}+ </div>+ {error && <p className="mt-2 text-sm text-red-500">{error}</p>}+ </SettingsCard>+ </AdvancedFold>);}@@ -325,12 +327,10 @@ function RoleSection() {}return (- <div className="py-4 first:pt-0 last:pb-0">- <div className="text-xs font-medium text-fg">Your role</div>- <p className="text-xs text-fg-muted mt-0.5 mb-2 leading-relaxed">- So the Executive's advice fits your job, whatever your role: your own business, a- team you lead, or clients you advise.- </p>+ <SettingsCard+ title="Your role"+ description="So the Executive's advice fits your job, whatever your role: your own business, a team you lead, or clients you advise."+ ><RoleFieldsvalue={form}onChange={(next) => {@@ -341,32 +341,27 @@ function RoleSection() {idPrefix="ws-role"/>{problems.map((p) => (- <p key={p} className="mt-1.5 text-xs text-red-400">+ <p key={p} className="mt-2 text-sm text-red-500">{p}</p>))}- {error && <p className="mt-1.5 text-xs text-red-400">{error}</p>}- <div className="mt-2.5 flex items-center gap-2">- <button- type="button"+ {error && <p className="mt-2 text-sm text-red-500">{error}</p>}+ <div className="mt-4 flex flex-wrap items-center gap-2">+ <Button+ variant="primary"disabled={!dirty || busy || problems.length > 0}onClick={() => void save()}- className="px-3 py-1.5 rounded-lg text-xs font-medium bg-indigo-500 hover:bg-indigo-600 text-white transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed">{busy ? "Saving…" : "Save role"}- </button>+ </Button>{dirty && !busy && (- <button- type="button"- onClick={() => setForm(roleFormFrom(role))}- className="px-3 py-1.5 rounded-lg text-xs text-fg-muted hover:text-fg transition-colors cursor-pointer"- >+ <Button variant="ghost" onClick={() => setForm(roleFormFrom(role))}>Discard changes- </button>+ </Button>)}- {saved && !dirty && <span className="text-xs text-fg-muted">Saved.</span>}+ {saved && !dirty && <span className="text-sm text-fg-muted">Saved.</span>}</div>- </div>+ </SettingsCard>);}@@ -400,9 +395,9 @@ function MeetingAutonomySwitch() {if (state === "absent" || state === "loading") return null;if (state === "error") {return (- <div className="py-4 first:pt-0 last:pb-0">- <p className="text-xs text-fg-subtle">Couldn't load the meeting-booking setting.</p>- </div>+ <SettingsCard>+ <p className="text-sm text-fg-muted">Couldn't load the meeting-booking setting.</p>+ </SettingsCard>);}@@ -421,21 +416,17 @@ function MeetingAutonomySwitch() {};return (- <div className="py-4 first:pt-0 last:pb-0">- <div className="flex items-start justify-between gap-3">- <div>- <div className="text-xs font-medium text-fg" id="ws-meetings-label">- Book meetings without asking- </div>- <p className="text-xs text-fg-muted mt-0.5 leading-relaxed">- {on- ? "The Executive books meetings on your calendar on its own."- : "Each meeting the Executive wants to book waits for your approval in the briefing."}- </p>- </div>- <Switch checked={on} onChange={() => void toggle()} disabled={busy} labelledBy="ws-meetings-label" />- </div>- {error && <p className="mt-1 text-xs text-red-400">{error}</p>}- </div>+ <SettingsCard+ title="Book meetings without asking"+ titleId="ws-meetings-label"+ description={+ on+ ? "The Executive books meetings on your calendar on its own."+ : "Each meeting the Executive wants to book waits for your approval in the briefing."+ }+ action={<Switch checked={on} onChange={() => void toggle()} disabled={busy} labelledBy="ws-meetings-label" />}+ >+ {error && <p className="text-sm text-red-500">{error}</p>}+ </SettingsCard>);}diff --git a/packages/ui/src/components/shell/AppShell.tsx b/packages/ui/src/components/shell/AppShell.tsxindex 84ae7c1a..dd4da59e 100644--- a/packages/ui/src/components/shell/AppShell.tsx+++ b/packages/ui/src/components/shell/AppShell.tsx@@ -11,10 +11,12 @@ import PausedBanner from "@/components/executive/PausedBanner";import AppSidebar from "@/components/shell/AppSidebar";import {buildMobilePrimary,- isNavActive,+ hubForPath,+ isDestinationActive,PROFILE_NAV,profileWording,} from "@/components/shell/navConfig";+import HubTabs from "@/components/ui/HubTabs";import { useWorkspace } from "@/components/workspace/WorkspaceContext";// Routes that own their full layout and should not be wrapped by the@@ -36,7 +38,7 @@ const SEGMENT_LABELS: Record<string, string> = {departments: "Departments",goals: "Goals",memories: "Pulse",- knowledge: "Knowledge base",+ knowledge: "Knowledge",jobs: "Workflows",artifacts: "Documents",chats: "Chats",@@ -53,6 +55,11 @@ const SEGMENT_LABELS: Record<string, string> = {watchlist: "Watch list",settings: "Settings",status: "Setup status",+ executive: "Your Executive",+ "act-as-me": "Act as me",+ workspace: "Workspace",+ advanced: "Advanced",+ about: "About",guide: "User Guide",clients: "Client Companies",};@@ -69,12 +76,14 @@ function isExempt(pathname: string): boolean {export default function AppShell({ children }: { children: React.ReactNode }) {const pathname = usePathname() ?? "/";const [drawerOpen, setDrawerOpen] = useState(false);+ const { mode, role } = useWorkspace();if (isExempt(pathname)) {return <>{children}</>;}const segments = pathname.split("/").filter(Boolean);+ const hub = hubForPath(pathname, { mode, roleKind: role.role_kind });return (<AskOEProvider>@@ -105,13 +114,14 @@ export default function AppShell({ children }: { children: React.ReactNode }) {onOpenDrawer={() => setDrawerOpen(true)}/><PausedBanner />+ {hub && <HubTabs hub={hub} pathname={pathname} />}{/* The shell slot has overflow-y-auto as a safety net for pagesthat don't manage their own scroll. Pages that DO own ascroll region (h-full + inner overflow-y-auto on <main>)still work — the inner constraint dominates and the outerslot stays a no-op. */}<div className="flex-1 min-h-0 flex flex-col overflow-y-auto">{children}</div>- <MobileBottomNav pathname={pathname} onOpenDrawer={() => setDrawerOpen(true)} />+ <MobileBottomNav pathname={pathname} /></div>{/* Ask OE — page-aware assistant panel, docked right on lg+,@@ -222,11 +232,9 @@ function AskOEButton() {// route gets from the shell, keeping mobile nav consistent everywhere.export function MobileBottomNav({pathname,- onOpenDrawer,hideFrom = "lg",}: {pathname: string;- onOpenDrawer: () => void;// Breakpoint at which the bar disappears, matching the breakpoint where// the host layout's persistent sidebar/rail takes over. The shell rail// appears at `lg`; the chat home's sidebar appears at `md`, so that host@@ -235,37 +243,38 @@ export function MobileBottomNav({hideFrom?: "md" | "lg";}) {const hideClass = hideFrom === "md" ? "md:hidden" : "lg:hidden";- const { mode } = useWorkspace();+ const { mode, role } = useWorkspace();+ // Everything not on the bar (Knowledge, Pulse, Settings, the account+ // menu) is in the sidebar the top bar's menu button opens.return (<navaria-label="Primary"className={`${hideClass} h-[calc(4rem+env(safe-area-inset-bottom))] pb-[env(safe-area-inset-bottom)] border-t border-line bg-surface-elevated flex items-stretch flex-shrink-0`}>- {buildMobilePrimary(mode).map((item) => {- const active = isNavActive(item.href, pathname);+ {buildMobilePrimary({ mode, roleKind: role.role_kind }).map((item) => {+ const active = isDestinationActive(item, pathname);+ const isNew = item.key === "new";return (<Linkkey={item.href}href={item.href}title={item.description}- className={`flex-1 flex flex-col items-center justify-center gap-0.5 transition-colors ${- active ? "text-indigo-300" : "text-fg-muted hover:text-fg"+ aria-current={active ? "page" : undefined}+ className={`flex-1 flex flex-col items-center justify-center gap-1 transition-colors ${+ active ? "text-accent" : "text-fg-muted hover:text-fg"}`}>- <Icon name={item.icon} size="w-5 h-5" />- <span className="text-[10px] font-medium">{item.label}</span>+ {isNew ? (+ <span className="flex h-9 w-9 items-center justify-center rounded-full bg-accent-strong text-white shadow-sm">+ <Icon name={item.icon} size="w-5 h-5" />+ </span>+ ) : (+ <Icon name={item.icon} size="w-6 h-6" />+ )}+ <span className={`text-[11px] font-medium ${isNew ? "sr-only" : ""}`}>{item.label}</span></Link>);})}- <button- type="button"- onClick={onOpenDrawer}- className="flex-1 flex flex-col items-center justify-center gap-0.5 text-fg-muted hover:text-fg transition-colors cursor-pointer"- aria-label="Open menu"- >- <Icon name="menu" size="w-5 h-5" />- <span className="text-[10px] font-medium">More</span>- </button></nav>);}diff --git a/packages/ui/src/components/shell/AppSidebar.tsx b/packages/ui/src/components/shell/AppSidebar.tsxindex 26958c35..17402e83 100644--- a/packages/ui/src/components/shell/AppSidebar.tsx+++ b/packages/ui/src/components/shell/AppSidebar.tsx@@ -4,28 +4,17 @@ import Link from "next/link";import { useEffect, useState } from "react";import BrandMark from "@/components/BrandMark";-import ExecutiveRunSwitch from "@/components/executive/ExecutiveRunSwitch";import Icon, { IconName } from "@/components/Icon";-import { useSessions } from "@/components/sessions/SessionsContext";import UserBadge from "@/components/UserBadge";import { useWorkspace } from "@/components/workspace/WorkspaceContext";import {- BRIEFING_DESCRIPTION,- buildPrimaryNav,- GUIDE_NAV_ITEM,+ buildDestinations,+ isDestinationActive,isNavActive,NEW_CHAT_DESCRIPTION,- PULSE_NAV_ITEM,SETTINGS_NAV_ITEM,} from "@/components/shell/navConfig";import { getReviewStats } from "@/lib/api";-import { formatRelativeTime } from "@/lib/relativeTime";-import { recentWebChats, sessionTitle } from "@/lib/sessionChannel";--// The sidebar keeps history short on purpose: the full, searchable list-// (with Slack/Telegram/Discord conversations) lives on /chats.-const RECENT_LIMIT = 7;-const COLLAPSED_STORAGE_KEY = "oe.sidebar.collapsedGroups";/*** Wiring the chat home passes in. `/` keeps its state in memory (mode,@@ -38,7 +27,6 @@ export interface SidebarHomeControls {activeSessionId?: string;onBriefing: () => void;onNewChat: () => void;- onSelectSession: (sessionId: string) => void;}interface AppSidebarProps {@@ -68,7 +56,6 @@ export default function AppSidebar({companyName,home,}: AppSidebarProps) {- const { sessions } = useSessions();const { mode, role } = useWorkspace();const [reviewBadge, setReviewBadge] = useState(0);@@ -81,10 +68,7 @@ export default function AppSidebar({.catch(() => {});}, [pathname]);- const groups = buildPrimaryNav({ isOnboarded, reviewBadge, mode, roleKind: role.role_kind });- const recent = recentWebChats(sessions, RECENT_LIMIT);-- const briefingActive = home ? home.mode === "briefing" : isNavActive("/", pathname);+ const destinations = buildDestinations({ isOnboarded, reviewBadge, mode, roleKind: role.role_kind });const newChatActive = home ? home.mode === "chat" && home.activeSessionId === undefined : false;return (@@ -97,18 +81,18 @@ export default function AppSidebar({${open ? "translate-x-0" : "-translate-x-full"}`}>- <div className="px-4 py-4 border-b border-line flex items-center justify-between flex-shrink-0">+ <div className="px-4 py-4 flex items-center justify-between flex-shrink-0"><SidebarEntryhref={home ? undefined : "/"}onClick={home ? home.onBriefing : onClose}- ariaLabel="Back to briefing"+ ariaLabel="Back to home"className="flex items-center gap-2.5 min-w-0 text-left text-fg cursor-pointer hover:opacity-80 transition-opacity"><span className="flex-shrink-0"><BrandMark size="sm" /></span><span className="min-w-0">- <span className="block text-sm font-semibold truncate">Open Executive</span>+ <span className="block text-[15px] font-semibold truncate">Open Executive</span>{companyName && (<span className="block text-xs text-fg-muted truncate">{companyName}</span>)}@@ -124,65 +108,52 @@ export default function AppSidebar({</button></div>- <nav className="flex-1 min-h-0 overflow-y-auto px-2 py-3">- <div className="space-y-0.5">- <NavRow- href={home ? undefined : "/?new=1"}- onClick={home ? home.onNewChat : onClose}- label="New chat"- icon="plus"- description={NEW_CHAT_DESCRIPTION}- active={newChatActive}- accent- />- <NavRow- href={home ? undefined : "/"}- onClick={home ? home.onBriefing : onClose}- label="Briefing"- icon="clipboard"- description={BRIEFING_DESCRIPTION}- active={briefingActive}- />- <NavRow- href={PULSE_NAV_ITEM.href}- onClick={onClose}- label={PULSE_NAV_ITEM.label}- icon={PULSE_NAV_ITEM.icon}- description={PULSE_NAV_ITEM.description}- active={isNavActive(PULSE_NAV_ITEM.href, pathname)}- />- </div>-- <NavGroups groups={groups} pathname={pathname} onNavigate={onClose} />+ <div className="px-3 pb-2 flex-shrink-0">+ <SidebarEntry+ href={home ? undefined : "/?new=1"}+ onClick={home ? home.onNewChat : onClose}+ title={NEW_CHAT_DESCRIPTION}+ ariaCurrent={newChatActive}+ className="w-full h-11 rounded-xl bg-accent-strong text-white text-[15px] font-semibold flex items-center justify-center gap-2 shadow-sm hover:bg-accent-strong/90 transition-colors cursor-pointer"+ >+ <Icon name="plus" size="w-5 h-5" />+ New chat+ </SidebarEntry>+ </div>- <RecentChats- recent={recent}- hasAny={sessions.length > 0}- activeSessionId={home?.activeSessionId}- allChatsActive={isNavActive("/chats", pathname)}- onSelect={home?.onSelectSession}- onNavigate={onClose}- />+ {/* The six places. Everything else is a tab inside one of them, or a+ tool on Settings. */}+ <nav aria-label="Main" className="flex-1 min-h-0 overflow-y-auto px-3 py-2">+ <div className="space-y-1">+ {destinations.map((d) => {+ const isHome = d.key === "home";+ const active =+ isHome && home ? home.mode === "briefing" : isDestinationActive(d, pathname);+ return (+ <NavRow+ key={d.key}+ href={isHome && home ? undefined : d.href}+ onClick={isHome && home ? home.onBriefing : onClose}+ label={d.label}+ icon={d.icon}+ description={d.description}+ active={active}+ badge={d.badge}+ />+ );+ })}+ </div></nav>- {/* Footer — the Executive's pause switch (here, in the shared sidebar,- so it is one click away on every route, the chat home included),- User Guide (always-visible help) and Settings (the hub for- admin/power tools), kept out of the primary groups above so- day-to-day nav stays focused. */}- <div className="px-2 pb-1 border-t border-line pt-2 space-y-0.5 flex-shrink-0">- <ExecutiveRunSwitch variant="sidebar" />- {[GUIDE_NAV_ITEM, SETTINGS_NAV_ITEM].map((item) => (- <NavRow- key={item.href}- href={item.href}- onClick={onClose}- label={item.label}- icon={item.icon}- description={item.description}- active={isNavActive(item.href, pathname)}- />- ))}+ <div className="px-3 pb-2 pt-2 border-t border-line flex-shrink-0">+ <NavRow+ href={SETTINGS_NAV_ITEM.href}+ onClick={onClose}+ label={SETTINGS_NAV_ITEM.label}+ icon={SETTINGS_NAV_ITEM.icon}+ description={SETTINGS_NAV_ITEM.description}+ active={isNavActive(SETTINGS_NAV_ITEM.href, pathname)}+ /></div><UserBadge variant="sidebar" />@@ -190,167 +161,6 @@ export default function AppSidebar({);}-function NavGroups({- groups,- pathname,- onNavigate,-}: {- groups: ReturnType<typeof buildPrimaryNav>;- pathname: string;- onNavigate: () => void;-}) {- // Explicit user toggles, persisted so they survive the remount between the- // chat home and the shell. Absent keys fall back to "open the first group- // and the one holding the current page".- const [collapsedOverride, setCollapsedOverride] = useState<Record<string, boolean>>({});-- // Read after mount, not in the initial state, so the prerendered HTML and- // the first client render agree.- useEffect(() => {- try {- const raw = window.localStorage.getItem(COLLAPSED_STORAGE_KEY);- const parsed: unknown = raw ? JSON.parse(raw) : null;- if (parsed && typeof parsed === "object") {- const stored: Record<string, boolean> = {};- for (const [k, v] of Object.entries(parsed)) {- if (typeof v === "boolean") stored[k] = v;- }- setCollapsedOverride(stored);- }- } catch {- // Storage blocked or corrupt — fall back to the defaults.- }- }, []);-- const isCollapsed = (key: string, index: number, holdsActive: boolean) =>- key in collapsedOverride ? collapsedOverride[key] : index !== 0 && !holdsActive;-- const toggle = (key: string, collapsed: boolean) => {- setCollapsedOverride((prev) => {- const next = { ...prev, [key]: !collapsed };- try {- window.localStorage.setItem(COLLAPSED_STORAGE_KEY, JSON.stringify(next));- } catch {- // Not persisted this time; the toggle still applies in memory.- }- return next;- });- };-- return (- <>- {groups.map((group, index) => {- const holdsActive = group.items.some((i) => isNavActive(i.href, pathname));- const collapsed = isCollapsed(group.key, index, holdsActive);- const badgeTotal = group.items.reduce((sum, e) => sum + (e.badge ?? 0), 0);- return (- <div key={group.key} className="pt-3">- <button- type="button"- onClick={() => toggle(group.key, collapsed)}- aria-expanded={!collapsed}- className="w-full flex items-center gap-1.5 px-3 py-1.5 text-fg-subtle hover:text-fg transition-colors cursor-pointer"- >- <Icon- name="chevron-right"- size="w-3 h-3"- className={`transition-transform ${collapsed ? "" : "rotate-90"}`}- />- <span className="text-[11px] font-medium uppercase tracking-wide flex-1 text-left">- {group.label}- </span>- {collapsed && badgeTotal > 0 && <Badge count={badgeTotal} />}- </button>- {!collapsed && (- <div className="space-y-0.5 mt-0.5">- {group.items.map((item) => (- <NavRow- key={item.href}- href={item.href}- onClick={onNavigate}- label={item.label}- icon={item.icon}- description={item.description}- active={isNavActive(item.href, pathname)}- badge={item.badge}- />- ))}- </div>- )}- </div>- );- })}- </>- );-}--function RecentChats({- recent,- hasAny,- activeSessionId,- allChatsActive,- onSelect,- onNavigate,-}: {- recent: ReturnType<typeof recentWebChats>;- hasAny: boolean;- activeSessionId?: string;- allChatsActive: boolean;- /** Present on the chat home; elsewhere rows link to `/?session=<id>`. */- onSelect?: (sessionId: string) => void;- onNavigate: () => void;-}) {- if (!hasAny) return null;- return (- <div className="pt-3">- <div className="flex items-center justify-between px-3 py-1.5">- <span className="text-[11px] font-medium uppercase tracking-wide text-fg-subtle">- Recent- </span>- <Link- href="/chats"- onClick={onNavigate}- title="Every conversation, searchable — including Slack, Telegram and Discord"- className={`text-[11px] transition-colors ${- allChatsActive ? "text-fg font-medium" : "text-fg-subtle hover:text-fg"- }`}- >- All chats- </Link>- </div>- {recent.length === 0 ? (- <p className="px-3 py-1.5 text-xs text-fg-subtle">No web chats yet.</p>- ) : (- <div className="space-y-0.5">- {recent.map((s) => {- const active = activeSessionId === s.session_id;- const when = formatRelativeTime(s.updated_at);- return (- <SidebarEntry- key={s.session_id}- href={onSelect ? undefined : `/?session=${encodeURIComponent(s.session_id)}`}- onClick={() => {- onSelect?.(s.session_id);- onNavigate();- }}- title={when ? `${sessionTitle(s)} · ${when}` : sessionTitle(s)}- ariaCurrent={active}- className={`w-full block text-left px-3 py-2 rounded-lg text-xs truncate transition-colors cursor-pointer ${- active- ? "bg-surface-overlay text-fg"- : "text-fg-muted hover:bg-surface-overlay/60 hover:text-fg"- }`}- >- {sessionTitle(s)}- </SidebarEntry>- );- })}- </div>- )}- </div>- );-}-// A link when `href` is given, otherwise a button — the chat home drives// its in-page entries through callbacks, every other route through URLs.function SidebarEntry({@@ -406,7 +216,6 @@ function NavRow({icon,description,active,- accent,badge,}: {href?: string;@@ -416,26 +225,20 @@ function NavRow({/** Tooltip explaining the destination — shown via `title` on hover. */description?: string;active: boolean;- /** Tints the primary action (New chat). */- accent?: boolean;badge?: number;}) {const tone = active- ? accent- ? "bg-indigo-500/15 text-indigo-200 font-medium"- : "bg-surface-overlay text-fg font-medium"- : accent- ? "text-indigo-300 hover:text-indigo-200 hover:bg-surface-overlay"- : "text-fg-muted hover:text-fg hover:bg-surface-overlay";+ ? "bg-accent/10 text-accent font-semibold"+ : "text-fg-muted font-medium hover:text-fg hover:bg-surface-overlay";return (<SidebarEntryhref={href}onClick={onClick}title={description}ariaCurrent={active}- className={`w-full text-left px-3 py-2 min-h-touch rounded-lg flex items-center gap-2.5 text-sm transition-colors cursor-pointer ${tone}`}+ className={`w-full text-left px-3 h-11 rounded-xl flex items-center gap-3 text-[15px] transition-colors cursor-pointer ${tone}`}>- <Icon name={icon} size="w-4 h-4" />+ <Icon name={icon} size="w-5 h-5" /><span className="flex-1 truncate">{label}</span>{badge != null && badge > 0 && <Badge count={badge} />}</SidebarEntry>@@ -444,7 +247,7 @@ function NavRow({function Badge({ count }: { count: number }) {return (- <span className="text-[10px] bg-amber-500/20 text-amber-400 border border-amber-500/30 rounded-full px-1.5 py-0.5 leading-none font-medium">+ <span className="text-xs bg-amber-500 text-white rounded-full px-2 py-0.5 leading-none font-semibold">{count}</span>);diff --git a/packages/ui/src/components/shell/navConfig.ts b/packages/ui/src/components/shell/navConfig.tsindex d038030a..9bffd41c 100644--- a/packages/ui/src/components/shell/navConfig.ts+++ b/packages/ui/src/components/shell/navConfig.ts@@ -22,12 +22,6 @@ export interface NavItem {badge?: number;}-export interface NavGroup {- key: string;- label: string;- items: NavItem[];-}-interface BuildOpts {/*** When false, the Company-profile entry points at the onboarding@@ -112,113 +106,172 @@ const GOALS_ITEM: NavItem = {description: "What you're working towards, grouped by area — add, update and close goals.",};-function companyGroup(isOnboarded: boolean): NavGroup {- return {- key: "company",- label: "Company",- items: [- {- href: "/departments",- label: "Departments",- icon: "grid",- description: "Org units with goals, an authority level, and a specialist behind each.",- },- {- ...GOALS_ITEM,- description: "Every department's goals in one place — add, update and close them.",- },- {- href: "/people",- label: "People",- icon: "users",- description: PEOPLE_DESCRIPTION,- },- profileItem("company", isOnboarded),- ],- };+// The Company hub's tabs in a team: who's on it, what you're aiming for,+// how it's organised, and the profile.+function companyTabs(isOnboarded: boolean): NavItem[] {+ return [+ { href: "/people", label: "People", icon: "users", description: PEOPLE_DESCRIPTION },+ {+ ...GOALS_ITEM,+ description: "Every department's goals in one place — add, update and close them.",+ },+ {+ href: "/departments",+ label: "Departments",+ icon: "grid",+ description: "Org units with goals, an authority level, and a specialist behind each.",+ },+ profileItem("company", isOnboarded),+ ];}// Solo: the same destinations minus Departments (their goals live on /goals,-// grouped by area), with the copy speaking to one person.-function youGroup(isOnboarded: boolean, roleKind: RoleKind | null): NavGroup {- return {- key: "you",- label: "You",- items: [- GOALS_ITEM,- {- href: "/people",- label: "People",- icon: "users",- description: "The people the Executive knows about — clients, partners, anyone you work with.",- },- profileItem(profileWording("solo", roleKind), isOnboarded),- ],+// grouped by area), with the copy speaking to one person. Goals come first:+// it's the page a team of one visits most.+function youTabs(isOnboarded: boolean, roleKind: RoleKind | null): NavItem[] {+ return [+ GOALS_ITEM,+ {+ href: "/people",+ label: "People",+ icon: "users",+ description: "The people the Executive knows about — clients, partners, anyone you work with.",+ },+ profileItem(profileWording("solo", roleKind), isOnboarded),+ ];+}++const WORK_TABS: NavItem[] = [+ {+ href: "/jobs",+ label: "Workflows",+ icon: "doc",+ description: "Workflows that produce a deliverable, plus the playbooks the Executive follows.",+ },+ {+ href: "/artifacts",+ label: "Documents",+ icon: "book",+ description: "Your library of finished documents — drafts and workflow outputs.",+ },+ {+ href: "/watchlist",+ label: "Watch list",+ icon: "eye",+ description: "External monitors — tickers, feeds, status pages — that raise alerts.",+ },+];++/**+ * A hub: one menu entry that holds several pages, shown as a row of tabs at+ * the top of each of them (components/ui/HubTabs.tsx). The menu entry opens+ * the first tab.+ */+export interface Hub {+ key: "work" | "company" | "you";+ label: string;+ icon: IconName;+ description: string;+ tabs: NavItem[];+}++export function buildHubs({+ isOnboarded = true,+ mode = "team",+ roleKind = null,+}: BuildOpts = {}): Hub[] {+ const work: Hub = {+ key: "work",+ label: "Work",+ icon: "briefcase",+ description: "Workflows, finished documents and the watch list.",+ tabs: WORK_TABS,};+ const people: Hub =+ mode === "solo"+ ? {+ key: "you",+ label: "You",+ icon: "users",+ description: "Your goals, the people you work with, and your profile.",+ tabs: youTabs(isOnboarded, roleKind),+ }+ : {+ key: "company",+ label: "Company",+ icon: "building",+ description: "People, goals, departments and the company profile.",+ tabs: companyTabs(isOnboarded),+ };+ return [work, people];+}++// The hub a page belongs to, or null for a page that isn't in one.+export function hubForPath(pathname: string, opts: BuildOpts = {}): Hub | null {+ return (+ buildHubs(opts).find((hub) => hub.tabs.some((tab) => isNavActive(tab.href, pathname))) ?? null+ );+}++export const PULSE_NAV_ITEM: NavItem = {+ href: "/memories",+ label: "Pulse",+ icon: "activity",+ description:+ "The Executive's memory and heartbeat — what it knows and the rhythm it runs on.",+};++/** A main-menu entry. A hub's entry is active on any of its tabs. */+export interface Destination extends NavItem {+ key: string;+ /** Pages that light this entry up, besides `href` itself. */+ alsoActiveOn?: string[];}-// Day-to-day navigation only. Power/admin tools live on the Settings-// page (see ADVANCED_ITEMS) so this list stays focused.-export function buildPrimaryNav({+// The main menu, the same in the sidebar on every page: six places, then+// Settings at the bottom. Everything else is a tab inside one of them or a+// tool under Settings.+export function buildDestinations({isOnboarded = true,reviewBadge = 0,mode = "team",roleKind = null,-}: BuildOpts = {}): NavGroup[] {+}: BuildOpts = {}): Destination[] {+ const hubs = buildHubs({ isOnboarded, mode, roleKind });+ const hubEntry = (hub: Hub): Destination => ({+ key: hub.key,+ href: hub.tabs[0].href,+ label: hub.label,+ icon: hub.icon,+ description: hub.description,+ alsoActiveOn: hub.tabs.slice(1).map((t) => t.href),+ });return [+ { key: "home", href: "/", label: "Home", icon: "home", description: BRIEFING_DESCRIPTION },{- key: "workspace",- label: "Workspace",- items: [- {- href: "/jobs",- label: "Workflows",- icon: "doc",- description:- "Workflows that produce a deliverable, plus the playbooks the Executive follows.",- },- {- href: "/artifacts",- label: "Documents",- icon: "book",- description: "Your library of finished documents — drafts and workflow outputs.",- },- {- href: "/watchlist",- label: "Watch list",- icon: "eye",- description: "External monitors — tickers, feeds, status pages — that raise alerts.",- },- ],+ key: "chats",+ href: "/chats",+ label: "Chats",+ icon: "chat",+ description: "Every conversation, searchable — including Slack, Telegram and Discord.",},- mode === "solo" ? youGroup(isOnboarded, roleKind) : companyGroup(isOnboarded),+ ...hubs.map(hubEntry),{key: "knowledge",+ href: "/knowledge",label: "Knowledge",- items: [- {- href: "/knowledge",- label: "Knowledge base",- icon: "book",- badge: reviewBadge,- description:- "Upload company documents so the Executive can ground its answers in your context, and approve what it relies on.",- },- ],+ icon: "book",+ badge: reviewBadge,+ description:+ "Upload company documents so the Executive can ground its answers in your context, and approve what it relies on.",},+ { key: "pulse", ...PULSE_NAV_ITEM },];}-// Pinned, always-visible top-level destination — rendered as a standalone link-// directly beneath Briefing in BOTH navs (rail + chat-home sidebar), the same-// way Briefing is. Kept here as the single source so the two navs stay in sync.-export const PULSE_NAV_ITEM: NavItem = {- href: "/memories",- label: "Pulse",- icon: "activity",- description:- "The Executive's memory and heartbeat — what it knows and the rhythm it runs on.",-};+export function isDestinationActive(dest: Destination, pathname: string): boolean {+ return [dest.href, ...(dest.alsoActiveOn ?? [])].some((href) => isNavActive(href, pathname));+}// Single rail/sidebar entry that leads to the Settings hub.export const SETTINGS_NAV_ITEM: NavItem = {@@ -228,8 +281,8 @@ export const SETTINGS_NAV_ITEM: NavItem = {description: "Configuration, diagnostics, and power-user tools.",};-// User Guide — pinned next to Settings in both nav footers so help is-// always one click away (it also stays listed on the Settings hub).+// User Guide — in the account menu at the foot of the sidebar so help is+// always one click away (it also stays listed under Settings → Advanced).export const GUIDE_NAV_ITEM: NavItem = {href: "/guide",label: "User Guide",@@ -244,8 +297,8 @@ export const NEW_CHAT_DESCRIPTION = "Start a fresh conversation with the Executiexport const BRIEFING_DESCRIPTION ="Land on a daily brief of what's happened and what needs you.";-// Where a Settings tool sits on that page: what you open to check on the-// install, to change how it runs, or to learn how it works.+// Where a Settings tool sits on Settings → Advanced: what you open to check+// on the install, to change how it runs, or to learn how it works.export type AdvancedGroupKey = "diagnose" | "configure" | "learn";export interface AdvancedItem extends NavItem {@@ -258,7 +311,7 @@ export const ADVANCED_GROUPS: { key: AdvancedGroupKey; label: string }[] = [{ key: "learn", label: "Learn" },];-// Admin / power-user tools surfaced on the Settings page rather than+// Admin / power-user tools surfaced on Settings → Advanced rather than// in the primary nav — they aren't part of the day-to-day loop.export const ADVANCED_ITEMS: AdvancedItem[] = [{@@ -326,7 +379,7 @@ export const ADVANCED_ITEMS: AdvancedItem[] = [},];-// The tools as the Settings page lists them: by group, in ADVANCED_GROUPS+// The tools as Settings → Advanced lists them: by group, in ADVANCED_GROUPS// order, each keeping its ADVANCED_ITEMS order within the group.export function advancedItemsByGroup(): {key: AdvancedGroupKey;@@ -339,51 +392,97 @@ export function advancedItemsByGroup(): {}));}-// The Settings page's sections in page order. Its in-page nav and the page-// itself both read this list, so the two can't drift; the ids are the-// hashes a link can land on (`/settings#workspace`). "act-as-me" is only-// on the page for the owner — the page drops it when the card is hidden.-export type SettingsSectionId = "executive" | "workspace" | "act-as-me" | "tools" | "about";+// The Settings hub's tiles, in hub order. Each opens a short page of its+// own at `href`. "act-as-me" shows only for someone who can have Act as me+// (the hub drops it when the card is hidden). `hashes` are the anchors the+// old one-page Settings used (`/settings#workspace`): links that still+// carry one land on the matching page (see settingsPageForHash).+export type SettingsPageId = "executive" | "act-as-me" | "workspace" | "advanced" | "about";-export interface SettingsSectionDef {- id: SettingsSectionId;+export interface SettingsPageDef {+ id: SettingsPageId;label: string;+ href: string;+ icon: IconName;+ /** What's on the page, as the hub tile says it. */+ description: string;+ hashes: string[];}-export const SETTINGS_SECTIONS: SettingsSectionDef[] = [- { id: "executive", label: "Executive" },- { id: "workspace", label: "Workspace" },- { id: "act-as-me", label: "Act as me" },- { id: "tools", label: "Tools" },- { id: "about", label: "About" },+export const SETTINGS_PAGES: SettingsPageDef[] = [+ {+ id: "executive",+ label: "Your Executive",+ href: "/settings/executive",+ icon: "cog",+ description: "Pause or resume its own work, and the voice it answers in.",+ hashes: ["executive"],+ },+ {+ id: "act-as-me",+ label: "Act as me",+ href: "/settings/act-as-me",+ icon: "mail",+ description: "Your mailbox, drafts written as you, and how you write.",+ hashes: ["act-as-me"],+ },+ {+ id: "workspace",+ label: "Workspace",+ href: "/settings/workspace",+ icon: "building",+ description: "Just you or your team, time zone, meeting booking, email domains.",+ hashes: ["workspace"],+ },+ {+ id: "advanced",+ label: "Advanced",+ href: "/settings/advanced",+ icon: "grid",+ description: "Agent Council, audit log, token usage, setup status, simulator, guide.",+ // The old Tools section, and the anchors of its groups.+ hashes: ["tools", ...ADVANCED_GROUPS.map((g) => `tools-${g.key}`)],+ },+ {+ id: "about",+ label: "About",+ href: "/settings/about",+ icon: "info",+ description: "The version this install runs, and whether a newer one is out.",+ hashes: ["about"],+ },];-// Anchors the mobile bottom nav. ≤5 per Material guidance; "More" opens-// the drawer with the full menu. `/` lands on the briefing surface. Solo-// swaps People for Goals — the page a team of one visits most.-export function buildMobilePrimary(mode: WorkspaceMode = "team"): NavItem[] {- return [- { href: "/", label: "Briefing", icon: "clipboard", description: BRIEFING_DESCRIPTION },- PULSE_NAV_ITEM,- // `?new=1` signals the chat home to reset to a fresh chat and strip- // the query — see the effect in app/page.tsx.- { href: "/?new=1", label: "New chat", icon: "plus", description: NEW_CHAT_DESCRIPTION },- mode === "solo"- ? GOALS_ITEM- : {- href: "/people",- label: "People",- icon: "users",- description: PEOPLE_DESCRIPTION,- },- {- href: "/jobs",- label: "Workflows",- icon: "doc",- description:- "Multi-step workflows that produce a deliverable — board prep, GTM plans, reviews.",- },- ];+// The page an old `/settings#<hash>` link meant, or null for no hash or one+// that never named a section. Takes the hash with or without its "#".+export function settingsPageForHash(hash: string): SettingsPageDef | null {+ let id = hash.replace(/^#/, "");+ try {+ id = decodeURIComponent(id);+ } catch {+ // A malformed escape: match it as typed.+ }+ id = id.trim();+ if (!id) return null;+ return SETTINGS_PAGES.find((p) => p.hashes.includes(id)) ?? null;+}++// The phone's bottom bar: five, with New chat in the middle. Knowledge,+// Pulse and Settings are in the menu the top bar's button opens.+// `?new=1` signals the chat home to reset to a fresh chat and strip the+// query — see the effect in app/page.tsx.+export function buildMobilePrimary(opts: BuildOpts = {}): Destination[] {+ const all = buildDestinations(opts);+ const pick = (key: string) => all.find((d) => d.key === key)!;+ const newChat: Destination = {+ key: "new",+ href: "/?new=1",+ label: "New chat",+ icon: "plus",+ description: NEW_CHAT_DESCRIPTION,+ };+ const people = all.find((d) => d.key === "company" || d.key === "you")!;+ return [pick("home"), pick("chats"), newChat, pick("work"), people];}// Is `href` the active destination for `pathname`? Active on an exact matchdiff --git a/packages/ui/src/components/ui/Button.tsx b/packages/ui/src/components/ui/Button.tsxnew file mode 100644index 00000000..7d720c32--- /dev/null+++ b/packages/ui/src/components/ui/Button.tsx@@ -0,0 +1,44 @@+import type { ButtonHTMLAttributes } from "react";++// The app's buttons. One primary per card or screen; everything else is+// secondary or ghost, and rare or destructive actions go in an OverflowMenu.+// `buttonClass` is exported so a <Link> or <a> can look like a button.++export type ButtonVariant = "primary" | "secondary" | "ghost" | "danger";+export type ButtonSize = "md" | "sm";++const BASE =+ "inline-flex items-center justify-center gap-2 rounded-xl font-semibold whitespace-nowrap transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60 disabled:opacity-50 disabled:cursor-not-allowed";++const SIZES: Record<ButtonSize, string> = {+ md: "h-11 px-5 text-[15px]",+ sm: "h-9 px-3.5 text-sm",+};++const VARIANTS: Record<ButtonVariant, string> = {+ primary: "bg-accent-strong text-white hover:bg-accent-strong/90 shadow-sm",+ secondary: "bg-surface-overlay text-fg border border-line hover:bg-surface-hover",+ ghost: "text-fg-muted hover:text-fg hover:bg-surface-overlay",+ danger: "text-rose-500 border border-line hover:bg-rose-500/10",+};++export function buttonClass(+ variant: ButtonVariant = "secondary",+ size: ButtonSize = "md",+ extra = "",+): string {+ return `${BASE} ${SIZES[size]} ${VARIANTS[variant]} ${extra}`.trim();+}++export default function Button({+ variant = "secondary",+ size = "md",+ className = "",+ type = "button",+ ...rest+}: ButtonHTMLAttributes<HTMLButtonElement> & {+ variant?: ButtonVariant;+ size?: ButtonSize;+}) {+ return <button type={type} className={buttonClass(variant, size, className)} {...rest} />;+}diff --git a/packages/ui/src/components/ui/HubTabs.tsx b/packages/ui/src/components/ui/HubTabs.tsxnew file mode 100644index 00000000..2297f9fd--- /dev/null+++ b/packages/ui/src/components/ui/HubTabs.tsx@@ -0,0 +1,38 @@+"use client";++import Link from "next/link";++import type { Hub } from "@/components/shell/navConfig";+import { isNavActive } from "@/components/shell/navConfig";++// The tab row at the top of every page in a hub (Work, Company / You), so+// the hub's pages read as one place. The shell renders it; pages don't.+export default function HubTabs({ hub, pathname }: { hub: Hub; pathname: string }) {+ return (+ <nav+ aria-label={hub.label}+ className="flex-shrink-0 border-b border-line px-4 sm:px-6 overflow-x-auto"+ >+ <div className="flex gap-1 py-2">+ {hub.tabs.map((tab) => {+ const active = isNavActive(tab.href, pathname);+ return (+ <Link+ key={tab.href}+ href={tab.href}+ title={tab.description}+ aria-current={active ? "page" : undefined}+ className={`flex-shrink-0 rounded-xl px-4 py-2 text-[15px] font-medium transition-colors ${+ active+ ? "bg-accent/10 text-accent"+ : "text-fg-muted hover:text-fg hover:bg-surface-overlay"+ }`}+ >+ {tab.label}+ </Link>+ );+ })}+ </div>+ </nav>+ );+}diff --git a/packages/ui/src/components/ui/OverflowMenu.tsx b/packages/ui/src/components/ui/OverflowMenu.tsxnew file mode 100644index 00000000..32f8d8b0--- /dev/null+++ b/packages/ui/src/components/ui/OverflowMenu.tsx@@ -0,0 +1,192 @@+"use client";++import Link from "next/link";+import { useEffect, useId, useRef, useState } from "react";++import { buttonClass } from "@/components/ui/Button";+import { nextMenuIndex } from "@/lib/menuNav";++// The ⋯ menu: where a card's rarer actions live (edit, dismiss, delete...)+// so the card shows one primary button. Items are buttons or links.+// Keyboard: Enter/Space or ArrowDown opens it, arrows move, Escape closes+// and returns focus to the ⋯ button. A click outside closes it.+// With `trigger`, the button shows that text instead of ⋯ (e.g. a+// "Download" menu of formats).++export interface OverflowItem {+ label: string;+ onSelect?: () => void;+ href?: string;+ /** Opens in a new tab (links only). */+ external?: boolean;+ danger?: boolean;+ disabled?: boolean;+}++export default function OverflowMenu({+ items,+ label = "More actions",+ size = "md",+ align = "right",+ placement = "down",+ icon,+ trigger,+}: {+ items: OverflowItem[];+ /** Accessible name of the ⋯ button. */+ label?: string;+ size?: "md" | "sm";+ align?: "left" | "right";+ /** "up" for a menu at the bottom of the screen (the account menu). */+ placement?: "down" | "up";+ /** Replaces the ⋯ glyph, e.g. a + for a composer's attach menu. */+ icon?: React.ReactNode;+ /** Text for the button in place of ⋯, styled as a secondary button. */+ trigger?: string;+}) {+ const [open, setOpen] = useState(false);+ const [focus, setFocus] = useState(-1);+ const rootRef = useRef<HTMLDivElement>(null);+ const buttonRef = useRef<HTMLButtonElement>(null);+ const itemRefs = useRef<(HTMLElement | null)[]>([]);+ const menuId = useId();++ const close = (returnFocus: boolean) => {+ setOpen(false);+ setFocus(-1);+ if (returnFocus) buttonRef.current?.focus();+ };++ useEffect(() => {+ if (!open) return;+ const onDown = (e: PointerEvent) => {+ if (!rootRef.current?.contains(e.target as Node)) close(false);+ };+ document.addEventListener("pointerdown", onDown);+ return () => document.removeEventListener("pointerdown", onDown);+ }, [open]);++ useEffect(() => {+ if (open && focus >= 0) itemRefs.current[focus]?.focus();+ }, [open, focus]);++ if (items.length === 0) return null;+ const disabled = items.map((i) => !!i.disabled);++ const onKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === "Escape") {+ if (open) {+ e.stopPropagation();+ close(true);+ }+ return;+ }+ if (e.key === "Tab") {+ close(false);+ return;+ }+ if (!open && (e.key === "ArrowDown" || e.key === "ArrowUp")) {+ e.preventDefault();+ setOpen(true);+ setFocus(nextMenuIndex(-1, e.key, disabled));+ return;+ }+ if (open && ["ArrowDown", "ArrowUp", "Home", "End"].includes(e.key)) {+ e.preventDefault();+ setFocus((f) => nextMenuIndex(f, e.key, disabled));+ }+ };++ const dim = size === "sm" ? "h-9 w-9" : "h-11 w-11";+ const itemClass = (item: OverflowItem) =>+ `flex w-full items-center px-3.5 py-2.5 text-left text-[15px] rounded-lg transition-colors focus:outline-none focus-visible:bg-surface-hover disabled:opacity-40 disabled:cursor-not-allowed ${+ item.danger ? "text-rose-500 hover:bg-rose-500/10" : "text-fg hover:bg-surface-hover"+ }`;++ return (+ <div ref={rootRef} className="relative inline-flex" onKeyDown={onKeyDown}>+ <button+ ref={buttonRef}+ type="button"+ aria-label={trigger ? undefined : label}+ title={trigger ? undefined : label}+ aria-haspopup="menu"+ aria-expanded={open}+ aria-controls={open ? menuId : undefined}+ onClick={() => (open ? close(false) : setOpen(true))}+ className={+ trigger+ ? buttonClass("secondary", size)+ : `${dim} inline-flex items-center justify-center rounded-xl text-fg-muted hover:text-fg hover:bg-surface-overlay border border-transparent hover:border-line transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60`+ }+ >+ {trigger ? (+ <>+ {trigger}+ <svg aria-hidden="true" viewBox="0 0 20 20" className="h-4 w-4" fill="currentColor">+ <path d="M5.3 7.3a1 1 0 0 1 1.4 0L10 10.6l3.3-3.3a1 1 0 1 1 1.4 1.4l-4 4a1 1 0 0 1-1.4 0l-4-4a1 1 0 0 1 0-1.4z" />+ </svg>+ </>+ ) : icon ? (+ icon+ ) : (+ <svg aria-hidden="true" viewBox="0 0 24 24" className="h-5 w-5" fill="currentColor">+ <circle cx="5" cy="12" r="1.8" />+ <circle cx="12" cy="12" r="1.8" />+ <circle cx="19" cy="12" r="1.8" />+ </svg>+ )}+ </button>+ {open && (+ <div+ id={menuId}+ role="menu"+ aria-label={label}+ className={`absolute z-40 min-w-[13rem] max-w-[calc(100vw-2rem)] rounded-xl border border-line bg-surface-elevated p-1.5 shadow-xl ${+ align === "right" ? "right-0" : "left-0"+ } ${placement === "up" ? "bottom-full mb-1.5" : "top-full mt-1.5"}`}+ >+ {items.map((item, i) => {+ const setRef = (el: HTMLElement | null) => {+ itemRefs.current[i] = el;+ };+ if (item.href && !item.disabled) {+ return (+ <Link+ key={item.label}+ ref={setRef}+ role="menuitem"+ tabIndex={-1}+ href={item.href}+ target={item.external ? "_blank" : undefined}+ rel={item.external ? "noopener noreferrer" : undefined}+ onClick={() => close(false)}+ className={itemClass(item)}+ >+ {item.label}+ </Link>+ );+ }+ return (+ <button+ key={item.label}+ ref={setRef}+ type="button"+ role="menuitem"+ tabIndex={-1}+ disabled={item.disabled}+ onClick={() => {+ close(true);+ item.onSelect?.();+ }}+ className={itemClass(item)}+ >+ {item.label}+ </button>+ );+ })}+ </div>+ )}+ </div>+ );+}diff --git a/packages/ui/src/components/ui/SectionTabs.tsx b/packages/ui/src/components/ui/SectionTabs.tsxnew file mode 100644index 00000000..c8ba22c2--- /dev/null+++ b/packages/ui/src/components/ui/SectionTabs.tsx@@ -0,0 +1,130 @@+"use client";++import { useEffect, useRef } from "react";++// A row of tabs inside one page or panel (a person's page, a settings form+// split into short sections, the Pulse and Knowledge views), as opposed to+// HubTabs, which links pages. Pill style, 40px tall, with an optional count+// or badge per tab; too many tabs for a phone scroll sideways inside the row,+// never the page. The caller renders the active tab's content; when it also+// spreads `sectionPanelProps(idBase, active)` on it, it passes the same+// `idBase` (from useId) here so tab and panel point at each other. Arrow+// keys, Home and End move between tabs.++export interface SectionTab<T extends string> {+ id: T;+ label: string;+ /** Shown after the label, e.g. how many rows the tab lists. */+ count?: number;+ /** A count drawn as a pill after the label; null or undefined shows none. */+ badge?: number | null;+ /** "attention" draws the badge in amber, for things waiting on you. */+ badgeTone?: "muted" | "attention";+}++export default function SectionTabs<T extends string>({+ tabs,+ active,+ onChange,+ label,+ idBase,+ disabled = false,+ className = "",+}: {+ tabs: SectionTab<T>[];+ active: T;+ onChange: (id: T) => void;+ /** Accessible name of the tab row. */+ label: string;+ /** Shared with the content's `sectionPanelProps`, so the two point at each+ * other. Leave it out when the content carries no panel attributes. */+ idBase?: string;+ disabled?: boolean;+ className?: string;+}) {+ const base = idBase;+ const refs = useRef<(HTMLButtonElement | null)[]>([]);+ const rowRef = useRef<HTMLDivElement>(null);++ // A row that scrolls sideways (a phone) keeps the active tab in view, so a+ // deep link to a later tab (`/memories?tab=corrections`) shows it selected.+ const activeIndex = tabs.findIndex((t) => t.id === active);+ useEffect(() => {+ const row = rowRef.current;+ const el = refs.current[activeIndex];+ if (!row || !el || row.scrollWidth <= row.clientWidth) return;+ if (el.offsetLeft < row.scrollLeft || el.offsetLeft + el.offsetWidth > row.scrollLeft + row.clientWidth) {+ row.scrollLeft = el.offsetLeft - (row.clientWidth - el.offsetWidth) / 2;+ }+ }, [activeIndex]);++ const onKeyDown = (e: React.KeyboardEvent, i: number) => {+ const last = tabs.length - 1;+ const next =+ e.key === "ArrowRight" ? (i === last ? 0 : i + 1)+ : e.key === "ArrowLeft" ? (i === 0 ? last : i - 1)+ : e.key === "Home" ? 0+ : e.key === "End" ? last+ : -1;+ if (next < 0) return;+ e.preventDefault();+ refs.current[next]?.focus();+ onChange(tabs[next].id);+ };++ return (+ <div+ ref={rowRef}+ role="tablist"+ aria-label={label}+ className={`relative inline-flex max-w-full gap-1 overflow-x-auto rounded-2xl bg-surface-overlay p-1 ${className}`}+ >+ {tabs.map((tab, i) => {+ const selected = tab.id === active;+ return (+ <button+ key={tab.id}+ ref={(el) => {+ refs.current[i] = el;+ }}+ type="button"+ role="tab"+ id={base ? `${base}-tab-${tab.id}` : undefined}+ aria-selected={selected}+ aria-controls={base ? `${base}-panel-${tab.id}` : undefined}+ tabIndex={selected ? 0 : -1}+ disabled={disabled}+ onClick={() => onChange(tab.id)}+ onKeyDown={(e) => onKeyDown(e, i)}+ className={`flex h-10 flex-shrink-0 items-center gap-2 rounded-xl px-4 text-[15px] font-medium whitespace-nowrap transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60 disabled:opacity-50 ${+ selected+ ? "bg-surface-elevated text-fg shadow-sm"+ : "text-fg-muted hover:bg-surface-hover hover:text-fg"+ }`}+ >+ {tab.label}+ {tab.count !== undefined && (+ <span className={`text-sm ${selected ? "text-fg-muted" : "text-fg-subtle"}`}>{tab.count}</span>+ )}+ {tab.badge != null && (+ <span+ className={`rounded-full px-2 py-0.5 text-xs font-semibold tabular-nums ${+ tab.badgeTone === "attention" && tab.badge > 0+ ? "bg-amber-500/15 text-amber-500"+ : "bg-surface-input text-fg-muted"+ }`}+ >+ {tab.badge}+ </span>+ )}+ </button>+ );+ })}+ </div>+ );+}++/** The attributes for the active tab's content (its tab's `aria-controls`). */+export function sectionPanelProps(idBase: string, id: string) {+ return { role: "tabpanel", id: `${idBase}-panel-${id}`, "aria-labelledby": `${idBase}-tab-${id}` };+}diff --git a/packages/ui/src/components/ui/SidePanel.tsx b/packages/ui/src/components/ui/SidePanel.tsxnew file mode 100644index 00000000..13317893--- /dev/null+++ b/packages/ui/src/components/ui/SidePanel.tsx@@ -0,0 +1,100 @@+"use client";++import { useEffect, useId, useRef } from "react";++import Icon from "@/components/Icon";++// A panel that slides in from the right over the page: where a summary tile+// or an app tile opens its full list or settings, so the screen behind stays+// short. Full screen on phones. Escape, the close button or a click on the+// dimmed page closes it; focus moves into it on open and back on close.+export default function SidePanel({+ open,+ onClose,+ title,+ subtitle,+ width = "md",+ children,+ footer,+}: {+ open: boolean;+ onClose: () => void;+ title: React.ReactNode;+ subtitle?: React.ReactNode;+ width?: "md" | "lg";+ children: React.ReactNode;+ /** Pinned under the scrolling body, e.g. Save / Cancel. */+ footer?: React.ReactNode;+}) {+ const panelRef = useRef<HTMLDivElement>(null);+ const titleId = useId();+ const onCloseRef = useRef(onClose);+ useEffect(() => {+ onCloseRef.current = onClose;+ });++ useEffect(() => {+ if (!open) return;+ const opener = document.activeElement as HTMLElement | null;+ panelRef.current?.focus();+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape" && !e.defaultPrevented) {+ e.preventDefault();+ onCloseRef.current();+ }+ };+ document.addEventListener("keydown", onKey);+ const overflow = document.body.style.overflow;+ document.body.style.overflow = "hidden";+ return () => {+ document.removeEventListener("keydown", onKey);+ document.body.style.overflow = overflow;+ opener?.focus?.();+ };+ }, [open]);++ if (!open) return null;++ return (+ <div className="fixed inset-0 z-50 flex justify-end">+ <div aria-hidden="true" className="absolute inset-0 bg-black/40" onClick={onClose} />+ <div+ ref={panelRef}+ role="dialog"+ aria-modal="true"+ aria-labelledby={titleId}+ tabIndex={-1}+ className={`relative flex h-full w-full flex-col bg-surface-elevated shadow-2xl outline-none sm:border-l sm:border-line ${+ width === "lg" ? "sm:max-w-2xl" : "sm:max-w-lg"+ }`}+ style={{ paddingTop: "env(safe-area-inset-top, 0px)" }}+ >+ <div className="flex items-start gap-3 border-b border-line px-5 py-4">+ <div className="min-w-0 flex-1">+ <h2 id={titleId} className="text-lg font-semibold text-fg leading-tight">+ {title}+ </h2>+ {subtitle && <p className="mt-1 text-sm text-fg-muted">{subtitle}</p>}+ </div>+ <button+ type="button"+ onClick={onClose}+ aria-label="Close"+ className="-mr-1 inline-flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl text-fg-muted hover:bg-surface-overlay hover:text-fg"+ >+ <Icon name="close" className="h-5 w-5" />+ </button>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">{children}</div>+ {footer && (+ <div+ className="border-t border-line px-5 py-3"+ style={{ paddingBottom: "max(0.75rem, env(safe-area-inset-bottom, 0px))" }}+ >+ {footer}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/lib/briefingSummary.ts b/packages/ui/src/lib/briefingSummary.tsnew file mode 100644index 00000000..dbb9b091--- /dev/null+++ b/packages/ui/src/lib/briefingSummary.ts@@ -0,0 +1,123 @@+// The Home screen's wording: the greeting, the one-line summary that replaced+// the row of status pills, and the single status chip a collapsed proposal+// card keeps. Kept apart from the components so `npm test` can check it (see+// scripts/briefingSummary.test.mjs). No imports, so the test can load this+// under `node --experimental-strip-types`.++/** "Good morning" before noon, "Good afternoon" until 6pm, then "Good evening". */+export function greeting(firstName: string | undefined, now: Date = new Date()): string {+ const h = now.getHours();+ const part = h < 12 ? "morning" : h < 18 ? "afternoon" : "evening";+ const name = firstName?.trim();+ return name ? `Good ${part}, ${name}` : `Good ${part}`;+}++/** Where a summary phrase leads: a lane on the page, one of the tiles' side+ * panels, or another route. */+export type SummaryTarget =+ | { kind: "needsYou" }+ | { kind: "panel"; panel: "handled" | "people" | "departments" | "inFlight" | "monitoring" }+ | { kind: "href"; href: string };++export interface SummaryPart {+ text: string;+ target: SummaryTarget;+}++export interface SummaryCounts {+ needsYou: number;+ handledOvernight: number;+ peopleOverdue: number;+ peopleNeedReply: number;+ deptAtRisk: number;+ /** Solo only: at-risk + off-track goals, which have no tile on the page. */+ goalsAtRisk?: number;+ inFlight: number;+ monitoring: number;+}++const plural = (n: number, one: string, many: string) => (n === 1 ? one : many);++/** The summary under the greeting, as phrases in the order they are read:+ * what needs you first, then what the Executive did on its own (trust and+ * relief), then the rest by urgency. Zero counts are dropped; an empty list+ * means all clear. Each phrase opens the detail it counts. */+export function briefingSummary(c: SummaryCounts): SummaryPart[] {+ const parts: SummaryPart[] = [];+ if (c.needsYou > 0)+ parts.push({+ text: `${c.needsYou} ${plural(c.needsYou, "thing needs", "things need")} you`,+ target: { kind: "needsYou" },+ });+ if (c.handledOvernight > 0)+ parts.push({+ text: `The Executive handled ${c.handledOvernight} overnight`,+ target: { kind: "panel", panel: "handled" },+ });+ if (c.peopleOverdue > 0)+ parts.push({ text: `${c.peopleOverdue} overdue`, target: { kind: "panel", panel: "people" } });+ if (c.peopleNeedReply > 0)+ parts.push({+ text: `${c.peopleNeedReply} awaiting reply`,+ target: { kind: "panel", panel: "people" },+ });+ if (c.deptAtRisk > 0)+ parts.push({+ text: `${c.deptAtRisk} ${plural(c.deptAtRisk, "department", "departments")} at risk`,+ target: { kind: "panel", panel: "departments" },+ });+ if (c.goalsAtRisk && c.goalsAtRisk > 0)+ parts.push({+ text: `${c.goalsAtRisk} ${plural(c.goalsAtRisk, "goal", "goals")} at risk`,+ target: { kind: "href", href: "/goals" },+ });+ if (c.inFlight > 0)+ parts.push({ text: `${c.inFlight} in flight`, target: { kind: "panel", panel: "inFlight" } });+ if (c.monitoring > 0)+ parts.push({+ text: `${c.monitoring} ${plural(c.monitoring, "signal", "signals")} monitored`,+ target: { kind: "panel", panel: "monitoring" },+ });+ return parts;+}++/** Compact age label ("3h", "9d") for a card chip; "" for an unparseable stamp. */+export function ageLabel(iso: string | null | undefined, now: Date = new Date()): string {+ if (!iso) return "";+ const t = Date.parse(iso);+ if (Number.isNaN(t)) return "";+ const mins = Math.max(0, Math.round((now.getTime() - t) / 60000));+ if (mins < 60) return `${mins}m`;+ const hours = Math.round(mins / 60);+ if (hours < 48) return `${hours}h`;+ return `${Math.round(hours / 24)}d`;+}++/** Whole days between now and an ISO stamp: 0 = due within the day, negative =+ * past (floor, so an 11-hour-old deadline is -1 → "overdue", never "due+ * today"). null if unparseable. */+export function daysUntil(iso: string | null | undefined, now: Date = new Date()): number | null {+ if (!iso) return null;+ const t = Date.parse(iso);+ if (Number.isNaN(t)) return null;+ return Math.floor((t - now.getTime()) / 86400000);+}++export type ChipTone = "rose" | "amber" | "neutral";++/** The one status chip a collapsed proposal card shows: its deadline when it+ * has one (overdue in red), else "Likely stale" when the review says so, else+ * how long it has waited. The full chip row shows when the card is opened. */+export function proposalStatusChip(+ p: { due_at?: string | null; review_verdict?: string; created_at: string },+ now: Date = new Date(),+): { label: string; tone: ChipTone } | null {+ const dueIn = daysUntil(p.due_at, now);+ if (dueIn != null) {+ if (dueIn < 0) return { label: "Overdue", tone: "rose" };+ return { label: dueIn === 0 ? "Due today" : `Due in ${dueIn}d`, tone: "amber" };+ }+ if ((p.review_verdict ?? "") === "likely_stale") return { label: "Likely stale", tone: "amber" };+ const age = ageLabel(p.created_at, now);+ return age ? { label: `${age} old`, tone: "neutral" } : null;+}diff --git a/packages/ui/src/lib/councilCards.ts b/packages/ui/src/lib/councilCards.tsnew file mode 100644index 00000000..eb516408--- /dev/null+++ b/packages/ui/src/lib/councilCards.ts@@ -0,0 +1,119 @@+// What an Agent Council card shows for one agent (app/council/page.tsx):+// a short name, its area in plain words, initials for the avatar, a short+// model name and one status line. Kept pure so `npm test` can check it+// (scripts/councilCards.test.mjs).++// Plain-word areas for the built-in agents. An agent missing here (a new+// specialist) falls back to its role's grouping or its knowledge domains.+const AREAS: Record<string, string> = {+ executive: "Leads every answer",+ cso: "Strategy",+ cfo: "Finance",+ chro: "People",+ gc: "Legal",+ coo: "Operations",+ cmo: "Marketing",+ cpo: "Product",+ sales: "Sales",+ board_comms: "Board and investors",+ triage: "Sorts incoming messages",+ quality_judge: "Reviews committee answers",+ utility_fast: "Quick checks, titles and replies",+ research: "Background research scans",+ fixture_generator: "Builds sample companies",+ engagement_intake: "Drafts client companies",+ onboarding_interviewer: "Company setup interview",+ workflow_designer: "Designs new workflows",+ workflow_actor: "Runs workflow steps",+};++const DOMAIN_WORDS: Record<string, string> = { hr: "people" };++const capitalize = (s: string) => (s ? s[0].toUpperCase() + s.slice(1) : s);++// "Utility · Fast model (gates, titles, decision parsing)" → group "Utility",+// name "Fast model", note "gates, titles, decision parsing".+function splitRole(role: string): { group: string | null; name: string; note: string | null } {+ let rest = role.trim();+ let group: string | null = null;+ const dot = rest.indexOf(" · ");+ if (dot > 0) {+ group = rest.slice(0, dot).trim();+ rest = rest.slice(dot + 3).trim();+ }+ let note: string | null = null;+ const paren = rest.match(/^(.*?)\s*\((.+)\)\s*$/);+ if (paren && paren[1]) {+ rest = paren[1];+ note = paren[2];+ }+ return { group, name: rest || role.trim(), note };+}++/** The card's title: the role without its "Utility ·" group or (note). */+export function agentDisplayName(role: string): string {+ return splitRole(role).name;+}++/** What the agent covers, in a few plain words. */+export function agentArea(agent: { name: string; role: string; domains: string[] }): string {+ const known = AREAS[agent.name];+ if (known) return known;+ const { group, note } = splitRole(agent.role);+ if (note) return capitalize(note);+ if (agent.domains.length > 0) {+ return capitalize(agent.domains.map((d) => DOMAIN_WORDS[d] ?? d.replace(/_/g, " ")).join(" and "));+ }+ return group ?? "Specialist";+}++const SMALL_WORDS = new Set(["of", "the", "and", "&", "for", "a", "an"]);++/** Two letters for the avatar: "Chief Financial Officer" → "CF", "Executive" → "EX". */+export function agentInitials(name: string): string {+ const words = name+ .split(/[\s/·-]+/)+ .map((w) => w.replace(/[^\p{L}\p{N}]/gu, ""))+ .filter((w) => w && !SMALL_WORDS.has(w.toLowerCase()));+ if (words.length === 0) return "?";+ if (words.length === 1) return words[0].slice(0, 2).toUpperCase();+ return (words[0][0] + words[1][0]).toUpperCase();+}++/**+ * A short model name: "Sonnet 5" for claude-sonnet-5, "Opus 5.5" for+ * claude-opus-5-5 or anthropic/claude-opus-5.5, "gpt-5" for openai/gpt-5.+ * `label` is the picker's label for the id when known ("Claude Sonnet 5").+ */+export function shortModelName(id: string, label?: string): string {+ if (label && label !== id) return label.replace(/^Claude\s+/i, "");+ const bare = id.replace(/^anthropic\//i, "");+ const claude = bare.match(/^claude-([a-z]+)-([0-9][0-9.-]*?)(?:-\d{8})?$/i);+ if (claude) return `${capitalize(claude[1].toLowerCase())} ${claude[2].replace(/-/g, ".")}`;+ const slash = bare.lastIndexOf("/");+ return slash >= 0 ? bare.slice(slash + 1) : bare;+}++// Override fields that only a Quality preset also writes.+const PRESET_FIELDS = new Set(["model", "use_deep_reasoning"]);++export type AgentCardStatus = "instructions" | "custom-model" | "default";++/**+ * The card's status line. "instructions" when the owner changed anything a+ * preset doesn't touch (instructions, prompt, role, research focus);+ * "custom-model" when only the model or deep reasoning differs from the+ * active Quality preset; otherwise "default" (the model follows Quality).+ * `overriddenFields` is undefined when the agent's detail wasn't loaded; an+ * override then counts as the owner's own.+ */+export function agentCardStatus(+ hasOverride: boolean,+ overriddenFields: readonly string[] | undefined,+ differsFromPreset: boolean,+): AgentCardStatus {+ if (!hasOverride) return differsFromPreset ? "custom-model" : "default";+ if (overriddenFields === undefined) return "instructions";+ if (overriddenFields.some((f) => !PRESET_FIELDS.has(f))) return "instructions";+ return differsFromPreset ? "custom-model" : "default";+}diff --git a/packages/ui/src/lib/heartbeatVitals.ts b/packages/ui/src/lib/heartbeatVitals.tsindex 4230443d..236a2d95 100644--- a/packages/ui/src/lib/heartbeatVitals.ts+++ b/packages/ui/src/lib/heartbeatVitals.ts@@ -124,3 +124,22 @@ export function formatTrend(t: HeartbeatTrend): string {return "—";}}++/**+ * The "Next beat" tile's value: how long until the soonest pending action+ * fires. A run time that has already passed (the scheduler picks it up on its+ * next tick) reads "Due now", never "0m ago"; a future one reads "in 12m",+ * "in 3h" or "in 2d". Empty for an unparseable time so the caller can fall+ * back.+ */+export function formatNextBeat(runAt: string, now: number = Date.now()): string {+ const at = new Date(runAt).getTime();+ if (!Number.isFinite(at)) return "";+ const deltaMs = at - now;+ if (deltaMs < 60_000) return "Due now";+ const mins = Math.round(deltaMs / 60_000);+ if (mins < 60) return `in ${mins}m`;+ const hours = Math.round(deltaMs / 3_600_000);+ if (hours < 48) return `in ${hours}h`;+ return `in ${Math.round(deltaMs / 86_400_000)}d`;+}diff --git a/packages/ui/src/lib/knowledgeViews.ts b/packages/ui/src/lib/knowledgeViews.tsnew file mode 100644index 00000000..c9d74620--- /dev/null+++ b/packages/ui/src/lib/knowledgeViews.ts@@ -0,0 +1,49 @@+// The Knowledge page's views: Company documents up front, and four views+// behind "Advanced" (review queue, built-in playbooks, reference library,+// query test). Kept apart from the components so `npm test` can check the+// mapping (scripts/knowledgeViews.test.mjs).++export type KnowledgeView = "company" | "review" | "playbooks" | "reference" | "query";++/** The views under "Advanced", in tab order. */+export const ADVANCED_VIEWS: readonly KnowledgeView[] = ["review", "playbooks", "reference", "query"];++export const VIEW_LABELS: Record<KnowledgeView, string> = {+ company: "Company documents",+ review: "Review queue",+ playbooks: "Built-in playbooks",+ reference: "Reference library",+ query: "Query test",+};++/** What the workspace has open. A built-in file and the new-file form sit+ * under the playbooks view. */+export type SelectionKind = "file" | "new" | "playbooks" | "company" | "reference" | "query" | "review";++export function viewForSelection(kind: SelectionKind | undefined | null): KnowledgeView {+ switch (kind) {+ case "file":+ case "new":+ case "playbooks":+ return "playbooks";+ case "review":+ case "reference":+ case "query":+ return kind;+ default:+ return "company";+ }+}++export function isAdvancedView(view: KnowledgeView): boolean {+ return view !== "company";+}++/** The view a `?view=` value opens: `/knowledge?view=review` (and the old+ * `/review` route) opens the review queue; anything unknown opens the+ * company documents. */+export function viewFromParam(param: string | null | undefined): KnowledgeView {+ return param && (ADVANCED_VIEWS as readonly string[]).includes(param)+ ? (param as KnowledgeView)+ : "company";+}diff --git a/packages/ui/src/lib/menuNav.ts b/packages/ui/src/lib/menuNav.tsnew file mode 100644index 00000000..e079e8b4--- /dev/null+++ b/packages/ui/src/lib/menuNav.ts@@ -0,0 +1,35 @@+// Keyboard movement inside a menu (components/ui/OverflowMenu.tsx), kept+// pure so `npm test` can check it (scripts/menuNav.test.mjs).+//+// `current` is the focused item's index, or -1 when focus is still on the+// button that opened the menu. Disabled items are skipped. Returns the index+// to focus next, or `current` when the key doesn't move focus or nothing can+// take it.+export function nextMenuIndex(+ current: number,+ key: string,+ disabled: readonly boolean[],+): number {+ const n = disabled.length;+ if (n === 0 || disabled.every(Boolean)) return current;+ const step = (from: number, dir: 1 | -1): number => {+ let i = from;+ for (let tries = 0; tries < n; tries++) {+ i = (i + dir + n) % n;+ if (!disabled[i]) return i;+ }+ return current;+ };+ switch (key) {+ case "ArrowDown":+ return step(current < 0 ? -1 : current, 1);+ case "ArrowUp":+ return step(current < 0 ? 0 : current, -1);+ case "Home":+ return step(-1, 1);+ case "End":+ return step(0, -1);+ default:+ return current;+ }+}diff --git a/packages/ui/src/lib/peopleKinds.ts b/packages/ui/src/lib/peopleKinds.tsindex 651a37b1..e8cec2eb 100644--- a/packages/ui/src/lib/peopleKinds.ts+++ b/packages/ui/src/lib/peopleKinds.ts@@ -66,3 +66,23 @@ export function effectiveKind(kind: PersonKind, isPrincipal: boolean): PersonKinexport function shouldOfferTeamMode(mode: WorkspaceMode, kind: PersonKind, isPrincipal: boolean): boolean {return mode === "solo" && effectiveKind(kind, isPrincipal) === "team" && !isPrincipal;}++export type CardStatusTone = "ok" | "warn" | "muted";++/**+ * The one status a People card shows. A contact: whether there's an email to+ * reach them on. A team member on leave: until when (an ISO date, compared+ * with `today` as YYYY-MM-DD). Anyone else on the team: how fast they're+ * expected to reply. Their approval scopes are on their own page.+ */+export function personCardStatus(+ person: Pick<Person, "kind" | "email" | "on_leave_until" | "response_sla_hours">,+ today: string,+): { label: string; tone: CardStatusTone } {+ if (isContact(person)) {+ return person.email ? { label: "Email on file", tone: "ok" } : { label: "No email", tone: "muted" };+ }+ const leave = person.on_leave_until?.slice(0, 10);+ if (leave && leave >= today) return { label: `On leave until ${leave}`, tone: "warn" };+ return { label: `Replies within ${person.response_sla_hours}h`, tone: "ok" };+}diff --git a/packages/ui/src/lib/reviewBulk.ts b/packages/ui/src/lib/reviewBulk.tsnew file mode 100644index 00000000..a04eec18--- /dev/null+++ b/packages/ui/src/lib/reviewBulk.ts@@ -0,0 +1,69 @@+// The review queue's per-domain bulk actions (approve what's queued, or start+// or stop curating a domain), worked out the way the server would act on them.+// Kept apart from ReviewQueue so `npm test` can check it+// (scripts/reviewBulk.test.mjs).++export interface BulkPendingItem {+ domain: string;+ trusted_default?: boolean;+ reviewed_at?: string | null;+}++export type BulkActionKind = "approve" | "curate-start" | "curate-stop";++export interface BulkAction {+ kind: BulkActionKind;+ domain: string;+ /** Items the action touches. */+ count: number;+ label: string;+ /** Longer explanation, for a hint under the menu. */+ detail: string;+}++/** The actions available for one domain. `pending` must be the unfiltered+ * pending list and `trustedDefaults` the shipped-and-unreviewed count per+ * domain, so a status filter on the list can't hide an action. */+export function domainBulkActions(+ domain: string,+ pending: BulkPendingItem[],+ trustedDefaults: Record<string, number>,+): BulkAction[] {+ const actions: BulkAction[] = [];+ const pendingInDomain = pending.filter((i) => i.domain === domain);+ if (pendingInDomain.length > 0) {+ actions.push({+ kind: "approve",+ domain,+ count: pendingInDomain.length,+ label: `Approve all pending in ${domain} (${pendingInDomain.length})`,+ detail: `Approve the ${pendingInDomain.length} pending item(s) in ${domain}.`,+ });+ }+ // "Stop curating" reverses queue_for_curation, whose selector is+ // `trusted_default = 1 AND reviewed_at IS NULL`. Mirror BOTH: a user's own+ // upload is pending with no timestamp too, and counting it would offer an+ // action that does nothing.+ const untouchedPending = pendingInDomain.filter(+ (i) => i.trusted_default && i.reviewed_at == null,+ ).length;+ const defaults = trustedDefaults[domain] ?? 0;+ if (untouchedPending > 0) {+ actions.push({+ kind: "curate-stop",+ domain,+ count: untouchedPending,+ label: `Stop curating ${domain}`,+ detail: `Return ${untouchedPending} unreviewed item(s) in ${domain} to trusted default.`,+ });+ } else if (defaults > 0) {+ actions.push({+ kind: "curate-start",+ domain,+ count: defaults,+ label: `Curate ${domain} (${defaults})`,+ detail: `Send ${defaults} shipped item(s) in ${domain} for review — they will be withheld from the Executive until approved.`,+ });+ }+ return actions;+}diff --git a/packages/ui/src/lib/useActiveSection.ts b/packages/ui/src/lib/useActiveSection.tsdeleted file mode 100644index d214cfca..00000000--- a/packages/ui/src/lib/useActiveSection.ts+++ /dev/null@@ -1,62 +0,0 @@-"use client";--import { useCallback, useEffect, useState, type RefObject } from "react";--// Which of the sections `ids` is in view inside the scroller `root`, for an-// in-page nav to highlight, plus `jumpTo` for its links. Same observer band-// as the Architecture and User Guide pages (a section is "active" while it-// crosses the 20-30% mark from the top), but with the page's own scroller as-// the root so the band is measured against it, not the whole viewport.-export function useActiveSection(- ids: readonly string[],- root: RefObject<HTMLElement | null>,-): { active: string | null; jumpTo: (id: string) => void } {- const [active, setActive] = useState<string | null>(ids[0] ?? null);- // A section that mounts late (Act as me, after its fetch) must be- // observed too, so re-run whenever the list changes.- const key = ids.join("|");-- useEffect(() => {- const list = key ? key.split("|") : [];- const scroller = root.current;- // Several short sections can sit in the band at once (the top of the- // page, say): the first in page order is the one in view.- const inBand = new Set<string>();- const observer = new IntersectionObserver(- (entries) => {- for (const e of entries) {- if (e.isIntersecting) inBand.add(e.target.id);- else inBand.delete(e.target.id);- }- const first = list.find((id) => inBand.has(id));- if (first) setActive(first);- },- { root: scroller, rootMargin: "-20% 0px -70% 0px", threshold: 0 },- );- for (const id of list) {- const el = document.getElementById(id);- if (el) observer.observe(el);- }- // A short last section never reaches the band, so at the very bottom- // the last section is the one in view.- const onScroll = () => {- if (!scroller) return;- if (scroller.scrollTop + scroller.clientHeight >= scroller.scrollHeight - 2) {- setActive(list[list.length - 1] ?? null);- }- };- scroller?.addEventListener("scroll", onScroll, { passive: true });- return () => {- observer.disconnect();- scroller?.removeEventListener("scroll", onScroll);- };- }, [key, root]);-- const jumpTo = useCallback((id: string) => {- setActive(id);- document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });- window.history.replaceState(null, "", `#${id}`);- }, []);-- return { active, jumpTo };-}diff --git a/packages/ui/src/lib/watchSlug.ts b/packages/ui/src/lib/watchSlug.tsnew file mode 100644index 00000000..4f1c25a9--- /dev/null+++ b/packages/ui/src/lib/watchSlug.ts@@ -0,0 +1,27 @@+/**+ * A monitor's slug when the person adding it leaves the field empty: the+ * signal type and target, kebab-cased to the rule the API enforces+ * (`[a-z0-9][a-z0-9-]{0,60}`). Tested in scripts/watchSlug.test.mjs.+ */++const PREFIX: Record<string, string> = {+ stock: "stock",+ rss: "rss",+ vendor_status: "status",+ edgar: "edgar",+ page_watch: "page",+ query: "search",+};++const MAX_LEN = 61;++export function suggestWatchSlug(signalType: string, target: string): string {+ let t = target.trim().toLowerCase();+ if (!t) return "";+ // A URL is named by its host and path, not its scheme or "www.".+ t = t.replace(/^[a-z][a-z0-9+.-]*:\/\//, "").replace(/^www\./, "");+ const prefix = PREFIX[signalType] ?? signalType.toLowerCase().replace(/[^a-z0-9]+/g, "-");+ const body = t.replace(/[^a-z0-9]+/g, "-");+ const slug = `${prefix}-${body}`.replace(/-+/g, "-").replace(/^-+/, "");+ return slug.slice(0, MAX_LEN).replace(/-+$/, "");+}diff --git a/packages/ui/src/lib/workflowCards.ts b/packages/ui/src/lib/workflowCards.tsnew file mode 100644index 00000000..9be1a96a--- /dev/null+++ b/packages/ui/src/lib/workflowCards.ts@@ -0,0 +1,78 @@+/**+ * What a card under "Your workflows" on /jobs shows: a plain line for its+ * schedule, and which one button leads. Pure, so it is tested on its own+ * (scripts/workflowCards.test.mjs).+ */++const DAYS: Record<string, string> = {+ mon: "Monday",+ tue: "Tuesday",+ wed: "Wednesday",+ thu: "Thursday",+ fri: "Friday",+ sat: "Saturday",+ sun: "Sunday",+};++const TIME = /^\d{1,2}:\d{2}$/;++/**+ * A saved cadence (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`,+ * all UTC) in words. Anything else comes back as written, so a format this+ * doesn't know yet still shows rather than vanishing.+ */+export function cadenceLabel(cadence: string | null | undefined): string {+ const raw = (cadence ?? "").trim();+ if (!raw) return "";+ const parts = raw.split("@");+ if (parts[0] === "daily" && parts.length === 2 && TIME.test(parts[1])) {+ return `Every day at ${parts[1]} UTC`;+ }+ if (parts[0] === "weekly" && parts.length === 3 && TIME.test(parts[2])) {+ const day = DAYS[parts[1].toLowerCase()];+ if (day) return `Every ${day} at ${parts[2]} UTC`;+ }+ if (parts[0] === "quarterly" && parts.length === 2) {+ const m = /^(\d{1,2})-(\d{1,2}:\d{2})$/.exec(parts[1]);+ if (m) return `Quarterly, day ${Number(m[1])} at ${m[2]} UTC`;+ }+ return raw;+}++interface RunLike {+ run_id: string;+ workflow_name: string;+ status: string;+ updated_at: string;+}++export type CardAction =+ /** Switched off: its review card turns it on. */+ | { kind: "approve" }+ /** A run is waiting on a sign-off: open that run. */+ | { kind: "signoff"; runId: string }+ | { kind: "run" };++/**+ * The card's primary button. A workflow that is off can only be reviewed;+ * one with a run waiting for sign-off leads with that run (the newest, if+ * several wait); otherwise Run.+ */+export function cardAction(name: string, active: boolean, runs: RunLike[]): CardAction {+ if (!active) return { kind: "approve" };+ const waiting = runs+ .filter((r) => r.workflow_name === name && r.status === "awaiting_human")+ .sort((a, b) => b.updated_at.localeCompare(a.updated_at));+ if (waiting.length > 0) return { kind: "signoff", runId: waiting[0].run_id };+ return { kind: "run" };+}++/** When this workflow last ran (its newest run's update time), or null. */+export function lastRunAt(name: string, runs: RunLike[]): string | null {+ let latest: string | null = null;+ for (const r of runs) {+ if (r.workflow_name !== name) continue;+ if (latest === null || r.updated_at > latest) latest = r.updated_at;+ }+ return latest;+}diff --git a/packages/ui/src/lib/workflowStarters.ts b/packages/ui/src/lib/workflowStarters.tsindex 20124973..6f826d64 100644--- a/packages/ui/src/lib/workflowStarters.ts+++ b/packages/ui/src/lib/workflowStarters.ts@@ -9,6 +9,16 @@ export const WORKFLOW_STARTERS = ["A launch readiness check I run before every product release",];+/**+ * Short chips for the front of /jobs: a label to tap and the starter it puts+ * in the box. The wizard shows the full sentences (all of them).+ */+export const WORKFLOW_STARTER_CHIPS: { label: string; text: string }[] = [+ { label: "Competitor digest", text: WORKFLOW_STARTERS[0] },+ { label: "Board pre-read", text: WORKFLOW_STARTERS[1] },+ { label: "Hiring plan review", text: WORKFLOW_STARTERS[2] },+];+const HANDOFF_KEY = "oe.workflowWizard.describe";// A hand-off older than this is from a Start the user walked away from, and// must not fire on a later visit to the wizard.diff --git a/packages/ui/tailwind.config.ts b/packages/ui/tailwind.config.tsindex 5340c9a6..85807aa0 100644--- a/packages/ui/tailwind.config.ts+++ b/packages/ui/tailwind.config.ts@@ -43,7 +43,7 @@ const config: Config = {DEFAULT: rgbVar("--border-default"),},fontFamily: {- sans: ["Inter", "system-ui", "sans-serif"],+ sans: ["var(--font-sans)", "system-ui", "-apple-system", "Segoe UI", "sans-serif"],},minHeight: {touch: "2.5rem",