refactor: remove the billing tier model (P0.1)

The community edition has no monetization (ADR-0001). Remove the tier
model (packages/shared/src/tiers.ts), the requireTier middleware and every
tier gate, GET/PATCH /api/tier and the trial start, and the Stripe
integration, which depends on the tier model.

Personal features a tier used to limit are open to everyone: unlimited
workspaces and connectors, every embedding provider including LiteLLM,
per-workspace costs, Approvals. The workspace session cap is one constant
(100). Team and enterprise surfaces are hidden instead of unlocked (team
dock zone, Settings Team/Enterprise/Plan tabs, workspace Team tab);
cloud sync reports unavailable, as it did for free users.

The sidecar ignores the tier keys in config.json but does not delete them:
both editions may still share ~/.waggle.

Web billing UI is deleted: plan cards, upgrade and trial modals, payment
success route, the KVARK sales block, tier 403 handling.
This commit is contained in:
shumeiko.it
2026-10-15 19:31:50 +02:00
parent 369d8269c1
commit fe2eb0f648
117 changed files with 342 additions and 6424 deletions

View File

@@ -1,5 +1,5 @@
import { lazy, Suspense, useEffect, type ReactNode } from "react";
import { BrowserRouter, Navigate, Route, Routes, useNavigate } from "react-router-dom";
import { BrowserRouter, Route, Routes, useNavigate } from "react-router-dom";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
@@ -39,7 +39,6 @@ const UsageRoute = lazy(() => import("@/routes/UsageRoute"));
const BenchmarkRoute = lazy(() => import("@/routes/BenchmarkRoute"));
const PlatformRoute = lazy(() => import("@/routes/PlatformRoute"));
const WorkspacesRoute = lazy(() => import("@/routes/WorkspacesRoute"));
const PaymentSuccessRoute = lazy(() => import("@/routes/PaymentSuccessRoute"));
const AuthRoute = lazy(() => import("@/routes/AuthRoute"));
// Theme is now owned by <ThemeProvider>; the pre-paint apply lives in main.tsx
@@ -153,7 +152,7 @@ const App = () => (
<Route path="mcps" element={routeElement(<McpsRoute />)} />
<Route path="marketplace" element={routeElement(<MarketplaceRoute />)} />
<Route path="launcher" element={routeElement(<LauncherRoute />)} />
{/* ── Team (route registered; nav tier-hidden below TEAMS, D5) ── */}
{/* ── Team (route registered; no nav entry — team mode is not shipped, ADR-0003) ── */}
<Route path="team" element={routeElement(<TeamRoute />)} />
{/* ── System (§9.4: System surfaces nest under /settings/*) ── */}
<Route path="settings" element={routeElement(<SettingsRoute />)} />
@@ -166,9 +165,6 @@ const App = () => (
{/* ── PR6a: ⌘K-only static surfaces ── */}
<Route path="benchmarks" element={routeElement(<BenchmarkRoute />)} />
<Route path="platform" element={routeElement(<PlatformRoute />)} />
{/* ── PR7a: Stripe Checkout return URLs (checkout.ts:42-43) ── */}
<Route path="payment-success" element={routeElement(<PaymentSuccessRoute />)} />
<Route path="payment-cancelled" element={<Navigate to="/settings?tab=billing&checkout=cancelled" replace />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
<Route path="*" element={<NotFound />} />
</Route>

View File

@@ -4,9 +4,9 @@
* Owns: BootScreen gate (FR #23 sequencing ported from the retired
* pages/Index.tsx), the §3.3 window-state migration boot (one-shot, before the
* first canvas render), onboarding takeover (§1.2 — wizard renders INSTEAD of
* nav+canvas), left nav (same getDockForTier/filterByBillingTier data the dock
* consumed, §1.3), StatusBar, global overlays (the old Desktop.tsx mount block
* relocated), the `waggle:open-app` shim (§2.3), the keep-alive ChatHost
* nav+canvas), left nav (same getDockForTier data the dock consumed, §1.3),
* StatusBar, global overlays (the old Desktop.tsx mount block relocated),
* the `waggle:open-app` shim (§2.3), the keep-alive ChatHost
* (§4.2), and `<Outlet/>` as the single canvas.
*
* Stage C (the flip): this IS the live shell — App.tsx mounts it as the `/`
@@ -23,7 +23,6 @@ import StatusBar from './StatusBar';
import RouteTransition from './RouteTransition';
import Sidebar, { type SidebarNavItem } from './Sidebar';
import AppErrorBoundary from './ErrorBoundary';
import UpgradeModal from './overlays/UpgradeModal';
import { adapter } from '@/lib/adapter';
import { stashDeepLink } from '@/lib/app-deeplink';
import { writeLoginBriefingDismissed, writeLoginBriefingLastDismissedAt, readLoginBriefingDismissed, readSkipBriefingParam } from '@/lib/login-briefing';
@@ -33,8 +32,7 @@ import { resolveReturningUserOnboarding, isOnboardingStatusKnownSync } from '@/h
import { shouldShowCoachMarks, readOnboardedThisSession, readForceTour, clearForceTour } from '@/lib/coach-marks-gate';
import { matchNavRoute, queryString, routeFor, routeForSearchResult } from '@/lib/routes';
import { bootWindowStateMigration, indexLandingRoute } from '@/lib/window-state-migration';
import { getDockForTier, BILLING_TIER_ORDER, type AppId, type DockEntry } from '@/lib/dock-tiers';
import { TIER_LABELS } from '@waggle/shared';
import { getDockForTier, type AppId, type DockEntry } from '@/lib/dock-tiers';
import { buildCommandCatalog, type CatalogCommand } from '@/lib/command-catalog';
import { ShellProvider, useShell } from '@/providers/ShellContext';
import { seedChat, useChatWidgetState } from '@/hooks/useChatWidgetState';
@@ -58,7 +56,6 @@ 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 TrialExpiredModal = lazy(() => import('./overlays/TrialExpiredModal'));
const deferredShellElement = (element: ReactNode) => (
<Suspense fallback={null}>{element}</Suspense>
@@ -74,7 +71,7 @@ const deferredShellElement = (element: ReactNode) => (
*/
const WORKSPACE_TAB_LABELS: Record<string, string> = {
overview: 'Overview', chat: 'Chat', memory: 'Memory',
artifacts: 'Artifacts', files: 'Files', team: 'Team', tasks: 'Tasks',
artifacts: 'Artifacts', files: 'Files', tasks: 'Tasks',
};
/** Flatten zone-parents so nav active-state/title lookups see every app entry. */
@@ -124,7 +121,7 @@ const ShellLayout = () => {
workspaces, activeWorkspace, activeWorkspaceId,
selectWorkspace, createWorkspace, patchWorkspace, refreshWorkspaces, workspacesError,
workspacesLoading,
currentTier, billingTier, trialInfo, refreshTier, showTrialExpired, setShowTrialExpired,
currentTier,
notifications, unreadCount, markRead, markAllRead,
onboardingState, updateOnboarding, completeOnboarding,
offline, agentStatus,
@@ -197,9 +194,6 @@ const ShellLayout = () => {
// call can race the session-token attach and 401 → name:null. Falls back to
// "Account" in the row when unconfigured.
const [userName, setUserName] = useState<string | null>(null);
// F5: the UpgradeModal self-opens on a window event, so the shell can't see
// its open state without this. Feeds `anyModalOpen` so coach-marks hide under it.
const [upgradeOpen, setUpgradeOpen] = useState(false);
useEffect(() => {
let cancelled = false;
const loadIdentity = () => {
@@ -299,10 +293,7 @@ const ShellLayout = () => {
// Onboarding completion handlers (relocated from Desktop.tsx:290-313).
const handleOnboardingComplete = useCallback((_serverBaseUrl: string) => {
completeOnboarding();
// Atomic start. 409 (trial already started) is fine — refresh state
// either way so the StatusBar countdown picks up the existing timestamp.
adapter.startTrial().then(refreshTier).catch(refreshTier);
}, [completeOnboarding, refreshTier]);
}, [completeOnboarding]);
const handleOnboardingFinish = useCallback((workspaceId: string, workspaceName: string, firstMessage?: string, personaId?: string) => {
selectWorkspace(workspaceId);
@@ -332,7 +323,7 @@ const ShellLayout = () => {
// everything else lives one keystroke away in ⌘K. The StatusBar breadcrumb
// still derives from the full dock route table — every route is now reachable
// via ⌘K regardless of tier, so the label map must cover them all.
const labelEntries = useMemo(() => flattenAppEntries(getDockForTier('power', billingTier)), [billingTier]);
const labelEntries = useMemo(() => flattenAppEntries(getDockForTier('power')), []);
const activeRoute = useMemo(
() => matchNavRoute(location.pathname, labelEntries.map(e => e.route).filter((r): r is string => !!r)),
[location.pathname, labelEntries],
@@ -385,7 +376,6 @@ const ShellLayout = () => {
// Agents & tasks badge surfaces unacknowledged coordination signals for now;
// PR3 refines it to the real pending-approvals/tasks count.
const isPro = currentTier === 'power' || currentTier === 'admin';
const billingRank = BILLING_TIER_ORDER[billingTier] ?? 0;
const spine: SidebarNavItem[] = useMemo(() => [
{ key: 'home', label: 'Home', icon: Home, to: '/home', match: ['/home'] },
// Chat resolves to the active workspace's chat tab; with no real workspace,
@@ -407,27 +397,17 @@ const ShellLayout = () => {
], [effectiveActiveWorkspaceId, navigateToActiveChat, waggleUnacknowledged]);
const pinned: SidebarNavItem[] = useMemo(() => {
if (!isPro) return [];
const items: SidebarNavItem[] = [
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'] },
];
// Approvals is a TEAMS-tier surface (parity with dock-tiers minBillingTier).
if (billingRank >= BILLING_TIER_ORDER.TEAMS) items.push({ key: 'approvals', label: 'Approvals', icon: Shield, to: '/approvals', match: ['/approvals'] });
return items;
}, [isPro, billingRank]);
// Plan label for the user row (e.g. "Trial · 9d", "Solo", "Team").
const tierLabel = useMemo(() => {
if (billingTier === 'TRIAL' || (trialInfo.trialDaysRemaining > 0 && !trialInfo.trialExpired)) {
return trialInfo.trialDaysRemaining > 0 ? `Trial · ${trialInfo.trialDaysRemaining}d` : 'Trial';
}
return TIER_LABELS[billingTier];
}, [billingTier, trialInfo.trialDaysRemaining, trialInfo.trialExpired]);
}, [isPro]);
// ⌘K curated catalog (Jump to / Do / Power tools + Pro "Pinned") → real routes.
const commandCatalog = useMemo(
() => buildCommandCatalog({ chatHref: routeFor('chat', { activeWorkspaceId: effectiveActiveWorkspaceId }), isPro, billingRank }),
[effectiveActiveWorkspaceId, isPro, billingRank],
() => buildCommandCatalog({ chatHref: routeFor('chat', { activeWorkspaceId: effectiveActiveWorkspaceId }), isPro }),
[effectiveActiveWorkspaceId, isPro],
);
const handleCatalogSelect = useCallback((cmd: CatalogCommand) => {
if (cmd.action === 'spawn') { ov.setShowSpawnAgent(true); return; }
@@ -455,12 +435,11 @@ const ShellLayout = () => {
}
// F5: any shell overlay open ⇒ suppress the coach-mark carousel (hide-but-keep
// tour state, per OnboardingTooltips' `suppressed` contract). Includes the
// event-driven UpgradeModal (via upgradeOpen) and the trial paywall.
// tour state, per OnboardingTooltips' `suppressed` contract).
const anyModalOpen =
ov.showGlobalSearch || ov.showCreateWorkspace || ov.showPersonaSwitcher ||
ov.showWorkspaceSwitcher || ov.showNotifications || ov.showKeyboardHelp ||
ov.showSpawnAgent || showTrialExpired || upgradeOpen;
ov.showSpawnAgent;
return (
<div className="relative w-screen h-screen overflow-hidden select-none">
@@ -475,7 +454,6 @@ const ShellLayout = () => {
model={effectiveActiveWorkspace?.model ?? (agentStatus.model !== 'unknown' ? agentStatus.model : undefined)}
tokensUsed={agentStatus.tokensUsed} costUsd={agentStatus.costUsd} offline={offline}
unreadNotifications={unreadCount}
trialDaysRemaining={trialInfo.trialDaysRemaining} trialExpired={trialInfo.trialExpired}
onSearchClick={() => ov.setShowGlobalSearch(true)} onNotificationClick={ov.toggleNotifications} />
<div className="absolute inset-x-0 top-8 bottom-0 flex">
@@ -489,7 +467,6 @@ const ShellLayout = () => {
onOpenCommand={() => ov.setShowGlobalSearch(true)}
onSpawnAgent={() => ov.setShowSpawnAgent(true)}
userName={userName}
tierLabel={tierLabel}
/>
{/* Single canvas (§2.1 rule 1). Route wrappers bring their own
@@ -616,38 +593,6 @@ const ShellLayout = () => {
{contextRailTarget && deferredShellElement(
<ContextRail target={contextRailTarget} onClose={() => setContextRailTarget(null)} />
)}
<UpgradeModal
onOpenChange={setUpgradeOpen}
onStartTrial={() => {
adapter.startTrial().then(refreshTier).catch(refreshTier);
}}
onUpgrade={(tier) => {
// PR7a: navigate to hosted Stripe Checkout (the URL was previously
// discarded — a dead happy path). Same-tab assign rather than a deferred
// window.open: the open happens after an awaited round-trip, outside the
// user-gesture window, so a popup blocker / Tauri WebView could swallow it.
// Hosted Checkout redirects back to /payment-success on completion.
adapter.createCheckoutSession(tier)
.then(({ url }) => { if (url) window.location.assign(url); })
.catch(() => { navigate('/settings?tab=billing'); });
}}
/>
{showTrialExpired && deferredShellElement(
<TrialExpiredModal
open
onDismiss={() => setShowTrialExpired(false)}
onUpgrade={(tier) => {
setShowTrialExpired(false);
// PR7a: same-tab navigate to hosted Checkout (avoids the deferred-popup
// blocker; redirects back to /payment-success). Plan-tab fallback on failure.
adapter.createCheckoutSession(tier)
.then(({ url }) => { if (url) window.location.assign(url); })
.catch(() => { navigate('/settings?tab=billing'); });
}}
/>
)}
</div>
);
};

View File

@@ -2,8 +2,8 @@
* EmbeddingRoutingCard — pick the memory embedding provider (steal #10).
*
* Sits under ModelPilotCard in Settings › Models. Mirrors ModelPilotCard's Hive DS
* styling and key-gating pattern. The picker offers `auto` + the tier-allowed
* providers; voyage/openai are disabled when their vault key is missing. A live
* styling and key-gating pattern. The picker offers `auto` + every selectable
* provider; voyage/openai are disabled when their vault key is missing. A live
* badge shows what is actually running; a Reprobe button re-runs the probe (useful
* after installing Ollama or adding a key). Because the live embedder is fixed at
* boot, an explicit switch shows a "restart to apply" hint honestly.
@@ -13,14 +13,11 @@ import { useState, useEffect, useCallback } from 'react';
import { Boxes, RotateCw, Info, AlertTriangle } from 'lucide-react';
import { adapter, AdapterHttpError, type EmbeddingRoutingStatus } from '@/lib/adapter';
import type { Provider } from '@/hooks/useProviders';
import { TIER_CAPABILITIES, type Tier } from '@waggle/shared';
import { HintTooltip } from '@/components/ui/hint-tooltip';
interface EmbeddingRoutingCardProps {
/** For voyage/openai key-gating (mirrors ModelPilotCard). */
providers: Provider[];
/** Gates which providers the tier may select. */
tier: Tier;
}
/** Display order for the picker; 'mock' is never user-selectable. */
@@ -36,7 +33,7 @@ const PROVIDER_LABELS: Record<string, string> = {
mock: 'Mock (no semantics)',
};
const EmbeddingRoutingCard = ({ providers, tier }: EmbeddingRoutingCardProps) => {
const EmbeddingRoutingCard = ({ providers }: EmbeddingRoutingCardProps) => {
const [status, setStatus] = useState<EmbeddingRoutingStatus | null>(null);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
@@ -56,10 +53,6 @@ const EmbeddingRoutingCard = ({ providers, tier }: EmbeddingRoutingCardProps) =>
useEffect(() => { void load(); }, [load]);
// Tier-allowed providers (+ always 'auto'), in display order, minus 'mock'.
const allowed = new Set(TIER_CAPABILITIES[tier].embeddingProviders as readonly string[]);
const options = PROVIDER_ORDER.filter(p => p === 'auto' || (p !== ('mock' as string) && allowed.has(p)));
/** True when a cloud provider's key is missing (disable + hint). */
const keyMissing = (id: string): boolean => {
if (id === 'openai') {
@@ -182,7 +175,7 @@ const EmbeddingRoutingCard = ({ providers, tier }: EmbeddingRoutingCardProps) =>
onChange={(e) => void handleChange(e.target.value)}
className="w-full bg-muted/50 border border-border/30 rounded-lg px-2 py-1.5 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary/30 disabled:opacity-50"
>
{options.map(p => {
{PROVIDER_ORDER.map(p => {
const missing = keyMissing(p);
return (
<option key={p} value={p} disabled={missing}>

View File

@@ -1,30 +0,0 @@
import { Lock, ArrowUpRight } from 'lucide-react';
interface LockedFeatureProps {
featureName: string;
upgradePrompt: string;
children?: React.ReactNode;
}
const LockedFeature = ({ featureName, upgradePrompt, children }: LockedFeatureProps) => (
<div className="relative h-full">
{children && (
<div className="h-full opacity-20 pointer-events-none select-none blur-[1px]">
{children}
</div>
)}
<div className="absolute inset-0 flex flex-col items-center justify-center gap-3 p-6 text-center">
<div className="w-12 h-12 rounded-full bg-muted/50 flex items-center justify-center">
<Lock className="w-5 h-5 text-muted-foreground" />
</div>
<p className="text-sm font-display font-medium text-foreground">{featureName}</p>
<p className="text-xs text-muted-foreground max-w-xs">{upgradePrompt}</p>
<button className="flex items-center gap-1.5 mt-1 px-4 py-2 text-xs font-medium rounded-lg bg-primary/20 text-honey hover:bg-primary/30 transition-colors">
<ArrowUpRight className="w-3.5 h-3.5" />
View Plans
</button>
</div>
</div>
);
export default LockedFeature;

View File

@@ -43,7 +43,6 @@ interface SidebarProps {
onOpenCommand: () => void;
onSpawnAgent: () => void;
userName: string | null;
tierLabel: string;
}
function initialOf(name: string | null, fallback: string): string {
@@ -59,7 +58,6 @@ const Sidebar = ({
onOpenCommand,
onSpawnAgent,
userName,
tierLabel,
}: SidebarProps) => {
const navigate = useNavigate();
const { pathname } = useLocation();
@@ -207,9 +205,6 @@ const Sidebar = ({
<span className="block truncate text-[13px] font-semibold">
{userName ?? "Account"}
</span>
{/* Lane F2: --text-dim measured 4.47:1 on --bg-2 (nav) in light — sub-AA.
--text-tertiary clears it (4.77:1 light / 6.31:1 dark). */}
<span className="font-mono text-[10.5px] text-[var(--text-tertiary)]">{tierLabel}</span>
</span>
</button>
</HintTooltip>

View File

@@ -1,5 +1,4 @@
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { WifiOff, Search, Bell, Brain } from "lucide-react";
import waggleLogoDark from "@/assets/waggle-logo.jpeg";
import waggleLogoLight from "@/assets/waggle-logo.png";
@@ -25,15 +24,12 @@ interface StatusBarProps {
costUsd?: number;
offline?: boolean;
unreadNotifications?: number;
trialDaysRemaining?: number;
trialExpired?: boolean;
onSearchClick?: () => void;
onNotificationClick?: () => void;
}
const StatusBar = ({ workspaceName, focusedWindowLabel, model, tokensUsed, costUsd, offline, unreadNotifications = 0, trialDaysRemaining: trialDays, trialExpired, onSearchClick, onNotificationClick }: StatusBarProps) => {
const StatusBar = ({ workspaceName, focusedWindowLabel, model, tokensUsed, costUsd, offline, unreadNotifications = 0, onSearchClick, onNotificationClick }: StatusBarProps) => {
const [time, setTime] = useState(new Date());
const navigate = useNavigate();
const isLight = useIsLightTheme();
const waggleLogo = isLight ? waggleLogoLight : waggleLogoDark;
// M-20 / UX-5: token + cost are developer-facing signal. Hidden by
@@ -203,24 +199,6 @@ const StatusBar = ({ workspaceName, focusedWindowLabel, model, tokensUsed, costU
</div>
<div className="flex items-center gap-2 lg:gap-4 shrink-0">
{trialDays !== undefined && trialDays > 0 && (
<span className={`text-[10px] font-display font-semibold px-2 py-0.5 rounded-full whitespace-nowrap ${trialDays <= 3 ? 'bg-destructive/20 text-destructive' : 'bg-primary/15 text-honey'}`}>
Trial: {trialDays}d left
</span>
)}
{trialExpired && (
/* R9 Lane D: the amber pill "screamed" on every screen for a benign
steady state (you're on the free Solo plan). Demoted to a quiet
neutral text-chip — still a button that routes to plans. */
<button
type="button"
onClick={() => navigate('/settings?tab=billing')}
className="text-[10px] font-display px-1.5 py-0.5 rounded-md text-muted-foreground whitespace-nowrap transition-colors hover:text-honey"
title="You're on the free Solo plan (your trial ended). See plans."
>
Solo plan
</button>
)}
<HintTooltip content="Search (Ctrl+K)">
<button
onClick={onSearchClick}

View File

@@ -23,8 +23,6 @@ import InstallAuditPanel from './extend/InstallAuditPanel';
* - Test = C37 PREVIEW-ONLY (injected prompt + parsed metadata, no LLM call).
* - Install = the per-source dispatcher (starter | pack | marketplace) —
* capability packs no longer mis-route through the starter installer.
* - The PRO tier gate stays load-bearing: 403 → 'waggle:tier-insufficient'
* → UpgradeModal.
*/
const trustBadges: Record<string, { color: string; icon: React.ElementType }> = {
@@ -200,9 +198,8 @@ const CapabilitiesApp = () => {
/**
* §D2 — run the run-and-grade audit for ONE skill (scoped POST = a few LLM
* calls), then reload so a freshly-minted "verified" badge appears. A 403
* (non-PRO tier) throws AdapterHttpError and is routed to the UpgradeModal by
* the fetch chokepoint; any other failure surfaces in the result panel.
* calls), then reload so a freshly-minted "verified" badge appears. A
* failure surfaces in the result panel.
*/
const handleVerifySkill = async (skillName: string) => {
setVerifying(skillName);
@@ -222,23 +219,6 @@ const CapabilitiesApp = () => {
finally { setVerifying(null); }
};
// Shared 403→UpgradeModal routing. Other errors fall through to the caller
// so they can show a toast or inline state without duplicating tier logic.
const handleInstallError = (err: unknown, packName: string): boolean => {
const e = err as { status?: number; message?: string; body?: { required?: string; actual?: string } };
if (e.status === 403) {
window.dispatchEvent(new CustomEvent('waggle:tier-insufficient', {
detail: {
required: e.body?.required ?? 'TEAMS',
actual: e.body?.actual ?? 'FREE',
message: `Installing "${packName}" needs the Team plan or an active trial.`,
},
}));
return true;
}
return false;
};
/** Per-source install dispatcher (3A): starter-pack ids install via the
* starter route, capability-pack ids via the pack route. A pack install
* with per-skill failures comes back 422 — surfaced inline, not swallowed. */
@@ -254,9 +234,7 @@ const CapabilitiesApp = () => {
// invisible until the window is reopened.
load();
} catch (err) {
if (!handleInstallError(err, packId)) {
setInstallError(err instanceof Error ? err.message : `Failed to install "${packId}"`);
}
setInstallError(err instanceof Error ? err.message : `Failed to install "${packId}"`);
} finally { setInstalling(null); }
};
@@ -639,7 +617,6 @@ const CapabilitiesApp = () => {
// skill on disk even when the user Escapes/Cancels instead of
// pressing Done — the Hub must reflect the file that now exists.
onCancel={() => { setShowCreate(false); load(); }}
onTierError={handleInstallError}
/>
)}

View File

@@ -7,10 +7,9 @@
* C21 test with the live/static mode label, C19 scope editor, revoke with
* a scope-and-consequence confirm). Logs = honest coming-soon (no route).
* - Catalog: the static registry grid (McpCatalog) wired to the real
* installer — PRO+ (B5; 403 routes through the UpgradeModal) and the
* SecurityGate "risk approval required" path renders the ApprovalModal
* (HIGH findings can be force-overridden; CRITICAL never).
* - Custom: register an arbitrary stdio server (PRO+ server-side).
* installer — the SecurityGate "risk approval required" path renders the
* ApprovalModal (HIGH findings can be force-overridden; CRITICAL never).
* - Custom: register an arbitrary stdio server.
* - Remote Registry: C20 deferred — static catalog pointers only, the
* runtime is stdio-only in v1.
*
@@ -156,7 +155,7 @@ const MCPHubApp = ({ personaId }: MCPHubAppProps = {}) => {
// instead of being wiped by an unmount.
const initialLoading = loading && items.length === 0;
/** B5 PRO+ install via the marketplace installer; `force` = approved HIGH
/** Install via the marketplace installer; `force` = approved HIGH
* override. The block that actually fires lives INSIDE installer.install()
* and is only overridable via `forceInsecure` (the audited override path);
* `force` alone just means "reinstall" — retrying with it loops the
@@ -168,7 +167,6 @@ const MCPHubApp = ({ personaId }: MCPHubAppProps = {}) => {
const res = await adapter.installMcp(id, force ? { force: true, forceInsecure: true } : undefined) as {
installed?: boolean; server?: string; status?: string; startError?: string;
requiresApproval?: boolean; error?: string; message?: string;
required?: string; actual?: string;
// Installer-level 422 blocks nest the scan; route-level 403 blocks
// are top-level { blocked, severity, message } with NO scanResult.
blocked?: boolean; severity?: string;
@@ -185,19 +183,6 @@ const MCPHubApp = ({ personaId }: MCPHubAppProps = {}) => {
await load();
return;
}
if (res.error === 'TIER_INSUFFICIENT') {
// The adapter's global 403 handler routes this through the
// UpgradeModal; the explicit dispatch keeps the house pattern (and
// the unit-testable contract) — the event is idempotent.
window.dispatchEvent(new CustomEvent('waggle:tier-insufficient', {
detail: {
required: res.required ?? 'TEAMS',
actual: res.actual ?? 'FREE',
message: `Installing MCP servers needs the Team plan or an active trial.`,
},
}));
return;
}
if (res.requiresApproval) {
// Cover BOTH block envelopes: installer-level (scanResult.overall_severity)
// and route-level (top-level severity) — a route-level CRITICAL must

View File

@@ -8,8 +8,8 @@
* Add / Connect / Enable through the shared install store, so installing in
* ANY view reflects in ALL (the count bar + inline chat). Security is
* preserved server-side — a SecurityGate block surfaces as a destructive
* toast, tier routes to Upgrade — and the destructive Remove direction keeps
* its ApprovalModal consequence dialog. The Audit tab is the C18 shared feed.
* toast — and the destructive Remove direction keeps its ApprovalModal
* consequence dialog. The Audit tab is the C18 shared feed.
*/
import { useState, useEffect, useCallback, useRef } from 'react';
import { Store, Loader2, Package, Sparkles } from 'lucide-react';

View File

@@ -1,99 +0,0 @@
/**
* PaymentSuccessApp — warm-Hive PR7a Billing (design screen 14 "Success" state).
*
* The post-Stripe-Checkout landing (`/payment-success?session_id=…`, set by
* `checkout.ts:42`). `useBilling` auto-detects `?session_id=` on mount and calls
* POST /api/stripe/sync (payment-gated) → flips the tier. This screen renders the
* confirmation OFF THE SYNCED TIER only.
*
* No-fabrication (recon 04 §3 / plan F5): the design's receipt block (receipt #,
* "Trial ends Jun 28", "Then $19/mo", "Emailed →") has NO data source — `/sync`
* returns only `{ tier, customerId }`. Those rows are GATED OFF here; we never invent
* a charge amount, a trial-end date, or a receipt link.
*/
import { useNavigate } from 'react-router-dom';
import { Check, Loader2, AlertCircle } from 'lucide-react';
import { useBilling } from '@/hooks/useBilling';
const TIER_HEADLINE: Record<string, string> = {
// PRO retained for legacy checkout sessions that predate the Solo/Team split.
PRO: 'Legacy Pro',
TEAMS: 'Team',
ENTERPRISE: 'Enterprise',
};
export default function PaymentSuccessApp() {
const navigate = useNavigate();
const billing = useBilling();
const isPaid = billing.tier === 'PRO' || billing.tier === 'TEAMS' || billing.tier === 'ENTERPRISE';
return (
<div className="h-full overflow-auto">
<div className="max-w-[520px] mx-auto px-8 py-[70px] text-center">
{/* Syncing — the real payment confirmation is in flight */}
{billing.syncing ? (
<div className="flex flex-col items-center gap-4" data-testid="payment-success-syncing">
<Loader2 className="w-9 h-9 animate-spin text-honey" />
<p className="text-[15px] text-[var(--text-2)]">Confirming your payment…</p>
</div>
) : billing.error ? (
/* Honest failure — never fake a success (F10/F5) */
<div className="flex flex-col items-center gap-4" data-testid="payment-success-error">
<div className="w-[78px] h-[78px] rounded-full grid place-items-center bg-destructive/10 border border-destructive/30">
<AlertCircle className="w-9 h-9 text-destructive" strokeWidth={2.2} />
</div>
<h1 className="text-[24px] font-[650] tracking-[-0.02em] text-foreground">We couldn’t confirm the payment</h1>
<p className="text-[14px] text-[var(--text-muted)] max-w-[42ch]">{billing.error}</p>
<button
onClick={() => navigate('/settings?tab=billing')}
className="mt-2 px-[22px] py-3 rounded-[11px] text-[14.5px] font-[650] bg-[var(--surface)] text-[var(--text-2)] border border-[var(--line-strong)] hover:border-[var(--honey-line)] hover:text-honey transition-colors"
>
Back to plans
</button>
</div>
) : isPaid ? (
/* Confirmation off the SYNCED tier — no receipt rows (F5) */
<>
<div className="w-[78px] h-[78px] rounded-full mx-auto mb-6 grid place-items-center bg-[var(--healthy-wash)] border border-[color:color-mix(in_srgb,var(--healthy)_40%,transparent)]">
<Check className="w-9 h-9 text-[var(--healthy)]" strokeWidth={2.2} />
</div>
<h1 className="text-[28px] font-[650] tracking-[-0.02em] mb-3 text-foreground">
You’re <span className="text-honey">{TIER_HEADLINE[billing.tier] ?? billing.tier}.</span>
</h1>
<p className="text-[15px] text-[var(--text-2)] leading-relaxed mx-auto mb-7 max-w-[42ch]">
Your hive just leveled up — <b className="text-foreground">shared team memory, cross-device sync, and governance</b> are live.
</p>
<div className="inline-flex gap-2.5">
<button
onClick={() => navigate('/home')}
className="px-[22px] py-3 rounded-[11px] text-[14.5px] font-[650] bg-primary text-primary-foreground hover:bg-[var(--honey-bright)] transition-colors"
>
Start using {TIER_HEADLINE[billing.tier] ?? billing.tier} →
</button>
<button
onClick={() => navigate('/settings?tab=billing')}
className="px-[22px] py-3 rounded-[11px] text-[14.5px] font-[650] bg-[var(--surface)] text-[var(--text-2)] border border-[var(--line-strong)] hover:border-[var(--honey-line)] hover:text-honey transition-colors"
>
Manage billing
</button>
</div>
</>
) : (
/* Synced but not on a paid tier (cancelled / unpaid) — honest, no fake success */
<div className="flex flex-col items-center gap-4" data-testid="payment-success-unpaid">
<h1 className="text-[24px] font-[650] tracking-[-0.02em] text-foreground">Nothing to confirm</h1>
<p className="text-[14px] text-[var(--text-muted)] max-w-[42ch]">
We didn’t detect a completed checkout. If you just paid, give it a moment and refresh.
</p>
<button
onClick={() => navigate('/settings?tab=billing')}
className="mt-2 px-[22px] py-3 rounded-[11px] text-[14.5px] font-[650] bg-[var(--surface)] text-[var(--text-2)] border border-[var(--line-strong)] hover:border-[var(--honey-line)] hover:text-honey transition-colors"
>
Back to plans
</button>
</div>
)}
</div>
</div>
);
}

View File

@@ -1,15 +1,11 @@
import { useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import {
Cpu, Shield, Palette, Save, Loader2, Users, Database,
Download, Upload, Link2, Building, Wrench, DollarSign, Key, Lock, BarChart3, Trash2,
Cpu, Shield, Palette, Save, Loader2, Database,
Download, Upload, Wrench, DollarSign, Key, Lock, BarChart3, Trash2,
RotateCcw, GraduationCap, HelpCircle, AlertTriangle, MessageCircle,
} from 'lucide-react';
import PlanCards from '@/components/os/billing/PlanCards';
import { useToast } from '@/hooks/use-toast';
import { useBilling } from '@/hooks/useBilling';
import { parseTier, tierSatisfies, TIER_LABELS, type Tier } from '@waggle/shared';
import LockedFeature from '@/components/os/LockedFeature';
import { adapter } from '@/lib/adapter';
import { Input } from '@/components/ui/input';
import { HintTooltip } from '@/components/ui/hint-tooltip';
@@ -35,13 +31,12 @@ import { ModelGate } from '@/components/os/model-gate/ModelGate';
import EraseDataDialog from '@/components/os/overlays/EraseDataDialog';
import TelegramDigestCard from '@/components/os/settings/TelegramDigestCard';
import ChannelsSettings from '@/components/os/settings/ChannelsSettings';
import CoverageCompassCard from '@/components/os/settings/CoverageCompassCard';
import BrowserCompanionSettings from '@/components/os/settings/BrowserCompanionSettings';
import { AVAILABLE_SHAPES, useSelectedShape, type PromptShape } from '@/lib/shape-selection';
import { SectionLabel } from '@/components/os/warm';
import { ApprovalModal, type ApprovalRequest } from '@/components/ui/approval-modal';
type SettingsTab = 'general' | 'models' | 'billing' | 'permissions' | 'channels' | 'team' | 'backup' | 'enterprise' | 'advanced';
type SettingsTab = 'general' | 'models' | 'permissions' | 'channels' | 'backup' | 'advanced';
type SettingsApproval =
| { kind: 'clear-telemetry' }
| { kind: 'restore-backup'; file: File };
@@ -50,12 +45,9 @@ type BackupStatus = { tone: 'success' | 'error'; message: string };
const tabs: { id: SettingsTab; label: string; icon: React.ElementType }[] = [
{ id: 'general', label: 'General', icon: Palette },
{ id: 'models', label: 'Models', icon: Cpu },
{ id: 'billing', label: 'Plan', icon: DollarSign },
{ id: 'permissions', label: 'Permissions', icon: Shield },
{ id: 'channels', label: 'Channels', icon: MessageCircle },
{ id: 'team', label: 'Team', icon: Users },
{ id: 'backup', label: 'Backup', icon: Database },
{ id: 'enterprise', label: 'Enterprise', icon: Building },
{ id: 'advanced', label: 'Advanced', icon: Wrench },
];
@@ -118,13 +110,11 @@ const SettingsApp = () => {
}
}, [activeTab]);
// PR7a/D12: `?tab=` deep-link reader. Upgrade entry points route to
// `/settings?tab=billing`; this also fixes the pre-existing `?tab=backup`
// deep-link (routes.ts:52) that opened Models because there was no reader.
// Snaps to a KNOWN tab, respecting the tier filter (e.g. an Essential user
// deep-linked to `advanced` falls back to general, never a half-shipped tab).
// PR7a/D12: `?tab=` deep-link reader. This also fixes the pre-existing
// `?tab=backup` deep-link (routes.ts:52) that opened Models because there was
// no reader. Snaps to a KNOWN tab, respecting the tier filter (e.g. an Essential
// user deep-linked to `advanced` falls back to general, never a half-shipped tab).
const [searchParams] = useSearchParams();
const checkoutCancelled = searchParams.get('checkout') === 'cancelled';
useEffect(() => {
const tabParam = searchParams.get('tab');
if (!tabParam || !tabs.some(t => t.id === tabParam)) return;
@@ -135,20 +125,6 @@ const SettingsApp = () => {
const { toast } = useToast();
const [showWizardReplayConfirm, setShowWizardReplayConfirm] = useState(false);
// Billing
const billing = useBilling();
// Tier gating — canonical resolution off the billing tier (never null: a
// legacy/unknown value falls back to Solo/FREE, never locking a user out).
const tier: Tier = parseTier(billing.tier) ?? 'FREE';
const isTeamLocked = !tierSatisfies(tier, 'TEAMS');
const isEnterpriseLocked = !tierSatisfies(tier, 'ENTERPRISE');
const LOCKED_TABS: Partial<Record<SettingsTab, { feature: string; label: string; prompt: string }>> = {
...(isTeamLocked ? { team: { feature: 'team', label: 'Team Management', prompt: 'Upgrade to Team for shared workspaces and governance' } } : {}),
...(isEnterpriseLocked ? { enterprise: { feature: 'enterprise', label: 'Enterprise Features', prompt: 'Enterprise feature — contact sales for audit trail, compliance, and governance' } } : {}),
};
// P4: permissions state. `defaultAutonomy` replaces the old yoloMode
// binary — it's the inherited level new chat windows start at. Per-window
// overrides in Chat's AutonomyPicker always beat this.
@@ -161,16 +137,6 @@ const SettingsApp = () => {
// focus-visible, testable confirm row.
const [pendingYolo, setPendingYolo] = useState(false);
// Team state
const [teamUrl, setTeamUrl] = useState('');
const [teamToken, setTeamToken] = useState('');
const [teamConnected, setTeamConnected] = useState(false);
const [teamConnecting, setTeamConnecting] = useState(false);
// KVARK state
const [kvarkUrl, setKvarkUrl] = useState('');
const [kvarkToken, setKvarkToken] = useState('');
// M2-7: Telemetry state
const [telemetryEnabled, setTelemetryEnabled] = useState(false);
// Phase 4.1: GDPR Art. 17 erasure flow. Visible at all tiers — erasure
@@ -198,7 +164,7 @@ const SettingsApp = () => {
// Load settings
useEffect(() => {
adapter.getSettings().then((s: { defaultModel?: string; model?: string; dailyBudget?: number; tier?: string; fallbackModel?: string; budgetModel?: string; budgetThreshold?: number }) => {
adapter.getSettings().then((s: { defaultModel?: string; model?: string; dailyBudget?: number; fallbackModel?: string; budgetModel?: string; budgetThreshold?: number }) => {
setDefaultModel(s.defaultModel ?? s.model ?? '');
setFallbackModel(s.fallbackModel ?? null);
setBudgetModel(s.budgetModel ?? null);
@@ -213,11 +179,9 @@ const SettingsApp = () => {
setExternalGates(p.externalGates);
}).catch(() => {});
adapter.getTeamStatus().then(s => setTeamConnected(s.connected)).catch(() => {});
// M2-7: Load telemetry status. P7/D15 B5: this was the ONE loader missing a
// .catch — a getTelemetryStatus rejection became an unhandled promise
// rejection (its three siblings above all swallow). Match the local pattern.
// rejection (its siblings above all swallow). Match the local pattern.
adapter.getTelemetryStatus().then(s => {
setTelemetryEnabled(s.enabled);
setTelemetryCount(s.totalEvents);
@@ -347,7 +311,6 @@ const SettingsApp = () => {
<div className="w-full shrink-0 border-b border-border/50 sm:w-36 sm:border-b-0 sm:border-r flex flex-col">
<div className="grid grid-cols-3 gap-1 p-2 sm:block sm:flex-1 sm:space-y-0.5" role="tablist" aria-label="Settings sections">
{visibleTabs.map(tab => {
const locked = LOCKED_TABS[tab.id];
return (
<button
key={tab.id}
@@ -368,7 +331,6 @@ const SettingsApp = () => {
>
<tab.icon className="h-3.5 w-3.5 shrink-0" />
<span className="min-w-0 truncate">{tab.label}</span>
{locked && <Lock className="ml-auto h-3 w-3 shrink-0 text-muted-foreground/50" />}
</button>
);
})}
@@ -429,33 +391,13 @@ const SettingsApp = () => {
<div className="space-y-5">
<h3 className="text-sm font-display font-semibold text-foreground">General</h3>
{/* Tier. P1b D3-4: single-sourced from the resolved billing state
(was a separate getSettings-fed copy that defaulted to 'FREE'
on failure and could disagree with the Billing tab). Unresolved
renders a neutral placeholder, never 'FREE plan' as fact. */}
<div className="p-3 rounded-xl bg-secondary/30 border border-border/30">
<div className="flex items-center justify-between">
<div>
<p className="text-xs font-display font-medium text-foreground">Tier</p>
<p className="text-[11px] text-muted-foreground">
{billing.tierResolved ? `${TIER_LABELS[tier]} plan` : 'Confirming plan…'}
</p>
</div>
<span className="px-2 py-0.5 rounded-full text-[11px] font-display bg-primary/20 text-honey">
{billing.tierResolved ? TIER_LABELS[tier] : '…'}
</span>
</div>
</div>
{/* PR5 D10 — local-first reassurance + the dock/plan distinction. The
disclosure selector that used to live here is now the "Show"
control in the settings content header (R10; D6/Wave P); QW-5's
"dock tier ≠ billing plan" note is preserved here so the
distinction isn't lost. */}
{/* PR5 D10 — local-first reassurance. The disclosure selector that
used to live here is now the "Show" control in the settings
content header (R10; D6/Wave P). */}
<div className="p-3 rounded-xl bg-secondary/30 border border-border/30">
<p className="text-xs font-display font-medium text-foreground mb-1">Local-first</p>
<p className="text-[11px] text-muted-foreground leading-relaxed">
Waggle runs on your machine — your memory and data stay local, always. The <strong className="text-foreground">Show</strong> control (top-right of Settings) sets how much of the app and these settings you see; it’s independent of your Solo/Team plan, and every app stays reachable via Ctrl+K.
Waggle runs on your machine — your memory and data stay local, always. The <strong className="text-foreground">Show</strong> control (top-right of Settings) sets how much of the app and these settings you see; every app stays reachable via Ctrl+K.
</p>
</div>
@@ -594,7 +536,7 @@ const SettingsApp = () => {
}}
/>
<EmbeddingRoutingCard providers={providers} tier={tier} />
<EmbeddingRoutingCard providers={providers} />
<SectionLabel>Model Configuration</SectionLabel>
@@ -680,150 +622,6 @@ const SettingsApp = () => {
</div>
)}
{/* ═══ BILLING (PR7a — screen 14, themed over the REAL useBilling→Stripe flow) ═══ */}
{activeTab === 'billing' && (
<div className="space-y-6">
<div>
<h3 className="text-sm font-display font-semibold text-foreground">Plan & Subscription</h3>
{/* §14 load-bearing positioning copy — honestly satisfiable under the
ratified Option A (BYO-key + flat subscription): Teams unlock
scale, never feature-count paywalls on memory. */}
<p className="text-[11px] text-[var(--text-muted)] mt-1">
Memory is free forever. You only pay for scale — no feature-count games.
</p>
</div>
{/* F4 from the 2026-05-28 addictiveness audit — visible value-prop
framing so users see they're replacing 7-ish subscription tools,
not adding an 8th. */}
{checkoutCancelled && (
<div className="flex items-start gap-3 rounded-[14px] border border-[var(--line-soft)] bg-[var(--surface-2)] p-4">
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-honey" aria-hidden="true" />
<div>
<p className="text-[13px] font-display font-semibold text-foreground">Checkout was cancelled</p>
<p className="mt-1 text-[11px] leading-relaxed text-[var(--text-muted)]">
No charge was made. You can review the Team plan here or keep using Solo.
</p>
</div>
</div>
)}
<CoverageCompassCard />
{/* Current tier badge. F7: while the tier is unresolved (boot race /
sidecar down) render an explicit unresolved state — NEVER the
default 'FREE' as fact. */}
{!billing.tierResolved ? (
<div className="p-4 rounded-[14px] bg-[var(--surface-2)] border border-[var(--line-soft)]" data-testid="billing-tier-unresolved">
<div className="flex items-center justify-between">
<div>
<p className="text-xs font-display font-medium text-foreground">Current Plan</p>
<p className="text-[11px] text-[var(--text-muted)] mt-0.5">
{billing.error ? 'Couldn’t reach the server to confirm your plan — retrying automatically.' : 'Confirming your plan…'}
</p>
</div>
<span className="px-3 py-1 rounded-full text-xs font-display font-semibold bg-muted text-muted-foreground">…</span>
</div>
</div>
) : (
<div className="p-4 rounded-[14px] bg-[var(--surface)] border border-[var(--line-soft)]">
<div className="flex items-center justify-between">
<div>
<p className="text-xs font-display font-medium text-foreground">Current Plan</p>
<p className="text-[11px] text-[var(--text-muted)] mt-0.5">
{billing.tier === 'FREE' && 'Solo — every individual feature, free forever'}
{billing.tier === 'TRIAL' && 'Trial — 15 days of Team features, then Solo'}
{billing.tier === 'TEAMS' && '$49/mo per seat — shared workspaces, WaggleDance, governance'}
{billing.tier === 'ENTERPRISE' && 'Enterprise — KVARK sovereign deployment'}
</p>
</div>
<span className={`px-3 py-1 rounded-full text-xs font-display font-semibold ${
billing.tier === 'FREE' ? 'bg-muted text-muted-foreground' :
billing.tier === 'TRIAL' ? 'bg-[var(--honey-wash)] text-honey' :
billing.tier === 'TEAMS' ? 'bg-[var(--intel-wash)] text-[var(--intel)]' :
'bg-[var(--work-wash)] text-[var(--work)]'
}`}>
{TIER_LABELS[tier]}
</span>
</div>
</div>
)}
{/* Error display (F8 — honest, e.g. STRIPE_NOT_CONFIGURED 503; never a fake subscribe) */}
{billing.error && (
<div className="p-3 rounded-lg bg-destructive/10 border border-destructive/20">
<p className="text-[11px] text-destructive">{billing.error}</p>
</div>
)}
{/* Syncing indicator */}
{billing.syncing && (
<div className="flex items-center gap-2 p-3 rounded-lg bg-primary/10 border border-primary/20">
<Loader2 className="w-3 h-3 animate-spin text-honey" />
<p className="text-[11px] text-honey">Confirming your payment...</p>
</div>
)}
{/* Plans grid — tiers that still have an upgrade path (FREE/TRIAL, plus legacy PRO).
Choosing a plan hands off to hosted Stripe Checkout (D5); the
Monthly/Annual toggle resolves the REAL annual price (D8/F9), not
a cosmetic client discount. Only on a RESOLVED tier (F7). */}
{billing.tierResolved && (billing.tier === 'FREE' || billing.tier === 'TRIAL' || billing.tier === 'PRO') && (
<PlanCards
currentTier={billing.tier}
onChoose={(tier, period) => billing.startCheckout(tier, period)}
disabled={!billing.checkoutAvailable}
/>
)}
{/* Manage — paid tiers. Hosted Stripe Customer Portal launchpad (D6).
The mock's invoice list / "VISA ···4242" / next-charge date are
GATED OFF (F2/F3/F4) — there is no data source; the Portal is the
real surface for payment method, invoices, plan change, cancel. */}
{billing.tierResolved && (billing.tier === 'PRO' || billing.tier === 'TEAMS') && (
<div className="p-5 rounded-[18px] bg-[var(--surface)] border border-[var(--honey-line)]">
<div className="flex items-center justify-between gap-3">
<div>
<p className="text-[15px] font-display font-semibold text-foreground">Waggle {billing.tier === 'PRO' ? 'Pro (legacy)' : 'Team'}</p>
<p className="text-[12px] text-[var(--text-muted)] mt-0.5">Subscription managed securely via Stripe.</p>
</div>
<span className="text-[11.5px] font-[650] text-honey bg-[var(--honey-wash)] border border-[var(--honey-line)] px-3 py-1.5 rounded-full whitespace-nowrap">● Active</span>
</div>
<div className="mt-4 pt-4 border-t border-[var(--line-soft)]">
<button
onClick={() => billing.openPortal()}
className="flex items-center gap-1.5 px-3.5 py-2 text-[13px] font-[650] rounded-[10px] bg-[var(--surface-2)] text-[var(--text-2)] border border-[var(--line-strong)] hover:border-[var(--honey-line)] hover:text-honey transition-colors"
>
<DollarSign className="w-3.5 h-3.5" />
Manage subscription
</button>
<p className="text-[11px] text-[var(--text-muted)] mt-2">
Update payment method, view invoices, switch to annual, or cancel — all via the Stripe customer portal.
</p>
</div>
</div>
)}
{/* Enterprise CTA — the KVARK funnel. Only on a RESOLVED tier (F7). */}
{billing.tierResolved && billing.tier !== 'ENTERPRISE' && (
<div className="p-4 rounded-[14px] bg-[var(--work-wash)] border border-[var(--line-soft)]">
<p className="text-xs font-display font-medium text-[var(--work)]">Enterprise</p>
<p className="text-[11px] text-[var(--text-muted)] mt-1">
Need sovereign deployment, audit trail, and KVARK integration?
</p>
<a
href="https://www.kvark.ai"
target="_blank"
rel="noopener noreferrer"
className="inline-block mt-2 text-[11px] text-[var(--work)] hover:text-honey underline"
>
Contact sales at kvark.ai
</a>
</div>
)}
</div>
)}
{/* ═══ PERMISSIONS ═══ */}
{activeTab === 'permissions' && (
<div className="space-y-4">
@@ -949,56 +747,6 @@ const SettingsApp = () => {
{/* ═══ CHANNELS ═══ */}
{activeTab === 'channels' && <ChannelsSettings />}
{/* ═══ TEAM ═══ */}
{activeTab === 'team' && LOCKED_TABS.team && (
<LockedFeature featureName={LOCKED_TABS.team.label} upgradePrompt={LOCKED_TABS.team.prompt} />
)}
{activeTab === 'team' && !LOCKED_TABS.team && (
<div className="space-y-4">
<h3 className="text-sm font-display font-semibold text-foreground">Team Server</h3>
<div className="space-y-3">
<div className="flex items-center gap-2 mb-2">
<div className={`w-2 h-2 rounded-full ${teamConnected ? 'bg-emerald-400' : 'bg-muted-foreground'}`} />
<span className="text-xs text-muted-foreground">{teamConnected ? 'Connected' : 'Disconnected'}</span>
</div>
{!teamConnected && (
<div className="p-2 rounded-lg bg-amber-500/10 border border-amber-500/20">
<p className="text-[11px] text-amber-400">Connecting to a team server will share workspace data. Ensure you trust the server.</p>
</div>
)}
<div>
<label htmlFor="settings-team-url" className="text-xs text-muted-foreground block mb-1">Team Server URL</label>
<Input id="settings-team-url" name="teamServerUrl" type="url" autoComplete="url" spellCheck={false} value={teamUrl} onChange={e => setTeamUrl(e.target.value)} placeholder="https://team.waggle.ai"
className="w-full bg-muted/50 h-auto py-1.5" />
</div>
<div>
<label htmlFor="settings-team-token" className="text-xs text-muted-foreground block mb-1">Auth Token</label>
<Input id="settings-team-token" name="teamAuthToken" type="password" autoComplete="current-password" spellCheck={false} value={teamToken} onChange={e => setTeamToken(e.target.value)}
className="w-full bg-muted/50 h-auto py-1.5" />
</div>
<div className="flex gap-2">
{!teamConnected ? (
<button onClick={async () => {
setTeamConnecting(true);
try { await adapter.teamConnect(teamUrl, teamToken); setTeamConnected(true); } catch { /* ignore */ }
finally { setTeamConnecting(false); }
}} disabled={teamConnecting || !teamUrl}
className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-primary text-primary-foreground hover:bg-primary/80 disabled:opacity-50 transition-colors">
{teamConnecting ? <Loader2 className="w-3 h-3 animate-spin" /> : <Link2 className="w-3 h-3" />} Connect
</button>
) : (
<button onClick={async () => {
try { await adapter.teamDisconnect(); setTeamConnected(false); } catch { /* ignore */ }
}}
className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-destructive text-foreground hover:bg-destructive/80 transition-colors">
Disconnect
</button>
)}
</div>
</div>
</div>
)}
{/* ═══ BACKUP ═══ */}
{activeTab === 'backup' && (
<div className="space-y-4">
@@ -1070,33 +818,6 @@ const SettingsApp = () => {
</div>
)}
{/* ═══ ENTERPRISE ═══ */}
{activeTab === 'enterprise' && LOCKED_TABS.enterprise && (
<LockedFeature featureName={LOCKED_TABS.enterprise.label} upgradePrompt={LOCKED_TABS.enterprise.prompt} />
)}
{activeTab === 'enterprise' && !LOCKED_TABS.enterprise && (
<div className="space-y-4">
<h3 className="text-sm font-display font-semibold text-foreground">Enterprise (KVARK)</h3>
<p className="text-xs text-muted-foreground">Connect to KVARK for enterprise document retrieval, compliance, and governance features.</p>
<div className="space-y-3">
<div>
<label htmlFor="settings-kvark-url" className="text-xs text-muted-foreground block mb-1">KVARK Server URL</label>
<Input id="settings-kvark-url" name="kvarkServerUrl" type="url" autoComplete="url" spellCheck={false} value={kvarkUrl} onChange={e => setKvarkUrl(e.target.value)} placeholder="https://kvark.company.com"
className="w-full bg-muted/50 h-auto py-1.5" />
</div>
<div>
<label htmlFor="settings-kvark-token" className="text-xs text-muted-foreground block mb-1">API Token</label>
<Input id="settings-kvark-token" name="kvarkApiToken" type="password" autoComplete="current-password" spellCheck={false} value={kvarkToken} onChange={e => setKvarkToken(e.target.value)}
className="w-full bg-muted/50 h-auto py-1.5" />
</div>
<button disabled className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-secondary text-muted-foreground opacity-50 cursor-not-allowed">
<Building className="w-3 h-3" /> Test Connection
</button>
<p className="text-[11px] text-muted-foreground">Requires Enterprise tier. Contact sales for access.</p>
</div>
</div>
)}
{/* ═══ ADVANCED ═══ */}
{activeTab === 'advanced' && (
<div className="space-y-4">

View File

@@ -49,16 +49,16 @@ const TelemetryApp = () => {
const load = useCallback(async () => {
try {
// /api/cost/summary is free for all tiers (P22) and carries byModel + budget.
// /api/cost/by-workspace is TEAMS-gated; tolerate its absence (object OR []).
// /api/cost/summary carries byModel + budget; /api/cost/by-workspace the
// per-workspace split. Tolerate a by-workspace failure (object OR []).
const [summaryRes, costRes, statsRes] = await Promise.all([
adapter.fetch('/api/cost/summary').then(r => r.json()).catch(() => null),
adapter.fetch('/api/cost/by-workspace').then(r => r.json()).catch(() => null),
adapter.fetch('/api/events/stats').then(r => r.json()).catch(() => ({})),
]);
// by-workspace returns { workspaces, totalCost } (TEAMS) — older callers
// expected a bare array; accept both, default to empty when gated off.
// by-workspace returns { workspaces, totalCost } — older callers
// expected a bare array; accept both, default to empty on failure.
const wsRows: Array<Record<string, unknown>> = Array.isArray(costRes)
? costRes
: Array.isArray(costRes?.workspaces) ? costRes.workspaces : [];
@@ -267,7 +267,7 @@ const TelemetryApp = () => {
</div>
)}
{/* By workspace (TEAMS) */}
{/* By workspace */}
{data.byWorkspace.length > 0 && (
<div>
<h2 className="text-[11px] font-display font-semibold text-[var(--text-muted)] uppercase tracking-wide mb-2">By workspace</h2>

View File

@@ -21,7 +21,7 @@
* └──────────────────────────────────────┴───────────────────────┘
*
* Reuse: consumes adapter.getWorkspaceState / getWorkspaceContext /
* getWorkspaceActivity / getTeamMembers (the Phase-1 contract surface) and
* getWorkspaceActivity (the Phase-1 contract surface) and
* useRoomState for the live agents-running indicator. Other tabs (Chat,
* Memory, Timeline, Settings, Research, Artifacts) are integrator-embedded;
* this shell owns the header, tab routing, Overview canvas, and right panel.
@@ -34,14 +34,12 @@ import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { motion, useReducedMotion } from 'framer-motion';
import {
LayoutGrid, MessageSquare, FileBox, Brain,
Users, WifiOff, ShieldAlert, ChevronRight,
WifiOff, ShieldAlert, ChevronRight,
FileText, SearchX, RefreshCw,
} from 'lucide-react';
import { tierSatisfies, TIER_LABELS } from '@waggle/shared';
import { adapter } from '@/lib/adapter';
import { SPRING } from '@/lib/motion/tokens';
import { workspaceHeroAvatarId, workspaceHeroNameId, heroMorphEnabled } from '@/lib/motion/hero-morph';
import { useShell } from '@/providers/ShellContext';
import { useRoomState } from '@/hooks/useRoomState';
import { useRevalidateOnError } from '@/hooks/useRevalidateOnError';
import MemoryCenterTab from './memory/MemoryCenterTab';
@@ -60,13 +58,13 @@ import type {
// The 8 PRD §12.2 tabs (Settings included). The shell renders Overview
// itself; the other tabs are embedded by the integrator (Chat / Memory /
// Timeline / Settings have hosts; Research / Artifacts are interim panels).
// Warm-Hive (SCREENS §03): the calm 6-tab bar. `tasks` stays a valid id (so
// Warm-Hive (SCREENS §03): the calm 5-tab bar. `tasks` stays a valid id (so
// /workspaces/:id/tasks still deep-links the full TasksTab + the Overview "Up
// next" card can route to it) but is NOT shown in the bar — Research / Timeline
// / Settings are dropped (their URLs fall back to Overview, see WorkspaceRoute).
export type WorkspaceTabId =
| 'overview' | 'chat' | 'memory' | 'artifacts'
| 'files' | 'team' | 'tasks';
| 'files' | 'tasks';
interface WorkspaceTabDef {
id: WorkspaceTabId;
@@ -80,17 +78,8 @@ const TABS: readonly WorkspaceTabDef[] = [
{ id: 'memory', label: 'Memory', icon: Brain },
{ id: 'artifacts', label: 'Artifacts', icon: FileBox },
{ id: 'files', label: 'Files', icon: FileText },
{ id: 'team', label: 'Team', icon: Users },
] as const;
// ── Member view-model (from adapter.getTeamMembers) ──────────────────────
interface WorkspaceMember {
id: string;
name: string;
status: string;
avatar?: string;
}
interface WorkspaceDesktopAppProps {
workspaceId: string;
workspaceName: string;
@@ -121,13 +110,6 @@ interface WorkspaceDesktopAppProps {
// ── Small presentational helpers ─────────────────────────────────────────
function initialsOf(name: string): string {
const parts = name.trim().split(/\s+/).filter(Boolean);
if (parts.length === 0) return '?';
if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}
function relativeTime(iso?: string): string {
if (!iso) return '';
const t = Date.parse(iso);
@@ -268,31 +250,12 @@ function UpNextCard({ state, onOpenTab }: { state: WorkspaceStateView | null; on
);
}
function TeamCard({ members }: { members: WorkspaceMember[] }) {
if (members.length === 0) return null;
return (
<div className="rounded-[18px] border border-[var(--line-soft)] bg-card p-4">
<SectionLabel className="mb-3">Team</SectionLabel>
<ul className="space-y-2.5">
{members.slice(0, 6).map((m) => (
<li key={m.id} className="flex items-center gap-2.5 text-[13px]">
<span className="grid h-7 w-7 shrink-0 place-items-center rounded-full bg-[var(--surface-3)] font-mono text-[11px] text-[var(--text-2)]">{initialsOf(m.name)}</span>
<span className="flex-1 truncate text-[var(--text)]">{m.name}</span>
{m.status && <span className="font-mono text-[11px] capitalize text-[var(--text-dim)]">{m.status}</span>}
</li>
))}
</ul>
</div>
);
}
function OverviewTab({
ctx, state, artifacts, members, agentsRunning, onOpenTab,
ctx, state, artifacts, agentsRunning, onOpenTab,
}: {
ctx: WorkspaceContext | null;
state: WorkspaceStateView | null;
artifacts: ArtifactRow[];
members: WorkspaceMember[];
agentsRunning: number;
onOpenTab: (tab: WorkspaceTabId) => void;
}) {
@@ -313,7 +276,6 @@ function OverviewTab({
<div className="space-y-4">
<StatusCard ctx={ctx} agentsRunning={agentsRunning} />
<UpNextCard state={state} onOpenTab={onOpenTab} />
<TeamCard members={members} />
</div>
</div>
);
@@ -358,7 +320,6 @@ const WorkspaceDesktopApp = ({
const [ctx, setCtx] = useState<WorkspaceContext | null>(null);
const [state, setState] = useState<WorkspaceStateView | null>(null);
const [activity, setActivity] = useState<WorkspaceActivityEvent[]>([]);
const [members, setMembers] = useState<WorkspaceMember[]>([]);
const [artifacts, setArtifacts] = useState<ArtifactRow[]>([]);
const [loading, setLoading] = useState(true);
// Distinguish a hard fetch failure (offline) from a permission denial and
@@ -374,12 +335,6 @@ const WorkspaceDesktopApp = ({
const retry = useCallback(() => setReloadKey((k) => k + 1), []);
useRevalidateOnError(errorKind === 'offline', retry);
// Team tab tier gate: Solo users see the upsell, Team users the real roster.
// `?? 'FREE'` keeps existing useShell test mocks (which don't stub billingTier)
// green and fail-closed to the upsell.
const { billingTier, tierResolved } = useShell();
const isTeam = tierSatisfies(billingTier ?? 'FREE', 'TEAMS');
// Live agents-running indicator for THIS workspace (reuse Room SSE state).
const { workspaceMap } = useRoomState();
const agentsRunning = useMemo(
@@ -460,7 +415,7 @@ const WorkspaceDesktopApp = ({
return;
}
// State / activity / members / artifacts are best-effort — each one
// State / activity / artifacts are best-effort — each one
// empties gracefully without taking down the screen.
try {
const s = await adapter.getWorkspaceState(workspaceId);
@@ -472,14 +427,6 @@ const WorkspaceDesktopApp = ({
if (!cancelled) setActivity(Array.isArray(a?.events) ? a.events : []);
} catch { if (!cancelled) setActivity([]); }
// getTeamMembers() returns the GLOBAL team roster, not a per-workspace
// membership list — the UI is labelled "Team members" accordingly.
// TODO(Phase 5/S10): workspace-scoped members endpoint.
try {
const m = await adapter.getTeamMembers();
if (!cancelled) setMembers(Array.isArray(m) ? m : []);
} catch { if (!cancelled) setMembers([]); }
// Interim "artifacts" = the workspace file registry (S05 owns the real
// Artifact entity; until then we surface files/documents read-only).
try {
@@ -521,7 +468,6 @@ const WorkspaceDesktopApp = ({
: tab.id === 'memory' ? ctx?.stats?.memoryCount
: tab.id === 'artifacts' ? (artifacts.length || undefined)
: tab.id === 'files' ? ctx?.stats?.fileCount
: tab.id === 'team' ? (members.length || undefined)
: undefined;
return (
<button
@@ -792,7 +738,6 @@ const WorkspaceDesktopApp = ({
ctx={ctx}
state={state}
artifacts={artifacts}
members={members}
agentsRunning={agentsRunning}
onOpenTab={setActiveTab}
/>
@@ -920,50 +865,6 @@ const WorkspaceDesktopApp = ({
)}
</>
)}
{/* Team — Solo users see a Team-tier upsell; Team users the roster.
While the tier is unresolved, render the neutral roster so a real
Team user never flashes the upsell during the getTier round-trip. */}
{activeTab === 'team' && (
<div className="h-full overflow-auto p-5" data-testid="ws-team-tab">
{tierResolved && !isTeam ? (
<div className="flex h-full flex-col items-center justify-center text-center p-8" data-testid="ws-team-upsell">
<Users className="mb-3 h-10 w-10 text-violet-400/60" />
<p className="text-sm font-display text-foreground">Invite your team</p>
<p className="mt-1 max-w-sm text-[11px] text-muted-foreground">
Shared memory, WaggleDance multi-agent coordination, and governance —
turn this workspace into a shared surface for your whole team.
</p>
<button
type="button"
onClick={() => window.dispatchEvent(new CustomEvent('waggle:tier-insufficient', {
detail: {
required: 'TEAMS',
actual: billingTier ?? 'FREE',
message: 'Team plan required for shared workspaces and collaboration.',
},
}))}
className="mt-4 rounded-xl border border-violet-400/20 bg-violet-400/10 px-4 py-2 text-xs text-violet-300 transition-colors hover:bg-violet-400/20"
data-testid="ws-team-upgrade"
>
Upgrade to {TIER_LABELS.TEAMS} — $49/seat
</button>
</div>
) : members.length === 0 ? (
<TabPlaceholder icon={Users} title="Just you for now" body="Team members with access to this workspace will appear here." />
) : (
<ul className="space-y-2">
{members.map(m => (
<li key={m.id} className="flex items-center gap-3 rounded-[14px] border border-[var(--line-soft)] bg-card px-4 py-3">
<span className="grid h-8 w-8 shrink-0 place-items-center rounded-full bg-[var(--surface-3)] font-mono text-[12px] text-[var(--text-2)]">{initialsOf(m.name)}</span>
<span className="flex-1 truncate text-[14px] text-[var(--text)]">{m.name}</span>
{m.status && <span className="shrink-0 font-mono text-[11px] capitalize text-[var(--text-dim)]">{m.status}</span>}
</li>
))}
</ul>
)}
</div>
)}
</section>
</div>
</div>

View File

@@ -1,9 +1,8 @@
/**
* AddCustomMcpForm — the S08 Custom tab (UX-Refactor Phase 4B). Registers an
* arbitrary stdio MCP server via POST /api/mcps (tier-gated server-side, B5):
* arbitrary stdio MCP server via POST /api/mcps:
* `{ name, command, args[], env{}, workspaceId? }`. 400 (validation /
* injection-scan) and 409 (duplicate) render inline; the tier 403 routes
* through the global UpgradeModal handler.
* injection-scan) and 409 (duplicate) render inline.
*/
import { useEffect, useState } from 'react';
import { Loader2, Plus } from 'lucide-react';
@@ -62,7 +61,7 @@ const AddCustomMcpForm = ({ onAdded }: AddCustomMcpFormProps) => {
if (res.id) {
setName(''); setCommand(''); setArgsText(''); setEnvText(''); setWorkspaceId('');
onAdded(res.id);
} else if (res.error && res.error !== 'TIER_INSUFFICIENT') {
} else if (res.error) {
// 400 validation / injection-scan rejection or 409 duplicate.
setError(res.error);
}
@@ -78,8 +77,7 @@ const AddCustomMcpForm = ({ onAdded }: AddCustomMcpFormProps) => {
<div>
<h3 className="text-sm font-display font-semibold text-foreground">Add a custom MCP server</h3>
<p className="text-[11px] text-muted-foreground">
Registers a local stdio server (command + args). Teams governance can manage shared use;
Solo can run local servers on this device.
Registers a local stdio server (command + args) that runs on this device.
</p>
</div>

View File

@@ -28,8 +28,6 @@ import { adapter } from '@/lib/adapter';
interface SkillBuilderProps {
onCreated: (name: string) => void;
onCancel: () => void;
/** Shared 403→UpgradeModal routing (server gate may land later). */
onTierError: (err: unknown, name: string) => boolean;
}
/** Backend SKILL_FAMILIES 7-set (skills.ts) — NOT the narrower SkillPack union. */
@@ -57,7 +55,7 @@ export function appendIoSections(content: string, inputs: string[], outputs: str
return `${content.trimEnd()}\n${section('Inputs', inputs)}${section('Outputs', outputs)}`;
}
const SkillBuilder = ({ onCreated, onCancel, onTierError }: SkillBuilderProps) => {
const SkillBuilder = ({ onCreated, onCancel }: SkillBuilderProps) => {
const [step, setStep] = useState(0);
// Identity
const [name, setName] = useState('');
@@ -138,9 +136,7 @@ const SkillBuilder = ({ onCreated, onCancel, onTierError }: SkillBuilderProps) =
}
onCreated(skillName);
} catch (err) {
if (!onTierError(err, skillName)) {
setError(err instanceof Error ? err.message : 'Failed to create skill');
}
setError(err instanceof Error ? err.message : 'Failed to create skill');
} finally {
setBusy(false);
}

View File

@@ -14,7 +14,6 @@
*/
import { useState } from 'react';
import { SignIn, SignUp } from '@clerk/clerk-react';
import EnterpriseCTA from './EnterpriseCTA';
type Mode = 'signin' | 'signup';
@@ -49,8 +48,6 @@ export default function ClerkAuthForm() {
{mode === 'signin' ? 'Create an account' : 'Sign in'}
</button>
</p>
<EnterpriseCTA />
</div>
);
}

View File

@@ -1,24 +0,0 @@
/**
* EnterpriseCTA — PR7b Auth (design §2d, D15). The SSO/enterprise panel as a custom
* "Talk to sales → KVARK/Teams" CTA. NOT a live SAML/SCIM form: those are
* Teams/KVARK/Clerk-Enterprise features, so rendering a working-looking SAML form would
* be a fabrication (F11 / recon 03 §5.5). This is the KVARK funnel.
*/
export default function EnterpriseCTA() {
return (
<div className="mt-6 pt-5 border-t border-[var(--line-soft)] text-center">
<p className="text-[12px] leading-relaxed text-[var(--text-muted)]">
SAML, SCIM provisioning, and audit logs are available on{' '}
<b className="text-foreground">Teams</b> and <b className="text-foreground">KVARK</b>.
</p>
<a
href="https://www.kvark.ai"
target="_blank"
rel="noopener noreferrer"
className="inline-block mt-1.5 text-[12.5px] font-[650] text-honey hover:text-[var(--honey-bright)] transition-colors"
>
Talk to sales →
</a>
</div>
);
}

View File

@@ -1,180 +0,0 @@
/**
* PlanCards — warm-Hive PR7a Billing (design screen 14 "Plans" state).
*
* The 2-card Plans grid (Solo · free / Team · most-popular) + the Monthly|Annual
* −20% cycle toggle, themed to the warm tokens (PR1). Prices are DISPLAY COPY from
* `tiers.ts` (D10) — the *charged* amount is whatever Stripe renders on the hosted
* Checkout page; this UI never asserts the real charge. Choosing a plan hands off to
* hosted Stripe Checkout via `onChoose` (D5) — no in-app card capture.
*
* The toggle resolves a real `billingPeriod` that threads to the annual Stripe price
* (D8/F9) — it is NOT a cosmetic `× 0.8` client number.
*/
import { useState } from 'react';
import { Check } from 'lucide-react';
type CheckoutTier = 'TEAMS';
type BillingPeriod = 'monthly' | 'annual';
interface PlanDef {
/** Canonical tier id this card maps to (FREE has no checkout). */
tier: 'FREE' | CheckoutTier;
name: string;
priceMonthly: string;
priceAnnual: string;
unitMonthly: string;
unitAnnual: string;
tagline: string;
features: readonly string[];
popular?: boolean;
}
/** Display copy only (D10) — mirrors `billing.html` + `tiers.ts` doc prices. */
const PLANS: readonly PlanDef[] = [
{
tier: 'FREE',
name: 'Solo',
priceMonthly: '$0',
priceAnnual: '$0',
unitMonthly: '/ forever',
unitAnnual: '/ forever',
tagline: 'Everything one person needs — free, forever.',
features: ['Personal memory graph', 'Unlimited workspaces & connectors', 'Marketplace skills & connectors', 'Self-evolving skills', 'All major LLMs + local'],
},
{
tier: 'TEAMS',
name: 'Team',
priceMonthly: '$49',
priceAnnual: '$39',
unitMonthly: '/ seat / mo',
unitAnnual: '/ seat · yearly',
tagline: 'Shared memory without losing privacy.',
features: ['Everything in Solo', 'Sync across devices', 'Shared team memory', 'WaggleDance multi-agent', 'SSO & role-based access'],
popular: true,
},
];
/** Upgrade ordering. TRIAL collapses to the Solo (FREE) entry-point for the "current"
* marker; a legacy PRO value maps to 0 so it reads as the Solo tier. */
const RANK: Record<string, number> = { FREE: 0, TRIAL: 0, PRO: 0, TEAMS: 1, ENTERPRISE: 2 };
interface PlanCardsProps {
/** Resolved current tier (caller must only render this on a resolved tier — F7). */
currentTier: string;
/** Hand off to hosted Stripe Checkout for an upgrade. */
onChoose: (tier: CheckoutTier, period: BillingPeriod) => void;
/** Stripe not configured (503) — render CTAs as a disabled honest state (F8). */
disabled?: boolean;
}
export default function PlanCards({ currentTier, onChoose, disabled = false }: PlanCardsProps) {
const [period, setPeriod] = useState<BillingPeriod>('monthly');
const currentRank = RANK[currentTier] ?? 0;
return (
<div className="space-y-6">
{/* Monthly | Annual −20% cycle toggle */}
<div className="flex justify-center">
<div
className="inline-flex p-1 gap-[3px] rounded-[11px] bg-[var(--surface-2)] border border-[var(--line-soft)]"
role="group"
aria-label="Billing cycle"
>
{(['monthly', 'annual'] as const).map((p) => (
<button
key={p}
type="button"
aria-pressed={period === p}
onClick={() => setPeriod(p)}
className={`px-4 py-2 rounded-lg text-[13px] font-semibold transition-colors ${
period === p ? 'bg-primary text-primary-foreground' : 'text-[var(--text-muted)] hover:text-foreground'
}`}
>
{p === 'monthly' ? 'Monthly' : 'Annual'}
{p === 'annual' && (
<span className={`ml-1.5 text-[10.5px] ${period === 'annual' ? 'text-primary-foreground' : 'text-[var(--healthy)]'}`}>
−20%
</span>
)}
</button>
))}
</div>
</div>
{/* 2-card plans grid */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-stretch">
{PLANS.map((plan) => {
const planRank = RANK[plan.tier];
// A TRIAL user is not on the Free plan — the honest "Trial — everything
// unlocked" badge lives above the grid, so no card claims to be "current".
const isCurrent = planRank === currentRank && currentTier !== 'TRIAL';
const isUpgrade = planRank > currentRank && plan.tier !== 'FREE';
const price = period === 'annual' ? plan.priceAnnual : plan.priceMonthly;
const unit = period === 'annual' ? plan.unitAnnual : plan.unitMonthly;
return (
<div
key={plan.tier}
// Honey glow via inline style (the BenchmarkApp pattern): Tailwind v4's
// arbitrary `shadow-[var(--shadow-honey)]` resolves to box-shadow:none
// here (live-verified), so the focal card sets the shadow var inline.
style={plan.popular ? { boxShadow: 'var(--shadow-honey)' } : undefined}
className={`relative flex flex-col p-6 rounded-[18px] border bg-[var(--surface)] ${
plan.popular
? 'border-[var(--honey-line)]'
: isCurrent
? 'border-[var(--work)]'
: 'border-[var(--line-soft)]'
}`}
>
{plan.popular && (
<span className="absolute -top-[11px] left-6 text-[11px] font-bold uppercase tracking-[0.04em] text-primary-foreground bg-primary px-[11px] py-1 rounded-full">
Most popular
</span>
)}
{isCurrent && (
<span className="absolute -top-[11px] right-6 text-[11px] font-bold uppercase text-primary-foreground bg-[var(--work)] px-[11px] py-1 rounded-full">
Current
</span>
)}
<div className="text-[15px] font-semibold text-[var(--text-2)]">{plan.name}</div>
<div className="text-[38px] font-[750] tracking-[-0.03em] mt-3 mb-0.5 text-foreground">
{price}
<small className="text-[15px] font-medium text-[var(--text-muted)] tracking-normal"> {unit}</small>
</div>
<div className="text-[13px] text-[var(--text-muted)] mb-5 min-h-[36px]">{plan.tagline}</div>
<ul className="list-none m-0 mb-6 p-0 grid gap-2.5 flex-1">
{plan.features.map((f) => (
<li key={f} className="text-[13px] text-[var(--text-2)] grid grid-cols-[17px_1fr] gap-2 leading-snug">
<Check className="w-3.5 h-3.5 mt-0.5 text-[var(--healthy)]" strokeWidth={2.4} />
<span>{f}</span>
</li>
))}
</ul>
{isUpgrade ? (
<button
onClick={() => onChoose(plan.tier as CheckoutTier, period)}
disabled={disabled}
className={`py-2.5 rounded-[10px] text-[14px] font-[650] text-center border transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${
plan.popular
? 'bg-primary text-primary-foreground border-transparent hover:bg-[var(--honey-bright)]'
: 'bg-[var(--surface-2)] text-[var(--text-2)] border-[var(--line-strong)] hover:border-[var(--honey-line)] hover:text-honey'
}`}
>
{disabled ? 'Unavailable' : `Choose ${plan.name}`}
</button>
) : (
<div className="py-2.5 rounded-[10px] text-[14px] font-[650] text-center border border-[var(--line-soft)] bg-transparent text-[var(--text-dim)] cursor-default">
{isCurrent ? 'Your plan' : 'Included'}
</div>
)}
</div>
);
})}
</div>
</div>
);
}

View File

@@ -505,9 +505,6 @@ const CommandCenter = ({ open, onClose, onNavigate, onExecute, workspaceId, cata
if (res.ok) {
toast({ title: 'Done', description: action.label });
onClose();
} else if (res.status === 403) {
// The global adapter handler already raised the UpgradeModal — just close.
onClose();
} else {
toast({ title: 'Action failed', description: action.label, variant: 'destructive' });
}
@@ -521,13 +518,6 @@ const CommandCenter = ({ open, onClose, onNavigate, onExecute, workspaceId, cata
// ── Tier 1: dispatch a resolved intent onto the existing execution paths. ──
const handleResolvedAction = useCallback((res: InterpretResult) => {
if (res.kind === 'tier_gated') {
window.dispatchEvent(new CustomEvent('waggle:tier-insufficient', {
detail: { required: res.requiredTier, actual: res.actualTier, message: res.message },
}));
onClose();
return;
}
if (res.kind !== 'action' || !res.action) return;
const action = res.action;
if (action.navigate) {
@@ -636,7 +626,7 @@ const CommandCenter = ({ open, onClose, onNavigate, onExecute, workspaceId, cata
{/* ── Tier 1: Ask Waggle (NL intent) — sits above Tier 0 results,
never replacing them. Renders interpreting / resolved action /
clarify / upgrade / decline. ── */}
clarify / decline. ── */}
{(interpreting || interpret) && (
<CommandGroup
heading={
@@ -656,27 +646,6 @@ const CommandCenter = ({ open, onClose, onNavigate, onExecute, workspaceId, cata
<ResultRow result={actionToResult(interpret.action)} onSelect={() => handleResolvedAction(interpret)} />
)}
{!interpreting && interpret?.kind === 'tier_gated' && (
<CommandItem
value="__intent_tier__"
onSelect={() => handleResolvedAction(interpret)}
className="flex items-center gap-3 rounded-lg px-3 py-2 text-sm aria-selected:bg-[var(--honey-glow,rgba(229,160,0,0.08))]"
>
<Sparkles className="h-4 w-4 shrink-0" style={{ color: 'var(--honey-500)' }} />
<div className="min-w-0 flex-1 text-left">
<span className="block truncate font-display" style={{ color: 'var(--hive-100)' }}>
Upgrade to {interpret.requiredTier} to do this
</span>
<span className="block truncate text-xs" style={{ color: 'var(--hive-400)' }}>
{interpret.capability}
</span>
</div>
<span className="shrink-0 rounded-full px-1.5 py-0.5 text-[10px]" style={{ backgroundColor: 'rgba(167,139,250,0.15)', color: '#a78bfa' }}>
{interpret.requiredTier}
</span>
</CommandItem>
)}
{!interpreting && interpret?.kind === 'clarify' && (
<div className="px-3 py-2" data-testid="intent-clarify">
<p className="mb-2 text-sm" style={{ color: 'var(--hive-100)' }}>{interpret.question}</p>

View File

@@ -13,13 +13,10 @@ import { PERSONAS } from '@/lib/personas';
import { motion, AnimatePresence, useDragControls } from 'framer-motion';
import { adapter } from '@/lib/adapter';
import { useWorkspaces } from '@/hooks/useWorkspaces';
import { useShell } from '@/providers/ShellContext';
import { canCreateWorkspaceAtTier } from '@/lib/workspace-limit';
import LockedFeature from '@/components/os/LockedFeature';
import { buildBreadcrumbs } from '@/lib/browse-breadcrumbs';
import { useFocusTrap } from '@/hooks/useFocusTrap';
import type { StorageType, WorkspaceTemplate, TemplateCategory } from '@/lib/types';
import { TIER_CAPABILITIES, type ConnectorDefinition } from '@waggle/shared';
import type { ConnectorDefinition } from '@waggle/shared';
/** Use native OS folder picker when running inside Tauri, falls back to custom browse modal. */
async function pickFolderNative(): Promise<string | null> {
@@ -729,12 +726,6 @@ function TemplateCreatorModal({ open, onClose, onCreated, availableConnectors, e
const CreateWorkspaceDialog = ({ open, onClose, onCreate }: CreateWorkspaceDialogProps) => {
const { workspaces } = useWorkspaces();
const { billingTier } = useShell();
// Gate off the SAME canonical rule the server enforces (tiers.ts
// workspaceLimit), not the retired onboarding-complexity flag that blocked
// Solo at workspace #2 while the backend would have allowed unlimited. Client
// and server now agree by construction.
const canCreateWorkspace = canCreateWorkspaceAtTier(billingTier, workspaces.length);
const [name, setName] = useState('');
const [group, setGroup] = useState('Personal');
@@ -856,28 +847,6 @@ const CreateWorkspaceDialog = ({ open, onClose, onCreate }: CreateWorkspaceDialo
if (!open) return null;
if (!canCreateWorkspace) {
return (
<AnimatePresence>
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
className="fixed inset-0 z-[100] flex items-center justify-center" onClick={onClose}>
<div className="absolute inset-0 bg-black/50 backdrop-blur-sm" />
<motion.div initial={{ opacity: 0, scale: 0.95 }} animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
className="relative w-full max-w-sm glass-strong rounded-2xl shadow-2xl overflow-hidden"
onClick={e => e.stopPropagation()}>
<div className="p-6">
{/* The gate now matches the server (tiers.ts workspaceLimit), so
the count is finally safe to quote: this paywall only fires once
a FREE user has actually reached the limit. */}
<LockedFeature featureName="Multiple Workspaces" upgradePrompt={`Upgrade for unlimited workspaces. The Free plan includes ${TIER_CAPABILITIES.FREE.workspaceLimit}.`} />
</div>
</motion.div>
</motion.div>
</AnimatePresence>
);
}
const virtualPath = defaultVirtualPath(name);
// Non-blocking dup-name warning: two "Research Hub"s are indistinguishable in

View File

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

View File

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

View File

@@ -135,11 +135,10 @@ export function getPersonasForTemplate(templateId: string): readonly OnboardingP
];
}
// QW-5: display labels renamed to avoid collision with billing tiers
// (billing uses "Pro $19/mo", "Teams $49/seat"). Dock tiers describe how
// many icons appear — they are UI layout, not billing. Internal enum
// values ('simple' / 'professional' / 'power') stay the same so stored
// user preferences keep working without migration.
// QW-5: display labels for the dock tiers. Dock tiers describe how many
// icons appear — they are UI layout. Internal enum values ('simple' /
// 'professional' / 'power') stay the same so stored user preferences keep
// working without migration.
export const TIER_OPTIONS: readonly TierOption[] = [
{
id: 'simple' as UserTier,

View File

@@ -1,15 +0,0 @@
import { describe, expect, it } from 'vitest';
import { render, screen } from '@testing-library/react';
import CoverageCompassCard from './CoverageCompassCard';
describe('CoverageCompassCard', () => {
it('does not claim Browser Companion coverage before native entry points are proven', () => {
render(<CoverageCompassCard />);
const partialRows = screen.getAllByTestId('coverage-compass-row-partial');
const browserRow = partialRows.find((row) => row.textContent?.includes('Browser AI extensions'));
expect(browserRow).toBeDefined();
expect(browserRow).toHaveTextContent(/native toolbar\/context menu pending/i);
});
});

View File

@@ -1,105 +0,0 @@
/**
* Coverage compass card — Settings → Billing.
*
* F4 polish from the 2026-05-28 addictiveness audit. Answers the
* "what am I getting for what I pay?" question that personas P3 (Sarah,
* marketing), P4 (Imran, consultant), and P7 (Anya, writer) all hit
* when comparing Waggle to their current ChatGPT Plus / Notion AI /
* Gamma stack.
*
* Items split into three groups: COVERED (Waggle does this), PARTIAL
* (Waggle has the substrate but the UX isn't first-class yet), and
* NOT YET (out of scope for now). Honest categorisation matters — if
* we mark something COVERED that the user opens another tool for,
* trust evaporates fast.
*/
import { Check, CircleDashed, X } from 'lucide-react';
type Coverage = 'covered' | 'partial' | 'not-yet';
interface CompetingTool {
name: string;
category: string;
coverage: Coverage;
via?: string; // how Waggle covers it (short noun phrase)
}
const TOOLS: CompetingTool[] = [
{ name: 'ChatGPT / Claude.ai', category: 'general AI chat', coverage: 'covered', via: 'Chat app + persona switcher' },
{ name: 'Mem.ai / Heyday', category: 'personal memory', coverage: 'covered', via: 'FrameStore + Knowledge Graph + Harvest' },
{ name: 'Browser AI extensions', category: 'save-to-memory from web', coverage: 'partial', via: 'Companion popup + capture flow; native toolbar/context menu pending' },
{ name: 'Notion AI', category: 'notes + AI in notes', coverage: 'covered', via: 'Memory app + Wiki compiler' },
{ name: 'Granola / Otter.ai', category: 'meeting transcripts', coverage: 'partial', via: 'Voice app + transcript ingest (no native recording yet)' },
{ name: 'Gamma / Beautiful.ai', category: 'AI-generated decks', coverage: 'partial', via: 'pptx / presentation-design skills (no native deck editor)' },
{ name: 'Telegram bot for cron updates', category: 'outbound digests', coverage: 'covered', via: 'Scheduled Jobs → Telegram channel' },
{ name: 'Zapier / n8n', category: 'workflow automation', coverage: 'partial', via: 'Scheduled Jobs + Skills marketplace (limited triggers)' },
{ name: 'Excel Copilot', category: 'spreadsheet AI', coverage: 'not-yet', via: 'xlsx skill exists; native editor planned' },
{ name: 'GitHub Copilot / Cursor', category: 'in-editor coding', coverage: 'not-yet', via: 'intentional — use Claude Code for coding, Waggle for everything else' },
];
const ICONS: Record<Coverage, { Icon: typeof Check; className: string; label: string }> = {
'covered': { Icon: Check, className: 'text-emerald-400', label: 'Covered' },
'partial': { Icon: CircleDashed, className: 'text-amber-400', label: 'Partial' },
'not-yet': { Icon: X, className: 'text-muted-foreground/60', label: 'Not yet' },
};
const CoverageCompassCard = () => {
const counts = TOOLS.reduce<Record<Coverage, number>>(
(acc, t) => ({ ...acc, [t.coverage]: (acc[t.coverage] ?? 0) + 1 }),
{ 'covered': 0, 'partial': 0, 'not-yet': 0 },
);
return (
<div
className="p-4 rounded-xl bg-secondary/30 border border-border/30 space-y-3"
data-testid="coverage-compass-card"
>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-xs font-display font-medium text-foreground">What Waggle replaces</p>
<p className="text-[11px] text-muted-foreground mt-0.5">
Honest scoring — only items that genuinely don't need another tool open are marked covered.
</p>
</div>
<div className="flex items-center gap-2 shrink-0 text-[10px] font-display">
<span className="inline-flex items-center gap-1 text-emerald-400">
<Check className="w-2.5 h-2.5" />{counts['covered']}
</span>
<span className="inline-flex items-center gap-1 text-amber-400">
<CircleDashed className="w-2.5 h-2.5" />{counts['partial']}
</span>
<span className="inline-flex items-center gap-1 text-muted-foreground/60">
<X className="w-2.5 h-2.5" />{counts['not-yet']}
</span>
</div>
</div>
<ul className="space-y-1.5" role="list">
{TOOLS.map(tool => {
const { Icon, className, label } = ICONS[tool.coverage];
return (
<li
key={tool.name}
className="flex items-start gap-2.5 text-[11px]"
data-testid={`coverage-compass-row-${tool.coverage}`}
>
<Icon className={`w-3 h-3 mt-0.5 shrink-0 ${className}`} aria-label={label} />
<div className="min-w-0 flex-1">
<p className="text-foreground">
{tool.name}
<span className="text-muted-foreground"> · {tool.category}</span>
</p>
{tool.via && (
<p className="text-[10px] text-muted-foreground/80 mt-0.5">via {tool.via}</p>
)}
</div>
</li>
);
})}
</ul>
</div>
);
};
export default CoverageCompassCard;

View File

@@ -1,156 +0,0 @@
/**
* useBilling — billing state management and Stripe checkout sync.
*
* After the user returns from Stripe checkout (detected by ?session_id= in URL),
* this hook calls POST /api/stripe/sync to confirm payment, then refreshes
* the tier via GET /api/tier.
*/
import { useState, useCallback, useEffect, useRef } from 'react';
import { adapter } from '@/lib/adapter';
import { useRevalidateOnError } from '@/hooks/useRevalidateOnError';
export interface BillingState {
tier: string;
/** P1b D3-4: false until a getTier() round-trip succeeds. While false the
* default 'FREE' is a placeholder, NOT the user's plan — billing surfaces
* must render an unresolved state instead of the FREE card + upgrade grid. */
tierResolved: boolean;
loading: boolean;
error: string | null;
syncing: boolean;
/** PR7a/F8: whether Stripe checkout is configured server-side. Defaults true
* (never disable a working upgrade path on a probe hiccup); flips false only
* when the /api/stripe/status probe explicitly reports it unconfigured. */
checkoutAvailable: boolean;
}
export function useBilling() {
const [state, setState] = useState<BillingState>({
tier: 'FREE',
tierResolved: false,
loading: true,
error: null,
syncing: false,
checkoutAvailable: true,
});
// PR7a fix: on /payment-success, the mount refreshTier() and the post-checkout
// syncAfterCheckout() race. The sync result is authoritative — once a checkout
// sync owns the tier, a late getTier() (e.g. stale 'FREE') must not clobber it
// back, which would flash the just-paid user a wrong "Nothing to confirm".
const checkoutSyncStartedRef = useRef(false);
/** Fetch current tier from the server. */
const refreshTier = useCallback(async () => {
try {
const data = await adapter.getTier();
setState((prev) =>
checkoutSyncStartedRef.current
// A checkout sync owns the tier on this surface — don't overwrite it.
? { ...prev, loading: false }
: { ...prev, tier: data.tier, tierResolved: true, loading: false, error: null });
} catch (err) {
// P1b D3-4: keep the previous tier (never present the 'FREE' default as
// fact) and surface the failure so the Billing tab can render it.
const message = err instanceof Error ? err.message : 'Tier lookup failed';
setState((prev) => ({ ...prev, loading: false, error: prev.tierResolved ? prev.error : message }));
}
}, []);
// D3 plus-clause: revalidate an unresolved tier on focus/online/connect-settled.
useRevalidateOnError(!state.tierResolved && !state.loading, refreshTier);
/** Call after Stripe checkout redirect to confirm payment and update tier. */
const syncAfterCheckout = useCallback(async (sessionId: string) => {
// Claim tier ownership synchronously (before any await) so a concurrent
// mount refreshTier() that resolves later won't overwrite the sync result.
checkoutSyncStartedRef.current = true;
setState((prev) => ({ ...prev, syncing: true, error: null }));
try {
const result = await adapter.syncStripeCheckout(sessionId);
setState((prev) => ({
...prev,
tier: result.tier,
tierResolved: true,
syncing: false,
error: null,
}));
return result;
} catch (err) {
const message = err instanceof Error ? err.message : 'Checkout sync failed';
setState((prev) => ({ ...prev, syncing: false, error: message }));
return null;
}
}, []);
/** Open Stripe checkout for a tier upgrade. Returns the checkout URL.
* PR7a/D8: billingPeriod honors the Monthly/Annual toggle (annual → the real
* annual Stripe price, not a cosmetic client discount). */
const startCheckout = useCallback(async (tier: 'TEAMS', billingPeriod?: 'monthly' | 'annual') => {
try {
const { url } = await adapter.createCheckoutSession(tier, billingPeriod);
if (url) {
window.open(url, '_blank', 'noopener,noreferrer');
}
return url;
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to create checkout session';
setState((prev) => ({ ...prev, error: message }));
return null;
}
}, []);
/** Open the Stripe customer portal for subscription management. */
const openPortal = useCallback(async () => {
try {
const { url } = await adapter.createPortalSession();
if (url) {
window.open(url, '_blank', 'noopener,noreferrer');
}
return url;
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to open billing portal';
setState((prev) => ({ ...prev, error: message }));
return null;
}
}, []);
// On mount, fetch the current tier
useEffect(() => {
refreshTier();
}, [refreshTier]);
// PR7a/F8: probe whether Stripe checkout is configured so billing surfaces can
// disable the upgrade CTAs pre-click instead of failing with a 503 after one.
// Fail-safe: any probe error (or an adapter without the method, e.g. in tests)
// leaves checkoutAvailable=true — the real checkout call still 503s honestly.
useEffect(() => {
let alive = true;
Promise.resolve(adapter.getStripeStatus?.())
.then((s) => { if (alive && s) setState((prev) => ({ ...prev, checkoutAvailable: s.configured })); })
.catch(() => { /* leave checkoutAvailable=true */ });
return () => { alive = false; };
}, []);
// Auto-detect session_id in URL params (post-checkout redirect)
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const sessionId = params.get('session_id');
if (sessionId) {
syncAfterCheckout(sessionId).then(() => {
// Clean the URL after sync
const url = new URL(window.location.href);
url.searchParams.delete('session_id');
window.history.replaceState({}, '', url.toString());
});
}
}, [syncAfterCheckout]);
return {
...state,
refreshTier,
syncAfterCheckout,
startCheckout,
openPortal,
};
}

View File

@@ -791,23 +791,18 @@ export const useChat = ({ workspaceId, sessionId, persona, model, autonomy }: Us
setPendingApproval(null);
// P1b D3: sendMessage now THROWS AdapterHttpError on HTTP failure (it
// used to parse the error body as an empty SSE stream — silent dead
// chat). 'Backend is offline' is reserved for genuine network failures;
// a tier 403 already opened the UpgradeModal via the adapter's global
// dispatch, so its inline copy points there instead of duplicating the
// upsell. Duck-typed on error.name (NOT instanceof an imported class) so
// chat). 'Backend is offline' is reserved for genuine network failures.
// Duck-typed on error.name (NOT instanceof an imported class) so
// component tests that vi.mock('@/lib/adapter') wholesale stay decoupled.
const httpErr = e instanceof Error && e.name === 'AdapterHttpError'
? (e as Error & { status?: number; body?: unknown })
: null;
const isTier403 = (httpErr?.body as { error?: string } | undefined)?.error === 'TIER_INSUFFICIENT';
const isIncompleteStream = e instanceof Error && e.name === 'ChatStreamIncompleteError';
const isUnexpectedAbort = e instanceof Error && e.name === 'AbortError';
const message = isIncompleteStream
? e.message
: isUnexpectedAbort
? 'The response was interrupted before completion. Please retry.'
: isTier403
? 'This action needs a higher plan — see the upgrade window.'
: httpErr
? `Chat request failed (${httpErr.status}): ${httpErr.message}`
: 'Backend is offline. Connect to a Waggle server to start chatting.';

View File

@@ -268,8 +268,7 @@ export const useOnboarding = () => {
setState(prev => {
const next = { ...prev, ...updates };
// F1/F5: stamp the completion time on the transition ONLY (immutable copy)
// so the trial-modal gate + coach-marks gate can quiet themselves right
// after the wizard. The two returning-user auto-complete effects use
// so the coach-marks gate can quiet itself right after the wizard. The two returning-user auto-complete effects use
// saveState() directly and deliberately leave completedAt unset.
const justCompleted = next.completed && !prev.completed;
const stamped = justCompleted ? { ...next, completedAt: Date.now() } : next;

View File

@@ -464,7 +464,7 @@
}
/* R11 Lane D (a11y): the bright glass status bar washed its muted chrome
(breadcrumbs · 'Solo plan' · Search/Ctrl-K · date) toward invisible in
(breadcrumbs · Search/Ctrl-K · date) toward invisible in
light. Redefine ONLY the bar's --muted-foreground one step darker
(33% L ≈ #625946, ~6:1 on the bar) — every text-muted-foreground child
inherits it. Dark keeps its tuned 57%. */

View File

@@ -4,7 +4,7 @@
* Pins the four-state ensureReady() contract (never-attempted passthrough /
* in-flight deferral / settled-success passthrough / settled-failure re-arm),
* the connect watchdog, the setServerUrl epoch guard, AdapterHttpError's
* message-first precedence, the 403 dispatch-then-throw ordering, the
* message-first precedence, the 403 throw / body-envelope split, the
* token-versioned single-flight 401 retry, and the fetchRaw body-envelope
* contract for the getters whose ERROR bodies are load-bearing (installMcp's
* ApprovalModal security envelope et al). These are the regression locks the
@@ -664,23 +664,23 @@ describe('P1b auth gate', () => {
it('AdapterHttpError: message-first precedence (body.message ?? body.error ?? HTTP n) + status/body fields', async () => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [['/api/tier', () => jsonRes({ error: 'E_CODE', message: 'Human reason' }, 500)]]);
const err = await a.getTier().catch((e: unknown) => e) as AdapterHttpError;
routeMock(fetchSpy, [['/api/personas', () => jsonRes({ error: 'E_CODE', message: 'Human reason' }, 500)]]);
const err = await a.getPersonas().catch((e: unknown) => e) as AdapterHttpError;
expect(err).toBeInstanceOf(AdapterHttpError);
expect(err.message).toBe('Human reason');
expect(err.status).toBe(500);
expect((err.body as { error: string }).error).toBe('E_CODE');
routeMock(fetchSpy, [['/api/tier', () => jsonRes({ error: 'only-error' }, 404)]]);
const err2 = await a.getTier().catch((e: unknown) => e) as AdapterHttpError;
routeMock(fetchSpy, [['/api/personas', () => jsonRes({ error: 'only-error' }, 404)]]);
const err2 = await a.getPersonas().catch((e: unknown) => e) as AdapterHttpError;
expect(err2.message).toBe('only-error');
routeMock(fetchSpy, [['/api/tier', () => new Response('plain text', { status: 502 })]]);
const err3 = await a.getTier().catch((e: unknown) => e) as AdapterHttpError;
routeMock(fetchSpy, [['/api/personas', () => new Response('plain text', { status: 502 })]]);
const err3 = await a.getPersonas().catch((e: unknown) => e) as AdapterHttpError;
expect(err3.message).toBe('HTTP 502');
});
it('the six ruling-named getters reject on HTTP failure instead of returning silent-empty', async () => {
it('the ruling-named getters reject on HTTP failure instead of returning silent-empty', async () => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [['/api/', () => jsonRes({ error: 'Unauthorized', code: 'MISSING_TOKEN' }, 500)]]);
await expect(a.getMarketplace()).rejects.toThrow(AdapterHttpError);
@@ -688,27 +688,17 @@ describe('P1b auth gate', () => {
await expect(a.getPersonas()).rejects.toThrow(AdapterHttpError);
await expect(a.getModels()).rejects.toThrow(AdapterHttpError);
await expect(a.getWorkspaceTemplates()).rejects.toThrow(AdapterHttpError);
await expect(a.getTier()).rejects.toThrow(AdapterHttpError);
});
it('403 TIER_INSUFFICIENT: dispatch-then-throw on the throwing path, dispatch-and-return on fetchRaw', async () => {
it('403: throws on the throwing path, returns the body envelope on fetchRaw', async () => {
const a = new LocalAdapter(BASE);
const events: unknown[] = [];
const listener = (e: Event) => events.push((e as CustomEvent).detail);
window.addEventListener('waggle:tier-insufficient', listener);
try {
const tierBody = { error: 'TIER_INSUFFICIENT', message: 'Needs TEAMS', required: 'TEAMS', actual: 'FREE' };
routeMock(fetchSpy, [['/api/personas', () => jsonRes(tierBody, 403)]]);
await expect(a.getPersonas()).rejects.toThrow('Needs TEAMS');
expect(events).toHaveLength(1);
const forbiddenBody = { error: 'FORBIDDEN', message: 'Not allowed' };
routeMock(fetchSpy, [['/api/personas', () => jsonRes(forbiddenBody, 403)]]);
await expect(a.getPersonas()).rejects.toThrow('Not allowed');
routeMock(fetchSpy, [['/api/mcps/install', () => jsonRes({ installed: false, ...tierBody }, 403)]]);
const envelope = await a.installMcp('exa');
expect((envelope as { error?: string }).error).toBe('TIER_INSUFFICIENT');
expect(events).toHaveLength(2);
} finally {
window.removeEventListener('waggle:tier-insufficient', listener);
}
routeMock(fetchSpy, [['/api/mcps/install', () => jsonRes({ installed: false, ...forbiddenBody }, 403)]]);
const envelope = await a.installMcp('exa');
expect((envelope as { error?: string }).error).toBe('FORBIDDEN');
});
it('sendMessage: an HTTP error now throws into the consumer instead of yielding nothing', async () => {
@@ -816,7 +806,7 @@ describe('P1b auth gate', () => {
it('installMarketplacePackage stays raw (status readable); uninstall now throws on failure', async () => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [['/api/marketplace/install', () => jsonRes({ error: 'TIER_INSUFFICIENT' }, 403)]]);
routeMock(fetchSpy, [['/api/marketplace/install', () => jsonRes({ blocked: true, severity: 'CRITICAL', message: 'Blocked' }, 403)]]);
const res = await a.installMarketplacePackage(7);
expect(res.status).toBe(403);
@@ -874,23 +864,23 @@ describe('P1b auth gate', () => {
fetchSpy.mockClear();
let release401!: (r: Response) => void;
const gate401 = new Promise<Response>(res => { release401 = res; });
let tierCalls = 0;
let personaCalls = 0;
let wsCalls = 0;
routeMock(fetchSpy, [
[TOKEN_PATH, () => jsonRes({ token: 'tok-B' })],
['/api/tier', () => (++tierCalls === 1 ? gate401 : jsonRes({ tier: 'TEAMS', capabilities: {}, usage: {} }))],
['/api/personas', () => (++personaCalls === 1 ? gate401 : jsonRes([]))],
['/api/workspaces', () => (++wsCalls === 1
? jsonRes({ error: 'Unauthorized', code: 'INVALID_TOKEN' }, 401)
: jsonRes([]))],
]);
const tierP = a.getTier(); // in flight with tok-A, response held
const personasP = a.getPersonas(); // in flight with tok-A, response held
await a.getWorkspaces(); // 401 → refresh → tok-B
expect(callsTo(fetchSpy, TOKEN_PATH)).toHaveLength(1);
release401(jsonRes({ error: 'Unauthorized', code: 'INVALID_TOKEN' }, 401)); // straggler lands post-rotation
await tierP;
await personasP;
expect(callsTo(fetchSpy, TOKEN_PATH)).toHaveLength(1); // no second refresh
const tier = callsTo(fetchSpy, '/api/tier');
expect((tier[1][1]!.headers as Record<string, string>).Authorization).toBe('Bearer tok-B');
const personas = callsTo(fetchSpy, '/api/personas');
expect((personas[1][1]!.headers as Record<string, string>).Authorization).toBe('Bearer tok-B');
});
it('refresh failure is LOUD: the original call rejects with the refresh cause, no token-less retry', async () => {

View File

@@ -1,89 +0,0 @@
/**
* LocalAdapter.startTrial — atomic 15-day trial start wiring.
*
* Pins the contract between Desktop's UpgradeModal `onStartTrial` callback
* + the onboarding-complete handler, and the server's POST
* /api/tier/start-trial route. Guards against the original silent-failure
* pattern where the call site used a non-existent `adapter.updateSettings`
* method behind an `as any` cast (see commit db069a7 for the bug
* post-mortem).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import LocalAdapter from './adapter';
describe('LocalAdapter.startTrial', () => {
let fetchSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
fetchSpy = vi.spyOn(globalThis, 'fetch');
});
afterEach(() => {
fetchSpy.mockRestore();
});
it('POSTs to /api/tier/start-trial and returns the parsed body on 200', async () => {
const serverBody = {
tier: 'TRIAL',
rawTier: 'TRIAL',
trialStartedAt: '2026-05-07T18:00:00.000Z',
trialDaysRemaining: 15,
trialExpired: false,
capabilities: { workspaceLimit: -1, spawnAgents: true },
};
fetchSpy.mockResolvedValue(
new Response(JSON.stringify(serverBody), {
status: 200,
headers: { 'Content-Type': 'application/json' },
}),
);
const adapter = new LocalAdapter('http://test-server:9999');
const result = await adapter.startTrial();
// Wiring: correct URL + method.
expect(fetchSpy).toHaveBeenCalledOnce();
const [url, init] = fetchSpy.mock.calls[0] as [string | URL, RequestInit];
expect(String(url)).toBe('http://test-server:9999/api/tier/start-trial');
expect(init.method).toBe('POST');
// Returns the server body verbatim — Desktop's refreshTier path depends
// on `tier` + `trialDaysRemaining` being present.
expect(result).toEqual(serverBody);
});
it('throws on 409 TRIAL_ALREADY_STARTED so call sites can decide whether to surface', async () => {
fetchSpy.mockResolvedValue(
new Response(JSON.stringify({
error: 'TRIAL_ALREADY_STARTED',
message: 'A trial has already been started for this installation.',
tier: 'TRIAL',
trialStartedAt: '2026-05-01T00:00:00.000Z',
trialDaysRemaining: 9,
trialExpired: false,
}), {
status: 409,
headers: { 'Content-Type': 'application/json' },
}),
);
const adapter = new LocalAdapter('http://test-server:9999');
await expect(adapter.startTrial()).rejects.toThrow(/Start trial failed.*409/);
// The thrown message must surface the server's `message` field so a
// future toast/inline-error UI can show something useful instead of
// the bare HTTP status text.
await expect(adapter.startTrial()).rejects.toThrow(/A trial has already been started/);
});
it('throws on 500 with the server status text when the body is not JSON', async () => {
fetchSpy.mockResolvedValue(
new Response('upstream timeout', {
status: 500,
statusText: 'Internal Server Error',
}),
);
const adapter = new LocalAdapter('http://test-server:9999');
await expect(adapter.startTrial()).rejects.toThrow(/Start trial failed.*500/);
});
});

View File

@@ -180,11 +180,10 @@ function deadlined<T>(p: Promise<T>, ms: number, label: string): Promise<T> {
* P1b D3 — thrown by `adapter.fetch()` on any non-2xx response (the
* chokepoint conversion of ~145 silent-empty getters). Message precedence is
* MESSAGE-FIRST (`body.message ?? body.error ?? HTTP <status>`) — matches the
* incumbent eraseData/startTrial convention and surfaces the human-readable
* reason for `{ error: 'TIER_INSUFFICIENT', message: '…' }`-shaped bodies.
* incumbent eraseData convention and surfaces the human-readable reason for
* `{ error: '…', message: '…' }`-shaped bodies.
* `.status`/`.body` are field-compatible with the pre-existing rich errors
* thrown by installSkill/installPack (consumers: CapabilitiesApp
* handleInstallError, SkillBuilder onTierError).
* thrown by installSkill/installPack.
*/
export class AdapterHttpError extends Error {
readonly status: number;
@@ -731,7 +730,7 @@ class LocalAdapter {
/**
* P1b D3-2: the THROWING request path — rejects with AdapterHttpError on any
* non-2xx response (after the 403 tier dispatch). This is the chokepoint
* non-2xx response. This is the chokepoint
* conversion of the failure-as-data class: ~145 getters that previously
* parsed error bodies as data now surface failures to their callers.
* Callers that need raw status/body semantics use `fetchRaw()`.
@@ -747,8 +746,8 @@ class LocalAdapter {
/**
* P1b D3: today's pre-conversion semantics — never throws on HTTP status
* (still defers on the gate, attaches the token, runs the 401-refresh-retry
* and dispatches the 403 tier event). For the two caller classes whose
* (still defers on the gate, attaches the token and runs the 401-refresh-retry).
* For the two caller classes whose
* error-path payload is load-bearing: raw-Response consumers
* (installMarketplacePackage) and body-envelope getters (installMcp et al,
* whose 403/422 bodies drive the ApprovalModal security flow).
@@ -757,8 +756,8 @@ class LocalAdapter {
return this.request(path, init, timeoutMs);
}
/** Shared request core: deferral gate → headers/token → fetch → 403 tier
* dispatch → 401 refresh-retry (token-versioned, once per request). */
/** Shared request core: deferral gate → headers/token → fetch → 401
* refresh-retry (token-versioned, once per request). */
private async request(
path: string,
init?: RequestInit,
@@ -803,17 +802,6 @@ class LocalAdapter {
headers['X-Waggle-Desktop-Bootstrap'] = this.desktopEndpoint.bootstrapToken;
}
const res = await fetchWithTimeout(`${this.baseUrl}${path}`, { ...init, headers }, timeoutMs);
if (res.status === 403) {
const clone = res.clone();
try {
const body = await clone.json();
if (body.error === 'TIER_INSUFFICIENT') {
window.dispatchEvent(new CustomEvent('waggle:tier-insufficient', {
detail: { required: body.required, actual: body.actual, message: body.message },
}));
}
} catch { /* not JSON — ignore */ }
}
// P1b D3-3: the session token is per-sidecar-process — it rotates on every
// restart. One silent refresh + single retry per request recovers without
// a page reload. Token-versioned: if another request's refresh already
@@ -1729,8 +1717,7 @@ class LocalAdapter {
// Phase-3 fix: this used to send only { name, description }, which the
// route rejects (steps is mandatory) — the call could never succeed.
// P1b D3: the chokepoint AdapterHttpError carries the same .status/.body
// fields the bespoke rich error did (SkillBuilder routes a 403 to the
// UpgradeModal tier event via onTierError) — the local !ok block is gone.
// fields the bespoke rich error did — the local !ok block is gone.
await this.fetch('/api/skills/create', { method: 'POST', body: JSON.stringify(data) });
}
@@ -1743,10 +1730,9 @@ class LocalAdapter {
}
/**
* §D2: run the run-and-grade skill-audit loop (PRO) to mint the "verified"
* §D2: run the run-and-grade skill-audit loop to mint the "verified"
* badge. Pass a names[] to scope the run to specific skills (keeps each POST
* to a few LLM calls). A 403 (FREE/expired tier) throws AdapterHttpError and
* is routed to the UpgradeModal by the fetch chokepoint, like createSkill.
* to a few LLM calls). A failure throws AdapterHttpError, like createSkill.
*/
async auditSkills(names?: string[]): Promise<{
ok: boolean;
@@ -1861,8 +1847,8 @@ class LocalAdapter {
* bearer token) — a raw fetch() returns 401 before the session token has
* bootstrapped, and the UI was silently caching the empty 401 body as an
* empty catalog. The INSTALL variant returns the raw Response (fetchRaw) so
* the caller keeps its status-aware handling (403 → UpgradeModal, scan-
* blocked toasts). P1b D3: uninstall moved to the THROWING fetch — its only
* the caller keeps its status-aware handling (scan-blocked toasts). P1b D3:
* uninstall moved to the THROWING fetch — its only
* consumer ignored the Response and toasted success unconditionally, so a
* failed uninstall rendered as success; throwing routes it to the catch.
* search also throws now: its consumers parse the body with no ok check, so
@@ -2674,8 +2660,8 @@ class LocalAdapter {
return res.json();
}
/** Persist the embedding provider. Throws AdapterHttpError on 403 (tier) /
* 409 (env override) / 400 (invalid) — the message carries the reason. */
/** Persist the embedding provider. Throws AdapterHttpError on 409 (env
* override) / 400 (invalid) — the message carries the reason. */
async setEmbeddingProvider(provider: string): Promise<EmbeddingRoutingStatus> {
const res = await this.fetch('/api/embedding/provider', {
method: 'POST',
@@ -2863,7 +2849,7 @@ class LocalAdapter {
return unwrapArray(await res.json());
}
/** PRO+ (B5); delegates to the marketplace installer (SecurityGate + audit).
/** Delegates to the marketplace installer (SecurityGate + audit).
* `force` = reinstall over an existing install; `forceInsecure` = the
* audited override for an installer-level HIGH scan block (the block that
* actually fires — `force` alone does NOT override it). */
@@ -2871,9 +2857,9 @@ class LocalAdapter {
installed: boolean; server?: string; status?: string; requiresApproval?: boolean;
}> {
// P1b D3: fetchRaw — the 403/422 ERROR body is load-bearing: it carries
// { error: 'TIER_INSUFFICIENT' } AND the SecurityGate envelope
// { requiresApproval, blocked, severity, scanResult } that drives
// MCPHubApp's ApprovalModal HIGH-override / CRITICAL-non-overridable flow.
// the SecurityGate envelope { requiresApproval, blocked, severity,
// scanResult } that drives MCPHubApp's ApprovalModal HIGH-override /
// CRITICAL-non-overridable flow.
const res = await this.fetchRaw('/api/mcps/install', {
method: 'POST',
body: JSON.stringify({ mcpId, ...opts }),
@@ -2886,8 +2872,8 @@ class LocalAdapter {
env?: Record<string, string>; workspaceId?: string;
}): Promise<{ id: string; registered: boolean }> {
// P1b D3: fetchRaw — body-envelope getter; AddCustomMcpForm branches on
// res.error (incl. the deliberate TIER_INSUFFICIENT inline-suppression)
// and renders 400-validation / injection-scan / 409-duplicate reasons.
// res.error and renders 400-validation / injection-scan / 409-duplicate
// reasons.
const res = await this.fetchRaw('/api/mcps', { method: 'POST', body: JSON.stringify(config) });
return res.json();
}
@@ -3012,19 +2998,6 @@ class LocalAdapter {
}
// --- Team ---
async teamConnect(serverUrl: string, token: string): Promise<void> {
await this.fetch('/api/team/connect', { method: 'POST', body: JSON.stringify({ serverUrl, token }) });
}
async teamDisconnect(): Promise<void> {
await this.fetch('/api/team/disconnect', { method: 'POST' });
}
async getTeamStatus(): Promise<{ connected: boolean; teamName?: string }> {
const res = await this.fetch('/api/team/status');
return res.json();
}
async getTeamMembers(): Promise<{ id: string; name: string; status: string; avatar?: string }[]> {
try {
const res = await this.fetch('/api/team/members');
@@ -3216,8 +3189,7 @@ class LocalAdapter {
/**
* Execute a server-derived ResolvedAction's endpoint (create / side-effect).
* The endpoint + body are produced by the closed registry — the client only
* dispatches what the server already validated. A 403 still flows through the
* global tier handler in `fetch`.
* dispatches what the server already validated.
*/
async commandDispatchAction(action: ResolvedAction): Promise<{ ok: boolean; status: number; result?: unknown }> {
if (!action.endpoint) return { ok: false, status: 0 };
@@ -3631,47 +3603,6 @@ class LocalAdapter {
this.fetch('/api/telemetry/track', { method: 'POST', body: JSON.stringify({ event, properties }) }).catch(() => {});
}
// --- Stripe Billing ---
async syncStripeCheckout(sessionId: string): Promise<{ tier: string; customerId: string | null }> {
const res = await this.fetch('/api/stripe/sync', {
method: 'POST',
body: JSON.stringify({ sessionId }),
});
return res.json();
}
async createCheckoutSession(
tier: 'TEAMS',
billingPeriod?: 'monthly' | 'annual',
): Promise<{ url: string }> {
// PR7a/D8: thread billingPeriod so the annual toggle resolves the real annual
// Stripe price (priceIdForTier). Omitted → backend defaults to monthly.
const res = await this.fetch('/api/stripe/create-checkout-session', {
method: 'POST',
body: JSON.stringify(billingPeriod ? { tier, billingPeriod } : { tier }),
});
return res.json();
}
async createPortalSession(): Promise<{ url: string }> {
const res = await this.fetch('/api/stripe/create-portal-session', {
method: 'POST',
});
return res.json();
}
/** PR7a/F8: secret-free probe of whether Stripe checkout is wired, so the
* billing UI can render the honest disabled state before a click (not a 503 after). */
async getStripeStatus(): Promise<{ configured: boolean }> {
const res = await this.fetch('/api/stripe/status');
return res.json();
}
async getTier(): Promise<{ tier: string; trialDaysRemaining?: number; trialExpired?: boolean; capabilities: Record<string, unknown>; usage: Record<string, unknown> }> {
const res = await this.fetch('/api/tier');
return res.json();
}
/**
* Schedule a complete erasure of this install's data dir (GDPR Art. 17).
*
@@ -3714,40 +3645,6 @@ class LocalAdapter {
}
}
/**
* Start the 15-day trial atomically. Server writes
* `{ tier: 'TRIAL', trialStartedAt: now() }` in a single config.json
* mutation. Throws on 409 (trial already started) — call sites can
* .catch() and either ignore (idempotent UX, e.g. onboarding-complete) or
* surface to the user (e.g. "Start trial" button after expiry).
*
* Replaces the previous broken path where Desktop.tsx called
* `adapter.updateSettings({ tier: 'TRIAL', trialStartedAt: ... } as any)`
* — `updateSettings` did not exist on the adapter (silently swallowed by
* `.catch(() => {})`), and even if it had, `PATCH /api/tier` ignores
* `trialStartedAt`, so the trial never actually started.
*/
async startTrial(): Promise<{
tier: string;
rawTier: string;
trialStartedAt: string;
trialDaysRemaining: number;
trialExpired: boolean;
capabilities: Record<string, unknown>;
}> {
// P1b D3: chokepoint throws first — rethrow in the test-pinned legacy format.
try {
const res = await this.fetch('/api/tier/start-trial', { method: 'POST' });
return res.json();
} catch (e) {
if (e instanceof AdapterHttpError) {
const b = e.body as { message?: string; error?: string } | undefined;
throw new Error(`Start trial failed (${e.status}): ${b?.message ?? b?.error ?? e.statusText}`);
}
throw e;
}
}
// --- Import ---
async importPreview(data: unknown, source: string): Promise<{ knowledgeExtracted: unknown[] }> {
const res = await this.fetch('/api/import/preview', { method: 'POST', body: JSON.stringify({ data, source }) });

View File

@@ -2,8 +2,7 @@
* Coach-marks (OnboardingTooltips) first-run deferral gate (F5).
*
* The tooltip carousel used to fire the instant the shell first landed —
* stacking on top of the trial-paywall dismissal and any other first-launch
* overlay. This gate defers the FIRST post-completion showing: it suppresses
* stacking on top of any other first-launch overlay. This gate defers the FIRST post-completion showing: it suppresses
* the carousel while the user just finished the wizard (same session) or within
* 24h of completion, so the very first landing stays calm and the tour shows on
* the next eligible visit. "Dismiss all" (tooltipsDismissed) and the Settings

View File

@@ -3,7 +3,7 @@ import { buildCommandCatalog } from './command-catalog';
describe('command catalog watch-agent (#4)', () => {
it('includes a "Watch a coding agent live" entry deep-linking to watch mode', () => {
const groups = buildCommandCatalog({ chatHref: '/chat', isPro: false, billingRank: 0 });
const groups = buildCommandCatalog({ chatHref: '/chat', isPro: false });
const all = groups.flatMap((g) => g.items);
const watch = all.find((i) => i.id === 'watch-agent');
expect(watch).toBeTruthy();
@@ -13,10 +13,16 @@ describe('command catalog watch-agent (#4)', () => {
});
it('labels the pinned group without legacy Pro copy', () => {
const groups = buildCommandCatalog({ chatHref: '/chat', isPro: true, billingRank: 3 });
const groups = buildCommandCatalog({ chatHref: '/chat', isPro: true });
const pinned = groups.find((g) => g.key === 'pinned');
expect(pinned).toBeTruthy();
expect(pinned!.heading).toBe('Pinned');
expect(pinned!.heading).not.toMatch(/pro/i);
});
it('lists Approvals for everyone and no upgrade or team governance entry', () => {
const all = buildCommandCatalog({ chatHref: '/chat', isPro: false }).flatMap((g) => g.items);
expect(all.some((i) => i.id === 'approvals')).toBe(true);
expect(all.some((i) => i.id === 'upgrade' || i.to === '/team' || i.to?.includes('tab=billing'))).toBe(false);
});
});

View File

@@ -1,8 +1,7 @@
import type { ElementType } from "react";
import { BILLING_TIER_ORDER } from "@/lib/dock-tiers";
import {
Home, MessageSquare, Brain, ListTodo, Library, UserCircle,
Plus, Rocket, Settings, Sparkles,
Plus, Rocket, Settings,
Network, Server, Plug, Store, Package, Shield, Clock, FolderOpen,
Lock, Activity, History, BarChart3, Users, Radio,
Gauge, Monitor, LayoutGrid, Eye,
@@ -13,8 +12,7 @@ import {
*
* The command bar holds the depth the calm spine leaves out. Every entry is
* **plain name + a mono technical subtitle** and routes to a REAL destination
* (no dead links) or fires a known overlay action. Tier-gated entries (Approvals,
* Team governance) drop below their billing rank. In power mode a "Pinned"
* (no dead links) or fires a known overlay action. In power mode a "Pinned"
* group floats the power tools to the top.
*/
@@ -36,8 +34,6 @@ export interface CatalogCommand {
action?: "spawn";
/** Keyboard hint shown on the right. */
meta?: string;
/** Minimum billing rank to show (FREE 0 · TRIAL 1 · TEAMS 2 · ENT 3). */
minBillingRank?: number;
/** Also floats into the Pinned group. */
pinned?: boolean;
}
@@ -53,14 +49,10 @@ export interface CatalogContext {
chatHref: string;
/** Power/admin tier — shows the Pinned group. */
isPro: boolean;
/** Billing rank for tier gating. */
billingRank: number;
}
const TEAMS_RANK = BILLING_TIER_ORDER.TEAMS;
export function buildCommandCatalog(ctx: CatalogContext): CatalogGroup[] {
const { chatHref, isPro, billingRank } = ctx;
const { chatHref, isPro } = ctx;
const jump: CatalogCommand[] = [
{ id: "home", group: "jump", name: "Home", subtitle: "your daily briefing", icon: Home, to: "/home" },
@@ -76,8 +68,7 @@ export function buildCommandCatalog(ctx: CatalogContext): CatalogGroup[] {
{ 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: "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 · plan", icon: Settings, to: "/settings" },
{ id: "upgrade", group: "do", name: "Upgrade to Team", subtitle: "plans · billing · invoices", icon: Sparkles, to: "/settings?tab=billing" },
{ id: "settings", group: "do", name: "Settings", subtitle: "models · failover · permissions", icon: Settings, to: "/settings" },
];
const power: CatalogCommand[] = [
@@ -86,7 +77,7 @@ export function buildCommandCatalog(ctx: CatalogContext): CatalogGroup[] {
{ id: "connectors", group: "power", name: "Connectors", subtitle: "integrations", icon: Plug, to: "/connectors", pinned: true },
{ id: "marketplace", group: "power", name: "Add a capability", subtitle: "marketplace · skills, connectors, tools", icon: Store, to: "/marketplace" },
{ id: "skills", group: "power", name: "Skills", subtitle: "teach your agents new abilities", icon: Package, to: "/skills" },
{ id: "approvals", group: "power", name: "Approvals", subtitle: "pending agent actions", icon: Shield, to: "/approvals", minBillingRank: TEAMS_RANK, pinned: true },
{ id: "approvals", group: "power", name: "Approvals", subtitle: "pending agent actions", icon: Shield, to: "/approvals", pinned: true },
{ id: "automations", group: "power", name: "Automations", subtitle: "scheduled jobs", icon: Clock, to: "/automations" },
{ id: "files", group: "power", name: "Files & storage", subtitle: "where this workspace lives", icon: FolderOpen, to: "/files" },
{ id: "room", group: "power", name: "Room", subtitle: "work alongside agents live", icon: Users, to: "/room" },
@@ -97,26 +88,22 @@ export function buildCommandCatalog(ctx: CatalogContext): CatalogGroup[] {
{ id: "usage", group: "power", name: "Usage & cost", subtitle: "tokens · spend", icon: BarChart3, to: "/settings/usage" },
{ id: "benchmarks", group: "power", name: "Benchmarks", subtitle: "capabilities · memory SOTA", icon: Gauge, to: "/benchmarks" },
{ id: "platform", group: "power", name: "Platform & roadmap", subtitle: "desktop · what's coming", icon: Monitor, to: "/platform" },
{ id: "team", group: "power", name: "Team governance", subtitle: "rules · permissions · oversight", icon: Shield, to: "/team", minBillingRank: TEAMS_RANK },
];
const gate = (items: CatalogCommand[]): CatalogCommand[] =>
items.filter((i) => i.minBillingRank === undefined || billingRank >= i.minBillingRank);
const groups: CatalogGroup[] = [];
if (isPro) {
const pinnedItems = [...jump, ...doGroup, ...power]
.filter((i) => i.pinned && (i.minBillingRank === undefined || billingRank >= i.minBillingRank))
.filter((i) => i.pinned)
.map((i) => ({ ...i, id: `pin-${i.id}`, group: "pinned" as const }));
if (pinnedItems.length > 0) {
groups.push({ key: "pinned", heading: "Pinned", items: pinnedItems });
}
}
groups.push({ key: "jump", heading: "Jump to", items: gate(jump) });
groups.push({ key: "do", heading: "Do", items: gate(doGroup) });
groups.push({ key: "power", heading: "Power tools", items: gate(power) });
groups.push({ key: "jump", heading: "Jump to", items: jump });
groups.push({ key: "do", heading: "Do", items: doGroup });
groups.push({ key: "power", heading: "Power tools", items: power });
return groups;
}

View File

@@ -19,8 +19,6 @@ export type AppId =
export type UserTier = 'simple' | 'professional' | 'power' | 'admin';
export type BillingTier = 'TRIAL' | 'FREE' | 'TEAMS' | 'ENTERPRISE';
export interface DockEntry {
type: 'app' | 'zone-parent' | 'separator';
key: string;
@@ -29,12 +27,6 @@ export interface DockEntry {
label: string;
color?: string;
children?: DockEntry[];
/**
* Minimum billing tier required to see this entry.
* If the user's tier is below this, the entry is hidden from the dock.
* Undefined = always visible.
*/
minBillingTier?: BillingTier;
/**
* UX Refactor v2.1 P1a (conversion plan §1.3): the entry's canonical URL —
* the appId→route table the AppShell left nav navigates by and prefix-matches
@@ -51,14 +43,10 @@ export interface DockEntry {
description?: string;
}
export const BILLING_TIER_ORDER: Record<BillingTier, number> = {
FREE: 0, TRIAL: 1, TEAMS: 2, ENTERPRISE: 3,
};
export const DEFAULT_TIER: UserTier = 'simple';
// UX-Refactor Phase 0 (S00 §4b): the power dock expresses the PRD §10 IA layers —
// Work (flat primary spine) + Intelligence / Extend / Team / System zone-parents.
// Work (flat primary spine) + Intelligence / Extend / System zone-parents.
// The Command Center (Ctrl+K) lives in the StatusBar, not the dock. Grouping is data-only; the
// Dock renders zone-parents generically off entry.type/entry.key.
const POWER_CONFIG: DockEntry[] = [
@@ -78,8 +66,7 @@ const POWER_CONFIG: DockEntry[] = [
{ 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' },
// Approvals: TEAMS-tier trust/audit surface (Pro gets inline chat approvals).
{ type: 'app', key: 'approvals', appId: 'approvals', icon: Shield, label: 'Approvals', color: 'text-amber-400', minBillingTier: 'TEAMS', route: '/approvals', description: 'Review and approve actions your agents want to take' },
{ type: 'app', key: 'approvals', appId: 'approvals', icon: Shield, label: 'Approvals', color: 'text-amber-400', route: '/approvals', description: 'Review and approve actions your agents want to take' },
],
},
// ── Extend ──
@@ -93,13 +80,6 @@ const POWER_CONFIG: DockEntry[] = [
{ type: 'app', key: 'launcher', appId: 'launcher', icon: Rocket, label: 'AI Tools', color: 'text-amber-400', route: '/launcher', description: 'Launch other AI tools you use, linked to Waggle' },
],
},
// ── Team (TEAMS-tier; whole zone hidden below TEAMS) ──
{
type: 'zone-parent', key: 'team', icon: Users, label: 'Team', color: 'text-violet-400', minBillingTier: 'TEAMS', description: 'Shared workspaces and team controls',
children: [
{ type: 'app', key: 'governance', appId: 'governance', icon: Shield, label: 'Team Governance', color: 'text-violet-400', minBillingTier: 'TEAMS', route: '/team', description: 'Team rules, permissions, and oversight' },
],
},
{ type: 'separator', key: 'sep-system', label: '' },
// ── System ──
{
@@ -145,27 +125,6 @@ export const TIER_DOCK_CONFIG: Record<UserTier, DockEntry[]> = {
admin: POWER_CONFIG,
};
/**
* Recursively filter out entries whose minBillingTier exceeds the user's tier.
* Zone parents with no remaining children are also removed.
*/
function filterByBillingTier(entries: DockEntry[], billingTier: BillingTier): DockEntry[] {
const userRank = BILLING_TIER_ORDER[billingTier] ?? 0;
const out: DockEntry[] = [];
for (const e of entries) {
if (e.minBillingTier && BILLING_TIER_ORDER[e.minBillingTier] > userRank) continue;
if (e.type === 'zone-parent' && e.children) {
const kids = filterByBillingTier(e.children, billingTier);
if (kids.length === 0) continue;
out.push({ ...e, children: kids });
} else {
out.push(e);
}
}
return out;
}
export function getDockForTier(tier: UserTier, billingTier: BillingTier = 'FREE'): DockEntry[] {
const base = TIER_DOCK_CONFIG[tier] ?? TIER_DOCK_CONFIG[DEFAULT_TIER];
return filterByBillingTier(base, billingTier);
export function getDockForTier(tier: UserTier): DockEntry[] {
return TIER_DOCK_CONFIG[tier] ?? TIER_DOCK_CONFIG[DEFAULT_TIER];
}

View File

@@ -231,8 +231,8 @@ export function fromMcpCatalogRow(row: McpCatalogRow): Extension {
installed: row.installed,
lifecycle: lifecycle(row.installed),
// PR4 D3: enableable in-place — installMcp still rides the real
// SecurityGate + PRO gate server-side; the Hub deep-link stays for
// managing running servers.
// SecurityGate server-side; the Hub deep-link stays for managing
// running servers.
installable: true,
kind: 'federated',
category: row.category,

View File

@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { rawId, isTogglable, describeError, isTierError } from './install-store';
import { rawId, isTogglable, describeError } from './install-store';
describe('rawId', () => {
it('strips the namespace prefix', () => {
@@ -43,15 +43,3 @@ describe('describeError', () => {
expect(describeError(undefined)).toBe('Server unreachable');
});
});
describe('isTierError', () => {
it('is true for a 403 with the TIER_INSUFFICIENT marker', () => {
expect(isTierError({ status: 403, body: { error: 'TIER_INSUFFICIENT' } })).toBe(true);
});
it('is false for other 403s, other statuses, and non-errors', () => {
expect(isTierError({ status: 403, body: { error: 'blocked' } })).toBe(false);
expect(isTierError({ status: 500, body: { error: 'TIER_INSUFFICIENT' } })).toBe(false);
expect(isTierError(new Error('boom'))).toBe(false);
expect(isTierError(undefined)).toBe(false);
});
});

View File

@@ -28,7 +28,6 @@ export interface InstallTarget {
/** Why an install attempt did not succeed (drives the caller's follow-up UI). */
export type InstallReason =
| 'tier' // PRO required — the adapter already dispatched waggle:tier-insufficient
| 'security' // SecurityGate blocked / requires approval
| 'error' // network / server / unknown failure (toast already shown)
| 'needs-credentials' // connector needs a token the caller did not supply (card collects it / OAuth → Hub)
@@ -72,10 +71,3 @@ export function describeError(e: unknown): string {
return 'Server unreachable';
}
/** A thrown AdapterHttpError that is a 403 tier rejection (the adapter has
* already dispatched waggle:tier-insufficient). The connector connect path
* throws (vs the fetchRaw install paths whose tier body is inspected inline). */
export function isTierError(e: unknown): boolean {
const err = e as { status?: number; body?: { error?: unknown } } | undefined;
return err?.status === 403 && err?.body?.error === 'TIER_INSUFFICIENT';
}

View File

@@ -3,17 +3,9 @@
*
* Spec: docs/ux-disclosure-levels.md r2 §"Settings app — filter sections per tier".
* Mapping live SettingsApp tabs to spec buckets:
* - general / models / billing → Essential (always)
* - permissions / team / backup / advanced → Standard+
* - enterprise (compliance + governance) → Power only
*
* Notes:
* - billing tab visibility within Essential is gated separately by user's
* billing tier (Trial/Pro/Teams) — that's a render-side concern in SettingsApp,
* not the dock-tier filter. This helper only handles the UserTier (dock-tier)
* dimension.
* - team tab has its own LOCKED_TABS gate for non-TEAMS billing tiers — that's
* a separate layer, also not this helper's job.
* - general / models → Essential (always)
* - permissions / channels / backup → Standard+
* - advanced → Power only (PR5 D7)
*/
import { describe, it, expect } from 'vitest';
import {
@@ -27,69 +19,76 @@ import {
const ALL_TABS = [
{ id: 'general' },
{ id: 'models' },
{ id: 'billing' },
{ id: 'permissions' },
{ id: 'team' },
{ id: 'channels' },
{ id: 'backup' },
{ id: 'enterprise' },
{ id: 'advanced' },
] as const;
describe('ESSENTIAL_SETTINGS_TAB_IDS', () => {
it('contains exactly 3 IDs: general, models, billing', () => {
expect(ESSENTIAL_SETTINGS_TAB_IDS).toEqual(['general', 'models', 'billing']);
it('contains exactly 2 IDs: general, models', () => {
expect(ESSENTIAL_SETTINGS_TAB_IDS).toEqual(['general', 'models']);
});
it('does NOT include any operational/advanced tabs', () => {
for (const id of ['permissions', 'team', 'backup', 'enterprise', 'advanced']) {
for (const id of ['permissions', 'channels', 'backup', 'advanced']) {
expect(ESSENTIAL_SETTINGS_TAB_IDS).not.toContain(id);
}
});
});
describe('STANDARD_SETTINGS_TAB_IDS', () => {
it('extends Essential with operational tabs (no enterprise, no advanced)', () => {
it('extends Essential with operational tabs (no advanced)', () => {
expect(STANDARD_SETTINGS_TAB_IDS).toEqual([
'general', 'models', 'billing',
'permissions', 'channels', 'team', 'backup',
'general', 'models',
'permissions', 'channels', 'backup',
]);
});
it('does NOT include enterprise or advanced (both are Everything/Power-only)', () => {
expect(STANDARD_SETTINGS_TAB_IDS).not.toContain('enterprise');
it('does NOT include advanced (Everything/Power-only)', () => {
expect(STANDARD_SETTINGS_TAB_IDS).not.toContain('advanced'); // PR5 D7
});
});
describe('POWER_SETTINGS_TAB_IDS', () => {
it('includes all 9 tabs', () => {
expect(POWER_SETTINGS_TAB_IDS).toHaveLength(9);
it('includes all 6 tabs', () => {
expect(POWER_SETTINGS_TAB_IDS).toHaveLength(6);
for (const t of ALL_TABS) {
expect(POWER_SETTINGS_TAB_IDS).toContain(t.id);
}
});
});
describe('removed plan / team / enterprise tabs', () => {
it('no disclosure level lists billing, team or enterprise', () => {
for (const id of ['billing', 'team', 'enterprise']) {
expect(ESSENTIAL_SETTINGS_TAB_IDS).not.toContain(id);
expect(STANDARD_SETTINGS_TAB_IDS).not.toContain(id);
expect(POWER_SETTINGS_TAB_IDS).not.toContain(id);
}
});
});
describe('getSettingsTabsForTier', () => {
it('returns 3 essential tabs for simple tier', () => {
it('returns 2 essential tabs for simple tier', () => {
const result = getSettingsTabsForTier('simple', ALL_TABS);
expect(result.map(t => t.id)).toEqual(['general', 'models', 'billing']);
expect(result.map(t => t.id)).toEqual(['general', 'models']);
});
it('returns 6 standard tabs for professional tier (no enterprise, no advanced)', () => {
it('returns 5 standard tabs for professional tier (no advanced)', () => {
const result = getSettingsTabsForTier('professional', ALL_TABS);
expect(result.map(t => t.id)).toEqual([
'general', 'models', 'billing',
'permissions', 'team', 'backup',
'general', 'models',
'permissions', 'channels', 'backup',
]);
});
it('returns all 8 tabs for power tier', () => {
it('returns all 6 tabs for power tier', () => {
const result = getSettingsTabsForTier('power', ALL_TABS);
expect(result.length).toBe(ALL_TABS.length);
});
it('returns all 8 tabs for admin tier (admin = power in TIER_DOCK_CONFIG)', () => {
it('returns all 6 tabs for admin tier (admin = power in TIER_DOCK_CONFIG)', () => {
const result = getSettingsTabsForTier('admin', ALL_TABS);
expect(result.length).toBe(ALL_TABS.length);
});
@@ -97,13 +96,12 @@ describe('getSettingsTabsForTier', () => {
it('preserves the input ordering (not the spec-list ordering)', () => {
// Reorder input — output should follow input order, not the constant's order
const reordered = [
{ id: 'billing' },
{ id: 'general' },
{ id: 'models' },
{ id: 'enterprise' },
{ id: 'general' },
{ id: 'advanced' },
];
const result = getSettingsTabsForTier('simple', reordered);
expect(result.map(t => t.id)).toEqual(['billing', 'general', 'models']);
expect(result.map(t => t.id)).toEqual(['models', 'general']);
});
it('handles empty input gracefully', () => {
@@ -145,14 +143,9 @@ describe('resolveActiveSettingsTab', () => {
expect(result).toBe('general');
});
it('preserves enterprise when on power tier', () => {
const result = resolveActiveSettingsTab('power', 'enterprise', ALL_TABS);
expect(result).toBe('enterprise');
});
it('drops enterprise when on professional tier (Power-only tab)', () => {
const result = resolveActiveSettingsTab('professional', 'enterprise', ALL_TABS);
expect(result).toBe('general');
it('preserves advanced when on power tier', () => {
const result = resolveActiveSettingsTab('power', 'advanced', ALL_TABS);
expect(result).toBe('advanced');
});
it('drops advanced when on professional tier (PR5 D7: Everything-only)', () => {
@@ -162,7 +155,7 @@ describe('resolveActiveSettingsTab', () => {
it('falls back to first visible tab when general itself is hidden (defensive)', () => {
// If `tabs` array is reordered or shrunk to exclude general, fall back to first
const noGeneral = [{ id: 'models' }, { id: 'billing' }];
const noGeneral = [{ id: 'models' }, { id: 'backup' }];
const result = resolveActiveSettingsTab('simple', 'permissions', noGeneral);
expect(result).toBe('models');
});

View File

@@ -3,10 +3,8 @@
*
* Source spec: `docs/ux-disclosure-levels.md` r2 §"Settings app — filter sections per tier".
*
* Maps the 8 SettingsApp tabs (general / models / billing / permissions / team /
* backup / enterprise / advanced) to the 3-level UX disclosure system. The
* `team` tab additionally gates on billing tier (TEAMS-only) via SettingsApp's
* own LOCKED_TABS map — that's a separate layer this helper doesn't touch.
* Maps the 6 SettingsApp tabs (general / models / permissions / channels /
* backup / advanced) to the 3-level UX disclosure system.
*
* Design choice: power-tier surfaces unknown tab IDs by default. If a future
* tab is added to SettingsApp without updating this filter, a power user (the
@@ -15,32 +13,28 @@
*/
import type { UserTier } from '@/lib/dock-tiers';
/** 3 tabs visible at Essential — clean and focused. */
/** 2 tabs visible at Essential — clean and focused. */
export const ESSENTIAL_SETTINGS_TAB_IDS = [
'general', // Profile + Display + dock-experience selector + theme
'models', // Provider, API key, default/fallback model, daily budget
'billing', // Trial / Pro / Teams subscription (visibility within depends on user's billing tier)
] as const;
/** 7 tabs visible at Standard — Essential + workspace ops. */
/** 5 tabs visible at Standard — Essential + workspace ops. */
export const STANDARD_SETTINGS_TAB_IDS = [
...ESSENTIAL_SETTINGS_TAB_IDS,
'permissions', // Default autonomy + external gates (Tools surface)
'channels', // IM channels (Slack/Telegram/WhatsApp/Discord) — CHANNELS-ARC P4
'team', // Team Sync URL + token (still gated by billing TEAMS LOCKED_TABS layer)
'backup', // Memory backup + restore
] as const;
/**
* All 8 tabs visible at Power — full access. PR5 D7: `advanced` (MCP servers +
* All 6 tabs visible at Power — full access. PR5 D7: `advanced` (MCP servers +
* dev mode + telemetry export) moves here from Standard so Standard stays calm —
* "depth when you ask for it" (Everything/Power only). `enterprise` was already
* Power-only.
* "depth when you ask for it" (Everything/Power only).
*/
export const POWER_SETTINGS_TAB_IDS = [
...STANDARD_SETTINGS_TAB_IDS,
'advanced', // MCP servers + dev mode + telemetry export (D7: Everything-only)
'enterprise', // Compliance + audit trail + governance (gated by feature flag too)
] as const;
const ESSENTIAL_SET = new Set<string>(ESSENTIAL_SETTINGS_TAB_IDS);
@@ -51,8 +45,8 @@ const STANDARD_SET = new Set<string>(STANDARD_SETTINGS_TAB_IDS);
* Filter a tab list to those visible at the given tier. Preserves input ordering
* so callers don't lose their array sort.
*
* - `simple` → 3 essentials only
* - `professional` → 6 standard tabs (Advanced is Everything-only per D7)
* - `simple` → 2 essentials only
* - `professional` → 5 standard tabs (Advanced is Everything-only per D7)
* - `power` / `admin` → all input tabs (including unknowns — least-surprise)
*/
export function getSettingsTabsForTier<T extends { id: string }>(

View File

@@ -1,208 +0,0 @@
/**
* Trial countdown + tier resolution tests for @waggle/shared/tiers.
*
* Tests the helpers that drive: StatusBar countdown badge (Desktop.tsx:413),
* TrialExpiredModal trigger (Desktop.tsx:137), and server tier resolution
* (settings.ts:315 + assert-tier.ts:28).
*
* Infrastructure was discovered fully wired during 0507_s2:
* - tiers.ts:191 isTrialExpired — test
* - tiers.ts:201 getEffectiveTier — test
* - tiers.ts:207 trialDaysRemaining — test
* - tiers.ts:198 TRIAL_DURATION_DAYS — pin to 15
*
* These guard against future drift (e.g. someone bumping TRIAL_DURATION_DAYS
* without intent, or breaking TRIAL→FREE downgrade).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
isTrialExpired,
getEffectiveTier,
trialDaysRemaining,
parseTier,
TRIAL_DURATION_DAYS,
} from '@waggle/shared';
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
// Fixed reference time so we don't rely on Date.now() drift mid-test
const NOW_ISO = '2026-05-07T16:00:00.000Z';
const NOW_MS = new Date(NOW_ISO).getTime();
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date(NOW_ISO));
});
afterEach(() => {
vi.useRealTimers();
});
describe('parseTier (Solo/Team migration)', () => {
it('maps legacy PRO → FREE (Solo) — never null, never a lockout for a legacy sub', () => {
expect(parseTier('PRO')).toBe('FREE');
expect(parseTier('pro')).toBe('FREE');
});
it('maps legacy basic → FREE and preserves the canonical names', () => {
expect(parseTier('basic')).toBe('FREE');
expect(parseTier('FREE')).toBe('FREE');
expect(parseTier('TEAMS')).toBe('TEAMS');
expect(parseTier('ENTERPRISE')).toBe('ENTERPRISE');
});
});
describe('TRIAL_DURATION_DAYS', () => {
it('is exactly 15 days (pricing canon — packages/shared/src/tiers.ts:23)', () => {
expect(TRIAL_DURATION_DAYS).toBe(15);
});
});
describe('isTrialExpired', () => {
it('returns true for null / undefined / empty input', () => {
expect(isTrialExpired(null)).toBe(true);
expect(isTrialExpired(undefined)).toBe(true);
expect(isTrialExpired('')).toBe(true);
});
it('returns true for unparseable timestamps', () => {
expect(isTrialExpired('not-a-date')).toBe(true);
expect(isTrialExpired('2026-13-99')).toBe(true);
});
it('returns false for trial that started today', () => {
expect(isTrialExpired(NOW_ISO)).toBe(false);
});
it('returns false at day 14 (still within 15-day window)', () => {
const fourteenDaysAgo = new Date(NOW_MS - 14 * ONE_DAY_MS).toISOString();
expect(isTrialExpired(fourteenDaysAgo)).toBe(false);
});
it('returns false at day 15 boundary (still within window)', () => {
// Exactly 15 days: elapsed === 15*ONE_DAY, which is NOT > 15*ONE_DAY → false
const fifteenDaysAgo = new Date(NOW_MS - 15 * ONE_DAY_MS).toISOString();
expect(isTrialExpired(fifteenDaysAgo)).toBe(false);
});
it('returns true at day 15 + 1ms (just over the boundary)', () => {
const justOver = new Date(NOW_MS - (15 * ONE_DAY_MS + 1)).toISOString();
expect(isTrialExpired(justOver)).toBe(true);
});
it('returns true after 30 days', () => {
const thirtyDaysAgo = new Date(NOW_MS - 30 * ONE_DAY_MS).toISOString();
expect(isTrialExpired(thirtyDaysAgo)).toBe(true);
});
});
describe('getEffectiveTier', () => {
it('passes FREE through unchanged regardless of trialStartedAt', () => {
expect(getEffectiveTier('FREE', null)).toBe('FREE');
expect(getEffectiveTier('FREE', NOW_ISO)).toBe('FREE');
});
it('passes TEAMS through unchanged', () => {
expect(getEffectiveTier('TEAMS', null)).toBe('TEAMS');
});
it('passes ENTERPRISE through unchanged', () => {
expect(getEffectiveTier('ENTERPRISE', null)).toBe('ENTERPRISE');
});
it('keeps TRIAL active when started today', () => {
expect(getEffectiveTier('TRIAL', NOW_ISO)).toBe('TRIAL');
});
it('keeps TRIAL active at day 14 (still within window)', () => {
const fourteenDaysAgo = new Date(NOW_MS - 14 * ONE_DAY_MS).toISOString();
expect(getEffectiveTier('TRIAL', fourteenDaysAgo)).toBe('TRIAL');
});
it('downgrades TRIAL → FREE when expired', () => {
const sixteenDaysAgo = new Date(NOW_MS - 16 * ONE_DAY_MS).toISOString();
expect(getEffectiveTier('TRIAL', sixteenDaysAgo)).toBe('FREE');
});
it('downgrades TRIAL → FREE when trialStartedAt is null (never started but stuck on TRIAL)', () => {
expect(getEffectiveTier('TRIAL', null)).toBe('FREE');
});
it('downgrades TRIAL → FREE when trialStartedAt is undefined', () => {
expect(getEffectiveTier('TRIAL', undefined)).toBe('FREE');
});
});
describe('trialDaysRemaining', () => {
it('returns 0 for null / undefined input', () => {
expect(trialDaysRemaining(null)).toBe(0);
expect(trialDaysRemaining(undefined)).toBe(0);
});
it('returns 0 for unparseable timestamps', () => {
expect(trialDaysRemaining('not-a-date')).toBe(0);
});
it('returns 15 for trial that started today (day 0)', () => {
// 15 - 0 = 15. Math.ceil(15) = 15.
expect(trialDaysRemaining(NOW_ISO)).toBe(15);
});
it('returns 14 for trial that started 1 day ago (using ceil)', () => {
// elapsed = 1 day → remaining = 15 - 1 = 14 → ceil(14) = 14
const oneDayAgo = new Date(NOW_MS - ONE_DAY_MS).toISOString();
expect(trialDaysRemaining(oneDayAgo)).toBe(14);
});
it('returns 1 at day 14 (final day showing as "1d left")', () => {
// elapsed = 14 days → remaining = 1.0 → ceil(1) = 1
const fourteenDaysAgo = new Date(NOW_MS - 14 * ONE_DAY_MS).toISOString();
expect(trialDaysRemaining(fourteenDaysAgo)).toBe(1);
});
it('returns 0 once expired', () => {
const sixteenDaysAgo = new Date(NOW_MS - 16 * ONE_DAY_MS).toISOString();
expect(trialDaysRemaining(sixteenDaysAgo)).toBe(0);
});
it('returns 0 (not negative) for arbitrarily-old trials', () => {
const longAgo = new Date(NOW_MS - 365 * ONE_DAY_MS).toISOString();
expect(trialDaysRemaining(longAgo)).toBe(0);
});
it('rounds UP via Math.ceil (mid-day reads as the higher number — friendlier UX)', () => {
// 12.5 hours into trial → elapsed = 0.52 days → remaining = 14.48 → ceil = 15
const halfDayAgo = new Date(NOW_MS - 12.5 * 60 * 60 * 1000).toISOString();
expect(trialDaysRemaining(halfDayAgo)).toBe(15);
});
});
describe('integration — StatusBar badge color thresholds (UX contract)', () => {
it('day 4 trial → countdown shows in primary (>3 days, "still safe" feel)', () => {
// StatusBar.tsx:88 — trialDays > 3 ? primary : destructive
const elevenDaysAgo = new Date(NOW_MS - 11 * ONE_DAY_MS).toISOString();
const days = trialDaysRemaining(elevenDaysAgo);
expect(days).toBe(4);
expect(days > 3).toBe(true); // primary color path
});
it('day 3 trial → countdown shows in destructive ("act soon" red)', () => {
const twelveDaysAgo = new Date(NOW_MS - 12 * ONE_DAY_MS).toISOString();
const days = trialDaysRemaining(twelveDaysAgo);
expect(days).toBe(3);
expect(days <= 3).toBe(true); // destructive color path
});
it('day 1 trial → countdown shows in destructive (final day urgency)', () => {
const fourteenDaysAgo = new Date(NOW_MS - 14 * ONE_DAY_MS).toISOString();
const days = trialDaysRemaining(fourteenDaysAgo);
expect(days).toBe(1);
expect(days <= 3).toBe(true);
});
it('expired trial → countdown badge hidden (days === 0), expired badge shown instead', () => {
// StatusBar.tsx:87 — `trialDays > 0` gates the countdown badge
const sixteenDaysAgo = new Date(NOW_MS - 16 * ONE_DAY_MS).toISOString();
expect(trialDaysRemaining(sixteenDaysAgo)).toBe(0);
expect(isTrialExpired(sixteenDaysAgo)).toBe(true);
});
});

View File

@@ -1,127 +0,0 @@
/**
* F1 — TrialExpiredModal auto-open gate regression.
*
* Pins the pure decision (never over/under the wizard, once per session, the
* post-onboarding quiet window, the weekly snooze) and the localStorage
* accessors' NaN/garbage guards.
*/
import { describe, it, expect, beforeEach } from 'vitest';
import {
shouldAutoOpenTrialModal,
readTrialModalLastAutoOpenedAt,
writeTrialModalLastAutoOpenedAt,
readOnboardingCompletionSnapshot,
TRIAL_MODAL_LAST_AUTO_OPENED_AT_KEY,
ONBOARDING_STORAGE_KEY,
type TrialModalGateInput,
} from './trial-expired-gate';
const NOW = new Date('2026-07-04T12:00:00.000Z').getTime();
const MIN = 60 * 1000;
const DAY = 24 * 60 * 60 * 1000;
/** A baseline input that DOES auto-open; each case overrides one field. */
function base(overrides: Partial<TrialModalGateInput> = {}): TrialModalGateInput {
return {
trialExpired: true,
onboardingCompleted: true,
briefingOpen: false,
lastAutoOpenedAt: null,
onboardingCompletedAt: null,
shownThisSession: false,
now: NOW,
...overrides,
};
}
describe('shouldAutoOpenTrialModal', () => {
it('opens when trial expired, onboarding done, and no snooze/quiet/session guard trips', () => {
expect(shouldAutoOpenTrialModal(base())).toBe(true);
});
it('never opens when the trial is not expired', () => {
expect(shouldAutoOpenTrialModal(base({ trialExpired: false }))).toBe(false);
});
it('never opens before onboarding is completed', () => {
expect(shouldAutoOpenTrialModal(base({ onboardingCompleted: false }))).toBe(false);
});
it('never opens twice in one page-load session', () => {
expect(shouldAutoOpenTrialModal(base({ shownThisSession: true }))).toBe(false);
});
it('defers while the login briefing is showing (no stack)', () => {
expect(shouldAutoOpenTrialModal(base({ briefingOpen: true }))).toBe(false);
});
it('suppresses during the post-onboarding quiet window (9 min ago)', () => {
expect(shouldAutoOpenTrialModal(base({ onboardingCompletedAt: NOW - 9 * MIN }))).toBe(false);
});
it('allows after the post-onboarding quiet window (11 min ago)', () => {
expect(shouldAutoOpenTrialModal(base({ onboardingCompletedAt: NOW - 11 * MIN }))).toBe(true);
});
it('suppresses within the weekly snooze (6 days ago)', () => {
expect(shouldAutoOpenTrialModal(base({ lastAutoOpenedAt: NOW - 6 * DAY }))).toBe(false);
});
it('allows after the weekly snooze lapses (8 days ago)', () => {
expect(shouldAutoOpenTrialModal(base({ lastAutoOpenedAt: NOW - 8 * DAY }))).toBe(true);
});
it('legacy profile (both timestamps null) opens — no quiet period, no snooze', () => {
expect(shouldAutoOpenTrialModal(base({ onboardingCompletedAt: null, lastAutoOpenedAt: null }))).toBe(true);
});
});
describe('readTrialModalLastAutoOpenedAt / writeTrialModalLastAutoOpenedAt', () => {
beforeEach(() => {
window.localStorage.removeItem(TRIAL_MODAL_LAST_AUTO_OPENED_AT_KEY);
});
it('returns null when never written', () => {
expect(readTrialModalLastAutoOpenedAt()).toBe(null);
});
it('round-trips an epoch-ms timestamp', () => {
writeTrialModalLastAutoOpenedAt(NOW);
expect(readTrialModalLastAutoOpenedAt()).toBe(NOW);
});
it('returns null for a corrupt (non-numeric) stored value', () => {
window.localStorage.setItem(TRIAL_MODAL_LAST_AUTO_OPENED_AT_KEY, 'not-a-number');
expect(readTrialModalLastAutoOpenedAt()).toBe(null);
});
});
describe('readOnboardingCompletionSnapshot', () => {
beforeEach(() => {
window.localStorage.removeItem(ONBOARDING_STORAGE_KEY);
});
it('returns not-completed when nothing is stored', () => {
expect(readOnboardingCompletionSnapshot()).toEqual({ completed: false, completedAt: null });
});
it('reads completed + completedAt from the onboarding blob', () => {
window.localStorage.setItem(ONBOARDING_STORAGE_KEY, JSON.stringify({ completed: true, completedAt: NOW }));
expect(readOnboardingCompletionSnapshot()).toEqual({ completed: true, completedAt: NOW });
});
it('completed:true without completedAt reads completedAt=null (legacy/E2E)', () => {
window.localStorage.setItem(ONBOARDING_STORAGE_KEY, JSON.stringify({ completed: true }));
expect(readOnboardingCompletionSnapshot()).toEqual({ completed: true, completedAt: null });
});
it('returns not-completed on garbage JSON', () => {
window.localStorage.setItem(ONBOARDING_STORAGE_KEY, '{not json');
expect(readOnboardingCompletionSnapshot()).toEqual({ completed: false, completedAt: null });
});
it('ignores a non-finite completedAt', () => {
window.localStorage.setItem(ONBOARDING_STORAGE_KEY, JSON.stringify({ completed: true, completedAt: 'soon' }));
expect(readOnboardingCompletionSnapshot()).toEqual({ completed: true, completedAt: null });
});
});

View File

@@ -1,121 +0,0 @@
/**
* TrialExpiredModal auto-open gating (F1).
*
* The paywall modal used to auto-open on EVERY successful getTier() that
* reported `trialExpired`, and refreshTier runs on every provider mount (full
* page load), after both startTrial() paths (including immediately after the
* onboarding wizard finishes), and on focus/visibility/online/connect-settled
* revalidation — with dismissal never persisted. The result: the modal
* re-popped seconds after onboarding and on every navigation/refocus.
*
* This module mirrors login-briefing.ts: a pure decision function plus
* try/catch localStorage accessors. The gate collapses the auto-open to at
* most once per page-load session, suppresses it for a quiet window right after
* onboarding, and snoozes it for a week after it was last shown. Manual opens
* (StatusBar pill) intentionally bypass this gate.
*/
export const TRIAL_MODAL_LAST_AUTO_OPENED_AT_KEY = 'waggle:trial-expired-last-shown-at';
export const ONBOARDING_STORAGE_KEY = 'waggle:onboarding';
/** Snooze the auto-open for a week after it last fired. */
export const TRIAL_MODAL_SNOOZE_DAYS = 7;
/** Don't pop the paywall in the first minutes after the wizard completes. */
export const TRIAL_MODAL_POST_ONBOARDING_QUIET_MINUTES = 10;
const DAY_MS = 24 * 60 * 60 * 1000;
const MINUTE_MS = 60 * 1000;
export interface TrialModalGateInput {
/** Server says the trial has expired. */
trialExpired: boolean;
/** The onboarding wizard has been completed. */
onboardingCompleted: boolean;
/** The login-briefing modal is (or is about to be) showing this session.
* We never stack the paywall on top of it — defer WITHOUT stamping the
* snooze so a later session (once the briefing is dismissed) can show it. */
briefingOpen: boolean;
/** Epoch ms the modal was last auto-opened; null = never. */
lastAutoOpenedAt: number | null;
/** Epoch ms the wizard was completed; null = unknown/legacy. */
onboardingCompletedAt: number | null;
/** Modal already auto-opened in this page-load session. */
shownThisSession: boolean;
/** Current epoch ms. */
now: number;
}
/**
* Decide whether the trial-expired modal may auto-open now. Pure — all reads
* and writes are the caller's responsibility.
*/
export function shouldAutoOpenTrialModal(input: TrialModalGateInput): boolean {
if (!input.trialExpired) return false;
// Never overlay the paywall on top of / under the onboarding wizard.
if (!input.onboardingCompleted) return false;
// Never stack the paywall with the login briefing (same-load collision).
// Returning false here also skips the caller's snooze stamp, so this is a
// deferral — a later session shows the paywall once the briefing is gone.
if (input.briefingOpen) return false;
// Once per page-load session — covers post-dismissal re-fires from
// focus/visibility/online/connect-settled revalidation.
if (input.shownThisSession) return false;
// Quiet window right after finishing the wizard.
if (
input.onboardingCompletedAt != null &&
input.now - input.onboardingCompletedAt < TRIAL_MODAL_POST_ONBOARDING_QUIET_MINUTES * MINUTE_MS
) {
return false;
}
// Weekly snooze after the last auto-open.
if (
input.lastAutoOpenedAt != null &&
input.now - input.lastAutoOpenedAt < TRIAL_MODAL_SNOOZE_DAYS * DAY_MS
) {
return false;
}
return true;
}
/** Epoch ms the modal was last auto-opened, or null if never / unreadable. */
export function readTrialModalLastAutoOpenedAt(): number | null {
try {
const raw = window.localStorage.getItem(TRIAL_MODAL_LAST_AUTO_OPENED_AT_KEY);
if (!raw) return null;
const ts = Number(raw);
if (!Number.isFinite(ts)) return null;
return ts;
} catch {
return null;
}
}
/** Record "the modal auto-opened just now" for the weekly snooze. */
export function writeTrialModalLastAutoOpenedAt(now: number = Date.now()): void {
try {
window.localStorage.setItem(TRIAL_MODAL_LAST_AUTO_OPENED_AT_KEY, String(now));
} catch {
// no-op — storage disabled
}
}
/**
* Snapshot the onboarding completion flags straight from localStorage, so the
* []-dep refreshTier callback never closes over a stale onboarding state
* object. Returns `{ completed:false, completedAt:null }` on any read/parse
* failure (fail-closed: no auto-open).
*/
export function readOnboardingCompletionSnapshot(): { completed: boolean; completedAt: number | null } {
try {
const raw = window.localStorage.getItem(ONBOARDING_STORAGE_KEY);
if (!raw) return { completed: false, completedAt: null };
const parsed = JSON.parse(raw) as { completed?: unknown; completedAt?: unknown };
const completed = parsed.completed === true;
const ts = typeof parsed.completedAt === 'number' && Number.isFinite(parsed.completedAt)
? parsed.completedAt
: null;
return { completed, completedAt: ts };
} catch {
return { completed: false, completedAt: null };
}
}

View File

@@ -648,7 +648,7 @@ export interface Skill {
initiator?: 'agent' | 'user' | 'built-in';
source?: string;
/**
* §D2 skill-audit: the run-and-grade "verified" badge (PRO upgrade artifact).
* §D2 skill-audit: the run-and-grade "verified" badge.
* Present + true only when the audit loop confirmed the skill passed; confidence
* is the deciding grade 0–1, shown as a percentage on the card.
*/

View File

@@ -1,31 +0,0 @@
import { describe, it, expect } from 'vitest';
import { TIER_CAPABILITIES } from '@waggle/shared';
import { canCreateWorkspaceAtTier } from './workspace-limit';
describe('canCreateWorkspaceAtTier', () => {
it('FREE (Solo) is unlimited (workspaceLimit -1) — never blocks', () => {
// Solo/Team migration raised FREE to unlimited workspaces — the whole point.
expect(TIER_CAPABILITIES.FREE.workspaceLimit).toBe(-1);
expect(canCreateWorkspaceAtTier('FREE', 0)).toBe(true);
expect(canCreateWorkspaceAtTier('FREE', 999)).toBe(true);
});
it('TEAMS / ENTERPRISE / TRIAL are unlimited', () => {
for (const t of ['TEAMS', 'ENTERPRISE', 'TRIAL'] as const) {
expect(canCreateWorkspaceAtTier(t, 999)).toBe(true);
}
});
it('mirrors the server rule: blocks exactly when limit > 0 && currentCount >= limit', () => {
// The server (workspaces.ts) blocks when `limit > 0 && currentCount >= limit`.
// Every canonical tier is now unlimited (-1), so the helper must always allow —
// the negation formula still holds around every boundary.
for (const t of ['FREE', 'TEAMS', 'ENTERPRISE', 'TRIAL'] as const) {
const limit = TIER_CAPABILITIES[t].workspaceLimit;
for (let count = 0; count <= 8; count++) {
const serverWouldAllow = !(limit > 0 && count >= limit);
expect(canCreateWorkspaceAtTier(t, count)).toBe(serverWouldAllow);
}
}
});
});

View File

@@ -1,19 +0,0 @@
import { TIER_CAPABILITIES, type Tier } from '@waggle/shared';
/**
* Client-side workspace-creation gate — the exact mirror of the server rule in
* `packages/server/src/local/routes/workspaces.ts` (the authoritative check):
* a tier whose `workspaceLimit` is < 0 is unlimited; otherwise creation is
* blocked once `currentCount` reaches the limit.
*
* Why this exists: the dialog previously gated off a legacy onboarding-complexity
* flag that blocked Solo (FREE) at workspace #2 even though the server — reading the
* canonical `tiers.ts` — already allows Solo unlimited workspaces. The two disagreed,
* so the paywall fired when the backend would not actually reject. Keying the client
* off the same `TIER_CAPABILITIES.workspaceLimit` the server uses makes them agree by
* construction.
*/
export function canCreateWorkspaceAtTier(tier: Tier, currentCount: number): boolean {
const limit = TIER_CAPABILITIES[tier]?.workspaceLimit ?? -1;
return limit < 0 || currentCount < limit;
}

View File

@@ -12,8 +12,6 @@
* - Confirmed-success flip: an id enters `installed` only after the server
* confirms; it stays in `installing` (spinner) during the flight. A
* gate-rejected install therefore never appears in the count (PR4 §6).
* - The adapter's request() already dispatches waggle:tier-insufficient on a
* 403 TIER, so this store classifies tier but never re-fires the event.
*/
import {
createContext, useCallback, useContext, useEffect, useMemo, useRef, useState,
@@ -25,7 +23,7 @@ import { useToast } from '@/hooks/use-toast';
import { CONNECT_SETTLED_EVENT } from '@/hooks/useRevalidateOnError';
import type { MarketplacePackageRow } from '@/lib/extension-catalog';
import {
describeError, isTierError, isTogglable, rawId,
describeError, isTogglable, rawId,
type InstallCredentials, type InstallOutcome, type InstallTarget,
} from '@/lib/install-store';
@@ -188,9 +186,6 @@ export const InstallProvider = ({ children }: { children: ReactNode }) => {
toast({ title: 'Connected', description: `${target.name} is connected.` });
return { ok: true };
} catch (e) {
// A 403 tier rejection — the adapter already dispatched the upgrade
// event; classify as tier and don't toast over it.
if (isTierError(e)) return { ok: false, reason: 'tier' };
toast({ title: 'Connection failed', description: describeError(e), variant: 'destructive' });
return { ok: false, reason: 'error' };
} finally {
@@ -198,7 +193,7 @@ export const InstallProvider = ({ children }: { children: ReactNode }) => {
}
}
// CATALOG MCP — enable (PRO-gated; SecurityGate). Body envelope is load-bearing.
// CATALOG MCP — enable (SecurityGate). Body envelope is load-bearing.
if (target.kind === 'federated' && target.type === 'mcp') {
addInstalling(id);
try {
@@ -211,7 +206,6 @@ export const InstallProvider = ({ children }: { children: ReactNode }) => {
toast({ title: 'Enabled', description: `${target.name} is enabled.` });
return { ok: true };
}
if (result.error === 'TIER_INSUFFICIENT') return { ok: false, reason: 'tier' };
if (result.requiresApproval || result.blocked) {
toast({ title: 'Enable blocked', description: securityMessage(result), variant: 'destructive' });
return { ok: false, reason: 'security' };
@@ -226,7 +220,7 @@ export const InstallProvider = ({ children }: { children: ReactNode }) => {
}
}
// PACKAGE — marketplace install (PRO-gated; SecurityGate). RAW Response.
// PACKAGE — marketplace install (SecurityGate). RAW Response.
if (target.kind === 'package') {
if (target.packageId == null) return { ok: false, reason: 'unsupported' };
addInstalling(id);
@@ -240,9 +234,6 @@ export const InstallProvider = ({ children }: { children: ReactNode }) => {
const err = (await res.json().catch(() => ({}))) as {
error?: string; blocked?: boolean; severity?: string; message?: string;
};
// Only a real tier rejection is a tier outcome — the adapter already
// dispatched the upgrade event, so do not re-fire or toast it.
if (res.status === 403 && err.error === 'TIER_INSUFFICIENT') return { ok: false, reason: 'tier' };
if (err.blocked) {
toast({ title: 'Install blocked', description: securityMessage(err), variant: 'destructive' });
return { ok: false, reason: 'security' };

View File

@@ -35,7 +35,7 @@ export const ServiceProvider = ({ children }: { children: ReactNode }) => {
const mounted = useRef(true);
// P1b D3: every settlement (success or failure) is broadcast so errored
// Stage-B surfaces (tier, workspaces, briefing, …) revalidate without
// Stage-B surfaces (workspaces, briefing, …) revalidate without
// waiting for a focus event that never fires on an already-focused window.
// `force` bypasses the adapter's retained settled-success memo — without it
// a user-initiated reconnect after a sidecar death would silently no-op.

View File

@@ -8,7 +8,6 @@
* - useWorkspaces bundle (Desktop.tsx:119, flattened exactly as Desktop
* destructures it, incl. the `refresh` → `refreshWorkspaces` rename)
* - UI-complexity tier (Desktop.tsx:129)
* - billing tier + trial info + refreshTier (Desktop.tsx:141-158)
* - P4 default autonomy (Desktop.tsx:160-167 — consumed by the Stage-B
* ChatHost / useChatWidgetState, §4.2)
* - useNotifications / useOnboarding / useOfflineStatus / useAgentStatus
@@ -24,21 +23,9 @@
* Desktop.tsx itself is untouched at this stage; it keeps hosting its own
* copies until the Stage-C flip mounts AppShell.
*/
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react';
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
import { adapter } from '@/lib/adapter';
import {
shouldAutoOpenTrialModal,
readOnboardingCompletionSnapshot,
readTrialModalLastAutoOpenedAt,
writeTrialModalLastAutoOpenedAt,
} from '@/lib/trial-expired-gate';
import {
shouldShowLoginBriefing,
readLoginBriefingDismissed,
readMinutesSinceLastDismiss,
readSkipBriefingParam,
} from '@/lib/login-briefing';
import type { BillingTier, UserTier } from '@/lib/dock-tiers';
import type { UserTier } from '@/lib/dock-tiers';
import type { ContextRailTarget } from '@/components/os/overlays/ContextRail';
import { useWorkspaces } from '@/hooks/useWorkspaces';
import { useAgentStatus } from '@/hooks/useAgentStatus';
@@ -46,7 +33,6 @@ import { useNotifications } from '@/hooks/useNotifications';
import { useOnboarding } from '@/hooks/useOnboarding';
import { useOfflineStatus } from '@/hooks/useOfflineStatus';
import { useOverlayState } from '@/hooks/useOverlayState';
import { useRevalidateOnError } from '@/hooks/useRevalidateOnError';
type WorkspacesBundle = ReturnType<typeof useWorkspaces>;
type AgentStatusBundle = ReturnType<typeof useAgentStatus>;
@@ -54,11 +40,6 @@ type NotificationsBundle = ReturnType<typeof useNotifications>;
type OnboardingBundle = ReturnType<typeof useOnboarding>;
type OverlayBundle = ReturnType<typeof useOverlayState>;
export interface TrialInfo {
trialDaysRemaining?: number;
trialExpired?: boolean;
}
export interface ShellContextValue {
// ── Workspaces (Desktop.tsx:119) ──
workspaces: WorkspacesBundle['workspaces'];
@@ -78,18 +59,8 @@ export interface ShellContextValue {
* shelf stood in a time heuristic for it (Wave U Lane A) and a slow cold
* fetch could still flash the empty state between skeleton and grid. */
workspacesLoading: WorkspacesBundle['loading'];
// ── Tier (Desktop.tsx:129, 141-158) ──
// ── UI-complexity tier (Desktop.tsx:129) ──
currentTier: UserTier;
billingTier: BillingTier;
/** P1b D3-4: false until a getTier() round-trip SUCCEEDS. While false,
* billingTier's 'FREE' default is a fail-closed capability gate (nav
* hiding) — it must never be rendered as the user's actual plan. */
tierResolved: boolean;
tierError: string | null;
trialInfo: TrialInfo;
refreshTier: () => Promise<void>;
showTrialExpired: boolean;
setShowTrialExpired: (open: boolean) => void;
// ── P4 default autonomy (Desktop.tsx:160-167) ──
defaultAutonomy: 'normal' | 'trusted' | 'yolo';
// ── Notifications (Desktop.tsx:123) ──
@@ -131,73 +102,6 @@ export const ShellProvider = ({ children }: { children: ReactNode }) => {
const offline = useOfflineStatus();
const currentTier: UserTier = onboardingState.tier || 'simple';
// Trial info from backend (relocated from Desktop.tsx:141-158)
const [trialInfo, setTrialInfo] = useState<TrialInfo>({});
const [billingTier, setBillingTier] = useState<BillingTier>('FREE');
const [tierResolved, setTierResolved] = useState(false);
const [tierError, setTierError] = useState<string | null>(null);
const [showTrialExpired, setShowTrialExpired] = useState(false);
// F1: auto-open the paywall at most once per page-load session. The gate
// (localStorage-backed 7d snooze + post-onboarding quiet window) plus this
// ref make refreshTier's mount/focus/online/connect-settled re-runs harmless.
const trialModalShownThisSessionRef = useRef(false);
// Extracted so post-action paths (start-trial, post-checkout-redirect)
// can re-pull tier/trial state without duplicating the fetch+parse logic.
// P1b D3-4: getTier now THROWS on HTTP failure (adapter chokepoint), so the
// catch is the single failure path — it must touch NEITHER billingTier NOR
// trialInfo (a failed refresh used to actively reset a paying user to FREE
// and wipe the trial countdown). tierResolved flips true on ANY successful
// round-trip, even an unrecognized tier string — resolution is about the
// server answering, not the value parsing.
const refreshTier = useCallback(async () => {
try {
const data = await adapter.getTier();
setTrialInfo({ trialDaysRemaining: data.trialDaysRemaining, trialExpired: data.trialExpired });
const t = String(data.tier ?? 'FREE').toUpperCase();
// Legacy PRO subscriptions collapse to Solo (FREE) — decision 8: 'PRO'
// must never reach the dock's BillingTier union.
if (t === 'PRO') {
setBillingTier('FREE');
} else if (t === 'FREE' || t === 'TRIAL' || t === 'TEAMS' || t === 'ENTERPRISE') {
setBillingTier(t);
}
setTierResolved(true);
setTierError(null);
// F1: gate the auto-open. Reads flow through localStorage/refs so this
// []-dep callback never closes over stale onboarding state. Stamp at OPEN
// time (not dismiss) so a reload while the modal is up can't re-fire it.
if (data.trialExpired) {
const ob = readOnboardingCompletionSnapshot();
// Same snapshot useOverlayState uses to decide the briefing's initial
// visibility, so the paywall never auto-opens under a showing briefing.
const briefingOpen = shouldShowLoginBriefing({
skipBriefing: readSkipBriefingParam(),
permanentlyDismissed: readLoginBriefingDismissed(),
minutesSinceLastDismiss: readMinutesSinceLastDismiss(),
});
if (shouldAutoOpenTrialModal({
trialExpired: true,
onboardingCompleted: ob.completed,
onboardingCompletedAt: ob.completedAt,
briefingOpen,
lastAutoOpenedAt: readTrialModalLastAutoOpenedAt(),
shownThisSession: trialModalShownThisSessionRef.current,
now: Date.now(),
})) {
trialModalShownThisSessionRef.current = true;
writeTrialModalLastAutoOpenedAt();
setShowTrialExpired(true);
}
}
} catch (e) {
setTierError(e instanceof Error ? e.message : 'Tier lookup failed');
}
}, []);
useEffect(() => { refreshTier(); }, [refreshTier]);
// D3 plus-clause: an errored tier revalidates on focus/visibility/online
// and on connect-settled (the only signal on an already-focused desktop).
useRevalidateOnError(tierError !== null, refreshTier);
// P4: default autonomy inherited by new chat widgets (relocated from
// Desktop.tsx:160-167). Fetched once on mount; SettingsApp writes via
// /api/settings/permissions, so a flipped setting takes effect on the next
@@ -217,7 +121,7 @@ export const ShellProvider = ({ children }: { children: ReactNode }) => {
<ShellContext.Provider value={{
workspaces, activeWorkspace, activeWorkspaceId,
selectWorkspace, createWorkspace, patchWorkspace, deleteWorkspace, refreshWorkspaces, workspacesError, workspacesLoading,
currentTier, billingTier, tierResolved, tierError, trialInfo, refreshTier, showTrialExpired, setShowTrialExpired,
currentTier,
defaultAutonomy,
notifications, unreadCount, markRead, markAllRead,
onboardingState, updateOnboarding, completeOnboarding,

View File

@@ -1,8 +1,5 @@
/**
* P1a route wrapper — `/approvals` → ApprovalsApp (bare mount, Desktop.tsx:462).
* D5: route registered for everyone; the NAV entry carries minBillingTier
* 'TEAMS' exactly as the dock entry does (dock-tiers.ts) — tier-hidden, not
* stripped (§1.1).
*/
import ApprovalsApp from '@/components/os/apps/ApprovalsApp';
import SurfaceBoundary from './SurfaceBoundary';

View File

@@ -1,13 +0,0 @@
/** PR7a route wrapper — `/payment-success` → PaymentSuccessApp (post-Stripe-Checkout
* landing; `checkout.ts:42` success_url). AppShell child: the user is back inside the
* app after the hosted redirect. */
import PaymentSuccessApp from '@/components/os/apps/PaymentSuccessApp';
import SurfaceBoundary from './SurfaceBoundary';
const PaymentSuccessRoute = () => (
<SurfaceBoundary appName="Payment">
<PaymentSuccessApp />
</SurfaceBoundary>
);
export default PaymentSuccessRoute;

View File

@@ -1,7 +1,7 @@
/**
* P1a route wrapper — `/team` → TeamGovernanceApp (bare mount, Desktop.tsx:466).
* Reserved (§1.1): renders the legacy app for TEAMS+; FREE/PRO never see the
* nav zone (filterByBillingTier parity). No new Team work (D5).
* 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';

View File

@@ -15,11 +15,11 @@ import { ChatSlot } from '@/components/os/ChatHost';
import SurfaceBoundary from './SurfaceBoundary';
import { useShell } from '@/providers/ShellContext';
// The warm-Hive 6-tab bar + `tasks` (deep-link-reachable, not shown in the bar
// The warm-Hive 5-tab bar + `tasks` (deep-link-reachable, not shown in the bar
// — the Overview "Up next" card routes to it). Dropped Research/Timeline/
// Settings fall through to the overview default instead of an empty panel.
const WS_TABS: readonly WorkspaceTabId[] = [
'overview', 'chat', 'memory', 'artifacts', 'files', 'team', 'tasks',
'overview', 'chat', 'memory', 'artifacts', 'files', 'tasks',
];
const WorkspaceRoute = () => {

View File

@@ -57,7 +57,5 @@ export { default as UsageRoute } from './UsageRoute';
export { default as BenchmarkRoute } from './BenchmarkRoute';
export { default as PlatformRoute } from './PlatformRoute';
export { default as WorkspacesRoute } from './WorkspacesRoute';
// PR7a — post-Stripe-Checkout landing (success_url; checkout.ts:42)
export { default as PaymentSuccessRoute } from './PaymentSuccessRoute';
// PR7b — pre-shell /auth route (sibling outside AppShell)
export { default as AuthRoute } from './AuthRoute';

View File

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

View File

@@ -1,8 +1,8 @@
/**
* EmbeddingRoutingCard (steal #10) — provider picker + live status + reprobe.
* Verifies: tier-scoped options, key-gating (openai disabled without a key),
* reprobe calls the API, provider change persists + surfaces the restart hint,
* and the env-override state disables the picker.
* Verifies: every selectable provider is offered, key-gating (openai disabled
* without a key), reprobe calls the API, provider change persists + surfaces the
* restart hint, and the env-override state disables the picker.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';
@@ -35,12 +35,12 @@ const PROVIDERS = [
{ id: 'anthropic', name: 'Anthropic', hasKey: true, badge: null, keyUrl: null, requiresKey: true, models: [] },
];
async function renderCard(tier: 'FREE' | 'TEAMS' = 'FREE') {
async function renderCard() {
const { default: EmbeddingRoutingCard } = await import('@/components/os/EmbeddingRoutingCard');
const { TooltipProvider } = await import('@/components/ui/tooltip');
render(
<TooltipProvider>
<EmbeddingRoutingCard providers={PROVIDERS as never} tier={tier} />
<EmbeddingRoutingCard providers={PROVIDERS as never} />
</TooltipProvider>,
);
}
@@ -54,28 +54,20 @@ afterEach(() => { cleanup(); vi.clearAllMocks(); });
describe('EmbeddingRoutingCard', () => {
it('names the embeddings information control', async () => {
await renderCard('FREE');
await renderCard();
expect(screen.getByRole('button', { name: 'About memory embeddings' })).toBeInTheDocument();
});
it('renders the tier-allowed provider options (FREE has no litellm)', async () => {
await renderCard('FREE');
it('offers auto and every selectable provider, including litellm but never mock', async () => {
await renderCard();
const select = await screen.findByTestId('embedding-provider-select');
const values = Array.from(select.querySelectorAll('option')).map(o => (o as HTMLOptionElement).value);
expect(values).toEqual(expect.arrayContaining(['auto', 'inprocess', 'ollama', 'voyage', 'openai']));
expect(values).not.toContain('litellm');
expect(values).toEqual(['auto', 'inprocess', 'ollama', 'voyage', 'openai', 'litellm']);
expect(values).not.toContain('mock');
});
it('includes litellm on TEAMS', async () => {
await renderCard('TEAMS');
const select = await screen.findByTestId('embedding-provider-select');
const values = Array.from(select.querySelectorAll('option')).map(o => (o as HTMLOptionElement).value);
expect(values).toContain('litellm');
});
it('disables the openai option when its vault key is missing', async () => {
await renderCard('FREE');
await renderCard();
const select = await screen.findByTestId('embedding-provider-select');
const openai = Array.from(select.querySelectorAll('option')).find(
o => (o as HTMLOptionElement).value === 'openai',
@@ -84,18 +76,18 @@ describe('EmbeddingRoutingCard', () => {
});
it('shows the active provider from the status probe', async () => {
await renderCard('FREE');
await renderCard();
expect(await screen.findByTestId('embedding-active-provider')).toHaveTextContent(/mock/i);
});
it('Reprobe calls the API', async () => {
await renderCard('FREE');
await renderCard();
fireEvent.click(await screen.findByTestId('embedding-reprobe'));
await waitFor(() => expect(mocks.adapter.reprobeEmbedding).toHaveBeenCalledTimes(1));
});
it('changing the provider persists and surfaces the restart hint', async () => {
await renderCard('FREE');
await renderCard();
const select = await screen.findByTestId('embedding-provider-select');
fireEvent.change(select, { target: { value: 'inprocess' } });
await waitFor(() => expect(mocks.adapter.setEmbeddingProvider).toHaveBeenCalledWith('inprocess'));
@@ -104,7 +96,7 @@ describe('EmbeddingRoutingCard', () => {
it('disables the picker and hints when an env override is active', async () => {
mocks.adapter.getEmbeddingStatus.mockResolvedValue({ ...baseStatus, envOverride: true });
await renderCard('FREE');
await renderCard();
const select = await screen.findByTestId('embedding-provider-select');
expect((select as HTMLSelectElement).disabled).toBe(true);
expect(screen.getByTestId('embedding-env-hint')).toBeInTheDocument();

View File

@@ -67,8 +67,6 @@ const mocks = vi.hoisted(() => ({
selectWorkspace: vi.fn(),
createWorkspace: vi.fn(),
refreshWorkspaces: vi.fn(),
billingTier: 'FREE' as string,
tierResolved: true,
activeWorkspaceId: 'w1' as string | null,
setContextRailTarget: vi.fn(),
},

View File

@@ -212,7 +212,7 @@ describe('WorkspaceDesktopApp two-seam edit (§5.2, founder-ratified, test-pinne
/>,
);
// Tasks is reachable but NOT a bar tab in the warm-Hive 6-tab set, so a
// Tasks is reachable but NOT a bar tab in the warm-Hive 5-tab set, so a
// controlled activeTab='tasks' still renders the Tasks body (the seam is
// tab-agnostic) while no bar tab is selected.
expect(await screen.findByTestId('ws-tasks-tab')).toBeInTheDocument();

View File

@@ -229,13 +229,13 @@ describe('dock-tiers route field — §1.3 invariant', () => {
}
});
it('billing-tier filtering still applies to nav data (Approvals/Team hidden below TEAMS — D5)', () => {
const free = flattenAppEntries(getDockForTier('power', 'FREE'));
const teams = flattenAppEntries(getDockForTier('power', 'TEAMS'));
expect(free.some(e => e.appId === 'approvals')).toBe(false);
expect(free.some(e => e.appId === 'governance')).toBe(false);
expect(teams.some(e => e.appId === 'approvals')).toBe(true);
expect(teams.some(e => e.appId === 'governance')).toBe(true);
it('power nav shows Approvals to everyone and has no Team zone or Team Governance entry (ADR-0003)', () => {
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);
});
it('APP_ROUTES has no entry for the parameterized ids (function-not-record, §2.3)', () => {

View File

@@ -1,16 +1,11 @@
/**
* P1b D3 — Stage B boot-path surface contracts over a mocked adapter:
*
* - ShellContext tier: a failed getTier touches NEITHER billingTier NOR
* trialInfo (the severity-critical silent-FREE class), tierResolved stays
* false, and the tier revalidates on connect-settled.
* - useBilling: failure keeps tierResolved=false (Billing tab renders the
* unresolved state, never 'FREE' as fact).
* - useWorkspaces: failure sets the (previously dead) error channel, keeps
* a previously-good list, and recovers on connect-settled.
* - useChat: a thrown AdapterHttpError-shaped failure renders a status-true
* error block ('Backend is offline' reserved for network errors); the
* tier-403 copy defers to the UpgradeModal; empty-messages race guarded.
* error block ('Backend is offline' reserved for network errors);
* empty-messages race guarded.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act, waitFor, cleanup } from '@testing-library/react';
@@ -20,7 +15,6 @@ const mocks = vi.hoisted(() => ({
toast: vi.fn(),
adapter: {
connect: vi.fn().mockResolvedValue(undefined),
getTier: vi.fn(),
getWorkspaces: vi.fn(),
createWorkspace: vi.fn(),
getPermissions: vi.fn().mockResolvedValue({ defaultAutonomy: 'normal', externalGates: {} }),
@@ -37,7 +31,6 @@ const mocks = vi.hoisted(() => ({
fetchRaw: vi.fn(),
getSettings: vi.fn(),
getTelemetryStatus: vi.fn(),
getTeamStatus: vi.fn(),
getServerUrl: vi.fn(),
// PR5: Settings opens on the Models tab → ModelGate fetches these on mount.
getProviders: vi.fn(),
@@ -131,133 +124,6 @@ describe('useWorkspaces (P1b)', () => {
});
});
// ── useBilling ─────────────────────────────────────────────────────────────
describe('useBilling (P1b D3-4)', () => {
it('failure keeps tierResolved=false and surfaces the error — FREE default is never presented as fact', async () => {
const { useBilling } = await import('@/hooks/useBilling');
mocks.adapter.getTier.mockRejectedValue(httpError(401, {}, 'Unauthorized'));
const { result } = renderHook(() => useBilling());
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.tierResolved).toBe(false);
expect(result.current.error).toBe('Unauthorized');
});
it('connect-settled revalidates an unresolved tier to the real plan', async () => {
const { useBilling } = await import('@/hooks/useBilling');
mocks.adapter.getTier.mockRejectedValueOnce(httpError(401, {}, 'Unauthorized'));
const { result } = renderHook(() => useBilling());
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.tierResolved).toBe(false);
mocks.adapter.getTier.mockResolvedValue({ tier: 'TEAMS', capabilities: {}, usage: {} });
settleConnect();
await waitFor(() => expect(result.current.tierResolved).toBe(true));
expect(result.current.tier).toBe('TEAMS');
});
});
// ── ShellContext tier (the severity-critical silent-FREE class) ────────────
describe('ShellContext tier (P1b D3-4)', () => {
beforeEach(() => {
window.localStorage.clear();
});
async function renderShell() {
const { ShellProvider, useShell } = await import('@/providers/ShellContext');
const wrapper = ({ children }: { children: React.ReactNode }) => <ShellProvider>{children}</ShellProvider>;
return renderHook(() => useShell(), { wrapper });
}
/** Seed a completed-wizard onboarding blob so the trial gate's
* onboardingCompleted precondition is met. `completedAt` past the 10-min
* quiet window by default. */
function seedOnboardingCompleted(completedAt = Date.now() - 11 * 60_000) {
window.localStorage.setItem(
'waggle:onboarding',
JSON.stringify({ completed: true, step: 7, tier: 'power', completedAt }),
);
// Wave-3 modal coordination: the paywall defers while the login briefing
// is eligible to show. These tests exercise the paywall itself, so arrange
// a dismissed briefing (as a returning user who closed it would have).
window.localStorage.setItem('waggle:login-briefing-dismissed', 'true');
}
it('failed getTier touches neither billingTier nor trialInfo; tierResolved stays false', async () => {
mocks.adapter.getWorkspaces.mockResolvedValue([]);
mocks.adapter.getTier.mockRejectedValue(httpError(401, { code: 'MISSING_TOKEN' }, 'Unauthorized'));
const { result } = await renderShell();
await waitFor(() => expect(result.current.tierError).toBe('Unauthorized'));
expect(result.current.billingTier).toBe('FREE'); // fail-closed capability default…
expect(result.current.tierResolved).toBe(false); // …never presented as resolved fact
expect(result.current.trialInfo).toEqual({}); // trial countdown not clobbered
expect(result.current.showTrialExpired).toBe(false);
});
it('a paying user is not reset to FREE by a transient failure, and recovers on connect-settled', async () => {
mocks.adapter.getWorkspaces.mockResolvedValue([]);
mocks.adapter.getTier.mockResolvedValueOnce({
tier: 'TEAMS', trialDaysRemaining: undefined, trialExpired: false, capabilities: {}, usage: {},
});
const { result } = await renderShell();
await waitFor(() => expect(result.current.billingTier).toBe('TEAMS'));
expect(result.current.tierResolved).toBe(true);
// Transient failure (e.g. sidecar restart mid-refresh): state must hold.
mocks.adapter.getTier.mockRejectedValueOnce(httpError(401, {}, 'Unauthorized'));
await act(async () => { await result.current.refreshTier(); });
expect(result.current.billingTier).toBe('TEAMS');
expect(result.current.tierError).toBe('Unauthorized');
// Recovery: connect-settled revalidates while errored.
mocks.adapter.getTier.mockResolvedValue({ tier: 'TEAMS', capabilities: {}, usage: {} });
settleConnect();
await waitFor(() => expect(result.current.tierError).toBeNull());
});
// ── F1: trial-expired auto-open gate ──
it('auto-opens the paywall once and stamps the snooze when trial expired + onboarding done', async () => {
seedOnboardingCompleted();
mocks.adapter.getWorkspaces.mockResolvedValue([]);
mocks.adapter.getTier.mockResolvedValue({ tier: 'TRIAL', trialExpired: true, capabilities: {}, usage: {} });
const { result } = await renderShell();
await waitFor(() => expect(result.current.showTrialExpired).toBe(true));
expect(window.localStorage.getItem('waggle:trial-expired-last-shown-at')).not.toBeNull();
});
it('does NOT auto-open within the post-onboarding quiet window', async () => {
seedOnboardingCompleted(Date.now() - 60_000); // completed 1 min ago
mocks.adapter.getWorkspaces.mockResolvedValue([]);
mocks.adapter.getTier.mockResolvedValue({ tier: 'TRIAL', trialExpired: true, capabilities: {}, usage: {} });
const { result } = await renderShell();
await waitFor(() => expect(result.current.tierResolved).toBe(true));
expect(result.current.showTrialExpired).toBe(false);
});
it('a dismissed paywall stays closed on later same-session refreshTier re-runs', async () => {
seedOnboardingCompleted();
mocks.adapter.getWorkspaces.mockResolvedValue([]);
mocks.adapter.getTier.mockResolvedValue({ tier: 'TRIAL', trialExpired: true, capabilities: {}, usage: {} });
const { result } = await renderShell();
await waitFor(() => expect(result.current.showTrialExpired).toBe(true));
act(() => { result.current.setShowTrialExpired(false); });
await act(async () => { await result.current.refreshTier(); });
expect(result.current.showTrialExpired).toBe(false);
});
it('a fresh session (reload) within the 7-day snooze does not auto-open', async () => {
const now = Date.now();
seedOnboardingCompleted(now - 2 * 24 * 60 * 60_000);
window.localStorage.setItem('waggle:trial-expired-last-shown-at', String(now - 24 * 60 * 60_000));
mocks.adapter.getWorkspaces.mockResolvedValue([]);
mocks.adapter.getTier.mockResolvedValue({ tier: 'TRIAL', trialExpired: true, capabilities: {}, usage: {} });
const { result } = await renderShell();
await waitFor(() => expect(result.current.tierResolved).toBe(true));
expect(result.current.showTrialExpired).toBe(false);
});
});
// ── LoginBriefing failure ≠ Day-0 ──────────────────────────────────────────
describe('LoginBriefing (P1b)', () => {
@@ -375,13 +241,12 @@ describe('BackupApp (P1b)', () => {
});
});
// ── SettingsApp tier-as-fact pins ──────────────────────────────────────────
// ── SettingsApp General tab: no plan card ─────────────────────────────────
describe('SettingsApp tier badges (P1b D3-4)', () => {
describe('SettingsApp General tab', () => {
async function renderSettings() {
mocks.adapter.getSettings.mockResolvedValue({});
mocks.adapter.getTelemetryStatus.mockResolvedValue({ enabled: false });
mocks.adapter.getTeamStatus.mockResolvedValue({ connected: false });
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 });
@@ -391,25 +256,16 @@ describe('SettingsApp tier badges (P1b D3-4)', () => {
const { render, screen, fireEvent } = await import('@testing-library/react');
// SettingsApp reads `?tab=` via useSearchParams (PR7a/D12) — needs a Router.
render(<MemoryRouter><TooltipProvider><SettingsApp /></TooltipProvider></MemoryRouter>);
// PR5 §11: Settings now opens on Models ("Models leads"). The tier card lives
// in General — navigate there for these tier-as-fact assertions.
// PR5 §11: Settings opens on Models ("Models leads") — navigate to General.
fireEvent.click(await screen.findByRole('tab', { name: /general/i }));
return screen;
}
it('getTier failure: General tab never renders "FREE plan" as fact', async () => {
mocks.adapter.getTier.mockRejectedValue(httpError(401, {}, 'Unauthorized'));
it('renders no plan or tier card', async () => {
const screen = await renderSettings();
await waitFor(() => expect(screen.getByText(/confirming plan/i)).toBeInTheDocument());
expect(screen.queryByText(/FREE plan/i)).toBeNull();
}, 15000);
it('resolved TEAMS tier renders the real plan in the General tab', async () => {
mocks.adapter.getTier.mockResolvedValue({ tier: 'TEAMS', capabilities: {}, usage: {} });
const screen = await renderSettings();
await waitFor(() => {
expect(screen.getAllByText(/Team plan/i).some((el) => el.textContent?.trim() === 'Team plan')).toBe(true);
});
await waitFor(() => expect(screen.getByText('Local-first')).toBeInTheDocument());
expect(screen.queryByText(/confirming plan/i)).toBeNull();
expect(screen.queryByText(/\b(FREE|Solo|Team|Trial) plan\b/i)).toBeNull();
}, 15000);
});
@@ -442,12 +298,6 @@ describe('useChat error surfacing (P1b)', () => {
expect(errBlock?.message).toBe('Chat request failed (500): boom');
});
it('tier-403 copy defers to the UpgradeModal instead of duplicating the upsell', async () => {
const result = await sendFailing(httpError(403, { error: 'TIER_INSUFFICIENT', required: 'TEAMS' }, 'Needs TEAMS'));
const last = result.current.messages[result.current.messages.length - 1];
expect(last.content).toBe('This action needs a higher plan — see the upgrade window.');
});
it('network failure keeps the Backend-is-offline copy', async () => {
const result = await sendFailing(new TypeError('fetch failed'));
const last = result.current.messages[result.current.messages.length - 1];

View File

@@ -1,6 +1,6 @@
/**
* P7/D15 B1 — Approvals must not render a fetch FAILURE as an empty inbox.
* On a TEAMS trust surface, "No pending approvals" while the server is down is a
* On a trust surface, "No pending approvals" while the server is down is a
* correctness defect: it tells the user nothing is awaiting them when the truth
* is unknown. A failed load must show an error + Retry, not the empty state.
*/

View File

@@ -34,7 +34,6 @@ const renderBuilder = (over: Partial<Parameters<typeof SkillBuilder>[0]> = {}) =
const props = {
onCreated: vi.fn(),
onCancel: vi.fn(),
onTierError: vi.fn().mockReturnValue(false),
...over,
};
render(<SkillBuilder {...props} />);
@@ -211,19 +210,18 @@ describe('SkillBuilder — S19', () => {
expect(screen.getByTestId('skill-builder-next')).not.toBeDisabled();
});
it('routes a 403 through onTierError instead of rendering it as a plain error', async () => {
const props = renderBuilder({ onTierError: vi.fn().mockReturnValue(true) });
it('renders a 403 create failure as a plain inline error', async () => {
const props = renderBuilder();
fillIdentity();
fireEvent.click(screen.getByTestId('skill-builder-next'));
fireEvent.change(screen.getByLabelText('Step 1'), { target: { value: 'Draft' } });
fireEvent.click(screen.getByTestId('skill-builder-next'));
fireEvent.click(screen.getByTestId('skill-builder-next'));
mocks.adapter.createSkill.mockRejectedValue(Object.assign(new Error('tier_insufficient'), { status: 403 }));
mocks.adapter.createSkill.mockRejectedValue(Object.assign(new Error('Forbidden'), { status: 403 }));
fireEvent.click(screen.getByTestId('skill-builder-finish'));
await waitFor(() => expect(props.onTierError).toHaveBeenCalledWith(expect.any(Error), 'weekly-report'));
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
expect(await screen.findByRole('alert')).toHaveTextContent('Forbidden');
expect(props.onCreated).not.toHaveBeenCalled();
});

View File

@@ -1,8 +1,8 @@
/**
* Phase 4B (S08) — MCP Hub behaviour over a mocked adapter: installed
* instance rendering (state badge + C19 scope chip + honest logs-coming-soon),
* the C21 test-mode label, the B5 install tier gate (TIER_INSUFFICIENT →
* upgrade event), the SecurityGate blocked → ApprovalModal → forceInsecure-
* the C21 test-mode label, a plain install failure surfacing its reason
* inline, the SecurityGate blocked → ApprovalModal → forceInsecure-
* override flow, the C19 scope-editor exact payloads, and revoke with
* consequences.
*/
@@ -131,22 +131,14 @@ describe('MCPHubApp — MCP Hub (S08)', () => {
// Headroom for parallel-suite load on the catalog-tab tests.
const CATALOG_TIMEOUT = 20_000;
it('B5: a TIER_INSUFFICIENT install routes through the upgrade event', { timeout: CATALOG_TIMEOUT }, async () => {
mocks.adapter.installMcp.mockResolvedValue({ error: 'TIER_INSUFFICIENT', required: 'TEAMS', actual: 'FREE' });
const events: CustomEvent[] = [];
const listener = (e: Event) => events.push(e as CustomEvent);
window.addEventListener('waggle:tier-insufficient', listener);
try {
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('tab', { name: 'Catalog' }));
fireEvent.click(await screen.findByTestId('mcp-install-postgres'));
await waitFor(() => expect(mocks.adapter.installMcp).toHaveBeenCalledWith('postgres', undefined));
await waitFor(() => expect(events.length).toBeGreaterThan(0));
expect(events[0].detail.required).toBe('TEAMS');
} finally {
window.removeEventListener('waggle:tier-insufficient', listener);
}
it('a plain install failure surfaces the server reason inline', { timeout: CATALOG_TIMEOUT }, async () => {
mocks.adapter.installMcp.mockResolvedValue({ installed: false, error: 'FORBIDDEN', message: 'Not allowed' });
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('tab', { name: 'Catalog' }));
fireEvent.click(await screen.findByTestId('mcp-install-postgres'));
await waitFor(() => expect(mocks.adapter.installMcp).toHaveBeenCalledWith('postgres', undefined));
expect(await screen.findByTestId('mcp-install-notice')).toHaveTextContent('Not allowed');
});
it('scopes MCP catalog filters and distribution transitions to explicit properties', { timeout: CATALOG_TIMEOUT }, async () => {

View File

@@ -166,16 +166,16 @@ describe('InstallProvider — install dispatcher', () => {
expect(mocks.toast).toHaveBeenCalledWith(expect.objectContaining({ title: 'Added' }));
});
it('package install 403 TIER → reason tier, NOT installed, no destructive toast (adapter dispatches the event)', async () => {
it('package install plain 403 → reason error + destructive toast, NOT installed', async () => {
mocks.adapter.installMarketplacePackage.mockResolvedValue(
new Response(JSON.stringify({ error: 'TIER_INSUFFICIENT', required: 'TEAMS' }), { status: 403 }));
new Response(JSON.stringify({ error: 'Forbidden' }), { status: 403 }));
const { result } = await mountStore();
let outcome;
await act(async () => { outcome = await result.current.install(pkg(9)); });
expect(outcome).toEqual({ ok: false, reason: 'tier' });
expect(outcome).toEqual({ ok: false, reason: 'error' });
expect(result.current.isInstalled('pkg:9')).toBe(false);
expect(mocks.toast).not.toHaveBeenCalled();
expect(mocks.toast).toHaveBeenCalledWith(expect.objectContaining({ title: 'Install failed', variant: 'destructive' }));
});
it('package install SecurityGate block → reason security + destructive toast, NOT installed', async () => {
@@ -209,14 +209,14 @@ describe('InstallProvider — install dispatcher', () => {
expect(mocks.toast).toHaveBeenCalledWith(expect.objectContaining({ title: 'Connected' }));
});
it('a connector 403 tier rejection is classified as tier (no destructive toast)', async () => {
mocks.adapter.connectConnector.mockRejectedValue(httpError(403, { error: 'TIER_INSUFFICIENT' }));
it('a connector 403 rejection is a plain failure (reason error + destructive toast)', async () => {
mocks.adapter.connectConnector.mockRejectedValue(httpError(403, { error: 'Forbidden' }));
const { result } = await mountStore();
let outcome;
await act(async () => { outcome = await result.current.install(connector('slack'), { token: 'xoxb' }); });
expect(outcome).toEqual({ ok: false, reason: 'tier' });
expect(outcome).toEqual({ ok: false, reason: 'error' });
expect(result.current.isInstalled('connector:slack')).toBe(false);
expect(mocks.toast).not.toHaveBeenCalled(); // the adapter dispatched the upgrade event
expect(mocks.toast).toHaveBeenCalledWith(expect.objectContaining({ title: 'Connection failed', variant: 'destructive' }));
});
it('catalog MCP enable success flips installed', async () => {

View File

@@ -1,7 +1,7 @@
/**
* PR5 Phase B — Settings reskin/reconcile pins:
* - Settings opens on the Models tab with the shared ModelGate leading (D: "Models leads").
* - Billing rail tab renamed to "Plan" (D8).
* - No Plan, Team or Enterprise rail tab at any disclosure level (ADR-0001, ADR-0003).
* - The "Show" disclosure control (D6, anchored to the foot of the tab rail)
* drives the rail, with Advanced surfacing only at Everything (D7).
*/
@@ -12,9 +12,7 @@ const mocks = vi.hoisted(() => ({
adapter: {
getSettings: vi.fn().mockResolvedValue({}),
getPermissions: vi.fn().mockResolvedValue({ defaultAutonomy: 'normal', externalGates: [] }),
getTeamStatus: vi.fn().mockResolvedValue({ connected: false }),
getTelemetryStatus: vi.fn().mockResolvedValue({ enabled: false, totalEvents: 0 }),
getTier: vi.fn().mockResolvedValue({ tier: 'FREE', capabilities: {}, usage: {} }),
getServerUrl: vi.fn().mockReturnValue('http://127.0.0.1:3333'),
getProviders: vi.fn().mockResolvedValue({ providers: [], search: [], activeSearch: 'duckduckgo' }),
getLocalInferenceStatus: vi.fn().mockResolvedValue({ servers: [], ollamaInstalled: false, totalLocalModels: 0 }),
@@ -52,7 +50,6 @@ async function renderSettings() {
await waitFor(() => {
expect(mocks.adapter.getSettings).toHaveBeenCalled();
expect(mocks.adapter.getPermissions).toHaveBeenCalled();
expect(mocks.adapter.getTeamStatus).toHaveBeenCalled();
expect(mocks.adapter.getTelemetryStatus).toHaveBeenCalled();
expect(mocks.adapter.getProviders).toHaveBeenCalled();
expect(mocks.adapter.getLocalInferenceStatus).toHaveBeenCalled();
@@ -68,10 +65,13 @@ describe('PR5 Settings reskin', () => {
expect(await screen.findByRole('tablist', { name: /how to add a model/i })).toBeInTheDocument();
});
it('renames the Billing rail tab to "Plan" (D8)', async () => {
it('shows no Plan, Team or Enterprise tab, even at Everything', async () => {
await renderSettings();
expect(await screen.findByRole('tab', { name: /^plan$/i })).toBeInTheDocument();
expect(screen.queryByRole('tab', { name: /^billing$/i })).toBeNull();
fireEvent.click(screen.getByRole('button', { name: /everything/i }));
expect(await screen.findByRole('tab', { name: /advanced/i })).toBeInTheDocument();
for (const name of [/^plan$/i, /^billing$/i, /^team$/i, /^enterprise$/i]) {
expect(screen.queryByRole('tab', { name })).toBeNull();
}
});
it('the Show control gates Advanced to Everything (D6 + D7)', async () => {

View File

@@ -1,179 +0,0 @@
/**
* PR7a — Billing (screen 14) themed over the REAL useBilling→Stripe flow.
* Pins the load-bearing behaviors + the no-fabrication gates:
* - PlanCards: 2-card grid (Solo · free / Team · most-popular), annual toggle
* swaps the displayed price AND threads the real `billingPeriod` to checkout
* (D8/F9), current tier marked "Your plan". Team is the only checkout path.
* - useBilling.startCheckout passes billingPeriod to the adapter (D8).
* - SettingsApp `?tab=billing` deep-link snaps to the Plan tab (D12).
* - PaymentSuccessApp confirms off the SYNCED tier and renders NO fabricated
* receipt rows (F5).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, renderHook, act, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
const mocks = vi.hoisted(() => ({
adapter: {
getSettings: vi.fn().mockResolvedValue({}),
getPermissions: vi.fn().mockResolvedValue({ defaultAutonomy: 'normal', externalGates: [] }),
getTeamStatus: vi.fn().mockResolvedValue({ connected: false }),
getTelemetryStatus: vi.fn().mockResolvedValue({ enabled: false, totalEvents: 0 }),
getTier: vi.fn().mockResolvedValue({ tier: 'FREE', capabilities: {}, usage: {} }),
getServerUrl: vi.fn().mockReturnValue('http://127.0.0.1:3333'),
getProviders: vi.fn().mockResolvedValue({ providers: [], search: [], activeSearch: 'duckduckgo' }),
getLocalInferenceStatus: vi.fn().mockResolvedValue({ servers: [], ollamaInstalled: false, totalLocalModels: 0 }),
createCheckoutSession: vi.fn().mockResolvedValue({ url: 'https://checkout.stripe.test/abc' }),
createPortalSession: vi.fn().mockResolvedValue({ url: 'https://portal.stripe.test/abc' }),
syncStripeCheckout: vi.fn().mockResolvedValue({ tier: 'TEAMS', customerId: 'cus_1' }),
getStripeStatus: vi.fn().mockResolvedValue({ configured: true }),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
beforeEach(() => { window.localStorage.clear(); });
afterEach(() => { cleanup(); vi.clearAllMocks(); window.history.replaceState({}, '', '/'); });
describe('PR7a · PlanCards', () => {
it('renders the 2-card grid (Solo · free / Team · most-popular)', async () => {
const { default: PlanCards } = await import('@/components/os/billing/PlanCards');
render(<PlanCards currentTier="FREE" onChoose={vi.fn()} />);
expect(screen.getByText('Solo')).toBeInTheDocument();
expect(screen.getByText('Team')).toBeInTheDocument();
expect(screen.queryByText('Pro')).not.toBeInTheDocument();
expect(screen.getByText('Most popular')).toBeInTheDocument();
// Solo (FREE) user → Solo is the current plan
expect(screen.getByText('Your plan')).toBeInTheDocument();
});
it('annual toggle swaps the displayed price AND threads billingPeriod to onChoose (D8/F9)', async () => {
const { default: PlanCards } = await import('@/components/os/billing/PlanCards');
const onChoose = vi.fn();
render(<PlanCards currentTier="FREE" onChoose={onChoose} />);
// Monthly default → Team shows $49
expect(screen.getByText('$49')).toBeInTheDocument();
// Switch to annual → Team shows $39 (the real annual price label, not a client × 0.8)
fireEvent.click(screen.getByRole('button', { name: /Annual/i }));
expect(screen.getByText('$39')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Choose Team/i }));
expect(onChoose).toHaveBeenCalledWith('TEAMS', 'annual');
});
it('does not offer an in-app downgrade — lower tiers show "Included", not a CTA (D6)', async () => {
const { default: PlanCards } = await import('@/components/os/billing/PlanCards');
const onChoose = vi.fn();
render(<PlanCards currentTier="TEAMS" onChoose={onChoose} />);
// TEAMS user: Team = "Your plan", Solo = "Included", no downgrade CTA
expect(screen.getByText('Your plan')).toBeInTheDocument();
expect(screen.getByText('Included')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /Choose Team/i })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /Choose Solo/i })).not.toBeInTheDocument();
});
it('TRIAL user: no card claims "Current"/"Your plan" — a trial is not a purchasable plan', async () => {
const { default: PlanCards } = await import('@/components/os/billing/PlanCards');
render(<PlanCards currentTier="TRIAL" onChoose={vi.fn()} />);
expect(screen.queryByText('Current')).not.toBeInTheDocument();
expect(screen.queryByText('Your plan')).not.toBeInTheDocument();
// Team remains the upgrade path during trial
expect(screen.getByRole('button', { name: /Choose Team/i })).toBeInTheDocument();
});
it('disabled (F8 Stripe-not-configured): upgrade CTAs render "Unavailable" and never fire onChoose', async () => {
const { default: PlanCards } = await import('@/components/os/billing/PlanCards');
const onChoose = vi.fn();
render(<PlanCards currentTier="FREE" onChoose={onChoose} disabled />);
const ctas = screen.getAllByRole('button', { name: /Unavailable/i });
expect(ctas.length).toBeGreaterThanOrEqual(1);
ctas.forEach((b) => expect(b).toBeDisabled());
fireEvent.click(ctas[0]);
expect(onChoose).not.toHaveBeenCalled();
});
});
describe('PR7a · useBilling.startCheckout', () => {
it('threads billingPeriod to adapter.createCheckoutSession (D8)', async () => {
const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
const { useBilling } = await import('@/hooks/useBilling');
const { result } = renderHook(() => useBilling());
await waitFor(() => expect(mocks.adapter.getTier).toHaveBeenCalled());
await act(async () => { await result.current.startCheckout('TEAMS', 'annual'); });
expect(mocks.adapter.createCheckoutSession).toHaveBeenCalledWith('TEAMS', 'annual');
expect(openSpy).toHaveBeenCalledWith('https://checkout.stripe.test/abc', '_blank', 'noopener,noreferrer');
openSpy.mockRestore();
});
});
describe('PR7a · SettingsApp ?tab= deep-link (D12)', () => {
it('?tab=billing snaps Settings to the Plan tab', async () => {
mocks.adapter.getTier.mockResolvedValue({ tier: 'FREE', capabilities: {}, usage: {} });
const { default: SettingsApp } = await import('@/components/os/apps/SettingsApp');
const { TooltipProvider } = await import('@/components/ui/tooltip');
render(
<MemoryRouter initialEntries={['/settings?tab=billing']}>
<TooltipProvider><SettingsApp /></TooltipProvider>
</MemoryRouter>,
);
// The Plan tab is selected (the rail tab labelled "Plan")
await waitFor(() => {
expect(screen.getByRole('tab', { name: /plan/i })).toHaveAttribute('aria-selected', 'true');
});
expect(await screen.findByText('Plan & Subscription')).toBeInTheDocument();
});
});
describe('PR7a · PaymentSuccessApp', () => {
it('confirms off the synced tier with NO fabricated receipt (F5)', async () => {
mocks.adapter.getTier.mockResolvedValue({ tier: 'TEAMS', capabilities: {}, usage: {} });
const { default: PaymentSuccessApp } = await import('@/components/os/apps/PaymentSuccessApp');
render(
<MemoryRouter initialEntries={['/payment-success']}>
<PaymentSuccessApp />
</MemoryRouter>,
);
expect(await screen.findByText(/You’re/i)).toBeInTheDocument();
expect(screen.getByText('Team.')).toBeInTheDocument();
// No-fabrication: the mock's receipt rows must NOT appear
expect(screen.queryByText(/Trial ends/i)).not.toBeInTheDocument();
expect(screen.queryByText(/Emailed/i)).not.toBeInTheDocument();
expect(screen.queryByText(/Receipt/i)).not.toBeInTheDocument();
expect(screen.queryByText(/\$49\.00/)).not.toBeInTheDocument();
});
it('sync wins a LATE getTier — a just-paid user is never flashed "Nothing to confirm" (race guard)', async () => {
// useBilling reads window.location for ?session_id= (not the router), so set it.
window.history.replaceState({}, '', '/payment-success?session_id=cs_test');
// getTier resolves FREE *after* the checkout sync resolves TEAMS; the authoritative
// sync result must not be clobbered back to FREE.
let resolveTier: (v: { tier: string; capabilities: object; usage: object }) => void = () => {};
mocks.adapter.getTier.mockReturnValue(new Promise((res) => { resolveTier = res; }));
mocks.adapter.syncStripeCheckout.mockResolvedValue({ tier: 'TEAMS', customerId: 'cus_1' });
const { default: PaymentSuccessApp } = await import('@/components/os/apps/PaymentSuccessApp');
render(
<MemoryRouter initialEntries={['/payment-success?session_id=cs_test']}>
<PaymentSuccessApp />
</MemoryRouter>,
);
// Sync resolves first → paid confirmation
expect(await screen.findByText('Team.')).toBeInTheDocument();
// The late getTier resolves FREE — must NOT flip the screen to "Nothing to confirm"
await act(async () => { resolveTier({ tier: 'FREE', capabilities: {}, usage: {} }); });
expect(screen.getByText('Team.')).toBeInTheDocument();
expect(screen.queryByText(/Nothing to confirm/i)).not.toBeInTheDocument();
});
it('renders legacy PRO checkout state as explicitly legacy', async () => {
mocks.adapter.getTier.mockResolvedValue({ tier: 'PRO', capabilities: {}, usage: {} });
const { default: PaymentSuccessApp } = await import('@/components/os/apps/PaymentSuccessApp');
render(
<MemoryRouter initialEntries={['/payment-success']}>
<PaymentSuccessApp />
</MemoryRouter>,
);
expect(await screen.findByText('Legacy Pro.')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Start using Legacy Pro/i })).toBeInTheDocument();
});
});

View File

@@ -4,8 +4,8 @@
* demo email, or a fake SSO button that does nothing (F1/F10).
* B2 (explicitly enabled + key present): the real prebuilt Clerk <SignIn/>/<SignUp/>
* (D13) with a redirect to the fully-local app, the §2b honey local-first note on
* Sign up, our own design-faithful toggle, and the enterprise panel as a sales CTA
* (not a live SAML form — F11/D15).
* Sign up and our own design-faithful toggle — no enterprise sales CTA and no
* live SAML form (F11/D15).
*/
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { render, screen, cleanup, fireEvent } from '@testing-library/react';
@@ -90,10 +90,11 @@ describe('PR7b · /auth — B2 Clerk form (explicitly enabled + key present)', (
expect(screen.getByTestId('clerk-signin')).toBeInTheDocument();
});
it('enterprise panel is a sales CTA → kvark.ai, NOT a live SAML form (F11/D15)', async () => {
it('renders no enterprise sales CTA and no live SAML form (F11/D15)', async () => {
const { default: AuthRoute } = await import('@/routes/AuthRoute');
render(<MemoryRouter><AuthRoute /></MemoryRouter>);
expect(screen.getByRole('link', { name: /Talk to sales/i })).toHaveAttribute('href', 'https://www.kvark.ai');
expect(screen.getByTestId('clerk-signin')).toBeInTheDocument();
expect(screen.queryByRole('link', { name: /Talk to sales/i })).not.toBeInTheDocument();
expect(screen.queryByPlaceholderText(/work email|organization/i)).not.toBeInTheDocument();
});
});

View File

@@ -7,9 +7,7 @@ const mocks = vi.hoisted(() => ({
adapter: {
getSettings: vi.fn(),
getPermissions: vi.fn(),
getTeamStatus: vi.fn(),
getTelemetryStatus: vi.fn(),
getTier: vi.fn(),
getServerUrl: vi.fn(),
getProviders: vi.fn(),
getLocalInferenceStatus: vi.fn(),
@@ -50,9 +48,7 @@ beforeEach(() => {
window.localStorage.clear();
mocks.adapter.getSettings.mockResolvedValue({});
mocks.adapter.getPermissions.mockResolvedValue({ defaultAutonomy: 'normal', externalGates: [] });
mocks.adapter.getTeamStatus.mockResolvedValue({ connected: false });
mocks.adapter.getTelemetryStatus.mockResolvedValue({ enabled: true, totalEvents: 3 });
mocks.adapter.getTier.mockResolvedValue({ tier: 'FREE', capabilities: {}, usage: {} });
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 });

View File

@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { useState } from 'react';
import { render, screen, fireEvent, cleanup, waitFor, within, act } from '@testing-library/react';
import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { TooltipProvider } from '@/components/ui/tooltip';
import NotificationInbox from '@/components/os/overlays/NotificationInbox';
@@ -9,8 +9,6 @@ import WorkspaceSwitcher from '@/components/os/overlays/WorkspaceSwitcher';
import PersonaSwitcher from '@/components/os/overlays/PersonaSwitcher';
import ContextRail from '@/components/os/overlays/ContextRail';
import OnboardingTooltips from '@/components/os/overlays/OnboardingTooltips';
import UpgradeModal from '@/components/os/overlays/UpgradeModal';
import TrialExpiredModal from '@/components/os/overlays/TrialExpiredModal';
import type { Notification, Workspace, WorkspaceTemplate } from '@/lib/types';
const mocks = vi.hoisted(() => ({
@@ -86,7 +84,7 @@ function WorkspaceSwitcherHarness() {
describe('Shell overlay contracts', () => {
beforeEach(() => {
mocks.useWorkspaces.mockReturnValue({ workspaces: [] });
mocks.useShell.mockReturnValue({ billingTier: 'FREE' });
mocks.useShell.mockReturnValue({});
mocks.adapter.getWorkspaceTemplates.mockResolvedValue({ templates: [] });
mocks.adapter.getConnectors.mockResolvedValue([]);
mocks.adapter.getPersonas.mockResolvedValue([]);
@@ -438,29 +436,4 @@ describe('Shell overlay contracts', () => {
expect(onDismiss).toHaveBeenCalledTimes(1);
expect(localStorage.getItem('waggle:tooltips_done')).toBe('true');
});
it('Tier interruption modals have named close controls', async () => {
renderWithProviders(<UpgradeModal />);
act(() => {
window.dispatchEvent(new CustomEvent('waggle:tier-insufficient', {
detail: {
required: 'TEAMS',
actual: 'FREE',
message: 'Team workspaces require a Team plan.',
},
}));
});
const upgradeDialog = await screen.findByRole('dialog', { name: /upgrade to unlock/i });
expect(within(upgradeDialog).getByRole('button', { name: /close upgrade dialog/i })).toBeInTheDocument();
cleanup();
renderWithProviders(
<TrialExpiredModal open onDismiss={vi.fn()} onUpgrade={vi.fn()} />,
);
const trialDialog = screen.getByRole('dialog', { name: /trial has ended/i });
expect(within(trialDialog).getByRole('button', { name: /close trial expired dialog/i })).toBeInTheDocument();
});
});

View File

@@ -32,7 +32,6 @@ function renderAt(pathname: string) {
onOpenCommand={() => {}}
onSpawnAgent={() => {}}
userName="Marko"
tierLabel="Solo"
/>
</MemoryRouter>,
);

View File

@@ -1,7 +1,7 @@
/**
* §D2 skill-audit: the "verified" badge renders on a skill row only when the
* audit loop confirmed the skill, with confidence shown as a percentage. Skill
* audit is a free (Solo) feature, so the badge's presence must track the
* audit is available to every user, so the badge's presence must track the
* verified flag exactly (never shown on an unverified skill).
*/
import { describe, it, expect, afterEach, vi } from 'vitest';