moving
Some checks failed
Installer Smoke / installer-smoke (push) Has been cancelled

This commit is contained in:
Oleg Maslov
2026-09-02 10:10:29 +02:00
commit 0c3e2ead3b
3841 changed files with 970576 additions and 0 deletions

View File

@@ -0,0 +1,831 @@
import { useState, useEffect, useRef, useMemo, useCallback } from 'react';
import {
Search, Rocket, Plus, Play, Compass, Puzzle, Loader2,
Sparkles, Brain, MessageSquare, Package, Plug, Server,
Bot, Workflow, FileText, UserCircle, Terminal, AlertTriangle,
CheckCircle2, History, Lightbulb, CornerDownLeft,
} from 'lucide-react';
import { Command as CommandPrimitive } from 'cmdk';
import {
Command as CommandMenu, CommandList,
CommandEmpty, CommandGroup, CommandItem,
} from '@/components/ui/command';
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';
import { adapter } from '@/lib/adapter';
import { fuzzyMatch } from '@/lib/fuzzy-match';
import { cmdKLabel } from '@/lib/platform';
import { useToast } from '@/hooks/use-toast';
import type { CommandCategory, CommandResultType, CommandResult } from '@/lib/types';
import type { CatalogCommand, CatalogGroup } from '@/lib/command-catalog';
import type { Command, InterpretResult, ResolvedAction } from '@waggle/shared';
/* ── Verb sections (PRD §12.3) ──
* The six command verbs, in display order. Each backend `CommandResult`
* declares its `category`; we bucket results into these sections. The
* Search bucket also catches federated object hits (workspace/memory/…).
*/
const CATEGORY_ORDER: readonly CommandCategory[] = [
'search', 'launch', 'create', 'run', 'navigate', 'extend',
] as const;
const CATEGORY_LABELS: Record<CommandCategory, string> = {
search: 'Search',
launch: 'Launch',
create: 'Create',
run: 'Run',
navigate: 'Navigate',
extend: 'Extend',
};
const CATEGORY_ICONS: Record<CommandCategory, React.ElementType> = {
search: Search,
launch: Rocket,
create: Plus,
run: Play,
navigate: Compass,
extend: Puzzle,
};
/* Per-object-type fallback icon when a result omits its own `icon`. */
const TYPE_ICONS: Record<CommandResultType, React.ElementType> = {
workspace: Sparkles,
memory: Brain,
artifact: FileText,
session: MessageSquare,
person: UserCircle,
agent: Bot,
skill: Package,
command: Terminal,
connector: Plug,
mcp: Server,
automation: Workflow,
};
/* Object types that resolve to a window/app the integrator can open (Navigate)
* vs. types that must be dispatched through the execute pipeline (Run/Create/
* Extend). Search results that point at a navigable object deep-link instead
* of executing. */
const NAVIGABLE_TYPES: ReadonlySet<CommandResultType> = new Set<CommandResultType>([
'workspace', 'memory', 'session', 'person', 'command',
]);
const DEBOUNCE_MS = 220;
const MIN_QUERY = 2;
/* ── Tier 1 (NL intent) trigger ──
* Tier 0 (cmdk fuzzy) stays instant and authoritative. Tier 1 fires only for
* sentence-like input — the brief's heuristic: ≥3 words, not a slash command,
* long enough to be an intent. The interpret call runs in parallel and never
* blocks the cmdk list. */
const INTERPRET_DEBOUNCE_MS = 500;
function isSentenceLike(q: string): boolean {
const t = q.trim();
if (!t || t.startsWith('/')) return false;
return t.split(/\s+/).length >= 3 && t.length >= 6;
}
/* Synthesize a display-only CommandResult from a ResolvedAction so the intent
* row + approval prompt reuse the existing ResultRow / PermissionPrompt UI. */
function actionToResult(action: ResolvedAction): CommandResult {
return {
id: `__intent__:${action.id}`,
type: 'command',
title: action.label,
subtitle: action.sideEffect ? 'Needs your approval' : 'Ready to run',
category: 'run',
requiresApproval: action.sideEffect,
action: {
endpoint: action.endpoint?.path,
route: action.navigate ? `${action.navigate.type}:${action.navigate.id}` : undefined,
payload: action.endpoint?.body,
},
};
}
/* ── Issue 3: idle "More tools" hint ──
* The calm spine deliberately surfaces only five everyday places; the rest of
* the depth lives one keystroke away here. Teach that affordance in the empty
* (idle) palette by naming the power-tool categories — no sidebar items added,
* no new persistence. Typing filters them away via the curated catalog above. */
const POWER_TOOL_HINTS: readonly string[] = [
'Automations', 'Files', 'Vault', 'Usage', 'Connectors', 'Evolution',
];
/* ── Permission prompt (C9 — reuses the chat ApprovalGate visual pattern) ──
* Command Center does not own its own approval mechanism; gated executes flow
* through the same approve/deny affordance the chat surface uses. Here the
* decision is local-to-the-overlay: the caller confirms, then we run execute.
*/
const PermissionPrompt = ({
result,
onConfirm,
onCancel,
busy,
}: {
result: CommandResult;
onConfirm: () => void;
onCancel: () => void;
busy: boolean;
}) => {
const target =
(result.action?.payload?.path as string | undefined) ||
(result.action?.payload?.command as string | undefined) ||
result.action?.endpoint ||
result.action?.route;
return (
<div className="m-2 rounded-xl border-2 border-amber-500/50 bg-amber-500/10 p-3">
<div className="mb-2 flex items-center gap-2">
<AlertTriangle className="h-4 w-4 text-amber-400" />
<span className="font-display text-sm font-semibold text-foreground">Approval required</span>
</div>
<p className="mb-1 text-xs text-muted-foreground">
{result.title}
{result.subtitle ? <span className="text-foreground"> — {result.subtitle}</span> : null}
</p>
{target && (
<p className="mb-2 truncate font-mono text-[11px] text-muted-foreground">→ {target}</p>
)}
<div className="flex flex-wrap gap-1.5">
<button
type="button"
onClick={onConfirm}
disabled={busy}
className="flex items-center gap-1.5 rounded-lg bg-emerald-600 px-3 py-1 text-xs text-foreground transition-colors hover:bg-emerald-500 disabled:opacity-60"
>
{busy ? <Loader2 className="h-3 w-3 animate-spin" /> : <CheckCircle2 className="h-3 w-3" />}
Allow &amp; run
</button>
<button
type="button"
onClick={onCancel}
disabled={busy}
className="rounded-lg bg-secondary px-3 py-1 text-xs text-foreground transition-colors hover:bg-secondary/70 disabled:opacity-60"
>
Cancel
</button>
</div>
</div>
);
};
/* ── Result row ── */
const ResultRow = ({ result, onSelect }: { result: CommandResult; onSelect: () => void }) => {
const Icon = TYPE_ICONS[result.type] ?? Terminal;
return (
<CommandItem
value={result.id}
onSelect={onSelect}
className="flex items-center gap-3 rounded-lg px-3 py-2 text-sm aria-selected:bg-[var(--honey-glow,rgba(229,160,0,0.08))]"
>
<Icon className="h-4 w-4 shrink-0" style={{ color: 'var(--hive-400)' }} />
<div className="min-w-0 flex-1 text-left">
<span className="block truncate font-display" style={{ color: 'var(--hive-100)' }}>
{result.title}
</span>
{result.subtitle && (
<span className="block truncate text-xs" style={{ color: 'var(--hive-400)' }}>
{result.subtitle}
</span>
)}
</div>
{result.requiresApproval && (
<span
className="shrink-0 rounded-full px-1.5 py-0.5 text-[10px]"
style={{ backgroundColor: 'rgba(229,160,0,0.15)', color: 'var(--honey-500)' }}
>
gated
</span>
)}
<span className="shrink-0 text-[11px] capitalize" style={{ color: 'var(--hive-500)' }}>
{result.type}
</span>
</CommandItem>
);
};
/* ── Group heading (mono, uppercase; honey for the Pinned group) ── */
const groupHeading = (label: string, pinned = false) => (
<span className={`font-mono text-[10px] uppercase tracking-[0.12em] ${pinned ? 'text-[var(--honey-text)]' : 'text-[var(--text-dim)]'}`}>
{label}
</span>
);
/* ── Catalog row — a curated place/action: plain name + mono subtitle (ia.html). ── */
const CatalogRow = ({ cmd, onSelect }: { cmd: CatalogCommand; onSelect: () => void }) => {
const Icon = cmd.icon;
return (
<CommandItem
value={`cat:${cmd.id}`}
onSelect={onSelect}
className="group flex min-w-0 items-center gap-3 rounded-[9px] px-3 py-2 aria-selected:bg-[var(--honey-wash)]"
>
<Icon className="h-[18px] w-[18px] shrink-0 text-[var(--text-2)] group-aria-selected:text-[var(--honey-text)]" strokeWidth={1.7} />
<div className="min-w-0 flex-1 text-left">
<span className="block truncate text-sm text-[var(--text)]">{cmd.name}</span>
{cmd.subtitle && (
<span className="block truncate font-mono text-[11px] text-[var(--text-dim)]">{cmd.subtitle}</span>
)}
</div>
{cmd.meta && (
<span className="shrink-0 font-mono text-[10.5px] text-[var(--text-dim)]">{cmd.meta}</span>
)}
</CommandItem>
);
};
/* ── Props (integrator wires to Desktop) ── */
interface CommandCenterProps {
open: boolean;
onClose: () => void;
onNavigate: (type: string, id: string) => void;
onExecute: (result: CommandResult) => void;
/** Active workspace for execute scoping (C7/C5 deep-links + execute payloads). */
workspaceId?: string;
/** Curated places & actions (Jump to / Do / Power tools + Pinned). Optional —
* when absent (isolated/standalone render) the palette falls back to the
* backend recent/suggested strips. */
catalog?: CatalogGroup[];
onCatalogSelect?: (cmd: CatalogCommand) => void;
}
type ViewState =
| 'idle'
| 'query'
| 'results'
| 'no-results'
| 'permission'
| 'success'
| 'failure';
/* Group a flat result list into the six verb sections, preserving order. */
function groupByCategory(results: readonly CommandResult[]): Array<{ category: CommandCategory; items: CommandResult[] }> {
const buckets = new Map<CommandCategory, CommandResult[]>();
for (const r of results) {
const list = buckets.get(r.category) ?? [];
list.push(r);
buckets.set(r.category, list);
}
return CATEGORY_ORDER
.map((category) => ({ category, items: buckets.get(category) ?? [] }))
.filter((s) => s.items.length > 0);
}
/* ── Component ── */
const CommandCenter = ({ open, onClose, onNavigate, onExecute, workspaceId, catalog, onCatalogSelect }: CommandCenterProps) => {
const { toast } = useToast();
const [query, setQuery] = useState('');
const [selected, setSelected] = useState('');
const [results, setResults] = useState<CommandResult[]>([]);
const [recent, setRecent] = useState<CommandResult[]>([]);
const [suggestions, setSuggestions] = useState<CommandResult[]>([]);
const [searching, setSearching] = useState(false);
// P7/D15 B3: when the search endpoint fails we fall back to local fuzzy match —
// flag it so the user knows results are degraded, not authoritative.
const [searchDegraded, setSearchDegraded] = useState(false);
const [executing, setExecuting] = useState(false);
const [pending, setPending] = useState<CommandResult | null>(null);
/** Tracks the last command outcome so we can render success/failure state. */
const [outcome, setOutcome] = useState<'success' | 'failure' | null>(null);
// ── Tier 1 (NL intent) state — layered on Tier 0, never replacing it. ──
const [interpreting, setInterpreting] = useState(false);
const [interpret, setInterpret] = useState<InterpretResult | null>(null);
const [pendingAction, setPendingAction] = useState<ResolvedAction | null>(null);
const [dispatching, setDispatching] = useState(false);
/** Last query we resolved, to avoid re-interpreting an unchanged sentence. */
const lastInterpreted = useRef<string>('');
// The cmdk `value` (selected) is keyed by result id; map it back to look up.
const byId = useRef(new Map<string, CommandResult>());
// Reset transient state every time the overlay opens, and hydrate the idle
// strips (recent + suggested). Each call degrades independently — a failing
// suggestions endpoint must not blank out recents.
useEffect(() => {
if (!open) return;
setQuery('');
setSelected('');
setResults([]);
setPending(null);
setOutcome(null);
setInterpret(null);
setInterpreting(false);
setPendingAction(null);
lastInterpreted.current = '';
let alive = true;
adapter.commandRecent()
.then((r) => { if (alive) setRecent(r.recent ?? []); })
.catch(() => { if (alive) setRecent([]); });
adapter.commandSuggestions()
.then((s) => { if (alive) setSuggestions(s.suggestions ?? []); })
.catch(() => { if (alive) setSuggestions([]); });
return () => { alive = false; };
}, [open]);
// Server-backed search, debounced. Falls back to a client offline filter over
// the already-loaded recent + suggested pools when the endpoint is unreachable
// (reuses lib/fuzzy-match — same matcher the legacy Command Center (Ctrl+K)
// predecessor, GlobalSearch, used).
useEffect(() => {
const q = query.trim();
if (q.length < MIN_QUERY) {
setResults([]);
setSearching(false);
return;
}
setSearching(true);
const handle = setTimeout(async () => {
try {
const res = await adapter.commandSearch(q, workspaceId ? 'workspace' : undefined);
setResults(res.results ?? []);
setSearchDegraded(false);
} catch {
// Offline fallback: fuzzy-match across recent + suggested.
setSearchDegraded(true);
const pool = [...recent, ...suggestions];
const seen = new Set<string>();
const matched: Array<CommandResult & { _score: number }> = [];
for (const item of pool) {
if (seen.has(item.id)) continue;
seen.add(item.id);
const hit = fuzzyMatch(q, `${item.title} ${item.subtitle ?? ''}`);
if (hit.match) matched.push({ ...item, _score: hit.score });
}
matched.sort((a, b) => b._score - a._score);
setResults(matched.map(({ _score, ...rest }) => rest));
} finally {
setSearching(false);
}
}, DEBOUNCE_MS);
return () => clearTimeout(handle);
}, [query, workspaceId, recent, suggestions]);
// Tier 1 (NL intent) — fire the resolver for sentence-like input, debounced
// and in parallel with Tier 0. Does NOT block the cmdk list; result renders
// in its own "Ask Waggle" group. Failures degrade silently (kind:'none'
// fallback) so Tier 0 always remains usable.
useEffect(() => {
if (!open) return;
const q = query.trim();
if (!isSentenceLike(q)) {
setInterpret(null);
setInterpreting(false);
lastInterpreted.current = '';
return;
}
if (lastInterpreted.current === q) return; // already resolved this exact sentence
let alive = true;
setInterpreting(true);
const handle = setTimeout(async () => {
const res = await adapter.commandInterpret(q, workspaceId);
if (!alive) return;
lastInterpreted.current = q;
setInterpreting(false);
// A pure fallback 'none' just defers to Tier 0 — don't surface a row for it.
setInterpret(res.kind === 'none' && res.fallback ? null : res);
}, INTERPRET_DEBOUNCE_MS);
return () => { alive = false; clearTimeout(handle); };
}, [open, query, workspaceId]);
// Natural-language fallback row (PRD line 464): when a non-empty query yields
// no structured matches, offer to run the raw string as a command.
const nlResult = useMemo<CommandResult | null>(() => {
const q = query.trim();
if (!q || results.length > 0) return null;
return {
id: `__nl__:${q}`,
type: 'command',
title: `Run as command: "${q}"`,
subtitle: 'Interpret your input as a natural-language command',
category: 'run',
requiresApproval: false,
action: { endpoint: '/api/command/execute', payload: { input: q } },
};
}, [query, results]);
// Choose which result pool feeds the list for the current view.
const sections = useMemo(() => {
const q = query.trim();
if (!q) {
const idle: CommandResult[] = [...recent, ...suggestions];
return groupByCategory(idle.length > 0 ? idle : []);
}
const live = nlResult ? [...results, nlResult] : results;
return groupByCategory(live);
}, [query, results, recent, suggestions, nlResult]);
// Curated catalog, filtered client-side by the query (the backend search runs
// in parallel and contributes federated object hits below).
const catalogSections = useMemo<CatalogGroup[]>(() => {
if (!catalog) return [];
const q = query.trim().toLowerCase();
if (!q) return catalog;
return catalog
.map((g) => ({ ...g, items: g.items.filter((i) => fuzzyMatch(q, `${i.name} ${i.subtitle ?? ''} ${i.keywords ?? ''}`).match) }))
.filter((g) => g.items.length > 0);
}, [catalog, query]);
// Keep an id→result lookup in sync with whatever is currently rendered so a
// cmdk onSelect (which yields the value/id) can resolve back to the object.
useEffect(() => {
const map = new Map<string, CommandResult>();
for (const sec of sections) for (const item of sec.items) map.set(item.id, item);
byId.current = map;
}, [sections]);
const viewState: ViewState = useMemo(() => {
if (pending || pendingAction) return 'permission';
if (outcome === 'success') return 'success';
if (outcome === 'failure') return 'failure';
const q = query.trim();
if (!q) return 'idle';
if (searching) return 'query';
return sections.length > 0 ? 'results' : 'no-results';
}, [pending, pendingAction, outcome, query, searching, sections]);
// Dispatch a chosen result. Navigable objects deep-link via onNavigate; Run/
// Create/Extend and gated items go through the execute pipeline. Gated results
// first raise the permission prompt (C9).
const runResult = useCallback(async (result: CommandResult) => {
setOutcome(null);
setExecuting(true);
try {
const payload: Command = {
id: result.id.startsWith('__nl__:') ? undefined : result.id,
input: result.action?.payload?.input as string | undefined,
category: result.category,
type: result.type,
workspaceId,
payload: result.action?.payload,
};
const res = await adapter.commandExecute(payload);
if (res.ok) {
setOutcome('success');
onExecute(result);
toast({ title: 'Command ran', description: result.title });
onClose();
} else {
setOutcome('failure');
toast({ title: 'Command failed', description: result.title, variant: 'destructive' });
}
} catch {
setOutcome('failure');
toast({ title: 'Command failed', description: result.title, variant: 'destructive' });
} finally {
setExecuting(false);
setPending(null);
}
}, [workspaceId, onExecute, onClose, toast]);
const handleSelect = useCallback((result: CommandResult) => {
// Navigate intents (and navigable search hits without a gate) deep-link.
const isNavigate =
result.category === 'navigate' ||
(result.category === 'search' && NAVIGABLE_TYPES.has(result.type) && !result.requiresApproval);
if (isNavigate) {
onNavigate(result.type, result.id);
onClose();
return;
}
// Gated executes raise the permission prompt before running (C9).
if (result.requiresApproval) {
setPending(result);
return;
}
void runResult(result);
}, [onNavigate, onClose, runResult]);
// ── Tier 1: execute a server-derived ResolvedAction's endpoint. ──
const dispatchAction = useCallback(async (action: ResolvedAction) => {
setDispatching(true);
try {
const res = await adapter.commandDispatchAction(action);
if (res.ok) {
toast({ title: 'Done', description: action.label });
onClose();
} else if (res.status === 403) {
// The global adapter handler already raised the UpgradeModal — just close.
onClose();
} else {
toast({ title: 'Action failed', description: action.label, variant: 'destructive' });
}
} catch {
toast({ title: 'Action failed', description: action.label, variant: 'destructive' });
} finally {
setDispatching(false);
setPendingAction(null);
}
}, [onClose, toast]);
// ── Tier 1: dispatch a resolved intent onto the existing execution paths. ──
const handleResolvedAction = useCallback((res: InterpretResult) => {
if (res.kind === 'tier_gated') {
window.dispatchEvent(new CustomEvent('waggle:tier-insufficient', {
detail: { required: res.requiredTier, actual: res.actualTier, message: res.message },
}));
onClose();
return;
}
if (res.kind !== 'action' || !res.action) return;
const action = res.action;
if (action.navigate) {
onNavigate(action.navigate.type, action.navigate.id);
onClose();
return;
}
if (action.sideEffect) {
setPendingAction(action); // preview-and-approve before executing
return;
}
void dispatchAction(action);
}, [onNavigate, onClose, dispatchAction]);
// Refine a clarify by appending the chosen option; re-resolves via the effect.
const handleClarifyOption = useCallback((option: string) => {
lastInterpreted.current = '';
setQuery((q) => `${q.trim()} ${option}`);
}, []);
return (
<Dialog open={open} onOpenChange={(o) => { if (!o) onClose(); }}>
<DialogContent
// F10: hide the dialog's built-in absolute ✕ (ui/dialog.tsx) — with p-0
// it lands on the ESC chip in the query row. ESC key / overlay click /
// onOpenChange all still close the palette; the ESC chip is the affordance.
className="overflow-hidden p-0 shadow-2xl sm:max-w-xl [&>button]:hidden"
style={{ backgroundColor: 'var(--hive-850)', border: '1px solid var(--hive-700)' }}
data-testid="command-center-dialog"
>
{/* Accessible label for the Radix dialog; visually hidden (sr-only is
the convention already used in ui/dialog.tsx). */}
<DialogTitle className="sr-only">Command Center</DialogTitle>
<DialogDescription className="sr-only">
Search and run commands, navigate surfaces, launch tools, and open workspace actions.
</DialogDescription>
<CommandMenu
label="Command Center"
shouldFilter={false}
loop
value={selected}
onValueChange={setSelected}
className="bg-transparent"
>
{/* Query input */}
<div
className="flex items-center gap-3 px-4 py-3"
style={{ borderBottom: '1px solid var(--hive-700)' }}
>
<Search className="h-5 w-5 shrink-0" style={{ color: 'var(--hive-400)' }} />
<CommandPrimitive.Input
value={query}
onValueChange={setQuery}
placeholder="What do you want to do? Search, launch, create, run, navigate, extend…"
className="h-auto flex-1 rounded-md border-0 bg-transparent p-0 text-sm outline-none placeholder:text-[var(--hive-500)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--hive-850)]"
aria-label="Command Center search"
/>
{searching && <Loader2 className="h-4 w-4 animate-spin" style={{ color: 'var(--honey-500)' }} />}
<kbd
className="rounded px-1.5 py-0.5 font-display text-[11px]"
style={{ backgroundColor: 'var(--hive-800)', color: 'var(--hive-400)' }}
>
ESC
</kbd>
</div>
{/* P7/D15 B3: surface the silent search-endpoint failure so the user
knows these are degraded local matches, not authoritative results. */}
{searchDegraded && viewState !== 'permission' && (
<div role="status" className="flex items-center gap-2 px-4 py-1.5 text-[11px]" style={{ color: 'var(--honey-500)' }}>
<AlertTriangle className="h-3.5 w-3.5 shrink-0" />
<span>Search service unreachable — showing local matches only.</span>
</div>
)}
{/* Permission prompt (C9) takes over the body when a gated item is chosen. */}
{viewState === 'permission' && pending && (
<PermissionPrompt
result={pending}
busy={executing}
onConfirm={() => void runResult(pending)}
onCancel={() => setPending(null)}
/>
)}
{/* Tier 1: a resolved side-effect intent reuses the same approval gate. */}
{viewState === 'permission' && !pending && pendingAction && (
<PermissionPrompt
result={actionToResult(pendingAction)}
busy={dispatching}
onConfirm={() => void dispatchAction(pendingAction)}
onCancel={() => setPendingAction(null)}
/>
)}
{viewState !== 'permission' && (
<CommandList className="max-h-[60vh] overflow-auto p-2">
{/* No results / NL hint is folded into the NL row, so a true empty
only shows when there is genuinely nothing to offer. */}
<CommandEmpty>
<span className="text-sm" style={{ color: 'var(--hive-400)' }}>
{query.trim() ? `No results for "${query.trim()}"` : 'Start typing to search everything'}
</span>
</CommandEmpty>
{/* ── Tier 1: Ask Waggle (NL intent) — sits above Tier 0 results,
never replacing them. Renders interpreting / resolved action /
clarify / upgrade / decline. ── */}
{(interpreting || interpret) && (
<CommandGroup
heading={
<span className="flex items-center gap-1.5 uppercase tracking-wider">
<Sparkles className="h-3 w-3" /> Ask Waggle
</span>
}
>
{interpreting && (
<div className="flex items-center gap-2 px-3 py-2 text-sm" style={{ color: 'var(--hive-400)' }} data-testid="intent-interpreting">
<Loader2 className="h-4 w-4 animate-spin" style={{ color: 'var(--honey-500)' }} />
Interpreting…
</div>
)}
{!interpreting && interpret?.kind === 'action' && interpret.action && (
<ResultRow result={actionToResult(interpret.action)} onSelect={() => handleResolvedAction(interpret)} />
)}
{!interpreting && interpret?.kind === 'tier_gated' && (
<CommandItem
value="__intent_tier__"
onSelect={() => handleResolvedAction(interpret)}
className="flex items-center gap-3 rounded-lg px-3 py-2 text-sm aria-selected:bg-[var(--honey-glow,rgba(229,160,0,0.08))]"
>
<Sparkles className="h-4 w-4 shrink-0" style={{ color: 'var(--honey-500)' }} />
<div className="min-w-0 flex-1 text-left">
<span className="block truncate font-display" style={{ color: 'var(--hive-100)' }}>
Upgrade to {interpret.requiredTier} to do this
</span>
<span className="block truncate text-xs" style={{ color: 'var(--hive-400)' }}>
{interpret.capability}
</span>
</div>
<span className="shrink-0 rounded-full px-1.5 py-0.5 text-[10px]" style={{ backgroundColor: 'rgba(167,139,250,0.15)', color: '#a78bfa' }}>
{interpret.requiredTier}
</span>
</CommandItem>
)}
{!interpreting && interpret?.kind === 'clarify' && (
<div className="px-3 py-2" data-testid="intent-clarify">
<p className="mb-2 text-sm" style={{ color: 'var(--hive-100)' }}>{interpret.question}</p>
{interpret.steps && interpret.steps.length > 0 ? (
<div className="flex flex-wrap gap-1.5">
<button
type="button"
onClick={() => handleResolvedAction({ kind: 'action', action: interpret.steps![0] })}
className="rounded-lg bg-emerald-600 px-3 py-1 text-xs text-foreground transition-colors hover:bg-emerald-500"
>
Start: {interpret.steps[0].label}
</button>
<button
type="button"
onClick={() => setInterpret(null)}
className="rounded-lg bg-secondary px-3 py-1 text-xs text-foreground transition-colors hover:bg-secondary/70"
>
Cancel
</button>
</div>
) : interpret.options && interpret.options.length > 0 ? (
<div className="flex flex-wrap gap-1.5">
{interpret.options.map((opt) => (
<button
key={opt}
type="button"
onClick={() => handleClarifyOption(opt)}
className="rounded-lg bg-secondary px-3 py-1 text-xs text-foreground transition-colors hover:bg-secondary/70"
>
{opt}
</button>
))}
</div>
) : null}
</div>
)}
{!interpreting && interpret?.kind === 'none' && interpret.message && (
<div className="px-3 py-2 text-xs" style={{ color: 'var(--hive-400)' }}>
{interpret.message}
</div>
)}
</CommandGroup>
)}
{/* Curated places & actions (Jump to / Do / Power tools + Pinned). */}
{catalogSections.map((g) => (
<CommandGroup key={`cat-${g.key}`} heading={groupHeading(g.heading, g.key === 'pinned')}>
{g.items.map((cmd) => (
<CatalogRow
key={cmd.id}
cmd={cmd}
onSelect={() => { onCatalogSelect?.(cmd); onClose(); }}
/>
))}
</CommandGroup>
))}
{/* Idle: backend Recent + Suggested strips — only when no curated
catalog is wired (isolated/standalone render). */}
{!catalog && viewState === 'idle' && recent.length > 0 && (
<CommandGroup
heading={
<span className="flex items-center gap-1.5">
<History className="h-3 w-3" /> Recent
</span>
}
>
{recent.map((r) => (
<ResultRow key={`recent-${r.id}`} result={r} onSelect={() => handleSelect(r)} />
))}
</CommandGroup>
)}
{!catalog && viewState === 'idle' && suggestions.length > 0 && (
<CommandGroup
heading={
<span className="flex items-center gap-1.5">
<Lightbulb className="h-3 w-3" /> Suggested for you
</span>
}
>
{suggestions.map((r) => (
<ResultRow key={`sugg-${r.id}`} result={r} onSelect={() => handleSelect(r)} />
))}
</CommandGroup>
)}
{/* Grouped verb sections for an active query. */}
{viewState !== 'idle' && sections.map((sec) => {
const HeadIcon = CATEGORY_ICONS[sec.category];
return (
<CommandGroup
key={sec.category}
heading={
<span className="flex items-center gap-1.5 uppercase tracking-wider">
<HeadIcon className="h-3 w-3" /> {CATEGORY_LABELS[sec.category]}
</span>
}
>
{sec.items.map((r) => (
<ResultRow key={`${sec.category}-${r.id}`} result={r} onSelect={() => handleSelect(r)} />
))}
</CommandGroup>
);
})}
{/* Issue 3: idle-only "More tools" affordance — names the power-tool
categories that live behind ⌘K (no sidebar item, no persistence). */}
{viewState === 'idle' && (
<div
className="mx-1 mt-1 flex flex-wrap items-center gap-1.5 px-2 py-2 text-[11px]"
style={{ borderTop: '1px solid var(--hive-700)', color: 'var(--text-muted)' }}
data-testid="command-center-more-tools"
>
<span className="font-mono uppercase tracking-[0.12em]">More tools</span>
{POWER_TOOL_HINTS.map((label) => (
<span
key={label}
className="rounded px-1.5 py-0.5"
style={{ backgroundColor: 'var(--hive-800)', color: 'var(--hive-400)' }}
>
{label}
</span>
))}
<span className="ml-auto">Type to find any of them.</span>
</div>
)}
</CommandList>
)}
{/* Footer hints */}
<div
className="flex items-center gap-4 px-4 py-2 text-[11px]"
style={{ borderTop: '1px solid var(--hive-700)', color: 'var(--hive-500)' }}
>
<span>{'↑↓'} Navigate</span>
<span className="flex items-center gap-1"><CornerDownLeft className="h-3 w-3" /> Run / Open</span>
{/* Platform-aware modifier — a ⌘ glyph on Windows is a key the
user's keyboard doesn't have. */}
<span>{cmdKLabel} Toggle</span>
{viewState === 'failure' && (
<span className="ml-auto text-amber-400">Last command failed</span>
)}
</div>
</CommandMenu>
</DialogContent>
</Dialog>
);
};
export default CommandCenter;

View File

@@ -0,0 +1,153 @@
import { useState, useEffect } from 'react';
import { X, Brain, Loader2, ChevronRight, FileText, Zap, Link2 } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { adapter } from '@/lib/adapter';
import {
fetchContextRailItems,
type ContextRailTarget as FetchTarget,
type ContextRailItem,
} from '@/lib/context-rail-fetch';
export type ContextRailTarget = FetchTarget;
interface ContextRailProps {
target: ContextRailTarget | null;
onClose: () => void;
}
type ContextItem = ContextRailItem;
const KIND_ICONS: Record<string, React.ElementType> = {
memory: Brain,
entity: Link2,
relation: Zap,
};
const KIND_COLORS: Record<string, string> = {
memory: 'text-amber-400',
entity: 'text-sky-400',
relation: 'text-violet-400',
};
const ContextRail = ({ target, onClose }: ContextRailProps) => {
const [items, setItems] = useState<ContextItem[]>([]);
const [loading, setLoading] = useState(false);
const [expandedId, setExpandedId] = useState<string | null>(null);
useEffect(() => {
if (!target) { setItems([]); return; }
let cancelled = false;
setLoading(true);
setExpandedId(null);
(async () => {
const results = await fetchContextRailItems(target, adapter);
if (!cancelled) {
setItems(results);
setLoading(false);
}
})();
return () => { cancelled = true; };
}, [target]);
return (
<AnimatePresence>
{target && (
<motion.div
initial={{ x: 320, opacity: 0 }}
animate={{ x: 0, opacity: 1 }}
exit={{ x: 320, opacity: 0 }}
transition={{ type: 'spring', stiffness: 300, damping: 30 }}
role="complementary"
aria-label={`Related context for ${target.label}`}
className="fixed top-8 right-0 bottom-16 w-80 z-40 glass-strong border-l border-border/50 flex flex-col"
>
{/* Header */}
<div className="shrink-0 px-4 py-3 border-b border-border/50 flex items-center justify-between">
<div className="flex items-center gap-2 min-w-0">
<FileText className="w-4 h-4 text-honey shrink-0" />
<div className="min-w-0">
<h3 className="text-xs font-display font-semibold text-foreground truncate">
{target.label}
</h3>
<p className="text-[10px] text-muted-foreground capitalize">{target.type}</p>
</div>
</div>
<button
type="button"
onClick={onClose}
aria-label="Close related context"
className="p-1 rounded-lg hover:bg-muted/50"
>
<X className="w-4 h-4 text-muted-foreground" />
</button>
</div>
{/* Content */}
<div className="flex-1 overflow-auto p-3 space-y-2">
{loading ? (
<div className="flex items-center justify-center h-32">
<Loader2 className="w-5 h-5 animate-spin text-honey" />
</div>
) : items.length === 0 ? (
<div className="flex flex-col items-center justify-center h-32 text-center">
<Brain className="w-8 h-8 text-muted-foreground/30 mb-2" />
<p className="text-xs text-muted-foreground">No related context found.</p>
</div>
) : (
<>
<p className="text-[10px] text-muted-foreground uppercase tracking-wide font-display">
{items.length} related item{items.length !== 1 ? 's' : ''}
</p>
{items.map(item => {
const Icon = KIND_ICONS[item.kind] ?? Brain;
const color = KIND_COLORS[item.kind] ?? 'text-muted-foreground';
const isExpanded = expandedId === item.id;
return (
<button
key={item.id}
type="button"
onClick={() => setExpandedId(isExpanded ? null : item.id)}
aria-expanded={isExpanded}
className={`w-full text-left p-2 rounded-lg transition-colors ${
isExpanded ? 'bg-muted/30' : 'hover:bg-muted/20'
}`}
>
<div className="flex items-start gap-2">
<Icon className={`w-3.5 h-3.5 mt-0.5 shrink-0 ${color}`} />
<div className="flex-1 min-w-0">
<p className="text-xs text-foreground truncate">{item.title}</p>
{item.importance && (
<span className={`text-[10px] ${
item.importance === 'critical' ? 'text-destructive'
: item.importance === 'important' ? 'text-amber-400'
: 'text-muted-foreground'
}`}>
{item.importance}
</span>
)}
{isExpanded && (
<p className="mt-1.5 text-[11px] text-muted-foreground whitespace-pre-wrap">
{item.content.slice(0, 500)}
</p>
)}
</div>
<ChevronRight className={`w-3 h-3 text-muted-foreground/40 mt-1 transition-transform ${
isExpanded ? 'rotate-90' : ''
}`} />
</div>
</button>
);
})}
</>
)}
</div>
</motion.div>
)}
</AnimatePresence>
);
};
export default ContextRail;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,29 @@
import { cleanup, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import EraseDataDialog from './EraseDataDialog';
const mocks = vi.hoisted(() => ({
adapter: {
eraseData: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter }));
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
describe('EraseDataDialog', () => {
it('a11y: destructive confirmation field exposes stable metadata and focus treatment', () => {
render(<EraseDataDialog open onClose={vi.fn()} />);
const phrase = screen.getByLabelText(/to confirm, type exactly/i);
expect(phrase).toHaveAttribute('id', 'erase-data-confirmation-phrase');
expect(phrase).toHaveAttribute('name', 'eraseDataConfirmationPhrase');
expect(phrase).toHaveAttribute('autocomplete', 'off');
expect(phrase.className).toContain('focus-visible:ring-2');
expect(phrase.className).toContain('focus-visible:ring-destructive');
});
});

View File

@@ -0,0 +1,244 @@
/**
* EraseDataDialog — confirmation modal for the GDPR Art. 17 erasure flow.
*
* Triggered from Settings → General → "Erase All My Data". Renders three
* sequential states:
* 1. Warning + phrase input ("type the exact phrase to confirm")
* 2. In-flight (calling adapter.eraseData)
* 3. Success (shows receipt + "quit and relaunch" instruction)
*
* The intentional friction (typing the full phrase, not just clicking) is
* the user-facing half of the route's confirmation gate. The other half
* (server-side phrase + header validation) lives in
* packages/server/src/local/routes/data-erase.ts. Both must match — if a
* future i18n attempt translates the phrase here, the server stays in
* English and a user typing the translated version gets a 400. Don't
* translate this gate.
*
* Side effect on success: nothing visible changes immediately — the wipe
* runs at next startup. The dialog presents the receipt + "quit Waggle
* and relaunch" copy so the user knows they aren't done yet.
*/
import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { AlertTriangle, X, Trash2, CheckCircle2, Loader2 } from 'lucide-react';
import { adapter } from '@/lib/adapter';
import { DATE_LOCALE } from '@/lib/date-locale';
import { useFocusTrap } from '@/hooks/useFocusTrap';
interface EraseDataDialogProps {
open: boolean;
onClose: () => void;
}
const REQUIRED_PHRASE = 'I UNDERSTAND THIS IS PERMANENT';
interface EraseReceipt {
requestedAt: string;
markerPath: string;
dataDirSnapshot: { fileCount: number; totalBytes: number };
instruction: string;
}
function formatBytes(n: number): string {
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
if (n < 1024 * 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)} MB`;
return `${(n / 1024 / 1024 / 1024).toFixed(2)} GB`;
}
export default function EraseDataDialog({ open, onClose }: EraseDataDialogProps) {
const [phrase, setPhrase] = useState('');
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [receipt, setReceipt] = useState<EraseReceipt | null>(null);
const phraseMatches = phrase === REQUIRED_PHRASE;
const handleErase = async () => {
if (!phraseMatches || submitting) return;
setSubmitting(true);
setError(null);
try {
const r = await adapter.eraseData(phrase);
setReceipt(r);
} catch (e) {
setError(e instanceof Error ? e.message : 'Erase failed');
} finally {
setSubmitting(false);
}
};
const handleClose = () => {
// Don't reset receipt — if the user closes after a successful erase
// and reopens, they'll just trigger another (idempotent) request.
// Resetting phrase + error keeps the next open clean.
setPhrase('');
setError(null);
setReceipt(null);
onClose();
};
// A11y (WCAG 2.1.1/2.4.3): Escape closes, Tab is trapped within the dialog,
// focus moves in on open and restores on close — the same shared hook the
// other modal overlays use. Passing `undefined` while submitting preserves
// the prior "don't close mid-erase" guard (Escape is inert during the wipe).
const dialogRef = useFocusTrap<HTMLDivElement>(open, submitting ? undefined : handleClose);
return (
<AnimatePresence>
{open && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-[220] flex items-center justify-center"
onClick={!submitting ? handleClose : undefined}
>
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm" aria-hidden="true" />
<motion.div
ref={dialogRef}
initial={{ opacity: 0, scale: 0.95, y: 16 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95, y: 16 }}
transition={{ type: 'spring', damping: 25, stiffness: 300 }}
role="dialog"
aria-modal="true"
aria-labelledby={receipt ? 'erase-data-success-title' : 'erase-data-title'}
tabIndex={-1}
className="relative w-full max-w-lg glass-strong rounded-2xl shadow-2xl overflow-hidden focus:outline-none"
onClick={e => e.stopPropagation()}
data-testid="erase-data-dialog"
>
{!submitting && (
<button
onClick={handleClose}
className="absolute top-4 right-4 p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors"
aria-label="Close"
>
<X className="w-4 h-4" />
</button>
)}
{/* ── Success state ─────────────────────────────────────── */}
{receipt ? (
<div className="p-6 space-y-4" data-testid="erase-data-success">
<div className="flex items-center gap-3">
<div className="p-2 rounded-xl bg-primary/10">
<CheckCircle2 className="w-5 h-5 text-honey" />
</div>
<h2 id="erase-data-success-title" className="text-lg font-display font-bold text-foreground">
Erasure scheduled
</h2>
</div>
<div className="rounded-xl bg-secondary/30 border border-border/30 p-3 text-xs space-y-1.5">
<div className="flex justify-between">
<span className="text-muted-foreground">Requested at</span>
<span className="text-foreground font-mono text-[11px]">
{new Date(receipt.requestedAt).toLocaleString(DATE_LOCALE)}
</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Files marked for deletion</span>
<span className="text-foreground">{receipt.dataDirSnapshot.fileCount}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Total size</span>
<span className="text-foreground">{formatBytes(receipt.dataDirSnapshot.totalBytes)}</span>
</div>
</div>
<div className="rounded-xl bg-amber-500/5 border border-amber-500/20 p-3">
<p className="text-xs text-foreground leading-relaxed">
{receipt.instruction}
</p>
</div>
<p className="text-[11px] text-muted-foreground leading-relaxed">
An <span className="font-mono">audit-receipt-*.json</span> file will be written to your data dir after relaunch — keep it as proof of erasure for compliance.
</p>
<div className="flex justify-end">
<button
onClick={handleClose}
className="px-4 py-2 rounded-xl bg-primary text-primary-foreground font-display text-sm font-semibold hover:bg-primary/90 transition-colors"
>
Close
</button>
</div>
</div>
) : (
/* ── Confirmation state ──────────────────────────────── */
<div className="p-6 space-y-4">
<div className="flex items-center gap-3">
<div className="p-2 rounded-xl bg-destructive/10">
<AlertTriangle className="w-5 h-5 text-destructive" />
</div>
<h2 id="erase-data-title" className="text-lg font-display font-bold text-foreground">
Erase all my data
</h2>
</div>
<div className="space-y-2 text-xs text-muted-foreground leading-relaxed">
<p>
This schedules a complete wipe of your data dir on next launch:
every memory frame, workspace, session, vault entry, and config
file. The wipe is <span className="text-foreground font-medium">not reversible</span> from the app — you'll need a previously-saved <span className="font-mono">.waggle-backup</span> file to restore.
</p>
<p>
Data already sent to cloud providers (Anthropic, OpenAI, Stripe, etc.) and Teams servers is <span className="text-foreground font-medium">not</span> erased by this action — see the data-handling policy for how to handle those separately.
</p>
</div>
<div className="space-y-1.5">
<label htmlFor="erase-data-confirmation-phrase" className="text-[11px] text-muted-foreground">
To confirm, type exactly: <span className="font-mono text-foreground">{REQUIRED_PHRASE}</span>
</label>
<input
id="erase-data-confirmation-phrase"
name="eraseDataConfirmationPhrase"
type="text"
autoComplete="off"
value={phrase}
onChange={e => setPhrase(e.target.value)}
disabled={submitting}
placeholder={REQUIRED_PHRASE}
className="w-full px-3 py-2 rounded-lg bg-secondary/30 border border-border/40 text-sm font-mono text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:border-destructive/60 focus-visible:ring-2 focus-visible:ring-destructive/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:opacity-50"
data-testid="erase-data-phrase-input"
autoFocus
/>
</div>
{error && (
<div className="rounded-lg bg-destructive/10 border border-destructive/30 p-2.5 text-[11px] text-destructive">
{error}
</div>
)}
<div className="flex items-center justify-end gap-3 pt-1">
<button
onClick={handleClose}
disabled={submitting}
className="px-4 py-2 rounded-xl text-sm text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50"
>
Cancel
</button>
<button
onClick={handleErase}
disabled={!phraseMatches || submitting}
className="flex items-center gap-1.5 px-4 py-2 rounded-xl bg-destructive text-destructive-foreground font-display text-sm font-semibold hover:bg-destructive/90 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
data-testid="erase-data-confirm-button"
>
{submitting ? (
<><Loader2 className="w-3.5 h-3.5 animate-spin" /> Erasing…</>
) : (
<><Trash2 className="w-3.5 h-3.5" /> Erase all data</>
)}
</button>
</div>
</div>
)}
</motion.div>
</motion.div>
)}
</AnimatePresence>
);
}

View File

@@ -0,0 +1,117 @@
import { motion, AnimatePresence } from 'framer-motion';
import { Keyboard, X } from 'lucide-react';
import { useFocusTrap } from '@/hooks/useFocusTrap';
interface KeyboardShortcutsHelpProps {
open: boolean;
onClose: () => void;
}
const shortcuts = [
{ category: 'Navigation', items: [
{ keys: ['Ctrl', 'Shift', '0'], action: 'Home' },
{ keys: ['Ctrl', 'Shift', '1'], action: 'Chat' },
{ keys: ['Ctrl', 'Shift', '2'], action: 'Agents' },
{ keys: ['Ctrl', 'Shift', '3'], action: 'Files' },
{ keys: ['Ctrl', 'Shift', '4'], action: 'Mission Control' },
{ keys: ['Ctrl', 'Shift', '5'], action: 'Memory' },
{ keys: ['Ctrl', 'Shift', '6'], action: 'Events' },
{ keys: ['Ctrl', 'Shift', '7'], action: 'Settings' },
{ keys: ['Ctrl', 'Shift', '8'], action: 'Skills' },
{ keys: ['Ctrl', 'Shift', '9'], action: 'Agent Swarm' },
]},
{ category: 'Quick Actions', items: [
{ keys: ['Ctrl', 'K'], action: 'Global Search' },
{ keys: ['Ctrl', 'Shift', 'N'], action: 'New chat' },
{ keys: ['Ctrl', 'Shift', 'O'], action: 'Open last workspace' },
{ keys: ['Ctrl', 'Shift', 'R'], action: 'Room' },
{ keys: ['Ctrl', 'Shift', 'P'], action: 'Persona Switcher' },
{ keys: ['Ctrl', 'Tab'], action: 'Workspace Switcher' },
{ keys: ['?'], action: 'Keyboard Shortcuts' },
]},
{ category: 'Chat', items: [
{ keys: ['Enter'], action: 'Send message' },
{ keys: ['Shift', 'Enter'], action: 'New line' },
{ keys: ['/'], action: 'Slash commands' },
{ keys: ['Esc'], action: 'Close overlay' },
]},
];
const KeyboardShortcutsHelp = ({ open, onClose }: KeyboardShortcutsHelpProps) => {
// A11y (WCAG 2.1.1/2.4.3): Escape closes, Tab is trapped within the dialog,
// focus moves in on open and restores on close — the same shared hook the
// other modal overlays use. Replaces the prior Escape-only handler.
const dialogRef = useFocusTrap<HTMLDivElement>(open, onClose);
if (!open) return null;
return (
<AnimatePresence>
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-[100] flex items-center justify-center"
onClick={onClose}
>
<div className="absolute inset-0 bg-black/50 backdrop-blur-sm" />
<motion.div
ref={dialogRef}
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
role="dialog"
aria-modal="true"
aria-labelledby="keyboard-shortcuts-title"
tabIndex={-1}
className="relative w-full max-w-lg glass-strong rounded-2xl shadow-2xl p-6 focus:outline-none"
onClick={e => e.stopPropagation()}
>
<div className="flex items-center justify-between mb-5">
<div className="flex items-center gap-2">
<Keyboard className="w-5 h-5 text-honey" />
<h2 id="keyboard-shortcuts-title" className="text-lg font-display font-semibold text-foreground">Keyboard Shortcuts</h2>
</div>
{/* Pillar 2.7 hit-area: a centered 40px ::before expands the effective
target from 24px without changing the visual size. */}
<button onClick={onClose} aria-label="Close keyboard shortcuts" className="relative p-1 rounded-lg text-muted-foreground hover:text-foreground transition-colors before:absolute before:left-1/2 before:top-1/2 before:h-10 before:w-10 before:-translate-x-1/2 before:-translate-y-1/2 before:content-['']">
<X className="w-4 h-4" />
</button>
</div>
<div className="space-y-5">
{shortcuts.map(cat => (
<div key={cat.category}>
<h3 className="text-xs font-display text-muted-foreground uppercase mb-2">{cat.category}</h3>
<div className="space-y-1.5">
{cat.items.map(item => (
<div key={item.action} className="flex items-center justify-between py-1">
<span className="text-xs text-foreground">{item.action}</span>
<div className="flex items-center gap-1">
{item.keys.map((key, i) => (
<kbd key={i} className="px-1.5 py-0.5 text-[11px] rounded bg-muted text-muted-foreground font-display min-w-[20px] text-center">
{key}
</kbd>
))}
</div>
</div>
))}
</div>
</div>
))}
</div>
{/* Pillar 2.7 — surface the keyboard-first reveal so it's discoverable:
every card kebab and memory-row action is reachable by Tab, no
mouse required. */}
<p className="mt-5 border-t border-border/40 pt-4 text-[11px] leading-relaxed text-muted-foreground">
Tab reaches every card &amp; memory-row action — the workspace kebab menu and the
confirm / edit / forget row controls reveal on keyboard focus, no mouse needed.
</p>
</motion.div>
</motion.div>
</AnimatePresence>
);
};
export default KeyboardShortcutsHelp;

View File

@@ -0,0 +1,446 @@
/**
* 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, Sparkles, 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<WorkspaceSummary[]>([]);
const [highlights, setHighlights] = useState<MemoryHighlight[]>([]);
const [brag, setBrag] = useState<BragSummary | null>(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<HTMLDivElement>(!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 (
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
// Bottom-RIGHT, not bottom-center: a centered toast sits in the content
// column and collided with home's overnight headline (R12 judge catch).
className="fixed bottom-6 right-6 z-[90] flex justify-end pointer-events-none"
>
<div
role="status"
data-testid="login-briefing-error"
className="pointer-events-auto flex items-center gap-3 rounded-[12px] border border-[var(--line-soft)] bg-[var(--surface)] px-4 py-2.5 shadow-[var(--shadow-elevated)]"
>
<Brain className="h-4 w-4 shrink-0 text-[var(--honey-text)]" aria-hidden />
<span className="text-[13px] text-[var(--text-2)]">Briefing unavailable</span>
{loading ? (
<Loader2 className="h-4 w-4 animate-spin text-[var(--honey-text)]" aria-label="Retrying" />
) : (
<button
onClick={() => { setLoading(true); void loadBriefing(); }}
data-testid="login-briefing-retry"
className="rounded-[10px] border border-[var(--line)] bg-[var(--surface)] px-2.5 py-1 text-[12.5px] font-medium text-[var(--text-2)] transition-colors hover:border-[var(--honey-line)] hover:text-[var(--text)]"
>
Retry
</button>
)}
<button
onClick={() => onDismiss()}
aria-label="Dismiss briefing"
className="rounded-lg p-1 text-[var(--text-dim)] transition-colors hover:bg-[var(--surface-2)] hover:text-[var(--text)]"
>
<X className="h-4 w-4" />
</button>
</div>
</motion.div>
);
}
return (
<AnimatePresence>
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-[100] bg-black/45 backdrop-blur-[3px] flex items-center justify-center p-8"
onClick={() => onDismiss()}
>
<motion.div
ref={dialogRef}
initial={{ opacity: 0, y: 20, scale: 0.95 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 20, scale: 0.95 }}
transition={{ type: 'spring', damping: 25 }}
role="dialog"
aria-modal="true"
aria-labelledby="login-briefing-title"
tabIndex={-1}
// Wave Q Lane A (item 3): a real elevated surface token instead of the
// translucent `glass` — in light mode `glass` let the dark backdrop
// bleed through as a muddy warm-gray; the opaque ivory `--surface`
// reads as a genuine elevated card in both themes.
className="w-full max-w-lg rounded-2xl border border-[var(--line-soft)] bg-[var(--surface)] p-6 shadow-[var(--shadow-elevated)] focus:outline-none"
onClick={e => e.stopPropagation()}
>
{/* Header — X on the header baseline (items-start), not centered
against the two-line title (Wave Q Lane A item 3). */}
<div className="flex items-start justify-between mb-4">
<div className="min-w-0">
{/* 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. */}
<div className="flex items-center gap-2">
<img src={beeMascot} alt="" aria-hidden width={28} height={28} className="w-7 h-7 shrink-0" />
<h2 id="login-briefing-title" className="text-lg font-display font-bold text-foreground">Catching you up</h2>
</div>
<p className="text-xs text-muted-foreground flex items-center flex-wrap gap-x-1 gap-y-0.5" data-testid="login-briefing-brag-line">
<Brain className="w-3 h-3 inline mr-0.5 shrink-0" />
<span>{bragLine ?? 'Loading…'}</span>
{totalPending > 0 && (
<span
className="text-amber-400 inline-flex items-center gap-0.5"
title="Tasks or approvals waiting for you inside the workspaces below."
>
<AlertTriangle className="w-3 h-3" />
{totalPending} awaiting your OK
</span>
)}
</p>
</div>
<button onClick={() => onDismiss()} aria-label="Close briefing" className="p-1 rounded-lg hover:bg-muted/50 transition-colors shrink-0">
<X className="w-4 h-4 text-muted-foreground" />
</button>
</div>
{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.
<div className="space-y-4" data-testid="login-briefing-skeleton" aria-hidden>
<div className="space-y-1.5">
{[0, 1].map(i => (
<div key={i} className="h-[42px] rounded-lg border border-[var(--honey-line)] bg-[var(--honey-wash)] animate-pulse" />
))}
</div>
<div className="space-y-2">
{[0, 1].map(i => (
<div key={i} className="h-[76px] rounded-xl border border-border/30 bg-secondary/30 animate-pulse" />
))}
</div>
</div>
) : 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.)
<div className="py-2 space-y-3" data-testid="login-briefing-empty-hook">
<div className="space-y-1.5">
<p className="text-[11px] font-display font-semibold text-[var(--honey-text)] uppercase tracking-wider flex items-center gap-1.5">
<Lightbulb className="w-3 h-3" /> Here's what I'll remember for you
</p>
{[
'"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) => (
<motion.div
key={i}
initial={{ opacity: 0, x: -8 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.2 + i * 0.12 }}
className="flex items-start gap-2 px-3 py-1.5 rounded-lg bg-primary/5 border border-primary/10 border-dashed"
>
<Sparkles className="w-3 h-3 text-honey/60 mt-0.5 shrink-0" />
<p className="text-[12px] text-foreground/70 italic leading-relaxed">{demo}</p>
</motion.div>
))}
</div>
<p className="text-[10px] text-muted-foreground italic px-1">
Examples. Your real memory populates as you chat — or import an existing ChatGPT/Claude export from the Memory app.
</p>
</div>
) : (
<>
{/* Memory highlights — "I remember..." */}
{highlights.length > 0 && (
<div className="mb-4 space-y-1.5">
<p className="text-[11px] font-display font-semibold text-[var(--honey-text)] uppercase tracking-wider flex items-center gap-1.5">
<Lightbulb className="w-3 h-3" /> I remember
</p>
{/* 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) => (
<motion.div key={`${revealKey}-h-${i}`} {...entranceProps(i)}>
<RecallCard highlight={h} timeLabel={h.timestamp ? timeAgo(h.timestamp) : undefined} />
</motion.div>
))}
</div>
)}
{/* Workspace list */}
{visibleSummaries.length === 0 ? (
<div className="text-center py-6">
<Sparkles className="w-8 h-8 text-honey/50 mx-auto mb-2" />
<p className="text-sm text-muted-foreground">No active workspaces yet. Create one to get started!</p>
</div>
) : (
// Wave R Lane E: a bottom edge-fade signals "more below" when
// the list overflows its cap (>3 rows overflow max-h-60).
<div className="relative">
<div className="space-y-2 max-h-60 overflow-auto">
{visibleSummaries.map((ws, j) => (
<motion.button
key={`${revealKey}-${ws.id}`}
{...entranceProps(shownHighlights.length + j)}
onClick={() => { 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"
>
<div className="flex items-center justify-between mb-1">
<div className="flex items-center gap-2">
<span className="text-sm font-display font-medium text-foreground">{ws.name}</span>
{/* FR #27: tooltip clarifies what the Personal/Team
tag means. Personal workspaces are private to the
account; Team workspaces are
shared. Without this hint the colored chip reads
as decorative metadata. */}
<HintTooltip
content={
ws.group === 'Personal'
? 'Personal workspaces are visible only to you.'
: 'Team workspaces (Teams/Enterprise) are shared across the organisation.'
}
>
<span className="text-[11px] px-1.5 py-0.5 rounded-full bg-muted text-muted-foreground cursor-help">{ws.group}</span>
</HintTooltip>
</div>
<ChevronRight className="w-3 h-3 text-muted-foreground group-hover:text-honey transition-colors" />
</div>
{/* 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 ? (
<p className="text-[11px] text-muted-foreground mb-1.5 italic">Nothing here yet — start a chat and I'll remember it.</p>
) : ws.summary && !isCannedWorkspaceSummary(ws.summary) ? (
<p className="text-[11px] text-muted-foreground mb-1.5 line-clamp-2">{ws.summary}</p>
) : null}
<div className="flex items-center gap-3 text-[11px] text-muted-foreground">
{/* 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. */}
<span
title={`${ws.memoryCount} ${ws.memoryCount === 1 ? 'memory' : 'memories'}`}
aria-label={`${ws.memoryCount} ${ws.memoryCount === 1 ? 'memory' : 'memories'}`}
>
<Brain className="w-2.5 h-2.5 inline mr-0.5" aria-hidden />{ws.memoryCount}
</span>
<span
title={`${ws.sessionCount} ${ws.sessionCount === 1 ? 'session' : 'sessions'}`}
aria-label={`${ws.sessionCount} ${ws.sessionCount === 1 ? 'session' : 'sessions'}`}
>
<MessageSquare className="w-2.5 h-2.5 inline mr-0.5" aria-hidden />{ws.sessionCount}
</span>
{/* 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) && (
<span><Clock className="w-2.5 h-2.5 inline mr-0.5" />{new Date(ws.lastActive).toLocaleDateString(DATE_LOCALE)}</span>
)}
{ws.pendingTasks && ws.pendingTasks.length > 0 && (
<span className="text-amber-400"><AlertTriangle className="w-2.5 h-2.5 inline mr-0.5" />{ws.pendingTasks.length} pending</span>
)}
</div>
</motion.button>
))}
</div>
{visibleSummaries.length > 3 && (
<div
aria-hidden
className="pointer-events-none absolute inset-x-0 bottom-0 h-6 rounded-b-xl bg-gradient-to-t from-[var(--surface)] to-transparent"
/>
)}
</div>
)}
</>
)}
{/* Footer */}
<div className="mt-4 pt-3 border-t border-border/30 flex justify-between items-center gap-3">
<HintTooltip content="Hide the briefing permanently. Re-enable in Settings → Advanced.">
<button
onClick={() => onDismiss(true)}
data-testid="login-briefing-dont-show-again"
className="text-[11px] text-[var(--text-tertiary)] hover:text-foreground transition-colors font-display"
>
Don't show again
</button>
</HintTooltip>
<button
onClick={() => onDismiss(false)}
disabled={loading}
data-testid="login-briefing-dismiss"
className="px-3 py-1.5 text-xs rounded-lg bg-primary text-primary-foreground hover:bg-primary/80 transition-colors font-display disabled:opacity-50 disabled:cursor-not-allowed"
>
Start Working
</button>
</div>
</motion.div>
</motion.div>
</AnimatePresence>
);
};
export default LoginBriefing;

View File

@@ -0,0 +1,125 @@
import { Bell, Check, CheckCheck, X, CheckCircle2, ArrowRight, Clock, ShieldCheck, ClipboardList, MessageSquare, Bot, Pin, type LucideIcon } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import type { Notification } from '@/lib/types';
import { motion, AnimatePresence } from 'framer-motion';
import { HintTooltip } from '@/components/ui/hint-tooltip';
import { humanizeNotification } from '@/lib/notification-copy';
import { formatRelativeTime } from '@/lib/agent-center-display';
import { useFocusTrap } from '@/hooks/useFocusTrap';
interface NotificationInboxProps {
open: boolean;
onClose: () => void;
notifications: Notification[];
onMarkRead: (id: string) => void;
onMarkAllRead: () => void;
}
// Lucide, not emoji — one icon language across the chrome (2026-07-06 P2).
const typeIcons: Record<string, LucideIcon> = {
cron: Clock, approval: ShieldCheck, task: ClipboardList, message: MessageSquare, agent: Bot,
};
const NotificationInbox = ({ open, onClose, notifications, onMarkRead, onMarkAllRead }: NotificationInboxProps) => {
const navigate = useNavigate();
const dialogRef = useFocusTrap<HTMLDivElement>(open, onClose);
if (!open) return null;
const openAction = (n: Notification, href: string) => {
if (!n.read) onMarkRead(n.id);
onClose();
navigate(href);
};
return (
<AnimatePresence>
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-[100]"
onClick={onClose}
>
<div className="absolute inset-0 bg-black/40 backdrop-blur-sm" />
<motion.div
ref={dialogRef}
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0 }}
role="dialog"
aria-modal="true"
aria-labelledby="notification-inbox-title"
tabIndex={-1}
className="absolute top-10 right-4 w-80 glass-strong rounded-2xl shadow-2xl overflow-hidden focus:outline-none"
onClick={e => e.stopPropagation()}
>
<div className="flex items-center justify-between px-4 py-3 border-b border-border/30">
<div className="flex items-center gap-2">
<Bell className="w-4 h-4 text-honey" />
<span id="notification-inbox-title" className="text-sm font-display font-semibold text-foreground">Notifications</span>
</div>
<div className="flex items-center gap-1">
<HintTooltip content="Mark all read">
<button
onClick={onMarkAllRead}
aria-label="Mark all notifications as read"
className="p-1 rounded text-muted-foreground hover:text-foreground transition-colors"
>
<CheckCheck className="w-3.5 h-3.5" />
</button>
</HintTooltip>
<button onClick={onClose} aria-label="Close notifications" className="p-1 rounded text-muted-foreground hover:text-foreground transition-colors">
<X className="w-3.5 h-3.5" />
</button>
</div>
</div>
<div className="max-h-80 overflow-auto">
{notifications.length === 0 && (
<div className="py-8 text-center">
<CheckCircle2 className="w-8 h-8 text-emerald-400/40 mx-auto mb-2" />
<p className="text-xs text-foreground font-display font-medium">All caught up</p>
<p className="text-[11px] text-muted-foreground mt-1">No new notifications</p>
</div>
)}
{notifications.map(n => {
const { title, body, href } = humanizeNotification(n);
const TypeIcon = typeIcons[n.type] ?? Pin;
return (
<div
key={n.id}
className={`px-4 py-3 border-b border-border/20 transition-colors ${
n.read ? 'opacity-60' : 'bg-primary/5'
}`}
>
<div className="flex items-start gap-2">
<TypeIcon className="w-4 h-4 mt-0.5 text-honey/70 shrink-0" aria-hidden />
<div className="flex-1 min-w-0">
<p className="text-xs font-display font-medium text-foreground">{title}</p>
{body && <p className="text-[11px] text-muted-foreground mt-0.5">{body}</p>}
<p className="text-[11px] text-muted-foreground mt-1">{formatRelativeTime(n.timestamp)}</p>
{href && (
<button
onClick={() => openAction(n, href)}
className="mt-1.5 inline-flex items-center gap-1 text-[11px] font-medium text-honey hover:underline"
>
Open <ArrowRight className="w-3 h-3" />
</button>
)}
</div>
{!n.read && (
<button onClick={() => onMarkRead(n.id)} className="p-1 text-muted-foreground hover:text-honey transition-colors" aria-label="Mark as read">
<Check className="w-3 h-3" />
</button>
)}
</div>
</div>
);
})}
</div>
</motion.div>
</motion.div>
</AnimatePresence>
);
};
export default NotificationInbox;

View File

@@ -0,0 +1,168 @@
import { useCallback, useEffect, useState, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { DUR } from '@/lib/motion/tokens';
// FR #47: previously two BASE_TIPS plus CLOSING_TIP gave a no-template flow
// only three slides, and the second slide ("Your AI remembers everything")
// can read as a paraphrase of the first slide's "search, draft, research"
// promise. Splitting the tour into four slides — commands, dock, memory,
// closing — gives every slide a distinct visual focus and prevents the
// "step 2 has identical text as step 1" perception PM hit on 2026-05-01.
const BASE_TIPS = [
'Type / for 22 powerful commands — search, draft, research, and more.',
'Click dock icons to open Memory, Files, Connectors, Mission Control, and more.',
'Your AI remembers everything — across every session, every workspace.',
];
const TEMPLATE_TIPS: Record<string, string[]> = {
'sales-pipeline': [
'Try "Research [company name]" to get a full prospect brief.',
'Use /draft to create personalized outreach emails.',
],
'research-project': [
'Try /research [any topic] — watch your agent search and synthesize.',
'Use /memory to review what your agent has learned so far.',
],
'code-review': [
'Try /review to analyze code quality and suggest improvements.',
'Use /plan for multi-step refactoring plans.',
],
'marketing-campaign': [
'Try /draft campaign brief to kickstart your strategy.',
'Use /research competitors to analyze your market.',
],
'product-launch': [
'Try /draft PRD to create a product requirements document.',
'Use /plan to build a launch checklist with milestones.',
],
'legal-review': [
'Try /review to analyze contracts and flag risky clauses.',
'Use /research for legal precedent and regulatory context.',
],
'agency-consulting': [
'Try /research [client company] for a deep client brief.',
'Use /status for project metrics across engagements.',
],
};
const CLOSING_TIP = 'Check your Memory tab to see what your agent learns over time.';
interface OnboardingTooltipsProps {
templateId?: string;
onDismiss?: () => void;
/** Hide the card (keep tour state) while an overlay it describes is open —
* the Ctrl+K tip painting OVER the open palette blocked reading both. */
suppressed?: boolean;
}
const OnboardingTooltips = ({ templateId, onDismiss, suppressed }: OnboardingTooltipsProps) => {
const [tipIndex, setTipIndex] = useState(0);
const [dismissed, setDismissed] = useState(() => {
return localStorage.getItem('waggle:tooltips_done') === 'true';
});
const tips = useMemo(() => {
const specific = templateId ? (TEMPLATE_TIPS[templateId] ?? []) : [];
return [...BASE_TIPS, ...specific, CLOSING_TIP];
}, [templateId]);
const isLast = tipIndex >= tips.length - 1;
const dismissTour = useCallback(() => {
setDismissed(true);
localStorage.setItem('waggle:tooltips_done', 'true');
onDismiss?.();
}, [onDismiss]);
useEffect(() => {
if (dismissed || suppressed) return;
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') dismissTour();
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [dismissed, dismissTour, suppressed]);
const handleNext = () => {
if (isLast) {
dismissTour();
} else {
setTipIndex(i => i + 1);
}
};
const handleDismissAll = () => {
dismissTour();
};
if (dismissed) return null;
return (
<AnimatePresence>
{!dismissed && !suppressed && (
<div className="pointer-events-none fixed inset-0 z-[100] flex items-center justify-center px-4">
<motion.div
initial={{ opacity: 0, scale: 0.95, y: 10 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95, y: 10 }}
transition={{ type: 'spring', damping: 22, stiffness: 260 }}
role="dialog"
aria-modal="false"
aria-labelledby="onboarding-tooltips-title"
aria-describedby="onboarding-tooltips-body"
tabIndex={-1}
className="glass-strong pointer-events-auto w-full max-w-lg rounded-2xl border border-primary/20 px-5 py-5 shadow-2xl sm:px-8 sm:py-7"
>
<h2 id="onboarding-tooltips-title" className="sr-only">Waggle tips</h2>
<AnimatePresence mode="wait">
<motion.p
key={tipIndex}
id="onboarding-tooltips-body"
initial={{ opacity: 0, x: 10 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -10 }}
transition={{ duration: DUR.fast }}
className="text-lg text-foreground mb-5 leading-relaxed"
>
{tips[tipIndex]}
</motion.p>
</AnimatePresence>
<div className="flex items-center justify-between">
{/* Dot indicators */}
<div className="flex gap-1.5" aria-hidden="true">
{tips.map((_, i) => (
<div
key={i}
className={`w-2 h-2 rounded-full transition-colors ${
i === tipIndex ? 'bg-primary' : 'bg-muted-foreground/30'
}`}
/>
))}
</div>
<div className="flex items-center gap-4">
<button
onClick={handleDismissAll}
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
>
Dismiss all
</button>
<button
onClick={handleNext}
className="px-4 py-1.5 rounded-lg bg-primary text-primary-foreground text-sm font-display font-semibold hover:bg-primary/80 transition-colors"
>
{isLast ? 'Got it' : 'Next'}
</button>
</div>
</div>
</motion.div>
</div>
)}
</AnimatePresence>
);
};
export default OnboardingTooltips;

View File

@@ -0,0 +1,470 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { motion, AnimatePresence, MotionConfig, useReducedMotion } from 'framer-motion';
import beeMascot from '@/assets/personas/general-purpose.png';
import { adapter } from '@/lib/adapter';
import { captureOnboardingComplete } from '@/lib/posthog';
import { useOfflineStatus } from '@/hooks/useOfflineStatus';
import type { OnboardingState } from '@/hooks/useOnboarding';
import type { UserProfile, ClassifiedHarvestItem } from '@/lib/types';
import {
WelcomeStep,
WhoAreYouStep,
ModelGateStep,
ImportStep,
TemplateStep,
FirstTaskStep,
} from './onboarding';
import type { OnboardingProfileFields } from './onboarding';
import { CURATED_ONBOARDING_TEMPLATES, TEMPLATE_PERSONA, TEMPLATE_SUGGESTIONS } from './onboarding/constants';
import { recommendTemplateId } from './onboarding/recommend-template';
import { DUR, EASE_OUT } from '@/lib/motion/tokens';
/* ─── Props ─── */
interface OnboardingWizardProps {
serverBaseUrl: string;
state: OnboardingState;
onUpdate: (updates: Partial<OnboardingState>) => void;
onComplete: (serverBaseUrl: string) => void;
onDismiss: () => void;
onFinish: (workspaceId: string, workspaceName: string, firstMessage: string, personaId?: string) => void;
}
/* ─── M2-7: Fire-and-forget telemetry via adapter ─── */
function trackTelemetry(_serverBaseUrl: string, event: string, properties?: Record<string, unknown>) {
adapter.trackTelemetry(event, properties);
}
/* ─── PR5 6-step chain (S12→S17, C33) with the hard model gate at step 3.
`ready` is terminal. All navigation is driven off STEP_NAMES.indexOf(name) —
never a magic number — so re-keying the chain can't strand the user mid-flow.
The model-gate sits between who-are-you and memory-import (D4 order: Welcome ·
About-you · Model · Import · Template · First-task). */
const STEP_NAMES = ['first-launch', 'who-are-you', 'model-gate', 'memory-import', 'template', 'first-task'] as const;
type StepName = typeof STEP_NAMES[number];
const stepIndex = (name: StepName): number => STEP_NAMES.indexOf(name);
const LAST_INDEX = STEP_NAMES.length - 1;
/** Steps that show the Back affordance + numbered dots (every interactive step
* after first-launch, THROUGH the terminal first-task — so it reads its own
* "Step 5 of 5" rather than a second "Step 4 of 4" duplicating the template). */
const FIRST_NAV_INDEX = stepIndex('who-are-you');
const LAST_NAV_INDEX = stepIndex('first-task');
const DEFAULT_FIRST_MESSAGE = 'Hello! What can you help me with?';
/* ─── Main Component (shell) ─── */
const OnboardingWizard = ({ serverBaseUrl, state, onUpdate, onComplete, onDismiss, onFinish }: OnboardingWizardProps) => {
// Resume guard: a pre-rework interrupted session could have persisted a
// `state.step` (5-7) that no longer maps to the re-keyed 5-step chain. Clamp
// into [0, LAST_INDEX] so resume always lands on a renderable step rather
// than a blank screen. `?forceWizard=true` already resets step to 0.
const [step, setStep] = useState(() => Math.min(Math.max(state.step, 0), LAST_INDEX));
const autoTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const offline = useOfflineStatus();
const reduceMotion = useReducedMotion();
/* ── Profile (S13 / B8) ── */
const [profile, setProfile] = useState<OnboardingProfileFields>({
name: '', role: '', industry: '', workType: '', teamSize: '', goals: [],
});
const [savingProfile, setSavingProfile] = useState(false);
/* ── Import (S15 / C33) ── */
const [importSource, setImportSource] = useState<string | null>(null);
const [importData, setImportData] = useState<unknown>(null);
const [importItems, setImportItems] = useState<ClassifiedHarvestItem[]>([]);
const [importing, setImporting] = useState(false);
const [importDone, setImportDone] = useState(false);
const [claudeCodeDetected, setClaudeCodeDetected] = useState<{ found: boolean; itemCount: number; path: string } | null>(null);
/* ── Workspace + first task (PR5 Template → First-task steps) ── */
const [workspaceName, setWorkspaceName] = useState('');
const [creatingWorkspace, setCreatingWorkspace] = useState(false);
const [creatingTemplateId, setCreatingTemplateId] = useState<string | null>(null);
const [createError, setCreateError] = useState<string | null>(null);
const [firstMessage, setFirstMessage] = useState(DEFAULT_FIRST_MESSAGE);
/* ── Connect on mount + track start; hydrate any existing profile ── */
useEffect(() => {
adapter.connect().catch(() => {});
trackTelemetry(serverBaseUrl, 'onboarding_start');
let cancelled = false;
(async () => {
try {
const p = (await adapter.getProfile()) as UserProfile | null;
if (cancelled || !p) return;
setProfile(prev => ({
name: p.name ?? prev.name,
role: p.role ?? prev.role,
industry: p.industry ?? prev.industry,
workType: p.workType ?? prev.workType,
teamSize: p.teamSize ?? prev.teamSize,
// Intent-signal chips always start unselected — hydrating stored goals
// lit every chip and gave zero fresh signal. Identity fields above
// still prefill; a returning user re-selecting none can't clobber the
// stored goals (handleProfileContinue maps empty → undefined, and the
// PUT /api/profile merge skips undefined).
goals: prev.goals ?? [],
}));
} catch { /* sidecar not ready — start with empty profile */ }
})();
return () => { cancelled = true; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
/* ── A11y (WCAG 2.1.1): Escape maps to Skip. Clears any pending timer. ── */
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
clearTimeout(autoTimer.current);
trackTelemetry(serverBaseUrl, 'onboarding_skip', { atStep: step, via: 'escape' });
onDismiss();
}
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [step, onDismiss, serverBaseUrl]);
const goToStep = useCallback((n: number) => {
setStep(n);
onUpdate({ step: n });
trackTelemetry(serverBaseUrl, 'onboarding_step', { step: n, stepName: STEP_NAMES[n] ?? `step-${n}` });
}, [onUpdate, serverBaseUrl]);
const goToName = useCallback((name: StepName) => goToStep(stepIndex(name)), [goToStep]);
/* ── S13 / B8: write profile AND seed identity in one Continue. ── */
const handleProfileContinue = useCallback(async () => {
setSavingProfile(true);
try {
const payload: Partial<OnboardingProfileFields> = {
name: profile.name?.trim() || undefined,
role: profile.role?.trim() || undefined,
industry: profile.industry || undefined,
workType: profile.workType || undefined,
teamSize: profile.teamSize || undefined,
goals: profile.goals && profile.goals.length > 0 ? profile.goals : undefined,
};
try {
await adapter.updateProfile(payload as Record<string, unknown>);
// B8: seed the per-mind identity so the Home cockpit greets by name.
await adapter.setIdentity({
name: payload.name,
role: payload.role,
department: payload.industry,
});
onUpdate({ profileSeeded: true });
} catch { /* sidecar offline — proceed; profile can be set later in My Profile */ }
trackTelemetry(serverBaseUrl, 'onboarding_profile_seeded', {
hasName: Boolean(payload.name),
hasRole: Boolean(payload.role),
goalCount: payload.goals?.length ?? 0,
});
goToName('model-gate');
} finally {
setSavingProfile(false);
}
}, [profile, onUpdate, serverBaseUrl, goToName]);
/* ── S15 / C33: file import → classified preview ── */
const handleFileImport = async (file: File, source: string) => {
try {
const text = await file.text();
let data: unknown;
try { data = JSON.parse(text); } catch { data = text; }
setImportData(data);
setImportSource(source);
const result = await adapter.harvestPreview(data, source);
const items = (result?.items ?? result?.preview ?? []) as ClassifiedHarvestItem[];
setImportItems(items);
} catch { /* ignore parse errors */ }
};
// C33: commit-all default — every item lands `status:'unreviewed'` server-side.
const handleImportCommit = async () => {
if (!importData || !importSource) return;
setImporting(true);
try {
await adapter.harvestCommit(importData, importSource);
setImportDone(true);
setTimeout(() => goToName('template'), 800);
} catch { /* ignore */ }
finally { setImporting(false); }
};
/* ── Claude Code auto-detect on mount ── */
useEffect(() => {
let cancelled = false;
(async () => {
try {
const data = await adapter.scanClaudeCode();
if (!cancelled) setClaudeCodeDetected(data);
} catch { /* sidecar offline — banner stays hidden */ }
})();
return () => { cancelled = true; };
}, []);
const handleClaudeCodeHarvest = async () => {
setImporting(true);
setImportSource('claude-code');
try {
await adapter.harvestCommit({ scanLocal: true }, 'claude-code');
setImportDone(true);
setTimeout(() => goToName('template'), 800);
} catch { /* ignore */ }
finally { setImporting(false); }
};
/* ── PR5 Template step: create the first workspace from the chosen template
(matching specialist persona + template id), then seed the first task. The
template names + types the workspace (D4 folds the old workspace-create step). ── */
const handleCreateFromTemplate = useCallback(async (templateId: string) => {
const tmpl = CURATED_ONBOARDING_TEMPLATES.find(t => t.id === templateId);
const persona = TEMPLATE_PERSONA[templateId] ?? 'general-purpose';
const wsName = tmpl?.name || 'My Workspace';
setCreatingWorkspace(true);
setCreatingTemplateId(templateId);
try {
let wsId: string;
// Reuse guard (nav-chrome now reaches first-task, so Back → re-select is
// possible): if this exact template already created a workspace, reuse it
// instead of minting a duplicate. Picking a DIFFERENT template still
// creates a new one (the prior workspace is orphaned but cheap/deletable).
if (state.workspaceId && state.templateId === templateId) {
wsId = state.workspaceId;
setCreateError(null);
} else {
try {
const ws = await adapter.createWorkspace({
name: wsName,
group: 'Personal',
type: 'project',
persona,
templateId,
});
wsId = ws.id;
setCreateError(null);
} catch {
setCreateError('Could not connect to server — workspace created locally. Connect to sync later.');
wsId = `local-${Date.now()}`;
}
}
setWorkspaceName(wsName);
// Seed the first task with the template's hint — the user can edit it.
setFirstMessage(tmpl?.hint?.trim() || DEFAULT_FIRST_MESSAGE);
// Persist templateId so the first-task suggestion chips are template-
// tailored (and survive a mid-wizard refresh) and the reuse guard can fire.
onUpdate({ workspaceId: wsId, personaId: persona, templateId });
trackTelemetry(serverBaseUrl, 'onboarding_complete', { templateId, importedMemory: importDone });
captureOnboardingComplete({ templateId, personaId: persona, model: null });
goToName('first-task');
} finally {
setCreatingWorkspace(false);
setCreatingTemplateId(null);
}
}, [importDone, onUpdate, serverBaseUrl, goToName, state.workspaceId, state.templateId]);
const handleLetsGo = useCallback(() => {
clearTimeout(autoTimer.current);
onComplete(serverBaseUrl);
const wsId = state.workspaceId || `local-${Date.now()}`;
const wsName = workspaceName.trim() || 'My Workspace';
const personaId = state.personaId || 'general-purpose';
onFinish(wsId, wsName, firstMessage.trim() || DEFAULT_FIRST_MESSAGE, personaId);
}, [serverBaseUrl, onComplete, onFinish, state.workspaceId, state.personaId, workspaceName, firstMessage]);
if (state.completed) return null;
const progressPct = LAST_INDEX > 0 ? (step / LAST_INDEX) * 100 : 0;
// Nav chrome (Back + "Step N of M" + dots) spans who-are-you → first-task, so
// each interactive step has a distinct counter/dot fill (template = 4 of 5,
// first-task = 5 of 5) instead of two identical "Step 4 of 4" screens.
const showNavChrome = step >= FIRST_NAV_INDEX;
const navTotal = LAST_NAV_INDEX - FIRST_NAV_INDEX + 1;
const navCurrent = step - FIRST_NAV_INDEX + 1;
const recommendedId = recommendTemplateId(profile.workType, profile.role);
return (
// Wave V Lane F item 3 (motion-safe): reducedMotion="user" makes the shared
// fadeSlide step transition (and the progress-bar fill) honor
// prefers-reduced-motion — the y-slide drops to a pure opacity fade for
// reduced-motion users, while everyone else keeps the ~200ms slide/fade.
<MotionConfig reducedMotion="user">
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
role="region"
aria-label="Waggle onboarding"
className="onboarding-scrim fixed inset-0 z-[9999] flex flex-col"
style={{
backdropFilter: 'blur(8px)',
WebkitBackdropFilter: 'blur(8px)',
}}
>
{/* Progress bar — carries the semantic progress signal for screen readers */}
<div
role="progressbar"
aria-valuenow={step}
aria-valuemin={0}
aria-valuemax={LAST_INDEX}
aria-label="Onboarding progress"
className="h-1 w-full bg-muted/30"
>
<motion.div
className="h-full bg-primary"
initial={{ width: 0 }}
animate={{ width: `${progressPct}%` }}
transition={{ duration: DUR.settle, ease: EASE_OUT }}
/>
</div>
{/* Top bar: mascot + step dots + back + skip */}
<div className="flex items-center justify-between px-6 py-4">
<div className="flex items-center gap-3">
{/* Wave V Lane F item 3 (mascot carry): the breathing hex-bee greets
the user on Welcome, then used to vanish — every later step opened
with a different generic glyph, breaking the brand moment. This
persistent mascot lives in the shell chrome (outside AnimatePresence)
so it stays mounted and keeps breathing continuously as steps change.
Shown from who-are-you onward (Welcome keeps its own hero mascot).
Motion-safe: reduced-motion holds a single static drop-shadow. */}
{showNavChrome && (
<motion.img
src={beeMascot}
alt="Waggle"
className="h-7 w-7 shrink-0"
animate={
reduceMotion
? { filter: 'drop-shadow(0 0 8px hsl(var(--primary) / 0.30))' }
: {
filter: [
'drop-shadow(0 0 5px hsl(var(--primary) / 0.20))',
'drop-shadow(0 0 11px hsl(var(--primary) / 0.42))',
'drop-shadow(0 0 5px hsl(var(--primary) / 0.20))',
],
}
}
transition={
reduceMotion
? { duration: 0 }
// Ambient breathing loop — deliberately outside the --mo interaction
// tiers (a 4.5s symmetric easeInOut pulse, not a fast/base/slow/settle
// gesture); REDUCED.ambient='off' is honoured by the reduceMotion branch.
: { duration: 4.5, repeat: Infinity, ease: 'easeInOut' }
}
/>
)}
{showNavChrome && (
<button
onClick={() => {
clearTimeout(autoTimer.current);
goToStep(step - 1);
}}
className="text-xs text-muted-foreground hover:text-foreground transition-colors font-display px-3 py-2 rounded-md focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background"
aria-label="Go to previous step"
>
← Back
</button>
)}
{showNavChrome && (
<span className="text-xs font-display text-muted-foreground">
Step {navCurrent} of {navTotal}
</span>
)}
{showNavChrome && (
<div className="flex gap-1.5" aria-hidden="true">
{STEP_NAMES.slice(FIRST_NAV_INDEX, LAST_NAV_INDEX + 1).map((_, idx) => {
const navStep = FIRST_NAV_INDEX + idx;
return (
<div
key={navStep}
className={`w-2 h-2 rounded-full transition-colors ${
navStep <= step ? 'bg-primary' : 'bg-muted/40'
}`}
/>
);
})}
</div>
)}
</div>
<button
onClick={() => {
trackTelemetry(serverBaseUrl, 'onboarding_skip', { atStep: step });
onDismiss();
}}
className="text-xs text-muted-foreground hover:text-foreground transition-colors font-display px-3 py-2 rounded-md focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
Skip setup
</button>
</div>
{/* Content area — renders current step by NAME */}
<div className="flex-1 flex items-start justify-center overflow-y-auto px-4 py-3 sm:items-center sm:px-6 sm:py-0">
<div className="w-full max-w-2xl">
<AnimatePresence mode="wait">
{step === stepIndex('first-launch') && (
<WelcomeStep
onClickAnywhere={() => { clearTimeout(autoTimer.current); goToName('who-are-you'); }}
offline={offline}
/>
)}
{step === stepIndex('who-are-you') && (
<WhoAreYouStep
profile={profile}
onChange={(patch) => setProfile(prev => ({ ...prev, ...patch }))}
onContinue={handleProfileContinue}
saving={savingProfile}
/>
)}
{step === stepIndex('model-gate') && (
<ModelGateStep
onContinue={() => goToName('memory-import')}
onLater={() => {
clearTimeout(autoTimer.current);
trackTelemetry(serverBaseUrl, 'onboarding_skip', { atStep: step, via: 'model-gate-later' });
onDismiss();
}}
/>
)}
{step === stepIndex('memory-import') && (
<ImportStep
importSource={importSource}
importItems={importItems}
importDone={importDone}
importing={importing}
onFileImport={handleFileImport}
onImportCommit={handleImportCommit}
claudeCodeDetected={claudeCodeDetected}
onClaudeCodeHarvest={handleClaudeCodeHarvest}
onContinue={() => goToName('template')}
/>
)}
{step === stepIndex('template') && (
<TemplateStep
templates={CURATED_ONBOARDING_TEMPLATES}
onSelect={handleCreateFromTemplate}
creating={creatingWorkspace}
creatingId={creatingTemplateId}
createError={createError}
recommendedId={recommendedId}
/>
)}
{step === stepIndex('first-task') && (
<FirstTaskStep
message={firstMessage}
onMessageChange={setFirstMessage}
suggestions={TEMPLATE_SUGGESTIONS[state.templateId ?? ''] ?? CURATED_ONBOARDING_TEMPLATES.map(t => t.hint)}
onPickSuggestion={setFirstMessage}
onLetsGo={handleLetsGo}
createError={createError}
/>
)}
</AnimatePresence>
</div>
</div>
</motion.div>
</MotionConfig>
);
};
export default OnboardingWizard;

View File

@@ -0,0 +1,349 @@
import { useState, useEffect, useMemo } from 'react';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { PERSONAS } from '@/lib/personas';
import { adapter } from '@/lib/adapter';
import { motion, AnimatePresence } from 'framer-motion';
import { Bot, Users, Loader2, Sparkles, ChevronDown, Eye } from 'lucide-react';
import { useFocusTrap } from '@/hooks/useFocusTrap';
import {
UNIVERSAL_MODE_IDS,
ALL_SPECIALIST_IDS,
getSpecialistsForTemplate,
} from '@/lib/persona-tier';
import { buildPersonaTooltip } from '@/lib/persona-tooltip';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
interface BackendPersona {
id: string;
name: string;
description: string;
icon?: string;
tagline?: string;
bestFor?: string[];
wontDo?: string;
isReadOnly?: boolean;
}
interface AgentGroupOption {
id: string;
name: string;
description?: string;
strategy: string;
members: { agentId: string }[];
}
interface PersonaSwitcherProps {
open: boolean;
onClose: () => void;
currentPersona?: string;
currentGroupId?: string;
/** Active workspace template id — controls which specialists are promoted. */
currentTemplateId?: string;
onSelect: (personaId: string) => void;
onSelectGroup?: (groupId: string) => void;
}
type PersonaCard = {
id: string;
name: string;
description: string;
icon?: string;
avatar?: string;
tagline?: string;
bestFor?: string[];
wontDo?: string;
isReadOnly?: boolean;
};
interface PersonaAgentsListProps {
personas: PersonaCard[];
currentTemplateId?: string;
showAllSpecialists: boolean;
onToggleShowAll: () => void;
renderPersonaCard: (p: PersonaCard) => React.ReactNode;
}
/**
* M-01 two-tier layout: UNIVERSAL MODES (8) + YOUR WORKSPACE SPECIALISTS
* (template-scoped). When a workspace template is active, the Specialists
* section surfaces only the mapped specialists; a "Show all specialists"
* toggle expands the full roster on demand.
*/
const PersonaAgentsList = ({
personas, currentTemplateId, showAllSpecialists, onToggleShowAll,
renderPersonaCard,
}: PersonaAgentsListProps) => {
const personaById = useMemo(() => new Map(personas.map(p => [p.id, p])), [personas]);
const universalCards = UNIVERSAL_MODE_IDS
.map(id => personaById.get(id))
.filter((p): p is PersonaCard => p !== undefined);
const availableSpecialistIds = ALL_SPECIALIST_IDS.filter(id => personaById.has(id));
const { primary, others, hasMapping } = useMemo(
() => getSpecialistsForTemplate(currentTemplateId, availableSpecialistIds),
[currentTemplateId, availableSpecialistIds],
);
const visibleSpecialists = (hasMapping && !showAllSpecialists ? primary : [...primary, ...others])
.map(id => personaById.get(id))
.filter((p): p is PersonaCard => p !== undefined);
return (
<div className="max-h-[380px] overflow-y-auto scrollbar-thin space-y-4">
{/* Universal Modes — always 8, same for every workspace */}
<div>
<h3 className="text-[11px] font-display font-bold text-muted-foreground uppercase tracking-wider mb-2 px-1">
Universal Modes
</h3>
<div className="grid grid-cols-2 gap-2">
{universalCards.map(p => renderPersonaCard(p))}
</div>
</div>
{/* Specialists — template-scoped */}
{visibleSpecialists.length > 0 && (
<div>
<div className="flex items-center justify-between mb-2 px-1">
<h3 className="text-[11px] font-display font-bold text-muted-foreground uppercase tracking-wider flex items-center gap-1.5">
{hasMapping && <Sparkles className="w-3 h-3 text-honey" aria-hidden="true" />}
{hasMapping ? 'Your Workspace Specialists' : 'Specialists'}
</h3>
{hasMapping && others.length > 0 && (
<button
onClick={onToggleShowAll}
aria-expanded={showAllSpecialists}
className="flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground transition-colors"
data-testid="persona-show-all-specialists"
>
{showAllSpecialists ? 'Hide others' : `Show all (${others.length} more)`}
<ChevronDown
className={`w-3 h-3 transition-transform ${showAllSpecialists ? 'rotate-180' : ''}`}
aria-hidden="true"
/>
</button>
)}
</div>
<div className="grid grid-cols-2 gap-2">
{visibleSpecialists.map(p => renderPersonaCard(p))}
</div>
</div>
)}
</div>
);
};
const PersonaSwitcher = ({
open, onClose, currentPersona, currentGroupId, currentTemplateId,
onSelect, onSelectGroup,
}: PersonaSwitcherProps) => {
const [tab, setTab] = useState<'agents' | 'groups'>('agents');
const [backendPersonas, setBackendPersonas] = useState<BackendPersona[] | null>(null);
const [groups, setGroups] = useState<AgentGroupOption[]>([]);
const [loading, setLoading] = useState(false);
// Template-scoping: when a template is active, only the mapped specialists
// render by default. User can expand to see the full roster.
const [showAllSpecialists, setShowAllSpecialists] = useState(false);
useEffect(() => {
if (!open) return;
setLoading(true);
Promise.allSettled([
adapter.getPersonas(),
adapter.getAgentGroups(),
]).then(([personasRes, groupsRes]) => {
if (personasRes.status === 'fulfilled') {
setBackendPersonas(personasRes.value as BackendPersona[]);
}
if (groupsRes.status === 'fulfilled') {
setGroups(groupsRes.value as AgentGroupOption[]);
}
setLoading(false);
});
}, [open]);
// A11y (WCAG 2.1.1/2.4.3): Escape closes, Tab is trapped within the dialog,
// focus moves in on open and restores on close — the same shared hook the
// other modal overlays use. Replaces the prior Escape-only handler (which
// had no focus trap or restore, so keyboard users tabbed out into the shell).
const dialogRef = useFocusTrap<HTMLDivElement>(open, onClose);
if (!open) return null;
// Use backend personas if available, fall back to local
const personas: PersonaCard[] =
backendPersonas
? backendPersonas.map(bp => {
const local = PERSONAS.find(p => p.id === bp.id);
return { ...bp, avatar: local?.avatar };
})
: PERSONAS.map(p => ({ id: p.id, name: p.name, description: p.description, avatar: p.avatar }));
const renderPersonaCard = (p: PersonaCard) => {
const tooltip = buildPersonaTooltip(p);
const card = (
<button
key={p.id}
onClick={() => { onSelect(p.id); onClose(); }}
aria-label={p.name}
className={`flex items-center gap-3 p-3 rounded-xl transition-colors text-left focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background ${
currentPersona === p.id && !currentGroupId
? 'bg-primary/20 border border-primary/50'
: 'bg-secondary/30 border border-transparent hover:bg-secondary/50'
}`}
// Fall back to description-only title when we don't have rich content;
// Radix Tooltip handles the rich case below.
title={tooltip.hasRichContent ? undefined : p.description}
>
<Avatar className="w-10 h-10 shrink-0">
{p.avatar ? <AvatarImage src={p.avatar} alt="" /> : (
<AvatarFallback className="text-[11px] bg-primary/20">{p.icon || p.name[0]}</AvatarFallback>
)}
</Avatar>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1">
<p className="text-xs font-display font-medium truncate text-foreground">{p.name}</p>
{tooltip.isReadOnly && (
<Eye className="w-3 h-3 text-sky-400/80 shrink-0" aria-label="Read-only persona" />
)}
</div>
{/* A11y audit #5: bumped text-[11px] → text-xs for readability floor */}
<p className="text-xs truncate text-muted-foreground">{p.description}</p>
</div>
</button>
);
if (!tooltip.hasRichContent) return card;
return (
<Tooltip key={p.id} delayDuration={250}>
<TooltipTrigger asChild>{card}</TooltipTrigger>
<TooltipContent side="right" align="start" className="max-w-[280px] text-xs p-3 space-y-2" sideOffset={6}>
<div>
<p className="font-display font-semibold text-foreground">{tooltip.name}</p>
<p className="text-muted-foreground mt-0.5">{tooltip.headline}</p>
</div>
{tooltip.bestFor.length > 0 && (
<div>
<p className="text-[10px] font-display font-semibold uppercase tracking-wider text-[var(--honey-text)] mb-1">Best for</p>
<ul className="space-y-0.5">
{tooltip.bestFor.map(item => (
<li key={item} className="text-muted-foreground leading-tight">• {item}</li>
))}
</ul>
</div>
)}
{tooltip.wontDo && (
<div>
<p className="text-[10px] font-display font-semibold uppercase tracking-wider text-[var(--status-error)] mb-1">Won’t do</p>
<p className="text-muted-foreground leading-tight">{tooltip.wontDo}</p>
</div>
)}
{tooltip.isReadOnly && (
<p className="text-[10px] text-sky-400/90 flex items-center gap-1">
<Eye className="w-3 h-3" aria-hidden="true" />Read-only — never writes files or runs commands
</p>
)}
</TooltipContent>
</Tooltip>
);
};
return (
<AnimatePresence>
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-[100] flex items-center justify-center"
onClick={onClose}
>
<div className="absolute inset-0 bg-black/50 backdrop-blur-sm" aria-hidden="true" />
<motion.div
ref={dialogRef}
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
role="dialog"
aria-modal="true"
aria-labelledby="persona-switcher-title"
tabIndex={-1}
className="relative w-full max-w-md glass-strong rounded-2xl shadow-2xl p-5 focus:outline-none"
onClick={e => e.stopPropagation()}
>
<div className="flex items-center justify-between mb-4">
<h2 id="persona-switcher-title" className="text-sm font-display font-semibold text-foreground">Switch Agent</h2>
{/* Tabs */}
<div className="flex items-center gap-0.5 bg-secondary/30 rounded-lg p-0.5">
<button
onClick={() => setTab('agents')}
className={`px-2.5 py-1 text-[11px] font-medium rounded-md transition-colors ${
tab === 'agents' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'
}`}
>
<Bot className="w-3 h-3 inline mr-1" />Agents
</button>
{(groups.length > 0 || onSelectGroup) && (
<button
onClick={() => setTab('groups')}
className={`px-2.5 py-1 text-[11px] font-medium rounded-md transition-colors ${
tab === 'groups' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'
}`}
>
<Users className="w-3 h-3 inline mr-1" />Groups
</button>
)}
</div>
</div>
{loading ? (
<div className="flex items-center justify-center py-10">
<Loader2 className="w-5 h-5 animate-spin text-honey" />
</div>
) : tab === 'agents' ? (
<PersonaAgentsList
personas={personas}
currentTemplateId={currentTemplateId}
showAllSpecialists={showAllSpecialists}
onToggleShowAll={() => setShowAllSpecialists(v => !v)}
renderPersonaCard={renderPersonaCard}
/>
) : (
<div className="space-y-2 max-h-[320px] overflow-y-auto scrollbar-thin">
{groups.length === 0 ? (
<p className="text-xs text-muted-foreground text-center py-8">
No agent groups created yet. Create one in the Agents app.
</p>
) : groups.map(g => (
<button
key={g.id}
onClick={() => { onSelectGroup?.(g.id); onClose(); }}
className={`w-full flex items-center gap-3 p-3 rounded-xl transition-colors text-left ${
currentGroupId === g.id
? 'bg-primary/20 border border-primary/50'
: 'bg-secondary/30 border border-transparent hover:bg-secondary/50'
}`}
>
<div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center shrink-0">
<Users className="w-5 h-5 text-honey" />
</div>
<div className="min-w-0 flex-1">
<p className="text-xs font-display font-medium text-foreground truncate">{g.name}</p>
<div className="flex items-center gap-1.5 mt-0.5">
<span className="text-[11px] px-1.5 py-0.5 rounded-full bg-primary/10 text-honey capitalize">{g.strategy}</span>
<span className="text-[11px] text-muted-foreground">{g.members.length} agents</span>
</div>
{g.description && <p className="text-[11px] text-muted-foreground truncate mt-0.5">{g.description}</p>}
</div>
</button>
))}
</div>
)}
<p className="text-[11px] text-muted-foreground mt-3 text-center">⌘⇧P to toggle</p>
</motion.div>
</motion.div>
</AnimatePresence>
);
};
export default PersonaSwitcher;

View File

@@ -0,0 +1,37 @@
/**
* RecallCard — the shared "I remember …" recall card (Lane H item 4).
*
* ONE card component consumed by BOTH the home hero recall strip and the
* ≥7-day "Catching you up" modal, so the product's signature memory moment
* looks and reads identically wherever it lands. Presentational only — each
* surface wraps it in its own motion entrance (STAGGER.brief), so the card is
* shared without coupling the two entrance choreographies.
*/
import { Sparkles } from 'lucide-react';
import type { MemoryHighlight } from '@/lib/briefing-source';
interface RecallCardProps {
highlight: MemoryHighlight;
/** Relative-time label (e.g. "yesterday") — the surface owns the formatter. */
timeLabel?: string;
}
export function RecallCard({ highlight, timeLabel }: RecallCardProps) {
return (
<div className="flex items-start gap-2 rounded-lg border border-[var(--honey-line)] bg-[var(--honey-wash)] px-3 py-1.5">
<Sparkles className="mt-0.5 h-3 w-3 shrink-0 text-honey/60" aria-hidden />
<div className="min-w-0">
<p className="text-[12px] leading-relaxed text-foreground">{highlight.content}</p>
{/* R21 (a11y/design): the 10px timestamp on the honey-wash card read
borderline on cream — --text-tertiary is the quiet-but-AA tier
(~4.7:1 light / 5.0:1 dark on the tinted surface). */}
{(highlight.workspace || timeLabel) && (
<p className="mt-0.5 text-[10px] text-[var(--text-tertiary)]">
{highlight.workspace && <span>{highlight.workspace} · </span>}
{timeLabel}
</p>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,218 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { SpawnAgentResult } from '@/lib/adapter';
import type { Workspace } from '@/lib/types';
const mocks = vi.hoisted(() => ({
adapter: {
getModels: vi.fn(),
getModelPricing: vi.fn(),
getProviders: vi.fn(),
getModel: vi.fn(),
createWorkspace: vi.fn(),
spawnAgent: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: {} }));
vi.mock('@/lib/personas', () => ({
PERSONAS: [
{ id: 'general-purpose', name: 'General Purpose', avatar: 'data:image/gif;base64,R0lGODlhAQABAAAAACw=' },
{ id: 'researcher', name: 'Researcher', avatar: 'data:image/gif;base64,R0lGODlhAQABAAAAACw=' },
],
}));
import SpawnAgentDialog from './SpawnAgentDialog';
const workspace: Workspace = {
id: 'w1',
name: 'Launch Room',
group: 'Personal',
status: 'active',
};
const spawned: SpawnAgentResult = {
id: 'run-1',
runId: 'run-1',
roomId: 'room-1',
workspaceId: workspace.id,
sessionId: 'spawn-run-1',
status: 'queued',
statusUrl: '/api/agent-runs/run-1',
resumable: false,
task: 'Map adoption risks',
persona: 'researcher',
model: 'anthropic/claude-3-5-sonnet',
};
function renderDialog({
onClose = () => {},
onSpawned,
workspaces = [workspace],
activeWorkspaceId = workspace.id,
}: {
onClose?: () => void;
onSpawned?: (result: SpawnAgentResult) => void;
workspaces?: Workspace[];
activeWorkspaceId?: string;
} = {}) {
return render(
<TooltipProvider>
<SpawnAgentDialog
open
onClose={onClose}
onSpawned={onSpawned}
workspaces={workspaces}
activeWorkspaceId={activeWorkspaceId}
/>
</TooltipProvider>,
);
}
beforeEach(() => {
mocks.adapter.getModels.mockResolvedValue(['anthropic/claude-3-5-sonnet']);
mocks.adapter.getModelPricing.mockResolvedValue([]);
mocks.adapter.getProviders.mockResolvedValue({
providers: [
{
id: 'anthropic',
name: 'Anthropic',
hasKey: true,
models: [{ id: 'anthropic/claude-3-5-sonnet', name: 'Claude 3.5 Sonnet' }],
},
],
search: [],
activeSearch: 'duckduckgo',
});
mocks.adapter.getModel.mockResolvedValue('anthropic/claude-3-5-sonnet');
mocks.adapter.spawnAgent.mockResolvedValue(spawned);
});
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
describe('SpawnAgentDialog media stability', () => {
it('keeps persona avatars intrinsically sized in the picker and launch review', async () => {
renderDialog();
const workspaceButton = await screen.findByRole('button', { name: 'Launch Room' });
expect(workspaceButton.className).not.toContain('transition-all');
expect(workspaceButton.className).toContain('transition-colors');
fireEvent.click(await screen.findByRole('button', { name: 'Persona override' }));
const personaButton = await screen.findByRole('button', { name: /General Purpose/i });
expect(personaButton.className).not.toContain('transition-all');
expect(personaButton.className).toContain('transition-colors');
const pickerAvatar = personaButton.querySelector('img');
expect(pickerAvatar).toHaveAttribute('width', '32');
expect(pickerAvatar).toHaveAttribute('height', '32');
fireEvent.click(personaButton);
fireEvent.change(screen.getByLabelText('Task'), {
target: { value: 'Map adoption risks' },
});
fireEvent.click(screen.getByRole('button', { name: 'Review & Launch' }));
await waitFor(() => expect(screen.getByText('Confirm Launch')).toBeInTheDocument());
const reviewAvatar = screen.getByText('General Purpose').closest('div')?.querySelector('img');
expect(reviewAvatar).toHaveAttribute('width', '24');
expect(reviewAvatar).toHaveAttribute('height', '24');
});
});
describe('SpawnAgentDialog form metadata', () => {
it('labels and names the custom workspace and task controls', async () => {
renderDialog();
await waitFor(() => expect(screen.queryByTestId('spawn-models-loading')).not.toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: '+ New' }));
const workspaceName = screen.getByRole('textbox', { name: /new workspace name/i });
expect(workspaceName).toHaveAttribute('name', 'spawnWorkspaceName');
expect(workspaceName).toHaveAttribute('autocomplete', 'off');
const task = screen.getByRole('textbox', { name: 'Task' });
expect(task).toHaveAttribute('name', 'spawnTask');
expect(task).toHaveAttribute('autocomplete', 'off');
});
});
describe('SpawnAgentDialog durable launch', () => {
it('preserves the selected task, persona, model, and workspace and returns canonical Room identity', async () => {
const onClose = vi.fn();
const onSpawned = vi.fn();
renderDialog({ onClose, onSpawned });
await waitFor(() => expect(screen.queryByTestId('spawn-models-loading')).not.toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: 'Persona override' }));
fireEvent.click(screen.getByRole('button', { name: /Researcher/i }));
fireEvent.change(screen.getByRole('textbox', { name: 'Task' }), {
target: { value: 'Map adoption risks' },
});
fireEvent.click(screen.getByRole('button', { name: 'Review & Launch' }));
fireEvent.click(await screen.findByRole('button', { name: 'Confirm & Launch' }));
await waitFor(() => expect(mocks.adapter.spawnAgent).toHaveBeenCalledWith({
task: 'Map adoption risks',
persona: 'researcher',
model: 'anthropic/claude-3-5-sonnet',
parentWorkspaceId: workspace.id,
}));
expect(onClose).toHaveBeenCalledOnce();
expect(onSpawned).toHaveBeenCalledWith(spawned);
});
it('populates models from keyed provider catalogs when getModels rejects', async () => {
mocks.adapter.getModels.mockRejectedValueOnce(new Error('LiteLLM models request timed out'));
mocks.adapter.getModel.mockResolvedValueOnce('unconfigured/runtime-model');
renderDialog();
const modelList = await screen.findByTestId('spawn-models-list');
expect(modelList).toContainElement(screen.getByTitle('anthropic/claude-3-5-sonnet'));
});
it('blocks launch and explains how to configure a model when no provider is ready', async () => {
mocks.adapter.getModels.mockResolvedValue([]);
mocks.adapter.getModel.mockResolvedValue('anthropic/claude-3-5-sonnet');
mocks.adapter.getProviders.mockResolvedValue({ providers: [], search: [], activeSearch: '' });
renderDialog();
await screen.findByTestId('spawn-no-keys-cta');
fireEvent.change(screen.getByRole('textbox', { name: 'Task' }), {
target: { value: 'Try to launch' },
});
expect(screen.getByText(/Settings → Vault/)).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Review & Launch' })).toBeDisabled();
});
it('blocks launch when the selected workspace no longer exists', async () => {
renderDialog({ workspaces: [], activeWorkspaceId: undefined });
await waitFor(() => expect(screen.queryByTestId('spawn-models-loading')).not.toBeInTheDocument());
fireEvent.change(screen.getByRole('textbox', { name: 'Task' }), {
target: { value: 'Try to launch' },
});
expect(screen.getByText(/No workspaces/)).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Review & Launch' })).toBeDisabled();
});
it('keeps a backend readiness failure visible in the dialog', async () => {
mocks.adapter.spawnAgent.mockRejectedValueOnce(new Error('No executable model is configured'));
renderDialog();
await waitFor(() => expect(screen.queryByTestId('spawn-models-loading')).not.toBeInTheDocument());
fireEvent.change(screen.getByRole('textbox', { name: 'Task' }), {
target: { value: 'Map adoption risks' },
});
fireEvent.click(screen.getByRole('button', { name: 'Review & Launch' }));
fireEvent.click(await screen.findByRole('button', { name: 'Confirm & Launch' }));
expect(await screen.findByRole('alert')).toHaveTextContent('No executable model is configured');
});
});

View File

@@ -0,0 +1,501 @@
import { useState, useEffect, useCallback } from 'react';
import { Rocket, RefreshCw, ChevronDown, ChevronRight, ArrowLeft, Zap, Key } from 'lucide-react';
import { adapter, type SpawnAgentResult } from '@/lib/adapter';
import { PERSONAS } from '@/lib/personas';
import { countProvidersWithKeys, selectDefaultModel } from '@/lib/spawn-agent-helpers';
import { useToast } from '@/hooks/use-toast';
import type { Workspace, ModelPricing } from '@/lib/types';
import type { Provider } from '@/hooks/useProviders';
import { formatModelLabel } from '@/lib/model-label';
import {
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
interface SpawnAgentDialogProps {
open: boolean;
onClose: () => void;
workspaces: Workspace[];
activeWorkspaceId?: string;
onWorkspaceCreated?: (ws: Workspace) => void;
onSpawned?: (result: SpawnAgentResult) => void;
}
const SpawnAgentDialog = ({ open, onClose, workspaces, activeWorkspaceId, onWorkspaceCreated, onSpawned }: SpawnAgentDialogProps) => {
const { toast } = useToast();
const [spawning, setSpawning] = useState(false);
const [step, setStep] = useState<'config' | 'confirm'>('config');
const [models, setModels] = useState<string[]>([]);
const [loadingModels, setLoadingModels] = useState(false);
const [modelsError, setModelsError] = useState<string | null>(null);
const [spawnError, setSpawnError] = useState<string | null>(null);
/** How many providers have a vault key configured — drives the empty-state copy. */
const [providersWithKeys, setProvidersWithKeys] = useState<number | null>(null);
// W2C: keep the fetched provider catalog so raw router ids render as friendly names.
const [providerList, setProviderList] = useState<Provider[]>([]);
const [pricing, setPricing] = useState<ModelPricing[]>([]);
const [showPersona, setShowPersona] = useState(false);
const [form, setForm] = useState({
task: '',
persona: '',
model: '',
workspaceMode: 'existing' as 'existing' | 'new',
workspaceId: '',
newWorkspaceName: '',
});
// Fetch models + providers. Models alone don't tell us why the list might
// be empty — we also need the provider list to know whether the user has
// any keys configured, so the empty-state copy can be actionable rather
// than "check backend config".
const fetchModels = useCallback(async () => {
setLoadingModels(true);
setModelsError(null);
const activeWs = workspaces.find(w => w.id === activeWorkspaceId);
const wsModel = activeWs?.model;
try {
const [m, p, providers] = await Promise.all([
// Tier-1 rejection must fall through to tiers 2/3 (live CPU-saturation timeout, 2026-07-16).
adapter.getModels().catch(() => [] as string[]),
adapter.getModelPricing().catch(() => [] as ModelPricing[]),
adapter.getProviders().catch(() => ({ providers: [], search: [], activeSearch: '' } as Awaited<ReturnType<typeof adapter.getProviders>>)),
]);
// /api/litellm/models is empty when LiteLLM is unreachable. Chat handles
// this with a hardcoded FALLBACK_MODELS list, but those identifiers
// (provider/model with dots) don't match the runtime model IDs the
// backend actually accepts. Fall back to the runtime active model so
// Spawn Agent always offers at least one valid option when the
// built-in Anthropic proxy is the active provider.
let modelList = m;
if (modelList.length === 0) {
try {
const active = await adapter.getModel();
const activeProviderReady = providers.providers.some((provider) => provider.hasKey && (
active.startsWith(`${provider.id}/`)
|| (provider.models ?? []).some((candidate) => (
candidate.id === active || candidate.id.endsWith(`/${active}`)
))
));
if (active && activeProviderReady) modelList = [active];
} catch (err) {
console.error('[SpawnAgentDialog] runtime-model fallback failed:', err);
}
}
// P35 fix — third-tier fallback: when LiteLLM is unreachable AND
// no runtime model is set, use the live provider catalogs returned by
// /api/providers. This keeps the spawn picker aligned with the same
// provider API inventory used by Settings and onboarding.
if (modelList.length === 0 && providers.providers.length > 0) {
const fromProviders = providers.providers
.filter((p) => p.hasKey)
.flatMap((p) => (p.models ?? []).map((mm) => mm.id))
.filter((id): id is string => typeof id === 'string' && id.length > 0);
const deduped = Array.from(new Set(fromProviders));
if (deduped.length > 0) modelList = deduped;
}
if (modelList.length === 0 && providers.providers.some((p) => p.hasKey)) {
setModelsError('Model list unavailable right now — retry, or check provider keys in Settings.');
}
setModels(modelList);
setPricing(p);
setProvidersWithKeys(countProvidersWithKeys(providers.providers));
setProviderList(providers.providers as Provider[]);
const defaultModel = selectDefaultModel(wsModel, modelList);
setForm(f => ({ ...f, model: modelList.includes(f.model) ? f.model : defaultModel }));
} catch (err) {
setModelsError(err instanceof Error ? err.message : 'Failed to fetch models');
} finally {
setLoadingModels(false);
}
}, [activeWorkspaceId, workspaces]);
useEffect(() => {
if (!open) return;
setSpawnError(null);
if (activeWorkspaceId) {
setForm(f => ({ ...f, workspaceId: f.workspaceId || activeWorkspaceId }));
}
void fetchModels();
}, [open, activeWorkspaceId, fetchModels]);
const selectedWorkspaceExists = form.workspaceMode === 'new'
? Boolean(form.newWorkspaceName.trim())
: workspaces.some(ws => ws.id === form.workspaceId && ws.status !== 'archived');
const selectedModelReady = !loadingModels
&& modelsError === null
&& Boolean(form.model)
&& models.includes(form.model);
const canSubmit = Boolean(form.task.trim() && selectedWorkspaceExists && selectedModelReady);
const handleSpawn = async () => {
setSpawnError(null);
if (!form.task.trim()) {
setSpawnError('Describe the task before launching the agent.');
setStep('config');
return;
}
if (!selectedWorkspaceExists) {
setSpawnError('Choose an existing workspace or create a new one.');
setStep('config');
return;
}
if (!selectedModelReady) {
setSpawnError('Choose an available model. Refresh models or configure a provider in Settings.');
setStep('config');
return;
}
setSpawning(true);
try {
let targetWorkspaceId = form.workspaceId;
// Create new workspace if needed
if (form.workspaceMode === 'new' && form.newWorkspaceName.trim()) {
const ws = await adapter.createWorkspace({
name: form.newWorkspaceName.trim(),
group: 'spawned',
persona: form.persona || undefined,
});
targetWorkspaceId = ws.id;
onWorkspaceCreated?.(ws);
}
const result = await adapter.spawnAgent({
task: form.task.trim(),
persona: form.persona || undefined,
model: form.model,
parentWorkspaceId: targetWorkspaceId || undefined,
});
toast({
title: 'Agent running',
description: `Opening Room · ${formatModelLabel(result.model, providerList)} · run ${result.runId.slice(0, 8)}`,
});
onClose();
setStep('config');
setForm({ task: '', persona: '', model: models[0] || '', workspaceMode: 'existing', workspaceId: activeWorkspaceId || '', newWorkspaceName: '' });
onSpawned?.(result);
} catch (err) {
// FR #15 Phase A: previously caught silently — backend errors now
// surface to the user so a half-broken spawn is visible immediately.
const message = err instanceof Error ? err.message : 'Failed to spawn agent';
setSpawnError(message);
console.error('[SpawnAgentDialog] spawn failed:', err);
toast({
title: 'Spawn failed',
description: message,
variant: 'destructive',
});
}
finally { setSpawning(false); }
};
const targetWorkspaceName = form.workspaceMode === 'existing'
? workspaces.find(w => w.id === form.workspaceId)?.name || 'Unknown'
: form.newWorkspaceName.trim();
const selectedPersona = PERSONAS.find(p => p.id === form.persona);
return (
<Dialog open={open} onOpenChange={(v) => { if (!v) { setStep('config'); onClose(); } }}>
<DialogContent className="sm:max-w-md bg-background border-border" data-testid="spawn-agent-dialog">
<DialogHeader>
<DialogTitle className="flex items-center gap-2 text-foreground">
<Rocket className="w-5 h-5 text-honey" />
{step === 'config' ? 'New Agent' : 'Confirm Launch'}
</DialogTitle>
<DialogDescription>
{step === 'config'
? 'Configure and launch a sub-agent to handle a task autonomously.'
: 'Review the details below before launching.'}
</DialogDescription>
</DialogHeader>
{spawnError && (
<div role="alert" className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive">
{spawnError}
</div>
)}
{step === 'config' ? (
<>
<div className="space-y-4 py-2 max-h-[60vh] overflow-y-auto">
{/* Workspace */}
<div className="space-y-2">
<Label className="text-foreground">Workspace</Label>
<div className="flex gap-1 p-0.5 rounded-lg bg-muted/50 w-fit">
{(['existing', 'new'] as const).map(mode => (
<button
key={mode}
type="button"
onClick={() => setForm(f => ({ ...f, workspaceMode: mode }))}
className={`px-3 py-1.5 text-xs rounded-md font-display transition-colors capitalize ${
form.workspaceMode === mode
? 'bg-primary text-primary-foreground'
: 'text-muted-foreground hover:text-foreground'
}`}
>
{mode === 'existing' ? 'Existing' : '+ New'}
</button>
))}
</div>
{form.workspaceMode === 'existing' ? (
<div className="grid grid-cols-2 gap-1.5 max-h-28 overflow-y-auto">
{workspaces.map(ws => (
<button
key={ws.id}
type="button"
onClick={() => setForm(f => ({ ...f, workspaceId: ws.id }))}
className={`px-2.5 py-1.5 text-xs rounded-lg border text-left transition-colors truncate ${
form.workspaceId === ws.id
? 'border-primary bg-primary/10 text-honey ring-1 ring-primary/30'
: 'border-border/30 bg-secondary/20 text-muted-foreground hover:text-foreground hover:bg-secondary/40'
}`}
>
{ws.name}
</button>
))}
{workspaces.length === 0 && (
<p className="col-span-2 text-xs text-muted-foreground py-2 text-center">No workspaces — create a new one</p>
)}
{workspaces.length > 0 && !selectedWorkspaceExists && (
<p className="col-span-2 text-xs text-destructive py-1">Choose an available workspace.</p>
)}
</div>
) : (
<>
<Label htmlFor="spawn-workspace-name" className="sr-only">New workspace name</Label>
<Input
id="spawn-workspace-name"
name="spawnWorkspaceName"
autoComplete="off"
placeholder="New workspace name..."
value={form.newWorkspaceName}
onChange={e => setForm(f => ({ ...f, newWorkspaceName: e.target.value }))}
className="bg-secondary/30 border-border/50 text-foreground placeholder:text-muted-foreground"
/>
</>
)}
</div>
{/* Task */}
<div className="space-y-2">
<Label htmlFor="spawn-task" className="text-foreground">Task</Label>
<Textarea
id="spawn-task"
name="spawnTask"
autoComplete="off"
placeholder="Describe what this agent should do..."
value={form.task}
onChange={e => setForm(f => ({ ...f, task: e.target.value }))}
className="min-h-[80px] bg-secondary/30 border-border/50 text-foreground placeholder:text-muted-foreground"
/>
</div>
{/* Persona (collapsible override) */}
<div className="space-y-2">
<button
type="button"
onClick={() => setShowPersona(v => !v)}
className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
{showPersona ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}
<span>Persona override</span>
{form.persona && (
<span className="text-[11px] text-honey ml-1">({PERSONAS.find(p => p.id === form.persona)?.name})</span>
)}
</button>
{showPersona && (
<div className="grid grid-cols-4 gap-1.5">
{PERSONAS.map(p => (
<button
key={p.id}
type="button"
onClick={() => setForm(f => ({ ...f, persona: f.persona === p.id ? '' : p.id }))}
className={`flex flex-col items-center gap-1 p-2 rounded-lg border text-center transition-colors ${
form.persona === p.id
? 'border-primary bg-primary/10 ring-1 ring-primary/30'
: 'border-border/30 bg-secondary/20 hover:bg-secondary/40'
}`}
>
<img src={p.avatar} alt={p.name} width={32} height={32} className="w-8 h-8 rounded-full object-cover" />
<span className="text-[11px] text-foreground font-medium leading-tight truncate w-full">{p.name}</span>
</button>
))}
</div>
)}
</div>
{/* Model */}
<div className="space-y-2">
<div className="flex items-center gap-2">
<Label className="text-foreground">Model</Label>
{workspaces.find(w => w.id === activeWorkspaceId)?.model && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<span className="text-[11px] text-muted-foreground cursor-help border-b border-dotted border-muted-foreground/50">
inherited from {workspaces.find(w => w.id === activeWorkspaceId)?.name}
</span>
</TooltipTrigger>
<TooltipContent side="top" className="max-w-[200px] text-xs">
Changing the model here only affects this spawned agent, not the parent workspace.
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</div>
{loadingModels ? (
<p className="text-xs text-muted-foreground" data-testid="spawn-models-loading">Loading models…</p>
) : modelsError ? (
<div className="flex items-center gap-2" data-testid="spawn-models-error">
<p className="text-xs text-destructive flex-1">Failed to load models: {modelsError}</p>
<Button size="sm" variant="ghost" onClick={() => void fetchModels()} className="h-7 px-2 gap-1">
<RefreshCw className="w-3 h-3" /> Retry
</Button>
</div>
) : models.length === 0 ? (
providersWithKeys === 0 ? (
<div className="flex items-start gap-2 p-3 rounded-lg bg-amber-500/5 border border-amber-500/20" data-testid="spawn-no-keys-cta">
<Key className="w-4 h-4 text-amber-400 mt-0.5 shrink-0" />
<div className="flex-1">
<p className="text-xs text-foreground font-medium">No API keys configured</p>
<p className="text-[11px] text-muted-foreground mt-0.5">Add a provider key in Settings → Vault, or install Ollama for free local models.</p>
</div>
<Button size="sm" variant="ghost" onClick={() => void fetchModels()} className="h-7 px-2 gap-1 shrink-0">
<RefreshCw className="w-3 h-3" />
</Button>
</div>
) : (
<div className="flex items-center gap-2" data-testid="spawn-no-models-cta">
<p className="text-xs text-muted-foreground flex-1">Keys configured but no models returned — the LiteLLM proxy may not be running.</p>
<Button size="sm" variant="ghost" onClick={() => void fetchModels()} className="h-7 px-2 gap-1">
<RefreshCw className="w-3 h-3" /> Retry
</Button>
</div>
)
) : (
<div className="flex flex-wrap gap-1.5" data-testid="spawn-models-list">
{models.map(m => (
<button
key={m}
type="button"
title={m}
onClick={() => setForm(f => ({ ...f, model: m }))}
className={`px-2.5 py-1 text-xs rounded-md border transition-colors ${
form.model === m
? 'border-primary bg-primary/10 text-honey'
: 'border-border/30 bg-secondary/20 text-muted-foreground hover:text-foreground'
}`}
>
{formatModelLabel(m, providerList)}
</button>
))}
</div>
)}
</div>
</div>
<DialogFooter>
<Button variant="ghost" size="sm" onClick={onClose}>Cancel</Button>
<Button
size="sm"
disabled={!canSubmit}
onClick={() => { setSpawnError(null); setStep('confirm'); }}
className="gap-1.5"
>
Review & Launch
</Button>
</DialogFooter>
</>
) : (
<>
<div className="space-y-3 py-2">
<div className="rounded-xl bg-secondary/30 border border-border/30 p-4 space-y-3">
<div>
<p className="text-[11px] uppercase tracking-wider text-muted-foreground mb-1">Workspace</p>
<p className="text-sm text-foreground font-display">
{form.workspaceMode === 'new' ? `${targetWorkspaceName} (new)` : targetWorkspaceName}
</p>
</div>
<div>
<p className="text-[11px] uppercase tracking-wider text-muted-foreground mb-1">Task</p>
<p className="text-sm text-foreground leading-relaxed">{form.task}</p>
</div>
<div>
<p className="text-[11px] uppercase tracking-wider text-muted-foreground mb-1">Model</p>
<p className="text-sm text-foreground" title={form.model}>{formatModelLabel(form.model, providerList)}</p>
</div>
{selectedPersona && (
<div>
<p className="text-[11px] uppercase tracking-wider text-muted-foreground mb-1">Persona</p>
<div className="flex items-center gap-2">
<img src={selectedPersona.avatar} alt={selectedPersona.name} width={24} height={24} className="w-6 h-6 rounded-full object-cover" />
<span className="text-sm text-foreground">{selectedPersona.name}</span>
</div>
</div>
)}
{/* Estimated cost */}
<div className="border-t border-border/20 pt-3 mt-3">
<p className="text-[11px] uppercase tracking-wider text-muted-foreground mb-1.5">Estimated Budget</p>
{(() => {
const mp = pricing.find(p => p.model === form.model);
if (!mp) {
return <p className="text-xs text-muted-foreground">Pricing unavailable for this model</p>;
}
const tokensMin = mp.estimatedTokens?.min ?? 4000;
const tokensMax = mp.estimatedTokens?.max ?? 16000;
const costMin = mp.estimatedCost?.min ?? (tokensMin / 1000 * mp.inputCostPer1k);
const costMax = mp.estimatedCost?.max ?? (tokensMax / 1000 * mp.outputCostPer1k);
return (
<>
<div className="flex items-center gap-4">
<div className="flex items-center gap-1.5">
<Zap className="w-3.5 h-3.5 text-amber-400" />
<span className="text-sm text-foreground font-mono">
~{(tokensMin / 1000).toFixed(0)}k–{(tokensMax / 1000).toFixed(0)}k tokens
</span>
</div>
<div className="text-[11px] text-muted-foreground">
≈ ${costMin.toFixed(2)}–${costMax.toFixed(2)}
</div>
</div>
<div className="flex gap-3 mt-1.5 text-[11px] text-muted-foreground/80">
<span>Input: ${mp.inputCostPer1k.toFixed(4)}/1k</span>
<span>Output: ${mp.outputCostPer1k.toFixed(4)}/1k</span>
</div>
</>
);
})()}
<p className="text-[11px] text-muted-foreground/60 mt-1">Estimates vary based on task complexity and tool usage</p>
</div>
</div>
</div>
<DialogFooter>
<Button variant="ghost" size="sm" onClick={() => setStep('config')} className="gap-1.5">
<ArrowLeft className="w-3.5 h-3.5" /> Back
</Button>
<Button
size="sm"
disabled={spawning || !canSubmit}
onClick={handleSpawn}
className="gap-1.5"
>
{spawning ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Rocket className="w-3.5 h-3.5" />}
{spawning ? 'Spawning…' : 'Confirm & Launch'}
</Button>
</DialogFooter>
</>
)}
</DialogContent>
</Dialog>
);
};
export default SpawnAgentDialog;

View File

@@ -0,0 +1,129 @@
import { motion, AnimatePresence } from 'framer-motion';
import { Crown, Users, Check, X, ArrowRight } from 'lucide-react';
import { useFocusTrap } from '@/hooks/useFocusTrap';
interface TrialExpiredModalProps {
open: boolean;
onDismiss: () => void;
onUpgrade: (tier: 'TEAMS') => void;
}
// Solo (free) keeps every personal capability — the trial only ever gated the
// collaboration/governance layer, so those are the only things "lost".
const KEEP_FEATURES = [
'Memory & Harvest — unlimited, forever',
'Unlimited workspaces & connectors',
'Marketplace skills & connectors',
'Self-evolving skills',
'All built-in agents',
'PDF & advanced exports',
];
const LOSE_FEATURES = [
'Shared team workspaces',
'Sync across devices',
'Team skill library',
'Team governance & audit',
'SSO & role-based access',
];
export default function TrialExpiredModal({ open, onDismiss, onUpgrade }: TrialExpiredModalProps) {
// A11y (WCAG 2.1.1/2.4.3): Escape closes, Tab is trapped, focus moves in on
// open and restores on close. Replaces the prior Escape-only handler.
const dialogRef = useFocusTrap<HTMLDivElement>(open, onDismiss);
return (
<AnimatePresence>
{open && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-[210] flex items-center justify-center"
>
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm" aria-hidden="true" />
<motion.div
ref={dialogRef}
initial={{ opacity: 0, scale: 0.95, y: 16 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95, y: 16 }}
transition={{ type: 'spring', damping: 25, stiffness: 300 }}
role="dialog"
aria-modal="true"
aria-labelledby="trial-expired-title"
tabIndex={-1}
className="relative w-full max-w-lg glass-strong rounded-2xl shadow-2xl overflow-hidden focus:outline-none"
onClick={e => e.stopPropagation()}
>
<button
type="button"
onClick={onDismiss}
aria-label="Close trial expired dialog"
className="absolute top-4 right-4 p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors"
>
<X className="w-4 h-4" />
</button>
<div className="p-6 pb-2 text-center">
<div className="inline-flex p-3 rounded-2xl bg-primary/10 mb-4">
<Crown className="w-8 h-8 text-honey" />
</div>
<h2 id="trial-expired-title" className="text-xl font-display font-bold text-foreground">
Your 15-day trial has ended
</h2>
<p className="text-sm text-muted-foreground mt-2">
Upgrade to Team to keep the collaboration features you've been using, or continue free with Solo.
</p>
</div>
<div className="px-6 py-4 grid grid-cols-2 gap-4">
<div>
<h3 className="text-xs font-display font-semibold text-[var(--text-2)] uppercase tracking-wider mb-2">
You keep
</h3>
<ul className="space-y-1.5">
{KEEP_FEATURES.map(f => (
<li key={f} className="flex items-start gap-2 text-[13px] text-foreground">
<Check className="w-3.5 h-3.5 text-[var(--healthy)] mt-0.5 shrink-0" />
{f}
</li>
))}
</ul>
</div>
<div>
<h3 className="text-xs font-display font-semibold text-[var(--text-2)] uppercase tracking-wider mb-2">
You lose
</h3>
<ul className="space-y-1.5">
{LOSE_FEATURES.map(f => (
<li key={f} className="flex items-start gap-2 text-[13px] text-muted-foreground">
<X className="w-3.5 h-3.5 text-[var(--risk)] mt-0.5 shrink-0" />
{f}
</li>
))}
</ul>
</div>
</div>
<div className="px-6 pb-6 pt-2 space-y-2">
<button
onClick={() => onUpgrade('TEAMS')}
className="w-full flex items-center justify-center gap-2 px-4 py-3 rounded-xl bg-primary text-primary-foreground font-display text-sm font-semibold hover:bg-primary/90 transition-colors"
>
<Users className="w-4 h-4" />
Upgrade to Team — $49/seat/mo
<ArrowRight className="w-4 h-4" />
</button>
<button
onClick={onDismiss}
className="w-full px-4 py-2 text-center text-xs text-muted-foreground hover:text-foreground transition-colors"
>
Continue free with Solo
</button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
);
}

View File

@@ -0,0 +1,170 @@
import { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Zap, X, Check, Users } from 'lucide-react';
import { TIER_CAPABILITIES } from '@waggle/shared';
import { useFocusTrap } from '@/hooks/useFocusTrap';
interface TierEvent {
required: string;
actual: string;
message: string;
}
type CapKey = keyof typeof TIER_CAPABILITIES.FREE;
// Trimmed to the caps that DIFFER between Solo (free) and Team — an honest
// "what Team adds" comparison, not a full feature dump (decision 11). Every
// personal capability is already free on Solo, so it doesn't belong here.
const FEATURE_ROWS: Array<{ label: string; key: CapKey; format: (v: unknown) => string }> = [
{ label: 'Shared Workspaces', key: 'sharedWorkspaces', format: v => v ? 'Yes' : '—' },
{ label: 'Team Members', key: 'teamMembersLimit', format: v => (v as number) === -1 ? 'Unlimited' : String(v) },
{ label: 'Sync Across Devices', key: 'cloudSync', format: v => v ? 'Yes' : '—' },
{ label: 'Team Skill Library', key: 'teamSkillLibrary', format: v => v ? 'Yes' : '—' },
{ label: 'Team Governance', key: 'adminPanel', format: v => v ? 'Yes' : '—' },
{ label: 'Audit Log', key: 'auditLog', format: v => {
if (v === 'none') return '—';
return String(v).charAt(0).toUpperCase() + String(v).slice(1);
}},
];
function CellValue({ value, isBool }: { value: string; isBool: boolean }) {
if (value === 'Yes' && isBool) return <Check className="w-4 h-4 text-honey mx-auto" />;
if (value === '—') return <span className="text-muted-foreground/40">—</span>;
return <span className="text-foreground">{value}</span>;
}
interface UpgradeModalProps {
onStartTrial?: () => void;
onUpgrade?: (tier: 'TEAMS') => void;
/** F5: report open/close so the shell can suppress coach-marks while this
* event-driven modal (invisible to AppShell otherwise) is up. */
onOpenChange?: (open: boolean) => void;
}
export default function UpgradeModal({ onStartTrial, onUpgrade, onOpenChange }: UpgradeModalProps) {
const [event, setEvent] = useState<TierEvent | null>(null);
const handleTierInsufficient = useCallback((e: Event) => {
setEvent((e as CustomEvent<TierEvent>).detail);
onOpenChange?.(true);
}, [onOpenChange]);
useEffect(() => {
window.addEventListener('waggle:tier-insufficient', handleTierInsufficient);
return () => window.removeEventListener('waggle:tier-insufficient', handleTierInsufficient);
}, [handleTierInsufficient]);
const close = useCallback(() => { setEvent(null); onOpenChange?.(false); }, [onOpenChange]);
// A11y (WCAG 2.1.1/2.4.3): Escape closes, Tab is trapped within the dialog,
// focus moves in on open and restores on close. Replaces the prior hand-rolled
// Escape-only handler (no trap, no focus restore).
const dialogRef = useFocusTrap<HTMLDivElement>(!!event, close);
const free = TIER_CAPABILITIES.FREE;
const teams = TIER_CAPABILITIES.TEAMS;
return (
<AnimatePresence>
{event && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-[200] flex items-center justify-center"
onClick={close}
>
<div className="absolute inset-0 bg-black/50 backdrop-blur-sm" aria-hidden="true" />
<motion.div
ref={dialogRef}
initial={{ opacity: 0, scale: 0.95, y: 10 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95, y: 10 }}
role="dialog"
aria-modal="true"
aria-labelledby="upgrade-modal-title"
tabIndex={-1}
className="relative w-full max-w-2xl glass-strong rounded-2xl shadow-2xl overflow-hidden focus:outline-none"
onClick={e => e.stopPropagation()}
>
<button
type="button"
onClick={close}
aria-label="Close upgrade dialog"
className="absolute top-4 right-4 p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors"
>
<X className="w-4 h-4" />
</button>
<div className="p-6 pb-4">
<div className="flex items-center gap-3 mb-1">
<div className="p-2 rounded-xl bg-primary/10">
<Zap className="w-5 h-5 text-honey" />
</div>
<h2 id="upgrade-modal-title" className="text-lg font-display font-bold text-foreground">
Upgrade to unlock this feature
</h2>
</div>
<p className="text-sm text-muted-foreground mt-2">
{event.message}
</p>
</div>
<div className="px-6 pb-4">
<div className="rounded-xl border border-border/50 overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border/50">
<th className="text-left p-3 text-muted-foreground font-medium">Feature</th>
<th className="text-center p-3 text-foreground font-medium w-28">Solo</th>
<th className="text-center p-3 font-medium w-28">
<span className="text-foreground flex items-center justify-center gap-1">
<Users className="w-3.5 h-3.5" /> Team
</span>
</th>
</tr>
</thead>
<tbody>
{FEATURE_ROWS.map(row => {
const freeVal = row.format(free[row.key]);
const teamsVal = row.format(teams[row.key]);
const isBool = typeof free[row.key] === 'boolean';
return (
<tr key={row.key} className="border-b border-border/30 last:border-0">
<td className="p-3 text-foreground">{row.label}</td>
<td className="p-3 text-center text-muted-foreground"><CellValue value={freeVal} isBool={isBool} /></td>
<td className="p-3 text-center"><CellValue value={teamsVal} isBool={isBool} /></td>
</tr>
);
})}
{/* Memory row — always free, hardcoded as marketing highlight */}
<tr className="border-b border-border/30 last:border-0">
<td className="p-3 text-foreground">Memory & Harvest</td>
<td className="p-3 text-center text-muted-foreground">Unlimited</td>
<td className="p-3 text-center"><span className="text-foreground">Unlimited</span></td>
</tr>
</tbody>
</table>
</div>
</div>
<div className="px-6 pb-6 flex items-center gap-3">
<button
onClick={() => { onStartTrial?.(); close(); }}
className="flex-1 px-4 py-2.5 rounded-xl border border-primary/30 text-honey font-display text-sm font-semibold hover:bg-primary/10 transition-colors"
>
Start 15-day Team trial
</button>
<button
onClick={() => { onUpgrade?.('TEAMS'); close(); }}
className="flex-1 px-4 py-2.5 rounded-xl bg-primary text-primary-foreground font-display text-sm font-semibold hover:bg-primary/90 transition-colors"
>
Upgrade to Team — $49/seat
</button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
);
}

View File

@@ -0,0 +1,229 @@
import { useState } from 'react';
import { Brain, ChevronRight, Plus, Archive, Check } from 'lucide-react';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { getPersonaById } from '@/lib/personas';
import { useFocusTrap } from '@/hooks/useFocusTrap';
import type { Workspace } from '@/lib/types';
import { motion, AnimatePresence } from 'framer-motion';
import WorkspaceActionsMenu from '../WorkspaceActionsMenu';
import { isDevNoiseWorkspace, compareWorkspaceRecency, workspaceCounts } from '@/lib/workspace-counts';
interface WorkspaceSwitcherProps {
open: boolean;
onClose: () => void;
workspaces: Workspace[];
activeWorkspaceId: string | null;
onSelect: (id: string) => void;
/** G1 (UX-Northstar 2026-06-13): create from the switcher itself. */
onCreateNew?: () => void;
/** W2B: jump to the full workspace shelf when the switcher is capped. */
onViewAll?: () => void;
/** P1b D3: load failure — an errored empty list must not read as "No workspaces". */
error?: string | null;
onRetry?: () => void;
}
// W2B: cap the un-searchable switcher list so the ~55-row store doesn't flood a
// 256px scrollbox; the rest is one click away via "view all".
const MAX_SWITCHER_ROWS = 12;
/** Compact relative time — disambiguates same-named workspaces (issue 2b). */
function relativeTime(iso?: string): string | null {
if (!iso) return null;
const t = new Date(iso).getTime();
if (Number.isNaN(t)) return null;
const mins = Math.round((Date.now() - t) / 60_000);
if (mins < 1) return 'just now';
if (mins < 60) return `${mins}m ago`;
const hrs = Math.round(mins / 60);
if (hrs < 24) return `${hrs}h ago`;
const days = Math.round(hrs / 24);
if (days < 7) return `${days}d ago`;
return `${Math.round(days / 7)}w ago`;
}
function WorkspaceRow({ ws, isActive, isDuplicateName, onSelect }: {
ws: Workspace;
isActive: boolean;
/** True when another visible workspace shares this name — show a date subtitle. */
isDuplicateName: boolean;
onSelect: (id: string) => void;
}) {
const persona = ws.persona ? getPersonaById(ws.persona) : null;
// On a name collision, append last-active so two "Research Hub"s differ.
const rel = isDuplicateName ? relativeTime(ws.lastActive ?? ws.updatedAt) : null;
// Never render an empty subtitle row: prefer "group · rel", fall back to whichever exists.
const subtitle = rel ? (ws.group ? `${ws.group} · ${rel}` : rel) : (ws.group || null);
return (
<div
className={`group flex items-center gap-1 rounded-xl transition-colors ${
isActive
? 'bg-primary/20 border border-primary/50'
: 'bg-secondary/20 border border-transparent hover:bg-secondary/40'
}`}
>
<button
onClick={() => onSelect(ws.id)}
className="flex-1 min-w-0 flex items-center gap-3 p-2.5 text-left"
>
{persona ? (
<Avatar className="w-7 h-7 shrink-0">
<AvatarImage src={persona.avatar} />
<AvatarFallback className="text-[11px] bg-primary/20">{persona.name[0]}</AvatarFallback>
</Avatar>
) : (
<div className="w-7 h-7 rounded-full bg-muted flex items-center justify-center shrink-0">
<Brain className="w-3.5 h-3.5 text-muted-foreground" />
</div>
)}
<div className="flex-1 min-w-0">
<span className="text-xs font-display font-medium text-foreground truncate block">{ws.name}</span>
{subtitle && <span className="text-[11px] text-muted-foreground truncate block">{subtitle}</span>}
</div>
{isActive
? <Check className="w-3.5 h-3.5 text-honey shrink-0" aria-label="Current workspace" />
: <ChevronRight className="w-3.5 h-3.5 text-muted-foreground shrink-0" />}
</button>
<WorkspaceActionsMenu
workspace={{ id: ws.id, name: ws.name, status: ws.status }}
buttonClassName="mr-1.5 opacity-0 group-hover:opacity-100 focus:opacity-100"
/>
</div>
);
}
const WorkspaceSwitcher = ({ open, onClose, workspaces, activeWorkspaceId, onSelect, onCreateNew, onViewAll, error, onRetry }: WorkspaceSwitcherProps) => {
const [showArchived, setShowArchived] = useState(false);
// A11y (WCAG 2.1.1/2.4.3): Escape closes, Tab is trapped within the dialog,
// focus moves in on open and restores on close — the same shared hook the
// other modal overlays use. Replaces the prior Escape-only handler (which
// had no focus trap or restore, so keyboard users tabbed out into the shell).
const dialogRef = useFocusTrap<HTMLDivElement>(open, onClose);
if (!open) return null;
const visibleWorkspaces = workspaces.filter(
ws => ws.id === activeWorkspaceId || !isDevNoiseWorkspace(ws.name),
);
// W2B: recency-sorted (most recent first, missing timestamps last), then
// capped so the un-searchable list can't flood the scrollbox.
const activeListFull = visibleWorkspaces
.filter(ws => ws.status !== 'archived')
.sort(compareWorkspaceRecency);
const activeList = activeListFull.slice(0, MAX_SWITCHER_ROWS);
const hiddenCount = activeListFull.length - activeList.length;
const totalCount = workspaceCounts(workspaces).total;
const archivedList = visibleWorkspaces.filter(ws => ws.status === 'archived');
// Names shared by more than one visible workspace — those rows get a date
// subtitle so they're tellable apart (issue 2b).
const nameCounts = new Map<string, number>();
for (const ws of visibleWorkspaces) {
const k = ws.name.trim().toLowerCase();
nameCounts.set(k, (nameCounts.get(k) ?? 0) + 1);
}
const isDup = (ws: Workspace) => (nameCounts.get(ws.name.trim().toLowerCase()) ?? 0) > 1;
return (
<AnimatePresence>
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-[100] flex items-center justify-center"
onClick={onClose}
>
<div className="absolute inset-0 bg-black/50 backdrop-blur-sm" />
<motion.div
ref={dialogRef}
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
role="dialog"
aria-modal="true"
aria-labelledby="workspace-switcher-title"
tabIndex={-1}
className="relative w-full max-w-sm glass-strong rounded-2xl shadow-2xl p-5 focus:outline-none"
onClick={e => e.stopPropagation()}
>
<h2 id="workspace-switcher-title" className="text-sm font-display font-semibold text-foreground mb-1">Switch Workspace</h2>
<p className="text-[11px] text-muted-foreground mb-3">
One workspace per project or area — each remembers its own work.
</p>
<div className="space-y-1 max-h-64 overflow-auto">
{activeList.map(ws => (
<WorkspaceRow
key={ws.id}
ws={ws}
isActive={ws.id === activeWorkspaceId}
isDuplicateName={isDup(ws)}
onSelect={(id) => { onSelect(id); onClose(); }}
/>
))}
{hiddenCount > 0 && (
<button
onClick={() => { onViewAll?.(); onClose(); }}
data-testid="workspace-switcher-overflow"
className="w-full flex items-center justify-center gap-1.5 px-2.5 py-1.5 text-[11px] text-muted-foreground hover:text-foreground transition-colors"
>
Showing {activeList.length} of {totalCount} — view all
<ChevronRight className="w-3 h-3" />
</button>
)}
{visibleWorkspaces.length === 0 && (
error ? (
<div className="text-center py-4 space-y-2" data-testid="workspace-switcher-error">
<p className="text-xs text-muted-foreground">Couldn’t load workspaces — retrying when the connection is back.</p>
{onRetry && (
<button
onClick={onRetry}
className="px-3 py-1 text-xs rounded-lg bg-secondary/50 text-foreground hover:bg-secondary/70 transition-colors"
>
Retry now
</button>
)}
</div>
) : (
<p className="text-xs text-muted-foreground text-center py-4">No workspaces</p>
)
)}
{archivedList.length > 0 && (
<div className="pt-1">
<button
onClick={() => setShowArchived(v => !v)}
data-testid="workspace-switcher-archived-toggle"
className="w-full flex items-center gap-2 px-2.5 py-1.5 text-[11px] text-muted-foreground hover:text-foreground transition-colors"
>
<Archive className="w-3 h-3" />
Archived ({archivedList.length})
<ChevronRight className={`w-3 h-3 ml-auto transition-transform ${showArchived ? 'rotate-90' : ''}`} />
</button>
{showArchived && archivedList.map(ws => (
<WorkspaceRow
key={ws.id}
ws={ws}
isActive={ws.id === activeWorkspaceId}
isDuplicateName={isDup(ws)}
onSelect={(id) => { onSelect(id); onClose(); }}
/>
))}
</div>
)}
</div>
{onCreateNew && (
<button
onClick={() => { onCreateNew(); onClose(); }}
data-testid="workspace-switcher-create"
className="w-full flex items-center justify-center gap-2 mt-3 px-3 py-2 rounded-xl border border-dashed border-border text-xs text-muted-foreground hover:text-foreground hover:border-primary/50 transition-colors"
>
<Plus className="w-3.5 h-3.5" /> New workspace
</button>
)}
<p className="text-[11px] text-muted-foreground mt-3 text-center">Ctrl+Tab to toggle</p>
</motion.div>
</motion.div>
</AnimatePresence>
);
};
export default WorkspaceSwitcher;

View File

@@ -0,0 +1,44 @@
/** PR5 Phase C2 — the terminal First-task step (seed the first message, open the workspace). */
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
import FirstTaskStep from './FirstTaskStep';
const base = {
message: 'Do a thing',
onMessageChange: vi.fn(),
suggestions: ['Suggestion A', 'Suggestion B'],
onPickSuggestion: vi.fn(),
onLetsGo: vi.fn(),
createError: null,
};
afterEach(() => cleanup());
describe('FirstTaskStep', () => {
it('shows the seeded first message and edits it', () => {
const onMessageChange = vi.fn();
render(<FirstTaskStep {...base} onMessageChange={onMessageChange} />);
const ta = screen.getByLabelText(/first task/i);
expect(ta).toHaveValue('Do a thing');
expect(ta).toHaveAttribute('name', 'onboardingFirstTask');
expect(ta).toHaveAttribute('autocomplete', 'off');
fireEvent.change(ta, { target: { value: 'New task' } });
expect(onMessageChange).toHaveBeenCalledWith('New task');
});
it('picks a suggested prompt', () => {
const onPickSuggestion = vi.fn();
render(<FirstTaskStep {...base} onPickSuggestion={onPickSuggestion} />);
const suggestion = screen.getByRole('button', { name: /suggestion a/i });
expect(suggestion).toHaveClass('text-foreground/80');
fireEvent.click(suggestion);
expect(onPickSuggestion).toHaveBeenCalledWith('Suggestion A');
});
it('opens the workspace on "Let\'s go"', () => {
const onLetsGo = vi.fn();
render(<FirstTaskStep {...base} onLetsGo={onLetsGo} />);
fireEvent.click(screen.getByRole('button', { name: /let's go/i }));
expect(onLetsGo).toHaveBeenCalledTimes(1);
});
});

View File

@@ -0,0 +1,60 @@
import { motion } from 'framer-motion';
import { fadeSlide } from './constants';
import type { FirstTaskStepProps } from './types';
/**
* Onboarding terminal step (PR5) — end inside the work. The workspace already exists
* (created on the Template step); here the user gives the agent its first task, seeded
* with the chosen template's hint and a few suggested prompts. "Let's go" opens the
* workspace with that first message (an empty box falls back to a default greeting in
* the wizard, so this never dead-ends).
*/
const FirstTaskStep = ({ message, onMessageChange, suggestions, onPickSuggestion, onLetsGo, createError }: FirstTaskStepProps) => (
<motion.div key="step-first-task" {...fadeSlide}>
<div className="text-center mb-5">
<h2 className="text-2xl font-display font-bold text-foreground mb-2">What&apos;s first?</h2>
<p className="text-sm text-muted-foreground">
Your workspace is ready. Give your agent its first task — or pick a suggestion.
</p>
</div>
{createError && <p className="text-xs text-muted-foreground mb-3 text-center">{createError}</p>}
<textarea
name="onboardingFirstTask"
autoComplete="off"
value={message}
onChange={(e) => onMessageChange(e.target.value)}
rows={3}
placeholder="Ask your agent to do something…"
aria-label="First task"
className="w-full bg-muted/50 border border-border/50 rounded-lg px-3 py-2.5 text-sm text-foreground resize-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background mb-3"
/>
{suggestions.length > 0 && (
<div className="flex flex-wrap gap-2 mb-6">
{suggestions.map((s) => (
<button
key={s}
type="button"
onClick={() => onPickSuggestion(s)}
className="rounded-full border border-border bg-card px-3 py-1.5 text-left text-xs text-foreground/80 hover:text-foreground hover:border-primary/40 transition-colors focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
{s}
</button>
))}
</div>
)}
<div className="flex justify-end">
<button
onClick={onLetsGo}
className="inline-flex items-center gap-2 px-8 py-3 rounded-xl bg-primary text-primary-foreground font-display text-sm font-semibold hover:bg-primary/80 transition-colors glow-primary focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
🐝 Let&apos;s go!
</button>
</div>
</motion.div>
);
export default FirstTaskStep;

View File

@@ -0,0 +1,228 @@
import { motion } from 'framer-motion';
import { Brain, Upload, Loader2, Check, Zap, ExternalLink, Info } from 'lucide-react';
import { fadeSlide } from './constants';
import { ConfidenceBadge } from '@/components/ui/confidence-badge';
import { memoryKindLabel } from '@/lib/harvest-kind-map';
import type { ImportStepProps } from './types';
/**
* S15 / C33 — Memory Import. Surfaces the classified `items[]` from
* `POST /api/harvest/preview` (per-item `kind` + `confidence`, Phase 2B.3) so
* the user sees what is being imported, then commits ALL items as
* `status:'unreviewed'` server-side (C33 commit-all default). Review happens
* later in Memory → Needs review (the S16 surface), pointed to below — there is
* no per-item selection UI in this cut.
*
* Source tiles map to `UniversalAdapter`-supported sources. Per C34, tools
* without an export adapter (Hermes / Codex / Cursor) route to the generic
* "Other" upload tile rather than a dedicated tile, and the long tail lives in
* Memory → Harvest after setup.
*/
const SOURCE_TILES: ReadonlyArray<{
id: string;
name: string;
desc: string;
/** One-line how-to: where in the source product the export file comes from. */
hint: string;
glyph: string;
accent: string;
}> = [
{ id: 'chatgpt', name: 'ChatGPT', desc: 'OpenAI export (.json)', hint: 'In ChatGPT: Settings → Data controls → Export data. You\'ll get an email with the file.', glyph: '✦', accent: 'text-emerald-400 bg-emerald-500/10 ring-emerald-500/30' },
{ id: 'claude', name: 'Claude', desc: 'Anthropic export (.json)', hint: 'In Claude: Settings → Privacy → Export data.', glyph: '✧', accent: 'text-orange-400 bg-orange-500/10 ring-orange-500/30' },
{ id: 'gemini', name: 'Gemini', desc: 'Google Takeout (.json)', hint: 'Go to takeout.google.com, select Gemini, download.', glyph: '✦', accent: 'text-sky-400 bg-sky-500/10 ring-sky-500/30' },
{ id: 'perplexity', name: 'Perplexity', desc: 'Threads export', hint: 'In Perplexity: Settings → Account → Export.', glyph: '◆', accent: 'text-teal-400 bg-teal-500/10 ring-teal-500/30' },
// C34: Cursor / Codex / Hermes have no export adapter yet — fold them into
// the generic "Other" file picker rather than a dedicated tile.
{ id: 'unknown', name: 'Other', desc: 'Cursor, Codex, any text/JSON', hint: 'Any .txt, .md or .json conversation file works.', glyph: '·', accent: 'text-muted-foreground bg-muted/30 ring-border/40' },
];
const LARGE_AUTO_IMPORT_THRESHOLD = 1000;
const formatImportCount = (count: number): string => new Intl.NumberFormat('en-US').format(count);
const ImportStep = ({
importSource,
importItems,
importDone,
importing,
onFileImport,
onImportCommit,
claudeCodeDetected,
onClaudeCodeHarvest,
onContinue,
}: ImportStepProps) => {
const detectedItemCount = claudeCodeDetected?.itemCount ?? 0;
const detectedItemCountLabel = formatImportCount(detectedItemCount);
const largeDetectedHistory = detectedItemCount >= LARGE_AUTO_IMPORT_THRESHOLD;
return (
<motion.div key="step-memory-import" {...fadeSlide}>
<div className="text-center mb-6">
<Brain className="w-10 h-10 text-honey mx-auto mb-3" />
<h2 className="text-2xl font-display font-bold text-foreground mb-2">
Where do you use AI today?
</h2>
<p className="text-sm text-muted-foreground">
Bring your existing conversations — Waggle extracts decisions, preferences, and knowledge into your persistent memory.
</p>
</div>
{/* Claude Code auto-detect banner — only when the sidecar found local files. */}
{!importDone && claudeCodeDetected?.found && (
<div className={`mb-5 p-3 rounded-xl border ${largeDetectedHistory ? 'bg-honey/10 border-honey/30' : 'bg-primary/10 border-primary/30'}`}>
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
<div className="flex items-center gap-2 min-w-0">
<Zap className="w-4 h-4 text-honey shrink-0" />
<div className="min-w-0">
<p className="text-xs font-display font-medium text-foreground">Claude Code detected</p>
<p className="text-[11px] text-muted-foreground truncate" title={claudeCodeDetected.path}>
Found {detectedItemCountLabel} items from Claude Code
</p>
{largeDetectedHistory && (
<p className="text-[11px] text-muted-foreground/80 mt-1 max-w-md">
That is a lot of memory to absorb at setup. Review it after your workspace is ready,
or import now if you are ready to curate Needs review.
</p>
)}
</div>
</div>
{onClaudeCodeHarvest && (
largeDetectedHistory ? (
<div className="flex flex-col sm:flex-row gap-2 sm:items-center shrink-0">
<button
onClick={onContinue}
disabled={importing}
className="px-3 py-1.5 rounded-lg bg-primary text-primary-foreground text-xs font-display font-semibold hover:bg-primary/90 transition-colors disabled:opacity-50"
>
Review after setup
</button>
<button
onClick={onClaudeCodeHarvest}
disabled={importing}
aria-busy={importing}
className="px-3 py-1.5 rounded-lg border border-border/70 bg-background/40 text-xs font-display font-semibold text-foreground hover:bg-muted/60 transition-colors disabled:opacity-50"
>
{importing ? <Loader2 aria-label="Importing" className="w-3 h-3 animate-spin" /> : `Import ${detectedItemCountLabel} now`}
</button>
</div>
) : (
<button
onClick={onClaudeCodeHarvest}
disabled={importing}
aria-busy={importing}
className="px-3 py-1.5 rounded-lg bg-primary text-primary-foreground text-xs font-display font-semibold hover:bg-primary/90 transition-colors disabled:opacity-50 shrink-0"
>
{importing ? <Loader2 aria-label="Importing" className="w-3 h-3 animate-spin" /> : 'Import my history'}
</button>
)
)}
</div>
</div>
)}
{!importSource && !importDone && (
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2.5 mb-6">
{SOURCE_TILES.map((src) => (
<label
key={src.id}
className="glass-strong rounded-xl p-3.5 cursor-pointer hover:border-primary/40 focus-within:ring-2 focus-within:ring-primary transition-colors text-left group flex flex-col gap-1"
>
<span
aria-hidden="true"
className={`inline-flex items-center justify-center w-7 h-7 rounded-lg ring-1 mb-0.5 text-base font-bold ${src.accent}`}
>
{src.glyph}
</span>
<h3 className="text-xs font-display font-semibold text-foreground">{src.name}</h3>
<p className="text-[11px] text-muted-foreground">{src.desc}</p>
<p className="text-[10px] text-muted-foreground/70">{src.hint}</p>
<div className="flex items-center gap-1 text-[11px] text-honey group-hover:text-honey/80 mt-0.5">
<Upload className="w-3 h-3" /> Choose file
</div>
<input
type="file"
accept=".json,.txt,.md,.csv"
aria-label={`Import ${src.name} export file`}
className="sr-only"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) onFileImport(file, src.id);
}}
/>
</label>
))}
</div>
)}
{/* C33: surface the classified items (kind + confidence) before commit. The
commit lands every item as `status:'unreviewed'`; no per-item selection. */}
{importItems.length > 0 && !importDone && (
<div className="glass-strong rounded-xl p-4 mb-4">
<h3 className="text-sm font-display font-semibold text-foreground mb-2">
Preview — {importItems.length} {importItems.length === 1 ? 'item' : 'items'} found
</h3>
<div className="max-h-40 overflow-y-auto space-y-1.5 mb-3">
{importItems.slice(0, 10).map((item, i) => (
<div key={item.id ?? i} className="flex items-center gap-2 text-xs">
<span className="inline-flex items-center rounded-md bg-muted/60 px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground shrink-0">
{memoryKindLabel(item.kind)}
</span>
<span className="text-muted-foreground truncate flex-1 min-w-0">{item.title}</span>
<ConfidenceBadge value={item.confidence} compact className="shrink-0" />
</div>
))}
{importItems.length > 10 && (
<div className="text-xs text-muted-foreground/60">
…and {importItems.length - 10} more
</div>
)}
</div>
<button
onClick={onImportCommit}
disabled={importing}
aria-busy={importing}
className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-primary-foreground text-xs font-display font-semibold hover:bg-primary/80 disabled:opacity-50 transition-colors focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
{importing ? <Loader2 aria-hidden="true" className="w-3 h-3 animate-spin" /> : <Check aria-hidden="true" className="w-3 h-3" />}
Import {importItems.length} {importItems.length === 1 ? 'item' : 'items'}
</button>
{/* C33: review-later pointer. */}
<p className="flex items-start gap-1.5 text-[11px] text-muted-foreground/80 mt-2.5">
<Info className="w-3 h-3 mt-0.5 shrink-0" />
Everything imports as <span className="text-foreground/70">Needs review</span> — you can review,
edit, or remove these anytime in Memory → Needs review.
</p>
</div>
)}
{importDone && (
<div className="glass-strong rounded-xl p-4 mb-4 text-center">
<Check className="w-6 h-6 text-honey mx-auto mb-2" />
<p className="text-sm text-foreground font-display">Memories imported!</p>
<p className="text-[11px] text-muted-foreground mt-1">
Find them under Memory → Needs review to curate.
</p>
</div>
)}
{/* Long-tail pointer for sources without a primary tile. */}
{!importSource && !importDone && (
<div className="mb-4 text-center">
<p className="text-[11px] text-muted-foreground">
Have history elsewhere? <span className="text-foreground/70">Open Memory → Harvest after setup for 14+ more sources <ExternalLink className="w-2.5 h-2.5 inline-block ml-0.5" /></span>
</p>
</div>
)}
<div className="flex items-center justify-end gap-4">
<button
onClick={onContinue}
className="text-xs text-muted-foreground hover:text-foreground transition-colors rounded-md px-1 focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
{importDone ? 'Continue →' : 'Skip this step →'}
</button>
</div>
</motion.div>
);
};
export default ImportStep;

View File

@@ -0,0 +1,69 @@
/**
* PR5 Phase C — the onboarding hard model gate. Continue is disabled until a
* working model exists; "I'll do this later" is the single soft escape (→ Home).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
const mocks = vi.hoisted(() => ({ useHasWorkingModel: vi.fn() }));
vi.mock('@/hooks/useHasWorkingModel', () => ({ useHasWorkingModel: mocks.useHasWorkingModel }));
vi.mock('@/components/os/model-gate/ModelGate', () => ({ ModelGate: () => <div data-testid="model-gate" /> }));
import ModelGateStep from './ModelGateStep';
const state = (over: Record<string, unknown> = {}) => ({
hasWorkingModel: false, cloudReady: false, localReady: false, loading: false, refresh: vi.fn(), ...over,
});
const props = () => ({ onContinue: vi.fn(), onLater: vi.fn() });
beforeEach(() => mocks.useHasWorkingModel.mockReturnValue(state()));
afterEach(() => { cleanup(); vi.clearAllMocks(); });
describe('ModelGateStep — the hard model gate', () => {
it('embeds the shared ModelGate', () => {
render(<ModelGateStep {...props()} />);
expect(screen.getByTestId('model-gate')).toBeInTheDocument();
});
it('disables Continue until a working model exists', () => {
const p = props();
render(<ModelGateStep {...p} />);
const cont = screen.getByRole('button', { name: /continue/i });
expect(cont).toBeDisabled();
fireEvent.click(cont);
expect(p.onContinue).not.toHaveBeenCalled();
});
it('enables Continue and advances once a model is working', () => {
mocks.useHasWorkingModel.mockReturnValue(state({ hasWorkingModel: true }));
const p = props();
render(<ModelGateStep {...p} />);
const cont = screen.getByRole('button', { name: /continue/i });
expect(cont).toBeEnabled();
fireEvent.click(cont);
expect(p.onContinue).toHaveBeenCalledTimes(1);
});
it('shows a local-ready state while keeping the setup gate available for another provider', () => {
mocks.useHasWorkingModel.mockReturnValue(state({ hasWorkingModel: true, localReady: true, loading: true }));
render(<ModelGateStep {...props()} />);
expect(screen.getByTestId('model-gate')).toBeInTheDocument();
expect(screen.getByRole('status')).toHaveTextContent(/model ready/i);
});
it('keeps cloud readiness owned by the shared gate so rejected keys remain visible', () => {
mocks.useHasWorkingModel.mockReturnValue(state({ hasWorkingModel: true, cloudReady: true, loading: true }));
render(<ModelGateStep {...props()} />);
expect(screen.getByTestId('model-gate')).toBeInTheDocument();
expect(screen.queryByText(/model ready/i)).not.toBeInTheDocument();
});
it('"I\'ll do this later" escapes even with no model (dismiss to Home)', () => {
const p = props();
render(<ModelGateStep {...p} />);
fireEvent.click(screen.getByRole('button', { name: /do this later/i }));
expect(p.onLater).toHaveBeenCalledTimes(1);
});
});

View File

@@ -0,0 +1,77 @@
import { motion } from 'framer-motion';
import { Cpu, ArrowRight, Loader2, Check } from 'lucide-react';
import { fadeSlide } from './constants';
import { ModelGate } from '@/components/os/model-gate/ModelGate';
import { useHasWorkingModel } from '@/hooks/useHasWorkingModel';
import type { ModelGateStepProps } from './types';
/**
* Onboarding step 3 — the HARD model gate (PR5 D2). Continue stays disabled until
* ≥1 working model exists (a cloud key live-validated → Vault, OR a detected/pulled
* local model). One soft escape — "I'll do this later" — dismisses onboarding to
* Home, where the NoModelBanner persists until a model is set up. A zero-model first
* task instantly errors; the gate prevents that cold-start dead-end (DESIGN_POV §2).
*
* Reuses the shared ModelGate (same component as Settings → Models) so the gate and
* the permanent home of model setup can never drift.
*/
const ModelGateStep = ({ onContinue, onLater }: ModelGateStepProps) => {
const { hasWorkingModel, cloudReady, localReady, loading, refresh } = useHasWorkingModel();
return (
<motion.div key="step-model-gate" {...fadeSlide}>
<div className="text-center mb-5">
<Cpu className="w-10 h-10 text-honey mx-auto mb-3" />
<h2 className="text-2xl font-display font-bold text-foreground mb-2">Connect a model</h2>
<p className="text-sm text-muted-foreground">
Waggle needs one model to think with. Bring your own provider key — stored encrypted
in your Vault — or run a model locally. Nothing leaves your machine without your key.
</p>
</div>
{hasWorkingModel && localReady && !cloudReady ? (
<div role="status" className="flex items-start gap-3 rounded-xl border border-primary/30 bg-primary/10 px-4 py-3 text-left">
<Check className="mt-0.5 h-5 w-5 shrink-0 text-honey" aria-hidden />
<div>
<p className="text-sm font-display font-semibold text-foreground">Model ready</p>
<p className="text-xs text-muted-foreground">
{cloudReady
? 'Your provider key is in Vault. You can tune models later in Settings.'
: localReady
? 'A local model is available. You can tune models later in Settings.'
: 'A model is available. You can tune models later in Settings.'}
</p>
</div>
</div>
) : null}
<ModelGate
variant="onboarding"
onModelReady={refresh}
suppressReadinessBanner={hasWorkingModel && localReady && !cloudReady}
/>
<div className="flex items-center justify-end gap-4 mt-6">
<div className="flex items-center gap-3">
<button
onClick={onLater}
className="text-sm text-muted-foreground hover:text-foreground transition-colors font-display rounded-md px-2 py-1 focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
I&apos;ll do this later
</button>
<button
onClick={onContinue}
disabled={!hasWorkingModel}
aria-disabled={!hasWorkingModel}
title={hasWorkingModel ? undefined : 'Add a working model to continue'}
className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-primary text-primary-foreground font-display text-sm font-semibold hover:bg-primary/80 disabled:opacity-50 transition-colors focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
{loading && !hasWorkingModel ? <Loader2 aria-hidden className="w-4 h-4 animate-spin" /> : null}
Continue <ArrowRight className="w-4 h-4" aria-hidden />
</button>
</div>
</div>
</motion.div>
);
};
export default ModelGateStep;

View File

@@ -0,0 +1,14 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import ReadyStep from './ReadyStep';
describe('ReadyStep', () => {
it('renders the Waggle logo with stable intrinsic dimensions', () => {
render(<ReadyStep createError={null} onLetsGo={vi.fn()} />);
const logo = screen.getByAltText('Waggle');
expect(logo).toHaveAttribute('width', '80');
expect(logo).toHaveAttribute('height', '80');
});
});

View File

@@ -0,0 +1,48 @@
import { motion } from 'framer-motion';
import waggleLogoDark from '@/assets/waggle-logo.jpeg';
import waggleLogoLight from '@/assets/waggle-logo.png';
import { useIsLightTheme } from '@/hooks/useIsLightTheme';
import { fadeSlide } from './constants';
import type { ReadyStepProps } from './types';
const ReadyStep = ({ createError, onLetsGo }: ReadyStepProps) => {
const isLight = useIsLightTheme();
const waggleLogo = isLight ? waggleLogoLight : waggleLogoDark;
return (
<motion.div key="step-7" {...fadeSlide} className="text-center">
<motion.div
initial={{ scale: 0.8, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ type: 'spring', damping: 12 }}
>
<div className="relative w-20 h-20 mx-auto mb-5">
<img
src={waggleLogo}
alt="Waggle"
width={80}
height={80}
className="w-20 h-20 rounded-2xl"
style={{ boxShadow: '0 0 60px hsl(var(--primary) / 0.4)' }}
/>
</div>
{createError && (
<p className="text-xs text-amber-400 mb-3 text-center">{createError}</p>
)}
<h2 className="text-3xl font-display font-bold text-foreground mb-2">
Your hive is ready ⬡
</h2>
<p className="text-sm text-muted-foreground mb-6">
Your workspace is ready. Let's get to work.
</p>
<button
onClick={onLetsGo}
className="inline-flex items-center gap-2 px-8 py-3 rounded-xl bg-primary text-primary-foreground font-display text-sm font-semibold hover:bg-primary/80 transition-colors glow-primary"
>
🐝 Let's go!
</button>
</motion.div>
</motion.div>
);
};
export default ReadyStep;

View File

@@ -0,0 +1,48 @@
/** PR5 Phase C2 — the Template step (curated 6; selecting creates the workspace). */
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
import { Microscope } from 'lucide-react';
import TemplateStep from './TemplateStep';
const templates = [
{ id: 'research-project', name: 'Research Hub', icon: Microscope, hint: 'Design a literature review', desc: 'Deep dive' },
{ id: 'blank', name: 'Blank Workspace', icon: Microscope, hint: 'Hello!', desc: 'From scratch' },
];
afterEach(() => cleanup());
describe('TemplateStep', () => {
it('renders the curated templates and selects one by id', () => {
const onSelect = vi.fn();
render(<TemplateStep templates={templates} onSelect={onSelect} creating={false} creatingId={null} createError={null} />);
fireEvent.click(screen.getByRole('button', { name: /research hub/i }));
expect(onSelect).toHaveBeenCalledWith('research-project');
});
it('disables the cards while creating and marks the chosen one busy', () => {
render(<TemplateStep templates={templates} onSelect={vi.fn()} creating creatingId="blank" createError={null} />);
expect(screen.getByRole('button', { name: /research hub/i })).toBeDisabled();
expect(screen.getByRole('button', { name: /blank workspace/i })).toHaveAttribute('aria-busy', 'true');
});
it('shows a soft create error', () => {
render(<TemplateStep templates={templates} onSelect={vi.fn()} creating={false} creatingId={null} createError="created locally" />);
expect(screen.getByText(/created locally/i)).toBeInTheDocument();
});
it('shows no Recommended badge and keeps input order when recommendedId is null', () => {
render(<TemplateStep templates={templates} onSelect={vi.fn()} creating={false} creatingId={null} createError={null} recommendedId={null} />);
expect(screen.queryByText(/recommended/i)).not.toBeInTheDocument();
const cards = screen.getAllByRole('button');
expect(cards[0]).toHaveTextContent(/research hub/i);
});
it('badges the recommended template and floats it first', () => {
// blank is second in the input list; recommending it must move it to the front.
render(<TemplateStep templates={templates} onSelect={vi.fn()} creating={false} creatingId={null} createError={null} recommendedId="blank" />);
expect(screen.getByText(/recommended/i)).toBeInTheDocument();
const cards = screen.getAllByRole('button');
expect(cards[0]).toHaveTextContent(/blank workspace/i);
expect(cards[0]).toHaveTextContent(/recommended/i);
});
});

View File

@@ -0,0 +1,70 @@
import { motion } from 'framer-motion';
import { Loader2 } from 'lucide-react';
import { fadeSlide } from './constants';
import type { TemplateStepProps } from './types';
/**
* Onboarding Template step (PR5 D4/D5). Folds the old workspace-create step: picking
* one of the curated 6 starting points creates the first workspace with a matching
* specialist persona + the template id, then advances to the first task. Calm/fast —
* no type picker, no name field (the template names it; renameable later).
*/
const TemplateStep = ({ templates, onSelect, creating, creatingId, createError, recommendedId }: TemplateStepProps) => {
// Recommended card first (immutable reorder); leave order untouched when the
// recommendation isn't one of the shown templates.
const ordered =
recommendedId && templates.some((t) => t.id === recommendedId)
? [
...templates.filter((t) => t.id === recommendedId),
...templates.filter((t) => t.id !== recommendedId),
]
: templates;
return (
<motion.div key="step-template" {...fadeSlide}>
<div className="text-center mb-6">
<h2 className="text-2xl font-display font-bold text-foreground mb-2">Pick a starting point</h2>
<p className="text-sm text-muted-foreground">
We&apos;ll set up your first workspace — its own brain, with a matching specialist. Add more anytime.
</p>
</div>
<div className="grid grid-cols-2 gap-2.5 mb-5">
{ordered.map((t) => {
const Icon = t.icon;
const isCreating = creating && creatingId === t.id;
const isRecommended = t.id === recommendedId;
return (
<button
key={t.id}
type="button"
onClick={() => onSelect(t.id)}
disabled={creating}
aria-busy={isCreating}
className="glass-strong rounded-xl p-3.5 text-left transition-colors flex flex-col gap-1 hover:border-primary/40 disabled:opacity-60 focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
<div className="flex items-center justify-between gap-2">
{isCreating ? (
<Loader2 className="w-5 h-5 mb-0.5 text-honey animate-spin" aria-hidden />
) : (
<Icon className="w-5 h-5 mb-0.5 text-muted-foreground" aria-hidden />
)}
{isRecommended && (
<span className="text-[10px] font-display font-semibold uppercase tracking-wide text-honey bg-primary/10 rounded-full px-2 py-0.5">
Recommended
</span>
)}
</div>
<h3 className="text-sm font-display font-semibold text-foreground">{t.name}</h3>
<p className="text-[11px] text-muted-foreground">{t.desc}</p>
</button>
);
})}
</div>
{createError && <p className="text-xs text-muted-foreground mb-3">{createError}</p>}
</motion.div>
);
};
export default TemplateStep;

View File

@@ -0,0 +1,106 @@
import { motion, useReducedMotion } from 'framer-motion';
import { ShieldCheck, Lock, Globe } from 'lucide-react';
import beeMascot from '@/assets/personas/general-purpose.png';
import { fadeSlide } from './constants';
import type { WelcomeStepProps } from './types';
/**
* S12 — First Launch. Manual "Continue" only (C29: the 3s auto-advance was
* dropped). Carries a static disabled `English (US)` chip (C28 — no i18n exists
* yet, so the selector is a non-interactive placeholder) and a one-line
* local-first / privacy note so the user sees the trust signal up front. When
* the sidecar is unreachable an "offline-ready" note reassures that setup still
* works locally.
*/
const WelcomeStep = ({ onClickAnywhere, offline }: WelcomeStepProps) => {
const reduceMotion = useReducedMotion();
return (
<motion.div
key="step-first-launch"
{...fadeSlide}
className="text-center"
>
<div className="relative w-24 h-24 mx-auto mb-6">
{/* Wave R Lane E — brand moment: the canonical flat-geometric hex-bee
mascot (the same set the persona picker + landing use) opens
onboarding, a warm greeting instead of a generic app-icon tile. The
transparent mascot reads on both themes.
Wave S Lane E — kill the square tile seam: the old `glow-breathe`
class animated a `box-shadow`, which hugs the element's RECTANGLE (so
the amber glow read as a square tile against light ivory). Drive the
pulse through the `filter: drop-shadow` instead — it follows the bee's
alpha silhouette, so the halo is bee-shaped, not a tile. Reduced-motion
holds a single static drop-shadow (no pulse).
Wave W Lane E fix 2: amplify the breathing so the hero moment has a
living pulse on video — a faster ~3s cycle with a visibly larger
radius/opacity swing (24→58px, 0.20→0.58) instead of the barely-there
28→46px / 0.26→0.46. Still tasteful; reduced-motion stays static. */}
<motion.img
src={beeMascot}
alt="Waggle"
className="w-24 h-24"
animate={
reduceMotion
? { filter: 'drop-shadow(0 0 38px hsl(var(--primary) / 0.36))' }
: {
filter: [
'drop-shadow(0 0 24px hsl(var(--primary) / 0.20))',
'drop-shadow(0 0 58px hsl(var(--primary) / 0.58))',
'drop-shadow(0 0 24px hsl(var(--primary) / 0.20))',
],
}
}
transition={
reduceMotion
? { duration: 0 }
: { duration: 3, repeat: Infinity, ease: 'easeInOut' }
}
/>
</div>
<span className="inline-block text-xs font-display font-semibold tracking-[0.3em] uppercase text-honey mb-4">
Personal AI Workspace
</span>
<h1 className="text-4xl font-display font-bold text-foreground mb-3">
Your AI should know how you work
</h1>
<p className="text-muted-foreground text-sm max-w-md mx-auto mb-6">
Waggle remembers you, knows your projects, evolves with each decision, and guides the next step.
</p>
{/* C28: static language badge — no i18n exists yet, so this is a
non-interactive marker of the (sole) current language, not a control. */}
<div className="mb-5">
<span
title="More languages coming soon"
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full border border-border/50 bg-muted/30 text-xs font-display text-muted-foreground"
>
<Globe className="w-3 h-3" aria-hidden /> English (US)
</span>
</div>
<button
onClick={(e) => { e.stopPropagation(); onClickAnywhere(); }}
autoFocus
className="inline-flex items-center gap-2 px-6 py-3 rounded-xl bg-primary text-primary-foreground font-display text-sm font-semibold hover:bg-primary/80 transition-colors focus-visible:outline-none focus-visible:shadow-[0_0_0_3px_var(--focus-ring)]"
>
Continue →
</button>
{/* Local-first / privacy note (C28 companion). Lane T: was
text-muted-foreground/70 — the /70 composited to ~2.9:1 (light) / 3.8:1
(dark) over the scrim (sub-AA). Full-opacity --text-tertiary → 5.4/7.0:1. */}
<p className="flex items-center justify-center gap-1.5 text-xs text-[var(--text-tertiary)] mt-5 max-w-md mx-auto">
<ShieldCheck className="w-3.5 h-3.5 text-honey/70 shrink-0" />
Your memory and data stay on your device. Nothing leaves unless you say so.
</p>
{offline && (
<p className="flex items-center justify-center gap-1.5 text-[11px] text-[var(--text-tertiary)] mt-2">
<Lock className="w-3 h-3 shrink-0" />
Offline-ready — setup works locally even without a connection.
</p>
)}
</motion.div>
);
};
export default WelcomeStep;

View File

@@ -0,0 +1,53 @@
import { cleanup, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import WhoAreYouStep from './WhoAreYouStep';
import type { OnboardingProfileFields } from './types';
const profile: OnboardingProfileFields = {
name: 'Mara',
role: 'Operations Lead',
industry: 'Technology',
workType: 'operations',
teamSize: 'small',
goals: ['remember'],
};
afterEach(() => cleanup());
describe('WhoAreYouStep', () => {
it('a11y: identity fields expose stable form metadata', () => {
render(
<WhoAreYouStep
profile={profile}
onChange={vi.fn()}
onContinue={vi.fn()}
saving={false}
/>,
);
const name = screen.getByRole('textbox', { name: 'Name' });
expect(name).toHaveAttribute('name', 'onboardingName');
expect(name).toHaveAttribute('autocomplete', 'name');
const role = screen.getByRole('textbox', { name: 'Role' });
expect(role).toHaveAttribute('name', 'onboardingRole');
expect(role).toHaveAttribute('autocomplete', 'organization-title');
});
it('keeps unselected profile chips readable instead of looking disabled', () => {
render(
<WhoAreYouStep
profile={{ ...profile, workType: '', teamSize: '', goals: [] }}
onChange={vi.fn()}
onContinue={vi.fn()}
saving={false}
/>,
);
for (const name of ['Engineering', 'Just me', 'Remember everything I work on']) {
const chip = screen.getByRole('button', { name });
expect(chip).toHaveClass('text-[var(--text-tertiary)]');
expect(chip).toHaveClass('border-[var(--line-affordance)]');
}
});
});

View File

@@ -0,0 +1,192 @@
import { motion } from 'framer-motion';
import { Loader2 } from 'lucide-react';
import { fadeSlide } from './constants';
import { WORK_TYPES, TEAM_SIZES, GOALS, buildProfilePreview } from '@/lib/onboarding-profile';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@/components/ui/select';
import type { WhoAreYouStepProps } from './types';
/** Industry options — copied from UserProfileApp's Identity tab (reuse pattern). */
const INDUSTRIES = [
'Technology', 'Financial Services', 'Consulting', 'Healthcare',
'Education', 'Manufacturing', 'Retail', 'Media', 'Legal',
'Real Estate', 'Energy', 'Government', 'Non-profit', 'Other',
] as const;
const profileChipClass = (selected: boolean): string => selected
? 'border border-primary/40 bg-primary text-primary-foreground'
: 'border border-[var(--line-affordance)] bg-muted/50 text-[var(--text-tertiary)] hover:border-[var(--focus-ring)] hover:text-foreground';
/**
* S13 / B8 — "Who Are You". Captures the day-0 identity + personalization
* signals and renders a live one-line preview. On Continue the wizard performs
* the dual write (`PUT /api/profile` AND `POST /api/identity`) so the Home
* cockpit greets the user by name (B8). This component is presentational: it
* lifts every field through `onChange` and delegates the save to `onContinue`.
*/
const WhoAreYouStep = ({ profile, onChange, onContinue, saving }: WhoAreYouStepProps) => {
const goals = profile.goals ?? [];
const toggleGoal = (id: string) => {
const next = goals.includes(id) ? goals.filter(g => g !== id) : [...goals, id];
onChange({ goals: next });
};
const preview = buildProfilePreview({
name: profile.name,
role: profile.role,
industry: profile.industry,
workType: profile.workType,
teamSize: profile.teamSize,
goals,
});
return (
<motion.div key="step-who-are-you" {...fadeSlide} className="w-full min-w-0">
{/* Wave V Lane F item 3 (mascot carry): the generic UserRound glyph that
used to head this step is gone — the wizard shell now carries the
persistent breathing hex-bee across every step, so the brand mascot is
the header instead of a per-step icon swap. */}
<div className="text-center mb-3 sm:mb-6">
<h2 className="text-xl sm:text-2xl font-display font-bold text-foreground mb-1.5 sm:mb-2">
Tell us who you are
</h2>
<p className="text-[13px] sm:text-sm text-muted-foreground leading-snug sm:leading-normal">
Waggle uses this to greet you by name and tailor how it helps. You can change it anytime in My Profile.
</p>
</div>
<div className="space-y-3 sm:space-y-5">
{/* Name / Role / Industry */}
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2 sm:gap-3">
<div>
<label className="text-xs text-muted-foreground block mb-1" htmlFor="who-name">Name</label>
<input
id="who-name"
name="onboardingName"
autoComplete="name"
value={profile.name ?? ''}
onChange={e => onChange({ name: e.target.value })}
placeholder="Marko Markovic"
className="w-full bg-muted/50 border border-border/50 rounded-lg px-3 py-1.5 text-[13px] sm:text-sm text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
/>
</div>
<div>
<label className="text-xs text-muted-foreground block mb-1" htmlFor="who-role">Role</label>
<input
id="who-role"
name="onboardingRole"
autoComplete="organization-title"
value={profile.role ?? ''}
onChange={e => onChange({ role: e.target.value })}
placeholder="Strategy Consultant"
className="w-full bg-muted/50 border border-border/50 rounded-lg px-3 py-1.5 text-[13px] sm:text-sm text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
/>
</div>
<div>
<label className="text-xs text-muted-foreground block mb-1" htmlFor="who-industry">Industry</label>
{/* Wave V Lane F item 3: the native OS <select> rendered its options
list in un-themed browser chrome (a white popup in dark mode).
The app's themed Select primitive (Radix) renders a token-driven
dropdown that matches both themes; the trigger inherits the same
bg-muted/50 + border-border/50 grammar as the Name/Role inputs. */}
<Select
value={profile.industry || undefined}
onValueChange={(v) => onChange({ industry: v })}
>
<SelectTrigger
id="who-industry"
aria-label="Industry"
className="w-full h-auto bg-muted/50 border-border/50 rounded-lg px-3 py-1.5 text-[13px] sm:text-sm text-foreground"
>
<SelectValue placeholder="Select…" />
</SelectTrigger>
<SelectContent>
{INDUSTRIES.map(i => (
<SelectItem key={i} value={i}>{i}</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{/* Work type (C30 — distinct personalization signal from the template) */}
<div>
<label className="text-xs text-muted-foreground block mb-1.5 sm:mb-2">What kind of work do you do?</label>
<div className="flex flex-wrap gap-1.5">
{WORK_TYPES.map(w => (
<button
key={w.id}
type="button"
aria-pressed={profile.workType === w.id}
onClick={() => onChange({ workType: profile.workType === w.id ? '' : w.id })}
className={`px-2.5 py-1 sm:px-3 sm:py-1.5 rounded-lg text-xs font-display transition-colors ${profileChipClass(profile.workType === w.id)}`}
>
{w.label}
</button>
))}
</div>
</div>
{/* Team size */}
<div>
<label className="text-xs text-muted-foreground block mb-1.5 sm:mb-2">How big is your team?</label>
<div className="flex flex-wrap gap-1.5">
{TEAM_SIZES.map(t => (
<button
key={t.id}
type="button"
aria-pressed={profile.teamSize === t.id}
onClick={() => onChange({ teamSize: profile.teamSize === t.id ? '' : t.id })}
className={`px-2.5 py-1 sm:px-3 sm:py-1.5 rounded-lg text-xs font-display transition-colors ${profileChipClass(profile.teamSize === t.id)}`}
>
{t.label}
</button>
))}
</div>
</div>
{/* Goals (multi-select chips) */}
<div>
<label className="text-xs text-muted-foreground block mb-1.5 sm:mb-2">What do you want Waggle to help with?</label>
<div className="flex flex-wrap gap-1.5">
{GOALS.map(g => {
const on = goals.includes(g.id);
return (
<button
key={g.id}
type="button"
aria-pressed={on}
onClick={() => toggleGoal(g.id)}
className={`px-2.5 py-1 sm:px-3 sm:py-1.5 rounded-lg text-xs font-display transition-colors ${profileChipClass(on)}`}
>
{g.label}
</button>
);
})}
</div>
</div>
{/* Live preview */}
<div className="p-2.5 sm:p-3 rounded-xl bg-secondary/30 border border-border/30">
{/* Lane T: was text-muted-foreground/70 (~2.9:1 light over the tinted
preview panel — sub-AA). Full-opacity --text-tertiary → ≥5.2:1. */}
<p className="text-[11px] uppercase tracking-wide text-[var(--text-tertiary)] mb-1 font-display">Preview</p>
<p className="text-sm text-foreground">{preview}</p>
</div>
</div>
<div className="flex items-center justify-end gap-4 mt-4 sm:mt-6">
<button
onClick={onContinue}
disabled={saving}
aria-busy={saving}
className="inline-flex items-center gap-2 px-5 py-2 sm:py-2.5 rounded-xl bg-primary text-primary-foreground font-display text-sm font-semibold hover:bg-primary/80 disabled:opacity-50 transition-colors focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
{saving ? <Loader2 aria-hidden="true" className="w-4 h-4 animate-spin" /> : null}
{saving ? 'Saving…' : 'Continue →'}
</button>
</div>
</motion.div>
);
};
export default WhoAreYouStep;

View File

@@ -0,0 +1,26 @@
import { cleanup, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import WorkspaceCreateStep from './WorkspaceCreateStep';
afterEach(() => cleanup());
describe('WorkspaceCreateStep', () => {
it('a11y: workspace name exposes stable form metadata', () => {
render(
<WorkspaceCreateStep
workspaceType="project"
workspaceName="Launch"
onSelectType={vi.fn()}
onNameChange={vi.fn()}
onCreate={vi.fn()}
onBack={vi.fn()}
creating={false}
createError={null}
/>,
);
const name = screen.getByRole('textbox', { name: /workspace name/i });
expect(name).toHaveAttribute('name', 'onboardingWorkspaceName');
expect(name).toHaveAttribute('autocomplete', 'off');
});
});

View File

@@ -0,0 +1,111 @@
import { motion } from 'framer-motion';
import { FolderPlus, Briefcase, Users2, Microscope, User, Loader2 } from 'lucide-react';
import type { ElementType } from 'react';
import { fadeSlide } from './constants';
import type { WorkspaceCreateStepProps, OnboardingWorkspaceType } from './types';
/**
* S17 (thin / onboarding-embedded) — Workspace Creation. A trimmed type-picker
* (C6: `project | client | research | personal`) + a name field, routed through
* the SAME existing create path (`handleFinish` → `adapter.createWorkspace`).
* The full stepped S17 wizard (suggested skills/agents/connectors panels) is a
* separate standalone card; per C35 no installs/OAuth run here. The full
* 6-type `WorkspaceType` reserves `team`/`organization` — onboarding offers the
* 4 personal-scope types only.
*/
const WORKSPACE_TYPES: ReadonlyArray<{
id: OnboardingWorkspaceType;
name: string;
desc: string;
icon: ElementType;
}> = [
{ id: 'project', name: 'Project', desc: 'A focused piece of work', icon: Briefcase },
{ id: 'client', name: 'Client', desc: 'Work for a specific client', icon: Users2 },
{ id: 'research', name: 'Research', desc: 'Explore a topic or question', icon: Microscope },
{ id: 'personal', name: 'Personal', desc: 'Your own space', icon: User },
];
const WorkspaceCreateStep = ({
workspaceType,
workspaceName,
onSelectType,
onNameChange,
onCreate,
onBack,
creating,
createError,
}: WorkspaceCreateStepProps) => (
<motion.div key="step-workspace-create" {...fadeSlide}>
<div className="text-center mb-6">
<FolderPlus className="w-10 h-10 text-honey mx-auto mb-3" />
<h2 className="text-2xl font-display font-bold text-foreground mb-2">
Create your first workspace
</h2>
<p className="text-sm text-muted-foreground">
Each workspace is its own brain — memory, files, and agents stay isolated.
</p>
<p className="text-xs text-muted-foreground/70 mt-1.5">
Your agent learns each workspace's patterns and can propose new skills — you approve every change.
</p>
</div>
<div className="grid grid-cols-2 gap-2.5 mb-5">
{WORKSPACE_TYPES.map((t) => {
const Icon = t.icon;
const selected = workspaceType === t.id;
return (
<button
key={t.id}
type="button"
onClick={() => onSelectType(t.id)}
aria-pressed={selected}
className={`glass-strong rounded-xl p-3.5 text-left transition-colors flex flex-col gap-1 ${
selected ? 'ring-2 ring-primary border-primary/40' : 'hover:border-primary/40'
}`}
>
<Icon className={`w-5 h-5 mb-0.5 ${selected ? 'text-honey' : 'text-muted-foreground'}`} />
<h3 className="text-sm font-display font-semibold text-foreground">{t.name}</h3>
<p className="text-[11px] text-muted-foreground">{t.desc}</p>
</button>
);
})}
</div>
<div className="mb-5">
<label className="text-xs text-muted-foreground block mb-1" htmlFor="ws-name">Workspace name</label>
<input
id="ws-name"
name="onboardingWorkspaceName"
autoComplete="off"
value={workspaceName}
onChange={e => onNameChange(e.target.value)}
placeholder="My Workspace"
className="w-full bg-muted/50 border border-border/50 rounded-lg px-3 py-2 text-sm text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
/>
</div>
{createError && (
<p className="text-xs text-[var(--sem-risk,theme(colors.red.400))] mb-3">{createError}</p>
)}
<div className="flex items-center justify-between gap-4">
<button
onClick={onBack}
className="text-sm text-muted-foreground hover:text-foreground transition-colors font-display rounded-md px-1 focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
Back
</button>
<button
onClick={onCreate}
disabled={creating || !workspaceName.trim()}
aria-busy={creating}
className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-primary text-primary-foreground font-display text-sm font-semibold hover:bg-primary/80 disabled:opacity-50 transition-colors focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
{creating ? <Loader2 aria-hidden="true" className="w-4 h-4 animate-spin" /> : null}
{creating ? 'Creating…' : 'Create workspace →'}
</button>
</div>
</motion.div>
);
export default WorkspaceCreateStep;

View File

@@ -0,0 +1,187 @@
import {
Brain, Layers, Wrench, Target, Microscope, Laptop, Megaphone, Rocket,
Scale, Building, Plus, PenLine, BarChart3, Code, ClipboardList, Mail,
Hexagon, Zap, Crown, HeadphonesIcon, Settings, Database, Users,
Palette, DollarSign, Briefcase,
} from 'lucide-react';
import { DUR } from '@/lib/motion/tokens';
import type { OnboardingTemplate, OnboardingPersona, ValueProp, TierOption } from './types';
import type { UserTier } from '@/lib/dock-tiers';
export const TEMPLATES: readonly OnboardingTemplate[] = [
{ id: 'sales-pipeline', name: 'Sales Pipeline', icon: Target, hint: 'Research the top 5 competitors in my industry', desc: 'Track deals and prospects' },
{ id: 'research-project', name: 'Research Hub', icon: Microscope, hint: 'Help me design a literature review on my topic', desc: 'Deep dive into any subject' },
{ id: 'code-review', name: 'Engineering', icon: Laptop, hint: 'Read my project and tell me what you see', desc: 'Code, review, and ship' },
{ id: 'marketing-campaign', name: 'Marketing & Content', icon: Megaphone, hint: 'Draft a campaign brief for my product launch', desc: 'Campaigns, copy, and SEO' },
{ id: 'product-launch', name: 'Product Management', icon: Rocket, hint: 'Help me write a PRD for my next feature', desc: 'Specs, roadmaps, and launches' },
{ id: 'legal-review', name: 'Legal & Compliance', icon: Scale, hint: 'Draft a standard NDA template', desc: 'Contracts, compliance, and risk' },
{ id: 'agency-consulting', name: 'Consulting', icon: Building, hint: 'Set up client workspaces for my biggest accounts', desc: 'Client delivery and strategy' },
{ id: 'customer-support', name: 'Customer Support', icon: HeadphonesIcon, hint: 'Help me draft a response to this customer issue', desc: 'Tickets, KB, and escalation' },
{ id: 'finance-accounting', name: 'Finance', icon: DollarSign, hint: 'Prepare a variance analysis for this month', desc: 'Budgets, reports, and close' },
{ id: 'hr-people', name: 'HR & People', icon: Users, hint: 'Draft a job description for a senior engineer', desc: 'Hiring, policy, and onboarding' },
{ id: 'operations-center', name: 'Operations', icon: Settings, hint: 'Create an SOP for our onboarding process', desc: 'Processes, SOPs, and vendors' },
{ id: 'data-analytics', name: 'Data & Analytics', icon: Database, hint: 'Write a SQL query to find our top customers', desc: 'SQL, dashboards, and insights' },
{ id: 'recruiting-pipeline', name: 'Recruiting', icon: Briefcase, hint: 'Write a job description and screening scorecard', desc: 'Source, screen, and hire' },
{ id: 'design-studio', name: 'Design Studio', icon: Palette, hint: 'Write a creative brief for our rebrand', desc: 'Briefs, feedback, and brand' },
{ id: 'blank', name: 'Blank Workspace', icon: Plus, hint: 'Hello! What can you help me with?', desc: 'Start from scratch' },
] as const;
export const TEMPLATE_PERSONA: Readonly<Record<string, string>> = {
'sales-pipeline': 'sales-rep',
'research-project': 'researcher',
'code-review': 'coder',
'marketing-campaign': 'marketer',
'product-launch': 'product-manager-senior',
'legal-review': 'legal-professional',
'agency-consulting': 'consultant',
'customer-support': 'support-agent',
'finance-accounting': 'finance-owner',
'hr-people': 'hr-manager',
'operations-center': 'ops-manager',
'data-analytics': 'data-engineer',
'recruiting-pipeline': 'recruiter',
'design-studio': 'creative-director',
'blank': 'general-purpose',
};
/**
* PR5 D5 — the curated 6 onboarding starting points for the ≤2-min flow. The full
* 15 (and more specialists) live in the workspace gallery later. These map to existing
* TEMPLATES ids + TEMPLATE_PERSONA — curation, not new data.
*/
export const CURATED_ONBOARDING_TEMPLATE_IDS = [
'research-project', 'code-review', 'sales-pipeline',
'marketing-campaign', 'product-launch', 'blank',
] as const;
export const CURATED_ONBOARDING_TEMPLATES: readonly OnboardingTemplate[] =
CURATED_ONBOARDING_TEMPLATE_IDS
.map((id) => TEMPLATES.find((t) => t.id === id))
.filter((t): t is OnboardingTemplate => Boolean(t));
/**
* First-task suggestion chips per curated template. The single `hint` on each
* TEMPLATE seeds the textarea; this gives the terminal step 2-3 tailored prompts
* to pick from instead of the same 6 generic hints for everyone. Keyed by curated
* template id; the wizard falls back to the curated hints when the chosen id has
* no group. Each group leads with the template's own `hint` for continuity.
*/
export const TEMPLATE_SUGGESTIONS: Readonly<Record<string, readonly string[]>> = {
'research-project': [
'Help me design a literature review on my topic',
'Summarize the key debates in my field',
'Find the strongest sources for my argument',
],
'code-review': [
'Read my project and tell me what you see',
'Review this file for bugs and edge cases',
'Explain how this codebase is structured',
],
'sales-pipeline': [
'Research the top 5 competitors in my industry',
'Draft a cold outreach email for a new prospect',
'Help me prep for an upcoming sales call',
],
'marketing-campaign': [
'Draft a campaign brief for my product launch',
'Write three headline options for this landing page',
'Outline a content calendar for next month',
],
'product-launch': [
'Help me write a PRD for my next feature',
'Draft a roadmap for the next quarter',
'Turn this idea into user stories',
],
'blank': [
'Hello! What can you help me with?',
'Summarize a document I paste here',
'Help me plan my week',
],
};
export const ALL_ONBOARDING_PERSONAS: readonly OnboardingPersona[] = [
{ id: 'general-purpose', name: 'General Purpose', icon: Brain, desc: 'Adapts to any task', tier: 'universal' as const },
{ id: 'researcher', name: 'Researcher', icon: Microscope, desc: 'Deep research & synthesis', tier: 'knowledge' as const },
{ id: 'writer', name: 'Writer', icon: PenLine, desc: 'Drafting & editing', tier: 'knowledge' as const },
{ id: 'analyst', name: 'Analyst', icon: BarChart3, desc: 'Data analysis & decisions', tier: 'knowledge' as const },
{ id: 'coder', name: 'Coder', icon: Code, desc: 'Code & architecture', tier: 'knowledge' as const },
{ id: 'project-manager', name: 'Project Manager', icon: ClipboardList, desc: 'Planning & coordination', tier: 'domain' as const },
{ id: 'executive-assistant', name: 'Exec Assistant', icon: Mail, desc: 'Email & scheduling', tier: 'domain' as const },
{ id: 'sales-rep', name: 'Sales Rep', icon: Target, desc: 'Prospecting & outreach', tier: 'domain' as const },
{ id: 'marketer', name: 'Marketer', icon: Megaphone, desc: 'Campaigns & copy', tier: 'domain' as const },
{ id: 'product-manager-senior', name: 'Senior PM', icon: Rocket, desc: 'PRDs & roadmaps', tier: 'domain' as const },
{ id: 'hr-manager', name: 'HR Manager', icon: Users, desc: 'Policy & compliance', tier: 'domain' as const },
{ id: 'legal-professional', name: 'Legal Counsel', icon: Scale, desc: 'Contracts & compliance', tier: 'domain' as const },
{ id: 'finance-owner', name: 'Business Finance', icon: DollarSign, desc: 'Budgets & reporting', tier: 'domain' as const },
{ id: 'consultant', name: 'Consultant', icon: Building, desc: 'Strategy & deliverables', tier: 'domain' as const },
{ id: 'support-agent', name: 'Support Agent', icon: HeadphonesIcon, desc: 'Tickets & KB articles', tier: 'domain' as const },
{ id: 'ops-manager', name: 'Ops Manager', icon: Settings, desc: 'SOPs & processes', tier: 'domain' as const },
{ id: 'data-engineer', name: 'Data Engineer', icon: Database, desc: 'SQL & dashboards', tier: 'domain' as const },
{ id: 'recruiter', name: 'Recruiter', icon: Briefcase, desc: 'Sourcing & hiring', tier: 'domain' as const },
{ id: 'creative-director', name: 'Creative Director', icon: Palette, desc: 'Briefs & brand', tier: 'domain' as const },
] as const;
/** Get personas relevant to the selected template — recommended first, then others */
export function getPersonasForTemplate(templateId: string): readonly OnboardingPersona[] {
const recommended = TEMPLATE_PERSONA[templateId];
const universal = ALL_ONBOARDING_PERSONAS.filter(p => p.tier === 'universal');
const knowledge = ALL_ONBOARDING_PERSONAS.filter(p => p.tier === 'knowledge');
const domain = ALL_ONBOARDING_PERSONAS.filter(p => p.tier === 'domain');
return [
...domain.filter(p => p.id === recommended),
...universal,
...knowledge,
...domain.filter(p => p.id !== recommended),
];
}
// QW-5: display labels renamed to avoid collision with billing tiers
// (billing uses "Pro $19/mo", "Teams $49/seat"). Dock tiers describe how
// many icons appear — they are UI layout, not billing. Internal enum
// values ('simple' / 'professional' / 'power') stay the same so stored
// user preferences keep working without migration.
export const TIER_OPTIONS: readonly TierOption[] = [
{
id: 'simple' as UserTier,
name: 'Essential',
icon: Hexagon,
color: 'text-sky-400',
desc: 'Clean and focused. Just the essentials — chat, files, and home.',
},
{
id: 'professional' as UserTier,
name: 'Standard',
icon: Zap,
color: 'text-amber-400',
desc: 'Agents, memory, and workspace tools. The full knowledge-worker kit.',
},
{
id: 'power' as UserTier,
name: 'Everything',
icon: Crown,
color: 'text-violet-400',
desc: 'All apps visible. Ops console, scheduled jobs, marketplace.',
},
] as const;
export const VALUE_PROPS: readonly ValueProp[] = [
{ icon: Brain, title: 'Remembers everything', desc: 'Persistent memory across all sessions' },
{ icon: Layers, title: 'Workspace-native', desc: 'One brain per project, fully isolated' },
{ icon: Wrench, title: 'Real tools', desc: 'Search, draft, code, plan — not just chat' },
] as const;
/**
* Shared framer-motion transition for step content.
* Wave W Lane E fix 2: directional (horizontal) slide instead of the old
* vertical nudge — the incoming step enters from the right (x:24) as the
* outgoing one exits left (x:-24), so welcome→step-1 (and every later step)
* reads as forward spatial motion rather than a fade-in-place. ~200ms.
* Motion-safe: the wizard wraps steps in <MotionConfig reducedMotion="user">,
* which drops the x transform to a pure opacity fade for reduced-motion users.
*/
export const fadeSlide = {
initial: { opacity: 0, x: 24 },
animate: { opacity: 1, x: 0 },
exit: { opacity: 0, x: -24 },
transition: { duration: DUR.base },
} as const;

View File

@@ -0,0 +1,36 @@
/** PR5 D5 — the curated 6 onboarding templates resolve to real data + personas. */
import { describe, it, expect } from 'vitest';
import {
CURATED_ONBOARDING_TEMPLATES,
CURATED_ONBOARDING_TEMPLATE_IDS,
TEMPLATE_PERSONA,
TEMPLATE_SUGGESTIONS,
} from './constants';
describe('curated onboarding templates (PR5 D5)', () => {
it('resolves all 6 curated ids to real templates (no silent drops)', () => {
expect(CURATED_ONBOARDING_TEMPLATE_IDS).toHaveLength(6);
expect(CURATED_ONBOARDING_TEMPLATES).toHaveLength(CURATED_ONBOARDING_TEMPLATE_IDS.length);
});
it('maps every curated template to a specialist persona', () => {
for (const t of CURATED_ONBOARDING_TEMPLATES) {
expect(TEMPLATE_PERSONA[t.id]).toBeTruthy();
}
});
it('gives every curated template a non-empty hint for the first-task seed', () => {
for (const t of CURATED_ONBOARDING_TEMPLATES) {
expect(t.hint.length).toBeGreaterThan(0);
}
});
it('gives every curated template a non-empty first-task suggestion group', () => {
for (const t of CURATED_ONBOARDING_TEMPLATES) {
const group = TEMPLATE_SUGGESTIONS[t.id];
expect(group).toBeDefined();
expect(group.length).toBeGreaterThan(0);
expect(group.every(s => s.length > 0)).toBe(true);
}
});
});

View File

@@ -0,0 +1,21 @@
export { default as WelcomeStep } from './WelcomeStep';
export { default as WhoAreYouStep } from './WhoAreYouStep';
export { default as ModelGateStep } from './ModelGateStep';
export { default as ImportStep } from './ImportStep';
export { default as TemplateStep } from './TemplateStep';
export { default as FirstTaskStep } from './FirstTaskStep';
export { default as WorkspaceCreateStep } from './WorkspaceCreateStep';
export { default as ReadyStep } from './ReadyStep';
export type {
WelcomeStepProps,
WhoAreYouStepProps,
ModelGateStepProps,
ImportStepProps,
TemplateStepProps,
FirstTaskStepProps,
WorkspaceCreateStepProps,
ReadyStepProps,
OnboardingProfileFields,
OnboardingWorkspaceType,
} from './types';

View File

@@ -0,0 +1,50 @@
/** Who-are-you → curated template recommendation (badge + first ordering). */
import { describe, it, expect } from 'vitest';
import { recommendTemplateId } from './recommend-template';
import { CURATED_ONBOARDING_TEMPLATE_IDS } from './constants';
describe('recommendTemplateId', () => {
it('maps each supported work type to a curated template id', () => {
expect(recommendTemplateId('engineering')).toBe('code-review');
expect(recommendTemplateId('product')).toBe('product-launch');
expect(recommendTemplateId('research')).toBe('research-project');
expect(recommendTemplateId('sales')).toBe('sales-pipeline');
expect(recommendTemplateId('marketing')).toBe('marketing-campaign');
// Consulting has no curated card — Research Hub is the proxy.
expect(recommendTemplateId('consulting')).toBe('research-project');
});
it('only ever recommends a curated id', () => {
const curated = new Set<string>(CURATED_ONBOARDING_TEMPLATE_IDS);
for (const wt of ['engineering', 'product', 'research', 'sales', 'marketing', 'consulting']) {
const id = recommendTemplateId(wt);
expect(id).not.toBeNull();
expect(curated.has(id as string)).toBe(true);
}
});
it('returns null for work types without a curated match', () => {
for (const wt of ['operations', 'finance', 'legal', 'design', 'leadership', 'other']) {
expect(recommendTemplateId(wt)).toBeNull();
}
});
it('falls back to keyword-matching the free-text role when work type is empty', () => {
expect(recommendTemplateId('', 'Senior Software Engineer')).toBe('code-review');
expect(recommendTemplateId(undefined, 'Strategy Consultant')).toBe('research-project');
expect(recommendTemplateId('', 'Head of Sales')).toBe('sales-pipeline');
expect(recommendTemplateId('', 'Growth Marketer')).toBe('marketing-campaign');
expect(recommendTemplateId('', 'Product Manager')).toBe('product-launch');
expect(recommendTemplateId('', 'Research Scientist')).toBe('research-project');
});
it('prefers the explicit work type over the role text', () => {
expect(recommendTemplateId('sales', 'Software Engineer')).toBe('sales-pipeline');
});
it('returns null when neither signal matches', () => {
expect(recommendTemplateId()).toBeNull();
expect(recommendTemplateId('', '')).toBeNull();
expect(recommendTemplateId('', 'Operations Lead')).toBeNull();
});
});

View File

@@ -0,0 +1,54 @@
// Pure mapping: who-are-you signals (workType / role) → a curated onboarding
// template id, used to badge + float the "Recommended" starting point on the
// Template step. Returns null when no confident match exists (no badge, list
// keeps its default order). Kept out of the component so the table is unit-
// testable without mounting the tree.
/** Curated-6 template ids (mirrors CURATED_ONBOARDING_TEMPLATE_IDS in constants.ts). */
type CuratedTemplateId =
| 'code-review'
| 'product-launch'
| 'research-project'
| 'sales-pipeline'
| 'marketing-campaign';
/** WORK_TYPES id → curated template id. Only work types with a curated match
* appear; everything else (operations/finance/legal/design/leadership/other)
* falls through to null. Consulting has no curated card — Research Hub is the
* plan-mandated proxy. */
const WORK_TYPE_TO_TEMPLATE: Readonly<Record<string, CuratedTemplateId>> = {
engineering: 'code-review',
product: 'product-launch',
research: 'research-project',
sales: 'sales-pipeline',
marketing: 'marketing-campaign',
consulting: 'research-project',
};
/** Free-text role keyword fallback (ordered — first match wins). */
const ROLE_PATTERNS: ReadonlyArray<readonly [RegExp, CuratedTemplateId]> = [
[/consult/i, 'research-project'],
[/engineer|develop/i, 'code-review'],
[/sales/i, 'sales-pipeline'],
[/market/i, 'marketing-campaign'],
[/product/i, 'product-launch'],
[/research/i, 'research-project'],
];
/**
* Recommend a curated template id from the day-0 signals. Prefers the explicit
* work-type chip; falls back to keyword-matching the free-text role. Returns
* null when neither yields a confident match.
*/
export function recommendTemplateId(workType?: string, role?: string): string | null {
const byWorkType = workType ? WORK_TYPE_TO_TEMPLATE[workType] : undefined;
if (byWorkType) return byWorkType;
const r = role?.trim();
if (r) {
for (const [pattern, id] of ROLE_PATTERNS) {
if (pattern.test(r)) return id;
}
}
return null;
}

View File

@@ -0,0 +1,135 @@
import type { ElementType } from 'react';
import type { UserTier } from '@/lib/dock-tiers';
import type { UserProfile, ClassifiedHarvestItem } from '@/lib/types';
import type { WorkspaceType } from '@waggle/shared';
/* ─── Shared step prop base ─── */
export interface StepNavigation {
readonly goToStep: (step: number) => void;
}
/* ─── WelcomeStep (S12 — first-launch) ─── */
export interface WelcomeStepProps {
/** Advance to the next step (manual Continue; no auto-advance — C29). */
readonly onClickAnywhere: () => void;
/** Sidecar reachability — surfaces an offline-ready note (C28 companion). */
readonly offline?: boolean;
}
/* ─── WhoAreYouStep (S13 / B8) ─── */
/** The profile slice the Who-Are-You step edits. */
export type OnboardingProfileFields = Pick<
UserProfile,
'name' | 'role' | 'industry' | 'workType' | 'teamSize' | 'goals'
>;
export interface WhoAreYouStepProps {
readonly profile: OnboardingProfileFields;
readonly onChange: (patch: Partial<OnboardingProfileFields>) => void;
/** Performs the dual write (profile + identity seed) then advances. */
readonly onContinue: () => void;
readonly saving: boolean;
}
/* ─── ImportStep (S15 / C33) ─── */
export interface ImportStepProps {
readonly importSource: string | null;
/** Classified preview items (kind + confidence) from harvest/preview (C33). */
readonly importItems: readonly ClassifiedHarvestItem[];
readonly importDone: boolean;
readonly importing: boolean;
readonly onFileImport: (file: File, source: string) => void;
readonly onImportCommit: () => void;
/** Claude Code auto-detect status; when found, renders a one-click harvest. */
readonly claudeCodeDetected?: { found: boolean; itemCount: number; path: string } | null;
readonly onClaudeCodeHarvest?: () => void;
readonly onContinue: () => void;
}
/* ─── WorkspaceCreateStep (S17 thin / C6 / C35) ─── */
/** Onboarding-scoped workspace types — the personal-scope subset of WorkspaceType
* (`team`/`organization` are reserved for the team flow, not day-0 onboarding). */
export type OnboardingWorkspaceType = Extract<
WorkspaceType,
'project' | 'client' | 'research' | 'personal'
>;
export interface WorkspaceCreateStepProps {
readonly workspaceType: OnboardingWorkspaceType;
readonly workspaceName: string;
readonly onSelectType: (type: OnboardingWorkspaceType) => void;
readonly onNameChange: (name: string) => void;
readonly onCreate: () => void;
readonly onBack: () => void;
readonly creating: boolean;
readonly createError: string | null;
}
/* ─── ModelGateStep (PR5 D2 — the hard model gate) ─── */
export interface ModelGateStepProps {
/** Advance to Import — only reachable once a working model exists (hard gate). */
readonly onContinue: () => void;
/** Soft escape: dismiss onboarding to Home (the NoModelBanner persists there). */
readonly onLater: () => void;
}
/* ─── TemplateStep (PR5 D4/D5 — curated 6; selecting one creates the workspace) ─── */
export interface TemplateStepProps {
readonly templates: readonly OnboardingTemplate[];
/** Create the workspace from this template (persona + templateId), then advance. */
readonly onSelect: (templateId: string) => void;
readonly creating: boolean;
/** The template id currently being created (for a per-card spinner). */
readonly creatingId: string | null;
readonly createError: string | null;
/** Curated id recommended from the who-are-you answers (badge + first ordering); null = none. */
readonly recommendedId?: string | null;
}
/* ─── FirstTaskStep (PR5 — terminal: seed the first message, open the workspace) ─── */
export interface FirstTaskStepProps {
readonly message: string;
readonly onMessageChange: (message: string) => void;
/** Suggested first prompts (the curated templates' hints). */
readonly suggestions: readonly string[];
readonly onPickSuggestion: (suggestion: string) => void;
readonly onLetsGo: () => void;
readonly createError: string | null;
}
/* ─── ReadyStep (superseded by FirstTaskStep; kept for any standalone reuse) ─── */
export interface ReadyStepProps {
readonly createError: string | null;
readonly onLetsGo: () => void;
}
/* ─── Shared data types (still consumed by constants.ts + onboarding-tier-filter.ts) ─── */
export interface OnboardingTemplate {
readonly id: string;
readonly name: string;
readonly icon: ElementType;
readonly hint: string;
readonly desc: string;
}
export interface OnboardingPersona {
readonly id: string;
readonly name: string;
readonly icon: ElementType;
readonly desc: string;
readonly tier: 'universal' | 'knowledge' | 'domain';
}
export interface ValueProp {
readonly icon: ElementType;
readonly title: string;
readonly desc: string;
}
export interface TierOption {
readonly id: UserTier;
readonly name: string;
readonly icon: ElementType;
readonly color: string;
readonly desc: string;
}