feat(web): ask before sending analytics, drop team screens, hide v1-absent memory features (P1.3a)

- Analytics are opt-in (decision Q7, ADR-0006). PostHog does not start or
  capture anything until the user clicks Allow in a first-run dialog that
  says what is sent. Escape or closing stores nothing and asks again. The
  existing Privacy & Telemetry toggle in Settings withdraws consent at once.
  Builds without VITE_POSTHOG_KEY show no dialog and send nothing.
- Remove the remaining upsell copy: the /team page with its per-seat price,
  Stripe and Teams wording in the erase-data dialog, Teams/Enterprise hints.
- Remove team screens (decision Q3): Waggle Dance, team presence in chat,
  team storage and sharing in workspace creation, storage and files.
- Hide memory features that are not in v1 (decision Q2) behind one map in
  lib/memory-features.ts: the knowledge graph, import history, wiki, agent
  memory hooks and Room launches. The map is the seam P1.5 fills from the
  memory store's capabilities.
- Say Windows, macOS and Linux instead of "Linux soon".
- Update the e2e specs for the removed and hidden screens.

Also logs UF-029: the Settings "Import Data" button has no handler.
This commit is contained in:
shumeiko.it
2026-10-23 14:51:29 +02:00
parent 0325c4eb11
commit f3eb6b6652
66 changed files with 934 additions and 1126 deletions

View File

@@ -2,13 +2,11 @@
# Copy to .env.local and fill in the real values. # Copy to .env.local and fill in the real values.
# NEVER commit .env.local — it is gitignored. # NEVER commit .env.local — it is gitignored.
# PostHog cloud analytics — project "Default project" id 161685, org "Egzakta" # PostHog product analytics, opt-in only (docs/oss/adr/0006-opt-in-analytics.md).
# Required for DAY0-04 (≥ 5 distinct onboarding_complete in 24h post-launch). # Leave unset for builds from source: without a key nothing is sent and the
# The REAL phc_* key is pasted into apps/web/.env.local at Wave 1 / P2b # consent dialog never appears. Release builds get the key from the build
# and is BAKED INTO THE TAURI BUNDLE at P4-win compile time — if missing # environment; Vite reads it at build time, so it cannot be added afterwards.
# at build moment, the shipped binary has PostHog as a permanent no-op. # VITE_POSTHOG_KEY=
# Local SQLite telemetry (packages/core/src/telemetry.ts) continues alongside.
VITE_POSTHOG_KEY=phc_REPLACE_ME
# PR7b Auth — Clerk publishable key (shared instance with apps/www). Public-safe by # PR7b Auth — Clerk publishable key (shared instance with apps/www). Public-safe by
# design (ships in the client bundle); the SECRET key is server-side only and is NOT # design (ships in the client bundle); the SECRET key is server-side only and is NOT

View File

@@ -26,9 +26,7 @@ const McpsRoute = lazy(() => import("@/routes/McpsRoute"));
const MarketplaceRoute = lazy(() => import("@/routes/MarketplaceRoute")); const MarketplaceRoute = lazy(() => import("@/routes/MarketplaceRoute"));
const LauncherRoute = lazy(() => import("@/routes/LauncherRoute")); const LauncherRoute = lazy(() => import("@/routes/LauncherRoute"));
const RoomRoute = lazy(() => import("@/routes/RoomRoute")); const RoomRoute = lazy(() => import("@/routes/RoomRoute"));
const WaggleDanceRoute = lazy(() => import("@/routes/WaggleDanceRoute"));
const ApprovalsRoute = lazy(() => import("@/routes/ApprovalsRoute")); const ApprovalsRoute = lazy(() => import("@/routes/ApprovalsRoute"));
const TeamRoute = lazy(() => import("@/routes/TeamRoute"));
const SettingsRoute = lazy(() => import("@/routes/SettingsRoute")); const SettingsRoute = lazy(() => import("@/routes/SettingsRoute"));
const VaultRoute = lazy(() => import("@/routes/VaultRoute")); const VaultRoute = lazy(() => import("@/routes/VaultRoute"));
const ProfileRoute = lazy(() => import("@/routes/ProfileRoute")); const ProfileRoute = lazy(() => import("@/routes/ProfileRoute"));
@@ -145,15 +143,12 @@ const App = () => (
<Route path="automations" element={routeElement(<AutomationsRoute />)} /> <Route path="automations" element={routeElement(<AutomationsRoute />)} />
<Route path="skills" element={routeElement(<SkillsRoute />)} /> <Route path="skills" element={routeElement(<SkillsRoute />)} />
<Route path="room" element={routeElement(<RoomRoute />)} /> <Route path="room" element={routeElement(<RoomRoute />)} />
<Route path="waggle-dance" element={routeElement(<WaggleDanceRoute />)} />
<Route path="approvals" element={routeElement(<ApprovalsRoute />)} /> <Route path="approvals" element={routeElement(<ApprovalsRoute />)} />
{/* ── Extend ── */} {/* ── Extend ── */}
<Route path="connectors" element={routeElement(<ConnectorsRoute />)} /> <Route path="connectors" element={routeElement(<ConnectorsRoute />)} />
<Route path="mcps" element={routeElement(<McpsRoute />)} /> <Route path="mcps" element={routeElement(<McpsRoute />)} />
<Route path="marketplace" element={routeElement(<MarketplaceRoute />)} /> <Route path="marketplace" element={routeElement(<MarketplaceRoute />)} />
<Route path="launcher" element={routeElement(<LauncherRoute />)} /> <Route path="launcher" element={routeElement(<LauncherRoute />)} />
{/* ── Team (route registered; no nav entry — team mode is not shipped, ADR-0003) ── */}
<Route path="team" element={routeElement(<TeamRoute />)} />
{/* ── System (§9.4: System surfaces nest under /settings/*) ── */} {/* ── System (§9.4: System surfaces nest under /settings/*) ── */}
<Route path="settings" element={routeElement(<SettingsRoute />)} /> <Route path="settings" element={routeElement(<SettingsRoute />)} />
<Route path="settings/vault" element={routeElement(<VaultRoute />)} /> <Route path="settings/vault" element={routeElement(<VaultRoute />)} />

View File

@@ -15,7 +15,7 @@
import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { AnimatePresence } from 'framer-motion'; import { AnimatePresence } from 'framer-motion';
import { Navigate, useLocation, useNavigate } from 'react-router-dom'; import { Navigate, useLocation, useNavigate } from 'react-router-dom';
import { Home, MessageSquare, Brain, ListTodo, Library, Network, Plug, Shield } from 'lucide-react'; import { Home, MessageSquare, Brain, ListTodo, Library, Plug, Shield } from 'lucide-react';
import wallpaperDark from '@/assets/wallpaper.jpg'; import wallpaperDark from '@/assets/wallpaper.jpg';
import wallpaperLight from '@/assets/wallpaper-light.jpg'; import wallpaperLight from '@/assets/wallpaper-light.jpg';
import BootScreen from './BootScreen'; import BootScreen from './BootScreen';
@@ -28,6 +28,7 @@ import { stashDeepLink } from '@/lib/app-deeplink';
import { writeLoginBriefingDismissed, writeLoginBriefingLastDismissedAt, readLoginBriefingDismissed, readSkipBriefingParam } from '@/lib/login-briefing'; import { writeLoginBriefingDismissed, writeLoginBriefingLastDismissedAt, readLoginBriefingDismissed, readSkipBriefingParam } from '@/lib/login-briefing';
import { prefetchBriefing, computeAwayDays, BRIEFING_ABSENCE_DAYS } from '@/lib/briefing-source'; import { prefetchBriefing, computeAwayDays, BRIEFING_ABSENCE_DAYS } from '@/lib/briefing-source';
import { homeCacheExists } from '@/lib/home-cache'; import { homeCacheExists } from '@/lib/home-cache';
import { shouldAskAnalyticsConsent } from '@/lib/analytics-consent';
import { resolveReturningUserOnboarding, isOnboardingStatusKnownSync } from '@/hooks/useOnboarding'; import { resolveReturningUserOnboarding, isOnboardingStatusKnownSync } from '@/hooks/useOnboarding';
import { shouldShowCoachMarks, readOnboardedThisSession, readForceTour, clearForceTour } from '@/lib/coach-marks-gate'; import { shouldShowCoachMarks, readOnboardedThisSession, readForceTour, clearForceTour } from '@/lib/coach-marks-gate';
import { matchNavRoute, queryString, routeFor, routeForSearchResult } from '@/lib/routes'; import { matchNavRoute, queryString, routeFor, routeForSearchResult } from '@/lib/routes';
@@ -37,7 +38,6 @@ import { buildCommandCatalog, type CatalogCommand } from '@/lib/command-catalog'
import { ShellProvider, useShell } from '@/providers/ShellContext'; import { ShellProvider, useShell } from '@/providers/ShellContext';
import { seedChat, useChatWidgetState } from '@/hooks/useChatWidgetState'; import { seedChat, useChatWidgetState } from '@/hooks/useChatWidgetState';
import { useKeyboardShortcuts } from '@/hooks/useKeyboardShortcuts'; import { useKeyboardShortcuts } from '@/hooks/useKeyboardShortcuts';
import { useWaggleDance } from '@/hooks/useWaggleDance';
import { useBumpSessionCount } from '@/hooks/useDockLabels'; import { useBumpSessionCount } from '@/hooks/useDockLabels';
import { useDockNudge } from '@/hooks/useDockNudge'; import { useDockNudge } from '@/hooks/useDockNudge';
import { useToast } from '@/hooks/use-toast'; import { useToast } from '@/hooks/use-toast';
@@ -56,6 +56,7 @@ const OnboardingWizard = lazy(() => import('./overlays/OnboardingWizard'));
const OnboardingTooltips = lazy(() => import('./overlays/OnboardingTooltips')); const OnboardingTooltips = lazy(() => import('./overlays/OnboardingTooltips'));
const LoginBriefing = lazy(() => import('./overlays/LoginBriefing')); const LoginBriefing = lazy(() => import('./overlays/LoginBriefing'));
const ContextRail = lazy(() => import('./overlays/ContextRail')); const ContextRail = lazy(() => import('./overlays/ContextRail'));
const AnalyticsConsentDialog = lazy(() => import('./overlays/AnalyticsConsentDialog'));
const deferredShellElement = (element: ReactNode) => ( const deferredShellElement = (element: ReactNode) => (
<Suspense fallback={null}>{element}</Suspense> <Suspense fallback={null}>{element}</Suspense>
@@ -129,12 +130,10 @@ const ShellLayout = () => {
contextRailTarget, setContextRailTarget, contextRailTarget, setContextRailTarget,
} = useShell(); } = useShell();
const { allSignals: waggleSignals } = useWaggleDance();
const overlaysRef = useRef(ov); const overlaysRef = useRef(ov);
useEffect(() => { useEffect(() => {
overlaysRef.current = ov; overlaysRef.current = ov;
}, [ov]); }, [ov]);
const waggleUnacknowledged = waggleSignals.filter(s => !s.acknowledged).length;
// W2A: no implicit workspaces[0] fallback — the chrome shows a workspace only // W2A: no implicit workspaces[0] fallback — the chrome shows a workspace only
// when one was explicitly selected. Sidebar/StatusBar accept null names; the // when one was explicitly selected. Sidebar/StatusBar accept null names; the
// Chat spine item opens the WorkspaceSwitcher when there is no real selection. // Chat spine item opens the WorkspaceSwitcher when there is no real selection.
@@ -189,6 +188,9 @@ const ShellLayout = () => {
const { entry: activeChatEntry, setPersona: setActiveChatPersona } = const { entry: activeChatEntry, setPersona: setActiveChatPersona } =
useChatWidgetState(effectiveActiveWorkspaceId ?? 'local-default'); useChatWidgetState(effectiveActiveWorkspaceId ?? 'local-default');
// ADR-0006: ask about analytics once per launch until the user chooses.
const [askAnalyticsConsent, setAskAnalyticsConsent] = useState(shouldAskAnalyticsConsent);
// User display name for the sidebar user row (PR1 LOW #2). Best-effort via the // User display name for the sidebar user row (PR1 LOW #2). Best-effort via the
// existing identity surface; re-fetched on connect-settle because the first // existing identity surface; re-fetched on connect-settle because the first
// call can race the session-token attach and 401 → name:null. Falls back to // call can race the session-token attach and 401 → name:null. Falls back to
@@ -372,9 +374,7 @@ const ShellLayout = () => {
const briefingAwayDays = useMemo(() => computeAwayDays(workspaces), [workspaces]); const briefingAwayDays = useMemo(() => computeAwayDays(workspaces), [workspaces]);
// Five-place spine + a power-tier "Pinned" group. Chat resolves to the active // Five-place spine + a power-tier "Pinned" group. Chat resolves to the active
// workspace's chat tab (routeFor falls back to /home with no workspace). The // workspace's chat tab (routeFor falls back to /home with no workspace).
// Agents & tasks badge surfaces unacknowledged coordination signals for now;
// PR3 refines it to the real pending-approvals/tasks count.
const isPro = currentTier === 'power' || currentTier === 'admin'; const isPro = currentTier === 'power' || currentTier === 'admin';
const spine: SidebarNavItem[] = useMemo(() => [ const spine: SidebarNavItem[] = useMemo(() => [
{ key: 'home', label: 'Home', icon: Home, to: '/home', match: ['/home'] }, { key: 'home', label: 'Home', icon: Home, to: '/home', match: ['/home'] },
@@ -392,13 +392,12 @@ const ShellLayout = () => {
onClick: navigateToActiveChat, onClick: navigateToActiveChat,
}, },
{ key: 'memory', label: 'Memory', icon: Brain, to: '/memory', match: ['/memory'] }, { key: 'memory', label: 'Memory', icon: Brain, to: '/memory', match: ['/memory'] },
{ key: 'agents', label: 'Agents', icon: ListTodo, to: '/agents', match: ['/agents', '/automations'], badge: waggleUnacknowledged || undefined }, { key: 'agents', label: 'Agents', icon: ListTodo, to: '/agents', match: ['/agents', '/automations'] },
{ key: 'library', label: 'Library', icon: Library, to: '/artifacts', match: ['/artifacts', '/files', '/skills'] }, { key: 'library', label: 'Library', icon: Library, to: '/artifacts', match: ['/artifacts', '/files', '/skills'] },
], [effectiveActiveWorkspaceId, navigateToActiveChat, waggleUnacknowledged]); ], [effectiveActiveWorkspaceId, navigateToActiveChat]);
const pinned: SidebarNavItem[] = useMemo(() => { const pinned: SidebarNavItem[] = useMemo(() => {
if (!isPro) return []; if (!isPro) return [];
return [ return [
{ key: 'swarm', label: 'Agent swarm', icon: Network, to: '/waggle-dance', match: ['/waggle-dance'] },
{ key: 'connectors', label: 'Connectors', icon: Plug, to: '/connectors', match: ['/connectors'] }, { key: 'connectors', label: 'Connectors', icon: Plug, to: '/connectors', match: ['/connectors'] },
{ key: 'approvals', label: 'Approvals', icon: Shield, to: '/approvals', match: ['/approvals'] }, { key: 'approvals', label: 'Approvals', icon: Shield, to: '/approvals', match: ['/approvals'] },
]; ];
@@ -417,11 +416,21 @@ const ShellLayout = () => {
} }
}, [navigate, ov]); }, [navigate, ov]);
// ADR-0006: the analytics question (only when the build has a PostHog key and
// the user has not chosen yet). On first launch it comes BEFORE the wizard
// mounts: the wizard maps a window-level Escape to Skip, so the two must not
// be open together, and asking first lets the one PostHog event
// (onboarding_complete) be sent if the user allows it.
const analyticsConsentDialog = askAnalyticsConsent && deferredShellElement(
<AnalyticsConsentDialog onClose={() => setAskAnalyticsConsent(false)} />
);
// FR #33: when the onboarding wizard is active, render ONLY the wizard — // FR #33: when the onboarding wizard is active, render ONLY the wizard —
// no nav, no canvas, no overlays (§1.2 OnboardingWizard row: full-screen // no nav, no canvas, no overlays (§1.2 OnboardingWizard row: full-screen
// takeover at the layout level, any URL). Hooks above keep running so // takeover at the layout level, any URL). Hooks above keep running so
// completion re-renders with workspaces/personas already populated. // completion re-renders with workspaces/personas already populated.
if (!onboardingState.completed) { if (!onboardingState.completed) {
if (analyticsConsentDialog) return analyticsConsentDialog;
return deferredShellElement( return deferredShellElement(
<OnboardingWizard <OnboardingWizard
serverBaseUrl={adapter.getServerUrl()} serverBaseUrl={adapter.getServerUrl()}
@@ -439,7 +448,7 @@ const ShellLayout = () => {
const anyModalOpen = const anyModalOpen =
ov.showGlobalSearch || ov.showCreateWorkspace || ov.showPersonaSwitcher || ov.showGlobalSearch || ov.showCreateWorkspace || ov.showPersonaSwitcher ||
ov.showWorkspaceSwitcher || ov.showNotifications || ov.showKeyboardHelp || ov.showWorkspaceSwitcher || ov.showNotifications || ov.showKeyboardHelp ||
ov.showSpawnAgent; ov.showSpawnAgent || askAnalyticsConsent;
return ( return (
<div className="relative w-screen h-screen overflow-hidden select-none"> <div className="relative w-screen h-screen overflow-hidden select-none">
@@ -574,7 +583,7 @@ const ShellLayout = () => {
Lane H item 4: additionally require a ≥7-day absence — otherwise the home Lane H item 4: additionally require a ≥7-day absence — otherwise the home
hero's recall strip is the catch-up, and this modal stays closed. */} hero's recall strip is the catch-up, and this modal stays closed. */}
{onboardingState.completed && onboardingState.tooltipsDismissed && ov.showLoginBriefing {onboardingState.completed && onboardingState.tooltipsDismissed && ov.showLoginBriefing
&& briefingLanding === 'armed' && location.pathname.startsWith('/home') && !offline && !askAnalyticsConsent && briefingLanding === 'armed' && location.pathname.startsWith('/home') && !offline
&& briefingAwayDays >= BRIEFING_ABSENCE_DAYS && ( && briefingAwayDays >= BRIEFING_ABSENCE_DAYS && (
deferredShellElement( deferredShellElement(
<LoginBriefing <LoginBriefing
@@ -593,6 +602,7 @@ const ShellLayout = () => {
{contextRailTarget && deferredShellElement( {contextRailTarget && deferredShellElement(
<ContextRail target={contextRailTarget} onClose={() => setContextRailTarget(null)} /> <ContextRail target={contextRailTarget} onClose={() => setContextRailTarget(null)} />
)} )}
{analyticsConsentDialog}
</div> </div>
); );
}; };

View File

@@ -65,7 +65,7 @@ describe('routeGroupKey — keys on the top segment only', () => {
describe('routeAnnouncement — the polite-live-region label', () => { describe('routeAnnouncement — the polite-live-region label', () => {
it('labels known surfaces', () => { it('labels known surfaces', () => {
expect(routeAnnouncement('/memory')).toBe('Memory'); expect(routeAnnouncement('/memory')).toBe('Memory');
expect(routeAnnouncement('/waggle-dance')).toBe('Agent swarm'); expect(routeAnnouncement('/approvals')).toBe('Approvals');
expect(routeAnnouncement('/workspaces/abc/chat')).toBe('Workspaces'); expect(routeAnnouncement('/workspaces/abc/chat')).toBe('Workspaces');
}); });

View File

@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback, useMemo } from 'react'; import { useState, useEffect, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { Bot, Plus, Search, AlertCircle, RefreshCw, LibraryBig, ChevronRight, Network, ArrowRight } from 'lucide-react'; import { Bot, Plus, Search, AlertCircle, RefreshCw, LibraryBig, ChevronRight } from 'lucide-react';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import BeeLoader from '@/components/ui/BeeLoader'; import BeeLoader from '@/components/ui/BeeLoader';
import { adapter } from '@/lib/adapter'; import { adapter } from '@/lib/adapter';
@@ -291,36 +291,6 @@ const AgentsApp = ({ workspaces, activeWorkspaceId }: AgentsAppProps) => {
</div> </div>
</div> </div>
{/* Promoted swarm CTA (PR6b §16 / D19) — the waggle-dance entry,
surfaced as a prominent honey banner instead of a buried link.
Navigates to the existing /waggle-dance route. */}
<div className="px-4 pt-2.5">
<button
onClick={() => navigate('/waggle-dance')}
className="group w-full flex items-center gap-3 rounded-xl border px-3.5 py-2.5 text-left transition-colors"
style={{ background: 'var(--honey-wash)', borderColor: 'var(--honey-line)' }}
>
<span
className="grid place-items-center w-8 h-8 rounded-lg shrink-0"
style={{ background: 'var(--honey)', color: '#1a1407' }}
>
<Network className="w-4 h-4" />
</span>
<span className="flex-1 min-w-0">
<span className="block text-xs font-display font-semibold text-foreground">Run a team of agents</span>
<span className="block text-[11px] text-muted-foreground truncate">
waggle-dance · let several specialists coordinate on one goal
</span>
</span>
<span
className="inline-flex items-center gap-1 text-[11px] font-display font-semibold shrink-0"
style={{ color: 'var(--honey-text)' }}
>
Start a swarm <ArrowRight className="w-3.5 h-3.5 group-hover:translate-x-0.5 transition-transform" />
</span>
</button>
</div>
{/* List */} {/* List */}
<div id="agent-center-tab-panel" className="flex-1 overflow-auto p-2.5" role="tabpanel" aria-labelledby={`agent-center-tab-${tab}`}> <div id="agent-center-tab-panel" className="flex-1 overflow-auto p-2.5" role="tabpanel" aria-labelledby={`agent-center-tab-${tab}`}>
{/* A post-action reload failure must be visible even when a stale {/* A post-action reload failure must be visible even when a stale

View File

@@ -3,7 +3,7 @@
* Pins the contract: * Pins the contract:
* - renders a grid card per workspace (name + real stats) * - renders a grid card per workspace (name + real stats)
* - the search box filters by name * - the search box filters by name
* - the storage-type pills filter (All / Virtual / Local / Team) * - the storage-type pills filter (All / Virtual / Local)
* - a zero-workspace visit shows the create-first empty state (D16) * - a zero-workspace visit shows the create-first empty state (D16)
* - NO-FABRICATION: a workspace with undefined memoryCount renders NO memory * - NO-FABRICATION: a workspace with undefined memoryCount renders NO memory
* chip (W2B: not even a filler "—"), never an invented number (PR3/PR3.5) * chip (W2B: not even a filler "—"), never an invented number (PR3/PR3.5)

View File

@@ -80,7 +80,6 @@ const STORAGE_FILTERS: { id: StorageFilter; label: string; dot?: string }[] = [
{ id: 'all', label: 'All' }, { id: 'all', label: 'All' },
{ id: 'virtual', label: 'Virtual', dot: 'var(--intel)' }, { id: 'virtual', label: 'Virtual', dot: 'var(--intel)' },
{ id: 'local', label: 'Local', dot: 'var(--honey)' }, { id: 'local', label: 'Local', dot: 'var(--honey)' },
{ id: 'team', label: 'Team', dot: 'var(--healthy)' },
]; ];
/** Storage badge: Local=honey, Virtual=intel, Team=healthy (design §04). */ /** Storage badge: Local=honey, Virtual=intel, Team=healthy (design §04). */

View File

@@ -8,9 +8,8 @@
* 2. Grants — persistent "always allow" decisions. Revoke individually * 2. Grants — persistent "always allow" decisions. Revoke individually
* or clear the whole list. * or clear the whole list.
* *
* This is the trust control surface for enterprise buyers. Every decision * This is the trust control surface: every decision the user has made
* the user has made about agent autonomy lives here, visible and * about agent autonomy lives here, visible and reversible.
* reversible.
*/ */
import { useState, useEffect, useCallback } from 'react'; import { useState, useEffect, useCallback } from 'react';

View File

@@ -41,7 +41,7 @@ const CAPABILITY_MATRIX: ReadonlyArray<{ capability: string; marks: readonly Mar
{ capability: 'Self-evolving skills', marks: ['Y', 'N', 'N', 'N', 'P', 'N'] }, { capability: 'Self-evolving skills', marks: ['Y', 'N', 'N', 'N', 'P', 'N'] },
{ capability: 'Skills shared across agents/workspaces', marks: ['Y', 'P', 'P', 'N', 'P', 'N'] }, { capability: 'Skills shared across agents/workspaces', marks: ['Y', 'P', 'P', 'N', 'P', 'N'] },
{ capability: 'Multi-agent swarm', marks: ['Y', 'P', 'N', 'P', 'P', 'Y'] }, { capability: 'Multi-agent swarm', marks: ['Y', 'P', 'N', 'P', 'P', 'Y'] },
{ capability: 'Native desktop app · Win + Mac', marks: ['Y', 'N', 'N', 'P', 'N', 'N'] }, { capability: 'Native desktop app · Windows, macOS, Linux', marks: ['Y', 'N', 'N', 'P', 'N', 'N'] },
{ capability: 'Audit-ready / EU AI Act', marks: ['Y', 'P', 'P', 'P', 'N', 'N'] }, { capability: 'Audit-ready / EU AI Act', marks: ['Y', 'P', 'P', 'P', 'N', 'N'] },
{ capability: 'Deep coding in the terminal', marks: ['P', 'Y', 'Y', 'P', 'P', 'Y'] }, { capability: 'Deep coding in the terminal', marks: ['P', 'Y', 'Y', 'P', 'P', 'Y'] },
]; ];

View File

@@ -26,13 +26,6 @@ import {
import { useToast } from '@/hooks/use-toast'; import { useToast } from '@/hooks/use-toast';
import { DUR } from '@/lib/motion/tokens'; import { DUR } from '@/lib/motion/tokens';
export interface TeamMember {
id: string;
name: string;
status: string;
avatar?: string;
}
type AutonomyLevel = 'normal' | 'trusted' | 'yolo'; type AutonomyLevel = 'normal' | 'trusted' | 'yolo';
interface ChatAppProps { interface ChatAppProps {
@@ -49,7 +42,6 @@ interface ChatAppProps {
currentModel?: string; currentModel?: string;
onModelChange?: (model: string) => void; onModelChange?: (model: string) => void;
availableModels?: string[]; availableModels?: string[];
teamPresence?: TeamMember[];
sessions?: { id: string; title: string; messageCount?: number; lastActive?: string }[]; sessions?: { id: string; title: string; messageCount?: number; lastActive?: string }[];
activeSessionId?: string | null; activeSessionId?: string | null;
onSelectSession?: (id: string) => void; onSelectSession?: (id: string) => void;
@@ -557,7 +549,6 @@ const ChatApp = ({
messages, isLoading, onSendMessage, onClearHistory, messages, isLoading, onSendMessage, onClearHistory,
pendingApproval, onApprove, currentPersona, pendingApproval, onApprove, currentPersona,
onPersonaChange, currentModel, onModelChange, availableModels, onPersonaChange, currentModel, onModelChange, availableModels,
teamPresence,
sessions, activeSessionId, onSelectSession, onNewSession, sessions, activeSessionId, onSelectSession, onNewSession,
workspaceId, templateId, storageType, workspaceId, templateId, storageType,
autonomyLevel = 'normal', autonomyExpiresAt = null, onAutonomyChange, autonomyLevel = 'normal', autonomyExpiresAt = null, onAutonomyChange,
@@ -612,19 +603,12 @@ const ChatApp = ({
const modelPickerRef = useRef<HTMLDivElement>(null); const modelPickerRef = useRef<HTMLDivElement>(null);
// M-21 / UX-6: observe the agent strip (round-6 fix 1: relocated from the // M-21 / UX-6: observe the agent strip (round-6 fix 1: relocated from the
// deleted header row to the composer) to decide whether the informational // deleted header row to the composer) to decide whether the informational
// chips (storage badge, team presence) should fold into a ⋯ overflow menu. // chips (storage badge) should fold into a ⋯ overflow menu.
const stripRef = useRef<HTMLDivElement>(null); const stripRef = useRef<HTMLDivElement>(null);
const overflowRef = useRef<HTMLDivElement>(null); const overflowRef = useRef<HTMLDivElement>(null);
const stripWidth = useContainerWidth(stripRef); const stripWidth = useContainerWidth(stripRef);
const isStripCompact = shouldCollapseChatHeader(stripWidth); const isStripCompact = shouldCollapseChatHeader(stripWidth);
// R9 Lane D: presence is meaningful only for OTHER people in the room. The
// team endpoint returns the current user as `{ id: 'local', name: 'You' }`
// in solo/offline mode, which rendered as an anonymous floating 'Y' avatar on
// the composer strip. Drop the self entry so a lone user sees no presence chip
// and real teammates still surface.
const roomPresence = (teamPresence ?? []).filter(m => m.id !== 'local' && m.name !== 'You');
// M-28 / ENG-7: suggested next-actions extracted from the most // M-28 / ENG-7: suggested next-actions extracted from the most
// recent assistant message. Empty array → no chips. Hidden while // recent assistant message. Empty array → no chips. Hidden while
// the assistant is still streaming to avoid flickering chips as // the assistant is still streaming to avoid flickering chips as
@@ -1573,7 +1557,7 @@ const ChatApp = ({
</span> </span>
</HintTooltip> </HintTooltip>
{/* M-21 / UX-6: storage + team presence render inline at full {/* M-21 / UX-6: the storage badge renders inline at full
width, or behind a ⋯ overflow menu when the strip is too width, or behind a ⋯ overflow menu when the strip is too
narrow. Interactive controls (persona, autonomy, model) narrow. Interactive controls (persona, autonomy, model)
stay always visible. */} stay always visible. */}
@@ -1590,37 +1574,9 @@ const ChatApp = ({
</span> </span>
)} )}
{/* Team presence — round-7 fix 2b: the bare avatar chip was
unlabeled (a floating 'Y'), so the whole cluster is now one
strip pill with a native title naming who's here. */}
{!isStripCompact && roomPresence.length > 0 && (
<div
className={`${STRIP_PILL} px-1.5 text-muted-foreground`}
data-testid="chat-header-team-presence"
title={roomPresence.length === 1
? `${roomPresence[0].name} — active in this chat`
: `Active in this chat: ${roomPresence.map(m => m.name).join(', ')}`}
>
<div className="flex -space-x-1.5">
{roomPresence.slice(0, 4).map(m => (
<div key={m.id} className="relative">
<Avatar className="w-4 h-4 border border-card">
{m.avatar ? <AvatarImage src={m.avatar} /> : null}
<AvatarFallback className="text-[9px] bg-sky-500/20 text-sky-400">{m.name[0]}</AvatarFallback>
</Avatar>
<div className={`absolute -bottom-0.5 -right-0.5 w-1.5 h-1.5 rounded-full border border-card ${m.status === 'online' ? 'bg-emerald-400' : 'bg-muted-foreground'}`} />
</div>
))}
</div>
{roomPresence.length > 4 && (
<span>+{roomPresence.length - 4}</span>
)}
</div>
)}
{/* ⋯ overflow menu — only rendered in compact mode and only {/* ⋯ overflow menu — only rendered in compact mode and only
when there's at least one informational chip to show. */} when there's at least one informational chip to show. */}
{isStripCompact && (storageType || roomPresence.length > 0) && ( {isStripCompact && storageType && (
<div className="relative" ref={overflowRef}> <div className="relative" ref={overflowRef}>
<button <button
onClick={() => setShowHeaderOverflow(p => !p)} onClick={() => setShowHeaderOverflow(p => !p)}
@@ -1650,23 +1606,6 @@ const ChatApp = ({
</span> </span>
</div> </div>
)} )}
{roomPresence.length > 0 && (
<div className="px-1" data-testid="chat-header-team-presence">
<p className="text-[11px] font-display text-muted-foreground mb-1">In this room</p>
<div className="flex flex-wrap gap-1.5">
{roomPresence.map(m => (
<div key={m.id} className="flex items-center gap-1.5 text-[11px] text-foreground">
<Avatar className="w-4 h-4 border border-card">
{m.avatar ? <AvatarImage src={m.avatar} /> : null}
<AvatarFallback className="text-[10px] bg-sky-500/20 text-sky-400">{m.name[0]}</AvatarFallback>
</Avatar>
<span className="truncate max-w-[8ch]">{m.name}</span>
<span className={`w-1.5 h-1.5 rounded-full shrink-0 ${m.status === 'online' ? 'bg-emerald-400' : 'bg-muted-foreground'}`} />
</div>
))}
</div>
</div>
)}
</div> </div>
)} )}
</div> </div>
@@ -1674,7 +1613,7 @@ const ChatApp = ({
<div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1.5"> <div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1.5">
{/* Round-7 fix 2a: subtle divider between the context cluster {/* Round-7 fix 2a: subtle divider between the context cluster
(sessions · persona · Memory · presence) and the control (sessions · persona · Memory) and the control
cluster (autonomy · model · profile). */} cluster (autonomy · model · profile). */}
<span aria-hidden className="h-4 border-l border-[var(--line-soft)]" /> <span aria-hidden className="h-4 border-l border-[var(--line-soft)]" />
{/* Phase B.5: autonomy toggle — only render when the parent wired a handler */} {/* Phase B.5: autonomy toggle — only render when the parent wired a handler */}

View File

@@ -5,7 +5,6 @@ import { useToast } from '@/hooks/use-toast';
import { adapter } from '@/lib/adapter'; import { adapter } from '@/lib/adapter';
import { formatModelLabel } from '@/lib/model-label'; import { formatModelLabel } from '@/lib/model-label';
import ChatApp from './ChatApp'; import ChatApp from './ChatApp';
import type { TeamMember } from './ChatApp';
type AutonomyLevel = 'normal' | 'trusted' | 'yolo'; type AutonomyLevel = 'normal' | 'trusted' | 'yolo';
@@ -104,7 +103,6 @@ const ChatWindowInstance = ({
}); });
const [availableModels, setAvailableModels] = useState<string[]>([]); const [availableModels, setAvailableModels] = useState<string[]>([]);
const [teamPresence, setTeamPresence] = useState<TeamMember[]>([]);
const { toast } = useToast(); const { toast } = useToast();
@@ -202,25 +200,11 @@ const ChatWindowInstance = ({
if (!currentLanded) fetchCurrentModel(); if (!currentLanded) fetchCurrentModel();
}, 2000); }, 2000);
// Fetch team members for presence display
const fetchTeam = async () => {
try {
const members = await adapter.getTeamMembers();
if (cancelled) return;
setTeamPresence(members.filter(m => m.status === 'online'));
} catch (err) {
console.error('[ChatWindowInstance] fetch team failed:', err);
if (!cancelled) setTeamPresence([]);
}
};
fetchTeam();
const teamInterval = setInterval(fetchTeam, 10000);
const refreshModelsOnFocus = () => { void fetchModels(); }; const refreshModelsOnFocus = () => { void fetchModels(); };
window.addEventListener('focus', refreshModelsOnFocus); window.addEventListener('focus', refreshModelsOnFocus);
return () => { return () => {
cancelled = true; cancelled = true;
window.removeEventListener('focus', refreshModelsOnFocus); window.removeEventListener('focus', refreshModelsOnFocus);
clearInterval(teamInterval);
clearInterval(retryInterval); clearInterval(retryInterval);
}; };
}, []); }, []);
@@ -273,7 +257,6 @@ const ChatWindowInstance = ({
currentModel={currentModel} currentModel={currentModel}
onModelChange={handleModelChange} onModelChange={handleModelChange}
availableModels={availableModels} availableModels={availableModels}
teamPresence={teamPresence}
sessions={displaySessions} sessions={displaySessions}
activeSessionId={activeSessionId} activeSessionId={activeSessionId}
onSelectSession={setActiveSessionId} onSelectSession={setActiveSessionId}

View File

@@ -1,7 +1,7 @@
/** /**
* FilesAppTabs — P16 three-tab layout wrapper around FilesApp. * FilesAppTabs — P16 tab layout wrapper around FilesApp.
* *
* Adds a "Virtual | Local | Team" tab strip above the existing FilesApp * Adds a "Virtual | Local" tab strip above the existing FilesApp
* shell. Each tab remounts FilesApp with a different `storageType`; the * shell. Each tab remounts FilesApp with a different `storageType`; the
* remount intentionally resets per-storage navigation state (currentPath, * remount intentionally resets per-storage navigation state (currentPath,
* selection, preview) so flipping back to Virtual doesn't carry a local * selection, preview) so flipping back to Virtual doesn't carry a local

View File

@@ -7,6 +7,10 @@
* *
* These tests assert the toggle wiring and that Variation B carries the * These tests assert the toggle wiring and that Variation B carries the
* static explainer content WITHOUT fabricating a live recall. * static explainer content WITHOUT fabricating a live recall.
*
* Agent hooks, the explainer and Waggle Room tasks are hidden in v1 by the
* memory feature map (ADR-0002). Most suites switch them on to keep the hidden
* code covered; the "v1 memory features" suite checks the default.
*/ */
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, cleanup, fireEvent, within } from '@testing-library/react'; import { render, screen, waitFor, cleanup, fireEvent, within } from '@testing-library/react';
@@ -24,6 +28,9 @@ const mocks = vi.hoisted(() => ({
})); }));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() })); vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
const features = vi.hoisted(() => ({ enabled: true }));
vi.mock('@/lib/memory-features', () => ({ hasMemoryFeature: () => features.enabled }));
import LauncherApp, { resetLauncherRouteCache } from './LauncherApp'; import LauncherApp, { resetLauncherRouteCache } from './LauncherApp';
const detectionResp = { const detectionResp = {
@@ -43,6 +50,7 @@ const detectionResp = {
}; };
beforeEach(() => { beforeEach(() => {
features.enabled = true;
resetLauncherRouteCache(); resetLauncherRouteCache();
mocks.adapter.detectTools.mockResolvedValue(detectionResp); mocks.adapter.detectTools.mockResolvedValue(detectionResp);
mocks.adapter.getToolProcesses.mockResolvedValue({ processes: [] }); mocks.adapter.getToolProcesses.mockResolvedValue({ processes: [] });
@@ -670,3 +678,36 @@ describe('LauncherApp · hook cohort (#3)', () => {
expect(screen.queryByText(/hooks are not supported for Claude Desktop yet/i)).not.toBeInTheDocument(); expect(screen.queryByText(/hooks are not supported for Claude Desktop yet/i)).not.toBeInTheDocument();
}); });
}); });
describe('LauncherApp · v1 memory features (ADR-0002)', () => {
it('hides hook controls, the memory-sharing explainer and Room tasks; launch stays', async () => {
features.enabled = false;
mocks.adapter.detectTools.mockResolvedValue({
platform: 'darwin',
detectedAt: '2026-07-11T00:00:00.000Z',
tools: [
{
id: 'codex',
displayName: 'Codex CLI',
installed: true,
installedPath: '/usr/local/bin/codex',
version: '0.144.1',
hooksInstalled: true,
hookPointerPath: '/home/.codex/hooks',
capabilities: { interactiveLaunch: true, headlessTask: true, structuredProgress: true, resumable: true },
permissionModes: ['read-only', 'workspace-write', 'native'],
},
],
});
render(<LauncherApp />);
expect(await screen.findByText('Codex CLI')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /^launch$/i })).toBeInTheDocument();
expect(screen.queryByRole('tablist', { name: /launcher view/i })).not.toBeInTheDocument();
expect(screen.queryByText(/hooks active/i)).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /install hooks|uninstall hooks|^verify$/i })).not.toBeInTheDocument();
expect(screen.queryByText(/launch only|hook management is not supported/i)).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /run task/i })).not.toBeInTheDocument();
});
});

View File

@@ -30,6 +30,7 @@ import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area'; import { ScrollArea } from '@/components/ui/scroll-area';
import { adapter } from '@/lib/adapter'; import { adapter } from '@/lib/adapter';
import { hasMemoryFeature } from '@/lib/memory-features';
import { createSurfaceCache } from '@/lib/surface-cache'; import { createSurfaceCache } from '@/lib/surface-cache';
import { import {
promptArgsForTool, promptArgsForTool,
@@ -291,6 +292,10 @@ const hookActionDetails = (
const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: LauncherAppProps = {}) => { const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: LauncherAppProps = {}) => {
const [view, setView] = useState<LauncherView>('a'); const [view, setView] = useState<LauncherView>('a');
// ADR-0002: agent memory hooks and Waggle Room are hidden in v1 (memory
// feature map). Launch, watch and stop stay.
const hooksShown = hasMemoryFeature('agentHooks');
const roomShown = hasMemoryFeature('room');
const cachedDetection = launcherRouteCache.read('tools'); const cachedDetection = launcherRouteCache.read('tools');
const [detection, setDetection] = useState<DetectionResult | null>(cachedDetection ?? null); const [detection, setDetection] = useState<DetectionResult | null>(cachedDetection ?? null);
const [loading, setLoading] = useState(() => !launcherRouteCache.hasResolved('tools')); const [loading, setLoading] = useState(() => !launcherRouteCache.hasResolved('tools'));
@@ -596,6 +601,7 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
</Badge> </Badge>
)} )}
</div> </div>
{hooksShown && (
<div <div
role="tablist" role="tablist"
aria-label="Launcher view" aria-label="Launcher view"
@@ -617,6 +623,7 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
</button> </button>
))} ))}
</div> </div>
)}
{view === 'a' && ( {view === 'a' && (
<Button type="button" variant="ghost" size="sm" onClick={refresh} aria-label="Refresh installed tools" className="h-7 w-7 p-0 ml-auto"> <Button type="button" variant="ghost" size="sm" onClick={refresh} aria-label="Refresh installed tools" className="h-7 w-7 p-0 ml-auto">
<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} /> <RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
@@ -624,7 +631,7 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
)} )}
</div> </div>
{view === 'b' ? ( {view === 'b' && hooksShown ? (
<MemorySharingView /> <MemorySharingView />
) : ( ) : (
<> <>
@@ -746,8 +753,8 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
)} )}
{tools.map((tool) => { {tools.map((tool) => {
const launchable = toolCanLaunch(tool); const launchable = toolCanLaunch(tool);
const hooksSupported = HOOKS_COHORT.includes(tool.id); const hooksSupported = hooksShown && HOOKS_COHORT.includes(tool.id);
const launchOnly = launchable && !hooksSupported; const launchOnly = hooksShown && launchable && !hooksSupported;
const isActive = activeAction?.toolId === tool.id; const isActive = activeAction?.toolId === tool.id;
return ( return (
<div <div
@@ -769,7 +776,7 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
Not installed Not installed
</Badge> </Badge>
)} )}
{tool.hooksInstalled && tool.releaseStatus !== 'roadmap' && ( {hooksShown && tool.hooksInstalled && tool.releaseStatus !== 'roadmap' && (
<Badge variant="secondary" className="text-[10px] px-1.5 py-0 h-4" style={{ background: 'var(--honey-wash)', color: 'var(--honey)' }}> <Badge variant="secondary" className="text-[10px] px-1.5 py-0 h-4" style={{ background: 'var(--honey-wash)', color: 'var(--honey)' }}>
Hooks active Hooks active
</Badge> </Badge>
@@ -834,7 +841,7 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
)} )}
Launch Launch
</Button> </Button>
{toolCanRunCapturedTask(tool) && ( {roomShown && toolCanRunCapturedTask(tool) && (
<Button <Button
size="sm" size="sm"
variant="default" variant="default"
@@ -921,7 +928,7 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
: 'Hook management is not supported for this tool yet.'} : 'Hook management is not supported for this tool yet.'}
</div> </div>
)} )}
{taskToolId === tool.id && toolCanRunCapturedTask(tool) && ( {roomShown && taskToolId === tool.id && toolCanRunCapturedTask(tool) && (
<div <div
className="rounded-lg border border-primary/30 bg-primary/5 p-3 space-y-3" className="rounded-lg border border-primary/30 bg-primary/5 p-3 space-y-3"
data-testid={`captured-task-${tool.id}`} data-testid={`captured-task-${tool.id}`}

View File

@@ -14,6 +14,7 @@ import MemoryCenterTab from './memory/MemoryCenterTab';
import TimelineTab, { type TimelineTabProps } from './memory/TimelineTab'; import TimelineTab, { type TimelineTabProps } from './memory/TimelineTab';
import ImportReminderBanner from './memory/ImportReminderBanner'; import ImportReminderBanner from './memory/ImportReminderBanner';
import { useOnboarding } from '@/hooks/useOnboarding'; import { useOnboarding } from '@/hooks/useOnboarding';
import { hasMemoryFeature, isMemoryViewAvailable } from '@/lib/memory-features';
/** /**
* Memory Center (P3/D2) — the standalone memory surface (ArtifactCenterApp * Memory Center (P3/D2) — the standalone memory surface (ArtifactCenterApp
@@ -86,16 +87,22 @@ export interface MemoryCenterAppProps {
} }
const MemoryCenterApp = ({ const MemoryCenterApp = ({
mind, onMindChange, view, onViewChange, workspaceId, workspaceName, mind, onMindChange, view: requestedView, onViewChange, workspaceId, workspaceName,
timeline, knowledgeGraph, onRefreshKG, kgScope, onKGScopeChange, timeline, knowledgeGraph, onRefreshKG, kgScope, onKGScopeChange,
kgLoading = false, kgError = null, onContextRail, kgLoading = false, kgError = null, onContextRail,
}: MemoryCenterAppProps) => { }: MemoryCenterAppProps) => {
// Reminder-banner eligibility (carried over from the retired MemoryApp shell). // Reminder-banner eligibility (carried over from the retired MemoryApp shell).
const { state: onboardingState } = useOnboarding(); const { state: onboardingState } = useOnboarding();
// ADR-0002: views of hidden memory features (graph, imports, wiki) are not
// offered; a hidden view requested anyway falls back to the default.
const view: MemoryView = isMemoryViewAvailable(requestedView) ? requestedView : 'trust';
const primaryTabs = PRIMARY_TABS.filter((t) => isMemoryViewAvailable(t.id));
const advancedTabs = ADVANCED_TABS.filter((t) => isMemoryViewAvailable(t.id));
// Advanced flyout (display-level IA regroup): open state + active child. // Advanced flyout (display-level IA regroup): open state + active child.
const [advancedOpen, setAdvancedOpen] = useState(false); const [advancedOpen, setAdvancedOpen] = useState(false);
const activeAdvanced = ADVANCED_TABS.find((t) => t.id === view); const activeAdvanced = advancedTabs.find((t) => t.id === view);
// Lane HM (Pillar 1.1): the memory tab panel morphs between views (the // Lane HM (Pillar 1.1): the memory tab panel morphs between views (the
// Trust↔Memories pair especially) rather than hard-cutting — a keyed // Trust↔Memories pair especially) rather than hard-cutting — a keyed
@@ -104,11 +111,13 @@ const MemoryCenterApp = ({
return ( return (
<div className="flex flex-col h-full" data-testid="memory-center-app"> <div className="flex flex-col h-full" data-testid="memory-center-app">
<ImportReminderBanner {hasMemoryFeature('importHistory') && (
onboardingCompleted={onboardingState.completed} <ImportReminderBanner
totalFrameCount={timeline.stats.total} onboardingCompleted={onboardingState.completed}
onOpenHarvest={() => onViewChange('harvest')} totalFrameCount={timeline.stats.total}
/> onOpenHarvest={() => onViewChange('harvest')}
/>
)}
{/* Tab bar + mind scope — Wave T Lane D (item 4): the memory surface stacked {/* Tab bar + mind scope — Wave T Lane D (item 4): the memory surface stacked
THREE control tiers (tabs · mind pills · the Trust Manage/Why switch). THREE control tiers (tabs · mind pills · the Trust Manage/Why switch).
@@ -117,7 +126,7 @@ const MemoryCenterApp = ({
not three. Every destination is preserved; only the chrome collapses. */} not three. Every destination is preserved; only the chrome collapses. */}
<div className="flex flex-wrap items-center gap-y-1 border-b border-border/50 bg-background/60"> <div className="flex flex-wrap items-center gap-y-1 border-b border-border/50 bg-background/60">
<div role="tablist" aria-label="Memory views" className="flex min-w-0 flex-wrap items-center"> <div role="tablist" aria-label="Memory views" className="flex min-w-0 flex-wrap items-center">
{PRIMARY_TABS.map((tab, i) => { {primaryTabs.map((tab, i) => {
const Icon = tab.icon; const Icon = tab.icon;
const active = view === tab.id; const active = view === tab.id;
return ( return (
@@ -146,10 +155,11 @@ const MemoryCenterApp = ({
{/* Advanced — a flyout tab holding the maintenance/import views. The {/* Advanced — a flyout tab holding the maintenance/import views. The
trigger names the active child (e.g. "Advanced: Imports") so a trigger names the active child (e.g. "Advanced: Imports") so a
deep-linked ?tab=harvest never looks like no tab is selected. */} deep-linked ?tab=harvest never looks like no tab is selected. */}
{advancedTabs.length > 0 && (
<div className="flex items-center"> <div className="flex items-center">
<div className="w-px h-4 bg-border/60 mx-1" aria-hidden="true" /> <div className="w-px h-4 bg-border/60 mx-1" aria-hidden="true" />
<div className="relative"> <div className="relative">
<HintTooltip content="Imports, maintenance, and wiki"> <HintTooltip content={advancedTabs.map((t) => t.label).join(', ')}>
<button <button
role="tab" role="tab"
onClick={() => setAdvancedOpen(o => !o)} onClick={() => setAdvancedOpen(o => !o)}
@@ -178,7 +188,7 @@ const MemoryCenterApp = ({
data-testid="memory-tab-advanced-menu" data-testid="memory-tab-advanced-menu"
className="absolute left-0 top-full mt-1 z-50 w-56 bg-card border border-border rounded-xl shadow-xl overflow-hidden" className="absolute left-0 top-full mt-1 z-50 w-56 bg-card border border-border rounded-xl shadow-xl overflow-hidden"
> >
{ADVANCED_TABS.map((tab) => { {advancedTabs.map((tab) => {
const Icon = tab.icon; const Icon = tab.icon;
const active = view === tab.id; const active = view === tab.id;
return ( return (
@@ -204,6 +214,7 @@ const MemoryCenterApp = ({
)} )}
</div> </div>
</div> </div>
)}
</div> </div>
{/* Mind pills — folded onto the tab row (Wave T Lane D item 4). Only on {/* Mind pills — folded onto the tab row (Wave T Lane D item 4). Only on
@@ -277,9 +288,9 @@ const MemoryCenterApp = ({
<HarvestTab /> <HarvestTab />
) : view === 'weaver' ? ( ) : view === 'weaver' ? (
<WeaverPanel /> <WeaverPanel />
) : ( ) : view === 'wiki' ? (
<WikiTab /> <WikiTab />
)} ) : null}
</motion.div> </motion.div>
</div> </div>
</div> </div>

View File

@@ -37,7 +37,7 @@ const SPECS: ReadonlyArray<Spec> = [
{ value: '~12 MB', label: 'Install size' }, { value: '~12 MB', label: 'Install size' },
{ value: 'Local', label: 'Data on your disk' }, { value: 'Local', label: 'Data on your disk' },
{ value: 'Auto-update', label: 'Signed & notarized' }, { value: 'Auto-update', label: 'Signed & notarized' },
{ value: 'Win · Mac', label: 'Linux soon' }, { value: 'Win · Mac · Linux', label: 'Desktop platforms' },
]; ];
interface BootStep { interface BootStep {
@@ -67,7 +67,7 @@ const CHANNELS: ReadonlyArray<Channel> = [
icon: Monitor, icon: Monitor,
title: 'Desktop app', title: 'Desktop app',
blurb: 'The full hive — native, local, fast.', blurb: 'The full hive — native, local, fast.',
platforms: ['macOS', 'Windows', 'Linux soon'], platforms: ['macOS', 'Windows', 'Linux'],
status: 'now', status: 'now',
statusLabel: 'Available now', statusLabel: 'Available now',
tint: 'var(--honey-wash)', tint: 'var(--honey-wash)',
@@ -177,8 +177,8 @@ function DesktopView({ os, onOsChange }: DesktopViewProps) {
title={<>A real <em className="not-italic text-honey">desktop app.</em></>} title={<>A real <em className="not-italic text-honey">desktop app.</em></>}
blurb={ blurb={
<> <>
Waggle ships as a native app for <b className="text-[var(--text-2)]">Windows &amp; macOS</b> — built on Waggle runs as a native app on <b className="text-[var(--text-2)]">Windows, macOS and Linux</b>. It is
Tauri, so it&rsquo;s tiny, fast, and truly local. Your hive lives on your disk; the app just opens a built on Tauri, so it&rsquo;s tiny, fast, and truly local. Your hive lives on your disk; the app just opens a
window onto it. window onto it.
</> </>
} }

View File

@@ -24,6 +24,8 @@ import {
resolveActiveSettingsTab, resolveActiveSettingsTab,
} from '@/lib/settings-tier-filter'; } from '@/lib/settings-tier-filter';
import { requiresYoloConfirm } from '@/lib/autonomy-confirm'; import { requiresYoloConfirm } from '@/lib/autonomy-confirm';
import { hasAnalyticsKey, isAnalyticsAllowed, setAnalyticsConsent } from '@/lib/analytics-consent';
import { hasMemoryFeature } from '@/lib/memory-features';
import ModelSelector from '@/components/os/ModelSelector'; import ModelSelector from '@/components/os/ModelSelector';
import ModelPilotCard from '@/components/os/ModelPilotCard'; import ModelPilotCard from '@/components/os/ModelPilotCard';
import EmbeddingRoutingCard from '@/components/os/EmbeddingRoutingCard'; import EmbeddingRoutingCard from '@/components/os/EmbeddingRoutingCard';
@@ -137,8 +139,11 @@ const SettingsApp = () => {
// focus-visible, testable confirm row. // focus-visible, testable confirm row.
const [pendingYolo, setPendingYolo] = useState(false); const [pendingYolo, setPendingYolo] = useState(false);
// M2-7: Telemetry state // M2-7: Telemetry state. ADR-0006: when the build has a PostHog key, this one
const [telemetryEnabled, setTelemetryEnabled] = useState(false); // toggle is also the analytics consent switch, so it shows the stored consent
// and drives the local log and PostHog together.
const analyticsKey = hasAnalyticsKey();
const [telemetryEnabled, setTelemetryEnabled] = useState(() => analyticsKey && isAnalyticsAllowed());
// Phase 4.1: GDPR Art. 17 erasure flow. Visible at all tiers — erasure // Phase 4.1: GDPR Art. 17 erasure flow. Visible at all tiers — erasure
// can't be tier-gated. Dialog handles the typed-phrase confirmation gate // can't be tier-gated. Dialog handles the typed-phrase confirmation gate
// + presents the receipt + relaunch instruction on success. // + presents the receipt + relaunch instruction on success.
@@ -183,10 +188,10 @@ const SettingsApp = () => {
// .catch — a getTelemetryStatus rejection became an unhandled promise // .catch — a getTelemetryStatus rejection became an unhandled promise
// rejection (its siblings above all swallow). Match the local pattern. // rejection (its siblings above all swallow). Match the local pattern.
adapter.getTelemetryStatus().then(s => { adapter.getTelemetryStatus().then(s => {
setTelemetryEnabled(s.enabled); if (!analyticsKey) setTelemetryEnabled(s.enabled);
setTelemetryCount(s.totalEvents); setTelemetryCount(s.totalEvents);
}).catch(() => {}); }).catch(() => {});
}, []); }, [analyticsKey]);
const handleSaveModel = async () => { const handleSaveModel = async () => {
setSaving(true); setSaving(true);
@@ -432,28 +437,41 @@ const SettingsApp = () => {
{/* M2-7: Privacy & Telemetry — Phase 4.1: hidden at Essential per ux-disclosure-levels.md {/* M2-7: Privacy & Telemetry — Phase 4.1: hidden at Essential per ux-disclosure-levels.md
§"Settings at Essential" (telemetry surfaced only at Standard+, where the user is §"Settings at Essential" (telemetry surfaced only at Standard+, where the user is
already opting into more advanced surface area). */} already opting into more advanced surface area). ADR-0006: shown at every level
{userTier !== 'simple' && ( when the build has a PostHog key, so analytics consent can always be withdrawn. */}
{(userTier !== 'simple' || analyticsKey) && (
<div className="space-y-3"> <div className="space-y-3">
<h3 className="text-xs font-display font-semibold text-foreground flex items-center gap-2"> <h3 className="text-xs font-display font-semibold text-foreground flex items-center gap-2">
<BarChart3 className="w-3.5 h-3.5 text-muted-foreground" /> <BarChart3 className="w-3.5 h-3.5 text-muted-foreground" />
Privacy & Telemetry Privacy & Telemetry
</h3> </h3>
<p className="text-[11px] text-muted-foreground leading-relaxed"> {analyticsKey ? (
Help improve Waggle by tracking anonymous usage patterns. All data stays on your machine — nothing is sent to any server. No message content, file paths, or personal info is ever recorded. <p className="text-[11px] text-muted-foreground leading-relaxed">
</p> Usage analytics are off unless you turn them on. When on, Waggle keeps a usage log on this computer and sends one event to PostHog when you finish onboarding, with the template, persona and model you chose. Your chats, files and memories are never sent.
</p>
) : (
<p className="text-[11px] text-muted-foreground leading-relaxed">
Help improve Waggle by tracking anonymous usage patterns. All data stays on your machine — nothing is sent to any server. No message content, file paths, or personal info is ever recorded.
</p>
)}
<div className="flex items-center justify-between p-3 rounded-xl bg-secondary/30 border border-border/30"> <div className="flex items-center justify-between p-3 rounded-xl bg-secondary/30 border border-border/30">
<div> <div>
<p className="text-xs font-display font-medium text-foreground">Enable anonymous telemetry</p> <p className="text-xs font-display font-medium text-foreground">
{analyticsKey ? 'Share anonymous usage analytics' : 'Enable anonymous telemetry'}
</p>
<p className="text-[11px] text-muted-foreground">{telemetryCount} events collected</p> <p className="text-[11px] text-muted-foreground">{telemetryCount} events collected</p>
</div> </div>
<button <button
type="button" type="button"
aria-label={telemetryEnabled ? 'Disable anonymous telemetry' : 'Enable anonymous telemetry'} aria-label={analyticsKey
? (telemetryEnabled ? 'Disable anonymous usage analytics' : 'Enable anonymous usage analytics')
: (telemetryEnabled ? 'Disable anonymous telemetry' : 'Enable anonymous telemetry')}
aria-pressed={telemetryEnabled} aria-pressed={telemetryEnabled}
onClick={async () => { onClick={async () => {
const next = !telemetryEnabled; const next = !telemetryEnabled;
setTelemetryEnabled(next); setTelemetryEnabled(next);
// Store the consent first: capture stops before any await.
if (analyticsKey) void setAnalyticsConsent(next ? 'granted' : 'denied');
await adapter.toggleTelemetry(next); await adapter.toggleTelemetry(next);
}} }}
className={`relative w-10 h-5 rounded-full transition-colors ${telemetryEnabled ? 'bg-primary' : 'bg-muted'}`} className={`relative w-10 h-5 rounded-full transition-colors ${telemetryEnabled ? 'bg-primary' : 'bg-muted'}`}
@@ -498,7 +516,7 @@ const SettingsApp = () => {
Danger Zone · Erase All Data Danger Zone · Erase All Data
</h3> </h3>
<p className="text-[11px] text-muted-foreground leading-relaxed"> <p className="text-[11px] text-muted-foreground leading-relaxed">
Schedule a complete wipe of every memory frame, workspace, session, vault entry, and config file in your data dir. The wipe runs at next launch and is unrecoverable from the app — keep a recent <span className="font-mono">.waggle-backup</span> if you might want to restore. Data already sent to cloud providers or Teams servers is not erased — handle those separately per the data-handling policy. Schedule a complete wipe of every memory frame, workspace, session, vault entry, and config file in your data dir. The wipe runs at next launch and is unrecoverable from the app — keep a recent <span className="font-mono">.waggle-backup</span> if you might want to restore. Data already sent to cloud model providers is not erased. Ask those providers to delete it.
</p> </p>
<button <button
onClick={() => setShowEraseDialog(true)} onClick={() => setShowEraseDialog(true)}
@@ -769,6 +787,7 @@ const SettingsApp = () => {
<p className="text-[11px] text-muted-foreground">Download all workspaces, sessions, and memory as a zip</p> <p className="text-[11px] text-muted-foreground">Download all workspaces, sessions, and memory as a zip</p>
</div> </div>
</button> </button>
{hasMemoryFeature('importHistory') && (
<button className="flex items-center gap-2 w-full p-3 rounded-xl bg-secondary/30 border border-border/30 text-left hover:bg-secondary/50 transition-colors"> <button className="flex items-center gap-2 w-full p-3 rounded-xl bg-secondary/30 border border-border/30 text-left hover:bg-secondary/50 transition-colors">
<Upload className="w-4 h-4 text-honey" /> <Upload className="w-4 h-4 text-honey" />
<div> <div>
@@ -776,6 +795,7 @@ const SettingsApp = () => {
<p className="text-[11px] text-muted-foreground">Import from ChatGPT or Claude export</p> <p className="text-[11px] text-muted-foreground">Import from ChatGPT or Claude export</p>
</div> </div>
</button> </button>
)}
{/* Encrypted Backup/Restore */} {/* Encrypted Backup/Restore */}
<div className="pt-4 border-t border-border/30"> <div className="pt-4 border-t border-border/30">

View File

@@ -19,7 +19,7 @@
* Source fidelity: docs/design_handoff_waggle_app/design-files/screens/storage.html (view-a) * Source fidelity: docs/design_handoff_waggle_app/design-files/screens/storage.html (view-a)
*/ */
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { Cloud, HardDrive, Server, ShieldCheck, Folder, FileText, Loader2 } from 'lucide-react'; import { Cloud, HardDrive, ShieldCheck, Folder, FileText, Loader2 } from 'lucide-react';
import type { ElementType } from 'react'; import type { ElementType } from 'react';
import type { FileEntry, StorageType, Workspace } from '@/lib/types'; import type { FileEntry, StorageType, Workspace } from '@/lib/types';
import { adapter } from '@/lib/adapter'; import { adapter } from '@/lib/adapter';
@@ -66,16 +66,6 @@ const STORAGE_TYPE_CARDS: readonly StorageTypeCard[] = [
accent: 'var(--honey)', accent: 'var(--honey)',
wash: 'var(--honey-wash)', wash: 'var(--honey-wash)',
}, },
{
type: 'team',
icon: Server,
title: 'Team',
where: 'shared, synced',
blurb: 'A shared memory + file space for a team — same workspace, role-based access, synced across seats.',
privacy: 'Shared with team',
accent: 'var(--healthy)',
wash: 'var(--healthy-wash)',
},
]; ];
const STORAGE_LIVE_LABEL: Record<StorageType, string> = { const STORAGE_LIVE_LABEL: Record<StorageType, string> = {
@@ -246,12 +236,12 @@ const StorageApp = ({ workspaceId, workspaceName, workspace }: StorageAppProps)
)} )}
</section> </section>
{/* Three ways a workspace can live */} {/* Two ways a workspace can live */}
<div className="font-mono text-[11px] uppercase tracking-[0.12em] text-muted-foreground mt-[30px] mb-3.5 flex items-center gap-2.5"> <div className="font-mono text-[11px] uppercase tracking-[0.12em] text-muted-foreground mt-[30px] mb-3.5 flex items-center gap-2.5">
Three ways a workspace can live Two ways a workspace can live
<span className="flex-1 h-px" style={{ background: 'var(--line-soft)' }} aria-hidden="true" /> <span className="flex-1 h-px" style={{ background: 'var(--line-soft)' }} aria-hidden="true" />
</div> </div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-3.5"> <div className="grid grid-cols-1 md:grid-cols-2 gap-3.5">
{STORAGE_TYPE_CARDS.map(card => { {STORAGE_TYPE_CARDS.map(card => {
const active = card.type === storageType; const active = card.type === storageType;
const Icon = card.icon; const Icon = card.icon;

View File

@@ -1,44 +0,0 @@
import { Shield, Lock, Users, Crown } from 'lucide-react';
const TeamGovernanceApp = () => {
return (
<div className="flex flex-col items-center justify-center h-full text-center p-8">
<div className="relative mb-4">
<Shield className="w-12 h-12 text-muted-foreground/20" />
<Lock className="w-5 h-5 text-honey absolute -bottom-1 -right-1" />
</div>
<h2 className="text-lg font-display font-semibold text-foreground mb-2">Team Governance</h2>
<p className="text-sm text-muted-foreground max-w-xs mb-4">
Fine-grained permissions, role-based access, and audit controls for your team.
</p>
<div className="space-y-2 text-left w-full max-w-xs">
<div className="flex items-center gap-3 p-3 rounded-lg bg-muted/20 border border-border/30">
<Users className="w-4 h-4 text-sky-400 shrink-0" />
<div>
<p className="text-xs font-display text-foreground">Role-Based Access</p>
<p className="text-[11px] text-muted-foreground">Owner, Admin, Member, Viewer</p>
</div>
</div>
<div className="flex items-center gap-3 p-3 rounded-lg bg-muted/20 border border-border/30">
<Shield className="w-4 h-4 text-amber-400 shrink-0" />
<div>
<p className="text-xs font-display text-foreground">Tool Governance</p>
<p className="text-[11px] text-muted-foreground">Per-role tool allow/deny lists</p>
</div>
</div>
<div className="flex items-center gap-3 p-3 rounded-lg bg-muted/20 border border-border/30">
<Crown className="w-4 h-4 text-violet-400 shrink-0" />
<div>
<p className="text-xs font-display text-foreground">Audit Trail</p>
<p className="text-[11px] text-muted-foreground">Full action history per member</p>
</div>
</div>
</div>
<div className="mt-6 px-4 py-2 rounded-xl bg-primary/10 border border-primary/30">
<p className="text-xs font-display text-honey">Available on Teams ($49/mo per seat) and Enterprise tiers</p>
</div>
</div>
);
};
export default TeamGovernanceApp;

View File

@@ -7,6 +7,7 @@ import {
} from 'lucide-react'; } from 'lucide-react';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { adapter } from '@/lib/adapter'; import { adapter } from '@/lib/adapter';
import { hasMemoryFeature } from '@/lib/memory-features';
interface IdentitySuggestion { interface IdentitySuggestion {
field: 'name' | 'role' | 'company' | 'industry' | 'bio'; field: 'name' | 'role' | 'company' | 'industry' | 'bio';
@@ -272,7 +273,7 @@ const UserProfileApp = () => {
so the user sees "here's what we learned" before seeing the so the user sees "here's what we learned" before seeing the
blank inputs. Each row: label + value + confidence dot + blank inputs. Each row: label + value + confidence dot +
accept / dismiss. Block auto-hides when all are handled. */} accept / dismiss. Block auto-hides when all are handled. */}
{suggestions.length > 0 && ( {hasMemoryFeature('importHistory') && suggestions.length > 0 && (
<div className="rounded-xl bg-accent/10 border border-accent/30 p-3 space-y-2"> <div className="rounded-xl bg-accent/10 border border-accent/30 p-3 space-y-2">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Sparkles className="w-3.5 h-3.5 text-accent" /> <Sparkles className="w-3.5 h-3.5 text-accent" />

View File

@@ -1,209 +0,0 @@
import { useMemo, useState } from 'react';
import { Zap, Eye, ArrowRightLeft, Lightbulb, AlertTriangle, Radio, RefreshCw, Check, Send } from 'lucide-react';
import { useWaggleDance } from '@/hooks/useWaggleDance';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import type { WaggleSignal } from '@/lib/types';
import { sortSignalsForDisplay } from '@/lib/waggle-signals';
import { DATE_LOCALE } from '@/lib/date-locale';
type TypeConfigEntry = { icon: React.ElementType; color: string; label: string };
const typeConfig: Record<WaggleSignal['type'], TypeConfigEntry> = {
discovery: { icon: Eye, color: 'text-amber-400', label: 'Discovery' },
handoff: { icon: ArrowRightLeft, color: 'text-sky-400', label: 'Handoff' },
insight: { icon: Lightbulb, color: 'text-emerald-400', label: 'Insight' },
alert: { icon: AlertTriangle, color: 'text-rose-400', label: 'Alert' },
coordination: { icon: Radio, color: 'text-violet-400', label: 'Coordination' },
};
const FALLBACK_TYPE_CONFIG: TypeConfigEntry = {
icon: Zap,
color: 'text-muted-foreground',
label: 'Activity',
};
function getTypeConfig(type: string): TypeConfigEntry {
const known = (typeConfig as Record<string, TypeConfigEntry>)[type];
return known ?? { ...FALLBACK_TYPE_CONFIG, label: type };
}
const filterTypes: (WaggleSignal['type'] | 'all')[] = ['all', 'discovery', 'handoff', 'insight', 'alert', 'coordination'];
const WaggleDanceApp = () => {
const { signals, allSignals, loading, error, filter, setFilter, refresh, acknowledge } = useWaggleDance();
const [selectedSignal, setSelectedSignal] = useState<WaggleSignal | null>(null);
// M-41 / P18 — unacknowledged first, severity desc, then recency.
const orderedSignals = useMemo(() => sortSignalsForDisplay(signals), [signals]);
const unacknowledgedCount = allSignals.filter(s => !s.acknowledged).length;
return (
<div className="flex flex-col h-full bg-background text-foreground">
{/* Header */}
<div className="flex items-center justify-between px-3 py-2 border-b border-border/50">
<div className="flex items-center gap-2">
<Zap className="w-4 h-4 text-amber-400" />
<span className="text-sm font-display font-semibold">Waggle Dance</span>
{unacknowledgedCount > 0 && (
<Badge data-testid="waggle-unacknowledged-count" variant="destructive" className="text-[11px] px-1.5 py-0 h-4">
{unacknowledgedCount}
</Badge>
)}
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={refresh}
aria-label="Refresh Waggle Dance"
className="h-7 w-7 p-0"
>
<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
</Button>
</div>
{/* Filter tabs */}
<div className="flex gap-1 px-3 py-1.5 border-b border-border/30 overflow-x-auto">
{filterTypes.map(t => {
const cfg = t === 'all' ? null : typeConfig[t];
const Icon = cfg?.icon;
return (
<button
key={t}
onClick={() => setFilter(t)}
className={`flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium transition-colors whitespace-nowrap
${filter === t ? 'bg-primary/20 text-honey' : 'text-muted-foreground hover:bg-muted/50'}`}
>
{Icon && <Icon className={`w-3 h-3 ${cfg!.color}`} />}
{t === 'all' ? 'All' : cfg!.label}
</button>
);
})}
</div>
{/* Content */}
<div className="flex flex-1 min-h-0">
{/* Signal list */}
<ScrollArea className={`${selectedSignal ? 'w-1/2 border-r border-border/30' : 'w-full'}`}>
<div className="p-2 space-y-1">
{loading && signals.length === 0 && (
<div className="text-xs text-muted-foreground text-center py-8">Loading signals…</div>
)}
{/* P7/D15 B5: the hook already tracks `error` — a load failure must
not masquerade as "no signals yet". */}
{!loading && error && signals.length === 0 && (
<div role="alert" className="flex flex-col items-center gap-2 py-8 text-muted-foreground">
<Zap className="w-8 h-8 text-destructive/50" />
<p className="text-xs text-foreground">Couldn't load signals</p>
<p className="text-[11px] opacity-70 max-w-xs text-center">The Waggle Dance feed is unreachable — this is a load error, not an empty feed.</p>
<button onClick={refresh} className="mt-1 text-[11px] px-3 py-1 rounded-lg bg-primary/10 text-honey hover:bg-primary/20 transition-colors">Retry</button>
</div>
)}
{!loading && !error && signals.length === 0 && (
<div className="flex flex-col items-center gap-2 py-8 text-muted-foreground">
<Zap className="w-8 h-8 opacity-30" />
<p className="text-xs">No waggle dance signals yet</p>
<p className="text-[11px] opacity-70">Signals appear when agents share findings across workspaces</p>
</div>
)}
{orderedSignals.map(signal => {
const cfg = getTypeConfig(signal.type);
const Icon = cfg.icon;
const isSelected = selectedSignal?.id === signal.id;
return (
<button
key={signal.id}
onClick={() => setSelectedSignal(isSelected ? null : signal)}
className={`w-full text-left p-2.5 rounded-lg transition-colors group
${isSelected ? 'bg-primary/10 ring-1 ring-primary/30' : 'hover:bg-muted/50'}
${!signal.acknowledged ? 'border-l-2 border-l-primary/60' : 'border-l-2 border-l-transparent'}`}
>
<div className="flex items-start gap-2">
<Icon className={`w-4 h-4 mt-0.5 ${cfg.color} shrink-0`} />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5">
<span className="text-xs font-semibold truncate">{signal.title}</span>
{signal.priority === 'critical' && (
<Badge data-testid="waggle-critical-priority" variant="destructive" className="text-[11px] px-1 py-0 h-3.5">CRITICAL</Badge>
)}
{signal.priority === 'high' && (
<Badge className="text-[11px] px-1 py-0 h-3.5 bg-amber-500/20 text-foreground border-amber-500/40">HIGH</Badge>
)}
</div>
<p className="text-[11px] text-muted-foreground line-clamp-2 mt-0.5">{signal.content}</p>
<div className="flex items-center gap-2 mt-1">
<span className="text-[11px] text-muted-foreground/70">
{signal.sourceWorkspaceName || signal.sourceWorkspaceId}
</span>
{signal.sourceUser && (
<span className="text-[11px] text-muted-foreground/70">· {signal.sourceUser}</span>
)}
<span className="ml-auto text-[11px] text-muted-foreground">
{new Date(signal.timestamp).toLocaleTimeString(DATE_LOCALE, { hour: '2-digit', minute: '2-digit' })}
</span>
</div>
</div>
</div>
</button>
);
})}
</div>
</ScrollArea>
{/* Detail pane */}
{selectedSignal && (
<div className="w-1/2 flex flex-col">
<div className="p-3 flex-1 overflow-auto">
<div className="flex items-center gap-2 mb-2">
{(() => {
const cfg = getTypeConfig(selectedSignal.type);
const Icon = cfg.icon;
return <Icon className={`w-5 h-5 ${cfg.color}`} />;
})()}
<Badge variant="outline" className="text-[11px]">{getTypeConfig(selectedSignal.type).label}</Badge>
{selectedSignal.priority && selectedSignal.priority !== 'normal' && selectedSignal.priority !== 'low' && (
<Badge variant={selectedSignal.priority === 'critical' ? 'destructive' : 'outline'} className="text-[11px]">
{selectedSignal.priority.toUpperCase()}
</Badge>
)}
</div>
<h3 className="text-sm font-semibold mb-1">{selectedSignal.title}</h3>
<p className="text-xs text-muted-foreground mb-3">{selectedSignal.content}</p>
<div className="space-y-1.5 text-[11px] text-muted-foreground">
<div><span className="text-foreground/70">Source:</span> {selectedSignal.sourceWorkspaceName || selectedSignal.sourceWorkspaceId}</div>
{selectedSignal.sourceUser && <div><span className="text-foreground/70">User:</span> {selectedSignal.sourceUser}</div>}
{selectedSignal.sourceAgentId && <div><span className="text-foreground/70">Agent:</span> {selectedSignal.sourceAgentId}</div>}
{selectedSignal.targetWorkspaceId && <div><span className="text-foreground/70">Target:</span> {selectedSignal.targetWorkspaceId}</div>}
<div><span className="text-foreground/70">Time:</span> {new Date(selectedSignal.timestamp).toLocaleString(DATE_LOCALE)}</div>
</div>
{selectedSignal.metadata && Object.keys(selectedSignal.metadata).length > 0 && (
<div className="mt-3">
<p className="text-[11px] uppercase tracking-wider text-[var(--text-tertiary)] mb-1">Metadata</p>
<pre className="text-[11px] bg-muted/30 rounded p-2 overflow-auto max-h-32">
{JSON.stringify(selectedSignal.metadata, null, 2)}
</pre>
</div>
)}
</div>
<div className="p-2 border-t border-border/30 flex gap-2">
{!selectedSignal.acknowledged && (
<Button size="sm" variant="outline" className="text-xs h-7" onClick={() => acknowledge(selectedSignal.id)}>
<Check className="w-3 h-3 mr-1" /> Acknowledge
</Button>
)}
<Button size="sm" variant="ghost" className="text-xs h-7 ml-auto" onClick={() => setSelectedSignal(null)}>
Close
</Button>
</div>
</div>
)}
</div>
</div>
);
};
export default WaggleDanceApp;

View File

@@ -19,7 +19,7 @@ import type { AgentType, AutonomyLevel, ConnectorDefinition, Scope } from '@wagg
* before Create. Elevated selections (connectors / MCP servers) route * before Create. Elevated selections (connectors / MCP servers) route
* through the ApprovalModal before the create fires (§17.3). * through the ApprovalModal before the create fires (§17.3).
* *
* Create is FREE-tier (no gate — agents generate memory, CLAUDE.md §1). * Create has no gate: agents generate memory.
* v1 deliberate omissions (rendered honestly, not silently): * v1 deliberate omissions (rendered honestly, not silently):
* - no per-tool grants — tools derive from persona + skills (the create * - no per-tool grants — tools derive from persona + skills (the create
* contract carries no tools field); * contract carries no tools field);

View File

@@ -2,8 +2,8 @@ import { describe, it, expect } from 'vitest';
import { initialTabFor, FILES_TAB_ORDER } from './files-tabs'; import { initialTabFor, FILES_TAB_ORDER } from './files-tabs';
describe('FILES_TAB_ORDER', () => { describe('FILES_TAB_ORDER', () => {
it('is virtual → local → team in that order', () => { it('is virtual → local in that order (no Team tab, ADR-0003)', () => {
expect(FILES_TAB_ORDER).toEqual(['virtual', 'local', 'team']); expect(FILES_TAB_ORDER).toEqual(['virtual', 'local']);
}); });
}); });
@@ -11,7 +11,10 @@ describe('initialTabFor', () => {
it("returns the workspace's configured storageType when it's one of the known tabs", () => { it("returns the workspace's configured storageType when it's one of the known tabs", () => {
expect(initialTabFor('virtual')).toBe('virtual'); expect(initialTabFor('virtual')).toBe('virtual');
expect(initialTabFor('local')).toBe('local'); expect(initialTabFor('local')).toBe('local');
expect(initialTabFor('team')).toBe('team'); });
it("opens a legacy team workspace on 'virtual'", () => {
expect(initialTabFor('team')).toBe('virtual');
}); });
it("falls back to 'virtual' when storageType is undefined", () => { it("falls back to 'virtual' when storageType is undefined", () => {

View File

@@ -10,16 +10,15 @@ import type { StorageType } from '@/lib/types';
* through. See FilesAppTabs.tsx for the key-based remount. * through. See FilesAppTabs.tsx for the key-based remount.
*/ */
export const FILES_TAB_ORDER: StorageType[] = ['virtual', 'local', 'team']; export const FILES_TAB_ORDER: StorageType[] = ['virtual', 'local'];
/** /**
* Pick the initial tab for the Files app when it opens. Preference order: * Pick the initial tab for the Files app when it opens. Preference order:
* 1. The workspace's configured storageType (if set) * 1. The workspace's configured storageType (if set)
* 2. 'virtual' — always available, safe default * 2. 'virtual' — always available, safe default
* *
* 'team' would be valid in the config but we never default to it on open * A legacy 'team' workspace opens on 'virtual': team storage needs a team
* because a team workspace without a connected team server has nothing to * server, and team mode is not part of the community edition (ADR-0003).
* show; the tab strip lets the user switch manually.
*/ */
export function initialTabFor( export function initialTabFor(
configured: StorageType | undefined, configured: StorageType | undefined,

View File

@@ -0,0 +1,83 @@
/**
* AnalyticsConsentDialog — the first-run analytics question (ADR-0006).
*
* AppShell mounts it only when the build carries a PostHog key and the user
* has not chosen yet (`shouldAskAnalyticsConsent`). "Allow" and "Don't allow"
* store the choice. Escape closes the dialog without storing anything: nothing
* is sent, and the question comes back on the next launch.
*
* The list of what is sent mirrors the events in `@/lib/posthog`.
*/
import { BarChart3 } from 'lucide-react';
import { adapter } from '@/lib/adapter';
import { setAnalyticsConsent, type AnalyticsConsent } from '@/lib/analytics-consent';
import { useFocusTrap } from '@/hooks/useFocusTrap';
interface AnalyticsConsentDialogProps {
/** Called after a choice is made or the dialog is dismissed. */
onClose: () => void;
}
const buttonClass =
'px-4 py-2 rounded-xl border border-border/50 bg-secondary/40 text-sm font-display font-semibold text-foreground hover:bg-secondary/70 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/60';
export default function AnalyticsConsentDialog({ onClose }: AnalyticsConsentDialogProps) {
const dialogRef = useFocusTrap<HTMLDivElement>(true, onClose);
const choose = (choice: AnalyticsConsent) => {
void setAnalyticsConsent(choice);
// The Settings toggle drives the local usage log and PostHog together;
// keep the local log in step with this first answer.
void adapter.toggleTelemetry(choice === 'granted').catch(() => {});
onClose();
};
return (
<div className="fixed inset-0 z-[220] flex items-center justify-center p-4">
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm" aria-hidden="true" />
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-labelledby="analytics-consent-title"
aria-describedby="analytics-consent-description"
tabIndex={-1}
className="relative w-full max-w-md glass-strong rounded-2xl shadow-2xl p-6 space-y-4 focus:outline-none"
data-testid="analytics-consent-dialog"
>
<div className="flex items-center gap-3">
<div className="p-2 rounded-xl bg-primary/10">
<BarChart3 className="w-5 h-5 text-honey" aria-hidden="true" />
</div>
<h2 id="analytics-consent-title" className="text-lg font-display font-bold text-foreground">
Share anonymous usage analytics?
</h2>
</div>
<div id="analytics-consent-description" className="space-y-2 text-xs text-muted-foreground leading-relaxed">
<p>
Waggle can send a small amount of usage data to PostHog to help improve the app.
Nothing is sent unless you choose Allow.
</p>
<p className="text-foreground font-medium">What is sent:</p>
<ul className="list-disc pl-4 space-y-1">
<li>One event when you finish onboarding, with the template, persona and model you chose.</li>
<li>A random ID for this install and the browser details PostHog adds, such as browser, operating system and screen size.</li>
</ul>
<p>Your chats, files and memories are never sent.</p>
<p>You can change this later in Settings, under Privacy &amp; Telemetry.</p>
</div>
<div className="flex items-center justify-end gap-3 pt-1">
<button type="button" onClick={() => choose('denied')} className={buttonClass}>
Don't allow
</button>
<button type="button" onClick={() => choose('granted')} className={buttonClass}>
Allow
</button>
</div>
</div>
</div>
);
}

View File

@@ -1,6 +1,6 @@
import { useState, useCallback, useEffect, useRef } from 'react'; import { useState, useCallback, useEffect, useRef } from 'react';
import { import {
X, Plus, Users, Cloud, HardDrive, Server, FolderOpen, Folder, X, Plus, Users, Cloud, HardDrive, FolderOpen, Folder,
FolderPlus, ChevronRight, Home, Check, Loader2, LayoutTemplate, FolderPlus, ChevronRight, Home, Check, Loader2, LayoutTemplate,
Sparkles, Info, Wand2, Target, Microscope, Code, Megaphone, Sparkles, Info, Wand2, Target, Microscope, Code, Megaphone,
Rocket, Scale, Building, FileText, Laptop, PenLine, BarChart3, Rocket, Scale, Building, FileText, Laptop, PenLine, BarChart3,
@@ -43,7 +43,7 @@ interface CreateWorkspaceDialogProps {
open: boolean; open: boolean;
onClose: () => void; onClose: () => void;
onCreate: (data: { onCreate: (data: {
name: string; group: string; persona?: string; agentGroupId?: string; shared?: boolean; name: string; group: string; persona?: string; agentGroupId?: string;
storageType?: StorageType; storagePath?: string; templateId?: string; storageType?: StorageType; storagePath?: string; templateId?: string;
}) => void; }) => void;
} }
@@ -54,7 +54,6 @@ const GROUPS = [...STANDARD_GROUPS];
const STORAGE_OPTIONS: { type: StorageType; label: string; desc: string; icon: React.ElementType; color: string }[] = [ const STORAGE_OPTIONS: { type: StorageType; label: string; desc: string; icon: React.ElementType; color: string }[] = [
{ type: 'virtual', label: 'Virtual', desc: 'Server-managed storage', icon: Cloud, color: 'text-violet-400' }, { type: 'virtual', label: 'Virtual', desc: 'Server-managed storage', icon: Cloud, color: 'text-violet-400' },
{ type: 'local', label: 'Local', desc: 'Local disk directory', icon: HardDrive, color: 'text-emerald-400' }, { type: 'local', label: 'Local', desc: 'Local disk directory', icon: HardDrive, color: 'text-emerald-400' },
{ type: 'team', label: 'Team', desc: 'Remote S3/MinIO storage', icon: Server, color: 'text-sky-400' },
]; ];
/** Icon map for known template IDs */ /** Icon map for known template IDs */
@@ -730,7 +729,6 @@ const CreateWorkspaceDialog = ({ open, onClose, onCreate }: CreateWorkspaceDialo
const [name, setName] = useState(''); const [name, setName] = useState('');
const [group, setGroup] = useState('Personal'); const [group, setGroup] = useState('Personal');
const [selectedPersona, setSelectedPersona] = useState<string | undefined>(); const [selectedPersona, setSelectedPersona] = useState<string | undefined>();
const [shared, setShared] = useState(false);
const [storageType, setStorageType] = useState<StorageType>('virtual'); const [storageType, setStorageType] = useState<StorageType>('virtual');
const [storagePath, setStoragePath] = useState(''); const [storagePath, setStoragePath] = useState('');
const [showFolderPicker, setShowFolderPicker] = useState(false); const [showFolderPicker, setShowFolderPicker] = useState(false);
@@ -801,11 +799,10 @@ const CreateWorkspaceDialog = ({ open, onClose, onCreate }: CreateWorkspaceDialo
name: name.trim(), group, name: name.trim(), group,
persona: agentMode === 'single' ? selectedPersona : undefined, persona: agentMode === 'single' ? selectedPersona : undefined,
agentGroupId: agentMode === 'group' ? selectedGroupId : undefined, agentGroupId: agentMode === 'group' ? selectedGroupId : undefined,
shared,
storageType, storagePath: storagePath.trim() || undefined, storageType, storagePath: storagePath.trim() || undefined,
templateId: selectedTemplate || undefined, templateId: selectedTemplate || undefined,
}); });
setName(''); setGroup('Personal'); setSelectedPersona(undefined); setShared(false); setName(''); setGroup('Personal'); setSelectedPersona(undefined);
setStorageType('virtual'); setStoragePath(''); setSelectedTemplate(null); setStorageType('virtual'); setStoragePath(''); setSelectedTemplate(null);
setShowTemplateOptions(false); setTemplateSearch(''); setCategoryFilter('all'); setShowAgentOptions(false); setShowTemplateOptions(false); setTemplateSearch(''); setCategoryFilter('all'); setShowAgentOptions(false);
setAgentMode('single'); setSelectedGroupId(undefined); setAgentMode('single'); setSelectedGroupId(undefined);
@@ -1105,7 +1102,7 @@ const CreateWorkspaceDialog = ({ open, onClose, onCreate }: CreateWorkspaceDialo
{/* ── Storage Type ── */} {/* ── Storage Type ── */}
<div> <div>
<label className="text-xs text-muted-foreground block mb-1.5">Storage Type</label> <label className="text-xs text-muted-foreground block mb-1.5">Storage Type</label>
<div className="grid grid-cols-3 gap-2"> <div className="grid grid-cols-2 gap-2">
{STORAGE_OPTIONS.map(opt => ( {STORAGE_OPTIONS.map(opt => (
<button key={opt.type} onClick={() => setStorageType(opt.type)} <button key={opt.type} onClick={() => setStorageType(opt.type)}
className={`flex flex-col items-center gap-1 p-3 rounded-xl transition-colors ${ className={`flex flex-col items-center gap-1 p-3 rounded-xl transition-colors ${
@@ -1156,7 +1153,6 @@ const CreateWorkspaceDialog = ({ open, onClose, onCreate }: CreateWorkspaceDialo
<p className="text-[11px] text-muted-foreground/60 mt-1"> <p className="text-[11px] text-muted-foreground/60 mt-1">
{storageType === 'virtual' && 'Managed automatically — files stored in server-managed storage.'} {storageType === 'virtual' && 'Managed automatically — files stored in server-managed storage.'}
{storageType === 'local' && 'Select or type the local directory where workspace files will be stored.'} {storageType === 'local' && 'Select or type the local directory where workspace files will be stored.'}
{storageType === 'team' && 'Browse or type the S3/MinIO bucket and prefix for shared storage.'}
</p> </p>
</div> </div>
@@ -1267,22 +1263,6 @@ const CreateWorkspaceDialog = ({ open, onClose, onCreate }: CreateWorkspaceDialo
</div>} </div>}
</div> </div>
{/* Share toggle */}
<div className="flex items-center justify-between mx-6 mb-3 p-3 rounded-xl bg-secondary/30 border border-border/30">
<div className="flex items-center gap-2">
<Users className="w-4 h-4 text-sky-400" />
<div>
<p className="text-xs font-display text-foreground">Share with team</p>
<p className="text-[11px] text-muted-foreground">Make visible to all team members</p>
</div>
</div>
<button type="button" onClick={() => setShared(!shared)}
aria-label={shared ? 'Stop sharing workspace with team' : 'Share workspace with team'}
className={`w-10 h-5 rounded-full transition-colors ${shared ? 'bg-sky-500' : 'bg-muted'}`}>
<div className={`w-4 h-4 rounded-full bg-foreground transition-transform mx-0.5 ${shared ? 'translate-x-5' : ''}`} />
</button>
</div>
<div className="flex justify-end gap-2 px-6 py-4 border-t border-border/30"> <div className="flex justify-end gap-2 px-6 py-4 border-t border-border/30">
<button type="button" onClick={onClose} className="px-4 py-2 text-xs font-display rounded-lg text-muted-foreground hover:text-foreground transition-colors">Cancel</button> <button type="button" onClick={onClose} className="px-4 py-2 text-xs font-display rounded-lg text-muted-foreground hover:text-foreground transition-colors">Cancel</button>
<button type="button" onClick={handleCreate} disabled={!name.trim() || (storageType === 'local' && !storagePath.trim())} aria-label="Create workspace" <button type="button" onClick={handleCreate} disabled={!name.trim() || (storageType === 'local' && !storagePath.trim())} aria-label="Create workspace"

View File

@@ -184,7 +184,7 @@ export default function EraseDataDialog({ open, onClose }: EraseDataDialogProps)
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. 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>
<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. Data already sent to cloud model providers (Anthropic, OpenAI and others) is <span className="text-foreground font-medium">not</span> erased by this action. Ask those providers to delete it.
</p> </p>
</div> </div>

View File

@@ -18,7 +18,6 @@ const shortcuts = [
{ keys: ['Ctrl', 'Shift', '6'], action: 'Events' }, { keys: ['Ctrl', 'Shift', '6'], action: 'Events' },
{ keys: ['Ctrl', 'Shift', '7'], action: 'Settings' }, { keys: ['Ctrl', 'Shift', '7'], action: 'Settings' },
{ keys: ['Ctrl', 'Shift', '8'], action: 'Skills' }, { keys: ['Ctrl', 'Shift', '8'], action: 'Skills' },
{ keys: ['Ctrl', 'Shift', '9'], action: 'Agent Swarm' },
]}, ]},
{ category: 'Quick Actions', items: [ { category: 'Quick Actions', items: [
{ keys: ['Ctrl', 'K'], action: 'Global Search' }, { keys: ['Ctrl', 'K'], action: 'Global Search' },

View File

@@ -346,16 +346,14 @@ const LoginBriefing = ({ onDismiss, onOpenWorkspace }: LoginBriefingProps) => {
<div className="flex items-center justify-between mb-1"> <div className="flex items-center justify-between mb-1">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="text-sm font-display font-medium text-foreground">{ws.name}</span> <span className="text-sm font-display font-medium text-foreground">{ws.name}</span>
{/* FR #27: tooltip clarifies what the Personal/Team {/* FR #27: tooltip clarifies what the group tag
tag means. Personal workspaces are private to the means. Without this hint the colored chip reads
account; Team workspaces are
shared. Without this hint the colored chip reads
as decorative metadata. */} as decorative metadata. */}
<HintTooltip <HintTooltip
content={ content={
ws.group === 'Personal' ws.group === 'Personal'
? 'Personal workspaces are visible only to you.' ? 'Personal workspaces are visible only to you.'
: 'Team workspaces (Teams/Enterprise) are shared across the organisation.' : `${ws.group} is a group for sorting your workspaces.`
} }
> >
<span className="text-[11px] px-1.5 py-0.5 rounded-full bg-muted text-muted-foreground cursor-help">{ws.group}</span> <span className="text-[11px] px-1.5 py-0.5 rounded-full bg-muted text-muted-foreground cursor-help">{ws.group}</span>

View File

@@ -3,6 +3,7 @@ import { motion, AnimatePresence, MotionConfig, useReducedMotion } from 'framer-
import beeMascot from '@/assets/personas/general-purpose.png'; import beeMascot from '@/assets/personas/general-purpose.png';
import { adapter } from '@/lib/adapter'; import { adapter } from '@/lib/adapter';
import { captureOnboardingComplete } from '@/lib/posthog'; import { captureOnboardingComplete } from '@/lib/posthog';
import { hasMemoryFeature } from '@/lib/memory-features';
import { useOfflineStatus } from '@/hooks/useOfflineStatus'; import { useOfflineStatus } from '@/hooks/useOfflineStatus';
import type { OnboardingState } from '@/hooks/useOnboarding'; import type { OnboardingState } from '@/hooks/useOnboarding';
import type { UserProfile, ClassifiedHarvestItem } from '@/lib/types'; import type { UserProfile, ClassifiedHarvestItem } from '@/lib/types';
@@ -49,6 +50,17 @@ const LAST_INDEX = STEP_NAMES.length - 1;
const FIRST_NAV_INDEX = stepIndex('who-are-you'); const FIRST_NAV_INDEX = stepIndex('who-are-you');
const LAST_NAV_INDEX = stepIndex('first-task'); const LAST_NAV_INDEX = stepIndex('first-task');
/** ADR-0002: history import is hidden in v1 (memory feature map), so its step
* is skipped. It keeps its index, so a persisted `state.step` still resolves. */
const isStepShown = (name: StepName): boolean =>
name !== 'memory-import' || hasMemoryFeature('importHistory');
/** Nearest shown step from `from`, walking forward (1) or back (-1). */
const shownStepFrom = (from: number, dir: 1 | -1): number => {
let i = from;
while (i > 0 && i < LAST_INDEX && !isStepShown(STEP_NAMES[i])) i += dir;
return i;
};
const DEFAULT_FIRST_MESSAGE = 'Hello! What can you help me with?'; const DEFAULT_FIRST_MESSAGE = 'Hello! What can you help me with?';
/* ─── Main Component (shell) ─── */ /* ─── Main Component (shell) ─── */
@@ -57,7 +69,7 @@ const OnboardingWizard = ({ serverBaseUrl, state, onUpdate, onComplete, onDismis
// `state.step` (5-7) that no longer maps to the re-keyed 5-step chain. Clamp // `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 // into [0, LAST_INDEX] so resume always lands on a renderable step rather
// than a blank screen. `?forceWizard=true` already resets step to 0. // 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 [step, setStep] = useState(() => shownStepFrom(Math.min(Math.max(state.step, 0), LAST_INDEX), 1));
const autoTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined); const autoTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const offline = useOfflineStatus(); const offline = useOfflineStatus();
const reduceMotion = useReducedMotion(); const reduceMotion = useReducedMotion();
@@ -191,8 +203,9 @@ const OnboardingWizard = ({ serverBaseUrl, state, onUpdate, onComplete, onDismis
finally { setImporting(false); } finally { setImporting(false); }
}; };
/* ── Claude Code auto-detect on mount ── */ /* ── Claude Code auto-detect on mount (only when the import step is shown) ── */
useEffect(() => { useEffect(() => {
if (!isStepShown('memory-import')) return;
let cancelled = false; let cancelled = false;
(async () => { (async () => {
try { try {
@@ -277,10 +290,15 @@ const OnboardingWizard = ({ serverBaseUrl, state, onUpdate, onComplete, onDismis
const progressPct = LAST_INDEX > 0 ? (step / LAST_INDEX) * 100 : 0; 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 // 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, // 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. // first-task = 5 of 5) instead of two identical "Step 4 of 4" screens. A
// hidden step (isStepShown) gets no dot and no number.
const showNavChrome = step >= FIRST_NAV_INDEX; const showNavChrome = step >= FIRST_NAV_INDEX;
const navTotal = LAST_NAV_INDEX - FIRST_NAV_INDEX + 1; const navSteps = STEP_NAMES
const navCurrent = step - FIRST_NAV_INDEX + 1; .map((name, index) => ({ name, index }))
.filter(({ name, index }) => index >= FIRST_NAV_INDEX && index <= LAST_NAV_INDEX && isStepShown(name))
.map(({ index }) => index);
const navTotal = navSteps.length;
const navCurrent = navSteps.indexOf(step) + 1;
const recommendedId = recommendTemplateId(profile.workType, profile.role); const recommendedId = recommendTemplateId(profile.workType, profile.role);
return ( return (
@@ -358,7 +376,7 @@ const OnboardingWizard = ({ serverBaseUrl, state, onUpdate, onComplete, onDismis
<button <button
onClick={() => { onClick={() => {
clearTimeout(autoTimer.current); clearTimeout(autoTimer.current);
goToStep(step - 1); goToStep(shownStepFrom(step - 1, -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" 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" aria-label="Go to previous step"
@@ -373,8 +391,7 @@ const OnboardingWizard = ({ serverBaseUrl, state, onUpdate, onComplete, onDismis
)} )}
{showNavChrome && ( {showNavChrome && (
<div className="flex gap-1.5" aria-hidden="true"> <div className="flex gap-1.5" aria-hidden="true">
{STEP_NAMES.slice(FIRST_NAV_INDEX, LAST_NAV_INDEX + 1).map((_, idx) => { {navSteps.map((navStep) => {
const navStep = FIRST_NAV_INDEX + idx;
return ( return (
<div <div
key={navStep} key={navStep}
@@ -418,7 +435,7 @@ const OnboardingWizard = ({ serverBaseUrl, state, onUpdate, onComplete, onDismis
)} )}
{step === stepIndex('model-gate') && ( {step === stepIndex('model-gate') && (
<ModelGateStep <ModelGateStep
onContinue={() => goToName('memory-import')} onContinue={() => goToName(isStepShown('memory-import') ? 'memory-import' : 'template')}
onLater={() => { onLater={() => {
clearTimeout(autoTimer.current); clearTimeout(autoTimer.current);
trackTelemetry(serverBaseUrl, 'onboarding_skip', { atStep: step, via: 'model-gate-later' }); trackTelemetry(serverBaseUrl, 'onboarding_skip', { atStep: step, via: 'model-gate-later' });

View File

@@ -26,7 +26,6 @@ const APP_SHORTCUTS: Record<string, AppId> = {
'6': 'events', '6': 'events',
'7': 'settings', '7': 'settings',
'8': 'capabilities', '8': 'capabilities',
'9': 'waggle-dance',
}; };
/** Shortcuts that work even when an input/textarea is focused */ /** Shortcuts that work even when an input/textarea is focused */

View File

@@ -4,7 +4,8 @@ import type { KGNode, KGEdge } from '@/lib/types';
export type KGScope = 'current' | 'personal' | 'all'; export type KGScope = 'current' | 'personal' | 'all';
export const useKnowledgeGraph = (workspaceId: string | null) => { /** `enabled: false` skips the fetch while the graph is hidden (memory feature map). */
export const useKnowledgeGraph = (workspaceId: string | null, enabled = true) => {
const [nodes, setNodes] = useState<KGNode[]>([]); const [nodes, setNodes] = useState<KGNode[]>([]);
const [edges, setEdges] = useState<KGEdge[]>([]); const [edges, setEdges] = useState<KGEdge[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -32,7 +33,7 @@ export const useKnowledgeGraph = (workspaceId: string | null) => {
} finally { setLoading(false); } } finally { setLoading(false); }
}, [workspaceId, scope]); }, [workspaceId, scope]);
useEffect(() => { fetchKG(); }, [fetchKG]); useEffect(() => { if (enabled) fetchKG(); }, [fetchKG, enabled]);
return { nodes, edges, loading, error, selectedNode, setSelectedNode, scope, setScope, refresh: fetchKG }; return { nodes, edges, loading, error, selectedNode, setSelectedNode, scope, setScope, refresh: fetchKG };
}; };

View File

@@ -1,59 +0,0 @@
import { useState, useEffect, useCallback } from 'react';
import { adapter } from '@/lib/adapter';
import type { WaggleSignal } from '@/lib/types';
export const useWaggleDance = () => {
const [signals, setSignals] = useState<WaggleSignal[]>([]);
const [loading, setLoading] = useState(true);
const [filter, setFilter] = useState<WaggleSignal['type'] | 'all'>('all');
const [error, setError] = useState<string | null>(null);
const refresh = useCallback(async () => {
setLoading(true);
try {
const data = await adapter.getWaggleSignals();
setSignals(data);
setError(null);
} catch (err) {
console.error('[useWaggleDance] refresh failed:', err);
setSignals([]);
setError(err instanceof Error ? err.message : 'Failed to load');
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
refresh();
let unsub: (() => void) | undefined;
try {
unsub = adapter.subscribeWaggleDance?.((signal) => {
setSignals(prev => [signal, ...prev]);
}) || undefined;
} catch (err) {
console.error('[useWaggleDance] SSE subscribe failed:', err);
}
return () => { try { unsub?.(); } catch (err) { console.error('[useWaggleDance] cleanup failed:', err); } };
}, [refresh]);
const publishSignal = useCallback(async (data: Omit<WaggleSignal, 'id' | 'timestamp'>) => {
try {
const signal = await adapter.publishWaggleSignal(data);
setSignals(prev => [signal, ...prev]);
return signal;
} catch (e) {
throw e;
}
}, []);
const acknowledge = useCallback(async (id: string) => {
try {
await adapter.acknowledgeWaggleSignal(id);
setSignals(prev => prev.map(s => s.id === id ? { ...s, acknowledged: true } : s));
} catch (err) { console.error('[useWaggleDance] acknowledge failed:', err); }
}, []);
const filtered = filter === 'all' ? signals : signals.filter(s => s.type === filter);
return { signals: filtered, allSignals: signals, loading, error, filter, setFilter, refresh, publishSignal, acknowledge };
};

View File

@@ -95,7 +95,7 @@ describe('P1b-SSE client', () => {
throw new Error(`unmocked: ${u}`); throw new Error(`unmocked: ${u}`);
}); });
const connectP = a.connect(); const connectP = a.connect();
a.subscribeWaggleDance(() => {}); // pre-settle — old code returned a dead noop here a.subscribeEvents(() => {}); // pre-settle — old code returned a dead noop here
await flush(); await flush();
expect(FakeEventSource.instances).toHaveLength(0); // deferred, not opened token-less expect(FakeEventSource.instances).toHaveLength(0); // deferred, not opened token-less
releaseToken(jsonRes({ token: 'tok-A' })); releaseToken(jsonRes({ token: 'tok-A' }));
@@ -173,26 +173,17 @@ describe('P1b-SSE client', () => {
expect(FakeEventSource.instances).toHaveLength(2); expect(FakeEventSource.instances).toHaveLength(2);
}); });
it('NAMED EVENTS: subscribeEvents/<audit> and subscribeWaggleDance/<signal> receive named payloads, not onmessage', async () => { it('NAMED EVENTS: subscribeEvents/<audit> receives named payloads, not onmessage', async () => {
// Review fix: the server emits `event: audit` / `event: signal` — an // Review fix: the server emits `event: audit` — an onmessage-only
// onmessage-only listener made both channels payload-dead even with // listener made the channel payload-dead even with working auth.
// working auth.
const a = await connectedAdapter('tok-A'); const a = await connectedAdapter('tok-A');
const audits: unknown[] = []; const audits: unknown[] = [];
const signals: unknown[] = [];
a.subscribeEvents((e) => audits.push(e)); a.subscribeEvents((e) => audits.push(e));
a.subscribeWaggleDance((s) => signals.push(s));
await flush(); await flush();
const [eventsEs, waggleEs] = FakeEventSource.instances; const [eventsEs] = FakeEventSource.instances;
eventsEs.fireNamed('audit', { type: 'tool_call' }); eventsEs.fireNamed('audit', { type: 'tool_call' });
waggleEs.fireNamed('signal', { id: 's1' });
expect(audits).toEqual([{ type: 'tool_call' }]); expect(audits).toEqual([{ type: 'tool_call' }]);
expect(signals).toEqual([{ id: 's1' }]);
// The named `event: connected` waggle handshake is ignored by spec.
waggleEs.fireNamed('connected', { type: 'connected' });
expect(signals).toHaveLength(1);
}); });
it('HANDSHAKE FILTER: the unnamed {"type":"connected"} on the notifications stream never reaches the consumer', async () => { it('HANDSHAKE FILTER: the unnamed {"type":"connected"} on the notifications stream never reaches the consumer', async () => {

View File

@@ -21,7 +21,7 @@ import type {
AgentStep, Session, SkillPack, FleetSession, CronJob, AgentStep, Session, SkillPack, FleetSession, CronJob,
Notification, AgentStatus, Persona, SystemHealth, Notification, AgentStatus, Persona, SystemHealth,
Settings, StreamEvent, KGNode, KGEdge, Settings, StreamEvent, KGNode, KGEdge,
ModelPricing, WaggleSignal, FileEntry, WorkspaceTemplate, ModelPricing, FileEntry, WorkspaceTemplate,
TimelineEvent, TimelineEvent,
HomeBriefing, OvernightSummary, QuickCaptureInput, HomeBriefing, OvernightSummary, QuickCaptureInput,
WorkspaceStateView, WorkspaceActivityEvent, WorkspaceTask, WorkspaceStateView, WorkspaceActivityEvent, WorkspaceTask,
@@ -3270,24 +3270,6 @@ class LocalAdapter {
}, },
}; };
// --- Waggle Dance ---
async getWaggleSignals(): Promise<WaggleSignal[]> {
try {
const res = await this.fetch('/api/waggle/signals');
if (!res.ok) return [];
return unwrapArray(await res.json());
} catch (err) { console.error('[adapter] getWaggleSignals failed:', err); return []; }
}
async publishWaggleSignal(data: Omit<WaggleSignal, 'id' | 'timestamp'>): Promise<WaggleSignal> {
const res = await this.fetch('/api/waggle/signals', { method: 'POST', body: JSON.stringify(data) });
return res.json();
}
async acknowledgeWaggleSignal(id: string): Promise<void> {
await this.fetch(`/api/waggle/signals/${id}/ack`, { method: 'PATCH' });
}
// --- AI-OS launcher (Phase 2B) --- // --- AI-OS launcher (Phase 2B) ---
// detectTools/launchTool/manageHooks each surface the matching // detectTools/launchTool/manageHooks each surface the matching
// sidecar route. All are loopback-only and report only the user's // sidecar route. All are loopback-only and report only the user's
@@ -3442,12 +3424,6 @@ class LocalAdapter {
}; };
} }
subscribeWaggleDance(onSignal: (signal: WaggleSignal) => void): () => void {
// Server emits NAMED `event: signal` events (waggle-signals.ts:103); its
// `event: connected` handshake is equally named and equally ignored here.
return this.subscribeSSE('/api/waggle/stream', (data) => onSignal(data as WaggleSignal), 'signal');
}
/** /**
* P1b-SSE: shared EventSource lifecycle — token-attached, lazy-open, * P1b-SSE: shared EventSource lifecycle — token-attached, lazy-open,
* reconnecting. Fixes the three defects that made every stream dead in * reconnecting. Fixes the three defects that made every stream dead in
@@ -3542,16 +3518,13 @@ class LocalAdapter {
/** /**
* P1b-SSE review fix: FAN-OUT, not replace. One ref-counted stream per * P1b-SSE review fix: FAN-OUT, not replace. One ref-counted stream per
* (path, eventName); concurrent subscribers share it (AppShell's * (path, eventName); concurrent subscribers share it (the old
* always-mounted waggle badge + the WaggleDance screen both consume * replace-on-resubscribe dedup let a second mount permanently kill the
* /api/waggle/stream — the old replace-on-resubscribe dedup let the second * first's stream). The socket closes only when the last subscriber leaves.
* mount permanently kill the first's stream). The socket closes only when
* the last subscriber leaves.
* *
* `eventName` selects NAMED SSE events (review fix: the events/waggle * `eventName` selects NAMED SSE events (review fix: the events route emits
* routes emit `event: audit` / `event: signal`, which `onmessage` never * `event: audit`, which `onmessage` never receives per the SSE spec — the
* receives per the SSE spec — both channels were payload-dead even with * channel was payload-dead even with working auth).
* working auth).
*/ */
private subscribeSSE(path: string, onData: (data: unknown) => void, eventName?: string): () => void { private subscribeSSE(path: string, onData: (data: unknown) => void, eventName?: string): () => void {
const key = `${path}#${eventName ?? 'message'}`; const key = `${path}#${eventName ?? 'message'}`;

View File

@@ -0,0 +1,62 @@
/**
* Analytics consent (ADR-0006): PostHog runs only after the user chooses
* "Allow". The choice is stored in localStorage; no choice means not allowed.
*
* This module stays free of posthog-js so the startup bundle never carries it:
* applying a choice loads `@/lib/posthog` on demand.
*/
export type AnalyticsConsent = 'granted' | 'denied';
/** localStorage key holding the user's choice. */
export const ANALYTICS_CONSENT_KEY = 'waggle:analytics-consent';
/** Pre-consent opt-out marker; 'true' is read as a denial. */
export const LEGACY_OPT_OUT_KEY = 'waggle:telemetry-opt-out';
/** True when the build carries a PostHog key. Source builds have none. */
export function hasAnalyticsKey(): boolean {
return Boolean(import.meta.env['VITE_POSTHOG_KEY']);
}
/** The stored choice, or null when the user has not chosen yet. */
export function readAnalyticsConsent(): AnalyticsConsent | null {
try {
const stored = window.localStorage.getItem(ANALYTICS_CONSENT_KEY);
if (stored === 'granted' || stored === 'denied') return stored;
if (window.localStorage.getItem(LEGACY_OPT_OUT_KEY) === 'true') return 'denied';
return null;
} catch {
// Storage unavailable: a choice could not be kept, so never send.
return 'denied';
}
}
export function isAnalyticsAllowed(): boolean {
return readAnalyticsConsent() === 'granted';
}
/** Show the consent dialog only when there is something to consent to. */
export function shouldAskAnalyticsConsent(): boolean {
return hasAnalyticsKey() && readAnalyticsConsent() === null;
}
/**
* Store the choice and apply it at once: "granted" starts PostHog, "denied"
* opts out and resets it if it was running.
*/
export async function setAnalyticsConsent(choice: AnalyticsConsent): Promise<void> {
try {
window.localStorage.setItem(ANALYTICS_CONSENT_KEY, choice);
} catch {
// Ignore storage errors; readAnalyticsConsent() then reports 'denied'.
}
if (!hasAnalyticsKey()) return;
try {
const posthog = await import('@/lib/posthog');
if (choice === 'granted') await posthog.initPostHog();
else posthog.stopPostHog();
} catch {
// Analytics must never break the app.
}
}

View File

@@ -44,7 +44,7 @@ describe('chat header control classification', () => {
it('overflow set is the informational chips only', () => { it('overflow set is the informational chips only', () => {
expect([...CHAT_HEADER_OVERFLOW_CONTROLS].sort()).toEqual( expect([...CHAT_HEADER_OVERFLOW_CONTROLS].sort()).toEqual(
['storage-type', 'team-presence'].sort(), ['storage-type'],
); );
}); });

View File

@@ -1,12 +1,11 @@
/** /**
* Chat-header layout decision (M-21 / UX-6). * Chat-header layout decision (M-21 / UX-6).
* *
* The header crowds the persona picker + storage badge + team presence * The header crowds the persona picker + storage badge + autonomy
* + autonomy toggle + model picker into a single row. Below a narrow * toggle + model picker into a single row. Below a narrow threshold, the
* threshold, the informational surfaces (storage badge, team presence) * informational surface (storage badge) moves into a ⋯ overflow menu
* move into a ⋯ overflow menu so the interactive controls (persona, * so the interactive controls (persona, autonomy, model) stay reachable
* autonomy, model) stay reachable without the header wrapping or * without the header wrapping or truncating.
* truncating.
* *
* This module holds the pure decision so a test can pin the threshold * This module holds the pure decision so a test can pin the threshold
* and the classification of each control without booting React. * and the classification of each control without booting React.
@@ -36,7 +35,6 @@ export function shouldCollapseChatHeader(containerWidth: number | null | undefin
*/ */
export const CHAT_HEADER_OVERFLOW_CONTROLS = [ export const CHAT_HEADER_OVERFLOW_CONTROLS = [
'storage-type', 'storage-type',
'team-presence',
] as const; ] as const;
export type ChatHeaderOverflowControl = (typeof CHAT_HEADER_OVERFLOW_CONTROLS)[number]; export type ChatHeaderOverflowControl = (typeof CHAT_HEADER_OVERFLOW_CONTROLS)[number];

View File

@@ -2,10 +2,11 @@ import type { ElementType } from "react";
import { import {
Home, MessageSquare, Brain, ListTodo, Library, UserCircle, Home, MessageSquare, Brain, ListTodo, Library, UserCircle,
Plus, Rocket, Settings, Plus, Rocket, Settings,
Network, Server, Plug, Store, Package, Shield, Clock, FolderOpen, Server, Plug, Store, Package, Shield, Clock, FolderOpen,
Lock, Activity, History, BarChart3, Users, Radio, Lock, Activity, History, BarChart3, Users, Radio,
Gauge, Monitor, LayoutGrid, Eye, Gauge, Monitor, LayoutGrid, Eye,
} from "lucide-react"; } from "lucide-react";
import { hasMemoryFeature } from "@/lib/memory-features";
/** /**
* Curated ⌘K catalog (design ref: design-files/screens/ia.html). * Curated ⌘K catalog (design ref: design-files/screens/ia.html).
@@ -66,13 +67,12 @@ export function buildCommandCatalog(ctx: CatalogContext): CatalogGroup[] {
const doGroup: CatalogCommand[] = [ const doGroup: CatalogCommand[] = [
{ id: "start-task", group: "do", name: "Start a task", subtitle: "new agent run", icon: Plus, action: "spawn" }, { id: "start-task", group: "do", name: "Start a task", subtitle: "new agent run", icon: Plus, action: "spawn" },
{ id: "launch-agent", group: "do", name: "Launch a coding agent", subtitle: "Claude Code · Cursor · Codex — shares this hive", icon: Rocket, to: "/launcher" }, { id: "launch-agent", group: "do", name: "Launch a coding agent", subtitle: hasMemoryFeature("agentHooks") ? "Claude Code · Cursor · Codex — shares this hive" : "Claude Code · Cursor · Codex", icon: Rocket, to: "/launcher" },
{ id: "watch-agent", group: "do", name: "Watch a coding agent live", subtitle: "Claude Code · Cursor · Codex — stream its output", keywords: "observe pty terminal live output tail", icon: Eye, to: "/launcher?watch=1" }, { id: "watch-agent", group: "do", name: "Watch a coding agent live", subtitle: "Claude Code · Cursor · Codex — stream its output", keywords: "observe pty terminal live output tail", icon: Eye, to: "/launcher?watch=1" },
{ id: "settings", group: "do", name: "Settings", subtitle: "models · failover · permissions", icon: Settings, to: "/settings" }, { id: "settings", group: "do", name: "Settings", subtitle: "models · failover · permissions", icon: Settings, to: "/settings" },
]; ];
const power: CatalogCommand[] = [ const power: CatalogCommand[] = [
{ id: "swarm", group: "power", name: "Run a team of agents", subtitle: "waggle-dance · swarm", icon: Network, to: "/waggle-dance", pinned: true },
{ id: "connect-mcp", group: "power", name: "Connect a tool", subtitle: "MCP servers", icon: Server, to: "/mcps" }, { id: "connect-mcp", group: "power", name: "Connect a tool", subtitle: "MCP servers", icon: Server, to: "/mcps" },
{ id: "connectors", group: "power", name: "Connectors", subtitle: "integrations", icon: Plug, to: "/connectors", pinned: true }, { id: "connectors", group: "power", name: "Connectors", subtitle: "integrations", icon: Plug, to: "/connectors", pinned: true },
{ id: "marketplace", group: "power", name: "Add a capability", subtitle: "marketplace · skills, connectors, tools", icon: Store, to: "/marketplace" }, { id: "marketplace", group: "power", name: "Add a capability", subtitle: "marketplace · skills, connectors, tools", icon: Store, to: "/marketplace" },

View File

@@ -1,16 +1,16 @@
import type { ElementType } from 'react'; import type { ElementType } from 'react';
import { import {
LayoutDashboard, MessageSquare, FolderOpen, Settings, Bot, Brain, LayoutDashboard, MessageSquare, FolderOpen, Settings, Bot, Brain,
Zap, Activity, Radio, Clock, Package, Plug, Store, Lock, Users, Shield, Rocket, FileStack, Server, Activity, Radio, Clock, Package, Plug, Store, Lock, Users, Shield, Rocket, FileStack, Server,
} from 'lucide-react'; } from 'lucide-react';
export type AppId = export type AppId =
| 'home' | 'chat' | 'dashboard' | 'memory' | 'events' | 'home' | 'chat' | 'dashboard' | 'memory' | 'events'
| 'capabilities' | 'connectors' | 'cockpit' | 'mission-control' | 'capabilities' | 'connectors' | 'cockpit' | 'mission-control'
| 'settings' | 'vault' | 'profile' | 'settings' | 'vault' | 'profile'
| 'waggle-dance' | 'files' | 'artifacts' | 'agents' | 'files' | 'artifacts' | 'agents'
| 'scheduled-jobs' | 'marketplace' | 'voice' | 'room' | 'approvals' | 'timeline' | 'scheduled-jobs' | 'marketplace' | 'voice' | 'room' | 'approvals' | 'timeline'
| 'backup' | 'telemetry' | 'governance' | 'launcher' | 'backup' | 'telemetry' | 'launcher'
// UX-Refactor Phase 1 (S02): single-workspace runtime surface, opened from // UX-Refactor Phase 1 (S02): single-workspace runtime surface, opened from
// Home / workspace selection (not a dock entry — A1 fixed-layout window). // Home / workspace selection (not a dock entry — A1 fixed-layout window).
| 'workspace-desktop' | 'workspace-desktop'
@@ -65,7 +65,6 @@ const POWER_CONFIG: DockEntry[] = [
{ type: 'app', key: 'skills', appId: 'capabilities', icon: Package, label: 'Skills Hub', color: 'text-violet-400', route: '/skills', description: 'Teach your agents new abilities' }, { type: 'app', key: 'skills', appId: 'capabilities', icon: Package, label: 'Skills Hub', color: 'text-violet-400', route: '/skills', description: 'Teach your agents new abilities' },
{ type: 'app', key: 'jobs', appId: 'scheduled-jobs', icon: Clock, label: 'Automation Center', color: 'text-amber-400', route: '/automations', description: 'Set up tasks that run on a schedule' }, { type: 'app', key: 'jobs', appId: 'scheduled-jobs', icon: Clock, label: 'Automation Center', color: 'text-amber-400', route: '/automations', description: 'Set up tasks that run on a schedule' },
{ type: 'app', key: 'room', appId: 'room', icon: Users, label: 'Room', color: 'text-violet-400', route: '/room', description: 'Watch your agents work together live' }, { type: 'app', key: 'room', appId: 'room', icon: Users, label: 'Room', color: 'text-violet-400', route: '/room', description: 'Watch your agents work together live' },
{ type: 'app', key: 'dance', appId: 'waggle-dance', icon: Zap, label: 'Waggle Dance', color: 'text-amber-400', route: '/waggle-dance', description: 'See what your agents learn from each other' },
{ type: 'app', key: 'approvals', appId: 'approvals', icon: Shield, label: 'Approvals', color: 'text-amber-400', route: '/approvals', description: 'Review and approve actions your agents want to take' }, { type: 'app', key: 'approvals', appId: 'approvals', icon: Shield, label: 'Approvals', color: 'text-amber-400', route: '/approvals', description: 'Review and approve actions your agents want to take' },
], ],
}, },

View File

@@ -0,0 +1,51 @@
/**
* Memory features the UI may show (ADR-0002).
*
* v1 memory is facts, search and the user profile. The features below are
* hidden, not deleted: their screens stay in the code and every surface that
* offers one checks this map first. A later work package fills the map from
* the server's memory capability map, so read it only through this module.
*/
export interface MemoryFeatures {
/** Knowledge graph (entities and relations). Deferred to a later release. */
knowledgeGraph: boolean;
/** Importing chat history from other AI tools (harvest). */
importHistory: boolean;
/** Compiled wiki pages. */
wiki: boolean;
/** Memory hooks installed into Claude Code, Codex and other coding agents. */
agentHooks: boolean;
/** Waggle Room: coding agents started as a team that shares one Room. */
room: boolean;
/** The Waggle memory MCP server for other clients. */
memoryMcp: boolean;
}
export type MemoryFeature = keyof MemoryFeatures;
const MEMORY_FEATURES: Readonly<MemoryFeatures> = {
knowledgeGraph: false,
importHistory: false,
wiki: false,
agentHooks: false,
room: false,
memoryMcp: false,
};
export function hasMemoryFeature(feature: MemoryFeature): boolean {
return MEMORY_FEATURES[feature];
}
/** Memory Center views (`?tab=`) that belong to a hidden feature. */
const MEMORY_VIEW_FEATURE: Readonly<Record<string, MemoryFeature>> = {
graph: 'knowledgeGraph',
harvest: 'importHistory',
wiki: 'wiki',
};
/** False for a Memory Center view whose feature is hidden. */
export function isMemoryViewAvailable(view: string): boolean {
const feature = MEMORY_VIEW_FEATURE[view];
return feature === undefined || hasMemoryFeature(feature);
}

View File

@@ -39,13 +39,11 @@ const ROUTE_LABELS: Record<string, string> = {
automations: 'Automations', automations: 'Automations',
skills: 'Skills', skills: 'Skills',
room: 'Room', room: 'Room',
'waggle-dance': 'Agent swarm',
approvals: 'Approvals', approvals: 'Approvals',
connectors: 'Connectors', connectors: 'Connectors',
mcps: 'MCP hub', mcps: 'MCP hub',
marketplace: 'Marketplace', marketplace: 'Marketplace',
launcher: 'Launcher', launcher: 'Launcher',
team: 'Team',
settings: 'Settings', settings: 'Settings',
benchmarks: 'Benchmarks', benchmarks: 'Benchmarks',
platform: 'Platform', platform: 'Platform',

View File

@@ -1,6 +1,7 @@
/** /**
* Tiny platform helpers. Waggle ships on Windows + macOS, so any modifier-key * Tiny platform helpers. Waggle runs on Windows, macOS and Linux, so any
* hint must adapt: a ⌘ glyph on Windows is a key the user's keyboard lacks. * modifier-key hint must adapt: a ⌘ glyph on Windows or Linux is a key the
* user's keyboard lacks.
* Centralised here so the ⌘K affordance reads correctly everywhere it appears * Centralised here so the ⌘K affordance reads correctly everywhere it appears
* (Sidebar, AskBar, CommandCenter footer, NotFound, ChatApp composer). * (Sidebar, AskBar, CommandCenter footer, NotFound, ChatApp composer).
*/ */

View File

@@ -1,15 +1,12 @@
/** /**
* posthog.ts unit tests (Phase 2 P1 / DAY0-04) * Opt-in analytics (ADR-0006): posthog.ts + analytics-consent.ts.
*
* Run: npx vitest run apps/web/src/lib/posthog.test.ts
* *
* Covers: * Covers:
* Test 1 — When VITE_POSTHOG_KEY is absent, captureOnboardingComplete * - no key at build time → nothing initializes, nothing is captured, no prompt;
* does NOT call posthog.capture. * - key present, no choice yet → nothing initializes or is captured;
* Test 2 — When user has opted out (waggle:telemetry-opt-out = 'true'), * - denial (new key or the old opt-out marker) → nothing is captured;
* captureOnboardingComplete does NOT call posthog.capture. * - grant → PostHog initializes and onboarding_complete is captured;
* Test 3 — When key is present AND user is opted in, * - withdrawal → PostHog opts out and resets; later events are dropped.
* captureOnboardingComplete calls posthog.capture('onboarding_complete', payload).
*/ */
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
@@ -21,6 +18,8 @@ const mockCapture = vi.fn();
const mockInit = vi.fn(); const mockInit = vi.fn();
const mockOptOut = vi.fn(); const mockOptOut = vi.fn();
const mockOptIn = vi.fn(); const mockOptIn = vi.fn();
const mockReset = vi.fn();
const mockHasOptedOut = vi.fn(() => false);
// posthog.ts imports the no-external build (no remote script — sovereignty // posthog.ts imports the no-external build (no remote script — sovereignty
// posture); the mock specifier must match that exact import. // posture); the mock specifier must match that exact import.
@@ -30,12 +29,11 @@ vi.mock('posthog-js/dist/module.no-external', () => ({
capture: mockCapture, capture: mockCapture,
opt_out_capturing: mockOptOut, opt_out_capturing: mockOptOut,
opt_in_capturing: mockOptIn, opt_in_capturing: mockOptIn,
reset: mockReset,
has_opted_out_capturing: mockHasOptedOut,
}, },
})); }));
// ── import.meta.env mock ──────────────────────────────────────────────────────
// We control PH_KEY presence by setting / clearing the env value before each test.
// ── localStorage mock ───────────────────────────────────────────────────────── // ── localStorage mock ─────────────────────────────────────────────────────────
const localStorageMock = (() => { const localStorageMock = (() => {
let store: Record<string, string> = {}; let store: Record<string, string> = {};
@@ -51,81 +49,143 @@ Object.defineProperty(window, 'localStorage', { value: localStorageMock });
// ── Test helpers ────────────────────────────────────────────────────────────── // ── Test helpers ──────────────────────────────────────────────────────────────
const OPT_OUT_KEY = 'waggle:telemetry-opt-out'; const TEST_KEY = 'phc_testkey12345678901234567890123456789012';
const CONSENT_KEY = 'waggle:analytics-consent';
const LEGACY_OPT_OUT_KEY = 'waggle:telemetry-opt-out';
const PAYLOAD = { templateId: 'sales-pipeline', personaId: 'coder', model: 'claude-opus-4' };
async function importPostHog() { async function importModules() {
// Re-import the module fresh for each test (Vitest clears module cache). // vi.resetModules() in beforeEach gives each test a fresh `initialized` flag
// Using a dynamic import so vi.resetModules() takes effect. // and a fresh read of the stubbed VITE_POSTHOG_KEY.
return import('./posthog.ts'); const posthog = await import('./posthog.ts');
const consent = await import('./analytics-consent.ts');
return { ...posthog, ...consent };
} }
// ── Tests ───────────────────────────────────────────────────────────────────── // ── Tests ─────────────────────────────────────────────────────────────────────
describe('posthog.ts', () => { describe('posthog.ts (opt-in)', () => {
beforeEach(() => { beforeEach(() => {
vi.resetModules(); vi.resetModules();
mockCapture.mockClear(); vi.clearAllMocks();
mockInit.mockClear(); mockHasOptedOut.mockReturnValue(false);
localStorageMock.clear(); localStorageMock.clear();
}); });
afterEach(() => { afterEach(() => {
vi.clearAllMocks(); vi.unstubAllEnvs();
}); });
it('Test 1: VITE_POSTHOG_KEY absent → captureOnboardingComplete is a no-op', async () => { it('is a no-op without VITE_POSTHOG_KEY, even after a grant', async () => {
// Simulate absent key (import.meta.env.VITE_POSTHOG_KEY is undefined by default in test env)
vi.stubEnv('VITE_POSTHOG_KEY', ''); vi.stubEnv('VITE_POSTHOG_KEY', '');
const m = await importModules();
const { initPostHog, captureOnboardingComplete } = await importPostHog(); expect(m.hasAnalyticsKey()).toBe(false);
expect(m.shouldAskAnalyticsConsent()).toBe(false);
await initPostHog(); await m.setAnalyticsConsent('granted');
captureOnboardingComplete({ templateId: 'sales-pipeline', personaId: 'coder', model: 'claude-opus-4' }); await m.initPostHog();
m.captureOnboardingComplete(PAYLOAD);
expect(mockInit).not.toHaveBeenCalled(); expect(mockInit).not.toHaveBeenCalled();
expect(mockCapture).not.toHaveBeenCalled(); expect(mockCapture).not.toHaveBeenCalled();
vi.unstubAllEnvs();
}); });
it('Test 2: User opted out → captureOnboardingComplete is a no-op', async () => { it('sends nothing before the user chooses', async () => {
// Set the opt-out key before importing so the module reads it. vi.stubEnv('VITE_POSTHOG_KEY', TEST_KEY);
localStorageMock.setItem(OPT_OUT_KEY, 'true'); const m = await importModules();
vi.stubEnv('VITE_POSTHOG_KEY', 'phc_testkey12345678901234567890123456789012'); expect(m.readAnalyticsConsent()).toBeNull();
expect(m.shouldAskAnalyticsConsent()).toBe(true);
const { initPostHog, captureOnboardingComplete } = await importPostHog(); await m.initPostHog();
m.captureOnboardingComplete(PAYLOAD);
await initPostHog(); expect(mockInit).not.toHaveBeenCalled();
captureOnboardingComplete({ templateId: 'sales-pipeline', personaId: 'coder', model: 'claude-opus-4' });
// posthog.init may or may not have been called (depends on module load order),
// but posthog.capture must NOT have been called.
expect(mockCapture).not.toHaveBeenCalled(); expect(mockCapture).not.toHaveBeenCalled();
vi.unstubAllEnvs();
}); });
it('Test 3: Key present + opted in → captureOnboardingComplete calls posthog.capture', async () => { it('sends nothing after the user denies', async () => {
// Opted in (no opt-out key in localStorage). vi.stubEnv('VITE_POSTHOG_KEY', TEST_KEY);
localStorageMock.removeItem(OPT_OUT_KEY); const m = await importModules();
vi.stubEnv('VITE_POSTHOG_KEY', 'phc_testkey12345678901234567890123456789012'); await m.setAnalyticsConsent('denied');
await m.initPostHog();
m.captureOnboardingComplete(PAYLOAD);
const { initPostHog, captureOnboardingComplete } = await importPostHog(); expect(localStorageMock.getItem(CONSENT_KEY)).toBe('denied');
expect(m.shouldAskAnalyticsConsent()).toBe(false);
expect(mockInit).not.toHaveBeenCalled();
expect(mockCapture).not.toHaveBeenCalled();
});
await initPostHog(); it('treats the old opt-out marker as a denial', async () => {
localStorageMock.setItem(LEGACY_OPT_OUT_KEY, 'true');
vi.stubEnv('VITE_POSTHOG_KEY', TEST_KEY);
const m = await importModules();
const payload = { templateId: 'sales-pipeline', personaId: 'coder', model: 'claude-opus-4' }; expect(m.readAnalyticsConsent()).toBe('denied');
captureOnboardingComplete(payload); expect(m.shouldAskAnalyticsConsent()).toBe(false);
await m.initPostHog();
m.captureOnboardingComplete(PAYLOAD);
expect(mockInit).not.toHaveBeenCalled();
expect(mockCapture).not.toHaveBeenCalled();
});
it('initializes and captures onboarding_complete after a grant', async () => {
vi.stubEnv('VITE_POSTHOG_KEY', TEST_KEY);
const m = await importModules();
await m.setAnalyticsConsent('granted');
m.captureOnboardingComplete(PAYLOAD);
expect(localStorageMock.getItem(CONSENT_KEY)).toBe('granted');
expect(mockInit).toHaveBeenCalledOnce();
expect(mockInit).toHaveBeenCalledWith(TEST_KEY, expect.objectContaining({
autocapture: false,
capture_pageview: false,
disable_session_recording: true,
}));
expect(mockCapture).toHaveBeenCalledOnce(); expect(mockCapture).toHaveBeenCalledOnce();
expect(mockCapture).toHaveBeenCalledWith('onboarding_complete', { expect(mockCapture).toHaveBeenCalledWith('onboarding_complete', {
template_id: payload.templateId, template_id: PAYLOAD.templateId,
persona_id: payload.personaId, persona_id: PAYLOAD.personaId,
model: payload.model, model: PAYLOAD.model,
}); });
});
vi.unstubAllEnvs(); it('initializes on boot when consent was granted earlier', async () => {
localStorageMock.setItem(CONSENT_KEY, 'granted');
vi.stubEnv('VITE_POSTHOG_KEY', TEST_KEY);
const m = await importModules();
await m.initPostHog();
m.captureOnboardingComplete(PAYLOAD);
expect(mockInit).toHaveBeenCalledOnce();
expect(mockCapture).toHaveBeenCalledOnce();
});
it('stops capture at once when consent is withdrawn, and resumes without an $opt_in event', async () => {
vi.stubEnv('VITE_POSTHOG_KEY', TEST_KEY);
const m = await importModules();
await m.setAnalyticsConsent('granted');
await m.setAnalyticsConsent('denied');
m.captureOnboardingComplete(PAYLOAD);
expect(mockOptOut).toHaveBeenCalledOnce();
expect(mockReset).toHaveBeenCalledOnce();
expect(mockCapture).not.toHaveBeenCalled();
mockHasOptedOut.mockReturnValue(true);
await m.setAnalyticsConsent('granted');
m.captureOnboardingComplete(PAYLOAD);
expect(mockInit).toHaveBeenCalledOnce();
expect(mockOptIn).toHaveBeenCalledWith({ captureEventName: false });
expect(mockCapture).toHaveBeenCalledOnce();
}); });
}); });

View File

@@ -1,31 +1,22 @@
/** /**
* PostHog cloud analytics — project "Default project" (id 161685), org "Egzakta". * PostHog product analytics, opt-in only (ADR-0006).
* *
* Opt-in gate: Only fires when both of the following are true: * Nothing is initialized or captured unless BOTH hold:
* 1. VITE_POSTHOG_KEY is set at compile time (baked into the Vite bundle by P4-win build). * 1. VITE_POSTHOG_KEY was set when the bundle was built. Source builds have
* 2. The user has not opted out (no client-side telemetry-disabled marker in localStorage). * no key, so every function here is a silent no-op.
* 2. The user chose "Allow" (see `@/lib/analytics-consent`). No choice, a
* denial, or the old 'waggle:telemetry-opt-out' marker all mean "no".
* *
* No-op behavior: * The key is read through import.meta.env at Vite build time and is never
* - If VITE_POSTHOG_KEY is absent (key never baked in or dev machine without .env.local) * committed; release builds receive it from the build environment.
* → all functions are silent no-ops. App boots normally.
* - If user has opted out via localStorage('waggle:telemetry-opt-out') === 'true'
* → all capture calls are silently skipped.
* *
* IMPORTANT — COMPILE-TIME BAKE: * Events captured (the consent dialog lists these; keep it in sync):
* VITE_POSTHOG_KEY is read via import.meta.env at Vite bundle time. * - onboarding_complete: template_id, persona_id, model
* If the key is absent when `npm run tauri:build:win` runs, the shipped binary
* will have VITE_POSTHOG_KEY === undefined permanently — rebuilding is the only fix.
* Per Phase 2 plan, Marko must paste phc_* into apps/web/.env.local BEFORE the
* binary build (Wave 1 / P2b prerequisite for P4-win).
* *
* Usage: * Usage:
* import { initPostHog, captureOnboardingComplete } from '@/lib/posthog'; * initPostHog() // app boot; returns early without consent
* * captureOnboardingComplete(...) // OnboardingWizard, at completion
* // In main.tsx — call once on app boot (non-blocking): * stopPostHog() // consent withdrawn
* initPostHog().catch(() => {});
*
* // In OnboardingWizard.tsx — alongside existing trackTelemetry call:
* captureOnboardingComplete({ templateId, personaId, model });
*/ */
// no-external build: never lazy-loads remote chunks (config.js, recorder, // no-external build: never lazy-loads remote chunks (config.js, recorder,
@@ -34,64 +25,67 @@
// desktop webview, preserving Waggle's data-sovereignty posture. Only // desktop webview, preserving Waggle's data-sovereignty posture. Only
// the capture endpoint (us.i.posthog.com) is ever contacted. // the capture endpoint (us.i.posthog.com) is ever contacted.
import posthog from 'posthog-js/dist/module.no-external'; import posthog from 'posthog-js/dist/module.no-external';
import { isAnalyticsAllowed } from '@/lib/analytics-consent';
/** PostHog project API key — baked into bundle at Vite build time. */ /** PostHog project API key — baked into bundle at Vite build time. */
const PH_KEY: string | undefined = import.meta.env['VITE_POSTHOG_KEY'] as string | undefined; const PH_KEY: string | undefined = import.meta.env['VITE_POSTHOG_KEY'] as string | undefined;
/** PostHog ingestion host — us.i.posthog.com for project 161685. */ /** PostHog ingestion host. */
const PH_HOST = 'https://us.i.posthog.com'; const PH_HOST = 'https://us.i.posthog.com';
/** localStorage key used to persist the user's opt-out preference. */
const OPT_OUT_KEY = 'waggle:telemetry-opt-out';
let initialized = false; let initialized = false;
/** /**
* Returns true if the user has opted out of telemetry via the localStorage key. * Initialize PostHog. Call on app boot and again when the user allows analytics.
* Default (key absent or any value other than 'true') = opted IN. *
* - Silent no-op if VITE_POSTHOG_KEY is absent or the user has not allowed it.
* - Non-blocking: caller should wrap in try/catch or `.catch(() => {})`.
*/ */
function isOptedOut(): boolean { export async function initPostHog(): Promise<void> {
if (!PH_KEY || !isAnalyticsAllowed()) {
return;
}
try { try {
return window.localStorage.getItem(OPT_OUT_KEY) === 'true'; if (!initialized) {
posthog.init(PH_KEY, {
api_host: PH_HOST,
// Capture only explicit events — no auto-capture of clicks/pageviews.
autocapture: false,
capture_pageview: false,
// Disable persistence in cookies; use localStorage only (privacy-first).
persistence: 'localStorage',
opt_out_capturing_by_default: false,
// No /decide, /flags, or remote-config fetch — capture endpoint only.
// (Belt-and-suspenders with the no-external build above; keeps CSP at
// script-src 'self' and connect-src limited to the ingest host.)
advanced_disable_decide: true,
disable_session_recording: true,
});
initialized = true;
}
// A withdrawal earlier (this session or a past one) leaves PostHog's own
// opt-out flag set; clear it without sending an `$opt_in` event.
if (posthog.has_opted_out_capturing()) {
posthog.opt_in_capturing({ captureEventName: false });
}
} catch { } catch {
// localStorage unavailable (sandboxed, private browsing) — treat as opted out // PostHog init failure must never block app boot.
return true;
} }
} }
/** /**
* Initialize PostHog on app boot. * Stop capturing at once after consent is withdrawn and drop the PostHog
* * identity stored on this machine.
* - Silent no-op if VITE_POSTHOG_KEY is absent.
* - Silent no-op if user has opted out.
* - Non-blocking: caller should wrap in try/catch or `.catch(() => {})`.
*
* @returns Promise<void> — resolves when initialization is complete or skipped.
*/ */
export async function initPostHog(): Promise<void> { export function stopPostHog(): void {
if (!PH_KEY || initialized || isOptedOut()) { if (!initialized) {
return; return;
} }
try { try {
posthog.init(PH_KEY, { posthog.opt_out_capturing();
api_host: PH_HOST, posthog.reset();
// Capture only explicit events — no auto-capture of clicks/pageviews.
autocapture: false,
capture_pageview: false,
// Disable persistence in cookies; use localStorage only (privacy-first).
persistence: 'localStorage',
// Opt-in to telemetry is explicit (this init path only runs when opted-in).
opt_out_capturing_by_default: false,
// No /decide, /flags, or remote-config fetch — capture endpoint only.
// (Belt-and-suspenders with the no-external build above; keeps CSP at
// script-src 'self' and connect-src limited to the ingest host.)
advanced_disable_decide: true,
disable_session_recording: true,
});
initialized = true;
} catch { } catch {
// PostHog init failure must never block app boot. // Ignore.
initialized = false;
} }
} }
@@ -106,13 +100,13 @@ export interface OnboardingCompletePayload {
* Capture the `onboarding_complete` event alongside the existing local * Capture the `onboarding_complete` event alongside the existing local
* telemetry call in OnboardingWizard.tsx. * telemetry call in OnboardingWizard.tsx.
* *
* - Silent no-op if PostHog was not initialized (key absent or opted out). * - Silent no-op unless PostHog was initialized and analytics are still allowed.
* - Does NOT replace the existing `trackTelemetry` call — both fire together. * - Does NOT replace the existing `trackTelemetry` call — both fire together.
* *
* @param payload - Template, persona, and model selected during onboarding. * @param payload - Template, persona, and model selected during onboarding.
*/ */
export function captureOnboardingComplete(payload: OnboardingCompletePayload): void { export function captureOnboardingComplete(payload: OnboardingCompletePayload): void {
if (!initialized || isOptedOut()) { if (!initialized || !isAnalyticsAllowed()) {
return; return;
} }
try { try {
@@ -125,42 +119,3 @@ export function captureOnboardingComplete(payload: OnboardingCompletePayload): v
// Never throw — telemetry capture failures must not interrupt user flow. // Never throw — telemetry capture failures must not interrupt user flow.
} }
} }
/**
* Opt the current user out of PostHog telemetry.
* Persists the opt-out preference to localStorage and stops all future captures.
*/
export function optOutPostHog(): void {
try {
window.localStorage.setItem(OPT_OUT_KEY, 'true');
} catch {
// Ignore localStorage errors.
}
if (initialized) {
try {
posthog.opt_out_capturing();
} catch {
// Ignore.
}
}
}
/**
* Opt the current user back into PostHog telemetry.
* Removes the opt-out preference from localStorage.
* Note: initPostHog() must be called again if it was previously skipped.
*/
export function optInPostHog(): void {
try {
window.localStorage.removeItem(OPT_OUT_KEY);
} catch {
// Ignore localStorage errors.
}
if (initialized) {
try {
posthog.opt_in_capturing();
} catch {
// Ignore.
}
}
}

View File

@@ -35,9 +35,7 @@ export const APP_ROUTES = {
marketplace: '/marketplace', marketplace: '/marketplace',
launcher: '/launcher', launcher: '/launcher',
room: '/room', room: '/room',
'waggle-dance': '/waggle-dance',
approvals: '/approvals', approvals: '/approvals',
governance: '/team',
settings: '/settings', settings: '/settings',
vault: '/settings/vault', vault: '/settings/vault',
profile: '/settings/profile', profile: '/settings/profile',
@@ -103,7 +101,7 @@ export function queryString(params: { tab?: string; automationId?: string; sessi
* session / person / command — plus the executed-object types the old handler * session / person / command — plus the executed-object types the old handler
* also navigated (skill / connector / mcp). `person:` → null no-op (parity: * also navigated (skill / connector / mcp). `person:` → null no-op (parity:
* unhandled today too — the server intentionally doesn't federate `person` * unhandled today too — the server intentionally doesn't federate `person`
* yet, routes/command.ts:22-24; retarget to `/team` when it federates). * yet, routes/command.ts:22-24).
* Returns null when there is nothing to navigate to. * Returns null when there is nothing to navigate to.
*/ */
export function routeForSearchResult(type: string, id: string, ctx?: RouteContext): string | null { export function routeForSearchResult(type: string, id: string, ctx?: RouteContext): string | null {

View File

@@ -775,18 +775,3 @@ export interface ModelPricing {
estimatedCost?: { min: number; max: number }; estimatedCost?: { min: number; max: number };
} }
export interface WaggleSignal {
id: string;
type: 'discovery' | 'handoff' | 'insight' | 'alert' | 'coordination';
sourceWorkspaceId: string;
sourceWorkspaceName?: string;
sourceAgentId?: string;
sourceUser?: string;
targetWorkspaceId?: string;
title: string;
content: string;
metadata?: Record<string, unknown>;
timestamp: string;
acknowledged?: boolean;
priority?: 'low' | 'normal' | 'high' | 'critical';
}

View File

@@ -1,124 +0,0 @@
/**
* M-41 / P18 — waggle-signal sort + group regression.
*/
import { describe, it, expect } from 'vitest';
import {
sortSignalsForDisplay,
groupSignalsByType,
countUnacknowledged,
type WaggleSignalLike,
} from './waggle-signals';
function make(overrides: Partial<WaggleSignalLike> = {}): WaggleSignalLike {
return {
id: overrides.id ?? `s-${Math.random()}`,
type: overrides.type ?? 'discovery',
severity: overrides.severity ?? 'normal',
acknowledged: overrides.acknowledged ?? false,
timestamp: overrides.timestamp ?? '2026-04-19T00:00:00Z',
...overrides,
};
}
describe('sortSignalsForDisplay', () => {
it('surfaces unacknowledged before acknowledged', () => {
const input = [
make({ id: 'a', acknowledged: true }),
make({ id: 'b', acknowledged: false }),
];
expect(sortSignalsForDisplay(input).map(s => s.id)).toEqual(['b', 'a']);
});
it('within the same ack bucket, higher severity wins', () => {
const input = [
make({ id: 'normal', severity: 'normal' }),
make({ id: 'critical', severity: 'critical' }),
make({ id: 'high', severity: 'high' }),
make({ id: 'low', severity: 'low' }),
];
expect(sortSignalsForDisplay(input).map(s => s.id)).toEqual(['critical', 'high', 'normal', 'low']);
});
it('within the same severity, more recent timestamp wins', () => {
const input = [
make({ id: 'old', timestamp: '2026-04-10T00:00:00Z' }),
make({ id: 'new', timestamp: '2026-04-19T00:00:00Z' }),
make({ id: 'mid', timestamp: '2026-04-15T00:00:00Z' }),
];
expect(sortSignalsForDisplay(input).map(s => s.id)).toEqual(['new', 'mid', 'old']);
});
it('composes ack > severity > timestamp', () => {
const input = [
make({ id: 'ack-critical', acknowledged: true, severity: 'critical', timestamp: '2026-04-19T00:00:00Z' }),
make({ id: 'new-normal', acknowledged: false, severity: 'normal', timestamp: '2026-04-19T00:00:00Z' }),
make({ id: 'old-critical', acknowledged: false, severity: 'critical', timestamp: '2026-04-01T00:00:00Z' }),
];
// Unacknowledged first; within unack, critical > normal; within critical, only one item.
expect(sortSignalsForDisplay(input).map(s => s.id)).toEqual([
'old-critical', 'new-normal', 'ack-critical',
]);
});
it('tolerates missing / null fields', () => {
const input = [
make({ id: 'a', severity: null, timestamp: null }),
make({ id: 'b', severity: undefined, timestamp: undefined }),
];
// No crash — treat missing as normal / 0.
expect(sortSignalsForDisplay(input)).toHaveLength(2);
});
it('does not mutate the input array', () => {
const input = [make({ id: '1' }), make({ id: '2' })];
const before = input.slice();
sortSignalsForDisplay(input);
expect(input).toEqual(before);
});
it('parses numeric timestamps as raw ms', () => {
const input = [
make({ id: 'old', timestamp: 1000 }),
make({ id: 'new', timestamp: 2000 }),
];
expect(sortSignalsForDisplay(input).map(s => s.id)).toEqual(['new', 'old']);
});
});
describe('groupSignalsByType', () => {
it('groups by the type field', () => {
const input = [
make({ id: '1', type: 'discovery' }),
make({ id: '2', type: 'handoff' }),
make({ id: '3', type: 'discovery' }),
];
const groups = groupSignalsByType(input);
expect(groups.discovery?.map(s => s.id)).toEqual(['1', '3']);
expect(groups.handoff?.map(s => s.id)).toEqual(['2']);
});
it('buckets unknown types under "unknown"', () => {
const input = [make({ id: '1', type: 123 as unknown as string })];
const groups = groupSignalsByType(input);
expect(groups.unknown?.map(s => s.id)).toEqual(['1']);
});
});
describe('countUnacknowledged', () => {
it('counts only unacked items', () => {
const input = [
make({ acknowledged: false }),
make({ acknowledged: false }),
make({ acknowledged: true }),
];
expect(countUnacknowledged(input)).toBe(2);
});
it('treats missing acknowledged as false (unacked)', () => {
const input = [
{ id: '1', type: 'discovery' } as WaggleSignalLike,
{ id: '2', type: 'discovery', acknowledged: true } as WaggleSignalLike,
];
expect(countUnacknowledged(input)).toBe(1);
});
});

View File

@@ -1,73 +0,0 @@
/**
* WaggleSignal presentation helpers (M-41 / P18).
*
* The Waggle Dance app surfaces cross-agent signals (discovery,
* handoff, insight, alert, coordination). A user scanning the list
* wants unacknowledged items first, then the most severe items,
* then recency. This helper centralises that ordering so the UI
* stays consistent across list, counters, and summary surfaces.
*/
export type WaggleSignalType = 'discovery' | 'handoff' | 'insight' | 'alert' | 'coordination';
export interface WaggleSignalLike {
readonly id: string;
readonly type: WaggleSignalType | string;
readonly severity?: 'critical' | 'high' | 'normal' | 'low' | null;
readonly acknowledged?: boolean;
readonly timestamp?: string | number | null;
}
/** Severity weight: higher = surfaces earlier. */
const SEVERITY_WEIGHT: Record<string, number> = {
critical: 4,
high: 3,
normal: 2,
low: 1,
};
function severityScore(s: WaggleSignalLike): number {
const key = s.severity ?? 'normal';
return SEVERITY_WEIGHT[key] ?? SEVERITY_WEIGHT.normal;
}
function timestampMs(s: WaggleSignalLike): number {
const ts = s.timestamp;
if (typeof ts === 'number') return ts;
if (typeof ts === 'string') {
const parsed = Date.parse(ts);
return Number.isFinite(parsed) ? parsed : 0;
}
return 0;
}
/**
* Sort signals for display. Unacknowledged first, then severity desc,
* then timestamp desc. Returns a new array — does not mutate.
*/
export function sortSignalsForDisplay<T extends WaggleSignalLike>(signals: readonly T[]): T[] {
return [...signals].sort((a, b) => {
const ackA = a.acknowledged ? 1 : 0;
const ackB = b.acknowledged ? 1 : 0;
if (ackA !== ackB) return ackA - ackB;
const sevDiff = severityScore(b) - severityScore(a);
if (sevDiff !== 0) return sevDiff;
return timestampMs(b) - timestampMs(a);
});
}
/** Group signals by type for summary display. */
export function groupSignalsByType<T extends WaggleSignalLike>(signals: readonly T[]): Record<string, T[]> {
const out: Record<string, T[]> = {};
for (const s of signals) {
const type = typeof s.type === 'string' ? s.type : 'unknown';
if (!out[type]) out[type] = [];
out[type].push(s);
}
return out;
}
/** Count of unacknowledged signals — used for the header badge. */
export function countUnacknowledged(signals: readonly WaggleSignalLike[]): number {
return signals.reduce((n, s) => n + (s.acknowledged ? 0 : 1), 0);
}

View File

@@ -27,6 +27,7 @@ import { useShell } from '@/providers/ShellContext';
import { useMemory } from '@/hooks/useMemory'; import { useMemory } from '@/hooks/useMemory';
import { useKnowledgeGraph } from '@/hooks/useKnowledgeGraph'; import { useKnowledgeGraph } from '@/hooks/useKnowledgeGraph';
import { stashDeepLink } from '@/lib/app-deeplink'; import { stashDeepLink } from '@/lib/app-deeplink';
import { hasMemoryFeature, isMemoryViewAvailable } from '@/lib/memory-features';
const MemoryRoute = () => { const MemoryRoute = () => {
const { mindScope } = useParams(); const { mindScope } = useParams();
@@ -36,8 +37,9 @@ const MemoryRoute = () => {
const mind: MindScope = mindScope === 'workspace' ? 'workspace' : 'personal'; const mind: MindScope = mindScope === 'workspace' ? 'workspace' : 'personal';
const tabParam = searchParams.get('tab'); const tabParam = searchParams.get('tab');
// PR3.5: 'trust' (screen 19) is the new default landing; ?tab= still selects // PR3.5: 'trust' (screen 19) is the new default landing; ?tab= still selects
// any view (incl. the legacy 'memories' list and the 6 secondary views). // any view (incl. the legacy 'memories' list and the 6 secondary views),
const view: MemoryView = MEMORY_VIEWS.includes(tabParam as MemoryView) // except views of memory features hidden in v1 (ADR-0002).
const view: MemoryView = MEMORY_VIEWS.includes(tabParam as MemoryView) && isMemoryViewAvailable(tabParam as MemoryView)
? (tabParam as MemoryView) ? (tabParam as MemoryView)
: 'trust'; : 'trust';
@@ -75,7 +77,7 @@ const MemoryRoute = () => {
const { activeWorkspaceId, workspaces, setContextRailTarget } = useShell(); const { activeWorkspaceId, workspaces, setContextRailTarget } = useShell();
const memory = useMemory(activeWorkspaceId); const memory = useMemory(activeWorkspaceId);
const kg = useKnowledgeGraph(activeWorkspaceId); const kg = useKnowledgeGraph(activeWorkspaceId, hasMemoryFeature('knowledgeGraph'));
const wsId = activeWorkspaceId && activeWorkspaceId !== 'local-default' ? activeWorkspaceId : undefined; const wsId = activeWorkspaceId && activeWorkspaceId !== 'local-default' ? activeWorkspaceId : undefined;
const wsName = wsId ? workspaces.find(w => w.id === wsId)?.name : undefined; const wsName = wsId ? workspaces.find(w => w.id === wsId)?.name : undefined;

View File

@@ -1,15 +0,0 @@
/**
* P1a route wrapper — `/team` → TeamGovernanceApp (bare mount, Desktop.tsx:466).
* Reserved (§1.1): no nav entry points here — team mode is not shipped
* (ADR-0003). No new Team work (D5).
*/
import TeamGovernanceApp from '@/components/os/apps/TeamGovernanceApp';
import SurfaceBoundary from './SurfaceBoundary';
const TeamRoute = () => (
<SurfaceBoundary appName="Team Governance">
<TeamGovernanceApp />
</SurfaceBoundary>
);
export default TeamRoute;

View File

@@ -1,11 +0,0 @@
/** P1a route wrapper — `/waggle-dance` → WaggleDanceApp (bare mount, Desktop.tsx:433). */
import WaggleDanceApp from '@/components/os/apps/WaggleDanceApp';
import SurfaceBoundary from './SurfaceBoundary';
const WaggleDanceRoute = () => (
<SurfaceBoundary appName="Waggle Dance">
<WaggleDanceApp />
</SurfaceBoundary>
);
export default WaggleDanceRoute;

View File

@@ -19,9 +19,7 @@
* /marketplace MarketplaceRoute * /marketplace MarketplaceRoute
* /launcher LauncherRoute * /launcher LauncherRoute
* /room RoomRoute * /room RoomRoute
* /waggle-dance WaggleDanceRoute
* /approvals ApprovalsRoute * /approvals ApprovalsRoute
* /team TeamRoute
* /settings SettingsRoute * /settings SettingsRoute
* /settings/vault VaultRoute * /settings/vault VaultRoute
* /settings/profile ProfileRoute * /settings/profile ProfileRoute
@@ -43,9 +41,7 @@ export { default as McpsRoute } from './McpsRoute';
export { default as MarketplaceRoute } from './MarketplaceRoute'; export { default as MarketplaceRoute } from './MarketplaceRoute';
export { default as LauncherRoute } from './LauncherRoute'; export { default as LauncherRoute } from './LauncherRoute';
export { default as RoomRoute } from './RoomRoute'; export { default as RoomRoute } from './RoomRoute';
export { default as WaggleDanceRoute } from './WaggleDanceRoute';
export { default as ApprovalsRoute } from './ApprovalsRoute'; export { default as ApprovalsRoute } from './ApprovalsRoute';
export { default as TeamRoute } from './TeamRoute';
export { default as SettingsRoute } from './SettingsRoute'; export { default as SettingsRoute } from './SettingsRoute';
export { default as VaultRoute } from './VaultRoute'; export { default as VaultRoute } from './VaultRoute';
export { default as ProfileRoute } from './ProfileRoute'; export { default as ProfileRoute } from './ProfileRoute';

View File

@@ -0,0 +1,188 @@
/**
* ADR-0006 opt-in analytics: the first-run consent dialog and the Settings
* toggle that changes the choice later. posthog.test.ts covers the capture gate.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { TooltipProvider } from '@/components/ui/tooltip';
const mocks = vi.hoisted(() => ({
adapter: {
getSettings: vi.fn(),
getPermissions: vi.fn(),
getTelemetryStatus: vi.fn(),
getServerUrl: vi.fn(),
getProviders: vi.fn(),
getLocalInferenceStatus: vi.fn(),
probeModel: vi.fn(),
probeProvider: vi.fn(),
toggleTelemetry: vi.fn(),
clearTelemetry: vi.fn(),
},
posthog: {
initPostHog: vi.fn(),
stopPostHog: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/lib/posthog', () => mocks.posthog);
import AnalyticsConsentDialog from '@/components/os/overlays/AnalyticsConsentDialog';
import SettingsApp from '@/components/os/apps/SettingsApp';
import {
ANALYTICS_CONSENT_KEY,
readAnalyticsConsent,
shouldAskAnalyticsConsent,
} from '@/lib/analytics-consent';
const TEST_KEY = 'phc_testkey12345678901234567890123456789012';
function renderDialog(onClose = vi.fn()) {
const opener = document.createElement('button');
opener.textContent = 'opener';
document.body.appendChild(opener);
opener.focus();
const utils = render(<AnalyticsConsentDialog onClose={onClose} />);
return { ...utils, onClose, opener };
}
beforeEach(() => {
vi.clearAllMocks();
window.localStorage.clear();
document.body.innerHTML = '';
mocks.posthog.initPostHog.mockResolvedValue(undefined);
mocks.adapter.getSettings.mockResolvedValue({});
mocks.adapter.getPermissions.mockResolvedValue({ defaultAutonomy: 'normal', externalGates: [] });
mocks.adapter.getTelemetryStatus.mockResolvedValue({ enabled: false, totalEvents: 0 });
mocks.adapter.getServerUrl.mockReturnValue('http://127.0.0.1:3333');
mocks.adapter.getProviders.mockResolvedValue({ providers: [], search: [], activeSearch: 'duckduckgo' });
mocks.adapter.getLocalInferenceStatus.mockResolvedValue({ servers: [], ollamaInstalled: false, totalLocalModels: 0 });
mocks.adapter.probeModel.mockResolvedValue({ configured: false });
mocks.adapter.probeProvider.mockResolvedValue({ configured: false, valid: false, verified: false });
mocks.adapter.toggleTelemetry.mockResolvedValue(undefined);
mocks.adapter.clearTelemetry.mockResolvedValue({ deleted: 0 });
});
afterEach(() => {
cleanup();
vi.unstubAllEnvs();
});
describe('when to ask', () => {
it('never asks when the build has no PostHog key', () => {
vi.stubEnv('VITE_POSTHOG_KEY', '');
expect(shouldAskAnalyticsConsent()).toBe(false);
});
it('asks when a key is present and the user has not chosen', () => {
vi.stubEnv('VITE_POSTHOG_KEY', TEST_KEY);
expect(shouldAskAnalyticsConsent()).toBe(true);
window.localStorage.setItem(ANALYTICS_CONSENT_KEY, 'denied');
expect(shouldAskAnalyticsConsent()).toBe(false);
});
});
describe('AnalyticsConsentDialog', () => {
beforeEach(() => {
vi.stubEnv('VITE_POSTHOG_KEY', TEST_KEY);
});
it('is a labelled modal dialog that takes focus and lists what is sent', () => {
renderDialog();
const dialog = screen.getByRole('dialog', { name: /share anonymous usage analytics/i });
expect(dialog).toHaveAttribute('aria-modal', 'true');
expect(dialog).toHaveFocus();
expect(dialog).toHaveTextContent(/one event when you finish onboarding/i);
expect(dialog).toHaveTextContent(/chats, files and memories are never sent/i);
});
it('Escape closes without granting and returns focus', () => {
const { onClose, opener } = renderDialog();
fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });
expect(onClose).toHaveBeenCalledOnce();
expect(readAnalyticsConsent()).toBeNull();
expect(mocks.posthog.initPostHog).not.toHaveBeenCalled();
expect(mocks.adapter.toggleTelemetry).not.toHaveBeenCalled();
cleanup();
expect(opener).toHaveFocus();
});
it('Allow stores the grant and starts analytics', async () => {
const { onClose } = renderDialog();
fireEvent.click(screen.getByRole('button', { name: /^allow$/i }));
expect(onClose).toHaveBeenCalledOnce();
expect(readAnalyticsConsent()).toBe('granted');
await waitFor(() => expect(mocks.posthog.initPostHog).toHaveBeenCalledOnce());
expect(mocks.adapter.toggleTelemetry).toHaveBeenCalledWith(true);
});
it("Don't allow stores the denial and starts nothing", async () => {
const { onClose } = renderDialog();
fireEvent.click(screen.getByRole('button', { name: /don't allow/i }));
expect(onClose).toHaveBeenCalledOnce();
expect(readAnalyticsConsent()).toBe('denied');
await waitFor(() => expect(mocks.posthog.stopPostHog).toHaveBeenCalledOnce());
expect(mocks.posthog.initPostHog).not.toHaveBeenCalled();
expect(mocks.adapter.toggleTelemetry).toHaveBeenCalledWith(false);
});
});
describe('Settings analytics toggle', () => {
function renderSettings() {
return render(
<MemoryRouter initialEntries={['/settings?tab=general']}>
<TooltipProvider>
<SettingsApp />
</TooltipProvider>
</MemoryRouter>,
);
}
it('with a key, shows the consent state at every level and turning it off stops capture', async () => {
vi.stubEnv('VITE_POSTHOG_KEY', TEST_KEY);
window.localStorage.setItem(ANALYTICS_CONSENT_KEY, 'granted');
renderSettings();
const toggle = await screen.findByRole('button', { name: /disable anonymous usage analytics/i });
expect(toggle).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(toggle);
expect(readAnalyticsConsent()).toBe('denied');
await waitFor(() => expect(mocks.posthog.stopPostHog).toHaveBeenCalledOnce());
expect(mocks.adapter.toggleTelemetry).toHaveBeenCalledWith(false);
expect(await screen.findByRole('button', { name: /enable anonymous usage analytics/i }))
.toHaveAttribute('aria-pressed', 'false');
});
it('with a key and no choice yet, the toggle is off and turning it on grants', async () => {
vi.stubEnv('VITE_POSTHOG_KEY', TEST_KEY);
mocks.adapter.getTelemetryStatus.mockResolvedValue({ enabled: true, totalEvents: 2 });
renderSettings();
const toggle = await screen.findByRole('button', { name: /enable anonymous usage analytics/i });
await screen.findByText(/2 events collected/i);
expect(toggle).toHaveAttribute('aria-pressed', 'false');
fireEvent.click(toggle);
expect(readAnalyticsConsent()).toBe('granted');
await waitFor(() => expect(mocks.posthog.initPostHog).toHaveBeenCalledOnce());
expect(mocks.adapter.toggleTelemetry).toHaveBeenCalledWith(true);
});
it('without a key, the toggle only drives the local log', async () => {
vi.stubEnv('VITE_POSTHOG_KEY', '');
renderSettings();
expect(screen.queryByRole('button', { name: /usage analytics/i })).not.toBeInTheDocument();
await screen.findByRole('group', { name: /settings detail level/i });
fireEvent.click(screen.getByRole('button', { name: /everything/i }));
fireEvent.click(screen.getByRole('tab', { name: /^general$/i }));
fireEvent.click(await screen.findByRole('button', { name: /enable anonymous telemetry/i }));
await waitFor(() => expect(mocks.adapter.toggleTelemetry).toHaveBeenCalledWith(true));
expect(readAnalyticsConsent()).toBeNull();
expect(mocks.posthog.initPostHog).not.toHaveBeenCalled();
});
});

View File

@@ -39,6 +39,7 @@ describe('build warning hygiene', () => {
'OnboardingTooltips', 'OnboardingTooltips',
'LoginBriefing', 'LoginBriefing',
'ContextRail', 'ContextRail',
'AnalyticsConsentDialog',
]) { ]) {
expect(shellSource).not.toContain(`import ${overlay} from './overlays/${overlay}'`); expect(shellSource).not.toContain(`import ${overlay} from './overlays/${overlay}'`);
expect(shellSource).toContain(`lazy(() => import('./overlays/${overlay}'))`); expect(shellSource).toContain(`lazy(() => import('./overlays/${overlay}'))`);

View File

@@ -0,0 +1,67 @@
/**
* ADR-0002: the v1 memory feature map and the onboarding import step it hides.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, cleanup, waitFor } from '@testing-library/react';
import { hasMemoryFeature, isMemoryViewAvailable, type MemoryFeature } from '@/lib/memory-features';
const mocks = vi.hoisted(() => ({
adapter: {
connect: vi.fn(),
getProfile: vi.fn(),
trackTelemetry: vi.fn(),
scanClaudeCode: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/hooks/useOfflineStatus', () => ({ useOfflineStatus: () => false }));
vi.mock('@/lib/posthog', () => ({ captureOnboardingComplete: vi.fn() }));
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
describe('memory feature map (v1 defaults)', () => {
it.each<MemoryFeature>(['knowledgeGraph', 'importHistory', 'wiki', 'agentHooks', 'room', 'memoryMcp'])(
'%s is hidden',
(feature) => {
expect(hasMemoryFeature(feature)).toBe(false);
},
);
it('keeps the v1 Memory Center views and hides Graph, Imports and Wiki', () => {
for (const view of ['trust', 'memories', 'timeline', 'weaver']) {
expect(isMemoryViewAvailable(view), view).toBe(true);
}
for (const view of ['graph', 'harvest', 'wiki']) {
expect(isMemoryViewAvailable(view), view).toBe(false);
}
});
});
describe('OnboardingWizard without history import', () => {
it('resumes a persisted import step on the template step and never scans Claude Code', async () => {
mocks.adapter.connect.mockResolvedValue(undefined);
mocks.adapter.getProfile.mockResolvedValue(null);
const { default: OnboardingWizard } = await import('@/components/os/overlays/OnboardingWizard');
render(
<OnboardingWizard
serverBaseUrl="http://127.0.0.1:3333"
state={{ completed: false, step: 3 }}
onUpdate={vi.fn()}
onComplete={vi.fn()}
onDismiss={vi.fn()}
onFinish={vi.fn()}
/>,
);
expect(await screen.findByRole('heading', { name: /pick a starting point/i })).toBeInTheDocument();
// who-are-you · model · template · first-task: the import step has no number.
expect(screen.getByText('Step 3 of 4')).toBeInTheDocument();
await waitFor(() => expect(mocks.adapter.getProfile).toHaveBeenCalled());
expect(mocks.adapter.scanClaudeCode).not.toHaveBeenCalled();
});
});

View File

@@ -20,19 +20,19 @@ import {
type DockEntry, type DockEntry,
} from '@/lib/dock-tiers'; } from '@/lib/dock-tiers';
/** Every AppId in the union (dock-tiers.ts:7-18) — keep in sync; 28 ids. */ /** Every AppId in the union (dock-tiers.ts:7-18) — keep in sync; 26 ids. */
const ALL_APP_IDS: AppId[] = [ const ALL_APP_IDS: AppId[] = [
'home', 'chat', 'dashboard', 'memory', 'events', 'home', 'chat', 'dashboard', 'memory', 'events',
'capabilities', 'connectors', 'cockpit', 'mission-control', 'capabilities', 'connectors', 'cockpit', 'mission-control',
'settings', 'vault', 'profile', 'settings', 'vault', 'profile',
'waggle-dance', 'files', 'artifacts', 'agents', 'files', 'artifacts', 'agents',
'scheduled-jobs', 'marketplace', 'voice', 'room', 'approvals', 'timeline', 'scheduled-jobs', 'marketplace', 'voice', 'room', 'approvals', 'timeline',
'backup', 'telemetry', 'governance', 'launcher', 'backup', 'telemetry', 'launcher',
'workspace-desktop', 'mcp-hub', 'workspace-desktop', 'mcp-hub',
]; ];
describe('routeFor — §1.1 table', () => { describe('routeFor — §1.1 table', () => {
it('maps every static AppId exactly per the table (22 routed ids)', () => { it('maps every static AppId exactly per the table (20 routed ids)', () => {
const expected: Record<string, string> = { const expected: Record<string, string> = {
home: '/home', home: '/home',
memory: '/memory', memory: '/memory',
@@ -46,9 +46,7 @@ describe('routeFor — §1.1 table', () => {
marketplace: '/marketplace', marketplace: '/marketplace',
launcher: '/launcher', launcher: '/launcher',
room: '/room', room: '/room',
'waggle-dance': '/waggle-dance',
approvals: '/approvals', approvals: '/approvals',
governance: '/team',
settings: '/settings', settings: '/settings',
vault: '/settings/vault', vault: '/settings/vault',
profile: '/settings/profile', profile: '/settings/profile',
@@ -60,7 +58,7 @@ describe('routeFor — §1.1 table', () => {
for (const [appId, route] of Object.entries(expected)) { for (const [appId, route] of Object.entries(expected)) {
expect(routeFor(appId as AppId), appId).toBe(route); expect(routeFor(appId as AppId), appId).toBe(route);
} }
expect(Object.keys(expected)).toHaveLength(22); expect(Object.keys(expected)).toHaveLength(20);
}); });
it('retargets the 4 KILLED ids per §2.2 (dashboard/voice/mission-control → /home, backup → /settings?tab=backup)', () => { it('retargets the 4 KILLED ids per §2.2 (dashboard/voice/mission-control → /home, backup → /settings?tab=backup)', () => {
@@ -85,8 +83,8 @@ describe('routeFor — §1.1 table', () => {
expect(routeFor('workspace-desktop', { activeWorkspaceId: 'local-default' })).toBe('/home'); expect(routeFor('workspace-desktop', { activeWorkspaceId: 'local-default' })).toBe('/home');
}); });
it('is total over all 28 AppIds (never throws, never returns empty)', () => { it('is total over all 26 AppIds (never throws, never returns empty)', () => {
expect(ALL_APP_IDS).toHaveLength(28); expect(ALL_APP_IDS).toHaveLength(26);
for (const appId of ALL_APP_IDS) { for (const appId of ALL_APP_IDS) {
const route = routeFor(appId, { activeWorkspaceId: 'ws-x' }); const route = routeFor(appId, { activeWorkspaceId: 'ws-x' });
expect(route, appId).toMatch(/^\//); expect(route, appId).toMatch(/^\//);
@@ -233,7 +231,6 @@ describe('dock-tiers route field — §1.3 invariant', () => {
const power = getDockForTier('power'); const power = getDockForTier('power');
const entries = flattenAppEntries(power); const entries = flattenAppEntries(power);
expect(entries.some(e => e.appId === 'approvals')).toBe(true); expect(entries.some(e => e.appId === 'approvals')).toBe(true);
expect(entries.some(e => e.appId === 'governance')).toBe(false);
expect(entries.some(e => e.route === '/team')).toBe(false); expect(entries.some(e => e.route === '/team')).toBe(false);
expect(power.some(e => e.key === 'team')).toBe(false); expect(power.some(e => e.key === 'team')).toBe(false);
}); });

View File

@@ -10,6 +10,9 @@
* - WorkspaceDesktopApp's memory tab embeds the per-mind list with * - WorkspaceDesktopApp's memory tab embeds the per-mind list with
* mind='workspace' + consumeDeepLinks=false (the J08 stash belongs to the * mind='workspace' + consumeDeepLinks=false (the J08 stash belongs to the
* /memory route instance). * /memory route instance).
* - Graph, Imports and Wiki are hidden in v1 by the memory feature map
* (ADR-0002). The URL-wiring suite switches them on to keep the hidden
* views covered; the "v1 memory features" suite checks the default.
*/ */
import { describe, it, expect, vi, afterEach } from 'vitest'; import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, waitFor, cleanup, fireEvent } from '@testing-library/react'; import { render, screen, waitFor, cleanup, fireEvent } from '@testing-library/react';
@@ -33,6 +36,16 @@ const mocks = vi.hoisted(() => ({
})); }));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() })); vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
const features = vi.hoisted(() => ({ enabled: true }));
vi.mock('@/lib/memory-features', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/memory-features')>();
return {
...actual,
hasMemoryFeature: (f: Parameters<typeof actual.hasMemoryFeature>[0]) => features.enabled || actual.hasMemoryFeature(f),
isMemoryViewAvailable: (view: string) => features.enabled || actual.isMemoryViewAvailable(view),
};
});
vi.mock('@/providers/ShellContext', () => ({ useShell: () => mocks.shell })); vi.mock('@/providers/ShellContext', () => ({ useShell: () => mocks.shell }));
vi.mock('@/hooks/useRoomState', () => ({ useRoomState: () => ({ workspaceMap: new Map() }) })); vi.mock('@/hooks/useRoomState', () => ({ useRoomState: () => ({ workspaceMap: new Map() }) }));
vi.mock('@/hooks/useOnboarding', () => ({ useOnboarding: () => ({ state: { completed: true } }) })); vi.mock('@/hooks/useOnboarding', () => ({ useOnboarding: () => ({ state: { completed: true } }) }));
@@ -92,7 +105,7 @@ async function renderRoute(path: string) {
); );
} }
afterEach(() => { cleanup(); vi.clearAllMocks(); mocks.shell.activeWorkspaceId = 'w1'; consumeDeepLink('memory'); }); afterEach(() => { cleanup(); vi.clearAllMocks(); mocks.shell.activeWorkspaceId = 'w1'; consumeDeepLink('memory'); features.enabled = true; });
describe('MemoryRoute + MemoryCenterApp URL wiring (P3/D2)', () => { describe('MemoryRoute + MemoryCenterApp URL wiring (P3/D2)', () => {
it('/memory defaults to the personal mind on the Trust view (PR3.5 new front door)', async () => { it('/memory defaults to the personal mind on the Trust view (PR3.5 new front door)', async () => {
@@ -207,6 +220,31 @@ describe('MemoryRoute + MemoryCenterApp URL wiring (P3/D2)', () => {
}); });
}); });
describe('v1 memory features (ADR-0002): Graph, Imports and Wiki are hidden', () => {
it.each(['graph', 'harvest', 'wiki'])('?tab=%s falls back to the Trust default', async (tabId) => {
features.enabled = false;
await renderRoute(`/memory?tab=${tabId}`);
expect(screen.getByTestId('stub-trust')).toBeTruthy();
expect(screen.queryByTestId(`stub-${tabId}`)).toBeNull();
});
it('offers no Graph tab and keeps only Maintenance under Advanced', async () => {
features.enabled = false;
await renderRoute('/memory');
expect(screen.queryByRole('tab', { name: /graph/i })).toBeNull();
fireEvent.click(screen.getByTestId('memory-tab-advanced'));
const menu = screen.getByTestId('memory-tab-advanced-menu');
expect(menu).toHaveTextContent('Maintenance');
expect(menu).not.toHaveTextContent(/imports|wiki/i);
});
it('?tab=weaver still mounts Maintenance', async () => {
features.enabled = false;
await renderRoute('/memory?tab=weaver');
expect(screen.getByTestId('stub-weaver')).toBeTruthy();
});
});
describe('WorkspaceDesktopApp memory tab embed (P3/D2, S02-FR2)', () => { describe('WorkspaceDesktopApp memory tab embed (P3/D2, S02-FR2)', () => {
it('renders the workspace-mind list instead of the placeholder', async () => { it('renders the workspace-mind list instead of the placeholder', async () => {
mocks.adapter.getWorkspaceContext.mockResolvedValue({ mocks.adapter.getWorkspaceContext.mockResolvedValue({

View File

@@ -1,6 +1,6 @@
/** /**
* P7/D15 B5 — error states that hooks already capture but components dropped. * P7/D15 B5 — error states that hooks already capture but components dropped.
* Covers WaggleDanceApp + EventsApp (error≠empty) and TimelineTab (error≠empty). * Covers EventsApp (error≠empty) and TimelineTab (error≠empty).
* The SettingsApp missing-.catch defect is structurally verified separately. * The SettingsApp missing-.catch defect is structurally verified separately.
*/ */
import { describe, it, expect, vi, afterEach } from 'vitest'; import { describe, it, expect, vi, afterEach } from 'vitest';
@@ -8,12 +8,7 @@ import { render as rtlRender, screen, cleanup, fireEvent } from '@testing-librar
import type { ReactElement } from 'react'; import type { ReactElement } from 'react';
import { TooltipProvider } from '@/components/ui/tooltip'; import { TooltipProvider } from '@/components/ui/tooltip';
const mocks = vi.hoisted(() => ({
useWaggleDance: vi.fn(),
}));
vi.mock('@/lib/adapter', () => ({ adapter: {}, default: vi.fn() })); vi.mock('@/lib/adapter', () => ({ adapter: {}, default: vi.fn() }));
vi.mock('@/hooks/useWaggleDance', () => ({ useWaggleDance: mocks.useWaggleDance }));
const render = (ui: ReactElement) => rtlRender(<TooltipProvider>{ui}</TooltipProvider>); const render = (ui: ReactElement) => rtlRender(<TooltipProvider>{ui}</TooltipProvider>);
@@ -22,27 +17,6 @@ afterEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
}); });
describe('P7/B5 — WaggleDanceApp action names', () => {
it('names the refresh action', async () => {
const refresh = vi.fn();
mocks.useWaggleDance.mockReturnValue({
signals: [],
allSignals: [],
loading: false,
error: null,
filter: 'all',
setFilter: vi.fn(),
refresh,
acknowledge: vi.fn(),
});
const { default: WaggleDanceApp } = await import('@/components/os/apps/WaggleDanceApp');
render(<WaggleDanceApp />);
expect(screen.getByRole('button', { name: /refresh waggle dance/i })).toBeInTheDocument();
});
});
describe('P7/B5 — EventsApp error state', () => { describe('P7/B5 — EventsApp error state', () => {
it('renders an error (not "No events yet") when error is set', async () => { it('renders an error (not "No events yet") when error is set', async () => {
const { default: EventsApp } = await import('@/components/os/apps/EventsApp'); const { default: EventsApp } = await import('@/components/os/apps/EventsApp');

View File

@@ -57,6 +57,7 @@ Baseline: commit `b20b138` of `git.os-dev.tech/oleg.m/waggle-os`.
| UF-026 | Three memory tools of the agent are never wired | Open | Agent, memory | | UF-026 | Three memory tools of the agent are never wired | Open | Agent, memory |
| UF-027 | Self-learning loops run on data nothing collects | Open | Agent, self-learning | | UF-027 | Self-learning loops run on data nothing collects | Open | Agent, self-learning |
| UF-028 | The Settings prompt-shape choice has no effect on chat | Open | Web UI, chat | | UF-028 | The Settings prompt-shape choice has no effect on chat | Open | Web UI, chat |
| UF-029 | The Settings "Import Data" button does nothing | Open | Web UI |
## Entries ## Entries
@@ -285,3 +286,12 @@ Entries UF-010 to UF-019 come from the UI audit `anti-slop/audit-001-2026-10-14.
- What we did: nothing yet. The setting stays in the community edition until its fate is decided. - What we did: nothing yet. The setting stays in the community edition until its fate is decided.
- Recommendation: pass `shape` into the chat agent loop as `agent-run.ts` does, or hide the dropdown until it works. - Recommendation: pass `shape` into the chat agent loop as `agent-run.ts` does, or hide the dropdown until it works.
### UF-029. The Settings "Import Data" button does nothing
- Status: Open
- Found: 2026-10-23
- Where: `apps/web/src/components/os/apps/SettingsApp.tsx:772` (commit `ad2ca87`), the Backup section
- Symptom: Settings → Backup shows an "Import Data — Import from ChatGPT or Claude export" button; clicking it has no effect.
- Cause: the `<button>` has no `onClick` handler and is not wired to the import flow.
- What we did: import history is hidden in the community edition v1 (decision Q2), so the button is hidden behind the memory feature map rather than wired.
- Recommendation: connect it to the existing import flow (the Memory → Imports screen) or remove it.

View File

@@ -217,21 +217,6 @@ const PERSONAS: PersonaBundle[] = [
], ],
expected: /360 events|Used bulk_tool_000/i, expected: /360 events|Used bulk_tool_000/i,
}, },
{
id: 'wiki-export-obsidian-failure',
path: '/memory?tab=wiki',
action: 'wiki-export-obsidian-failure',
mocks: [
{ url: '**/api/wiki/pages', status: 200, body: wikiPages() },
{
url: '**/api/wiki/export/obsidian',
status: 500,
body: { error: 'Disk permission denied for C:/Research Vault' },
},
],
expected: /Export Failed|Disk permission denied for C:\/Research Vault/i,
expectedConsoleErrors: [/Failed to load resource: the server responded with a status of 500/i],
},
], ],
}, },
{ {
@@ -366,7 +351,6 @@ const PERSONAS: PersonaBundle[] = [
nonMainGateDecisions: ['T13/T14/T15 evidenced or explicitly deferred for launch, desktop, and admin/utility paths.'], nonMainGateDecisions: ['T13/T14/T15 evidenced or explicitly deferred for launch, desktop, and admin/utility paths.'],
routes: [ routes: [
{ id: 'vault', path: '/settings/vault', expected: /vault|secret|encrypted|key/i }, { id: 'vault', path: '/settings/vault', expected: /vault|secret|encrypted|key/i },
{ id: 'team', path: '/team', expected: /team|governance|permission|member|upgrade/i },
{ id: 'approvals', path: '/approvals', expected: /approval|pending|risk|agent/i }, { id: 'approvals', path: '/approvals', expected: /approval|pending|risk|agent/i },
], ],
failureProbes: [ failureProbes: [
@@ -696,19 +680,6 @@ function largeMemoryList(count = 200): unknown {
}; };
} }
function wikiPages(): unknown[] {
return [{
slug: 'research-guide',
pageType: 'entity',
name: 'Research Guide',
contentHash: 'hash-research-guide',
markdown: '# Research Guide\n\nField notes for the Researcher judge export-failure lane.',
frameIds: 'memory-1',
compiledAt: '2026-07-09T12:00:00.000Z',
sourceCount: 3,
}];
}
function approvalGrants(): unknown[] { function approvalGrants(): unknown[] {
return [{ return [{
id: 'grant-send-email', id: 'grant-send-email',

View File

@@ -69,7 +69,6 @@ async function openCurrentApp(page: Page, label: string) {
Timeline: '/settings/timeline', Timeline: '/settings/timeline',
'Usage & Cost': '/settings/usage', 'Usage & Cost': '/settings/usage',
'Events & Logs': '/settings/events', 'Events & Logs': '/settings/events',
'Team Governance': '/team',
'Skills Hub': '/skills', 'Skills Hub': '/skills',
'Connector Hub': '/connectors', 'Connector Hub': '/connectors',
'MCP Hub': '/mcps', 'MCP Hub': '/mcps',
@@ -263,7 +262,6 @@ const ZONE_APPS = [
{ label: 'Timeline', zone: 'System', expect: /timeline|activity|no.*activity|last/i }, { label: 'Timeline', zone: 'System', expect: /timeline|activity|no.*activity|last/i },
{ label: 'Usage & Cost', zone: 'System', expect: /usage|telemetry|token|cost/i }, { label: 'Usage & Cost', zone: 'System', expect: /usage|telemetry|token|cost/i },
{ label: 'Events & Logs', zone: 'System', expect: /event|log|step|filter/i }, { label: 'Events & Logs', zone: 'System', expect: /event|log|step|filter/i },
{ label: 'Team Governance', zone: 'Team', expect: /governance|role|team|permission/i },
{ label: 'Skills Hub', zone: 'Intelligence', expect: /skill|installed|marketplace|starter|build/i }, { label: 'Skills Hub', zone: 'Intelligence', expect: /skill|installed|marketplace|starter|build/i },
{ label: 'Connector Hub', zone: 'Extend', expect: /connector|connect|service|integration/i }, { label: 'Connector Hub', zone: 'Extend', expect: /connector|connect|service|integration/i },
{ label: 'MCP Hub', zone: 'Extend', expect: /mcp|installed|catalog|server/i }, { label: 'MCP Hub', zone: 'Extend', expect: /mcp|installed|catalog|server/i },

View File

@@ -76,7 +76,9 @@ test.describe('Launcher rendered states', () => {
await expect(page.getByText(/sidecar may be offline/i)).not.toBeVisible(); await expect(page.getByText(/sidecar may be offline/i)).not.toBeVisible();
}); });
test('long hook stderr is summarized instead of flooding the rendered panel', async ({ page }) => { // Agent memory hooks are hidden in v1 by the memory feature map (ADR-0002,
// apps/web/src/lib/memory-features.ts). Re-enable with the agentHooks feature.
test.skip('long hook stderr is summarized instead of flooding the rendered panel', async ({ page }) => {
await mockProcesses(page); await mockProcesses(page);
await page.route('**/api/tools/detect', route => route.fulfill({ await page.route('**/api/tools/detect', route => route.fulfill({
status: 200, status: 200,
@@ -134,7 +136,9 @@ test.describe('Launcher rendered states', () => {
await expect(page.getByText('Recovery')).toBeVisible(); await expect(page.getByText('Recovery')).toBeVisible();
}); });
test('standard hook install output renders changed file, pointer, backup, and recovery labels', async ({ page }) => { // Agent memory hooks are hidden in v1 by the memory feature map (ADR-0002,
// apps/web/src/lib/memory-features.ts). Re-enable with the agentHooks feature.
test.skip('standard hook install output renders changed file, pointer, backup, and recovery labels', async ({ page }) => {
await mockProcesses(page); await mockProcesses(page);
await page.route('**/api/tools/detect', route => route.fulfill({ await page.route('**/api/tools/detect', route => route.fulfill({
status: 200, status: 200,
@@ -192,7 +196,9 @@ test.describe('Launcher rendered states', () => {
await expect(page.getByText(/hive-mind\/codex-hooks: install/i)).not.toBeVisible(); await expect(page.getByText(/hive-mind\/codex-hooks: install/i)).not.toBeVisible();
}); });
test('all hook-capable tools render install, verify, and uninstall state transitions', async ({ page }) => { // Agent memory hooks are hidden in v1 by the memory feature map (ADR-0002,
// apps/web/src/lib/memory-features.ts). Re-enable with the agentHooks feature.
test.skip('all hook-capable tools render install, verify, and uninstall state transitions', async ({ page }) => {
const hookState = new Map(HOOK_RENDER_CASES.map(tool => [tool.id, false])); const hookState = new Map(HOOK_RENDER_CASES.map(tool => [tool.id, false]));
await mockProcesses(page); await mockProcesses(page);
@@ -312,8 +318,9 @@ test.describe('Launcher rendered states', () => {
await expect(page.getByText('Foo CLI', { exact: true })).toBeVisible(); await expect(page.getByText('Foo CLI', { exact: true })).toBeVisible();
await expect(page.getByText(/v2\.1\.0/i)).toBeVisible(); await expect(page.getByText(/v2\.1\.0/i)).toBeVisible();
await expect(page.getByText(/Sent to:/i)).not.toBeVisible(); await expect(page.getByText(/Sent to:/i)).not.toBeVisible();
await expect(page.getByText(/Launch only/i)).toBeVisible(); // Hooks are hidden in v1 (ADR-0002), so there is no "launch only" contrast.
await expect(page.getByText(/Hook management is not supported for this tool yet/i)).toBeVisible(); await expect(page.getByText(/Launch only/i)).not.toBeVisible();
await expect(page.getByText(/Hook management is not supported for this tool yet/i)).not.toBeVisible();
await expect(page.getByRole('button', { name: /^Launch$/ })).toBeVisible(); await expect(page.getByRole('button', { name: /^Launch$/ })).toBeVisible();
await expect(page.getByRole('button', { name: /install hooks/i })).not.toBeVisible(); await expect(page.getByRole('button', { name: /install hooks/i })).not.toBeVisible();
await expect(page.getByRole('button', { name: /^Verify$/ })).not.toBeVisible(); await expect(page.getByRole('button', { name: /^Verify$/ })).not.toBeVisible();

View File

@@ -486,8 +486,8 @@ test.describe('10. Fresh User Onboarding', () => {
await onboarding.getByRole('button', { name: /continue/i }).click(); await onboarding.getByRole('button', { name: /continue/i }).click();
await onboarding.getByRole('button', { name: /continue/i }).click(); await onboarding.getByRole('button', { name: /continue/i }).click();
await expect(onboarding.getByRole('button', { name: /continue/i })).toBeEnabled({ timeout: 10_000 }); await expect(onboarding.getByRole('button', { name: /continue/i })).toBeEnabled({ timeout: 10_000 });
// History import is hidden in v1 (ADR-0002): the model step leads straight to templates.
await onboarding.getByRole('button', { name: /continue/i }).click(); await onboarding.getByRole('button', { name: /continue/i }).click();
await onboarding.getByRole('button', { name: /skip this step/i }).click();
await expect(page.getByText(/Research Hub|Engineering|Sales Pipeline/i).first()).toBeVisible({ timeout: 5_000 }); await expect(page.getByText(/Research Hub|Engineering|Sales Pipeline/i).first()).toBeVisible({ timeout: 5_000 });
}); });

View File

@@ -1,4 +1,4 @@
import { expect, test, type APIRequestContext, type Page } from '@playwright/test'; import { expect, test, type Page } from '@playwright/test';
import { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module'; import { createRequire } from 'node:module';
@@ -27,10 +27,7 @@ const ROUTES = [
'/memory?tab=trust', '/memory?tab=trust',
'/memory?tab=memories', '/memory?tab=memories',
'/memory?tab=timeline', '/memory?tab=timeline',
'/memory?tab=graph',
'/memory?tab=harvest',
'/memory?tab=weaver', '/memory?tab=weaver',
'/memory?tab=wiki',
'/workspaces', '/workspaces',
'/workspaces/default-workspace/chat', '/workspaces/default-workspace/chat',
'/workspaces/default-workspace/tasks', '/workspaces/default-workspace/tasks',
@@ -38,7 +35,6 @@ const ROUTES = [
'/automations', '/automations',
'/skills', '/skills',
'/room', '/room',
'/waggle-dance',
'/launcher', '/launcher',
'/connectors', '/connectors',
'/mcps', '/mcps',
@@ -46,7 +42,6 @@ const ROUTES = [
'/files', '/files',
'/approvals', '/approvals',
'/artifacts', '/artifacts',
'/team',
'/benchmarks', '/benchmarks',
'/platform', '/platform',
] as const; ] as const;
@@ -107,40 +102,25 @@ function formatViolations(violations: AxeViolation[]) {
})); }));
} }
async function seedWaggleDanceSignal(request: APIRequestContext) {
const response = await request.post('/api/waggle/signals', {
data: {
type: 'discovery',
workspaceId: 'default-workspace',
content: 'Accessible signal timestamp',
metadata: { senderId: 'runtime-a11y' },
},
});
expect(response.status()).toBe(201);
}
test.describe('Runtime accessibility smoke', () => { test.describe('Runtime accessibility smoke', () => {
test('milestone toast and signal badges have no mobile accessibility violations', async ({ page, request }) => { test('milestone toast has no mobile accessibility violations', async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 }); await page.setViewportSize({ width: 390, height: 844 });
await seedWaggleDanceSignal(request);
await page.addInitScript(() => { await page.addInitScript(() => {
window.localStorage.setItem('waggle:session-count', '49'); window.localStorage.setItem('waggle:session-count', '49');
window.localStorage.setItem('waggle:dock-nudge-dismissed', '[10]'); window.localStorage.setItem('waggle:dock-nudge-dismissed', '[10]');
}); });
await gotoApp(page, '/waggle-dance'); await gotoApp(page, '/agents');
await expect(page.getByText('50 sessions in — nicely done', { exact: true })).toBeVisible(); await expect(page.getByText('50 sessions in — nicely done', { exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: 'Close notification' })).toHaveCSS('opacity', '1'); await expect(page.getByRole('button', { name: 'Close notification' })).toHaveCSS('opacity', '1');
await expect(page.getByTestId('waggle-unacknowledged-count')).toBeVisible();
expect(formatViolations(await runAxe(page))).toEqual([]); expect(formatViolations(await runAxe(page))).toEqual([]);
}); });
for (const viewport of VIEWPORTS) { for (const viewport of VIEWPORTS) {
test(`axe has no violations across core routes (${viewport.name})`, async ({ page, request }) => { test(`axe has no violations across core routes (${viewport.name})`, async ({ page }) => {
test.setTimeout(150_000); test.setTimeout(150_000);
await page.setViewportSize({ width: viewport.width, height: viewport.height }); await page.setViewportSize({ width: viewport.width, height: viewport.height });
await seedWaggleDanceSignal(request);
const findings: Array<{ route: string; violations: ReturnType<typeof formatViolations> }> = []; const findings: Array<{ route: string; violations: ReturnType<typeof formatViolations> }> = [];
for (const route of ROUTES) { for (const route of ROUTES) {

View File

@@ -349,7 +349,9 @@ test.describe('User Journey Tests', () => {
await expect.poll(() => allowCalled).toBe(true); await expect.poll(() => allowCalled).toBe(true);
}); });
test('J3g: wiki export destinations use in-app forms', async ({ page }) => { // The wiki is hidden in v1 by the memory feature map (ADR-0002,
// apps/web/src/lib/memory-features.ts). Re-enable with the wiki feature.
test.skip('J3g: wiki export destinations use in-app forms', async ({ page }) => {
const nativeDialogs: string[] = []; const nativeDialogs: string[] = [];
let obsidianCalled = false; let obsidianCalled = false;
let notionCalled = false; let notionCalled = false;
@@ -898,7 +900,6 @@ test.describe('User Journey Tests', () => {
const routeChecks: Array<[string, RegExp]> = [ const routeChecks: Array<[string, RegExp]> = [
['/launcher', /tool launcher|optional prompt|detecting installed tools|launch/i], ['/launcher', /tool launcher|optional prompt|detecting installed tools|launch/i],
['/launcher?watch=1', /tool launcher|optional prompt|detecting installed tools|launch/i], ['/launcher?watch=1', /tool launcher|optional prompt|detecting installed tools|launch/i],
['/waggle-dance', /waggle dance|signals|discovery|handoff/i],
['/artifacts', /artifact|library|document|presentation/i], ['/artifacts', /artifact|library|document|presentation/i],
['/settings/profile', /who are you|identity|writing style|save/i], ['/settings/profile', /who are you|identity|writing style|save/i],
['/settings/timeline', /timeline|workspace|activity/i], ['/settings/timeline', /timeline|workspace|activity/i],