feat(web): ask before sending analytics, drop team screens, hide v1-absent memory features (P1.3a)
- Analytics are opt-in (decision Q7, ADR-0006). PostHog does not start or capture anything until the user clicks Allow in a first-run dialog that says what is sent. Escape or closing stores nothing and asks again. The existing Privacy & Telemetry toggle in Settings withdraws consent at once. Builds without VITE_POSTHOG_KEY show no dialog and send nothing. - Remove the remaining upsell copy: the /team page with its per-seat price, Stripe and Teams wording in the erase-data dialog, Teams/Enterprise hints. - Remove team screens (decision Q3): Waggle Dance, team presence in chat, team storage and sharing in workspace creation, storage and files. - Hide memory features that are not in v1 (decision Q2) behind one map in lib/memory-features.ts: the knowledge graph, import history, wiki, agent memory hooks and Room launches. The map is the seam P1.5 fills from the memory store's capabilities. - Say Windows, macOS and Linux instead of "Linux soon". - Update the e2e specs for the removed and hidden screens. Also logs UF-029: the Settings "Import Data" button has no handler.
This commit is contained in:
@@ -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/<audit> and subscribeWaggleDance/<signal> 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/<audit> 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 () => {
|
||||
|
||||
@@ -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<WaggleSignal[]> {
|
||||
try {
|
||||
const res = await this.fetch('/api/waggle/signals');
|
||||
if (!res.ok) return [];
|
||||
return unwrapArray(await res.json());
|
||||
} catch (err) { console.error('[adapter] getWaggleSignals failed:', err); return []; }
|
||||
}
|
||||
|
||||
async publishWaggleSignal(data: Omit<WaggleSignal, 'id' | 'timestamp'>): Promise<WaggleSignal> {
|
||||
const res = await this.fetch('/api/waggle/signals', { method: 'POST', body: JSON.stringify(data) });
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async acknowledgeWaggleSignal(id: string): Promise<void> {
|
||||
await this.fetch(`/api/waggle/signals/${id}/ack`, { method: 'PATCH' });
|
||||
}
|
||||
|
||||
// --- AI-OS launcher (Phase 2B) ---
|
||||
// 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'}`;
|
||||
|
||||
62
apps/web/src/lib/analytics-consent.ts
Normal file
62
apps/web/src/lib/analytics-consent.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Analytics consent (ADR-0006): PostHog runs only after the user chooses
|
||||
* "Allow". The choice is stored in localStorage; no choice means not allowed.
|
||||
*
|
||||
* This module stays free of posthog-js so the startup bundle never carries it:
|
||||
* applying a choice loads `@/lib/posthog` on demand.
|
||||
*/
|
||||
|
||||
export type AnalyticsConsent = 'granted' | 'denied';
|
||||
|
||||
/** localStorage key holding the user's choice. */
|
||||
export const ANALYTICS_CONSENT_KEY = 'waggle:analytics-consent';
|
||||
|
||||
/** Pre-consent opt-out marker; 'true' is read as a denial. */
|
||||
export const LEGACY_OPT_OUT_KEY = 'waggle:telemetry-opt-out';
|
||||
|
||||
/** True when the build carries a PostHog key. Source builds have none. */
|
||||
export function hasAnalyticsKey(): boolean {
|
||||
return Boolean(import.meta.env['VITE_POSTHOG_KEY']);
|
||||
}
|
||||
|
||||
/** The stored choice, or null when the user has not chosen yet. */
|
||||
export function readAnalyticsConsent(): AnalyticsConsent | null {
|
||||
try {
|
||||
const stored = window.localStorage.getItem(ANALYTICS_CONSENT_KEY);
|
||||
if (stored === 'granted' || stored === 'denied') return stored;
|
||||
if (window.localStorage.getItem(LEGACY_OPT_OUT_KEY) === 'true') return 'denied';
|
||||
return null;
|
||||
} catch {
|
||||
// Storage unavailable: a choice could not be kept, so never send.
|
||||
return 'denied';
|
||||
}
|
||||
}
|
||||
|
||||
export function isAnalyticsAllowed(): boolean {
|
||||
return readAnalyticsConsent() === 'granted';
|
||||
}
|
||||
|
||||
/** Show the consent dialog only when there is something to consent to. */
|
||||
export function shouldAskAnalyticsConsent(): boolean {
|
||||
return hasAnalyticsKey() && readAnalyticsConsent() === null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Store the choice and apply it at once: "granted" starts PostHog, "denied"
|
||||
* opts out and resets it if it was running.
|
||||
*/
|
||||
export async function setAnalyticsConsent(choice: AnalyticsConsent): Promise<void> {
|
||||
try {
|
||||
window.localStorage.setItem(ANALYTICS_CONSENT_KEY, choice);
|
||||
} catch {
|
||||
// Ignore storage errors; readAnalyticsConsent() then reports 'denied'.
|
||||
}
|
||||
if (!hasAnalyticsKey()) return;
|
||||
try {
|
||||
const posthog = await import('@/lib/posthog');
|
||||
if (choice === 'granted') await posthog.initPostHog();
|
||||
else posthog.stopPostHog();
|
||||
} catch {
|
||||
// Analytics must never break the app.
|
||||
}
|
||||
}
|
||||
@@ -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'],
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -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];
|
||||
|
||||
|
||||
@@ -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" },
|
||||
|
||||
@@ -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' },
|
||||
],
|
||||
},
|
||||
|
||||
51
apps/web/src/lib/memory-features.ts
Normal file
51
apps/web/src/lib/memory-features.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Memory features the UI may show (ADR-0002).
|
||||
*
|
||||
* v1 memory is facts, search and the user profile. The features below are
|
||||
* hidden, not deleted: their screens stay in the code and every surface that
|
||||
* offers one checks this map first. A later work package fills the map from
|
||||
* the server's memory capability map, so read it only through this module.
|
||||
*/
|
||||
|
||||
export interface MemoryFeatures {
|
||||
/** Knowledge graph (entities and relations). Deferred to a later release. */
|
||||
knowledgeGraph: boolean;
|
||||
/** Importing chat history from other AI tools (harvest). */
|
||||
importHistory: boolean;
|
||||
/** Compiled wiki pages. */
|
||||
wiki: boolean;
|
||||
/** Memory hooks installed into Claude Code, Codex and other coding agents. */
|
||||
agentHooks: boolean;
|
||||
/** Waggle Room: coding agents started as a team that shares one Room. */
|
||||
room: boolean;
|
||||
/** The Waggle memory MCP server for other clients. */
|
||||
memoryMcp: boolean;
|
||||
}
|
||||
|
||||
export type MemoryFeature = keyof MemoryFeatures;
|
||||
|
||||
const MEMORY_FEATURES: Readonly<MemoryFeatures> = {
|
||||
knowledgeGraph: false,
|
||||
importHistory: false,
|
||||
wiki: false,
|
||||
agentHooks: false,
|
||||
room: false,
|
||||
memoryMcp: false,
|
||||
};
|
||||
|
||||
export function hasMemoryFeature(feature: MemoryFeature): boolean {
|
||||
return MEMORY_FEATURES[feature];
|
||||
}
|
||||
|
||||
/** Memory Center views (`?tab=`) that belong to a hidden feature. */
|
||||
const MEMORY_VIEW_FEATURE: Readonly<Record<string, MemoryFeature>> = {
|
||||
graph: 'knowledgeGraph',
|
||||
harvest: 'importHistory',
|
||||
wiki: 'wiki',
|
||||
};
|
||||
|
||||
/** False for a Memory Center view whose feature is hidden. */
|
||||
export function isMemoryViewAvailable(view: string): boolean {
|
||||
const feature = MEMORY_VIEW_FEATURE[view];
|
||||
return feature === undefined || hasMemoryFeature(feature);
|
||||
}
|
||||
@@ -39,13 +39,11 @@ const ROUTE_LABELS: Record<string, string> = {
|
||||
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',
|
||||
|
||||
@@ -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).
|
||||
*/
|
||||
|
||||
@@ -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<string, string> = {};
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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<void> {
|
||||
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<void> — 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<void> {
|
||||
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.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<string, unknown>;
|
||||
timestamp: string;
|
||||
acknowledged?: boolean;
|
||||
priority?: 'low' | 'normal' | 'high' | 'critical';
|
||||
}
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
/**
|
||||
* M-41 / P18 — waggle-signal sort + group regression.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
sortSignalsForDisplay,
|
||||
groupSignalsByType,
|
||||
countUnacknowledged,
|
||||
type WaggleSignalLike,
|
||||
} from './waggle-signals';
|
||||
|
||||
function make(overrides: Partial<WaggleSignalLike> = {}): WaggleSignalLike {
|
||||
return {
|
||||
id: overrides.id ?? `s-${Math.random()}`,
|
||||
type: overrides.type ?? 'discovery',
|
||||
severity: overrides.severity ?? 'normal',
|
||||
acknowledged: overrides.acknowledged ?? false,
|
||||
timestamp: overrides.timestamp ?? '2026-04-19T00:00:00Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('sortSignalsForDisplay', () => {
|
||||
it('surfaces unacknowledged before acknowledged', () => {
|
||||
const input = [
|
||||
make({ id: 'a', acknowledged: true }),
|
||||
make({ id: 'b', acknowledged: false }),
|
||||
];
|
||||
expect(sortSignalsForDisplay(input).map(s => s.id)).toEqual(['b', 'a']);
|
||||
});
|
||||
|
||||
it('within the same ack bucket, higher severity wins', () => {
|
||||
const input = [
|
||||
make({ id: 'normal', severity: 'normal' }),
|
||||
make({ id: 'critical', severity: 'critical' }),
|
||||
make({ id: 'high', severity: 'high' }),
|
||||
make({ id: 'low', severity: 'low' }),
|
||||
];
|
||||
expect(sortSignalsForDisplay(input).map(s => s.id)).toEqual(['critical', 'high', 'normal', 'low']);
|
||||
});
|
||||
|
||||
it('within the same severity, more recent timestamp wins', () => {
|
||||
const input = [
|
||||
make({ id: 'old', timestamp: '2026-04-10T00:00:00Z' }),
|
||||
make({ id: 'new', timestamp: '2026-04-19T00:00:00Z' }),
|
||||
make({ id: 'mid', timestamp: '2026-04-15T00:00:00Z' }),
|
||||
];
|
||||
expect(sortSignalsForDisplay(input).map(s => s.id)).toEqual(['new', 'mid', 'old']);
|
||||
});
|
||||
|
||||
it('composes ack > severity > timestamp', () => {
|
||||
const input = [
|
||||
make({ id: 'ack-critical', acknowledged: true, severity: 'critical', timestamp: '2026-04-19T00:00:00Z' }),
|
||||
make({ id: 'new-normal', acknowledged: false, severity: 'normal', timestamp: '2026-04-19T00:00:00Z' }),
|
||||
make({ id: 'old-critical', acknowledged: false, severity: 'critical', timestamp: '2026-04-01T00:00:00Z' }),
|
||||
];
|
||||
// Unacknowledged first; within unack, critical > normal; within critical, only one item.
|
||||
expect(sortSignalsForDisplay(input).map(s => s.id)).toEqual([
|
||||
'old-critical', 'new-normal', 'ack-critical',
|
||||
]);
|
||||
});
|
||||
|
||||
it('tolerates missing / null fields', () => {
|
||||
const input = [
|
||||
make({ id: 'a', severity: null, timestamp: null }),
|
||||
make({ id: 'b', severity: undefined, timestamp: undefined }),
|
||||
];
|
||||
// No crash — treat missing as normal / 0.
|
||||
expect(sortSignalsForDisplay(input)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('does not mutate the input array', () => {
|
||||
const input = [make({ id: '1' }), make({ id: '2' })];
|
||||
const before = input.slice();
|
||||
sortSignalsForDisplay(input);
|
||||
expect(input).toEqual(before);
|
||||
});
|
||||
|
||||
it('parses numeric timestamps as raw ms', () => {
|
||||
const input = [
|
||||
make({ id: 'old', timestamp: 1000 }),
|
||||
make({ id: 'new', timestamp: 2000 }),
|
||||
];
|
||||
expect(sortSignalsForDisplay(input).map(s => s.id)).toEqual(['new', 'old']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('groupSignalsByType', () => {
|
||||
it('groups by the type field', () => {
|
||||
const input = [
|
||||
make({ id: '1', type: 'discovery' }),
|
||||
make({ id: '2', type: 'handoff' }),
|
||||
make({ id: '3', type: 'discovery' }),
|
||||
];
|
||||
const groups = groupSignalsByType(input);
|
||||
expect(groups.discovery?.map(s => s.id)).toEqual(['1', '3']);
|
||||
expect(groups.handoff?.map(s => s.id)).toEqual(['2']);
|
||||
});
|
||||
|
||||
it('buckets unknown types under "unknown"', () => {
|
||||
const input = [make({ id: '1', type: 123 as unknown as string })];
|
||||
const groups = groupSignalsByType(input);
|
||||
expect(groups.unknown?.map(s => s.id)).toEqual(['1']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('countUnacknowledged', () => {
|
||||
it('counts only unacked items', () => {
|
||||
const input = [
|
||||
make({ acknowledged: false }),
|
||||
make({ acknowledged: false }),
|
||||
make({ acknowledged: true }),
|
||||
];
|
||||
expect(countUnacknowledged(input)).toBe(2);
|
||||
});
|
||||
|
||||
it('treats missing acknowledged as false (unacked)', () => {
|
||||
const input = [
|
||||
{ id: '1', type: 'discovery' } as WaggleSignalLike,
|
||||
{ id: '2', type: 'discovery', acknowledged: true } as WaggleSignalLike,
|
||||
];
|
||||
expect(countUnacknowledged(input)).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -1,73 +0,0 @@
|
||||
/**
|
||||
* WaggleSignal presentation helpers (M-41 / P18).
|
||||
*
|
||||
* The Waggle Dance app surfaces cross-agent signals (discovery,
|
||||
* handoff, insight, alert, coordination). A user scanning the list
|
||||
* wants unacknowledged items first, then the most severe items,
|
||||
* then recency. This helper centralises that ordering so the UI
|
||||
* stays consistent across list, counters, and summary surfaces.
|
||||
*/
|
||||
|
||||
export type WaggleSignalType = 'discovery' | 'handoff' | 'insight' | 'alert' | 'coordination';
|
||||
|
||||
export interface WaggleSignalLike {
|
||||
readonly id: string;
|
||||
readonly type: WaggleSignalType | string;
|
||||
readonly severity?: 'critical' | 'high' | 'normal' | 'low' | null;
|
||||
readonly acknowledged?: boolean;
|
||||
readonly timestamp?: string | number | null;
|
||||
}
|
||||
|
||||
/** Severity weight: higher = surfaces earlier. */
|
||||
const SEVERITY_WEIGHT: Record<string, number> = {
|
||||
critical: 4,
|
||||
high: 3,
|
||||
normal: 2,
|
||||
low: 1,
|
||||
};
|
||||
|
||||
function severityScore(s: WaggleSignalLike): number {
|
||||
const key = s.severity ?? 'normal';
|
||||
return SEVERITY_WEIGHT[key] ?? SEVERITY_WEIGHT.normal;
|
||||
}
|
||||
|
||||
function timestampMs(s: WaggleSignalLike): number {
|
||||
const ts = s.timestamp;
|
||||
if (typeof ts === 'number') return ts;
|
||||
if (typeof ts === 'string') {
|
||||
const parsed = Date.parse(ts);
|
||||
return Number.isFinite(parsed) ? parsed : 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort signals for display. Unacknowledged first, then severity desc,
|
||||
* then timestamp desc. Returns a new array — does not mutate.
|
||||
*/
|
||||
export function sortSignalsForDisplay<T extends WaggleSignalLike>(signals: readonly T[]): T[] {
|
||||
return [...signals].sort((a, b) => {
|
||||
const ackA = a.acknowledged ? 1 : 0;
|
||||
const ackB = b.acknowledged ? 1 : 0;
|
||||
if (ackA !== ackB) return ackA - ackB;
|
||||
const sevDiff = severityScore(b) - severityScore(a);
|
||||
if (sevDiff !== 0) return sevDiff;
|
||||
return timestampMs(b) - timestampMs(a);
|
||||
});
|
||||
}
|
||||
|
||||
/** Group signals by type for summary display. */
|
||||
export function groupSignalsByType<T extends WaggleSignalLike>(signals: readonly T[]): Record<string, T[]> {
|
||||
const out: Record<string, T[]> = {};
|
||||
for (const s of signals) {
|
||||
const type = typeof s.type === 'string' ? s.type : 'unknown';
|
||||
if (!out[type]) out[type] = [];
|
||||
out[type].push(s);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Count of unacknowledged signals — used for the header badge. */
|
||||
export function countUnacknowledged(signals: readonly WaggleSignalLike[]): number {
|
||||
return signals.reduce((n, s) => n + (s.acknowledged ? 0 : 1), 0);
|
||||
}
|
||||
Reference in New Issue
Block a user