/** * LoginBriefing — shown on desktop load after boot screen. * Displays memory highlights ("I remember...") and cross-workspace summary * with links to each workspace. Feels like a colleague catching you up. */ import { useState, useEffect, useRef } from 'react'; import { motion, AnimatePresence, useReducedMotion, type MotionProps } from 'framer-motion'; import { STAGGER, DUR, EASE_OUT } from '@/lib/motion/tokens'; import { useFocusTrap } from '@/hooks/useFocusTrap'; import { Brain, Clock, MessageSquare, ChevronRight, Loader2, X, AlertTriangle, Lightbulb, } from 'lucide-react'; import beeMascot from '@/assets/personas/general-purpose.png'; import { DATE_LOCALE } from '@/lib/date-locale'; import { useService } from '@/providers/ServiceProvider'; import { useRevalidateOnError } from '@/hooks/useRevalidateOnError'; import { HintTooltip } from '@/components/ui/hint-tooltip'; import { formatBragLine, timeAgo as bragTimeAgo, type BragSummary, } from '@/lib/login-briefing-brag'; // Lane H item 3 — the ONE briefing truth: fetch/shape/count live in // briefing-source; the home hero recall strip and this modal both consume it, // so their catch-up numbers can never drift. import { takeBriefingData, isCannedWorkspaceSummary, type WorkspaceSummary, type MemoryHighlight, } from '@/lib/briefing-source'; import { RecallCard } from './RecallCard'; interface LoginBriefingProps { /** * Called when the user closes the briefing. `permanent=true` signals * that the user picked "Don't show again" and the caller should set * the persistent dismiss flag; `permanent=false` (default) hides for * this session only and the briefing will reappear on next launch. */ onDismiss: (permanent?: boolean) => void; onOpenWorkspace: (workspaceId: string) => void; } // timeAgo lives in @/lib/login-briefing-brag (shared with the brag summary so // the header and per-frame labels use one formatter). Keep a local alias so // callsites below read naturally. const timeAgo = bragTimeAgo; const LoginBriefing = ({ onDismiss, onOpenWorkspace }: LoginBriefingProps) => { const [summaries, setSummaries] = useState([]); const [highlights, setHighlights] = useState([]); const [brag, setBrag] = useState(null); const [loading, setLoading] = useState(true); // Wave W Lane B (item 1): bumped on every successful (re)load so the animated // recall cards + workspace rows re-key and replay their entrance stagger on // EVERY modal open (and post-error recovery) — not just the first paint, which // is all a prefetched-warm open would otherwise show. const [revealKey, setRevealKey] = useState(0); const reduceMotion = useReducedMotion(); // P1b D3: a failed briefing load must NOT render the Day-0 empty-hook — // backend failure was indistinguishable from a brand-new user (and the // brag header sat on 'Loading…' forever). const [errored, setErrored] = useState(false); // P1b D3: defer the batch until the connect attempt settles (the 0609 // HomeCockpit gate pattern) — gates on connecting-SETTLED, not connected, // so a failed connect still reaches the errored UI instead of a skeleton. const { connecting } = useService(); // W2G: Escape/Tab-trap/focus-restore via the shared modal hook (the bespoke // overlay previously closed only on a backdrop click). Escape routes through // onDismiss — same session-only dismissal as the backdrop. Wave Q Lane A: the // errored state is NOT a blocking modal (it degrades to a slim row below), so // the trap only arms while the modal itself renders. const dialogRef = useFocusTrap(!errored, () => onDismiss()); useEffect(() => { if (connecting) return; // W2G: the modal no longer computes its own greeting — that duplicated the // server-personalized Home greeting rendered directly behind it. Static // title now; identity is unused here. loadBriefing(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [connecting]); // D3 plus-clause: an errored briefing revalidates on focus/online/connect-settled. useRevalidateOnError(errored, () => { void loadBriefing(); }); // Review fix: a connect settlement fires BOTH the [connecting] effect and // the revalidation bus listener — single-flight the (5+ fetch) batch. const loadInFlight = useRef(false); const loadBriefing = async () => { if (loadInFlight.current) return; loadInFlight.current = true; try { // Wave T Lane A (item 2): consume the BootScreen-warmed cache when present // (content is already there → no spinner), else fetch fresh. The shaping // lives in fetchBriefingData; this just lands it in React state. const data = await takeBriefingData(); setHighlights(data.highlights); setSummaries(data.summaries); setBrag(data.brag); setErrored(false); // Fresh content landed → re-key the entrance so the stagger plays now. setRevealKey(k => k + 1); } catch { // P1b D3: surface the failure — do not let it fall through to the // Day-0 empty-hook render path. setErrored(true); } finally { setLoading(false); loadInFlight.current = false; } }; const bragLine = brag ? formatBragLine(brag) : null; const totalPending = brag?.pendingCount ?? 0; // Wave S Lane E (honesty): omit rows that carry no information — a canned // brochure summary AND zero memories. Guarded on memoryCount so a workspace // with real memory content is NEVER hidden (its brochure text is suppressed // below instead). Brag header counts are untouched (they read memory stats, // not this list), so the digest and header stay consistent. const visibleSummaries = summaries.filter( (ws) => !(isCannedWorkspaceSummary(ws.summary) && ws.memoryCount === 0), ); // Cap to 2 on first paint so the briefing greets rather than walls (the full // memory list lives in the Memory app). Hoisted so the entrance stagger can // continue its index from the recall cards into the workspace rows below. const shownHighlights = highlights.slice(0, 2); // Wave W Lane B (item 1): the product's hero moment deserves an entrance beat // that survives 2fps. Recall cards then workspace rows rise 8px + fade, // STAGGER.brief (80ms) apart, after a short base delay so the beat reads AFTER // the modal itself arrives. Duration/easing/stagger now resolve to the motion // vocabulary (DUR.base / EASE_OUT / STAGGER.brief) — one source of truth. // Reduced motion → instant (no rise/fade), honoring the header rule. const ENTER_BASE = 0.12; const entranceProps = (index: number): MotionProps => reduceMotion ? { initial: false, animate: { opacity: 1, y: 0 } } : { initial: { opacity: 0, y: 8 }, animate: { opacity: 1, y: 0 }, transition: { delay: ENTER_BASE + index * STAGGER.brief, duration: DUR.base, ease: EASE_OUT }, }; // Wave Q Lane A (item 1): a failed briefing must never boot a blocking modal // stacked over the NoModelBanner + Home's own error state. When the fetch // errors we collapse to ONE slim, non-blocking, dismissible row — a calm // branded moment (honey glyph, quiet secondary Retry), not a red-triangle // alarm. Auto-recovers via useRevalidateOnError; the Retry is the manual // escape hatch. (When the sidecar is unreachable the whole briefing is // suppressed a level up in AppShell so the connection problem speaks once.) if (errored) { return (
Briefing unavailable {loading ? ( ) : ( )}
); } return ( onDismiss()} > e.stopPropagation()} > {/* Header — X on the header baseline (items-start), not centered against the two-line title (Wave Q Lane A item 3). */}
{/* Wave R Lane E — brand moment: a small hex-bee mascot beside the title so the briefing greets like a colleague catching you up. Decorative (alt=""); the title carries the accessible name. */}

Catching you up

{bragLine ?? 'Loading…'} {totalPending > 0 && ( {totalPending} awaiting your OK )}

{loading ? ( // Wave T Lane A (item 2): a progressive reveal, not a spinner in an // empty box — two honey-wash highlight placeholders + two neutral // workspace-row placeholders at the real heights, so the shape is // already right when the (usually prefetched) content lands. // aria-hidden: the header's aria-live region already speaks for load.
{[0, 1].map(i => (
))}
{[0, 1].map(i => (
))}
) : highlights.length === 0 && summaries.length === 0 ? ( // Day-0 user — no workspaces AND no memory yet. The bare // "no workspaces" line failed dim 3 (first-session hook in // <60s) in the 2026-05-28 addictiveness audit. Three demo // "what I'll remember for you" bubbles teach the value prop // concretely. Examples are explicitly labelled so this isn't // deceptive copy. // (FR-5's sample-workspace-load buttons were reverted 2026-05-28 // as a redundant parallel of the existing workspace-templates // starterMemory system — see REDUNDANCY-AUDIT.md. The non- // redundant consolidation is to wire these to POST // /api/workspaces?templateId, tracked in FEATURE-REQUESTS.md.)

Here's what I'll remember for you

{[ '"Last week we decided to prioritise compliance over speed for the launch."', '"Sarah\'s feedback on the deck — slide 4 needs the regional breakdown."', '"Voice for the Wednesday newsletter — punchy, contrarian, second-person."', ].map((demo, i) => (

{demo}

))}

Examples. Your real memory populates as you chat — or import an existing ChatGPT/Claude export from the Memory app.

) : ( <> {/* Memory highlights — "I remember..." */} {highlights.length > 0 && (

I remember

{/* Cap to 2 on first paint (shownHighlights) so the briefing greets rather than walls — the full memory list lives in the Memory app. */} {/* Lane H item 4: the SAME RecallCard the home hero renders — one recall-card grammar wherever the memory moment lands. This modal owns only the STAGGER.brief entrance wrapper. */} {shownHighlights.map((h, i) => ( ))}
)} {/* Workspace list */} {visibleSummaries.length === 0 ? (

No active workspaces yet. Create one to get started!

) : ( // Wave R Lane E: a bottom edge-fade signals "more below" when // the list overflows its cap (>3 rows overflow max-h-60).
{visibleSummaries.map((ws, j) => ( { onOpenWorkspace(ws.id); onDismiss(); }} className="w-full text-left p-3 rounded-xl bg-secondary/30 border border-border/30 hover:bg-secondary/50 hover:border-primary/30 transition-colors group" >
{ws.name} {/* FR #27: tooltip clarifies what the group tag means. Without this hint the colored chip reads as decorative metadata. */} {ws.group}
{/* An empty workspace gets an honest nudge, not the brochure line the server emits as its summary. Wave S Lane E: a canned brochure summary on a kept row (real memories but no generated summary yet) is suppressed — template copy never renders as the user's data. */} {ws.memoryCount === 0 && ws.sessionCount === 0 ? (

Nothing here yet — start a chat and I'll remember it.

) : ws.summary && !isCannedWorkspaceSummary(ws.summary) ? (

{ws.summary}

) : null}
{/* Wave R Lane E: the bare glyph+number pairs were an unlabelled ⬡/💬 count — name them for screen readers and on hover (a11y). Icons are decorative. */} {ws.memoryCount} {ws.sessionCount} {/* FR #24/#26: only render the lastActive chip when the workspace has actual activity. For a brand-new workspace `lastActive` reflects creation time, not work, so "Last active 5/1/2026" reads as if the user already worked there when they haven't. */} {ws.lastActive && (ws.memoryCount > 0 || ws.sessionCount > 0) && ( {new Date(ws.lastActive).toLocaleDateString(DATE_LOCALE)} )} {ws.pendingTasks && ws.pendingTasks.length > 0 && ( {ws.pendingTasks.length} pending )}
))}
{visibleSummaries.length > 3 && (
)}
)} )} {/* Footer */}
); }; export default LoginBriefing;