diff --git a/apps/web/.env.example b/apps/web/.env.example index 58830b4..7e62e16 100644 --- a/apps/web/.env.example +++ b/apps/web/.env.example @@ -2,13 +2,11 @@ # Copy to .env.local and fill in the real values. # NEVER commit .env.local — it is gitignored. -# PostHog cloud analytics — project "Default project" id 161685, org "Egzakta" -# Required for DAY0-04 (≥ 5 distinct onboarding_complete in 24h post-launch). -# The REAL phc_* key is pasted into apps/web/.env.local at Wave 1 / P2b -# and is BAKED INTO THE TAURI BUNDLE at P4-win compile time — if missing -# at build moment, the shipped binary has PostHog as a permanent no-op. -# Local SQLite telemetry (packages/core/src/telemetry.ts) continues alongside. -VITE_POSTHOG_KEY=phc_REPLACE_ME +# PostHog product analytics, opt-in only (docs/oss/adr/0006-opt-in-analytics.md). +# Leave unset for builds from source: without a key nothing is sent and the +# consent dialog never appears. Release builds get the key from the build +# environment; Vite reads it at build time, so it cannot be added afterwards. +# VITE_POSTHOG_KEY= # 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 diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 64c97bd..a4db485 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -26,9 +26,7 @@ const McpsRoute = lazy(() => import("@/routes/McpsRoute")); const MarketplaceRoute = lazy(() => import("@/routes/MarketplaceRoute")); const LauncherRoute = lazy(() => import("@/routes/LauncherRoute")); const RoomRoute = lazy(() => import("@/routes/RoomRoute")); -const WaggleDanceRoute = lazy(() => import("@/routes/WaggleDanceRoute")); const ApprovalsRoute = lazy(() => import("@/routes/ApprovalsRoute")); -const TeamRoute = lazy(() => import("@/routes/TeamRoute")); const SettingsRoute = lazy(() => import("@/routes/SettingsRoute")); const VaultRoute = lazy(() => import("@/routes/VaultRoute")); const ProfileRoute = lazy(() => import("@/routes/ProfileRoute")); @@ -145,15 +143,12 @@ const App = () => ( )} /> )} /> )} /> - )} /> )} /> {/* ── Extend ── */} )} /> )} /> )} /> )} /> - {/* ── Team (route registered; no nav entry — team mode is not shipped, ADR-0003) ── */} - )} /> {/* ── System (§9.4: System surfaces nest under /settings/*) ── */} )} /> )} /> diff --git a/apps/web/src/components/os/AppShell.tsx b/apps/web/src/components/os/AppShell.tsx index 765ead8..0a8476f 100644 --- a/apps/web/src/components/os/AppShell.tsx +++ b/apps/web/src/components/os/AppShell.tsx @@ -15,7 +15,7 @@ import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { AnimatePresence } from 'framer-motion'; 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 wallpaperLight from '@/assets/wallpaper-light.jpg'; import BootScreen from './BootScreen'; @@ -28,6 +28,7 @@ import { stashDeepLink } from '@/lib/app-deeplink'; import { writeLoginBriefingDismissed, writeLoginBriefingLastDismissedAt, readLoginBriefingDismissed, readSkipBriefingParam } from '@/lib/login-briefing'; import { prefetchBriefing, computeAwayDays, BRIEFING_ABSENCE_DAYS } from '@/lib/briefing-source'; import { homeCacheExists } from '@/lib/home-cache'; +import { shouldAskAnalyticsConsent } from '@/lib/analytics-consent'; import { resolveReturningUserOnboarding, isOnboardingStatusKnownSync } from '@/hooks/useOnboarding'; import { shouldShowCoachMarks, readOnboardedThisSession, readForceTour, clearForceTour } from '@/lib/coach-marks-gate'; 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 { seedChat, useChatWidgetState } from '@/hooks/useChatWidgetState'; import { useKeyboardShortcuts } from '@/hooks/useKeyboardShortcuts'; -import { useWaggleDance } from '@/hooks/useWaggleDance'; import { useBumpSessionCount } from '@/hooks/useDockLabels'; import { useDockNudge } from '@/hooks/useDockNudge'; import { useToast } from '@/hooks/use-toast'; @@ -56,6 +56,7 @@ const OnboardingWizard = lazy(() => import('./overlays/OnboardingWizard')); const OnboardingTooltips = lazy(() => import('./overlays/OnboardingTooltips')); const LoginBriefing = lazy(() => import('./overlays/LoginBriefing')); const ContextRail = lazy(() => import('./overlays/ContextRail')); +const AnalyticsConsentDialog = lazy(() => import('./overlays/AnalyticsConsentDialog')); const deferredShellElement = (element: ReactNode) => ( {element} @@ -129,12 +130,10 @@ const ShellLayout = () => { contextRailTarget, setContextRailTarget, } = useShell(); - const { allSignals: waggleSignals } = useWaggleDance(); const overlaysRef = useRef(ov); useEffect(() => { overlaysRef.current = ov; }, [ov]); - const waggleUnacknowledged = waggleSignals.filter(s => !s.acknowledged).length; // W2A: no implicit workspaces[0] fallback — the chrome shows a workspace only // when one was explicitly selected. Sidebar/StatusBar accept null names; the // Chat spine item opens the WorkspaceSwitcher when there is no real selection. @@ -189,6 +188,9 @@ const ShellLayout = () => { const { entry: activeChatEntry, setPersona: setActiveChatPersona } = 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 // 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 @@ -372,9 +374,7 @@ const ShellLayout = () => { const briefingAwayDays = useMemo(() => computeAwayDays(workspaces), [workspaces]); // 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 - // Agents & tasks badge surfaces unacknowledged coordination signals for now; - // PR3 refines it to the real pending-approvals/tasks count. + // workspace's chat tab (routeFor falls back to /home with no workspace). const isPro = currentTier === 'power' || currentTier === 'admin'; const spine: SidebarNavItem[] = useMemo(() => [ { key: 'home', label: 'Home', icon: Home, to: '/home', match: ['/home'] }, @@ -392,13 +392,12 @@ const ShellLayout = () => { onClick: navigateToActiveChat, }, { 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'] }, - ], [effectiveActiveWorkspaceId, navigateToActiveChat, waggleUnacknowledged]); + ], [effectiveActiveWorkspaceId, navigateToActiveChat]); const pinned: SidebarNavItem[] = useMemo(() => { if (!isPro) 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: 'approvals', label: 'Approvals', icon: Shield, to: '/approvals', match: ['/approvals'] }, ]; @@ -417,11 +416,21 @@ const ShellLayout = () => { } }, [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( + setAskAnalyticsConsent(false)} /> + ); + // FR #33: when the onboarding wizard is active, render ONLY the wizard — // no nav, no canvas, no overlays (§1.2 OnboardingWizard row: full-screen // takeover at the layout level, any URL). Hooks above keep running so // completion re-renders with workspaces/personas already populated. if (!onboardingState.completed) { + if (analyticsConsentDialog) return analyticsConsentDialog; return deferredShellElement( { const anyModalOpen = ov.showGlobalSearch || ov.showCreateWorkspace || ov.showPersonaSwitcher || ov.showWorkspaceSwitcher || ov.showNotifications || ov.showKeyboardHelp || - ov.showSpawnAgent; + ov.showSpawnAgent || askAnalyticsConsent; return ( @@ -574,7 +583,7 @@ const ShellLayout = () => { 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. */} {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 && ( deferredShellElement( { {contextRailTarget && deferredShellElement( setContextRailTarget(null)} /> )} + {analyticsConsentDialog} ); }; diff --git a/apps/web/src/components/os/RouteTransition.test.tsx b/apps/web/src/components/os/RouteTransition.test.tsx index 98596bc..1529bc7 100644 --- a/apps/web/src/components/os/RouteTransition.test.tsx +++ b/apps/web/src/components/os/RouteTransition.test.tsx @@ -65,7 +65,7 @@ describe('routeGroupKey — keys on the top segment only', () => { describe('routeAnnouncement — the polite-live-region label', () => { it('labels known surfaces', () => { expect(routeAnnouncement('/memory')).toBe('Memory'); - expect(routeAnnouncement('/waggle-dance')).toBe('Agent swarm'); + expect(routeAnnouncement('/approvals')).toBe('Approvals'); expect(routeAnnouncement('/workspaces/abc/chat')).toBe('Workspaces'); }); diff --git a/apps/web/src/components/os/apps/AgentsApp.tsx b/apps/web/src/components/os/apps/AgentsApp.tsx index 9c68852..3880c9e 100644 --- a/apps/web/src/components/os/apps/AgentsApp.tsx +++ b/apps/web/src/components/os/apps/AgentsApp.tsx @@ -1,6 +1,6 @@ import { useState, useEffect, useCallback, useMemo } from 'react'; 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 BeeLoader from '@/components/ui/BeeLoader'; import { adapter } from '@/lib/adapter'; @@ -291,36 +291,6 @@ const AgentsApp = ({ workspaces, activeWorkspaceId }: AgentsAppProps) => { - {/* 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. */} - - 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)' }} - > - - - - - Run a team of agents - - waggle-dance · let several specialists coordinate on one goal - - - - Start a swarm - - - - {/* List */} {/* A post-action reload failure must be visible even when a stale diff --git a/apps/web/src/components/os/apps/AllWorkspacesApp.test.tsx b/apps/web/src/components/os/apps/AllWorkspacesApp.test.tsx index ec9430d..7d8c46d 100644 --- a/apps/web/src/components/os/apps/AllWorkspacesApp.test.tsx +++ b/apps/web/src/components/os/apps/AllWorkspacesApp.test.tsx @@ -3,7 +3,7 @@ * Pins the contract: * - renders a grid card per workspace (name + real stats) * - 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) * - NO-FABRICATION: a workspace with undefined memoryCount renders NO memory * chip (W2B: not even a filler "—"), never an invented number (PR3/PR3.5) diff --git a/apps/web/src/components/os/apps/AllWorkspacesApp.tsx b/apps/web/src/components/os/apps/AllWorkspacesApp.tsx index f9e2ce6..830a72e 100644 --- a/apps/web/src/components/os/apps/AllWorkspacesApp.tsx +++ b/apps/web/src/components/os/apps/AllWorkspacesApp.tsx @@ -80,7 +80,6 @@ const STORAGE_FILTERS: { id: StorageFilter; label: string; dot?: string }[] = [ { id: 'all', label: 'All' }, { id: 'virtual', label: 'Virtual', dot: 'var(--intel)' }, { id: 'local', label: 'Local', dot: 'var(--honey)' }, - { id: 'team', label: 'Team', dot: 'var(--healthy)' }, ]; /** Storage badge: Local=honey, Virtual=intel, Team=healthy (design §04). */ diff --git a/apps/web/src/components/os/apps/ApprovalsApp.tsx b/apps/web/src/components/os/apps/ApprovalsApp.tsx index 80e60df..affd249 100644 --- a/apps/web/src/components/os/apps/ApprovalsApp.tsx +++ b/apps/web/src/components/os/apps/ApprovalsApp.tsx @@ -8,9 +8,8 @@ * 2. Grants — persistent "always allow" decisions. Revoke individually * or clear the whole list. * - * This is the trust control surface for enterprise buyers. Every decision - * the user has made about agent autonomy lives here, visible and - * reversible. + * This is the trust control surface: every decision the user has made + * about agent autonomy lives here, visible and reversible. */ import { useState, useEffect, useCallback } from 'react'; diff --git a/apps/web/src/components/os/apps/BenchmarkApp.tsx b/apps/web/src/components/os/apps/BenchmarkApp.tsx index e5d5462..63ee23e 100644 --- a/apps/web/src/components/os/apps/BenchmarkApp.tsx +++ b/apps/web/src/components/os/apps/BenchmarkApp.tsx @@ -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: 'Skills shared across agents/workspaces', marks: ['Y', 'P', 'P', 'N', 'P', 'N'] }, { 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: 'Deep coding in the terminal', marks: ['P', 'Y', 'Y', 'P', 'P', 'Y'] }, ]; diff --git a/apps/web/src/components/os/apps/ChatApp.tsx b/apps/web/src/components/os/apps/ChatApp.tsx index b196267..6d89a9c 100644 --- a/apps/web/src/components/os/apps/ChatApp.tsx +++ b/apps/web/src/components/os/apps/ChatApp.tsx @@ -26,13 +26,6 @@ import { import { useToast } from '@/hooks/use-toast'; import { DUR } from '@/lib/motion/tokens'; -export interface TeamMember { - id: string; - name: string; - status: string; - avatar?: string; -} - type AutonomyLevel = 'normal' | 'trusted' | 'yolo'; interface ChatAppProps { @@ -49,7 +42,6 @@ interface ChatAppProps { currentModel?: string; onModelChange?: (model: string) => void; availableModels?: string[]; - teamPresence?: TeamMember[]; sessions?: { id: string; title: string; messageCount?: number; lastActive?: string }[]; activeSessionId?: string | null; onSelectSession?: (id: string) => void; @@ -557,7 +549,6 @@ const ChatApp = ({ messages, isLoading, onSendMessage, onClearHistory, pendingApproval, onApprove, currentPersona, onPersonaChange, currentModel, onModelChange, availableModels, - teamPresence, sessions, activeSessionId, onSelectSession, onNewSession, workspaceId, templateId, storageType, autonomyLevel = 'normal', autonomyExpiresAt = null, onAutonomyChange, @@ -612,19 +603,12 @@ const ChatApp = ({ const modelPickerRef = useRef(null); // 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 - // chips (storage badge, team presence) should fold into a ⋯ overflow menu. + // chips (storage badge) should fold into a ⋯ overflow menu. const stripRef = useRef(null); const overflowRef = useRef(null); const stripWidth = useContainerWidth(stripRef); 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 // recent assistant message. Empty array → no chips. Hidden while // the assistant is still streaming to avoid flickering chips as @@ -1573,7 +1557,7 @@ const ChatApp = ({ - {/* 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 narrow. Interactive controls (persona, autonomy, model) stay always visible. */} @@ -1590,37 +1574,9 @@ const ChatApp = ({ )} - {/* 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 && ( - m.name).join(', ')}`} - > - - {roomPresence.slice(0, 4).map(m => ( - - - {m.avatar ? : null} - {m.name[0]} - - - - ))} - - {roomPresence.length > 4 && ( - +{roomPresence.length - 4} - )} - - )} - {/* ⋯ overflow menu — only rendered in compact mode and only when there's at least one informational chip to show. */} - {isStripCompact && (storageType || roomPresence.length > 0) && ( + {isStripCompact && storageType && ( setShowHeaderOverflow(p => !p)} @@ -1650,23 +1606,6 @@ const ChatApp = ({ )} - {roomPresence.length > 0 && ( - - In this room - - {roomPresence.map(m => ( - - - {m.avatar ? : null} - {m.name[0]} - - {m.name} - - - ))} - - - )} )} @@ -1674,7 +1613,7 @@ const ChatApp = ({ {/* 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). */} {/* Phase B.5: autonomy toggle — only render when the parent wired a handler */} diff --git a/apps/web/src/components/os/apps/ChatWindowInstance.tsx b/apps/web/src/components/os/apps/ChatWindowInstance.tsx index 2a9a83e..939435e 100644 --- a/apps/web/src/components/os/apps/ChatWindowInstance.tsx +++ b/apps/web/src/components/os/apps/ChatWindowInstance.tsx @@ -5,7 +5,6 @@ import { useToast } from '@/hooks/use-toast'; import { adapter } from '@/lib/adapter'; import { formatModelLabel } from '@/lib/model-label'; import ChatApp from './ChatApp'; -import type { TeamMember } from './ChatApp'; type AutonomyLevel = 'normal' | 'trusted' | 'yolo'; @@ -104,7 +103,6 @@ const ChatWindowInstance = ({ }); const [availableModels, setAvailableModels] = useState([]); - const [teamPresence, setTeamPresence] = useState([]); const { toast } = useToast(); @@ -202,25 +200,11 @@ const ChatWindowInstance = ({ if (!currentLanded) fetchCurrentModel(); }, 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(); }; window.addEventListener('focus', refreshModelsOnFocus); return () => { cancelled = true; window.removeEventListener('focus', refreshModelsOnFocus); - clearInterval(teamInterval); clearInterval(retryInterval); }; }, []); @@ -273,7 +257,6 @@ const ChatWindowInstance = ({ currentModel={currentModel} onModelChange={handleModelChange} availableModels={availableModels} - teamPresence={teamPresence} sessions={displaySessions} activeSessionId={activeSessionId} onSelectSession={setActiveSessionId} diff --git a/apps/web/src/components/os/apps/FilesAppTabs.tsx b/apps/web/src/components/os/apps/FilesAppTabs.tsx index 8115133..aa45d00 100644 --- a/apps/web/src/components/os/apps/FilesAppTabs.tsx +++ b/apps/web/src/components/os/apps/FilesAppTabs.tsx @@ -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 * remount intentionally resets per-storage navigation state (currentPath, * selection, preview) so flipping back to Virtual doesn't carry a local diff --git a/apps/web/src/components/os/apps/LauncherApp.test.tsx b/apps/web/src/components/os/apps/LauncherApp.test.tsx index 1ad4e7f..68bc052 100644 --- a/apps/web/src/components/os/apps/LauncherApp.test.tsx +++ b/apps/web/src/components/os/apps/LauncherApp.test.tsx @@ -7,6 +7,10 @@ * * These tests assert the toggle wiring and that Variation B carries the * 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 { 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() })); +const features = vi.hoisted(() => ({ enabled: true })); +vi.mock('@/lib/memory-features', () => ({ hasMemoryFeature: () => features.enabled })); + import LauncherApp, { resetLauncherRouteCache } from './LauncherApp'; const detectionResp = { @@ -43,6 +50,7 @@ const detectionResp = { }; beforeEach(() => { + features.enabled = true; resetLauncherRouteCache(); mocks.adapter.detectTools.mockResolvedValue(detectionResp); 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(); }); }); + +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(); + + 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(); + }); +}); diff --git a/apps/web/src/components/os/apps/LauncherApp.tsx b/apps/web/src/components/os/apps/LauncherApp.tsx index 4b0cbda..7dc1495 100644 --- a/apps/web/src/components/os/apps/LauncherApp.tsx +++ b/apps/web/src/components/os/apps/LauncherApp.tsx @@ -30,6 +30,7 @@ import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { ScrollArea } from '@/components/ui/scroll-area'; import { adapter } from '@/lib/adapter'; +import { hasMemoryFeature } from '@/lib/memory-features'; import { createSurfaceCache } from '@/lib/surface-cache'; import { promptArgsForTool, @@ -291,6 +292,10 @@ const hookActionDetails = ( const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: LauncherAppProps = {}) => { const [view, setView] = useState('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 [detection, setDetection] = useState(cachedDetection ?? null); const [loading, setLoading] = useState(() => !launcherRouteCache.hasResolved('tools')); @@ -596,6 +601,7 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche )} + {hooksShown && ( ))} + )} {view === 'a' && ( @@ -624,7 +631,7 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche )} - {view === 'b' ? ( + {view === 'b' && hooksShown ? ( ) : ( <> @@ -746,8 +753,8 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche )} {tools.map((tool) => { const launchable = toolCanLaunch(tool); - const hooksSupported = HOOKS_COHORT.includes(tool.id); - const launchOnly = launchable && !hooksSupported; + const hooksSupported = hooksShown && HOOKS_COHORT.includes(tool.id); + const launchOnly = hooksShown && launchable && !hooksSupported; const isActive = activeAction?.toolId === tool.id; return ( )} - {tool.hooksInstalled && tool.releaseStatus !== 'roadmap' && ( + {hooksShown && tool.hooksInstalled && tool.releaseStatus !== 'roadmap' && ( Hooks active @@ -834,7 +841,7 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche )} Launch - {toolCanRunCapturedTask(tool) && ( + {roomShown && toolCanRunCapturedTask(tool) && ( )} - {taskToolId === tool.id && toolCanRunCapturedTask(tool) && ( + {roomShown && taskToolId === tool.id && toolCanRunCapturedTask(tool) && ( { // Reminder-banner eligibility (carried over from the retired MemoryApp shell). 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. 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 // Trust↔Memories pair especially) rather than hard-cutting — a keyed @@ -104,11 +111,13 @@ const MemoryCenterApp = ({ return ( - onViewChange('harvest')} - /> + {hasMemoryFeature('importHistory') && ( + onViewChange('harvest')} + /> + )} {/* 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). @@ -117,7 +126,7 @@ const MemoryCenterApp = ({ not three. Every destination is preserved; only the chrome collapses. */} - {PRIMARY_TABS.map((tab, i) => { + {primaryTabs.map((tab, i) => { const Icon = tab.icon; const active = view === tab.id; return ( @@ -146,10 +155,11 @@ const MemoryCenterApp = ({ {/* Advanced — a flyout tab holding the maintenance/import views. The trigger names the active child (e.g. "Advanced: Imports") so a deep-linked ?tab=harvest never looks like no tab is selected. */} + {advancedTabs.length > 0 && ( - + t.label).join(', ')}> setAdvancedOpen(o => !o)} @@ -178,7 +188,7 @@ const MemoryCenterApp = ({ 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" > - {ADVANCED_TABS.map((tab) => { + {advancedTabs.map((tab) => { const Icon = tab.icon; const active = view === tab.id; return ( @@ -204,6 +214,7 @@ const MemoryCenterApp = ({ )} + )} {/* Mind pills — folded onto the tab row (Wave T Lane D item 4). Only on @@ -277,9 +288,9 @@ const MemoryCenterApp = ({ ) : view === 'weaver' ? ( - ) : ( + ) : view === 'wiki' ? ( - )} + ) : null} diff --git a/apps/web/src/components/os/apps/PlatformApp.tsx b/apps/web/src/components/os/apps/PlatformApp.tsx index c5bd06e..c47f0fc 100644 --- a/apps/web/src/components/os/apps/PlatformApp.tsx +++ b/apps/web/src/components/os/apps/PlatformApp.tsx @@ -37,7 +37,7 @@ const SPECS: ReadonlyArray = [ { value: '~12 MB', label: 'Install size' }, { value: 'Local', label: 'Data on your disk' }, { value: 'Auto-update', label: 'Signed & notarized' }, - { value: 'Win · Mac', label: 'Linux soon' }, + { value: 'Win · Mac · Linux', label: 'Desktop platforms' }, ]; interface BootStep { @@ -67,7 +67,7 @@ const CHANNELS: ReadonlyArray = [ icon: Monitor, title: 'Desktop app', blurb: 'The full hive — native, local, fast.', - platforms: ['macOS', 'Windows', 'Linux soon'], + platforms: ['macOS', 'Windows', 'Linux'], status: 'now', statusLabel: 'Available now', tint: 'var(--honey-wash)', @@ -177,8 +177,8 @@ function DesktopView({ os, onOsChange }: DesktopViewProps) { title={<>A real desktop app.>} blurb={ <> - Waggle ships as a native app for Windows & macOS — built on - Tauri, so it’s tiny, fast, and truly local. Your hive lives on your disk; the app just opens a + Waggle runs as a native app on Windows, macOS and Linux. It is + built on Tauri, so it’s tiny, fast, and truly local. Your hive lives on your disk; the app just opens a window onto it. > } diff --git a/apps/web/src/components/os/apps/SettingsApp.tsx b/apps/web/src/components/os/apps/SettingsApp.tsx index a1b7b23..6c6e847 100644 --- a/apps/web/src/components/os/apps/SettingsApp.tsx +++ b/apps/web/src/components/os/apps/SettingsApp.tsx @@ -24,6 +24,8 @@ import { resolveActiveSettingsTab, } from '@/lib/settings-tier-filter'; 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 ModelPilotCard from '@/components/os/ModelPilotCard'; import EmbeddingRoutingCard from '@/components/os/EmbeddingRoutingCard'; @@ -137,8 +139,11 @@ const SettingsApp = () => { // focus-visible, testable confirm row. const [pendingYolo, setPendingYolo] = useState(false); - // M2-7: Telemetry state - const [telemetryEnabled, setTelemetryEnabled] = useState(false); + // M2-7: Telemetry state. ADR-0006: when the build has a PostHog key, this one + // 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 // can't be tier-gated. Dialog handles the typed-phrase confirmation gate // + presents the receipt + relaunch instruction on success. @@ -183,10 +188,10 @@ const SettingsApp = () => { // .catch — a getTelemetryStatus rejection became an unhandled promise // rejection (its siblings above all swallow). Match the local pattern. adapter.getTelemetryStatus().then(s => { - setTelemetryEnabled(s.enabled); + if (!analyticsKey) setTelemetryEnabled(s.enabled); setTelemetryCount(s.totalEvents); }).catch(() => {}); - }, []); + }, [analyticsKey]); const handleSaveModel = async () => { setSaving(true); @@ -432,28 +437,41 @@ const SettingsApp = () => { {/* 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 - already opting into more advanced surface area). */} - {userTier !== 'simple' && ( + already opting into more advanced surface area). ADR-0006: shown at every level + when the build has a PostHog key, so analytics consent can always be withdrawn. */} + {(userTier !== 'simple' || analyticsKey) && ( Privacy & Telemetry - - 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. - + {analyticsKey ? ( + + 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. + + ) : ( + + 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. + + )} - Enable anonymous telemetry + + {analyticsKey ? 'Share anonymous usage analytics' : 'Enable anonymous telemetry'} + {telemetryCount} events collected { const next = !telemetryEnabled; setTelemetryEnabled(next); + // Store the consent first: capture stops before any await. + if (analyticsKey) void setAnalyticsConsent(next ? 'granted' : 'denied'); await adapter.toggleTelemetry(next); }} 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 - 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 .waggle-backup 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 .waggle-backup if you might want to restore. Data already sent to cloud model providers is not erased. Ask those providers to delete it. setShowEraseDialog(true)} @@ -769,6 +787,7 @@ const SettingsApp = () => { Download all workspaces, sessions, and memory as a zip + {hasMemoryFeature('importHistory') && ( @@ -776,6 +795,7 @@ const SettingsApp = () => { Import from ChatGPT or Claude export + )} {/* Encrypted Backup/Restore */} diff --git a/apps/web/src/components/os/apps/StorageApp.tsx b/apps/web/src/components/os/apps/StorageApp.tsx index 59ee36c..d7d6ffa 100644 --- a/apps/web/src/components/os/apps/StorageApp.tsx +++ b/apps/web/src/components/os/apps/StorageApp.tsx @@ -19,7 +19,7 @@ * Source fidelity: docs/design_handoff_waggle_app/design-files/screens/storage.html (view-a) */ 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 { FileEntry, StorageType, Workspace } from '@/lib/types'; import { adapter } from '@/lib/adapter'; @@ -66,16 +66,6 @@ const STORAGE_TYPE_CARDS: readonly StorageTypeCard[] = [ accent: 'var(--honey)', 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 = { @@ -246,12 +236,12 @@ const StorageApp = ({ workspaceId, workspaceName, workspace }: StorageAppProps) )} - {/* Three ways a workspace can live */} + {/* Two ways a workspace can live */} - Three ways a workspace can live + Two ways a workspace can live - + {STORAGE_TYPE_CARDS.map(card => { const active = card.type === storageType; const Icon = card.icon; diff --git a/apps/web/src/components/os/apps/TeamGovernanceApp.tsx b/apps/web/src/components/os/apps/TeamGovernanceApp.tsx deleted file mode 100644 index bd203f1..0000000 --- a/apps/web/src/components/os/apps/TeamGovernanceApp.tsx +++ /dev/null @@ -1,44 +0,0 @@ -import { Shield, Lock, Users, Crown } from 'lucide-react'; - -const TeamGovernanceApp = () => { - return ( - - - - - - Team Governance - - Fine-grained permissions, role-based access, and audit controls for your team. - - - - - - Role-Based Access - Owner, Admin, Member, Viewer - - - - - - Tool Governance - Per-role tool allow/deny lists - - - - - - Audit Trail - Full action history per member - - - - - Available on Teams ($49/mo per seat) and Enterprise tiers - - - ); -}; - -export default TeamGovernanceApp; diff --git a/apps/web/src/components/os/apps/UserProfileApp.tsx b/apps/web/src/components/os/apps/UserProfileApp.tsx index 2361a94..8b14c7a 100644 --- a/apps/web/src/components/os/apps/UserProfileApp.tsx +++ b/apps/web/src/components/os/apps/UserProfileApp.tsx @@ -7,6 +7,7 @@ import { } from 'lucide-react'; import { Input } from '@/components/ui/input'; import { adapter } from '@/lib/adapter'; +import { hasMemoryFeature } from '@/lib/memory-features'; interface IdentitySuggestion { field: 'name' | 'role' | 'company' | 'industry' | 'bio'; @@ -272,7 +273,7 @@ const UserProfileApp = () => { so the user sees "here's what we learned" before seeing the blank inputs. Each row: label + value + confidence dot + accept / dismiss. Block auto-hides when all are handled. */} - {suggestions.length > 0 && ( + {hasMemoryFeature('importHistory') && suggestions.length > 0 && ( diff --git a/apps/web/src/components/os/apps/WaggleDanceApp.tsx b/apps/web/src/components/os/apps/WaggleDanceApp.tsx deleted file mode 100644 index b953bf1..0000000 --- a/apps/web/src/components/os/apps/WaggleDanceApp.tsx +++ /dev/null @@ -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 = { - 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)[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(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 ( - - {/* Header */} - - - - Waggle Dance - {unacknowledgedCount > 0 && ( - - {unacknowledgedCount} - - )} - - - - - - - {/* Filter tabs */} - - {filterTypes.map(t => { - const cfg = t === 'all' ? null : typeConfig[t]; - const Icon = cfg?.icon; - return ( - 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 && } - {t === 'all' ? 'All' : cfg!.label} - - ); - })} - - - {/* Content */} - - {/* Signal list */} - - - {loading && signals.length === 0 && ( - Loading signals… - )} - {/* P7/D15 B5: the hook already tracks `error` — a load failure must - not masquerade as "no signals yet". */} - {!loading && error && signals.length === 0 && ( - - - Couldn't load signals - The Waggle Dance feed is unreachable — this is a load error, not an empty feed. - Retry - - )} - {!loading && !error && signals.length === 0 && ( - - - No waggle dance signals yet - Signals appear when agents share findings across workspaces - - )} - {orderedSignals.map(signal => { - const cfg = getTypeConfig(signal.type); - const Icon = cfg.icon; - const isSelected = selectedSignal?.id === signal.id; - return ( - 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'}`} - > - - - - - {signal.title} - {signal.priority === 'critical' && ( - CRITICAL - )} - {signal.priority === 'high' && ( - HIGH - )} - - {signal.content} - - - {signal.sourceWorkspaceName || signal.sourceWorkspaceId} - - {signal.sourceUser && ( - · {signal.sourceUser} - )} - - {new Date(signal.timestamp).toLocaleTimeString(DATE_LOCALE, { hour: '2-digit', minute: '2-digit' })} - - - - - - ); - })} - - - - {/* Detail pane */} - {selectedSignal && ( - - - - {(() => { - const cfg = getTypeConfig(selectedSignal.type); - const Icon = cfg.icon; - return ; - })()} - {getTypeConfig(selectedSignal.type).label} - {selectedSignal.priority && selectedSignal.priority !== 'normal' && selectedSignal.priority !== 'low' && ( - - {selectedSignal.priority.toUpperCase()} - - )} - - {selectedSignal.title} - {selectedSignal.content} - - - Source: {selectedSignal.sourceWorkspaceName || selectedSignal.sourceWorkspaceId} - {selectedSignal.sourceUser && User: {selectedSignal.sourceUser}} - {selectedSignal.sourceAgentId && Agent: {selectedSignal.sourceAgentId}} - {selectedSignal.targetWorkspaceId && Target: {selectedSignal.targetWorkspaceId}} - Time: {new Date(selectedSignal.timestamp).toLocaleString(DATE_LOCALE)} - - - {selectedSignal.metadata && Object.keys(selectedSignal.metadata).length > 0 && ( - - Metadata - - {JSON.stringify(selectedSignal.metadata, null, 2)} - - - )} - - - {!selectedSignal.acknowledged && ( - acknowledge(selectedSignal.id)}> - Acknowledge - - )} - setSelectedSignal(null)}> - Close - - - - )} - - - ); -}; - -export default WaggleDanceApp; diff --git a/apps/web/src/components/os/apps/agents/AgentBuilder.tsx b/apps/web/src/components/os/apps/agents/AgentBuilder.tsx index 6f6417a..e2b8ace 100644 --- a/apps/web/src/components/os/apps/agents/AgentBuilder.tsx +++ b/apps/web/src/components/os/apps/agents/AgentBuilder.tsx @@ -19,7 +19,7 @@ import type { AgentType, AutonomyLevel, ConnectorDefinition, Scope } from '@wagg * before Create. Elevated selections (connectors / MCP servers) route * 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): * - no per-tool grants — tools derive from persona + skills (the create * contract carries no tools field); diff --git a/apps/web/src/components/os/apps/files/files-tabs.test.ts b/apps/web/src/components/os/apps/files/files-tabs.test.ts index 64ec85d..daf87ec 100644 --- a/apps/web/src/components/os/apps/files/files-tabs.test.ts +++ b/apps/web/src/components/os/apps/files/files-tabs.test.ts @@ -2,8 +2,8 @@ import { describe, it, expect } from 'vitest'; import { initialTabFor, FILES_TAB_ORDER } from './files-tabs'; describe('FILES_TAB_ORDER', () => { - it('is virtual → local → team in that order', () => { - expect(FILES_TAB_ORDER).toEqual(['virtual', 'local', 'team']); + it('is virtual → local in that order (no Team tab, ADR-0003)', () => { + 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", () => { expect(initialTabFor('virtual')).toBe('virtual'); 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", () => { diff --git a/apps/web/src/components/os/apps/files/files-tabs.ts b/apps/web/src/components/os/apps/files/files-tabs.ts index 48105c3..cffe7cc 100644 --- a/apps/web/src/components/os/apps/files/files-tabs.ts +++ b/apps/web/src/components/os/apps/files/files-tabs.ts @@ -10,16 +10,15 @@ import type { StorageType } from '@/lib/types'; * 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: * 1. The workspace's configured storageType (if set) * 2. 'virtual' — always available, safe default * - * 'team' would be valid in the config but we never default to it on open - * because a team workspace without a connected team server has nothing to - * show; the tab strip lets the user switch manually. + * A legacy 'team' workspace opens on 'virtual': team storage needs a team + * server, and team mode is not part of the community edition (ADR-0003). */ export function initialTabFor( configured: StorageType | undefined, diff --git a/apps/web/src/components/os/overlays/AnalyticsConsentDialog.tsx b/apps/web/src/components/os/overlays/AnalyticsConsentDialog.tsx new file mode 100644 index 0000000..caf21dd --- /dev/null +++ b/apps/web/src/components/os/overlays/AnalyticsConsentDialog.tsx @@ -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(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 ( + + + + + + + + + Share anonymous usage analytics? + + + + + + Waggle can send a small amount of usage data to PostHog to help improve the app. + Nothing is sent unless you choose Allow. + + What is sent: + + One event when you finish onboarding, with the template, persona and model you chose. + A random ID for this install and the browser details PostHog adds, such as browser, operating system and screen size. + + Your chats, files and memories are never sent. + You can change this later in Settings, under Privacy & Telemetry. + + + + choose('denied')} className={buttonClass}> + Don't allow + + choose('granted')} className={buttonClass}> + Allow + + + + + ); +} diff --git a/apps/web/src/components/os/overlays/CreateWorkspaceDialog.tsx b/apps/web/src/components/os/overlays/CreateWorkspaceDialog.tsx index 024012c..a8ecf9c 100644 --- a/apps/web/src/components/os/overlays/CreateWorkspaceDialog.tsx +++ b/apps/web/src/components/os/overlays/CreateWorkspaceDialog.tsx @@ -1,6 +1,6 @@ import { useState, useCallback, useEffect, useRef } from 'react'; import { - X, Plus, Users, Cloud, HardDrive, Server, FolderOpen, Folder, + X, Plus, Users, Cloud, HardDrive, FolderOpen, Folder, FolderPlus, ChevronRight, Home, Check, Loader2, LayoutTemplate, Sparkles, Info, Wand2, Target, Microscope, Code, Megaphone, Rocket, Scale, Building, FileText, Laptop, PenLine, BarChart3, @@ -43,7 +43,7 @@ interface CreateWorkspaceDialogProps { open: boolean; onClose: () => void; 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; }) => void; } @@ -54,7 +54,6 @@ const GROUPS = [...STANDARD_GROUPS]; 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: '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 */ @@ -730,7 +729,6 @@ const CreateWorkspaceDialog = ({ open, onClose, onCreate }: CreateWorkspaceDialo const [name, setName] = useState(''); const [group, setGroup] = useState('Personal'); const [selectedPersona, setSelectedPersona] = useState(); - const [shared, setShared] = useState(false); const [storageType, setStorageType] = useState('virtual'); const [storagePath, setStoragePath] = useState(''); const [showFolderPicker, setShowFolderPicker] = useState(false); @@ -801,11 +799,10 @@ const CreateWorkspaceDialog = ({ open, onClose, onCreate }: CreateWorkspaceDialo name: name.trim(), group, persona: agentMode === 'single' ? selectedPersona : undefined, agentGroupId: agentMode === 'group' ? selectedGroupId : undefined, - shared, storageType, storagePath: storagePath.trim() || undefined, templateId: selectedTemplate || undefined, }); - setName(''); setGroup('Personal'); setSelectedPersona(undefined); setShared(false); + setName(''); setGroup('Personal'); setSelectedPersona(undefined); setStorageType('virtual'); setStoragePath(''); setSelectedTemplate(null); setShowTemplateOptions(false); setTemplateSearch(''); setCategoryFilter('all'); setShowAgentOptions(false); setAgentMode('single'); setSelectedGroupId(undefined); @@ -1105,7 +1102,7 @@ const CreateWorkspaceDialog = ({ open, onClose, onCreate }: CreateWorkspaceDialo {/* ── Storage Type ── */} Storage Type - + {STORAGE_OPTIONS.map(opt => ( setStorageType(opt.type)} className={`flex flex-col items-center gap-1 p-3 rounded-xl transition-colors ${ @@ -1156,7 +1153,6 @@ const CreateWorkspaceDialog = ({ open, onClose, onCreate }: CreateWorkspaceDialo {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 === 'team' && 'Browse or type the S3/MinIO bucket and prefix for shared storage.'} @@ -1267,22 +1263,6 @@ const CreateWorkspaceDialog = ({ open, onClose, onCreate }: CreateWorkspaceDialo } - {/* Share toggle */} - - - - - Share with team - Make visible to all team members - - - 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'}`}> - - - - Cancel not reversible from the app — you'll need a previously-saved .waggle-backup file to restore. - Data already sent to cloud providers (Anthropic, OpenAI, Stripe, etc.) and Teams servers is not 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 not erased by this action. Ask those providers to delete it. diff --git a/apps/web/src/components/os/overlays/KeyboardShortcutsHelp.tsx b/apps/web/src/components/os/overlays/KeyboardShortcutsHelp.tsx index deba4d2..ff448b1 100644 --- a/apps/web/src/components/os/overlays/KeyboardShortcutsHelp.tsx +++ b/apps/web/src/components/os/overlays/KeyboardShortcutsHelp.tsx @@ -18,7 +18,6 @@ const shortcuts = [ { keys: ['Ctrl', 'Shift', '6'], action: 'Events' }, { keys: ['Ctrl', 'Shift', '7'], action: 'Settings' }, { keys: ['Ctrl', 'Shift', '8'], action: 'Skills' }, - { keys: ['Ctrl', 'Shift', '9'], action: 'Agent Swarm' }, ]}, { category: 'Quick Actions', items: [ { keys: ['Ctrl', 'K'], action: 'Global Search' }, diff --git a/apps/web/src/components/os/overlays/LoginBriefing.tsx b/apps/web/src/components/os/overlays/LoginBriefing.tsx index 44d2880..f9ae8fb 100644 --- a/apps/web/src/components/os/overlays/LoginBriefing.tsx +++ b/apps/web/src/components/os/overlays/LoginBriefing.tsx @@ -346,16 +346,14 @@ const LoginBriefing = ({ onDismiss, onOpenWorkspace }: LoginBriefingProps) => { {ws.name} - {/* FR #27: tooltip clarifies what the Personal/Team - tag means. Personal workspaces are private to the - account; Team workspaces are - shared. Without this hint the colored chip reads + {/* FR #27: tooltip clarifies what the group tag + means. Without this hint the colored chip reads as decorative metadata. */} {ws.group} diff --git a/apps/web/src/components/os/overlays/OnboardingWizard.tsx b/apps/web/src/components/os/overlays/OnboardingWizard.tsx index 6702c5f..cdb9cdb 100644 --- a/apps/web/src/components/os/overlays/OnboardingWizard.tsx +++ b/apps/web/src/components/os/overlays/OnboardingWizard.tsx @@ -3,6 +3,7 @@ import { motion, AnimatePresence, MotionConfig, useReducedMotion } from 'framer- import beeMascot from '@/assets/personas/general-purpose.png'; import { adapter } from '@/lib/adapter'; import { captureOnboardingComplete } from '@/lib/posthog'; +import { hasMemoryFeature } from '@/lib/memory-features'; import { useOfflineStatus } from '@/hooks/useOfflineStatus'; import type { OnboardingState } from '@/hooks/useOnboarding'; 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 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?'; /* ─── 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 // into [0, LAST_INDEX] so resume always lands on a renderable step rather // than a blank screen. `?forceWizard=true` already resets step to 0. - const [step, setStep] = useState(() => Math.min(Math.max(state.step, 0), LAST_INDEX)); + const [step, setStep] = useState(() => shownStepFrom(Math.min(Math.max(state.step, 0), LAST_INDEX), 1)); const autoTimer = useRef | undefined>(undefined); const offline = useOfflineStatus(); const reduceMotion = useReducedMotion(); @@ -191,8 +203,9 @@ const OnboardingWizard = ({ serverBaseUrl, state, onUpdate, onComplete, onDismis finally { setImporting(false); } }; - /* ── Claude Code auto-detect on mount ── */ + /* ── Claude Code auto-detect on mount (only when the import step is shown) ── */ useEffect(() => { + if (!isStepShown('memory-import')) return; let cancelled = false; (async () => { try { @@ -277,10 +290,15 @@ const OnboardingWizard = ({ serverBaseUrl, state, onUpdate, onComplete, onDismis const progressPct = LAST_INDEX > 0 ? (step / LAST_INDEX) * 100 : 0; // Nav chrome (Back + "Step N of M" + dots) spans who-are-you → first-task, so // each interactive step has a distinct counter/dot fill (template = 4 of 5, - // first-task = 5 of 5) instead of two identical "Step 4 of 4" screens. + // 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 navTotal = LAST_NAV_INDEX - FIRST_NAV_INDEX + 1; - const navCurrent = step - FIRST_NAV_INDEX + 1; + const navSteps = STEP_NAMES + .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); return ( @@ -358,7 +376,7 @@ const OnboardingWizard = ({ serverBaseUrl, state, onUpdate, onComplete, onDismis { 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" aria-label="Go to previous step" @@ -373,8 +391,7 @@ const OnboardingWizard = ({ serverBaseUrl, state, onUpdate, onComplete, onDismis )} {showNavChrome && ( - {STEP_NAMES.slice(FIRST_NAV_INDEX, LAST_NAV_INDEX + 1).map((_, idx) => { - const navStep = FIRST_NAV_INDEX + idx; + {navSteps.map((navStep) => { return ( goToName('memory-import')} + onContinue={() => goToName(isStepShown('memory-import') ? 'memory-import' : 'template')} onLater={() => { clearTimeout(autoTimer.current); trackTelemetry(serverBaseUrl, 'onboarding_skip', { atStep: step, via: 'model-gate-later' }); diff --git a/apps/web/src/hooks/useKeyboardShortcuts.ts b/apps/web/src/hooks/useKeyboardShortcuts.ts index 74600de..7f7681f 100644 --- a/apps/web/src/hooks/useKeyboardShortcuts.ts +++ b/apps/web/src/hooks/useKeyboardShortcuts.ts @@ -26,7 +26,6 @@ const APP_SHORTCUTS: Record = { '6': 'events', '7': 'settings', '8': 'capabilities', - '9': 'waggle-dance', }; /** Shortcuts that work even when an input/textarea is focused */ diff --git a/apps/web/src/hooks/useKnowledgeGraph.ts b/apps/web/src/hooks/useKnowledgeGraph.ts index 82ef4fd..62db5c5 100644 --- a/apps/web/src/hooks/useKnowledgeGraph.ts +++ b/apps/web/src/hooks/useKnowledgeGraph.ts @@ -4,7 +4,8 @@ import type { KGNode, KGEdge } from '@/lib/types'; 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([]); const [edges, setEdges] = useState([]); const [loading, setLoading] = useState(false); @@ -32,7 +33,7 @@ export const useKnowledgeGraph = (workspaceId: string | null) => { } finally { setLoading(false); } }, [workspaceId, scope]); - useEffect(() => { fetchKG(); }, [fetchKG]); + useEffect(() => { if (enabled) fetchKG(); }, [fetchKG, enabled]); return { nodes, edges, loading, error, selectedNode, setSelectedNode, scope, setScope, refresh: fetchKG }; }; diff --git a/apps/web/src/hooks/useWaggleDance.ts b/apps/web/src/hooks/useWaggleDance.ts deleted file mode 100644 index 28fd870..0000000 --- a/apps/web/src/hooks/useWaggleDance.ts +++ /dev/null @@ -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([]); - const [loading, setLoading] = useState(true); - const [filter, setFilter] = useState('all'); - const [error, setError] = useState(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) => { - 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 }; -}; diff --git a/apps/web/src/lib/adapter.sse.test.ts b/apps/web/src/lib/adapter.sse.test.ts index eccd0c4..02e9290 100644 --- a/apps/web/src/lib/adapter.sse.test.ts +++ b/apps/web/src/lib/adapter.sse.test.ts @@ -95,7 +95,7 @@ describe('P1b-SSE client', () => { throw new Error(`unmocked: ${u}`); }); 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(); expect(FakeEventSource.instances).toHaveLength(0); // deferred, not opened token-less releaseToken(jsonRes({ token: 'tok-A' })); @@ -173,26 +173,17 @@ describe('P1b-SSE client', () => { expect(FakeEventSource.instances).toHaveLength(2); }); - it('NAMED EVENTS: subscribeEvents/ and subscribeWaggleDance/ receive named payloads, not onmessage', async () => { - // Review fix: the server emits `event: audit` / `event: signal` — an - // onmessage-only listener made both channels payload-dead even with - // working auth. + it('NAMED EVENTS: subscribeEvents/ receives named payloads, not onmessage', async () => { + // Review fix: the server emits `event: audit` — an onmessage-only + // listener made the channel payload-dead even with working auth. const a = await connectedAdapter('tok-A'); const audits: unknown[] = []; - const signals: unknown[] = []; a.subscribeEvents((e) => audits.push(e)); - a.subscribeWaggleDance((s) => signals.push(s)); await flush(); - const [eventsEs, waggleEs] = FakeEventSource.instances; + const [eventsEs] = FakeEventSource.instances; eventsEs.fireNamed('audit', { type: 'tool_call' }); - waggleEs.fireNamed('signal', { id: 's1' }); 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 () => { diff --git a/apps/web/src/lib/adapter.ts b/apps/web/src/lib/adapter.ts index fab06e2..e648eec 100644 --- a/apps/web/src/lib/adapter.ts +++ b/apps/web/src/lib/adapter.ts @@ -21,7 +21,7 @@ import type { AgentStep, Session, SkillPack, FleetSession, CronJob, Notification, AgentStatus, Persona, SystemHealth, Settings, StreamEvent, KGNode, KGEdge, - ModelPricing, WaggleSignal, FileEntry, WorkspaceTemplate, + ModelPricing, FileEntry, WorkspaceTemplate, TimelineEvent, HomeBriefing, OvernightSummary, QuickCaptureInput, WorkspaceStateView, WorkspaceActivityEvent, WorkspaceTask, @@ -3270,24 +3270,6 @@ class LocalAdapter { }, }; - // --- Waggle Dance --- - async getWaggleSignals(): Promise { - 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): Promise { - const res = await this.fetch('/api/waggle/signals', { method: 'POST', body: JSON.stringify(data) }); - return res.json(); - } - - async acknowledgeWaggleSignal(id: string): Promise { - await this.fetch(`/api/waggle/signals/${id}/ack`, { method: 'PATCH' }); - } - // --- AI-OS launcher (Phase 2B) --- // detectTools/launchTool/manageHooks each surface the matching // 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, * 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 - * (path, eventName); concurrent subscribers share it (AppShell's - * always-mounted waggle badge + the WaggleDance screen both consume - * /api/waggle/stream — the old replace-on-resubscribe dedup let the second - * mount permanently kill the first's stream). The socket closes only when - * the last subscriber leaves. + * (path, eventName); concurrent subscribers share it (the old + * replace-on-resubscribe dedup let a second 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 - * routes emit `event: audit` / `event: signal`, which `onmessage` never - * receives per the SSE spec — both channels were payload-dead even with - * working auth). + * `eventName` selects NAMED SSE events (review fix: the events route emits + * `event: audit`, which `onmessage` never receives per the SSE spec — the + * channel was payload-dead even with working auth). */ private subscribeSSE(path: string, onData: (data: unknown) => void, eventName?: string): () => void { const key = `${path}#${eventName ?? 'message'}`; diff --git a/apps/web/src/lib/analytics-consent.ts b/apps/web/src/lib/analytics-consent.ts new file mode 100644 index 0000000..c54c7ed --- /dev/null +++ b/apps/web/src/lib/analytics-consent.ts @@ -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 { + 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. + } +} diff --git a/apps/web/src/lib/chat-header-layout.test.ts b/apps/web/src/lib/chat-header-layout.test.ts index 89687aa..02b828f 100644 --- a/apps/web/src/lib/chat-header-layout.test.ts +++ b/apps/web/src/lib/chat-header-layout.test.ts @@ -44,7 +44,7 @@ describe('chat header control classification', () => { it('overflow set is the informational chips only', () => { expect([...CHAT_HEADER_OVERFLOW_CONTROLS].sort()).toEqual( - ['storage-type', 'team-presence'].sort(), + ['storage-type'], ); }); diff --git a/apps/web/src/lib/chat-header-layout.ts b/apps/web/src/lib/chat-header-layout.ts index 35124a8..83cf181 100644 --- a/apps/web/src/lib/chat-header-layout.ts +++ b/apps/web/src/lib/chat-header-layout.ts @@ -1,12 +1,11 @@ /** * Chat-header layout decision (M-21 / UX-6). * - * The header crowds the persona picker + storage badge + team presence - * + autonomy toggle + model picker into a single row. Below a narrow - * threshold, the informational surfaces (storage badge, team presence) - * move into a ⋯ overflow menu so the interactive controls (persona, - * autonomy, model) stay reachable without the header wrapping or - * truncating. + * The header crowds the persona picker + storage badge + autonomy + * toggle + model picker into a single row. Below a narrow threshold, the + * informational surface (storage badge) moves into a ⋯ overflow menu + * so the interactive controls (persona, autonomy, model) stay reachable + * without the header wrapping or truncating. * * This module holds the pure decision so a test can pin the threshold * 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 = [ 'storage-type', - 'team-presence', ] as const; export type ChatHeaderOverflowControl = (typeof CHAT_HEADER_OVERFLOW_CONTROLS)[number]; diff --git a/apps/web/src/lib/command-catalog.ts b/apps/web/src/lib/command-catalog.ts index b91a1fc..acc52d8 100644 --- a/apps/web/src/lib/command-catalog.ts +++ b/apps/web/src/lib/command-catalog.ts @@ -2,10 +2,11 @@ import type { ElementType } from "react"; import { Home, MessageSquare, Brain, ListTodo, Library, UserCircle, Plus, Rocket, Settings, - Network, Server, Plug, Store, Package, Shield, Clock, FolderOpen, + Server, Plug, Store, Package, Shield, Clock, FolderOpen, Lock, Activity, History, BarChart3, Users, Radio, Gauge, Monitor, LayoutGrid, Eye, } from "lucide-react"; +import { hasMemoryFeature } from "@/lib/memory-features"; /** * Curated ⌘K catalog (design ref: design-files/screens/ia.html). @@ -66,13 +67,12 @@ export function buildCommandCatalog(ctx: CatalogContext): CatalogGroup[] { const doGroup: CatalogCommand[] = [ { 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: "settings", group: "do", name: "Settings", subtitle: "models · failover · permissions", icon: Settings, to: "/settings" }, ]; 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: "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" }, diff --git a/apps/web/src/lib/dock-tiers.ts b/apps/web/src/lib/dock-tiers.ts index 2a1cbb7..ce85a2a 100644 --- a/apps/web/src/lib/dock-tiers.ts +++ b/apps/web/src/lib/dock-tiers.ts @@ -1,16 +1,16 @@ import type { ElementType } from 'react'; import { 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'; export type AppId = | 'home' | 'chat' | 'dashboard' | 'memory' | 'events' | 'capabilities' | 'connectors' | 'cockpit' | 'mission-control' | 'settings' | 'vault' | 'profile' - | 'waggle-dance' | 'files' | 'artifacts' | 'agents' + | 'files' | 'artifacts' | 'agents' | '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 // Home / workspace selection (not a dock entry — A1 fixed-layout window). | '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: '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: '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' }, ], }, diff --git a/apps/web/src/lib/memory-features.ts b/apps/web/src/lib/memory-features.ts new file mode 100644 index 0000000..9647ba3 --- /dev/null +++ b/apps/web/src/lib/memory-features.ts @@ -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 = { + 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> = { + 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); +} diff --git a/apps/web/src/lib/motion/route-transition.ts b/apps/web/src/lib/motion/route-transition.ts index f90f938..ff14824 100644 --- a/apps/web/src/lib/motion/route-transition.ts +++ b/apps/web/src/lib/motion/route-transition.ts @@ -39,13 +39,11 @@ const ROUTE_LABELS: Record = { automations: 'Automations', skills: 'Skills', room: 'Room', - 'waggle-dance': 'Agent swarm', approvals: 'Approvals', connectors: 'Connectors', mcps: 'MCP hub', marketplace: 'Marketplace', launcher: 'Launcher', - team: 'Team', settings: 'Settings', benchmarks: 'Benchmarks', platform: 'Platform', diff --git a/apps/web/src/lib/platform.ts b/apps/web/src/lib/platform.ts index 1df1c18..9c43126 100644 --- a/apps/web/src/lib/platform.ts +++ b/apps/web/src/lib/platform.ts @@ -1,6 +1,7 @@ /** - * Tiny platform helpers. Waggle ships on Windows + macOS, so any modifier-key - * hint must adapt: a ⌘ glyph on Windows is a key the user's keyboard lacks. + * Tiny platform helpers. Waggle runs on Windows, macOS and Linux, so any + * 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 * (Sidebar, AskBar, CommandCenter footer, NotFound, ChatApp composer). */ diff --git a/apps/web/src/lib/posthog.test.ts b/apps/web/src/lib/posthog.test.ts index aa52ba4..865aae1 100644 --- a/apps/web/src/lib/posthog.test.ts +++ b/apps/web/src/lib/posthog.test.ts @@ -1,15 +1,12 @@ /** - * posthog.ts unit tests (Phase 2 P1 / DAY0-04) - * - * Run: npx vitest run apps/web/src/lib/posthog.test.ts + * Opt-in analytics (ADR-0006): posthog.ts + analytics-consent.ts. * * Covers: - * Test 1 — When VITE_POSTHOG_KEY is absent, captureOnboardingComplete - * does NOT call posthog.capture. - * Test 2 — When user has opted out (waggle:telemetry-opt-out = 'true'), - * captureOnboardingComplete does NOT call posthog.capture. - * Test 3 — When key is present AND user is opted in, - * captureOnboardingComplete calls posthog.capture('onboarding_complete', payload). + * - no key at build time → nothing initializes, nothing is captured, no prompt; + * - key present, no choice yet → nothing initializes or is captured; + * - denial (new key or the old opt-out marker) → nothing is captured; + * - grant → PostHog initializes and onboarding_complete is captured; + * - withdrawal → PostHog opts out and resets; later events are dropped. */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; @@ -21,6 +18,8 @@ const mockCapture = vi.fn(); const mockInit = vi.fn(); const mockOptOut = 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 // posture); the mock specifier must match that exact import. @@ -30,12 +29,11 @@ vi.mock('posthog-js/dist/module.no-external', () => ({ capture: mockCapture, opt_out_capturing: mockOptOut, 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 ───────────────────────────────────────────────────────── const localStorageMock = (() => { let store: Record = {}; @@ -51,81 +49,143 @@ Object.defineProperty(window, 'localStorage', { value: localStorageMock }); // ── 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() { - // Re-import the module fresh for each test (Vitest clears module cache). - // Using a dynamic import so vi.resetModules() takes effect. - return import('./posthog.ts'); +async function importModules() { + // vi.resetModules() in beforeEach gives each test a fresh `initialized` flag + // and a fresh read of the stubbed VITE_POSTHOG_KEY. + const posthog = await import('./posthog.ts'); + const consent = await import('./analytics-consent.ts'); + return { ...posthog, ...consent }; } // ── Tests ───────────────────────────────────────────────────────────────────── -describe('posthog.ts', () => { +describe('posthog.ts (opt-in)', () => { beforeEach(() => { vi.resetModules(); - mockCapture.mockClear(); - mockInit.mockClear(); + vi.clearAllMocks(); + mockHasOptedOut.mockReturnValue(false); localStorageMock.clear(); }); afterEach(() => { - vi.clearAllMocks(); + vi.unstubAllEnvs(); }); - it('Test 1: VITE_POSTHOG_KEY absent → captureOnboardingComplete is a no-op', async () => { - // Simulate absent key (import.meta.env.VITE_POSTHOG_KEY is undefined by default in test env) + it('is a no-op without VITE_POSTHOG_KEY, even after a grant', async () => { 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(); - captureOnboardingComplete({ templateId: 'sales-pipeline', personaId: 'coder', model: 'claude-opus-4' }); + await m.setAnalyticsConsent('granted'); + await m.initPostHog(); + m.captureOnboardingComplete(PAYLOAD); expect(mockInit).not.toHaveBeenCalled(); expect(mockCapture).not.toHaveBeenCalled(); - - vi.unstubAllEnvs(); }); - it('Test 2: User opted out → captureOnboardingComplete is a no-op', async () => { - // Set the opt-out key before importing so the module reads it. - localStorageMock.setItem(OPT_OUT_KEY, 'true'); + it('sends nothing before the user chooses', async () => { + vi.stubEnv('VITE_POSTHOG_KEY', TEST_KEY); + 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(); - 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(mockInit).not.toHaveBeenCalled(); expect(mockCapture).not.toHaveBeenCalled(); - - vi.unstubAllEnvs(); }); - it('Test 3: Key present + opted in → captureOnboardingComplete calls posthog.capture', async () => { - // Opted in (no opt-out key in localStorage). - localStorageMock.removeItem(OPT_OUT_KEY); + it('sends nothing after the user denies', async () => { + vi.stubEnv('VITE_POSTHOG_KEY', TEST_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' }; - captureOnboardingComplete(payload); + expect(m.readAnalyticsConsent()).toBe('denied'); + 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).toHaveBeenCalledWith('onboarding_complete', { - template_id: payload.templateId, - persona_id: payload.personaId, - model: payload.model, + template_id: PAYLOAD.templateId, + persona_id: PAYLOAD.personaId, + 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(); }); }); diff --git a/apps/web/src/lib/posthog.ts b/apps/web/src/lib/posthog.ts index 62f4984..4897956 100644 --- a/apps/web/src/lib/posthog.ts +++ b/apps/web/src/lib/posthog.ts @@ -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: - * 1. VITE_POSTHOG_KEY is set at compile time (baked into the Vite bundle by P4-win build). - * 2. The user has not opted out (no client-side telemetry-disabled marker in localStorage). + * Nothing is initialized or captured unless BOTH hold: + * 1. VITE_POSTHOG_KEY was set when the bundle was built. Source builds have + * 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: - * - If VITE_POSTHOG_KEY is absent (key never baked in or dev machine without .env.local) - * → 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. + * The key is read through import.meta.env at Vite build time and is never + * committed; release builds receive it from the build environment. * - * IMPORTANT — COMPILE-TIME BAKE: - * VITE_POSTHOG_KEY is read via import.meta.env at Vite bundle time. - * 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). + * Events captured (the consent dialog lists these; keep it in sync): + * - onboarding_complete: template_id, persona_id, model * * Usage: - * import { initPostHog, captureOnboardingComplete } from '@/lib/posthog'; - * - * // In main.tsx — call once on app boot (non-blocking): - * initPostHog().catch(() => {}); - * - * // In OnboardingWizard.tsx — alongside existing trackTelemetry call: - * captureOnboardingComplete({ templateId, personaId, model }); + * initPostHog() // app boot; returns early without consent + * captureOnboardingComplete(...) // OnboardingWizard, at completion + * stopPostHog() // consent withdrawn */ // no-external build: never lazy-loads remote chunks (config.js, recorder, @@ -34,64 +25,67 @@ // desktop webview, preserving Waggle's data-sovereignty posture. Only // the capture endpoint (us.i.posthog.com) is ever contacted. 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. */ 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'; -/** localStorage key used to persist the user's opt-out preference. */ -const OPT_OUT_KEY = 'waggle:telemetry-opt-out'; - let initialized = false; /** - * Returns true if the user has opted out of telemetry via the localStorage key. - * Default (key absent or any value other than 'true') = opted IN. + * Initialize PostHog. Call on app boot and again when the user allows analytics. + * + * - 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 { + if (!PH_KEY || !isAnalyticsAllowed()) { + return; + } 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 { - // localStorage unavailable (sandboxed, private browsing) — treat as opted out - return true; + // PostHog init failure must never block app boot. } } /** - * Initialize PostHog on app boot. - * - * - 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 — resolves when initialization is complete or skipped. + * Stop capturing at once after consent is withdrawn and drop the PostHog + * identity stored on this machine. */ -export async function initPostHog(): Promise { - if (!PH_KEY || initialized || isOptedOut()) { +export function stopPostHog(): void { + if (!initialized) { return; } try { - 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-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; + posthog.opt_out_capturing(); + posthog.reset(); } catch { - // PostHog init failure must never block app boot. - initialized = false; + // Ignore. } } @@ -106,13 +100,13 @@ export interface OnboardingCompletePayload { * Capture the `onboarding_complete` event alongside the existing local * 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. * * @param payload - Template, persona, and model selected during onboarding. */ export function captureOnboardingComplete(payload: OnboardingCompletePayload): void { - if (!initialized || isOptedOut()) { + if (!initialized || !isAnalyticsAllowed()) { return; } try { @@ -125,42 +119,3 @@ export function captureOnboardingComplete(payload: OnboardingCompletePayload): v // 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. - } - } -} diff --git a/apps/web/src/lib/routes.ts b/apps/web/src/lib/routes.ts index eb0dde8..592ab9d 100644 --- a/apps/web/src/lib/routes.ts +++ b/apps/web/src/lib/routes.ts @@ -35,9 +35,7 @@ export const APP_ROUTES = { marketplace: '/marketplace', launcher: '/launcher', room: '/room', - 'waggle-dance': '/waggle-dance', approvals: '/approvals', - governance: '/team', settings: '/settings', vault: '/settings/vault', 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 * also navigated (skill / connector / mcp). `person:` → null no-op (parity: * 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. */ export function routeForSearchResult(type: string, id: string, ctx?: RouteContext): string | null { diff --git a/apps/web/src/lib/types.ts b/apps/web/src/lib/types.ts index 68da665..af48c81 100644 --- a/apps/web/src/lib/types.ts +++ b/apps/web/src/lib/types.ts @@ -775,18 +775,3 @@ export interface ModelPricing { 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; - timestamp: string; - acknowledged?: boolean; - priority?: 'low' | 'normal' | 'high' | 'critical'; -} diff --git a/apps/web/src/lib/waggle-signals.test.ts b/apps/web/src/lib/waggle-signals.test.ts deleted file mode 100644 index 3a84e57..0000000 --- a/apps/web/src/lib/waggle-signals.test.ts +++ /dev/null @@ -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 { - 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); - }); -}); diff --git a/apps/web/src/lib/waggle-signals.ts b/apps/web/src/lib/waggle-signals.ts deleted file mode 100644 index 7d6c643..0000000 --- a/apps/web/src/lib/waggle-signals.ts +++ /dev/null @@ -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 = { - 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(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(signals: readonly T[]): Record { - const out: Record = {}; - 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); -} diff --git a/apps/web/src/routes/MemoryRoute.tsx b/apps/web/src/routes/MemoryRoute.tsx index 729e4e7..856e8ea 100644 --- a/apps/web/src/routes/MemoryRoute.tsx +++ b/apps/web/src/routes/MemoryRoute.tsx @@ -27,6 +27,7 @@ import { useShell } from '@/providers/ShellContext'; import { useMemory } from '@/hooks/useMemory'; import { useKnowledgeGraph } from '@/hooks/useKnowledgeGraph'; import { stashDeepLink } from '@/lib/app-deeplink'; +import { hasMemoryFeature, isMemoryViewAvailable } from '@/lib/memory-features'; const MemoryRoute = () => { const { mindScope } = useParams(); @@ -36,8 +37,9 @@ const MemoryRoute = () => { const mind: MindScope = mindScope === 'workspace' ? 'workspace' : 'personal'; const tabParam = searchParams.get('tab'); // 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). - const view: MemoryView = MEMORY_VIEWS.includes(tabParam as MemoryView) + // any view (incl. the legacy 'memories' list and the 6 secondary views), + // 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) : 'trust'; @@ -75,7 +77,7 @@ const MemoryRoute = () => { const { activeWorkspaceId, workspaces, setContextRailTarget } = useShell(); const memory = useMemory(activeWorkspaceId); - const kg = useKnowledgeGraph(activeWorkspaceId); + const kg = useKnowledgeGraph(activeWorkspaceId, hasMemoryFeature('knowledgeGraph')); const wsId = activeWorkspaceId && activeWorkspaceId !== 'local-default' ? activeWorkspaceId : undefined; const wsName = wsId ? workspaces.find(w => w.id === wsId)?.name : undefined; diff --git a/apps/web/src/routes/TeamRoute.tsx b/apps/web/src/routes/TeamRoute.tsx deleted file mode 100644 index 8defb4b..0000000 --- a/apps/web/src/routes/TeamRoute.tsx +++ /dev/null @@ -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 = () => ( - - - -); - -export default TeamRoute; diff --git a/apps/web/src/routes/WaggleDanceRoute.tsx b/apps/web/src/routes/WaggleDanceRoute.tsx deleted file mode 100644 index 6065731..0000000 --- a/apps/web/src/routes/WaggleDanceRoute.tsx +++ /dev/null @@ -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 = () => ( - - - -); - -export default WaggleDanceRoute; diff --git a/apps/web/src/routes/index.ts b/apps/web/src/routes/index.ts index 899acd9..80cd683 100644 --- a/apps/web/src/routes/index.ts +++ b/apps/web/src/routes/index.ts @@ -19,9 +19,7 @@ * /marketplace MarketplaceRoute * /launcher LauncherRoute * /room RoomRoute - * /waggle-dance WaggleDanceRoute * /approvals ApprovalsRoute - * /team TeamRoute * /settings SettingsRoute * /settings/vault VaultRoute * /settings/profile ProfileRoute @@ -43,9 +41,7 @@ export { default as McpsRoute } from './McpsRoute'; export { default as MarketplaceRoute } from './MarketplaceRoute'; export { default as LauncherRoute } from './LauncherRoute'; export { default as RoomRoute } from './RoomRoute'; -export { default as WaggleDanceRoute } from './WaggleDanceRoute'; export { default as ApprovalsRoute } from './ApprovalsRoute'; -export { default as TeamRoute } from './TeamRoute'; export { default as SettingsRoute } from './SettingsRoute'; export { default as VaultRoute } from './VaultRoute'; export { default as ProfileRoute } from './ProfileRoute'; diff --git a/apps/web/src/test/analytics-consent.test.tsx b/apps/web/src/test/analytics-consent.test.tsx new file mode 100644 index 0000000..31cf210 --- /dev/null +++ b/apps/web/src/test/analytics-consent.test.tsx @@ -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(); + 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( + + + + + , + ); + } + + 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(); + }); +}); diff --git a/apps/web/src/test/build-warning-hygiene.test.ts b/apps/web/src/test/build-warning-hygiene.test.ts index d422d9b..5e30556 100644 --- a/apps/web/src/test/build-warning-hygiene.test.ts +++ b/apps/web/src/test/build-warning-hygiene.test.ts @@ -39,6 +39,7 @@ describe('build warning hygiene', () => { 'OnboardingTooltips', 'LoginBriefing', 'ContextRail', + 'AnalyticsConsentDialog', ]) { expect(shellSource).not.toContain(`import ${overlay} from './overlays/${overlay}'`); expect(shellSource).toContain(`lazy(() => import('./overlays/${overlay}'))`); diff --git a/apps/web/src/test/memory-features.test.tsx b/apps/web/src/test/memory-features.test.tsx new file mode 100644 index 0000000..b81492e --- /dev/null +++ b/apps/web/src/test/memory-features.test.tsx @@ -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(['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( + , + ); + + 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(); + }); +}); diff --git a/apps/web/src/test/p1a-routes.test.ts b/apps/web/src/test/p1a-routes.test.ts index e417714..82c14df 100644 --- a/apps/web/src/test/p1a-routes.test.ts +++ b/apps/web/src/test/p1a-routes.test.ts @@ -20,19 +20,19 @@ import { type DockEntry, } 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[] = [ 'home', 'chat', 'dashboard', 'memory', 'events', 'capabilities', 'connectors', 'cockpit', 'mission-control', 'settings', 'vault', 'profile', - 'waggle-dance', 'files', 'artifacts', 'agents', + 'files', 'artifacts', 'agents', 'scheduled-jobs', 'marketplace', 'voice', 'room', 'approvals', 'timeline', - 'backup', 'telemetry', 'governance', 'launcher', + 'backup', 'telemetry', 'launcher', 'workspace-desktop', 'mcp-hub', ]; 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 = { home: '/home', memory: '/memory', @@ -46,9 +46,7 @@ describe('routeFor — §1.1 table', () => { marketplace: '/marketplace', launcher: '/launcher', room: '/room', - 'waggle-dance': '/waggle-dance', approvals: '/approvals', - governance: '/team', settings: '/settings', vault: '/settings/vault', profile: '/settings/profile', @@ -60,7 +58,7 @@ describe('routeFor — §1.1 table', () => { for (const [appId, route] of Object.entries(expected)) { 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)', () => { @@ -85,8 +83,8 @@ describe('routeFor — §1.1 table', () => { expect(routeFor('workspace-desktop', { activeWorkspaceId: 'local-default' })).toBe('/home'); }); - it('is total over all 28 AppIds (never throws, never returns empty)', () => { - expect(ALL_APP_IDS).toHaveLength(28); + it('is total over all 26 AppIds (never throws, never returns empty)', () => { + expect(ALL_APP_IDS).toHaveLength(26); for (const appId of ALL_APP_IDS) { const route = routeFor(appId, { activeWorkspaceId: 'ws-x' }); expect(route, appId).toMatch(/^\//); @@ -233,7 +231,6 @@ describe('dock-tiers route field — §1.3 invariant', () => { const power = getDockForTier('power'); const entries = flattenAppEntries(power); 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(power.some(e => e.key === 'team')).toBe(false); }); diff --git a/apps/web/src/test/p3-memory-center-app.test.tsx b/apps/web/src/test/p3-memory-center-app.test.tsx index fa22b06..68c7041 100644 --- a/apps/web/src/test/p3-memory-center-app.test.tsx +++ b/apps/web/src/test/p3-memory-center-app.test.tsx @@ -10,6 +10,9 @@ * - WorkspaceDesktopApp's memory tab embeds the per-mind list with * mind='workspace' + consumeDeepLinks=false (the J08 stash belongs to the * /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 { 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() })); + +const features = vi.hoisted(() => ({ enabled: true })); +vi.mock('@/lib/memory-features', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + hasMemoryFeature: (f: Parameters[0]) => features.enabled || actual.hasMemoryFeature(f), + isMemoryViewAvailable: (view: string) => features.enabled || actual.isMemoryViewAvailable(view), + }; +}); vi.mock('@/providers/ShellContext', () => ({ useShell: () => mocks.shell })); vi.mock('@/hooks/useRoomState', () => ({ useRoomState: () => ({ workspaceMap: new Map() }) })); 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)', () => { 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)', () => { it('renders the workspace-mind list instead of the placeholder', async () => { mocks.adapter.getWorkspaceContext.mockResolvedValue({ diff --git a/apps/web/src/test/p7-b5-error-threading.test.tsx b/apps/web/src/test/p7-b5-error-threading.test.tsx index 0857800..0f7568d 100644 --- a/apps/web/src/test/p7-b5-error-threading.test.tsx +++ b/apps/web/src/test/p7-b5-error-threading.test.tsx @@ -1,6 +1,6 @@ /** * 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. */ 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 { TooltipProvider } from '@/components/ui/tooltip'; -const mocks = vi.hoisted(() => ({ - useWaggleDance: vi.fn(), -})); - vi.mock('@/lib/adapter', () => ({ adapter: {}, default: vi.fn() })); -vi.mock('@/hooks/useWaggleDance', () => ({ useWaggleDance: mocks.useWaggleDance })); const render = (ui: ReactElement) => rtlRender({ui}); @@ -22,27 +17,6 @@ afterEach(() => { 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(); - - expect(screen.getByRole('button', { name: /refresh waggle dance/i })).toBeInTheDocument(); - }); -}); - describe('P7/B5 — EventsApp error state', () => { it('renders an error (not "No events yet") when error is set', async () => { const { default: EventsApp } = await import('@/components/os/apps/EventsApp'); diff --git a/docs/oss/upstream-fixes.md b/docs/oss/upstream-fixes.md index 6a79b69..5d9f61f 100644 --- a/docs/oss/upstream-fixes.md +++ b/docs/oss/upstream-fixes.md @@ -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-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-029 | The Settings "Import Data" button does nothing | Open | Web UI | ## 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. - 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 `` 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. + diff --git a/tests/e2e/five-persona-state-bundles.spec.ts b/tests/e2e/five-persona-state-bundles.spec.ts index 7980301..060b8c7 100644 --- a/tests/e2e/five-persona-state-bundles.spec.ts +++ b/tests/e2e/five-persona-state-bundles.spec.ts @@ -217,21 +217,6 @@ const PERSONAS: PersonaBundle[] = [ ], 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.'], routes: [ { 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 }, ], 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[] { return [{ id: 'grant-send-email', diff --git a/tests/e2e/full-product-audit.spec.ts b/tests/e2e/full-product-audit.spec.ts index 339015f..54e671e 100644 --- a/tests/e2e/full-product-audit.spec.ts +++ b/tests/e2e/full-product-audit.spec.ts @@ -69,7 +69,6 @@ async function openCurrentApp(page: Page, label: string) { Timeline: '/settings/timeline', 'Usage & Cost': '/settings/usage', 'Events & Logs': '/settings/events', - 'Team Governance': '/team', 'Skills Hub': '/skills', 'Connector Hub': '/connectors', 'MCP Hub': '/mcps', @@ -263,7 +262,6 @@ const ZONE_APPS = [ { label: 'Timeline', zone: 'System', expect: /timeline|activity|no.*activity|last/i }, { label: 'Usage & Cost', zone: 'System', expect: /usage|telemetry|token|cost/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: 'Connector Hub', zone: 'Extend', expect: /connector|connect|service|integration/i }, { label: 'MCP Hub', zone: 'Extend', expect: /mcp|installed|catalog|server/i }, diff --git a/tests/e2e/launcher-rendered-states.spec.ts b/tests/e2e/launcher-rendered-states.spec.ts index c8e7a65..1642c07 100644 --- a/tests/e2e/launcher-rendered-states.spec.ts +++ b/tests/e2e/launcher-rendered-states.spec.ts @@ -76,7 +76,9 @@ test.describe('Launcher rendered states', () => { 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 page.route('**/api/tools/detect', route => route.fulfill({ status: 200, @@ -134,7 +136,9 @@ test.describe('Launcher rendered states', () => { 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 page.route('**/api/tools/detect', route => route.fulfill({ status: 200, @@ -192,7 +196,9 @@ test.describe('Launcher rendered states', () => { 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])); 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(/v2\.1\.0/i)).toBeVisible(); await expect(page.getByText(/Sent to:/i)).not.toBeVisible(); - await expect(page.getByText(/Launch only/i)).toBeVisible(); - await expect(page.getByText(/Hook management is not supported for this tool yet/i)).toBeVisible(); + // Hooks are hidden in v1 (ADR-0002), so there is no "launch only" contrast. + 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: /install hooks/i })).not.toBeVisible(); await expect(page.getByRole('button', { name: /^Verify$/ })).not.toBeVisible(); diff --git a/tests/e2e/power-user-stress.spec.ts b/tests/e2e/power-user-stress.spec.ts index b4baaa2..e4ade1d 100644 --- a/tests/e2e/power-user-stress.spec.ts +++ b/tests/e2e/power-user-stress.spec.ts @@ -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 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: /skip this step/i }).click(); await expect(page.getByText(/Research Hub|Engineering|Sales Pipeline/i).first()).toBeVisible({ timeout: 5_000 }); }); diff --git a/tests/e2e/runtime-a11y.spec.ts b/tests/e2e/runtime-a11y.spec.ts index 152b670..334e1cc 100644 --- a/tests/e2e/runtime-a11y.spec.ts +++ b/tests/e2e/runtime-a11y.spec.ts @@ -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 { createRequire } from 'node:module'; @@ -27,10 +27,7 @@ const ROUTES = [ '/memory?tab=trust', '/memory?tab=memories', '/memory?tab=timeline', - '/memory?tab=graph', - '/memory?tab=harvest', '/memory?tab=weaver', - '/memory?tab=wiki', '/workspaces', '/workspaces/default-workspace/chat', '/workspaces/default-workspace/tasks', @@ -38,7 +35,6 @@ const ROUTES = [ '/automations', '/skills', '/room', - '/waggle-dance', '/launcher', '/connectors', '/mcps', @@ -46,7 +42,6 @@ const ROUTES = [ '/files', '/approvals', '/artifacts', - '/team', '/benchmarks', '/platform', ] 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('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 seedWaggleDanceSignal(request); await page.addInitScript(() => { window.localStorage.setItem('waggle:session-count', '49'); 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.getByRole('button', { name: 'Close notification' })).toHaveCSS('opacity', '1'); - await expect(page.getByTestId('waggle-unacknowledged-count')).toBeVisible(); expect(formatViolations(await runAxe(page))).toEqual([]); }); 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); await page.setViewportSize({ width: viewport.width, height: viewport.height }); - await seedWaggleDanceSignal(request); const findings: Array<{ route: string; violations: ReturnType }> = []; for (const route of ROUTES) { diff --git a/tests/e2e/user-journeys.spec.ts b/tests/e2e/user-journeys.spec.ts index 9a314f1..2f7a278 100644 --- a/tests/e2e/user-journeys.spec.ts +++ b/tests/e2e/user-journeys.spec.ts @@ -349,7 +349,9 @@ test.describe('User Journey Tests', () => { 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[] = []; let obsidianCalled = false; let notionCalled = false; @@ -898,7 +900,6 @@ test.describe('User Journey Tests', () => { const routeChecks: Array<[string, RegExp]> = [ ['/launcher', /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], ['/settings/profile', /who are you|identity|writing style|save/i], ['/settings/timeline', /timeline|workspace|activity/i],
In this room
- 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. -
+ 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. +
+ 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. +
Enable anonymous telemetry
+ {analyticsKey ? 'Share anonymous usage analytics' : 'Enable anonymous telemetry'} +
{telemetryCount} events collected
- 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 .waggle-backup 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 .waggle-backup if you might want to restore. Data already sent to cloud model providers is not erased. Ask those providers to delete it.
Download all workspaces, sessions, and memory as a zip
Import from ChatGPT or Claude export
- Fine-grained permissions, role-based access, and audit controls for your team. -
Role-Based Access
Owner, Admin, Member, Viewer
Tool Governance
Per-role tool allow/deny lists
Audit Trail
Full action history per member
Available on Teams ($49/mo per seat) and Enterprise tiers
Couldn't load signals
The Waggle Dance feed is unreachable — this is a load error, not an empty feed.
No waggle dance signals yet
Signals appear when agents share findings across workspaces
{signal.content}
{selectedSignal.content}
Metadata
- {JSON.stringify(selectedSignal.metadata, null, 2)} -
+ Waggle can send a small amount of usage data to PostHog to help improve the app. + Nothing is sent unless you choose Allow. +
What is sent:
Your chats, files and memories are never sent.
You can change this later in Settings, under Privacy & Telemetry.
{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 === 'team' && 'Browse or type the S3/MinIO bucket and prefix for shared storage.'}
Share with team
Make visible to all team members
- Data already sent to cloud providers (Anthropic, OpenAI, Stripe, etc.) and Teams servers is not 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 not erased by this action. Ask those providers to delete it.