Skip to content

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

feat(ui): share one sidebar with a short recent-chats list on every page (#195)

Rufus59b7d35813e2
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 318f1db1..5398822e 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -2013,7 +2013,7 @@ today:
explicit ids to `POST /alerts/bulk-ack` (never a server-side age sweep),
and "Re-check relevance" (`POST /alerts/review`); Monitoring gets the
same footer at 3 days; the ack body may carry `mute_topic`.
- ui_route: / (Next.js app router root) — the briefing is the default landing surface. `/today` still renders the same content as a standalone route (no sidebar shell) for bookmarks and the sidebar Briefing button. The chat lives at the same root behind a `mode` toggle — entering chat from "New chat" or by selecting a session swaps the main content; clicking the sidebar brandmark or the "Briefing" sidebar button returns to the briefing. A standalone "Pulse" link (→ `/memories`, the page titled "Pulse") is pinned directly beneath Briefing in the rail, the chat-home sidebar, and the mobile bottom bar — an always-visible top-level destination rather than a Knowledge-group entry (the Knowledge group now lists "RAG" → `/knowledge` and Skills). Both navs render it from the shared `PULSE_NAV_ITEM` in `navConfig.ts`.
+ ui_route: / (Next.js app router root) — the briefing is the default landing surface. `/today` still renders the same content as a standalone route (no sidebar shell) for bookmarks and the sidebar Briefing button. The chat lives at the same root behind a `mode` toggle — entering chat from "New chat" or by selecting a session swaps the main content; clicking the sidebar brandmark or the "Briefing" sidebar button returns to the briefing. Every signed-in route renders ONE sidebar component (`components/shell/AppSidebar.tsx`). The AppShell renders it for inner routes, and `/` (exempt from the shell for its own top bar and debug panel) renders the same component with in-page callbacks. On `/` its entries switch the page's in-memory mode; elsewhere they are links (`/?new=1`, `/?session=<id>`) that the home page applies on mount and then strips from the URL. The sidebar's "Recent" list is deliberately short — the 7 newest WEB chats only (channel sessions are recognised by their `slack:` / `telegram:` / `discord:` / `email:` / `google_chat:` session-id prefix, `lib/sessionChannel.ts`, since `sessions` has no channel column) — with an "All chats" link to `/chats`, the full history page with channel filter tabs, title search, date groups, a channel tag per row, and delete. The session list is held app-wide by `SessionsProvider` (root layout) over the unchanged `GET /sessions`, so the chat home refreshes it after each turn and every route sees the same list. A standalone "Pulse" link (→ `/memories`, the page titled "Pulse") is pinned directly beneath Briefing in the sidebar and the mobile bottom bar — an always-visible top-level destination rather than a Knowledge-group entry (the Knowledge group now lists "RAG" → `/knowledge` and Skills), rendered from the shared `PULSE_NAV_ITEM` in `navConfig.ts`.
briefing_first_landing: |
The root page (`packages/ui/src/app/page.tsx`) defaults to `mode="briefing"`
and renders `<Briefing>` (`packages/ui/src/components/Briefing.tsx`) in the
diff --git a/packages/core/openexecutive/architecture/prebuilt/today.json b/packages/core/openexecutive/architecture/prebuilt/today.json
index db884f26..43a9e8b1 100644
--- a/packages/core/openexecutive/architecture/prebuilt/today.json
+++ b/packages/core/openexecutive/architecture/prebuilt/today.json
@@ -1,7 +1,7 @@
{
"section_id": "today",
"title": "Today / Morning Brief",
- "markdown": "`openexecutive.api.routes.today` serves the morning brief — a one-screen, read-only view of what is happening across the org. It is the default landing surface (the Next.js root renders `<Briefing>`).\n\n`GET /today` returns `TodayResponse` assembled by `_build_today()`, which is synchronous and caller-agnostic:\n\n- **`departments`** — per-department goal health, rolling up each department's goal counts (`total`, `at_risk`, `off_track`) plus its awaiting-workflow count, and `attention_goals`: the actual off-track/at-risk goals (worst first, capped at 3) with `key_result`, `current`, `target`, and `status`, so the briefing's Department card shows *which* goal is off and how far without a click. Empty for healthy/inactive departments.\n- **`people`** — an attention-ranked roster. Each person carries `awaiting_action` count, soonest SLA, a `status` (`on_leave` / `needs_reply` / `awaiting` / `clear`), reachability, `overdue`, a server `priority` sort key, and a cached one-line `insight`. Sorted by `(-priority, full_name)`.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings): unread, inside their category TTL, not snoozed — see *Alert lifecycle* below. Each carries `score`, `category` (`action` vs `monitoring`), `surfaced_reason` from `openexecutive.briefing.ranking`, the lifecycle fields (`occurrence_count`, `last_seen_at`, `last_reviewed_at`, `review_verdict`, `review_note`, `recommended_move`, `why_now`, `due_at`, `superseded_count`, `suggested_workflow`), and `decision_instance_id` (set only when the proposal is backed by a decision-ledger row — a calendar booking awaiting approval). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. For decision-backed proposals the card's Approve/Reject call the `/decisions` endpoints (which book or cancel the event server-side and clear the alert) instead of the ack-and-hand-off-to-chat flow — so meeting bookings are reviewed in the briefing itself rather than on a separate page.\n- **`narrative`** — a per-viewer Executive-voice header synthesized by `synthesize_briefing_narrative`; the principal gets the whole-company scope, teammates a role-scoped one. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory). That digest (`briefing.context.format_open_alerts_for_prompt`) is capped at 30 items; when the board is longer the header says so explicitly and tells the Executive to point at this page for the rest — it previously presented the capped list as the complete board, so the Executive described a slice as everything that was open (#136). Chat adapters get the digest too, but Slack gates it to the principal's DMs: the board is company-wide and must not be pulled into a shared channel. The `[alert_id]` at the start of each line is also what `ack_alert` trusts, because an id quoted inside an alert's own body came from inbound mail or chat and is attacker-controlled. This page's `[Discuss mode — alert_id=N]` handoff primer is a pointer to which item is under discussion, not authority on its own: the server accepts it only if that id is on the live board too. Two things enforce that. Every field the digest interpolates — headline, body, suggested action, tags, review note — is collapsed to a single line, since a newline in any of them would forge a whole extra `[N]` line and with it a fabricated instruction to clear someone else's alert. And the server records the live board it derived, so `ack_alert` refuses any id outside it — on **every** session, not just the chat adapters. The recorded set is the whole live board, not just the rows the digest printed, so a card past the render cap stays ackable. The control stops invented, closed, snoozed and expired ids; it does not stop the model being argued into acking the wrong *live* card. That check used to run only when `origin_channel` was set, which the browser never sets, so the one surface where the principal actually reads their board had no check at all and the model could ack any id, including one quoted out of an alert body by the Discuss handoff. Rendering the block and recording its ids now happen together in `briefing.context.render_and_trust`, which both the web chat route and the channel adapters call: render without recording and the tool refuses everything, record without rendering and the model gets reach it was never shown. A turn that was shown nothing trusts nothing. Recording it is only half the wiring: the tool reads the board off the turn's session through a ContextVar, and the chat route binds that session for the whole SSE body (`set_session`, next to `set_turn`). Bound from inside the Executive's own generator instead, it survives exactly one stream step — `asyncio.wait_for` runs each step in a fresh Task with a copy of the context — and the tool-call loop, which runs later, sees nothing. That shipped, and every web ack was refused on cards that were open the whole time. The digest also carries a short **already handled** tail — recently acked / dismissed / resolved rows, named but deliberately NOT trusted for acking — because a card cleared on the page minutes ago is otherwise simply absent from chat: asked to \"record that as fixed\", the Executive could not tell a settled item from one it had never heard of, and sent the principal back to dismiss a card that was already gone. That tail renders even when nothing is open, which is exactly when it matters. Note it is a different window from the `handled_overnight` rail above: that one runs since the last delivered morning brief, while the chat tail looks back 14 days (matching the action-alert TTL, so it still covers an item cleared late in its life), so chat can name a settled item the rail no longer shows. The narrative is held to what is **live**, and to what it is actually for. The `alert_raised` source is dropped from the activity it reasons over (`_build_activity(..., include_alert_raised=False)`): a closed alert reads as work the principal already settled, and a *live* one is worse than redundant — `lifecycle.is_live` is the very predicate behind `list_live_alerts`, so every live raise is already a proposal card below the header, which the prompt forbids re-listing. The `/today/activity` rail keeps the whole source, because a raise really happened. The activity block is only labelled \"since last brief\" when the caller bounded it with `since` (the standalone briefs do; the header does not), since calling an unbounded history rail a delta made the header present weeks-old rows as overnight news. When the viewer's slice holds nothing that wants a decision — no action proposal, no at-risk/off-track department, nobody awaiting — the regen skips the model call entirely and writes the fixed quiet line (`Quiet right now — nothing pressing.`, or `… nothing needs you.` for a teammate). **The cache key is a hash of the rendered context itself** (`today._narrative_context` builds it once and both the hot path and the background task key off that one string, which is also handed to the model verbatim). That makes the key a function of the model's input: everything the prompt renders is covered, and nothing it omits can trigger a regeneration. Keying on hand-picked fields broke one half or the other each time — headlines alone left the rendered activity block uncovered, while the proposals' review fields are never rendered by this header yet are rewritten with fresh prose by every `alerts.review` pass, so they regenerated each viewer's narrative several times a day to re-synthesize identical input. A quiet board keys off a fixed sentinel instead, so a moving rail cannot re-key an entry whose text is constant. Together: on a fully dismissed board every other input was empty, the rail became the only context, and the model synthesized a confident header out of closed items.\n- **`in_flight`** / **`awaiting`** — upcoming Executive commitments and people we are waiting on.\n- **`handled_overnight`** — the autonomous moves the Executive *completed* since the last delivered morning brief: the alert review's (routed, nudged, escalated, drafted, merged, closed) plus the research watch policy's (`watching` — a watch added on its own because it was grounded in company data; `stopped_watching` — a research watch auto-disabled as noisy or dead; no alert id, re-enable from `/watchlist`). A `changed` verdict (the review rewrote an open alert's headline / body / severity) is deliberately **not** here: the alert is still open in \"Needs you\" and its card carries the note, so the brief reports it under \"what changed\" (a REWRITTEN block) rather than as done. Each row is structured, not just a sentence: `kind`, the audit `summary` (nudge bookkeeping marker stripped), `at`, `alert_id`, `event_type` (for a pre-filtered `/audit` deep link), `headline` (the alert's headline at move time; a watch's slug), `target` (person name for routed / nudged, survivor headline for merged, new severity for escalated, draft title, workflow name), `detail` (the cited evidence or the watch policy's reason), `outcome` (`resolved` | `dismissed` for a close, `proposed` for a route that went through the authority gate), `evidence_ref` (S1 / R2 / A3), `superseded_by_alert_id`, and `status` — the alert's lifecycle state **now** (`open` = live in the queue per `lifecycle.is_live` | `resolved` | `dismissed` | `expired` | `merged` | `acked` | `inactive` for snoozed / past-TTL rows), looked up per row so a close the principal already undid renders as reopened instead of offering a second Undo, and a \"still open\" jump link only appears when there is a card to land on. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\nThe route resolves the caller from `x-caller-email`, then attaches the viewer-scoped narrative in a `BackgroundTask` so the request never blocks on an LLM call. `GET /today/activity` returns the recent self-initiated action rail — merged from fired scheduled actions (DMs, follow-ups, nudges, cadences), logged decisions, saved advice, completed workflow runs (briefings/check-ins/research), kicked-off initiatives, resolved gated decisions, and raised alerts, so it reflects all of the Executive's activity rather than just dispatched messages. The Pulse page (`/memories`) polls it (limit 100) every ~20s so new events stream into the 'Recent activity' card, which scrolls internally at a fixed height instead of growing the page. The `morning_brief` workflow calls `_build_today()` directly to build the standalone DM (via a different, enumerated prompt). `GET /morning-brief` is a deprecated alias.\n\n## Alert lifecycle & the Executive review\n\nAlerts used to be write-once: raised, then never looked at again, so the \"Needs you\" queue grew without bound and the briefs re-listed it daily. Three things now keep it live:\n\n- **Time-to-live** (`openexecutive.alerts.lifecycle`). Action items expire after `ALERT_TTL_DAYS_ACTION` (14 d), unrouted low/medium monitoring signals after `ALERT_TTL_DAYS_MONITORING` (3 d). Every surface reads `list_live_alerts` (the same predicate the scheduler's 15-minute sweep persists as status `expired`), so `/today` is right even before the sweep runs. Artifacts and decision-backed alerts are exempt. `POST /alerts/{id}/reopen` is the Undo.\n- **Coalescing** (`alerts.pipeline` + `store.coalesce_alert`). A repeat of an open alert with the same `(source, dedup_key)` updates that row — `occurrence_count`, `last_seen_at`, severity max — instead of stacking a second card, and only re-pings when severity rose to high/urgent. Monitoring alerts carry a stable `watch:<slug>` key, so one watch means one card.\n- **The review** (`openexecutive.alerts.review`, heartbeat `alert_review_scan`, every 6 h and right before the morning brief). For each open alert the Executive sees what changed since it was raised — newer signals from the same watch, related alerts, activity since, the roster with SLAs, department authority — and returns a verdict (relevant / changed / resolved / stale) plus a recommended move. Deterministic policy then acts: **route** (assign + DM the owner; `propose_via_alert` for propose-only departments), **nudge**, **escalate** (severity + `due_at` + DM the principal only), **draft** (`draft_artifact`), **suggest a workflow** (a link, never a run), **merge** (`superseded_by_alert_id`), or **resolve** — only on high confidence citing a server-minted evidence ref (a newer signal, a related alert, an activity item shown for that alert); free text never closes a card, and anything weaker is annotated `likely_stale`, demoted 30 ranking points, and left for one click. Everything that came from outside is rendered as inert data inside the review prompt, so an injected email body cannot steer the batch. Board / comp / legal matters only ever go to a scope-holder or the principal and keep their text. Route and escalate are idempotent across passes, every DM carries an \"[Alert review] Re: …\" header, outbound moves are capped per pass, passes are single-flight, `ALERT_REVIEW_ENABLED=false` stops every caller, every move is audited with its evidence and prior state, and a distinct `resolved` status keeps Executive closes separate from `ack` (user approved).\n\nOn the page, cards read as decisions: the one-line \"what changed since you last looked\" (`review_note`) leads, the recommended move is the primary control (Nudge <owner> → chat; Run <workflow> → `/jobs/<name>`), with chips for age, seen ×N, why-now / due, folded-in and draft-ready, a \"Reviewed <ago>\" footer, and an amber Likely-stale treatment with one-click Dismiss. \"Needs you\" shows *Start here* + 8 cards + \"Show N more\", a \"Dismiss N older than 7 days\" footer (explicit ids to `POST /alerts/bulk-ack` — never a server-side age sweep, which would hit teammates' routed items), and \"Re-check relevance\" (`POST /alerts/review`). The handled rail (anchor of the \"Executive handled N overnight\" pill) is deliberately one sentence by default: a first-person heading built from counts only — \"Since your last brief: N off your plate (closes still standing, and merges whose survivor is not itself listed; a merge into a listed survivor counts on that survivor's row), N in others' hands (routed / nudged), N waiting on you (escalated)\", plus \"N drafts ready\", \"N workflows suggested\", \"N watch changes\", \"N other moves\" (a kind the UI does not know) and \"N back on your plate\" (a close that is open again) when present — with the rows behind a \"details\" disclosure, and nothing rendered at all when the grouped rows are empty. The pure logic (grouping, headline, links) lives in `packages/ui/src/lib/handled.ts` and is covered by `npm test`. Expanded, it shows one first-person row per alert (\"Resolved *X* — evidence\", \"Dismissed *X* as stale — evidence\", \"Handed *X* to Dana Kim\" / \"Proposed *X* to Dana Kim (awaiting their approval)\", \"Chased Dana Kim on *X*\", \"Raised *X* to high\", \"Drafted *T* from *X*\", \"Folded *X* into *Y*\", \"Started watching *slug*\"), escalations first; rows sharing an alert collapse to the newest move with the others as an \"also …\" trailer — a close always keeps the visible slot (it carries Undo), otherwise an escalation beats routed / nudged / drafted; a merge whose survivor is listed becomes \"N duplicates folded in\" on the survivor. Every row links its `evidence_ref` (or \"evidence\") to `/audit?event_type=…&q=…` (the audit page pre-fills those filters from the query string), a still-open row jumps to its card (`#alert-<id>`), drafted rows link `/artifacts`, watch rows `/watchlist`. Undo is offered only while the close still stands (`status` not `open`); a reverted close shows \"Reopened\". Dismissing a watch-sourced alert lowers that watch's `trust_score` (which discounts ranking and is shown to the review as evidence); the ack body may carry `mute_topic`. Acknowledging or resolving an alert — including the review closing it itself — marks the review's DMs about it `acted` in the Attunement outcome ledger, for the person it is routed to and the principal only; dismissing it, finding it stale or letting it expire voids them (counted neither way). Review DMs are tagged `alert_review` with `alert:<id>`.\n\n## Multi-client practice section\n\nIn multi-client practice mode (2+ client slots — see the Client Companies section), the response gains an additive `practice_clients` list: rollup cards for the **parked** clients (overdue follow-ups, awaiting replies, unread alerts, onboarding due soon, renewal countdowns), each stamped with the save point its data reflects. Single-company installs always receive an empty list and the UI renders nothing.",
+ "markdown": "`openexecutive.api.routes.today` serves the morning brief — a one-screen, read-only view of what is happening across the org. It is the default landing surface (the Next.js root renders `<Briefing>`). Every signed-in page shares one sidebar (`AppSidebar`). Its Recent list is capped at the 7 newest web chats. The full history, including Slack, Telegram and Discord conversations (recognised by their session-id prefix), lives on `/chats`. A chat opens from any page through `/?session=<id>`.\n\n`GET /today` returns `TodayResponse` assembled by `_build_today()`, which is synchronous and caller-agnostic:\n\n- **`departments`** — per-department goal health, rolling up each department's goal counts (`total`, `at_risk`, `off_track`) plus its awaiting-workflow count, and `attention_goals`: the actual off-track/at-risk goals (worst first, capped at 3) with `key_result`, `current`, `target`, and `status`, so the briefing's Department card shows *which* goal is off and how far without a click. Empty for healthy/inactive departments.\n- **`people`** — an attention-ranked roster. Each person carries `awaiting_action` count, soonest SLA, a `status` (`on_leave` / `needs_reply` / `awaiting` / `clear`), reachability, `overdue`, a server `priority` sort key, and a cached one-line `insight`. Sorted by `(-priority, full_name)`.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings): unread, inside their category TTL, not snoozed — see *Alert lifecycle* below. Each carries `score`, `category` (`action` vs `monitoring`), `surfaced_reason` from `openexecutive.briefing.ranking`, the lifecycle fields (`occurrence_count`, `last_seen_at`, `last_reviewed_at`, `review_verdict`, `review_note`, `recommended_move`, `why_now`, `due_at`, `superseded_count`, `suggested_workflow`), and `decision_instance_id` (set only when the proposal is backed by a decision-ledger row — a calendar booking awaiting approval). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. For decision-backed proposals the card's Approve/Reject call the `/decisions` endpoints (which book or cancel the event server-side and clear the alert) instead of the ack-and-hand-off-to-chat flow — so meeting bookings are reviewed in the briefing itself rather than on a separate page.\n- **`narrative`** — a per-viewer Executive-voice header synthesized by `synthesize_briefing_narrative`; the principal gets the whole-company scope, teammates a role-scoped one. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory). That digest (`briefing.context.format_open_alerts_for_prompt`) is capped at 30 items; when the board is longer the header says so explicitly and tells the Executive to point at this page for the rest — it previously presented the capped list as the complete board, so the Executive described a slice as everything that was open (#136). Chat adapters get the digest too, but Slack gates it to the principal's DMs: the board is company-wide and must not be pulled into a shared channel. The `[alert_id]` at the start of each line is also what `ack_alert` trusts, because an id quoted inside an alert's own body came from inbound mail or chat and is attacker-controlled. This page's `[Discuss mode — alert_id=N]` handoff primer is a pointer to which item is under discussion, not authority on its own: the server accepts it only if that id is on the live board too. Two things enforce that. Every field the digest interpolates — headline, body, suggested action, tags, review note — is collapsed to a single line, since a newline in any of them would forge a whole extra `[N]` line and with it a fabricated instruction to clear someone else's alert. And the server records the live board it derived, so `ack_alert` refuses any id outside it — on **every** session, not just the chat adapters. The recorded set is the whole live board, not just the rows the digest printed, so a card past the render cap stays ackable. The control stops invented, closed, snoozed and expired ids; it does not stop the model being argued into acking the wrong *live* card. That check used to run only when `origin_channel` was set, which the browser never sets, so the one surface where the principal actually reads their board had no check at all and the model could ack any id, including one quoted out of an alert body by the Discuss handoff. Rendering the block and recording its ids now happen together in `briefing.context.render_and_trust`, which both the web chat route and the channel adapters call: render without recording and the tool refuses everything, record without rendering and the model gets reach it was never shown. A turn that was shown nothing trusts nothing. Recording it is only half the wiring: the tool reads the board off the turn's session through a ContextVar, and the chat route binds that session for the whole SSE body (`set_session`, next to `set_turn`). Bound from inside the Executive's own generator instead, it survives exactly one stream step — `asyncio.wait_for` runs each step in a fresh Task with a copy of the context — and the tool-call loop, which runs later, sees nothing. That shipped, and every web ack was refused on cards that were open the whole time. The digest also carries a short **already handled** tail — recently acked / dismissed / resolved rows, named but deliberately NOT trusted for acking — because a card cleared on the page minutes ago is otherwise simply absent from chat: asked to \"record that as fixed\", the Executive could not tell a settled item from one it had never heard of, and sent the principal back to dismiss a card that was already gone. That tail renders even when nothing is open, which is exactly when it matters. Note it is a different window from the `handled_overnight` rail above: that one runs since the last delivered morning brief, while the chat tail looks back 14 days (matching the action-alert TTL, so it still covers an item cleared late in its life), so chat can name a settled item the rail no longer shows. The narrative is held to what is **live**, and to what it is actually for. The `alert_raised` source is dropped from the activity it reasons over (`_build_activity(..., include_alert_raised=False)`): a closed alert reads as work the principal already settled, and a *live* one is worse than redundant — `lifecycle.is_live` is the very predicate behind `list_live_alerts`, so every live raise is already a proposal card below the header, which the prompt forbids re-listing. The `/today/activity` rail keeps the whole source, because a raise really happened. The activity block is only labelled \"since last brief\" when the caller bounded it with `since` (the standalone briefs do; the header does not), since calling an unbounded history rail a delta made the header present weeks-old rows as overnight news. When the viewer's slice holds nothing that wants a decision — no action proposal, no at-risk/off-track department, nobody awaiting — the regen skips the model call entirely and writes the fixed quiet line (`Quiet right now — nothing pressing.`, or `… nothing needs you.` for a teammate). **The cache key is a hash of the rendered context itself** (`today._narrative_context` builds it once and both the hot path and the background task key off that one string, which is also handed to the model verbatim). That makes the key a function of the model's input: everything the prompt renders is covered, and nothing it omits can trigger a regeneration. Keying on hand-picked fields broke one half or the other each time — headlines alone left the rendered activity block uncovered, while the proposals' review fields are never rendered by this header yet are rewritten with fresh prose by every `alerts.review` pass, so they regenerated each viewer's narrative several times a day to re-synthesize identical input. A quiet board keys off a fixed sentinel instead, so a moving rail cannot re-key an entry whose text is constant. Together: on a fully dismissed board every other input was empty, the rail became the only context, and the model synthesized a confident header out of closed items.\n- **`in_flight`** / **`awaiting`** — upcoming Executive commitments and people we are waiting on.\n- **`handled_overnight`** — the autonomous moves the Executive *completed* since the last delivered morning brief: the alert review's (routed, nudged, escalated, drafted, merged, closed) plus the research watch policy's (`watching` — a watch added on its own because it was grounded in company data; `stopped_watching` — a research watch auto-disabled as noisy or dead; no alert id, re-enable from `/watchlist`). A `changed` verdict (the review rewrote an open alert's headline / body / severity) is deliberately **not** here: the alert is still open in \"Needs you\" and its card carries the note, so the brief reports it under \"what changed\" (a REWRITTEN block) rather than as done. Each row is structured, not just a sentence: `kind`, the audit `summary` (nudge bookkeeping marker stripped), `at`, `alert_id`, `event_type` (for a pre-filtered `/audit` deep link), `headline` (the alert's headline at move time; a watch's slug), `target` (person name for routed / nudged, survivor headline for merged, new severity for escalated, draft title, workflow name), `detail` (the cited evidence or the watch policy's reason), `outcome` (`resolved` | `dismissed` for a close, `proposed` for a route that went through the authority gate), `evidence_ref` (S1 / R2 / A3), `superseded_by_alert_id`, and `status` — the alert's lifecycle state **now** (`open` = live in the queue per `lifecycle.is_live` | `resolved` | `dismissed` | `expired` | `merged` | `acked` | `inactive` for snoozed / past-TTL rows), looked up per row so a close the principal already undid renders as reopened instead of offering a second Undo, and a \"still open\" jump link only appears when there is a card to land on. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\nThe route resolves the caller from `x-caller-email`, then attaches the viewer-scoped narrative in a `BackgroundTask` so the request never blocks on an LLM call. `GET /today/activity` returns the recent self-initiated action rail — merged from fired scheduled actions (DMs, follow-ups, nudges, cadences), logged decisions, saved advice, completed workflow runs (briefings/check-ins/research), kicked-off initiatives, resolved gated decisions, and raised alerts, so it reflects all of the Executive's activity rather than just dispatched messages. The Pulse page (`/memories`) polls it (limit 100) every ~20s so new events stream into the 'Recent activity' card, which scrolls internally at a fixed height instead of growing the page. The `morning_brief` workflow calls `_build_today()` directly to build the standalone DM (via a different, enumerated prompt). `GET /morning-brief` is a deprecated alias.\n\n## Alert lifecycle & the Executive review\n\nAlerts used to be write-once: raised, then never looked at again, so the \"Needs you\" queue grew without bound and the briefs re-listed it daily. Three things now keep it live:\n\n- **Time-to-live** (`openexecutive.alerts.lifecycle`). Action items expire after `ALERT_TTL_DAYS_ACTION` (14 d), unrouted low/medium monitoring signals after `ALERT_TTL_DAYS_MONITORING` (3 d). Every surface reads `list_live_alerts` (the same predicate the scheduler's 15-minute sweep persists as status `expired`), so `/today` is right even before the sweep runs. Artifacts and decision-backed alerts are exempt. `POST /alerts/{id}/reopen` is the Undo.\n- **Coalescing** (`alerts.pipeline` + `store.coalesce_alert`). A repeat of an open alert with the same `(source, dedup_key)` updates that row — `occurrence_count`, `last_seen_at`, severity max — instead of stacking a second card, and only re-pings when severity rose to high/urgent. Monitoring alerts carry a stable `watch:<slug>` key, so one watch means one card.\n- **The review** (`openexecutive.alerts.review`, heartbeat `alert_review_scan`, every 6 h and right before the morning brief). For each open alert the Executive sees what changed since it was raised — newer signals from the same watch, related alerts, activity since, the roster with SLAs, department authority — and returns a verdict (relevant / changed / resolved / stale) plus a recommended move. Deterministic policy then acts: **route** (assign + DM the owner; `propose_via_alert` for propose-only departments), **nudge**, **escalate** (severity + `due_at` + DM the principal only), **draft** (`draft_artifact`), **suggest a workflow** (a link, never a run), **merge** (`superseded_by_alert_id`), or **resolve** — only on high confidence citing a server-minted evidence ref (a newer signal, a related alert, an activity item shown for that alert); free text never closes a card, and anything weaker is annotated `likely_stale`, demoted 30 ranking points, and left for one click. Everything that came from outside is rendered as inert data inside the review prompt, so an injected email body cannot steer the batch. Board / comp / legal matters only ever go to a scope-holder or the principal and keep their text. Route and escalate are idempotent across passes, every DM carries an \"[Alert review] Re: …\" header, outbound moves are capped per pass, passes are single-flight, `ALERT_REVIEW_ENABLED=false` stops every caller, every move is audited with its evidence and prior state, and a distinct `resolved` status keeps Executive closes separate from `ack` (user approved).\n\nOn the page, cards read as decisions: the one-line \"what changed since you last looked\" (`review_note`) leads, the recommended move is the primary control (Nudge <owner> → chat; Run <workflow> → `/jobs/<name>`), with chips for age, seen ×N, why-now / due, folded-in and draft-ready, a \"Reviewed <ago>\" footer, and an amber Likely-stale treatment with one-click Dismiss. \"Needs you\" shows *Start here* + 8 cards + \"Show N more\", a \"Dismiss N older than 7 days\" footer (explicit ids to `POST /alerts/bulk-ack` — never a server-side age sweep, which would hit teammates' routed items), and \"Re-check relevance\" (`POST /alerts/review`). The handled rail (anchor of the \"Executive handled N overnight\" pill) is deliberately one sentence by default: a first-person heading built from counts only — \"Since your last brief: N off your plate (closes still standing, and merges whose survivor is not itself listed; a merge into a listed survivor counts on that survivor's row), N in others' hands (routed / nudged), N waiting on you (escalated)\", plus \"N drafts ready\", \"N workflows suggested\", \"N watch changes\", \"N other moves\" (a kind the UI does not know) and \"N back on your plate\" (a close that is open again) when present — with the rows behind a \"details\" disclosure, and nothing rendered at all when the grouped rows are empty. The pure logic (grouping, headline, links) lives in `packages/ui/src/lib/handled.ts` and is covered by `npm test`. Expanded, it shows one first-person row per alert (\"Resolved *X* — evidence\", \"Dismissed *X* as stale — evidence\", \"Handed *X* to Dana Kim\" / \"Proposed *X* to Dana Kim (awaiting their approval)\", \"Chased Dana Kim on *X*\", \"Raised *X* to high\", \"Drafted *T* from *X*\", \"Folded *X* into *Y*\", \"Started watching *slug*\"), escalations first; rows sharing an alert collapse to the newest move with the others as an \"also …\" trailer — a close always keeps the visible slot (it carries Undo), otherwise an escalation beats routed / nudged / drafted; a merge whose survivor is listed becomes \"N duplicates folded in\" on the survivor. Every row links its `evidence_ref` (or \"evidence\") to `/audit?event_type=…&q=…` (the audit page pre-fills those filters from the query string), a still-open row jumps to its card (`#alert-<id>`), drafted rows link `/artifacts`, watch rows `/watchlist`. Undo is offered only while the close still stands (`status` not `open`); a reverted close shows \"Reopened\". Dismissing a watch-sourced alert lowers that watch's `trust_score` (which discounts ranking and is shown to the review as evidence); the ack body may carry `mute_topic`. Acknowledging or resolving an alert — including the review closing it itself — marks the review's DMs about it `acted` in the Attunement outcome ledger, for the person it is routed to and the principal only; dismissing it, finding it stale or letting it expire voids them (counted neither way). Review DMs are tagged `alert_review` with `alert:<id>`.\n\n## Multi-client practice section\n\nIn multi-client practice mode (2+ client slots — see the Client Companies section), the response gains an additive `practice_clients` list: rollup cards for the **parked** clients (overdue follow-ups, awaiting replies, unread alerts, onboarding due soon, renewal countdowns), each stamped with the save point its data reflects. Single-company installs always receive an empty list and the UI renders nothing.",
"mermaid": "flowchart TD\n REQ[\"GET /today\"]\n BUILD[\"_build_today()\"]\n DEPTS[\"departments<br/>(per-dept goal health)\"]\n ROSTER[\"people<br/>(attention-ranked roster)\"]\n PROPS[\"proposals<br/>(unread alerts, routed)\"]\n INFLIGHT[\"in_flight<br/>(pending follow-ups / nudges)\"]\n AWAIT[\"awaiting<br/>(replies we await)\"]\n NARR[\"viewer-scoped narrative (BackgroundTask)\"]\n MB[\"morning_brief workflow\"]\n REQ --> BUILD\n BUILD --> DEPTS\n BUILD --> ROSTER\n BUILD --> PROPS\n BUILD --> INFLIGHT\n BUILD --> AWAIT\n REQ -->|\"resolve caller, attach\"| NARR\n MB -->|\"calls directly for standalone DM\"| BUILD\n class REQ entry\n class BUILD compute\n class DEPTS storage\n class ROSTER storage\n class PROPS storage\n class INFLIGHT storage\n class AWAIT storage\n class NARR compute\n class MB compute",
"generated_at": "2026-09-22T23:17:20.508677+00:00"
}
diff --git a/packages/ui/scripts/sessionChannel.test.mjs b/packages/ui/scripts/sessionChannel.test.mjs
new file mode 100644
index 00000000..39e3ad42
--- /dev/null
+++ b/packages/ui/scripts/sessionChannel.test.mjs
@@ -0,0 +1,85 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ countByChannel,
+ filterSessions,
+ recentWebChats,
+ sessionChannel,
+} from "../src/lib/sessionChannel.ts";
+
+const s = (session_id, title = session_id) => ({
+ session_id,
+ title,
+ created_at: "2026-09-20T10:00:00Z",
+ updated_at: "2026-09-20T10:00:00Z",
+ message_count: 1,
+});
+
+test("session ids are classified by their adapter prefix", () => {
+ assert.equal(sessionChannel("3f1c2a9e-8b1d-4c3e-9f0a-1b2c3d4e5f60"), "web");
+ assert.equal(sessionChannel("slack:dm:U123"), "slack");
+ assert.equal(sessionChannel("slack:thread:C1:1726000000.0001"), "slack");
+ assert.equal(sessionChannel("telegram:98765"), "telegram");
+ assert.equal(sessionChannel("discord:thread:111:222"), "discord");
+ assert.equal(sessionChannel("email:[email protected]"), "email");
+ assert.equal(sessionChannel("google_chat:spaces/X:t1"), "google_chat");
+});
+
+test("unknown prefixes and odd ids fall back to web", () => {
+ assert.equal(sessionChannel("carrier-pigeon:1"), "web");
+ assert.equal(sessionChannel(":leading-colon"), "web");
+ assert.equal(sessionChannel(""), "web");
+ // Prefix match is exact, not substring: "slackish" is not Slack.
+ assert.equal(sessionChannel("slackish:1"), "web");
+});
+
+test("recentWebChats keeps order, skips channel sessions and stops at the limit", () => {
+ const sessions = [
+ s("a"),
+ s("slack:dm:U1"),
+ s("b"),
+ s("telegram:1"),
+ s("c"),
+ s("d"),
+ ];
+ assert.deepEqual(
+ recentWebChats(sessions, 3).map((x) => x.session_id),
+ ["a", "b", "c"],
+ );
+ assert.deepEqual(recentWebChats(sessions, 0), []);
+ assert.equal(recentWebChats([s("slack:dm:U1")], 5).length, 0);
+});
+
+test("filterSessions combines channel and case-insensitive title query", () => {
+ const sessions = [
+ s("a", "Board prep for Q4"),
+ s("slack:dm:U1", "Slack DM — Priya"),
+ s("b", ""),
+ s("discord:dm:9", "Board sync"),
+ ];
+ const ids = (xs) => xs.map((x) => x.session_id);
+ assert.deepEqual(ids(filterSessions(sessions, { channel: "all", query: "" })), [
+ "a",
+ "slack:dm:U1",
+ "b",
+ "discord:dm:9",
+ ]);
+ assert.deepEqual(ids(filterSessions(sessions, { channel: "all", query: " BOARD " })), [
+ "a",
+ "discord:dm:9",
+ ]);
+ assert.deepEqual(ids(filterSessions(sessions, { channel: "web", query: "board" })), ["a"]);
+ assert.deepEqual(ids(filterSessions(sessions, { channel: "slack", query: "" })), [
+ "slack:dm:U1",
+ ]);
+ // An empty title is searchable by the label the UI shows for it.
+ assert.deepEqual(ids(filterSessions(sessions, { channel: "all", query: "untitled" })), ["b"]);
+});
+
+test("countByChannel only lists channels that have sessions", () => {
+ assert.deepEqual(
+ countByChannel([s("a"), s("b"), s("slack:dm:U1"), s("telegram:1"), s("telegram:2")]),
+ { web: 2, slack: 1, telegram: 2 },
+ );
+ assert.deepEqual(countByChannel([]), {});
+});
diff --git a/packages/ui/scripts/sessionGroups.test.mjs b/packages/ui/scripts/sessionGroups.test.mjs
new file mode 100644
index 00000000..1ac41fac
--- /dev/null
+++ b/packages/ui/scripts/sessionGroups.test.mjs
@@ -0,0 +1,54 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { groupSessionsByDate } from "../src/lib/sessionGroups.ts";
+
+const at = (session_id, updated_at) => ({
+ session_id,
+ title: session_id,
+ created_at: updated_at,
+ updated_at,
+ message_count: 1,
+});
+
+// Local-time "now" so the day boundaries below line up with the grouping's
+// own local-midnight arithmetic regardless of the machine's timezone.
+const NOW = new Date(2026, 8, 24, 15, 0, 0);
+const daysAgo = (d, hour = 12) =>
+ new Date(2026, 8, 24 - d, hour, 0, 0).toISOString();
+
+test("sessions land in Today / Yesterday / 7 / 30 / Older by local day", () => {
+ const groups = groupSessionsByDate(
+ [
+ at("today", daysAgo(0, 0)),
+ at("yesterday", daysAgo(1, 23)),
+ at("week", daysAgo(7)),
+ at("month", daysAgo(30)),
+ at("old", daysAgo(31)),
+ ],
+ NOW,
+ );
+ assert.deepEqual(
+ groups.map((g) => [g.key, g.items.map((i) => i.session_id)]),
+ [
+ ["today", ["today"]],
+ ["yesterday", ["yesterday"]],
+ ["prev7", ["week"]],
+ ["prev30", ["month"]],
+ ["older", ["old"]],
+ ],
+ );
+});
+
+test("empty buckets are dropped and in-bucket order is preserved", () => {
+ const groups = groupSessionsByDate(
+ [at("b", daysAgo(0, 14)), at("a", daysAgo(0, 9))],
+ NOW,
+ );
+ assert.equal(groups.length, 1);
+ assert.deepEqual(groups[0].items.map((i) => i.session_id), ["b", "a"]);
+});
+
+test("an unparseable timestamp falls into Older instead of throwing", () => {
+ const groups = groupSessionsByDate([at("bad", "not-a-date")], NOW);
+ assert.deepEqual(groups.map((g) => g.key), ["older"]);
+});
diff --git a/packages/ui/src/app/chats/page.tsx b/packages/ui/src/app/chats/page.tsx
new file mode 100644
index 00000000..5e1812b9
--- /dev/null
+++ b/packages/ui/src/app/chats/page.tsx
@@ -0,0 +1,136 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { useRouter } from "next/navigation";
+import Icon from "@/components/Icon";
+import ChatHistory from "@/components/sessions/ChatHistory";
+import { useSessions } from "@/components/sessions/SessionsContext";
+import {
+ CHANNEL_LABELS,
+ CHANNEL_ORDER,
+ countByChannel,
+ filterSessions,
+ type SessionChannel,
+} from "@/lib/sessionChannel";
+
+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.
+export default function ChatsPage() {
+ const router = useRouter();
+ const { sessions, loaded, error, refresh, remove } = useSessions();
+ const [channel, setChannel] = useState<ChannelFilter>("all");
+ const [query, setQuery] = useState("");
+
+ useEffect(() => {
+ refresh();
+ }, [refresh]);
+
+ const counts = useMemo(() => countByChannel(sessions), [sessions]);
+ // "All" and "Web" always show; a channel tab appears once it has a chat.
+ const tabs: ChannelFilter[] = [
+ "all",
+ ...CHANNEL_ORDER.filter((c) => c === "web" || (counts[c] ?? 0) > 0),
+ ];
+ // Deleting a channel's last chat removes its tab; fall back to "All" rather
+ // than leave an invisible filter selected over an empty list. The derived
+ // value covers this render; the effect makes it stick, so a later refresh
+ // that brings the channel back doesn't silently re-select it.
+ const channelShown = tabs.includes(channel);
+ const activeChannel: ChannelFilter = channelShown ? channel : "all";
+ useEffect(() => {
+ if (!channelShown) setChannel("all");
+ }, [channelShown]);
+ const visible = useMemo(
+ () => filterSessions(sessions, { channel: activeChannel, query }),
+ [sessions, activeChannel, query],
+ );
+ const searching = query.trim().length > 0;
+
+ 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-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>
+
+ <div className="flex flex-col sm:flex-row sm:items-center gap-3 mb-5">
+ <div
+ role="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"
+ >
+ {tabs.map((t) => {
+ const active = activeChannel === t;
+ const count = t === "all" ? sessions.length : (counts[t] ?? 0);
+ return (
+ <button
+ key={t}
+ type="button"
+ 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"
+ }`}
+ >
+ {t === "all" ? "All" : CHANNEL_LABELS[t]}
+ <span className="ml-1.5 text-fg-subtle">{count}</span>
+ </button>
+ );
+ })}
+ </div>
+ <div className="relative sm:ml-auto sm:w-64">
+ <Icon
+ name="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"
+ />
+ <input
+ type="text"
+ value={query}
+ 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"
+ />
+ </div>
+ </div>
+
+ {!loaded ? (
+ <p className="px-3 py-6 text-sm text-fg-muted">Loading conversations…</p>
+ ) : error && sessions.length === 0 ? (
+ <p className="px-3 py-6 text-sm text-fg-muted">
+ Couldn&apos;t load your conversations.{" "}
+ <button
+ type="button"
+ onClick={refresh}
+ className="text-indigo-400 hover:text-indigo-300 font-medium cursor-pointer"
+ >
+ Try again
+ </button>
+ </p>
+ ) : sessions.length === 0 ? (
+ <p className="px-3 py-6 text-sm text-fg-muted">
+ No conversations yet. Start one with New chat.
+ </p>
+ ) : (
+ <ChatHistory
+ sessions={visible}
+ searching={searching}
+ onSelect={(id) => router.push(`/?session=${encodeURIComponent(id)}`)}
+ onDelete={(id) => void remove(id)}
+ />
+ )}
+ </div>
+ </main>
+ </div>
+ );
+}
diff --git a/packages/ui/src/app/layout.tsx b/packages/ui/src/app/layout.tsx
index c65dd466..38784897 100644
--- a/packages/ui/src/app/layout.tsx
+++ b/packages/ui/src/app/layout.tsx
@@ -1,5 +1,6 @@
import type { Metadata } from "next";
import AuthProvider from "@/components/AuthProvider";
+import { SessionsProvider } from "@/components/sessions/SessionsContext";
import AppShell from "@/components/shell/AppShell";
import "./globals.css";
@@ -17,7 +18,9 @@ export default function RootLayout({
<html lang="en" className="h-full">
<body className="h-full antialiased bg-surface text-fg">
<AuthProvider>
- <AppShell>{children}</AppShell>
+ <SessionsProvider>
+ <AppShell>{children}</AppShell>
+ </SessionsProvider>
</AuthProvider>
</body>
</html>
diff --git a/packages/ui/src/app/page.tsx b/packages/ui/src/app/page.tsx
index 6be02533..d4f66d04 100644
--- a/packages/ui/src/app/page.tsx
+++ b/packages/ui/src/app/page.tsx
@@ -2,17 +2,14 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useSession } from "next-auth/react";
-import BrandMark from "@/components/BrandMark";
import Briefing from "@/components/Briefing";
import Chat from "@/components/Chat";
import DebugPanel from "@/components/DebugPanel";
import Icon from "@/components/Icon";
-import RecentSessions from "@/components/RecentSessions";
-import SidebarNav from "@/components/SidebarNav";
+import { useSessions } from "@/components/sessions/SessionsContext";
import { MobileBottomNav } from "@/components/shell/AppShell";
-import { buildPrimaryNav, GUIDE_NAV_ITEM, SETTINGS_NAV_ITEM } from "@/components/shell/navConfig";
-import UserBadge from "@/components/UserBadge";
-import { ChatMessage, DebugEvent, ReviewStats, SessionSummary, deleteSession, getReviewStats, getSessionMessages, listSessions } from "@/lib/api";
+import AppSidebar from "@/components/shell/AppSidebar";
+import { ChatMessage, DebugEvent, getSessionMessages } from "@/lib/api";
import Link from "next/link";
import { useRouter } from "next/navigation";
@@ -31,10 +28,9 @@ export default function HomePage() {
const [debugEvents, setDebugEvents] = useState<DebugEvent[]>([]);
const activeTurnIdRef = useRef<string | null>(null);
const [isTurnInFlight, setIsTurnInFlight] = useState(false);
- const [sessions, setSessions] = useState<SessionSummary[]>([]);
+ const { sessions, loaded: sessionsLoaded, refresh: refreshSessions } = useSessions();
const [activeSessionId, setActiveSessionId] = useState<string | undefined>();
const [activeMessages, setActiveMessages] = useState<ChatMessage[]>([]);
- const [reviewStats, setReviewStats] = useState<ReviewStats | null>(null);
const [mobileNavOpen, setMobileNavOpen] = useState(false);
// Briefing-first landing: default to "briefing" so opening the app shows
// what's been happening, not an empty chat. Switches to "chat" when the
@@ -54,23 +50,17 @@ export default function HomePage() {
.catch(() => setHealth({ status: "error", company_profile_loaded: false }));
}, []);
- const refreshSessions = useCallback(() => {
- listSessions()
- .then(setSessions)
- .catch(() => {});
- }, []);
-
- useEffect(() => {
- refreshSessions();
- }, [refreshSessions]);
-
- useEffect(() => {
- getReviewStats().then(setReviewStats).catch(() => {});
- }, []);
+ // Bumped by every navigation handler below. A session load that resolves
+ // after the user has already moved on (new chat, briefing, a hand-off, or
+ // another session) sees a stale generation and is dropped instead of
+ // yanking them into the old chat mid-turn.
+ const selectGenRef = useRef(0);
const handleSelectSession = useCallback(async (sessionId: string) => {
+ const gen = ++selectGenRef.current;
try {
const msgs = await getSessionMessages(sessionId);
+ if (gen !== selectGenRef.current) return;
setActiveSessionId(sessionId);
setActiveMessages(msgs);
setDebugEvents([]);
@@ -84,6 +74,7 @@ export default function HomePage() {
}, []);
const handleNewChat = useCallback(() => {
+ selectGenRef.current++;
setActiveSessionId(undefined);
setActiveMessages([]);
setDebugEvents([]);
@@ -100,6 +91,7 @@ export default function HomePage() {
// and seeds the input with the briefing context. The user can edit
// before sending, or just hit send.
const handleContinueFromBriefing = useCallback((prompt: string, memoryText?: string) => {
+ selectGenRef.current++;
setActiveSessionId(undefined);
setActiveMessages([]);
setDebugEvents([]);
@@ -111,6 +103,7 @@ export default function HomePage() {
// Reset to the briefing view from anywhere. Used by the sidebar
// brandmark/header — clicking it returns home from a chat session.
const handleBackToBriefing = useCallback(() => {
+ selectGenRef.current++;
setActiveSessionId(undefined);
setActiveMessages([]);
setDebugEvents([]);
@@ -120,29 +113,6 @@ export default function HomePage() {
setMobileNavOpen(false);
}, []);
- const handleDeleteSession = useCallback(
- async (sessionId: string) => {
- if (!window.confirm("Delete this chat? This cannot be undone.")) return;
- try {
- await deleteSession(sessionId);
- } catch (err) {
- console.error(err);
- window.alert("Failed to delete chat.");
- return;
- }
- setActiveSessionId((current) => {
- if (current === sessionId) {
- setActiveMessages([]);
- setDebugEvents([]);
- return undefined;
- }
- return current;
- });
- refreshSessions();
- },
- [refreshSessions]
- );
-
const handleTurnComplete = useCallback((sessionId: string) => {
// Only adopt a real id. A turn that ends without ever learning one (an
// aborted stream) would otherwise set this to "", which <Chat> reads as
@@ -154,25 +124,45 @@ export default function HomePage() {
refreshSessions();
}, [refreshSessions]);
- // Cross-route "New chat" entry: the AppShell rail and mobile bottom
- // nav link to `/?new=1` from every inner route. When that param is
- // present on mount, reset to a fresh chat and strip the query so a
- // refresh doesn't reapply the action.
+ // Cross-route entries: from every inner route the sidebar and mobile
+ // bottom nav link to `/?new=1` (New chat) and `/?session=<id>` (a
+ // Recent chat, or a row on /chats). When either param is present on
+ // mount, apply it and strip the query so a refresh doesn't reapply it.
+ // A `session` id is held until the caller's own (owner-scoped) session
+ // list has loaded, and opened only if that list contains it: the id comes
+ // from the URL, and the per-session backend routes don't check ownership,
+ // so a crafted link must not open — or send turns into — someone else's
+ // conversation. It is also dropped if the user navigates first.
//
// Read directly from `window.location` rather than `useSearchParams`:
// that hook opts the page out of static rendering in Next 15 unless
// wrapped in <Suspense>, and the chat home is a heavy static page we
// want to keep prerendered. The effect runs client-only anyway.
const router = useRouter();
+ const deepLinkRef = useRef<{ sessionId: string; gen: number } | null>(null);
useEffect(() => {
if (typeof window === "undefined") return;
const params = new URLSearchParams(window.location.search);
+ const sessionParam = params.get("session");
if (params.get("new") === "1") {
handleNewChat();
router.replace("/");
+ } else if (sessionParam) {
+ deepLinkRef.current = { sessionId: sessionParam, gen: selectGenRef.current };
+ router.replace("/");
}
}, [handleNewChat, router]);
+ useEffect(() => {
+ const pending = deepLinkRef.current;
+ if (!pending || !sessionsLoaded) return;
+ deepLinkRef.current = null;
+ if (pending.gen !== selectGenRef.current) return;
+ if (sessions.some((s) => s.session_id === pending.sessionId)) {
+ void handleSelectSession(pending.sessionId);
+ }
+ }, [sessions, sessionsLoaded, handleSelectSession]);
+
// Group debug events by turn_id. When we see a new turn_id, reset the
// panel. Track the current turn_id in a ref — state updater functions
// must be pure, but React Strict Mode double-invokes them in dev, so
@@ -195,15 +185,6 @@ export default function HomePage() {
const isOnboarded = health?.company_profile_loaded === true;
const companyName = health?.company_name;
- const reviewBadge = reviewStats != null ? reviewStats.pending + reviewStats.needs_revision : 0;
- // Primary nav is built from the shared config in
- // `components/shell/navConfig.ts` — the single source of truth the
- // AppShell rail also uses, so the two navs can never drift. Admin /
- // power tools are NOT here; they live on the Settings hub (linked from
- // the footer below). "Today" is intentionally omitted — the Briefing
- // button above is the in-app way back to that content.
- const navSections = buildPrimaryNav({ isOnboarded, reviewBadge });
-
return (
<div className="flex h-full relative">
{/* Mobile backdrop */}
@@ -215,97 +196,24 @@ export default function HomePage() {
/>
)}
- {/* Sidebar — slides in on mobile, static on md+ */}
- <aside
- className={`
- fixed top-8 bottom-0 left-0 z-40 w-64 md:w-56 md:top-0 flex-shrink-0
- border-r border-line flex flex-col bg-surface-elevated
- transform transition-transform duration-200
- md:relative md:translate-x-0 md:transition-none
- ${mobileNavOpen ? "translate-x-0" : "-translate-x-full"}
- `}
- >
- {/* Logo — clicking returns to the briefing landing */}
- <div className="px-4 py-5 border-b border-line flex items-center justify-between flex-shrink-0">
- <button
- type="button"
- onClick={handleBackToBriefing}
- aria-label="Back to briefing"
- className="flex items-center gap-2.5 min-w-0 text-left cursor-pointer hover:opacity-80 transition-opacity"
- >
- <div className="flex-shrink-0">
- <BrandMark size="sm" />
- </div>
- <div className="min-w-0">
- <p className="text-sm font-semibold text-fg">Open Executive</p>
- {companyName && (
- <p className="text-xs text-fg-muted truncate">{companyName}</p>
- )}
- </div>
- </button>
- {/* Close button on mobile only */}
- <button
- type="button"
- aria-label="Close menu"
- onClick={() => setMobileNavOpen(false)}
- className="md:hidden min-h-touch min-w-touch flex items-center justify-center text-fg-muted hover:text-fg cursor-pointer rounded-lg hover:bg-surface-overlay transition-colors"
- >
- <Icon name="close" size="w-5 h-5" />
- </button>
- </div>
-
- {/* Nav region — own scroll; compresses/scrolls internally only when the
- sidebar is too short, so Recent below always keeps a usable height */}
- <div className="min-h-0 overflow-y-auto pt-3">
- <SidebarNav
- sections={navSections}
- briefingActive={mode === "briefing"}
- newChatActive={mode === "chat" && activeSessionId === undefined}
- onBriefing={handleBackToBriefing}
- onNewChat={handleNewChat}
- onNavigate={() => setMobileNavOpen(false)}
- />
-
- </div>
-
- {/* Recent conversations — date-grouped, searchable, own scroll region */}
- <RecentSessions
- sessions={sessions}
- activeSessionId={activeSessionId}
- onSelect={handleSelectSession}
- onDelete={(id) => void handleDeleteSession(id)}
- />
-
- {/* Spacer — pins the footer to the bottom now that Recent is content-sized */}
- <div className="flex-1 min-h-0" />
-
- {/* Footer — 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 py-2 border-t border-line flex-shrink-0 space-y-0.5">
- <Link
- href={GUIDE_NAV_ITEM.href}
- onClick={() => setMobileNavOpen(false)}
- title={GUIDE_NAV_ITEM.description}
- className="px-3 py-2.5 min-h-touch rounded-lg hover:bg-surface-overlay text-fg-muted hover:text-fg flex items-center gap-2.5 text-sm transition-colors cursor-pointer"
- >
- <Icon name={GUIDE_NAV_ITEM.icon} size="w-4 h-4" />
- <span className="flex-1">{GUIDE_NAV_ITEM.label}</span>
- </Link>
- <Link
- href={SETTINGS_NAV_ITEM.href}
- onClick={() => setMobileNavOpen(false)}
- title={SETTINGS_NAV_ITEM.description}
- className="px-3 py-2.5 min-h-touch rounded-lg hover:bg-surface-overlay text-fg-muted hover:text-fg flex items-center gap-2.5 text-sm transition-colors cursor-pointer"
- >
- <Icon name={SETTINGS_NAV_ITEM.icon} size="w-4 h-4" />
- <span className="flex-1">{SETTINGS_NAV_ITEM.label}</span>
- </Link>
- </div>
-
- {/* Signed-in user */}
- <UserBadge variant="sidebar" />
- </aside>
+ {/* Sidebar — the same one every route renders (AppShell uses it
+ too); slides in on mobile, static on md+. On the home page its
+ entries drive this page's in-memory state instead of navigating. */}
+ <AppSidebar
+ pathname="/"
+ open={mobileNavOpen}
+ onClose={() => setMobileNavOpen(false)}
+ breakpoint="md"
+ isOnboarded={health ? isOnboarded : undefined}
+ companyName={companyName}
+ home={{
+ mode,
+ activeSessionId,
+ onBriefing: handleBackToBriefing,
+ onNewChat: handleNewChat,
+ onSelectSession: (id) => void handleSelectSession(id),
+ }}
+ />
{/* Main */}
<main className="flex-1 flex flex-col min-w-0">
diff --git a/packages/ui/src/components/RecentSessions.tsx b/packages/ui/src/components/RecentSessions.tsx
deleted file mode 100644
index 14c346dc..00000000
--- a/packages/ui/src/components/RecentSessions.tsx
+++ /dev/null
@@ -1,161 +0,0 @@
-"use client";
-
-import { useMemo, useState } from "react";
-import Icon from "@/components/Icon";
-import type { SessionSummary } from "@/lib/api";
-import { groupSessionsByDate, type GroupKey } from "@/lib/sessionGroups";
-import { formatRelativeTime } from "@/lib/relativeTime";
-
-const GROUP_CAP = 8;
-const DEFAULT_COLLAPSED = new Set<GroupKey>(["prev30", "older"]);
-
-interface RecentSessionsProps {
- sessions: SessionSummary[];
- activeSessionId?: string;
- onSelect: (sessionId: string) => void;
- onDelete: (sessionId: string) => void;
-}
-
-export default function RecentSessions({
- sessions,
- activeSessionId,
- onSelect,
- onDelete,
-}: RecentSessionsProps) {
- const [query, setQuery] = useState("");
- const [collapsedOverride, setCollapsedOverride] = useState<Record<string, boolean>>({});
- const [showAll, setShowAll] = useState<Set<string>>(new Set());
-
- const trimmedQuery = query.trim().toLowerCase();
- const searching = trimmedQuery.length > 0;
-
- const filtered = useMemo(() => {
- if (!searching) return sessions;
- return sessions.filter((s) =>
- (s.title || "Untitled chat").toLowerCase().includes(trimmedQuery),
- );
- }, [sessions, searching, trimmedQuery]);
-
- const groups = useMemo(() => groupSessionsByDate(filtered), [filtered]);
-
- if (sessions.length === 0) return null;
-
- // Stored collapse state (default-collapsed unless the user toggled it). While
- // searching we force every group open so matches are never hidden, but the
- // stored state is preserved and re-applies once the query is cleared.
- const storedCollapsed = (key: GroupKey) =>
- key in collapsedOverride ? collapsedOverride[key] : DEFAULT_COLLAPSED.has(key);
- const isCollapsed = (key: GroupKey) => (searching ? false : storedCollapsed(key));
- const toggleCollapse = (key: GroupKey) =>
- setCollapsedOverride((prev) => ({ ...prev, [key]: !storedCollapsed(key) }));
- const revealAll = (key: GroupKey) =>
- setShowAll((prev) => new Set(prev).add(key));
-
- return (
- <div className="flex flex-col min-h-0">
- {/* Pinned header — label + search, stays put while the list scrolls */}
- <div className="flex-shrink-0 px-2 pt-3 pb-2">
- <p className="px-2 pb-1.5 text-xs text-fg-subtle font-medium uppercase tracking-wide">
- Recent
- </p>
- <div className="relative">
- <Icon
- name="search"
- size="w-3.5 h-3.5"
- className="absolute left-2 top-1/2 -translate-y-1/2 text-fg-subtle pointer-events-none"
- />
- <input
- type="text"
- value={query}
- 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-7 pr-2 py-1.5 text-xs text-fg placeholder:text-fg-subtle focus:outline-none focus:border-fg-subtle"
- />
- </div>
- </div>
-
- {/* Scrollable list */}
- <div className="overflow-y-auto min-h-0 max-h-[75vh] px-2 pb-2">
- {groups.length === 0 ? (
- <p className="px-2 py-3 text-xs text-fg-subtle">No conversations match.</p>
- ) : (
- groups.map((group) => {
- const collapsed = isCollapsed(group.key);
- const expandedAll = searching || showAll.has(group.key);
- const visible = expandedAll ? group.items : group.items.slice(0, GROUP_CAP);
- const hiddenCount = group.items.length - visible.length;
- return (
- <div key={group.key} className="mb-1">
- <button
- type="button"
- onClick={() => toggleCollapse(group.key)}
- aria-expanded={!collapsed}
- className="sticky top-0 z-10 w-full flex items-center gap-1.5 px-2 py-1.5 bg-surface-elevated 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">
- {group.label}
- </span>
- <span className="text-[10px] text-fg-subtle/70">{group.items.length}</span>
- </button>
- {!collapsed && (
- <div className="space-y-0.5">
- {visible.map((s) => (
- <div
- key={s.session_id}
- className={`group relative flex items-center rounded-lg transition-colors ${
- activeSessionId === s.session_id
- ? "bg-surface-overlay text-fg"
- : "text-fg-muted hover:bg-surface-overlay/60 hover:text-fg"
- }`}
- >
- <button
- type="button"
- onClick={() => onSelect(s.session_id)}
- className="flex-1 min-w-0 text-left px-2 py-2 pr-10 cursor-pointer"
- >
- <p className="text-xs truncate leading-snug">
- {s.title || "Untitled chat"}
- </p>
- <p className="text-[10px] text-fg-subtle mt-0.5">
- {formatRelativeTime(s.updated_at)}
- </p>
- </button>
- <button
- type="button"
- aria-label="Delete chat"
- title="Delete chat"
- onClick={(e) => {
- e.stopPropagation();
- onDelete(s.session_id);
- }}
- className="absolute right-1 top-1/2 -translate-y-1/2 min-h-touch min-w-touch flex items-center justify-center rounded opacity-0 group-hover:opacity-100 focus:opacity-100 text-fg-muted hover:text-red-400 hover:bg-surface-input/60 transition-opacity cursor-pointer"
- >
- <Icon name="trash" size="w-4 h-4" />
- </button>
- </div>
- ))}
- {hiddenCount > 0 && (
- <button
- type="button"
- onClick={() => revealAll(group.key)}
- className="w-full text-left px-2 py-1.5 text-[11px] text-fg-subtle hover:text-fg cursor-pointer"
- >
- Show {hiddenCount} more
- </button>
- )}
- </div>
- )}
- </div>
- );
- })
- )}
- </div>
- </div>
- );
-}
diff --git a/packages/ui/src/components/SidebarNav.tsx b/packages/ui/src/components/SidebarNav.tsx
deleted file mode 100644
index 06379b20..00000000
--- a/packages/ui/src/components/SidebarNav.tsx
+++ /dev/null
@@ -1,133 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import Link from "next/link";
-import Icon from "@/components/Icon";
-import {
- BRIEFING_DESCRIPTION,
- NavGroup,
- NEW_CHAT_DESCRIPTION,
- PULSE_NAV_ITEM,
-} from "@/components/shell/navConfig";
-
-interface SidebarNavProps {
- sections: NavGroup[];
- briefingActive: boolean;
- newChatActive: boolean;
- onBriefing: () => void;
- onNewChat: () => void;
- onNavigate: () => void;
-}
-
-export default function SidebarNav({
- sections,
- briefingActive,
- newChatActive,
- onBriefing,
- onNewChat,
- onNavigate,
-}: SidebarNavProps) {
- // Explicit user toggles; absent keys fall back to "open only the first
- // section" so the menu starts short and the rest are tucked away.
- const [collapsedOverride, setCollapsedOverride] = useState<Record<string, boolean>>({});
-
- const isCollapsed = (key: string, index: number) =>
- key in collapsedOverride ? collapsedOverride[key] : index !== 0;
- const toggle = (key: string, index: number) =>
- setCollapsedOverride((prev) => ({ ...prev, [key]: !isCollapsed(key, index) }));
-
- return (
- <nav className="px-2 pt-3 pb-2 space-y-0.5">
- {/* New chat first — the single most-used action in a chat-first
- product, kept at the top of the sidebar to match the persistent
- rail (see AppShell) so the two navs agree on every route. */}
- <button
- type="button"
- onClick={onNewChat}
- title={NEW_CHAT_DESCRIPTION}
- className={`w-full text-left px-3 py-2.5 min-h-touch rounded-lg flex items-center gap-2.5 text-sm font-medium transition-colors cursor-pointer ${
- newChatActive
- ? "bg-surface-overlay text-fg"
- : "text-fg-muted hover:bg-surface-overlay hover:text-fg"
- }`}
- >
- <Icon name="plus" size="w-4 h-4" />
- New chat
- </button>
- <button
- type="button"
- onClick={onBriefing}
- title={BRIEFING_DESCRIPTION}
- className={`w-full text-left px-3 py-2.5 min-h-touch rounded-lg flex items-center gap-2.5 text-sm font-medium transition-colors cursor-pointer ${
- briefingActive
- ? "bg-surface-overlay text-fg"
- : "text-fg-muted hover:bg-surface-overlay hover:text-fg"
- }`}
- >
- <Icon name="clipboard" size="w-4 h-4" />
- Briefing
- </button>
- {/* Pulse — pinned beside Briefing/New chat as an always-visible
- destination, mirroring the persistent rail. */}
- <Link
- href={PULSE_NAV_ITEM.href}
- onClick={onNavigate}
- title={PULSE_NAV_ITEM.description}
- className="w-full text-left px-3 py-2.5 min-h-touch rounded-lg flex items-center gap-2.5 text-sm font-medium transition-colors cursor-pointer text-fg-muted hover:bg-surface-overlay hover:text-fg"
- >
- <Icon name={PULSE_NAV_ITEM.icon} size="w-4 h-4" />
- {PULSE_NAV_ITEM.label}
- </Link>
-
- {sections.map((section, index) => {
- const collapsed = isCollapsed(section.key, index);
- const badgeTotal = section.items.reduce((sum, e) => sum + (e.badge ?? 0), 0);
- return (
- <div key={section.key} className="pt-2">
- <button
- type="button"
- onClick={() => toggle(section.key, index)}
- 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">
- {section.label}
- </span>
- {collapsed && badgeTotal > 0 && (
- <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">
- {badgeTotal}
- </span>
- )}
- </button>
- {!collapsed && (
- <div className="space-y-0.5 mt-0.5">
- {section.items.map((entry) => (
- <Link
- key={entry.href}
- href={entry.href}
- onClick={onNavigate}
- title={entry.description}
- className="px-3 py-2.5 min-h-touch rounded-lg hover:bg-surface-overlay text-fg-muted hover:text-fg flex items-center gap-2.5 text-sm transition-colors cursor-pointer"
- >
- <Icon name={entry.icon} size="w-4 h-4" />
- <span className="flex-1">{entry.label}</span>
- {entry.badge != null && entry.badge > 0 && (
- <span className="ml-auto 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">
- {entry.badge}
- </span>
- )}
- </Link>
- ))}
- </div>
- )}
- </div>
- );
- })}
- </nav>
- );
-}
diff --git a/packages/ui/src/components/sessions/ChatHistory.tsx b/packages/ui/src/components/sessions/ChatHistory.tsx
new file mode 100644
index 00000000..da1b0d20
--- /dev/null
+++ b/packages/ui/src/components/sessions/ChatHistory.tsx
@@ -0,0 +1,132 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import Icon from "@/components/Icon";
+import type { SessionSummary } from "@/lib/api";
+import { formatRelativeTime } from "@/lib/relativeTime";
+import { CHANNEL_LABELS, sessionChannel, sessionTitle } from "@/lib/sessionChannel";
+import { groupSessionsByDate, type GroupKey } from "@/lib/sessionGroups";
+
+const GROUP_CAP = 20;
+const DEFAULT_COLLAPSED = new Set<GroupKey>(["older"]);
+
+interface ChatHistoryProps {
+ /** Already filtered by channel and search; newest first. */
+ sessions: SessionSummary[];
+ /** 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;
+}
+
+// Date-grouped conversation list for /chats — the full history the sidebar's
+// short Recent list links to.
+export default function ChatHistory({ sessions, searching, onSelect, onDelete }: ChatHistoryProps) {
+ const [collapsedOverride, setCollapsedOverride] = useState<Record<string, boolean>>({});
+ const [showAll, setShowAll] = useState<Set<string>>(new Set());
+
+ 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>;
+ }
+
+ // Stored collapse state (default-collapsed unless the user toggled it). While
+ // searching we force every group open so matches are never hidden, but the
+ // stored state is preserved and re-applies once the query is cleared.
+ const storedCollapsed = (key: GroupKey) =>
+ key in collapsedOverride ? collapsedOverride[key] : DEFAULT_COLLAPSED.has(key);
+ const isCollapsed = (key: GroupKey) => (searching ? false : storedCollapsed(key));
+ const toggleCollapse = (key: GroupKey) =>
+ setCollapsedOverride((prev) => ({ ...prev, [key]: !storedCollapsed(key) }));
+ const revealAll = (key: GroupKey) => setShowAll((prev) => new Set(prev).add(key));
+
+ return (
+ <div className="space-y-4">
+ {groups.map((group) => {
+ const collapsed = isCollapsed(group.key);
+ const expandedAll = searching || showAll.has(group.key);
+ const visible = expandedAll ? group.items : group.items.slice(0, GROUP_CAP);
+ const hiddenCount = group.items.length - visible.length;
+ return (
+ <section key={group.key}>
+ <button
+ 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"
+ >
+ <Icon
+ name="chevron-right"
+ size="w-3 h-3"
+ 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>
+ </button>
+ {!collapsed && (
+ <div className="mt-1 space-y-0.5">
+ {visible.map((s) => (
+ <ChatRow key={s.session_id} session={s} onSelect={onSelect} onDelete={onDelete} />
+ ))}
+ {hiddenCount > 0 && (
+ <button
+ type="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"
+ >
+ Show {hiddenCount} more
+ </button>
+ )}
+ </div>
+ )}
+ </section>
+ );
+ })}
+ </div>
+ );
+}
+
+function ChatRow({
+ session,
+ onSelect,
+ onDelete,
+}: {
+ session: SessionSummary;
+ onSelect: (sessionId: string) => void;
+ onDelete: (sessionId: string) => void;
+}) {
+ const channel = sessionChannel(session.session_id);
+ const messages = `${session.message_count} message${session.message_count === 1 ? "" : "s"}`;
+ 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>
+ );
+}
diff --git a/packages/ui/src/components/sessions/SessionsContext.tsx b/packages/ui/src/components/sessions/SessionsContext.tsx
new file mode 100644
index 00000000..a95ae58b
--- /dev/null
+++ b/packages/ui/src/components/sessions/SessionsContext.tsx
@@ -0,0 +1,81 @@
+"use client";
+
+import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
+import { useSession } from "next-auth/react";
+import { deleteSession, listSessions, type SessionSummary } from "@/lib/api";
+
+// App-wide conversation list. Lives in the root layout so the shared sidebar
+// shows the same Recent list on every route, and the chat home can refresh it
+// after a turn without owning the state itself.
+interface SessionsContextValue {
+ sessions: SessionSummary[];
+ /** False until the first list request has settled, so pages can tell "empty" from "not loaded yet". */
+ loaded: boolean;
+ /** True when the latest list request failed — distinct from an empty history. */
+ error: boolean;
+ refresh: () => void;
+ /** Confirms, deletes, and refreshes. Resolves true only if the chat was deleted. */
+ remove: (sessionId: string) => Promise<boolean>;
+}
+
+const SessionsContext = createContext<SessionsContextValue | null>(null);
+
+export function SessionsProvider({ children }: { children: React.ReactNode }) {
+ const { status } = useSession();
+ const [sessions, setSessions] = useState<SessionSummary[]>([]);
+ const [loaded, setLoaded] = useState(false);
+ const [error, setError] = useState(false);
+ // Only the newest request may write: several refreshes can overlap (mount,
+ // /chats, after a delete), and an older response landing last would
+ // resurrect a just-deleted chat.
+ const requestSeqRef = useRef(0);
+
+ const refresh = useCallback(() => {
+ const seq = ++requestSeqRef.current;
+ listSessions()
+ .then((list) => {
+ if (seq !== requestSeqRef.current) return;
+ setSessions(list);
+ setError(false);
+ setLoaded(true);
+ })
+ .catch(() => {
+ if (seq !== requestSeqRef.current) return;
+ setError(true);
+ setLoaded(true);
+ });
+ }, []);
+
+ // Only fetch once signed in — /signin renders under this provider too.
+ useEffect(() => {
+ if (status === "authenticated") refresh();
+ }, [status, refresh]);
+
+ 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();
+ return true;
+ },
+ [refresh],
+ );
+
+ const value = useMemo(
+ () => ({ sessions, loaded, error, refresh, remove }),
+ [sessions, loaded, error, refresh, remove],
+ );
+ return <SessionsContext.Provider value={value}>{children}</SessionsContext.Provider>;
+}
+
+export function useSessions(): SessionsContextValue {
+ const ctx = useContext(SessionsContext);
+ if (!ctx) throw new Error("useSessions must be used inside <SessionsProvider>");
+ return ctx;
+}
diff --git a/packages/ui/src/components/shell/AppShell.tsx b/packages/ui/src/components/shell/AppShell.tsx
index 100a28ad..ae409202 100644
--- a/packages/ui/src/components/shell/AppShell.tsx
+++ b/packages/ui/src/components/shell/AppShell.tsx
@@ -6,31 +6,17 @@ import { useState } from "react";
import { AskOEProvider, useAskOE } from "@/components/askoe/AskOEContext";
import AskOEPanel from "@/components/askoe/AskOEPanel";
-import BrandMark from "@/components/BrandMark";
-import Icon, { IconName } from "@/components/Icon";
-import UserBadge from "@/components/UserBadge";
-import {
- BRIEFING_DESCRIPTION,
- buildPrimaryNav,
- GUIDE_NAV_ITEM,
- MOBILE_PRIMARY,
- NEW_CHAT_DESCRIPTION,
- PULSE_NAV_ITEM,
- SETTINGS_NAV_ITEM,
-} from "@/components/shell/navConfig";
+import Icon from "@/components/Icon";
+import AppSidebar from "@/components/shell/AppSidebar";
+import { isNavActive, MOBILE_PRIMARY } from "@/components/shell/navConfig";
// Routes that own their full layout and should not be wrapped by the
// shell — sign-in, the onboarding wizard (full-screen flow), and the
-// chat home (`/`) which already provides its own sidebar with
-// recent-session controls. Every other route renders inside the shell.
+// chat home (`/`), which keeps its own top bar and debug panel but
+// renders the same `AppSidebar` as every other route.
const EXEMPT_PREFIXES = ["/signin", "/onboard", "/api"];
const EXEMPT_EXACT = new Set(["/"]);
-// Primary nav comes from the shared config (the same source the chat
-// home uses) so the two navs can never drift. The rail is only reached
-// post-onboarding, so the default `isOnboarded` is fine here.
-const NAV_GROUPS = buildPrimaryNav();
-
// Human-readable labels for path segments shown in the breadcrumb.
// Dynamic segments (slugs / ids) are rendered raw and truncated by CSS.
const SEGMENT_LABELS: Record<string, string> = {
@@ -44,6 +30,7 @@ const SEGMENT_LABELS: Record<string, string> = {
knowledge: "Knowledge base",
jobs: "Workflows",
artifacts: "Artifacts",
+ chats: "Chats",
runs: "Runs",
new: "New",
audit: "Audit log",
@@ -64,13 +51,6 @@ function labelFor(segment: string): string {
return SEGMENT_LABELS[segment] ?? segment;
}
-// Is `href` the active section for the current pathname? Active when
-// pathname matches exactly or sits below href as a sub-route.
-function isActive(href: string, pathname: string): boolean {
- if (href === "/") return pathname === "/";
- return pathname === href || pathname.startsWith(`${href}/`);
-}
-
function isExempt(pathname: string): boolean {
if (EXEMPT_EXACT.has(pathname)) return true;
return EXEMPT_PREFIXES.some((p) => pathname === p || pathname.startsWith(`${p}/`));
@@ -98,11 +78,14 @@ export default function AppShell({ children }: { children: React.ReactNode }) {
/>
)}
- {/* Left rail — fixed drawer on mobile, static on lg+ */}
- <Rail
+ {/* Left sidebar — fixed drawer on mobile, static on lg+. The rail
+ is only reached post-onboarding, so the default `isOnboarded`
+ is fine here. */}
+ <AppSidebar
pathname={pathname}
- drawerOpen={drawerOpen}
+ open={drawerOpen}
onClose={() => setDrawerOpen(false)}
+ breakpoint="lg"
/>
{/* Main column */}
@@ -128,168 +111,6 @@ export default function AppShell({ children }: { children: React.ReactNode }) {
);
}
-function Rail({
- pathname,
- drawerOpen,
- onClose,
-}: {
- pathname: string;
- drawerOpen: boolean;
- onClose: () => void;
-}) {
- return (
- <aside
- className={`
- fixed top-8 bottom-0 left-0 z-40 w-64 lg:w-56 lg:top-0 flex-shrink-0
- border-r border-line flex flex-col bg-surface-elevated
- transform transition-transform duration-200
- lg:relative lg:translate-x-0 lg:transition-none
- ${drawerOpen ? "translate-x-0" : "-translate-x-full"}
- `}
- >
- <div className="px-4 py-4 border-b border-line flex items-center justify-between flex-shrink-0">
- <Link
- href="/"
- onClick={onClose}
- className="flex items-center gap-2.5 min-w-0 text-fg hover:opacity-80 transition-opacity"
- >
- <BrandMark size="sm" />
- <span className="text-sm font-semibold truncate">Open Executive</span>
- </Link>
- <button
- type="button"
- aria-label="Close menu"
- onClick={onClose}
- className="lg:hidden min-h-touch min-w-touch flex items-center justify-center text-fg-muted hover:text-fg cursor-pointer rounded-lg hover:bg-surface-overlay transition-colors"
- >
- <Icon name="close" size="w-5 h-5" />
- </button>
- </div>
-
- <nav className="flex-1 overflow-y-auto px-2 py-3 space-y-4">
- {/* New chat — the single most-used action in a chat-first
- product, so it lives at the top of the rail on every route.
- `/?new=1` is consumed by the chat home, which resets state
- and strips the query. Never marked active (it's an action,
- not a destination). */}
- <RailLink
- href="/?new=1"
- label="New chat"
- icon="plus"
- description={NEW_CHAT_DESCRIPTION}
- active={false}
- onClick={onClose}
- accent
- />
- {/* Briefing — `/` lands on the briefing surface (main's
- briefing-first refactor); the chat is reached from there via
- "New chat" or by selecting a recent session. Labelled
- accordingly so the rail doesn't promise something else. */}
- <RailLink
- href="/"
- label="Briefing"
- icon="clipboard"
- description={BRIEFING_DESCRIPTION}
- active={pathname === "/"}
- onClick={onClose}
- />
- {/* Pulse — pinned beside Briefing as an always-visible destination,
- not buried in the Knowledge group. */}
- <RailLink
- href={PULSE_NAV_ITEM.href}
- label={PULSE_NAV_ITEM.label}
- icon={PULSE_NAV_ITEM.icon}
- description={PULSE_NAV_ITEM.description}
- active={isActive(PULSE_NAV_ITEM.href, pathname)}
- onClick={onClose}
- />
-
- {NAV_GROUPS.map((group) => (
- <div key={group.key}>
- <p className="px-3 mb-1 text-[10px] font-semibold uppercase tracking-widest text-fg-subtle">
- {group.label}
- </p>
- <div className="space-y-0.5">
- {group.items.map((item) => (
- <RailLink
- key={item.href}
- href={item.href}
- label={item.label}
- icon={item.icon}
- description={item.description}
- active={isActive(item.href, pathname)}
- onClick={onClose}
- />
- ))}
- </div>
- </div>
- ))}
- </nav>
-
- {/* Footer — 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. Pinned just above the user badge. */}
- <div className="px-2 pb-1 border-t border-line pt-2 space-y-0.5">
- <RailLink
- href={GUIDE_NAV_ITEM.href}
- label={GUIDE_NAV_ITEM.label}
- icon={GUIDE_NAV_ITEM.icon}
- description={GUIDE_NAV_ITEM.description}
- active={isActive(GUIDE_NAV_ITEM.href, pathname)}
- onClick={onClose}
- />
- <RailLink
- href={SETTINGS_NAV_ITEM.href}
- label={SETTINGS_NAV_ITEM.label}
- icon={SETTINGS_NAV_ITEM.icon}
- description={SETTINGS_NAV_ITEM.description}
- active={isActive(SETTINGS_NAV_ITEM.href, pathname)}
- onClick={onClose}
- />
- </div>
-
- <UserBadge variant="sidebar" />
- </aside>
- );
-}
-
-function RailLink({
- href,
- label,
- icon,
- description,
- active,
- onClick,
- accent,
-}: {
- href: string;
- label: string;
- icon: IconName;
- /** Tooltip explaining the destination — shown via `title` on hover. */
- description?: string;
- active: boolean;
- onClick: () => void;
- accent?: boolean;
-}) {
- // Active styling: filled overlay + bolder text. Accent (used for the
- // Chat entry) gets a subtle indigo tint to mark the primary action.
- const base =
- "px-3 py-2 min-h-touch rounded-lg flex items-center gap-2.5 text-sm transition-colors cursor-pointer";
- 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";
- return (
- <Link href={href} onClick={onClick} title={description} className={`${base} ${tone}`}>
- <Icon name={icon} size="w-4 h-4" />
- <span className="flex-1 truncate">{label}</span>
- </Link>
- );
-}
-
function TopBar({
segments,
onOpenDrawer,
@@ -404,7 +225,7 @@ export function MobileBottomNav({
className={`${hideClass} h-16 border-t border-line bg-surface-elevated flex items-stretch flex-shrink-0`}
>
{MOBILE_PRIMARY.map((item) => {
- const active = isActive(item.href, pathname);
+ const active = isNavActive(item.href, pathname);
return (
<Link
key={item.href}
diff --git a/packages/ui/src/components/shell/AppSidebar.tsx b/packages/ui/src/components/shell/AppSidebar.tsx
new file mode 100644
index 00000000..1671ae6c
--- /dev/null
+++ b/packages/ui/src/components/shell/AppSidebar.tsx
@@ -0,0 +1,444 @@
+"use client";
+
+import Link from "next/link";
+import { useEffect, useState } from "react";
+
+import BrandMark from "@/components/BrandMark";
+import Icon, { IconName } from "@/components/Icon";
+import { useSessions } from "@/components/sessions/SessionsContext";
+import UserBadge from "@/components/UserBadge";
+import {
+ BRIEFING_DESCRIPTION,
+ buildPrimaryNav,
+ GUIDE_NAV_ITEM,
+ 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,
+ * active session), so its entries are buttons that call back into the page;
+ * everywhere else the same entries are links (`/?new=1`, `/?session=<id>`)
+ * that the home page consumes on mount.
+ */
+export interface SidebarHomeControls {
+ mode: "briefing" | "chat";
+ activeSessionId?: string;
+ onBriefing: () => void;
+ onNewChat: () => void;
+ onSelectSession: (sessionId: string) => void;
+}
+
+interface AppSidebarProps {
+ pathname: string;
+ open: boolean;
+ onClose: () => void;
+ /** Width at which the sidebar stops being a drawer and sits in the layout. */
+ breakpoint: "md" | "lg";
+ isOnboarded?: boolean;
+ companyName?: string;
+ home?: SidebarHomeControls;
+}
+
+// Full literal class strings per breakpoint so Tailwind keeps them in the build.
+const ASIDE_CLASSES = {
+ md: "w-64 md:w-56 md:top-0 md:relative md:translate-x-0 md:transition-none",
+ lg: "w-64 lg:w-56 lg:top-0 lg:relative lg:translate-x-0 lg:transition-none",
+} as const;
+const HIDE_FROM = { md: "md:hidden", lg: "lg:hidden" } as const;
+
+export default function AppSidebar({
+ pathname,
+ open,
+ onClose,
+ breakpoint,
+ isOnboarded,
+ companyName,
+ home,
+}: AppSidebarProps) {
+ const { sessions } = useSessions();
+ const [reviewBadge, setReviewBadge] = useState(0);
+
+ // Refetched on navigation so approving items on /review clears the badge
+ // once you move on, rather than only on a full reload.
+ useEffect(() => {
+ getReviewStats()
+ .then((s) => setReviewBadge(s.pending + s.needs_revision))
+ .catch(() => {});
+ }, [pathname]);
+
+ const groups = buildPrimaryNav({ isOnboarded, reviewBadge });
+ const recent = recentWebChats(sessions, RECENT_LIMIT);
+
+ const briefingActive = home ? home.mode === "briefing" : isNavActive("/", pathname);
+ const newChatActive = home ? home.mode === "chat" && home.activeSessionId === undefined : false;
+
+ return (
+ <aside
+ className={`
+ fixed top-8 bottom-0 left-0 z-40 flex-shrink-0
+ border-r border-line flex flex-col bg-surface-elevated
+ transform transition-transform duration-200
+ ${ASIDE_CLASSES[breakpoint]}
+ ${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">
+ <SidebarEntry
+ href={home ? undefined : "/"}
+ onClick={home ? home.onBriefing : onClose}
+ ariaLabel="Back to briefing"
+ 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>
+ {companyName && (
+ <span className="block text-xs text-fg-muted truncate">{companyName}</span>
+ )}
+ </span>
+ </SidebarEntry>
+ <button
+ type="button"
+ aria-label="Close menu"
+ onClick={onClose}
+ className={`${HIDE_FROM[breakpoint]} min-h-touch min-w-touch flex items-center justify-center text-fg-muted hover:text-fg cursor-pointer rounded-lg hover:bg-surface-overlay transition-colors`}
+ >
+ <Icon name="close" size="w-5 h-5" />
+ </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} />
+
+ <RecentChats
+ recent={recent}
+ hasAny={sessions.length > 0}
+ activeSessionId={home?.activeSessionId}
+ allChatsActive={isNavActive("/chats", pathname)}
+ onSelect={home?.onSelectSession}
+ onNavigate={onClose}
+ />
+ </nav>
+
+ {/* Footer — 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">
+ {[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>
+
+ <UserBadge variant="sidebar" />
+ </aside>
+ );
+}
+
+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({
+ href,
+ onClick,
+ title,
+ ariaLabel,
+ ariaCurrent,
+ className,
+ children,
+}: {
+ href?: string;
+ onClick: () => void;
+ title?: string;
+ ariaLabel?: string;
+ ariaCurrent?: boolean;
+ className: string;
+ children: React.ReactNode;
+}) {
+ const current = ariaCurrent ? ("page" as const) : undefined;
+ if (href) {
+ return (
+ <Link
+ href={href}
+ onClick={onClick}
+ title={title}
+ aria-label={ariaLabel}
+ aria-current={current}
+ className={className}
+ >
+ {children}
+ </Link>
+ );
+ }
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ title={title}
+ aria-label={ariaLabel}
+ aria-current={current}
+ className={className}
+ >
+ {children}
+ </button>
+ );
+}
+
+function NavRow({
+ href,
+ onClick,
+ label,
+ icon,
+ description,
+ active,
+ accent,
+ badge,
+}: {
+ href?: string;
+ onClick: () => void;
+ label: string;
+ icon: IconName;
+ /** 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";
+ return (
+ <SidebarEntry
+ href={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}`}
+ >
+ <Icon name={icon} size="w-4 h-4" />
+ <span className="flex-1 truncate">{label}</span>
+ {badge != null && badge > 0 && <Badge count={badge} />}
+ </SidebarEntry>
+ );
+}
+
+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">
+ {count}
+ </span>
+ );
+}
diff --git a/packages/ui/src/components/shell/navConfig.ts b/packages/ui/src/components/shell/navConfig.ts
index 0dc12d76..4aaa3249 100644
--- a/packages/ui/src/components/shell/navConfig.ts
+++ b/packages/ui/src/components/shell/navConfig.ts
@@ -1,10 +1,9 @@
import { IconName } from "@/components/Icon";
-// Single source of truth for the app's navigation. Both the chat-home
-// sidebar (`app/page.tsx`, via `SidebarNav`) and the persistent rail
-// (`components/shell/AppShell.tsx`) build their menus from here, so the
-// two navs can never drift apart again. When adding a destination, add
-// it ONCE in this file.
+// Single source of truth for the app's navigation. The one sidebar
+// (`components/shell/AppSidebar.tsx`, rendered by both the chat home and
+// the AppShell) and the mobile bottom bar build their menus from here.
+// When adding a destination, add it ONCE in this file.
export interface NavItem {
href: string;
@@ -232,3 +231,10 @@ export const MOBILE_PRIMARY: NavItem[] = [
"Multi-step workflows that produce a deliverable — board prep, GTM plans, reviews.",
},
];
+
+// Is `href` the active destination for `pathname`? Active on an exact match
+// or anywhere below it (`/jobs` is active on `/jobs/runs/42`).
+export function isNavActive(href: string, pathname: string): boolean {
+ if (href === "/") return pathname === "/";
+ return pathname === href || pathname.startsWith(`${href}/`);
+}
diff --git a/packages/ui/src/lib/sessionChannel.ts b/packages/ui/src/lib/sessionChannel.ts
new file mode 100644
index 00000000..328b791a
--- /dev/null
+++ b/packages/ui/src/lib/sessionChannel.ts
@@ -0,0 +1,73 @@
+import type { SessionSummary } from "@/lib/api";
+
+// Where a conversation came from. The backend has no channel column on
+// `sessions`; the channel adapters namespace their session ids instead
+// (`slack:dm:U1`, `telegram:123`, `discord:thread:…`), while web chats get a
+// bare uuid. This classifies a session from that prefix alone.
+export type SessionChannel = "web" | "slack" | "telegram" | "discord" | "email" | "google_chat";
+
+export const CHANNEL_LABELS: Record<SessionChannel, string> = {
+ web: "Web",
+ slack: "Slack",
+ telegram: "Telegram",
+ discord: "Discord",
+ email: "Email",
+ google_chat: "Google Chat",
+};
+
+// Display order for the channel filter on /chats.
+export const CHANNEL_ORDER: SessionChannel[] = [
+ "web",
+ "slack",
+ "telegram",
+ "discord",
+ "email",
+ "google_chat",
+];
+
+const PREFIXED_CHANNELS = new Set<SessionChannel>(
+ CHANNEL_ORDER.filter((c) => c !== "web"),
+);
+
+export function sessionChannel(sessionId: string): SessionChannel {
+ const sep = sessionId.indexOf(":");
+ if (sep <= 0) return "web";
+ const prefix = sessionId.slice(0, sep) as SessionChannel;
+ return PREFIXED_CHANNELS.has(prefix) ? prefix : "web";
+}
+
+export function sessionTitle(session: SessionSummary): string {
+ return session.title || "Untitled chat";
+}
+
+/** The newest `limit` web chats. Input is newest-first (the API sorts by `updated_at DESC`). */
+export function recentWebChats(sessions: SessionSummary[], limit: number): SessionSummary[] {
+ const out: SessionSummary[] = [];
+ for (const s of sessions) {
+ if (out.length >= limit) break;
+ if (sessionChannel(s.session_id) === "web") out.push(s);
+ }
+ return out;
+}
+
+export function filterSessions(
+ sessions: SessionSummary[],
+ { channel, query }: { channel: SessionChannel | "all"; query: string },
+): SessionSummary[] {
+ const q = query.trim().toLowerCase();
+ return sessions.filter(
+ (s) =>
+ (channel === "all" || sessionChannel(s.session_id) === channel) &&
+ (q === "" || sessionTitle(s).toLowerCase().includes(q)),
+ );
+}
+
+/** Session count per channel, for the filter tabs. Channels with no sessions are absent. */
+export function countByChannel(sessions: SessionSummary[]): Partial<Record<SessionChannel, number>> {
+ const counts: Partial<Record<SessionChannel, number>> = {};
+ for (const s of sessions) {
+ const c = sessionChannel(s.session_id);
+ counts[c] = (counts[c] ?? 0) + 1;
+ }
+ return counts;
+}