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:
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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}>
|
||||
|
||||
@@ -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;
|
||||
@@ -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>
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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">
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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.';
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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%. */
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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/);
|
||||
});
|
||||
});
|
||||
@@ -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 }) });
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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];
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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';
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
|
||||
@@ -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 }>(
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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 });
|
||||
});
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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' };
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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;
|
||||
@@ -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';
|
||||
|
||||
@@ -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 = () => {
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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}'))`);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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(),
|
||||
},
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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)', () => {
|
||||
|
||||
@@ -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];
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -32,7 +32,6 @@ function renderAt(pathname: string) {
|
||||
onOpenCommand={() => {}}
|
||||
onSpawnAgent={() => {}}
|
||||
userName="Marko"
|
||||
tierLabel="Solo"
|
||||
/>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -23,9 +23,12 @@ becomes a fixed constant.
|
||||
- P0.1 removes `packages/shared/src/tiers.ts`, the `assert-tier` middleware and the routes
|
||||
that call `requireTier`, `/api/tier` and `/api/tier/start-trial`, and the trial auto-start
|
||||
after onboarding.
|
||||
- P1.1 removes `packages/server/src/stripe/` and `packages/server/src/kvark/`; P1.4 removes
|
||||
`packages/agent/src/kvark-tools.ts`; P1.3a removes the billing UI.
|
||||
- On startup the sidecar drops the `tier`, `trialStartedAt` and `stripe_customer_id` keys from
|
||||
`config.json`.
|
||||
- P0.1 also removes `packages/server/src/stripe/` and the web billing UI, because both depend
|
||||
on the tier model. P1.1 removes `packages/server/src/kvark/`; P1.4 removes
|
||||
`packages/agent/src/kvark-tools.ts`.
|
||||
- The sidecar ignores the `tier`, `trialStartedAt` and `stripe_customer_id` keys in
|
||||
`config.json`. It does not delete them: until the data-directory question is decided, the
|
||||
commercial and community editions may share `~/.waggle`, and deleting the keys would downgrade
|
||||
a paying user of the commercial edition.
|
||||
- UserTier (UI complexity), ModelTier, persona tiers, CLI levels and memory health levels are
|
||||
unrelated to billing and stay.
|
||||
|
||||
@@ -53,7 +53,7 @@ export {
|
||||
createInProcessEmbedder, normalizeDimensions, type InProcessEmbedderConfig,
|
||||
createOllamaEmbedder, type OllamaEmbedderConfig,
|
||||
createApiEmbedder, type ApiEmbedderConfig,
|
||||
createEmbeddingProvider, EmbeddingQuotaExceededError, getMinimumTierForProvider,
|
||||
createEmbeddingProvider,
|
||||
type EmbeddingProviderConfig, type EmbeddingProviderStatus, type EmbeddingProviderType,
|
||||
type EmbeddingProviderInstance, type EmbeddingQuotaStatus,
|
||||
normalizeEntityName, findDuplicates, isNoiseName, isLikelyAcronym,
|
||||
|
||||
@@ -1,272 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import Database from 'better-sqlite3';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createEmbeddingProvider, EmbeddingQuotaExceededError, getMinimumTierForProvider } from '@waggle/hive-mind-core';
|
||||
import { TierError, TIER_CAPABILITIES } from '@waggle/shared';
|
||||
|
||||
describe('Embedding Provider — Tier & Quota Enforcement', () => {
|
||||
let tmpDir: string;
|
||||
let db: InstanceType<typeof Database>;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-embed-test-'));
|
||||
db = new Database(path.join(tmpDir, 'quota.db'));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
db.close();
|
||||
fs.rmSync(tmpDir, {
|
||||
recursive: true,
|
||||
force: true,
|
||||
maxRetries: 10,
|
||||
retryDelay: 100,
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tier enforcement on provider selection', () => {
|
||||
it('FREE user requesting litellm throws TierError (litellm stays Team-only)', async () => {
|
||||
// Solo (FREE) unlocks BYO cloud embeddings (voyage/openai) but NOT the
|
||||
// managed litellm router — that stays a paid-tier provider.
|
||||
await expect(
|
||||
createEmbeddingProvider({
|
||||
provider: 'litellm',
|
||||
userTier: 'FREE',
|
||||
quotaDb: db,
|
||||
})
|
||||
).rejects.toThrow(TierError);
|
||||
});
|
||||
|
||||
it('FREE user requesting inprocess succeeds', async () => {
|
||||
// inprocess may fail to load ONNX in test env, but should NOT throw TierError
|
||||
try {
|
||||
await createEmbeddingProvider({
|
||||
provider: 'inprocess',
|
||||
userTier: 'FREE',
|
||||
quotaDb: db,
|
||||
});
|
||||
} catch (err) {
|
||||
// If it fails, it should NOT be a TierError — it should be a probe failure
|
||||
expect(err).not.toBeInstanceOf(TierError);
|
||||
}
|
||||
});
|
||||
|
||||
it('FREE user requesting voyage does not throw TierError (Solo unlocks BYO cloud embeddings)', async () => {
|
||||
// voyage will fail to connect (no real API), but should NOT throw TierError —
|
||||
// Solo now allows the voyage/openai providers directly.
|
||||
const provider = await createEmbeddingProvider({
|
||||
provider: 'auto',
|
||||
userTier: 'FREE',
|
||||
quotaDb: db,
|
||||
});
|
||||
// Should fall back to mock (no real providers in test), but no TierError
|
||||
expect(provider.getActiveProvider()).toBeDefined();
|
||||
});
|
||||
|
||||
it('auto mode surfaces only key-backed providers for FREE tier', async () => {
|
||||
const provider = await createEmbeddingProvider({
|
||||
provider: 'auto',
|
||||
userTier: 'FREE',
|
||||
quotaDb: db,
|
||||
});
|
||||
// FREE allows inprocess, mock, ollama + cloud (voyage/openai); cloud is
|
||||
// skipped here without API keys, so only local providers + mock surface.
|
||||
const status = provider.getStatus();
|
||||
for (const p of status.availableProviders) {
|
||||
expect(['inprocess', 'mock', 'ollama']).toContain(p);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Quota enforcement', () => {
|
||||
// All current tiers have unlimited quotas (-1), so we patch FREE
|
||||
// to a finite quota for these tests to exercise the quota mechanism.
|
||||
const originalQuota = TIER_CAPABILITIES.FREE.embeddingQuotaPerMonth;
|
||||
|
||||
beforeEach(() => {
|
||||
(TIER_CAPABILITIES.FREE as { embeddingQuotaPerMonth: number }).embeddingQuotaPerMonth = 500;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(TIER_CAPABILITIES.FREE as { embeddingQuotaPerMonth: number }).embeddingQuotaPerMonth = originalQuota;
|
||||
});
|
||||
|
||||
it('FREE user at 499 embeddings succeeds', async () => {
|
||||
const provider = await createEmbeddingProvider({
|
||||
provider: 'mock',
|
||||
userTier: 'FREE',
|
||||
userId: 'test-user',
|
||||
quotaDb: db,
|
||||
});
|
||||
|
||||
// Pre-fill 499 embeddings
|
||||
const ym = `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`;
|
||||
db.prepare('INSERT INTO embedding_usage (user_id, year_month, count, updated_at) VALUES (?, ?, 499, ?)').run('test-user', ym, Date.now());
|
||||
|
||||
// 500th should succeed (499 + 1 = 500 = quota)
|
||||
const result = await provider.embed('test text');
|
||||
expect(result).toBeInstanceOf(Float32Array);
|
||||
});
|
||||
|
||||
it('FREE user at 500 embeddings throws EmbeddingQuotaExceededError', async () => {
|
||||
const provider = await createEmbeddingProvider({
|
||||
provider: 'mock',
|
||||
userTier: 'FREE',
|
||||
userId: 'test-user',
|
||||
quotaDb: db,
|
||||
});
|
||||
|
||||
// Pre-fill to quota limit
|
||||
const ym = `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`;
|
||||
db.prepare('INSERT INTO embedding_usage (user_id, year_month, count, updated_at) VALUES (?, ?, 500, ?)').run('test-user', ym, Date.now());
|
||||
|
||||
await expect(provider.embed('test text')).rejects.toThrow(EmbeddingQuotaExceededError);
|
||||
});
|
||||
|
||||
it('TEAMS user with unlimited quota never throws quota error', async () => {
|
||||
const provider = await createEmbeddingProvider({
|
||||
provider: 'mock',
|
||||
userTier: 'TEAMS',
|
||||
userId: 'test-user',
|
||||
quotaDb: db,
|
||||
});
|
||||
|
||||
// Even with high usage, should succeed (TEAMS has -1 = unlimited)
|
||||
const ym = `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`;
|
||||
db.prepare('INSERT INTO embedding_usage (user_id, year_month, count, updated_at) VALUES (?, ?, 999999, ?)').run('test-user', ym, Date.now());
|
||||
|
||||
const result = await provider.embed('test text');
|
||||
expect(result).toBeInstanceOf(Float32Array);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getQuotaStatus', () => {
|
||||
const originalQuota = TIER_CAPABILITIES.FREE.embeddingQuotaPerMonth;
|
||||
|
||||
beforeEach(() => {
|
||||
(TIER_CAPABILITIES.FREE as { embeddingQuotaPerMonth: number }).embeddingQuotaPerMonth = 500;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(TIER_CAPABILITIES.FREE as { embeddingQuotaPerMonth: number }).embeddingQuotaPerMonth = originalQuota;
|
||||
});
|
||||
|
||||
it('returns correct percentage for FREE user', async () => {
|
||||
const provider = await createEmbeddingProvider({
|
||||
provider: 'mock',
|
||||
userTier: 'FREE',
|
||||
userId: 'test-user',
|
||||
quotaDb: db,
|
||||
});
|
||||
|
||||
// Use 250 of 500 quota
|
||||
const ym = `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`;
|
||||
db.prepare('INSERT INTO embedding_usage (user_id, year_month, count, updated_at) VALUES (?, ?, 250, ?)').run('test-user', ym, Date.now());
|
||||
|
||||
const status = provider.getQuotaStatus();
|
||||
expect(status.tier).toBe('FREE');
|
||||
expect(status.quota).toBe(500);
|
||||
expect(status.used).toBe(250);
|
||||
expect(status.remaining).toBe(250);
|
||||
expect(status.percentage).toBe(50);
|
||||
expect(status.resetsAt).toBeTruthy();
|
||||
});
|
||||
|
||||
it('returns unlimited for TEAMS tier', async () => {
|
||||
const provider = await createEmbeddingProvider({
|
||||
provider: 'mock',
|
||||
userTier: 'TEAMS',
|
||||
userId: 'test-user',
|
||||
quotaDb: db,
|
||||
});
|
||||
|
||||
const status = provider.getQuotaStatus();
|
||||
expect(status.tier).toBe('TEAMS');
|
||||
expect(status.quota).toBe(-1);
|
||||
expect(status.remaining).toBe(-1);
|
||||
expect(status.percentage).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('WAGGLE_EVAL_MODE tier bypass (PA v5 §11.3)', () => {
|
||||
// Defensive cleanup: never leak the flag across tests. If a prior run
|
||||
// crashed mid-test, this block restores a known-clean baseline.
|
||||
beforeEach(() => { delete process.env.WAGGLE_EVAL_MODE; });
|
||||
afterEach(() => { delete process.env.WAGGLE_EVAL_MODE; });
|
||||
|
||||
it('without WAGGLE_EVAL_MODE: FREE + litellm still throws TierError (control)', async () => {
|
||||
// Explicit sanity check that the normal gate is still live — baseline
|
||||
// for the bypass test below. litellm is the provider FREE still lacks.
|
||||
expect(process.env.WAGGLE_EVAL_MODE).toBeUndefined();
|
||||
await expect(
|
||||
createEmbeddingProvider({
|
||||
provider: 'litellm',
|
||||
userTier: 'FREE',
|
||||
quotaDb: db,
|
||||
})
|
||||
).rejects.toThrow(TierError);
|
||||
});
|
||||
|
||||
it('with WAGGLE_EVAL_MODE=1: FREE + litellm no longer throws TierError', async () => {
|
||||
process.env.WAGGLE_EVAL_MODE = '1';
|
||||
try {
|
||||
await createEmbeddingProvider({
|
||||
provider: 'litellm',
|
||||
userTier: 'FREE',
|
||||
quotaDb: db,
|
||||
});
|
||||
} catch (err) {
|
||||
// Probe failure (no real voyage backend in tests) is fine — just not
|
||||
// a TierError. The point: the tier gate is bypassed.
|
||||
expect(err).not.toBeInstanceOf(TierError);
|
||||
}
|
||||
});
|
||||
|
||||
it('with WAGGLE_EVAL_MODE=1 and no userTier set: behaves as if unenforced', async () => {
|
||||
process.env.WAGGLE_EVAL_MODE = '1';
|
||||
const provider = await createEmbeddingProvider({
|
||||
provider: 'auto',
|
||||
quotaDb: db,
|
||||
});
|
||||
// Falls back to mock with no tier skip/probe; provider is constructed.
|
||||
expect(provider.getActiveProvider()).toBeDefined();
|
||||
});
|
||||
|
||||
it('only activates when env value is exactly "1" (defensive literal match)', async () => {
|
||||
// Guard against accidental truthy-but-not-"1" values. Harness must use
|
||||
// "1" exactly per §11.3.
|
||||
for (const bad of ['true', 'yes', '0', '']) {
|
||||
process.env.WAGGLE_EVAL_MODE = bad;
|
||||
await expect(
|
||||
createEmbeddingProvider({
|
||||
provider: 'litellm',
|
||||
userTier: 'FREE',
|
||||
quotaDb: db,
|
||||
})
|
||||
).rejects.toThrow(TierError);
|
||||
delete process.env.WAGGLE_EVAL_MODE;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('getMinimumTierForProvider', () => {
|
||||
it('inprocess requires TRIAL (first tier that allows it)', () => {
|
||||
expect(getMinimumTierForProvider('inprocess')).toBe('TRIAL');
|
||||
});
|
||||
|
||||
it('voyage requires TRIAL (TRIAL unlocks all providers)', () => {
|
||||
// TRIAL is the first tier in TIERS array and has all providers
|
||||
expect(getMinimumTierForProvider('voyage')).toBe('TRIAL');
|
||||
});
|
||||
|
||||
it('litellm requires TRIAL', () => {
|
||||
// TRIAL is the first tier with litellm (all unlocked)
|
||||
expect(getMinimumTierForProvider('litellm')).toBe('TRIAL');
|
||||
});
|
||||
|
||||
it('mock requires TRIAL', () => {
|
||||
expect(getMinimumTierForProvider('mock')).toBe('TRIAL');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -59,7 +59,7 @@ export { createLiteLLMEmbedder, type LiteLLMEmbedderConfig } from './mind/litell
|
||||
export { createInProcessEmbedder, normalizeDimensions, type InProcessEmbedderConfig } from './mind/inprocess-embedder.js';
|
||||
export { createOllamaEmbedder, type OllamaEmbedderConfig } from './mind/ollama-embedder.js';
|
||||
export { createApiEmbedder, type ApiEmbedderConfig } from './mind/api-embedder.js';
|
||||
export { createEmbeddingProvider, EmbeddingQuotaExceededError, getMinimumTierForProvider, maxEmbedCharsForModel, capEmbedText, reembedPerText, type EmbeddingProviderConfig, type EmbeddingProviderStatus, type EmbeddingProviderType, type EmbeddingProviderInstance, type EmbeddingQuotaStatus } from './mind/embedding-provider.js';
|
||||
export { createEmbeddingProvider, maxEmbedCharsForModel, capEmbedText, reembedPerText, type EmbeddingProviderConfig, type EmbeddingProviderStatus, type EmbeddingProviderType, type EmbeddingProviderInstance, type EmbeddingQuotaStatus } from './mind/embedding-provider.js';
|
||||
export { normalizeEntityName, findDuplicates, isNoiseName, isLikelyAcronym } from './mind/entity-normalizer.js';
|
||||
export { Ontology, validateEntity, type EntitySchema, type ValidationResult } from './mind/ontology.js';
|
||||
export {
|
||||
|
||||
@@ -3,13 +3,11 @@
|
||||
* Single entry point for all embedding operations in Waggle.
|
||||
* Implements the Embedder interface — drop-in replacement everywhere.
|
||||
*
|
||||
* Tier enforcement: provider selection is gated by TIER_CAPABILITIES.embeddingProviders.
|
||||
* Quota enforcement: monthly embed count tracked in embedding_usage table.
|
||||
* Usage: the monthly embed count is tracked in the embedding_usage table (no limit).
|
||||
*/
|
||||
|
||||
import type { Embedder } from './embeddings.js';
|
||||
import type { Database as DatabaseType } from 'better-sqlite3';
|
||||
import { type Tier, TIERS, TIER_CAPABILITIES, TierError } from '@waggle/shared';
|
||||
import { createCoreLogger } from '../logger.js';
|
||||
|
||||
const log = createCoreLogger('embedding');
|
||||
@@ -19,11 +17,9 @@ export type EmbeddingProviderType = 'inprocess' | 'ollama' | 'voyage' | 'openai'
|
||||
export interface EmbeddingProviderConfig {
|
||||
provider?: EmbeddingProviderType | 'auto';
|
||||
targetDimensions?: number;
|
||||
/** User tier — gates which providers are available and monthly quota. Defaults to SOLO. */
|
||||
userTier?: Tier;
|
||||
/** User ID for quota tracking. Defaults to 'local'. */
|
||||
userId?: string;
|
||||
/** Raw SQLite database for quota tracking. Optional — quota not enforced without it. */
|
||||
/** Raw SQLite database for usage tracking. Optional — usage is not recorded without it. */
|
||||
quotaDb?: DatabaseType;
|
||||
inprocess?: { model?: string; cacheDir?: string };
|
||||
ollama?: { baseUrl?: string; model?: string };
|
||||
@@ -32,17 +28,6 @@ export interface EmbeddingProviderConfig {
|
||||
litellm?: { url: string; apiKey?: string; model?: string };
|
||||
}
|
||||
|
||||
// ── Tier enforcement helpers ──────────────────────────────────────────
|
||||
|
||||
/** Find the lowest tier that allows a given embedding provider. */
|
||||
export function getMinimumTierForProvider(provider: EmbeddingProviderType): Tier {
|
||||
for (const tier of TIERS) {
|
||||
const allowed = TIER_CAPABILITIES[tier].embeddingProviders as readonly string[];
|
||||
if (allowed.includes(provider)) return tier;
|
||||
}
|
||||
return 'ENTERPRISE';
|
||||
}
|
||||
|
||||
// ── Quota tracking ────────────────────────────────────────────────────
|
||||
|
||||
const EMBEDDING_USAGE_SCHEMA = `
|
||||
@@ -65,13 +50,6 @@ function getCurrentYearMonth(): string {
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function getUsageCount(db: DatabaseType, userId: string, yearMonth: string): number {
|
||||
const row = db.prepare(
|
||||
'SELECT count FROM embedding_usage WHERE user_id = ? AND year_month = ?'
|
||||
).get(userId, yearMonth) as { count: number } | undefined;
|
||||
return row?.count ?? 0;
|
||||
}
|
||||
|
||||
function incrementUsage(db: DatabaseType, userId: string, yearMonth: string, amount: number): void {
|
||||
db.prepare(`
|
||||
INSERT INTO embedding_usage (user_id, year_month, count, updated_at)
|
||||
@@ -80,23 +58,7 @@ function incrementUsage(db: DatabaseType, userId: string, yearMonth: string, amo
|
||||
`).run(userId, yearMonth, amount, Date.now(), amount, Date.now());
|
||||
}
|
||||
|
||||
export class EmbeddingQuotaExceededError extends Error {
|
||||
public readonly tier: Tier;
|
||||
public readonly quota: number;
|
||||
public readonly current: number;
|
||||
public readonly upgradeUrl = 'https://waggle-os.ai/upgrade';
|
||||
|
||||
constructor(tier: Tier, quota: number, current: number) {
|
||||
super(`Embedding quota exceeded: ${current}/${quota} for ${tier} tier`);
|
||||
this.name = 'EmbeddingQuotaExceededError';
|
||||
this.tier = tier;
|
||||
this.quota = quota;
|
||||
this.current = current;
|
||||
}
|
||||
}
|
||||
|
||||
export interface EmbeddingQuotaStatus {
|
||||
tier: Tier;
|
||||
quota: number;
|
||||
used: number;
|
||||
remaining: number;
|
||||
@@ -124,7 +86,7 @@ export interface EmbeddingProviderInstance extends Embedder {
|
||||
getStatus(): EmbeddingProviderStatus;
|
||||
getActiveProvider(): EmbeddingProviderType;
|
||||
reprobe(): Promise<EmbeddingProviderStatus>;
|
||||
/** Get current quota status for the user. Returns unlimited values if no quotaDb configured. */
|
||||
/** Get the usage status. Embedding is unlimited, so quota and remaining are -1. */
|
||||
getQuotaStatus(): EmbeddingQuotaStatus;
|
||||
}
|
||||
|
||||
@@ -289,20 +251,10 @@ async function probeProvider(
|
||||
export async function createEmbeddingProvider(config?: EmbeddingProviderConfig): Promise<EmbeddingProviderInstance> {
|
||||
const cfg: EmbeddingProviderConfig = { provider: 'auto', targetDimensions: 1024, ...config };
|
||||
const dims = cfg.targetDimensions ?? 1024;
|
||||
const userTier: Tier = cfg.userTier ?? 'FREE';
|
||||
const userId = cfg.userId ?? 'local';
|
||||
const quotaDb = cfg.quotaDb ?? null;
|
||||
// Tier enforcement is normally ON only when userTier is explicitly passed.
|
||||
// WAGGLE_EVAL_MODE=1 disables it unconditionally — the PA v5 eval harness
|
||||
// sets this so user-tier gates never confound measurement validity. This
|
||||
// env-var is eval-path-only; never set it in production code paths.
|
||||
// See PromptAssembler v5 brief §11.3.
|
||||
const evalModeActive = process.env.WAGGLE_EVAL_MODE === '1';
|
||||
const tierEnforced = evalModeActive ? false : cfg.userTier !== undefined;
|
||||
const tierCaps = TIER_CAPABILITIES[userTier];
|
||||
const allowedProviders = tierCaps.embeddingProviders as readonly string[];
|
||||
|
||||
// Initialize quota table if DB provided
|
||||
// Initialize the usage table if DB provided
|
||||
if (quotaDb) {
|
||||
ensureQuotaTable(quotaDb);
|
||||
}
|
||||
@@ -315,21 +267,6 @@ export async function createEmbeddingProvider(config?: EmbeddingProviderConfig):
|
||||
let availableProviders: EmbeddingProviderType[] = [];
|
||||
let probeTimestamp = new Date().toISOString();
|
||||
|
||||
/** Check quota before embedding. Throws if exceeded. Warns at 80%. */
|
||||
function checkQuota(count: number): void {
|
||||
if (!quotaDb || !tierEnforced) return;
|
||||
const quota = tierCaps.embeddingQuotaPerMonth;
|
||||
if (quota === -1) return; // unlimited
|
||||
const ym = getCurrentYearMonth();
|
||||
const used = getUsageCount(quotaDb, userId, ym);
|
||||
if (used + count > quota) {
|
||||
throw new EmbeddingQuotaExceededError(userTier, quota, used);
|
||||
}
|
||||
if (used + count >= quota * 0.8) {
|
||||
log.warn(`Embedding quota warning: ${used + count}/${quota} (${Math.round(((used + count) / quota) * 100)}%) for ${userTier} tier`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Record usage after successful embedding. */
|
||||
function recordUsage(count: number): void {
|
||||
if (!quotaDb) return;
|
||||
@@ -345,11 +282,6 @@ export async function createEmbeddingProvider(config?: EmbeddingProviderConfig):
|
||||
const requestedProvider = cfg.provider ?? 'auto';
|
||||
|
||||
if (requestedProvider !== 'auto' && requestedProvider !== 'mock') {
|
||||
// Explicit provider — tier-check only when tier is explicitly configured
|
||||
if (tierEnforced && !allowedProviders.includes(requestedProvider)) {
|
||||
const required = getMinimumTierForProvider(requestedProvider);
|
||||
throw new TierError(required, userTier);
|
||||
}
|
||||
log.info(`Trying ${requestedProvider}...`);
|
||||
const result = await probeProvider(requestedProvider, cfg);
|
||||
if (result) {
|
||||
@@ -358,15 +290,10 @@ export async function createEmbeddingProvider(config?: EmbeddingProviderConfig):
|
||||
log.info(`Trying ${requestedProvider}... OK`);
|
||||
}
|
||||
} else if (requestedProvider === 'auto') {
|
||||
// Auto: iterate chain, skip providers not allowed by tier
|
||||
// Auto: iterate the chain in order
|
||||
const chain: EmbeddingProviderType[] = ['inprocess', 'ollama', 'voyage', 'openai'];
|
||||
|
||||
for (const providerType of chain) {
|
||||
// Tier gate — skip providers not allowed (only when tier is explicitly configured)
|
||||
if (tierEnforced && !allowedProviders.includes(providerType)) {
|
||||
log.info(`Skipping ${providerType} (not available on ${userTier} tier)`);
|
||||
continue;
|
||||
}
|
||||
// Skip API providers without keys
|
||||
if (providerType === 'voyage' && !cfg.voyage?.apiKey) {
|
||||
log.info('Skipping voyage (no API key in Vault)');
|
||||
@@ -439,8 +366,6 @@ export async function createEmbeddingProvider(config?: EmbeddingProviderConfig):
|
||||
try {
|
||||
await runProbe();
|
||||
} catch (err) {
|
||||
// Re-throw tier errors — these are intentional enforcement, not probe failures
|
||||
if (err instanceof TierError) throw err;
|
||||
lastError = err instanceof Error ? err.message : String(err);
|
||||
activeEmbedder = createMockEmbedder(dims);
|
||||
activeType = 'mock';
|
||||
@@ -455,7 +380,6 @@ export async function createEmbeddingProvider(config?: EmbeddingProviderConfig):
|
||||
dimensions: dims,
|
||||
|
||||
async embed(text: string): Promise<Float32Array> {
|
||||
checkQuota(1);
|
||||
// Cap input to the active model's context so the backend never rejects
|
||||
// an oversized frame. Reverse-ported from OSS hive-mind (oss-drift triage R5, 2026-06-11).
|
||||
const capped = capEmbedText(text, maxEmbedCharsForModel(activeModelName));
|
||||
@@ -464,7 +388,6 @@ export async function createEmbeddingProvider(config?: EmbeddingProviderConfig):
|
||||
recordUsage(1);
|
||||
return result;
|
||||
} catch (err) {
|
||||
if (err instanceof EmbeddingQuotaExceededError) throw err;
|
||||
log.warn(`Embedding failed with ${activeType}, falling back to mock: ${(err as Error).message}`);
|
||||
lastError = (err as Error).message;
|
||||
const fallback = mockEmbed(capped, dims);
|
||||
@@ -475,7 +398,6 @@ export async function createEmbeddingProvider(config?: EmbeddingProviderConfig):
|
||||
|
||||
async embedBatch(texts: string[]): Promise<Float32Array[]> {
|
||||
if (texts.length === 0) return [];
|
||||
checkQuota(texts.length);
|
||||
// Cap each input first so one oversized frame can't make the backend
|
||||
// reject the whole request. Reverse-ported from OSS hive-mind
|
||||
// (oss-drift triage R5, 2026-06-11).
|
||||
@@ -485,7 +407,6 @@ export async function createEmbeddingProvider(config?: EmbeddingProviderConfig):
|
||||
recordUsage(texts.length);
|
||||
return result;
|
||||
} catch (err) {
|
||||
if (err instanceof EmbeddingQuotaExceededError) throw err;
|
||||
// Skip-not-abort: re-embed per-text so a single backend-rejected input
|
||||
// degrades alone instead of mock-poisoning the WHOLE batch.
|
||||
log.warn(`Batch embedding failed with ${activeType}, re-embedding per-text: ${(err as Error).message}`);
|
||||
@@ -517,19 +438,7 @@ export async function createEmbeddingProvider(config?: EmbeddingProviderConfig):
|
||||
},
|
||||
|
||||
getQuotaStatus(): EmbeddingQuotaStatus {
|
||||
const quota = tierCaps.embeddingQuotaPerMonth;
|
||||
if (!quotaDb || quota === -1) {
|
||||
return { tier: userTier, quota: -1, used: 0, remaining: -1, percentage: 0, resetsAt: getNextMonthReset() };
|
||||
}
|
||||
const used = getUsageCount(quotaDb, userId, getCurrentYearMonth());
|
||||
return {
|
||||
tier: userTier,
|
||||
quota,
|
||||
used,
|
||||
remaining: Math.max(0, quota - used),
|
||||
percentage: Math.round((used / quota) * 100),
|
||||
resetsAt: getNextMonthReset(),
|
||||
};
|
||||
return { quota: -1, used: 0, remaining: -1, percentage: 0, resetsAt: getNextMonthReset() };
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -11,18 +11,16 @@
|
||||
* `{ kind:'none', fallback:true }` so the frontend falls back to Tier 0.
|
||||
*/
|
||||
|
||||
import type { InterpretResult, ResolvedAction, Tier } from '@waggle/shared';
|
||||
import type { InterpretResult, ResolvedAction } from '@waggle/shared';
|
||||
import {
|
||||
buildActionCatalog,
|
||||
validateAndBuildAction,
|
||||
checkTier,
|
||||
type RegistryContext,
|
||||
} from './command-registry.js';
|
||||
|
||||
export interface InterpretDeps {
|
||||
text: string;
|
||||
workspaceId?: string;
|
||||
currentTier: Tier;
|
||||
workspaces: ReadonlyArray<{ id: string; name: string }>;
|
||||
/** The workspace "now" block (awareness + recent sessions + pending). */
|
||||
memoryContext: string;
|
||||
@@ -93,21 +91,6 @@ function buildValidStep(
|
||||
return validateAndBuildAction(actionId, params, ctx);
|
||||
}
|
||||
|
||||
/** Apply the tier gate to a resolved single action. */
|
||||
function finalizeAction(action: ResolvedAction, currentTier: Tier): InterpretResult {
|
||||
const tier = checkTier(action.id, currentTier);
|
||||
if (tier.gated && tier.requiredTier) {
|
||||
return {
|
||||
kind: 'tier_gated',
|
||||
capability: action.label,
|
||||
requiredTier: tier.requiredTier,
|
||||
actualTier: currentTier,
|
||||
message: `${action.label} requires the ${tier.requiredTier} tier.`,
|
||||
};
|
||||
}
|
||||
return { kind: 'action', action };
|
||||
}
|
||||
|
||||
export async function interpretCommand(deps: InterpretDeps): Promise<InterpretResult> {
|
||||
const ctx: RegistryContext = { workspaceId: deps.workspaceId, workspaces: deps.workspaces };
|
||||
|
||||
@@ -136,7 +119,7 @@ export async function interpretCommand(deps: InterpretDeps): Promise<InterpretRe
|
||||
if (!action) {
|
||||
return { kind: 'none', fallback: true, message: "I couldn't map that to an action I can run." };
|
||||
}
|
||||
return finalizeAction(action, deps.currentTier);
|
||||
return { kind: 'action', action };
|
||||
}
|
||||
|
||||
case 'plan': {
|
||||
@@ -144,7 +127,7 @@ export async function interpretCommand(deps: InterpretDeps): Promise<InterpretRe
|
||||
// a true multi-step plan downgrades to clarify (fast-follow executes it).
|
||||
const rawSteps = Array.isArray(parsed.steps) ? parsed.steps : [];
|
||||
const steps = rawSteps.map((s) => buildValidStep(s, ctx)).filter((s): s is ResolvedAction => s !== null);
|
||||
if (steps.length === 1) return finalizeAction(steps[0], deps.currentTier);
|
||||
if (steps.length === 1) return { kind: 'action', action: steps[0] };
|
||||
if (steps.length > 1) {
|
||||
const labels = steps.map((s) => s.label).join(' → ');
|
||||
return {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* The core safety property: the LLM resolver returns only an action `id` +
|
||||
* `params`. THIS module — never the model — maps the id onto an executable
|
||||
* shape (a navigation target or a server-derived endpoint), validates params,
|
||||
* and stamps `sideEffect` / `riskLevel` / `requiredTier`. An unknown id, or
|
||||
* and stamps `sideEffect` / `riskLevel`. An unknown id, or
|
||||
* params that fail validation, resolve to `null` (→ the caller returns `none`).
|
||||
*
|
||||
* No new execution layer: navigation reuses the CommandResult `onNavigate`
|
||||
@@ -15,9 +15,6 @@
|
||||
|
||||
import {
|
||||
MCP_CATALOG,
|
||||
assertTierCapability,
|
||||
TierError,
|
||||
type Tier,
|
||||
type RiskLevel,
|
||||
type ResolvedAction,
|
||||
} from '@waggle/shared';
|
||||
@@ -88,7 +85,6 @@ interface ActionDescriptor {
|
||||
params: Record<string, ParamSpec>;
|
||||
sideEffect: boolean;
|
||||
riskLevel: RiskLevel;
|
||||
requiredTier?: Tier;
|
||||
/** Build the executable shape, or return null when params are invalid. */
|
||||
build: (
|
||||
params: Record<string, unknown>,
|
||||
@@ -219,32 +215,14 @@ export function validateAndBuildAction(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Tier gate for a resolved action, reusing the canonical `assertTierCapability`.
|
||||
* Returns `{ gated: true, requiredTier }` when the current tier is below the
|
||||
* action's `requiredTier`.
|
||||
*/
|
||||
export function checkTier(actionId: string, currentTier: Tier): { gated: boolean; requiredTier?: Tier } {
|
||||
const descriptor = BY_ID.get(actionId);
|
||||
if (!descriptor?.requiredTier) return { gated: false };
|
||||
try {
|
||||
assertTierCapability(currentTier, descriptor.requiredTier);
|
||||
return { gated: false };
|
||||
} catch (e) {
|
||||
if (e instanceof TierError) return { gated: true, requiredTier: descriptor.requiredTier };
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Render the registry + nav/MCP catalogs as the system-prompt action catalog. */
|
||||
export function buildActionCatalog(): string {
|
||||
const actions = ACTION_REGISTRY.map((d) => {
|
||||
const params = Object.entries(d.params)
|
||||
.map(([k, s]) => `${k}${s.required ? '' : '?'}: ${s.description}${s.enum ? ` (one of: ${s.enum.join(', ')})` : ''}`)
|
||||
.join('; ');
|
||||
const tier = d.requiredTier ? ` [requires ${d.requiredTier}]` : '';
|
||||
const eff = d.sideEffect ? ' [side-effect → approval]' : '';
|
||||
return `- ${d.id}${tier}${eff}: ${d.description}\n params: ${params || '(none)'}`;
|
||||
return `- ${d.id}${eff}: ${d.description}\n params: ${params || '(none)'}`;
|
||||
}).join('\n');
|
||||
|
||||
const navList = NAV_TARGETS.map((t) => `- ${t.id} (${t.label}) — ${t.hints}`).join('\n');
|
||||
|
||||
@@ -69,8 +69,7 @@ import {
|
||||
} from '@waggle/agent';
|
||||
import { PluginRuntimeManager, getStarterSkillsDir, validatePluginManifest } from '@waggle/sdk';
|
||||
import { MarketplaceDB, MarketplaceSync, seedMcpServers, seedNewSources } from '@waggle/marketplace';
|
||||
import { parseTier, type RiskLevel } from '@waggle/shared';
|
||||
import { readTierFromDataDir } from '../middleware/assert-tier.js';
|
||||
import type { RiskLevel } from '@waggle/shared';
|
||||
import { runConnectorFetch } from './connector-harvest.js';
|
||||
import { writeAutoSyncSummaryFrame } from './harvest-autosync-frame.js';
|
||||
import { runLoopTick } from './loop-executor.js';
|
||||
@@ -163,7 +162,6 @@ import { waggleSignalRoutes } from './routes/waggle-signals.js';
|
||||
import { providerRoutes } from './routes/providers.js';
|
||||
import { profileRoutes } from './routes/profile.js';
|
||||
import { telemetryRoutes } from './routes/telemetry.js';
|
||||
import { stripeRoutes } from '../stripe/index.js';
|
||||
import { agentGroupRoutes } from './routes/agent-groups.js';
|
||||
import { localJobRoutes } from './routes/jobs.js';
|
||||
import { agentEntityRoutes } from './routes/agents.js';
|
||||
@@ -196,8 +194,7 @@ import {
|
||||
type ProactiveMessage,
|
||||
} from './proactive-handlers.js';
|
||||
import { generateMonthlyAssessment, saveAssessmentToMind } from './monthly-assessment.js';
|
||||
import { WorkspaceSessionManager } from './workspace-sessions.js';
|
||||
import { maxWorkspaceSessionsForTier } from './tier-session-cap.js';
|
||||
import { MAX_WORKSPACE_SESSIONS, WorkspaceSessionManager } from './workspace-sessions.js';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { LocalJobStore } from './job-store.js';
|
||||
import { AgentRunRegistry } from './agent-run-registry.js';
|
||||
@@ -213,8 +210,6 @@ export interface LocalConfig {
|
||||
instanceId?: string;
|
||||
/** Governed CLI execution — allowlist of program names the agent may run. */
|
||||
cli?: { allowlist?: string[] };
|
||||
/** Active subscription tier, when known (drives session/feature caps). */
|
||||
tier?: string;
|
||||
/** True only when startService owns the LiteLLM child lifecycle. */
|
||||
manageLiteLLM?: boolean;
|
||||
/** Stable child-process port, retained even while requests use a fallback proxy. */
|
||||
@@ -495,9 +490,6 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
|
||||
&& rawDesktopBootstrapToken.length <= 200
|
||||
? rawDesktopBootstrapToken
|
||||
: null;
|
||||
const resolvedTier = parseTier(String(fullConfig.tier ?? '')) ?? readTierFromDataDir(fullConfig.dataDir);
|
||||
fullConfig.tier = resolvedTier;
|
||||
|
||||
const server = Fastify({ logger: false });
|
||||
const localJobStore = new LocalJobStore();
|
||||
server.decorate('localJobStore', localJobStore);
|
||||
@@ -1289,9 +1281,8 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
|
||||
|
||||
// ── Workspace Session Manager ────────────────────────────────────
|
||||
// Manages concurrent workspace sessions with independent minds, orchestrators,
|
||||
// and tools. Cap is tied to the active tier at startup and when the tier changes.
|
||||
const sessionManager = new WorkspaceSessionManager(3);
|
||||
sessionManager.setMaxSessions(maxWorkspaceSessionsForTier(resolvedTier));
|
||||
// and tools.
|
||||
const sessionManager = new WorkspaceSessionManager(MAX_WORKSPACE_SESSIONS);
|
||||
server.decorate('sessionManager', sessionManager);
|
||||
|
||||
/**
|
||||
@@ -2893,7 +2884,6 @@ Return ONLY the improved system prompt text. No commentary, no markdown fences,
|
||||
await server.register(telemetryRoutes);
|
||||
await server.register(agentGroupRoutes);
|
||||
await server.register(localJobRoutes);
|
||||
await server.register(stripeRoutes);
|
||||
await server.register(harvestRoutes);
|
||||
await server.register(wikiRoutes);
|
||||
await server.register(identityRoutes);
|
||||
|
||||
@@ -40,10 +40,6 @@ import { assertSafeSegment, authHeaders, clampStr, clampStrArray } from './valid
|
||||
* spawn's {workspaceId, sessionId} in an in-process map keyed by agent id, and
|
||||
* liveStatus/pause act only on that recorded session. Entries are lost on
|
||||
* restart (the stored status then applies) — acceptable for one-shot C23 runs.
|
||||
*
|
||||
* Tier gating: agent creation is deliberately UNGATED — CLAUDE.md §1 moat
|
||||
* strategy: "Agents are free (they generate memory)", matching the executor
|
||||
* (`POST /api/fleet/spawn` is free for all tiers).
|
||||
*/
|
||||
|
||||
const AGENT_TYPES: readonly AgentType[] = ['personal', 'workspace', 'team', 'autonomous'];
|
||||
@@ -187,9 +183,7 @@ export const agentEntityRoutes: FastifyPluginAsync = async (server) => {
|
||||
return { agents, count: agents.length };
|
||||
});
|
||||
|
||||
// POST /api/agents — create. NOT tier-gated: CLAUDE.md §1 moat strategy says
|
||||
// "Agents are free (they generate memory)" and the executor (fleet spawn) is
|
||||
// free for all tiers — a tier gate here would be an incoherent surface.
|
||||
// POST /api/agents — create.
|
||||
// Blueprint hard gate: goal, model, memoryScopes and autonomyLevel are
|
||||
// required so the stored record is the full effective surface ("no hidden
|
||||
// tool/memory access").
|
||||
|
||||
@@ -34,7 +34,6 @@ import { loadSkills } from '@waggle/agent';
|
||||
import { buildWorkspaceNowBlock, formatWorkspaceNowPrompt } from './workspace-context.js';
|
||||
import { searchSessions } from './session-utils.js';
|
||||
import { interpretCommand } from '../command-interpret.js';
|
||||
import { readTierFromRequest } from '../../middleware/assert-tier.js';
|
||||
|
||||
/**
|
||||
* Memoized `loadSkills()` — the federated `/search` hot path runs per keystroke,
|
||||
@@ -342,7 +341,6 @@ export const commandRoutes: FastifyPluginAsync = async (server) => {
|
||||
const result = await interpretCommand({
|
||||
text,
|
||||
workspaceId,
|
||||
currentTier: readTierFromRequest(request),
|
||||
workspaces,
|
||||
memoryContext,
|
||||
llm,
|
||||
|
||||
@@ -1,30 +1,8 @@
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { ConnectorHealth } from '@waggle/shared';
|
||||
import { getCapabilities, parseTier, type Tier } from '@waggle/shared';
|
||||
import type { RecordAuditInput } from '@waggle/core';
|
||||
import { JiraConnector, SalesforceConnector } from '@waggle/agent';
|
||||
|
||||
/**
|
||||
* Tier cap for connecting connectors. All current tiers (Solo + Team) have an
|
||||
* unlimited connectorLimit (-1); the gate is retained for any future finite cap.
|
||||
* Re-connecting an already-connected connector (token refresh) does NOT
|
||||
* count against the cap. Returns the 403 payload data if the cap is exceeded,
|
||||
* else null. Pure (no IO) so it is unit-testable.
|
||||
*/
|
||||
export function connectorCapExceeded(
|
||||
tier: Tier,
|
||||
connectedIds: string[],
|
||||
id: string,
|
||||
): { limit: number; current: number } | null {
|
||||
const limit = getCapabilities(tier).connectorLimit;
|
||||
if (limit <= 0) return null; // unlimited
|
||||
if (connectedIds.includes(id)) return null; // already connected — token refresh
|
||||
if (connectedIds.length >= limit) return { limit, current: connectedIds.length };
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Vault sub-key holding the C16 manual-sync stamp. Matches the
|
||||
* `connector:{id}:*` prefix so disconnect/revoke auto-clean it. */
|
||||
const lastSyncKey = (id: string) => `connector:${id}:lastSync`;
|
||||
@@ -171,32 +149,6 @@ export async function connectorRoutes(fastify: FastifyInstance) {
|
||||
}
|
||||
}
|
||||
|
||||
// Tier cap — connectors are unlimited on all current tiers (Solo + Team);
|
||||
// gate retained for any future finite cap. Count REAL credentialed
|
||||
// connections (getDefinitions status==='connected' excludes the always-on
|
||||
// mock channels). Marker `error:'TIER_INSUFFICIENT'` so the adapter's tier
|
||||
// event + the install store's tier classification light up. Fail-open if the
|
||||
// tier read throws (matches the workspace-limit gate).
|
||||
try {
|
||||
const configPath = join(fastify.localConfig.dataDir, 'config.json');
|
||||
const tierRaw = existsSync(configPath) ? JSON.parse(readFileSync(configPath, 'utf-8')).tier : '';
|
||||
const tier = parseTier(String(tierRaw ?? '')) ?? 'FREE';
|
||||
const connectedIds = registry
|
||||
? registry.getDefinitions().filter(d => d.status === 'connected').map(d => d.id)
|
||||
: [];
|
||||
const cap = connectorCapExceeded(tier, connectedIds, id);
|
||||
if (cap) {
|
||||
return reply.code(403).send({
|
||||
error: 'TIER_INSUFFICIENT',
|
||||
required: 'TEAMS',
|
||||
actual: tier,
|
||||
message: `Connector limit reached for ${tier} (${cap.limit} max). Upgrade to connect more.`,
|
||||
limit: cap.limit,
|
||||
current: cap.current,
|
||||
});
|
||||
}
|
||||
} catch { /* tier read failed — allow the connect (fail-open) */ }
|
||||
|
||||
const connector = registry?.get(id);
|
||||
const authType = connector?.authType ?? 'bearer';
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
*/
|
||||
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { requireTier } from '../../middleware/assert-tier.js';
|
||||
|
||||
// ── Types (inline to avoid cross-package resolution issues in worktrees) ──
|
||||
|
||||
@@ -95,9 +94,8 @@ export const costRoutes: FastifyPluginAsync = async (server) => {
|
||||
}
|
||||
|
||||
// GET /api/cost/summary — total tokens, estimated cost, daily breakdown.
|
||||
// Intentionally FREE for all tiers (P22): it powers the personal Telemetry
|
||||
// dev-mode cost/budget view. The TEAM cost-visibility surface is the separate
|
||||
// /api/cost/by-workspace + /api/costs alias (both requireTier('TEAMS')).
|
||||
// Powers the Telemetry cost/budget view; /api/cost/by-workspace adds the
|
||||
// per-workspace breakdown and /api/costs is an alias of this route.
|
||||
server.get<{
|
||||
Querystring: { days?: string };
|
||||
}>('/api/cost/summary', async (request) => {
|
||||
@@ -220,7 +218,7 @@ export const costRoutes: FastifyPluginAsync = async (server) => {
|
||||
});
|
||||
|
||||
// GET /api/cost/by-workspace — per-workspace token usage breakdown
|
||||
server.get('/api/cost/by-workspace', { preHandler: [requireTier('TEAMS')] }, async () => {
|
||||
server.get('/api/cost/by-workspace', async () => {
|
||||
const entries = getEntries();
|
||||
const workspaces = server.workspaceManager.list();
|
||||
|
||||
@@ -281,8 +279,7 @@ export const costRoutes: FastifyPluginAsync = async (server) => {
|
||||
|
||||
// D2: Alias /api/costs → /api/cost/summary for API discoverability
|
||||
// Use internal routing instead of 302 redirect so clients get a direct 200 response
|
||||
// Cost visibility is a Team feature — gated identically to /api/cost/by-workspace.
|
||||
server.get('/api/costs', { preHandler: [requireTier('TEAMS')] }, async (request, reply) => {
|
||||
server.get('/api/costs', async (request, reply) => {
|
||||
const days = (request.query as Record<string, string>)?.days;
|
||||
const url = days ? `/api/cost/summary?days=${days}` : '/api/cost/summary';
|
||||
const response = await server.inject({ method: 'GET', url, headers: request.headers });
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
* The read side (`GET /api/embedding/status`) and reprobe
|
||||
* (`POST /api/embedding/reprobe`) live inline in local/index.ts, where they have
|
||||
* closure access to the boot-time embedding config. This plugin owns
|
||||
* `POST /api/embedding/provider`: validate → tier-gate → persist the choice.
|
||||
* `POST /api/embedding/provider`: validate → persist the choice. Every provider is
|
||||
* selectable (ADR-0001).
|
||||
*
|
||||
* Hot-swap note: the live embedder is created once at boot and threaded BY
|
||||
* REFERENCE into the Orchestrator, mind search, and the vector-backfill path.
|
||||
@@ -19,8 +20,7 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { FastifyInstance, FastifyPluginAsync } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import { WaggleConfig, getMinimumTierForProvider, type EmbeddingProviderType } from '@waggle/core';
|
||||
import { TIER_CAPABILITIES, parseTier, getEffectiveTier, type Tier } from '@waggle/shared';
|
||||
import { WaggleConfig } from '@waggle/core';
|
||||
import { validateBody } from '../../validate-body.js';
|
||||
|
||||
/**
|
||||
@@ -35,19 +35,6 @@ const setProviderSchema = z.object({
|
||||
provider: z.enum(SELECTABLE_PROVIDERS),
|
||||
});
|
||||
|
||||
/** Effective tier from config.json (mirrors settings.ts readTierConfig + trial resolution). */
|
||||
function readEffectiveTier(dataDir: string): Tier {
|
||||
try {
|
||||
const configPath = path.join(dataDir, 'config.json');
|
||||
if (fs.existsSync(configPath)) {
|
||||
const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
const parsed = parseTier(String(raw.tier ?? '')) ?? 'FREE';
|
||||
return getEffectiveTier(parsed, raw.trialStartedAt ?? null);
|
||||
}
|
||||
} catch { /* fall through to FREE */ }
|
||||
return 'FREE';
|
||||
}
|
||||
|
||||
/** True when EMBEDDING_PROVIDER env var is set — it wins over the persisted choice. */
|
||||
function envOverrideProvider(): string | null {
|
||||
const v = process.env.EMBEDDING_PROVIDER?.trim();
|
||||
@@ -103,22 +90,6 @@ export const embeddingRoutes: FastifyPluginAsync = async (server) => {
|
||||
});
|
||||
}
|
||||
|
||||
// Tier gate — 'auto' is always allowed; an explicit provider must be in
|
||||
// the tier's allowed set (TIER_CAPABILITIES.embeddingProviders).
|
||||
if (provider !== 'auto') {
|
||||
const tier = readEffectiveTier(server.localConfig.dataDir);
|
||||
const allowed = TIER_CAPABILITIES[tier].embeddingProviders as readonly string[];
|
||||
if (!allowed.includes(provider)) {
|
||||
const requiredTier = getMinimumTierForProvider(provider as EmbeddingProviderType);
|
||||
return reply.status(403).send({
|
||||
error: 'TIER_REQUIRED',
|
||||
message: `The "${provider}" embedding provider requires the ${requiredTier} tier or higher (current: ${tier}).`,
|
||||
requiredTier,
|
||||
currentTier: tier,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Persist (setEmbeddingProvider does not save on its own).
|
||||
const config = new WaggleConfig(server.localConfig.dataDir);
|
||||
config.setEmbeddingProvider(provider);
|
||||
|
||||
@@ -4,13 +4,11 @@
|
||||
*/
|
||||
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { parseTier, type GoalAncestry } from '@waggle/shared';
|
||||
import { requireTier } from '../../middleware/assert-tier.js';
|
||||
import type { GoalAncestry } from '@waggle/shared';
|
||||
import { runAgentLoop, isEnabled, detectTaskShape, listPersonas } from '@waggle/agent';
|
||||
import { emitWaggleSignal } from './waggle-signals.js';
|
||||
import { persistMessage } from './chat-persistence.js';
|
||||
import { createLogger } from '../logger.js';
|
||||
import { maxWorkspaceSessionsForTier } from '../tier-session-cap.js';
|
||||
import { spawnIsolatedFleetRun } from '../fleet-run-executor.js';
|
||||
import { resolveUsableModel } from '../model-availability.js';
|
||||
|
||||
@@ -58,15 +56,12 @@ export async function fleetRoutes(fastify: FastifyInstance) {
|
||||
};
|
||||
});
|
||||
|
||||
// Tier-based maxSessions: FREE=10, TEAMS=25, ENTERPRISE/TRIAL=100
|
||||
const tierRaw = fastify.localConfig?.tier ?? '';
|
||||
const tier = parseTier(String(tierRaw)) ?? 'FREE';
|
||||
const maxSessions = maxWorkspaceSessionsForTier(tier);
|
||||
const maxSessions = sessionManager.getMaxSessions();
|
||||
|
||||
return { sessions, count: sessions.length, maxSessions };
|
||||
});
|
||||
|
||||
// POST /api/fleet/spawn — spawn a new agent session (free for all tiers — agents generate memory)
|
||||
// POST /api/fleet/spawn — spawn a new agent session
|
||||
//
|
||||
// FR #15 Phase A: properly create the workspace session via getOrCreate so
|
||||
// Room/Mission Control register it as live, and emit an `agent:spawned`
|
||||
|
||||
@@ -18,7 +18,6 @@ import { validateSkillMd } from '@waggle/sdk';
|
||||
import { safeFetch, assertUrlAllowed, scanForInjection } from '@waggle/agent';
|
||||
import { getKvarkConfig } from '../../kvark/kvark-config.js';
|
||||
import { emitNotification } from './notifications.js';
|
||||
import { requireTier } from '../../middleware/assert-tier.js';
|
||||
import { loadMcpConfig, removeMcpServerEntry } from '../mcp-config.js';
|
||||
import { enqueueHeldAction } from '../held-action-executor.js';
|
||||
import { isMarketplaceBackgroundSyncDisabled } from '../marketplace-background-sync.js';
|
||||
@@ -187,7 +186,7 @@ export async function marketplaceRoutes(fastify: FastifyInstance) {
|
||||
// Returns enterprise packs that require KVARK. Only populated when
|
||||
// KVARK credentials are configured in the vault.
|
||||
|
||||
fastify.get('/api/marketplace/enterprise-packs', { preHandler: [requireTier('ENTERPRISE')] }, async (request, reply) => {
|
||||
fastify.get('/api/marketplace/enterprise-packs', async (request, reply) => {
|
||||
const vault = fastify.vault;
|
||||
const kvarkConfigured = vault ? getKvarkConfig(vault) !== null : false;
|
||||
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { FastifyInstance, FastifyPluginAsync } from 'fastify';
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import { WaggleConfig } from '@waggle/core';
|
||||
import { type Tier, TIERS, TIER_CAPABILITIES, parseTier, getCapabilities, getEffectiveTier, trialDaysRemaining } from '@waggle/shared';
|
||||
import type { AutonomyLevel } from '@waggle/agent';
|
||||
import { requireTier } from '../../middleware/assert-tier.js';
|
||||
import { validateBody } from '../../validate-body.js';
|
||||
import { probeProviderKey, validateKeyFormat } from '../llm-key-probe.js';
|
||||
import { resolveExplicitRoutableModel, resolveUsableModel } from '../model-availability.js';
|
||||
import { maxWorkspaceSessionsForTier } from '../tier-session-cap.js';
|
||||
import { applyProviderKeyToEnv } from '../provider-env.js';
|
||||
import { refreshManagedLiteLLM, type LiteLLMRefreshResult } from '../litellm-runtime-config.js';
|
||||
|
||||
@@ -44,11 +41,6 @@ function maskApiKey(key: string): string {
|
||||
return key.slice(0, 7) + '...' + key.slice(-4);
|
||||
}
|
||||
|
||||
function applyRuntimeTier(server: FastifyInstance, tier: Tier): void {
|
||||
server.localConfig.tier = tier;
|
||||
server.sessionManager?.setMaxSessions(maxWorkspaceSessionsForTier(tier));
|
||||
}
|
||||
|
||||
export const settingsRoutes: FastifyPluginAsync = async (server) => {
|
||||
// GET /api/settings — read config (keys from vault, metadata from vault+config)
|
||||
server.get('/api/settings', async () => {
|
||||
@@ -445,162 +437,23 @@ export const settingsRoutes: FastifyPluginAsync = async (server) => {
|
||||
return updated;
|
||||
});
|
||||
|
||||
// ── Tier detection ───────────────────────────────────────────────────
|
||||
// Tier is read from config.json → tier field (defaults to FREE).
|
||||
// Canonical values: TRIAL | FREE | TEAMS | ENTERPRISE (@waggle/shared
|
||||
// tiers.ts). Legacy names (PRO/BASIC/lowercase) auto-migrate via parseTier().
|
||||
// The Stripe webhook (packages/server/src/stripe/webhook.ts) writes this field.
|
||||
|
||||
function readTierConfig(dataDir: string): { tier: Tier; trialStartedAt: string | null } {
|
||||
try {
|
||||
const configPath = path.join(dataDir, 'config.json');
|
||||
if (fs.existsSync(configPath)) {
|
||||
const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
const parsed = parseTier(String(raw.tier ?? ''));
|
||||
if (parsed) return { tier: parsed, trialStartedAt: raw.trialStartedAt ?? null };
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
return { tier: 'FREE', trialStartedAt: null };
|
||||
}
|
||||
|
||||
// GET /api/tier — authoritative tier source for frontend
|
||||
server.get('/api/tier', async () => {
|
||||
const { tier: rawTier, trialStartedAt } = readTierConfig(server.localConfig.dataDir);
|
||||
const tier = getEffectiveTier(rawTier, trialStartedAt);
|
||||
const caps = getCapabilities(tier);
|
||||
const daysRemaining = trialDaysRemaining(trialStartedAt);
|
||||
// Usage counts for limit display
|
||||
const workspaceCount = server.workspaceManager?.list().length ?? 0;
|
||||
return {
|
||||
tier,
|
||||
rawTier,
|
||||
trialStartedAt,
|
||||
trialDaysRemaining: daysRemaining,
|
||||
trialExpired: rawTier === 'TRIAL' && tier === 'FREE',
|
||||
capabilities: caps,
|
||||
teamsServerUrl: process.env.DATABASE_URL
|
||||
? `http://127.0.0.1:${process.env.TEAMS_SERVER_PORT ?? '3101'}`
|
||||
: null,
|
||||
teamsServerAvailable: !!process.env.DATABASE_URL,
|
||||
usage: {
|
||||
workspaceCount,
|
||||
},
|
||||
// Legacy shape — kept for backward compatibility with existing frontend
|
||||
limits: {
|
||||
maxWorkspaces: caps.workspaceLimit,
|
||||
maxSessions: tier === 'FREE' ? 10 : 25,
|
||||
maxMembers: caps.teamMembersLimit,
|
||||
features: {
|
||||
teams: caps.sharedWorkspaces,
|
||||
marketplace: true,
|
||||
budgetControls: caps.adminPanel,
|
||||
kvark: tier === 'ENTERPRISE',
|
||||
governance: tier === 'ENTERPRISE',
|
||||
customModels: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// PATCH /api/tier — change tier (testing/dev — will be replaced by Stripe webhook)
|
||||
server.patch<{
|
||||
Body: { tier: string };
|
||||
}>('/api/tier', async (request, reply) => {
|
||||
// AV-3: this dev/test-only override must NOT be a production privilege-escalation
|
||||
// path. Under the loopback-trust model any local page/extension could PATCH a paid
|
||||
// tier for free (no payment, no auth). Fail closed — disabled unless explicitly
|
||||
// enabled for dev/testing. Legit tier changes flow through Stripe (sync/webhook)
|
||||
// and POST /api/tier/start-trial.
|
||||
if (process.env.WAGGLE_ALLOW_TIER_OVERRIDE !== '1') {
|
||||
return reply.status(403).send({ error: 'Tier override disabled', code: 'TIER_OVERRIDE_DISABLED' });
|
||||
}
|
||||
const { tier: tierRaw } = request.body ?? {};
|
||||
const parsed = parseTier(String(tierRaw ?? ''));
|
||||
if (!parsed) {
|
||||
return reply.status(400).send({ error: `Invalid tier. Must be one of: ${TIERS.join(', ')}` });
|
||||
}
|
||||
|
||||
const configPath = path.join(server.localConfig.dataDir, 'config.json');
|
||||
let raw: Record<string, unknown> = {};
|
||||
try {
|
||||
if (fs.existsSync(configPath)) {
|
||||
raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
}
|
||||
} catch { /* fresh */ }
|
||||
|
||||
raw.tier = parsed;
|
||||
fs.writeFileSync(configPath, JSON.stringify(raw, null, 2), 'utf-8');
|
||||
applyRuntimeTier(server, parsed);
|
||||
|
||||
return { tier: parsed, capabilities: getCapabilities(parsed), updated: true };
|
||||
});
|
||||
|
||||
// POST /api/tier/start-trial — atomic trial start.
|
||||
//
|
||||
// Sets `tier='TRIAL'` + `trialStartedAt=now` in a single write. Idempotent
|
||||
// by design: if `trialStartedAt` is already set, returns 409 with the
|
||||
// current tier state — a user gets exactly one 15-day trial. The previous
|
||||
// path (client-side `adapter.updateSettings({ tier: 'TRIAL', trialStartedAt })`)
|
||||
// was doubly broken: `updateSettings` didn't exist on the adapter, and
|
||||
// `PATCH /api/tier` ignores `trialStartedAt`, so trials silently never
|
||||
// started. See UpgradeModal `onStartTrial` and OnboardingWizard completion.
|
||||
server.post('/api/tier/start-trial', async (_request, reply) => {
|
||||
const configPath = path.join(server.localConfig.dataDir, 'config.json');
|
||||
let raw: Record<string, unknown> = {};
|
||||
try {
|
||||
if (fs.existsSync(configPath)) {
|
||||
raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
}
|
||||
} catch { /* fresh */ }
|
||||
|
||||
if (typeof raw.trialStartedAt === 'string' && raw.trialStartedAt.length > 0) {
|
||||
const existingTier = parseTier(String(raw.tier ?? '')) ?? 'FREE';
|
||||
const effective = getEffectiveTier(existingTier, raw.trialStartedAt);
|
||||
return reply.status(409).send({
|
||||
error: 'TRIAL_ALREADY_STARTED',
|
||||
message: 'A trial has already been started for this installation.',
|
||||
tier: effective,
|
||||
rawTier: existingTier,
|
||||
trialStartedAt: raw.trialStartedAt,
|
||||
trialDaysRemaining: trialDaysRemaining(raw.trialStartedAt),
|
||||
trialExpired: existingTier === 'TRIAL' && effective === 'FREE',
|
||||
});
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
raw.tier = 'TRIAL';
|
||||
raw.trialStartedAt = now;
|
||||
fs.writeFileSync(configPath, JSON.stringify(raw, null, 2), 'utf-8');
|
||||
applyRuntimeTier(server, 'TRIAL');
|
||||
|
||||
return {
|
||||
tier: 'TRIAL' as Tier,
|
||||
rawTier: 'TRIAL' as Tier,
|
||||
trialStartedAt: now,
|
||||
trialDaysRemaining: trialDaysRemaining(now),
|
||||
trialExpired: false,
|
||||
capabilities: getCapabilities('TRIAL'),
|
||||
};
|
||||
});
|
||||
|
||||
// ── Cloud Sync ────────────────────────────────────────────────────
|
||||
|
||||
server.get('/api/cloud-sync', async () => {
|
||||
const { tier } = readTierConfig(server.localConfig.dataDir);
|
||||
const caps = getCapabilities(tier);
|
||||
const configPath = path.join(server.localConfig.dataDir, 'config.json');
|
||||
let raw: Record<string, unknown> = {};
|
||||
try { if (fs.existsSync(configPath)) raw = JSON.parse(fs.readFileSync(configPath, 'utf-8')); } catch { /* */ }
|
||||
return {
|
||||
available: caps.cloudSync,
|
||||
// Cloud sync runs through the team server, which the community edition
|
||||
// does not ship (ADR-0003).
|
||||
available: false,
|
||||
enabled: raw.cloudSyncEnabled === true,
|
||||
tier,
|
||||
teamServerUrl: (raw.teamServer as Record<string, unknown>)?.url ?? null,
|
||||
connected: !!((raw.teamServer as Record<string, unknown>)?.token),
|
||||
};
|
||||
});
|
||||
|
||||
server.post<{ Body: { enabled: boolean } }>('/api/cloud-sync/toggle', { preHandler: [requireTier('TEAMS')] }, async (request, reply) => {
|
||||
server.post<{ Body: { enabled: boolean } }>('/api/cloud-sync/toggle', async (request, reply) => {
|
||||
const { enabled } = request.body ?? {};
|
||||
if (typeof enabled !== 'boolean') return reply.code(400).send({ error: 'enabled must be a boolean' });
|
||||
const configPath = path.join(server.localConfig.dataDir, 'config.json');
|
||||
@@ -613,7 +466,7 @@ export const settingsRoutes: FastifyPluginAsync = async (server) => {
|
||||
|
||||
// ── Admin Overview ────────────────────────────────────────────────
|
||||
|
||||
server.get('/api/admin/overview', { preHandler: [requireTier('TEAMS')] }, async () => {
|
||||
server.get('/api/admin/overview', async () => {
|
||||
const workspaces = server.workspaceManager?.list() ?? [];
|
||||
return {
|
||||
usage: { totalInputTokens: 0, totalOutputTokens: 0 },
|
||||
@@ -635,7 +488,7 @@ export const settingsRoutes: FastifyPluginAsync = async (server) => {
|
||||
// GET /api/admin/audit-export — download audit log as JSON or CSV
|
||||
server.get<{
|
||||
Querystring: { from?: string; to?: string; format?: 'json' | 'csv' };
|
||||
}>('/api/admin/audit-export', { preHandler: [requireTier('TEAMS')] }, async (request, reply) => {
|
||||
}>('/api/admin/audit-export', async (request, reply) => {
|
||||
const { from, to, format = 'json' } = request.query;
|
||||
const auditStore = server.auditStore;
|
||||
if (!auditStore?.getAll) {
|
||||
|
||||
@@ -15,7 +15,6 @@ import { WaggleConfig } from '@waggle/core';
|
||||
import { allowLocalFromEnv, safeFetch } from '@waggle/agent';
|
||||
import { emitNotification } from './notifications.js';
|
||||
import { emitAuditEvent } from './events.js';
|
||||
import { requireTier } from '../../middleware/assert-tier.js';
|
||||
|
||||
// ── Local team DB ────────────────────────────────────────────────────
|
||||
|
||||
@@ -140,7 +139,7 @@ export async function teamRoutes(fastify: FastifyInstance) {
|
||||
* POST /api/team/connect
|
||||
* Connect to a team server by validating the token against the server's health endpoint.
|
||||
*/
|
||||
fastify.post('/api/team/connect', { preHandler: [requireTier('TEAMS')] }, async (request, reply) => {
|
||||
fastify.post('/api/team/connect', async (request, reply) => {
|
||||
const { serverUrl, token } = request.body as { serverUrl: string; token: string };
|
||||
|
||||
if (!serverUrl || !token) {
|
||||
@@ -454,7 +453,7 @@ export async function teamRoutes(fastify: FastifyInstance) {
|
||||
}
|
||||
|
||||
// GET /api/team/governance/permissions — get effective permissions for current user
|
||||
fastify.get('/api/team/governance/permissions', { preHandler: [requireTier('ENTERPRISE')] }, async (request, reply) => {
|
||||
fastify.get('/api/team/governance/permissions', async (request, reply) => {
|
||||
const { workspaceId } = request.query as { workspaceId?: string };
|
||||
const waggleConfig = new WaggleConfig(dataDir);
|
||||
const teamServer = waggleConfig.getTeamServer();
|
||||
|
||||
@@ -5,7 +5,6 @@ import Database from 'better-sqlite3';
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import { MindDB, WaggleConfig, createFileStore, reconcileFtsIndex } from '@waggle/core';
|
||||
import { parseTier, getCapabilities } from '@waggle/shared';
|
||||
import { assertSafeSegment } from './validate.js';
|
||||
import { validateBody } from '../../validate-body.js';
|
||||
import { getBoundTeamServer } from '../team-server-binding.js';
|
||||
@@ -331,25 +330,6 @@ export const workspaceRoutes: FastifyPluginAsync = async (server) => {
|
||||
}>('/api/workspaces', { preHandler: validateBody(createWorkspaceSchema) }, async (request, reply) => {
|
||||
const { name, group, icon, model, personaId, directory, tone, teamId, teamServerUrl, teamRole, teamUserId, storageType, storagePath, storageConfig } = request.body;
|
||||
|
||||
// Tier limit enforcement: check workspaceLimit from @waggle/shared
|
||||
try {
|
||||
const configPath = path.join(server.localConfig.dataDir, 'config.json');
|
||||
const tierRaw = fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath, 'utf-8')).tier : '';
|
||||
const tier = parseTier(String(tierRaw ?? '')) ?? 'FREE';
|
||||
const caps = getCapabilities(tier);
|
||||
if (caps.workspaceLimit > 0) {
|
||||
const currentCount = server.workspaceManager.list().length;
|
||||
if (currentCount >= caps.workspaceLimit) {
|
||||
return reply.status(403).send({
|
||||
error: `Workspace limit reached for ${tier} tier (${caps.workspaceLimit} max). Upgrade to create more.`,
|
||||
tier,
|
||||
limit: caps.workspaceLimit,
|
||||
current: currentCount,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch { /* tier check failed — allow creation */ }
|
||||
|
||||
// BUG-R3-03: Validate model ID if provided
|
||||
if (model && !isValidModelId(model)) {
|
||||
return reply.status(400).send({
|
||||
|
||||
@@ -237,25 +237,12 @@ export class SessionTimeoutTracker {
|
||||
|
||||
/**
|
||||
* Routes exempt from bearer token authentication.
|
||||
*
|
||||
* `/api/stripe/webhook` is a tokenless POST from Stripe's servers — it can never
|
||||
* carry our per-process session bearer, so in a hosted (0.0.0.0) deploy it would
|
||||
* 401 before the handler and subscription-lifecycle events
|
||||
* (customer.subscription.deleted/updated) would never process — cancelled subs
|
||||
* would never downgrade to FREE. It is independently authenticated by Stripe
|
||||
* *signature verification* inside the handler (stripe.webhooks.constructEvent
|
||||
* rejects any body not signed with STRIPE_WEBHOOK_SECRET before the handler
|
||||
* trusts it), so exempting it from the bearer gate does not widen the trust
|
||||
* boundary. Desktop (loopback) mode is unaffected — Stripe can't reach a
|
||||
* loopback bind. The path string matches the route registered in
|
||||
* stripe/webhook.ts (`POST /api/stripe/webhook`, no prefix).
|
||||
*/
|
||||
const AUTH_EXEMPT_PATHS = [
|
||||
'/health',
|
||||
'/api/auth/session-token',
|
||||
'/api/browser-ext/session-token',
|
||||
'/api/browser-ext/pair',
|
||||
'/api/stripe/webhook',
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -738,8 +725,8 @@ async function securityMiddlewarePlugin(
|
||||
// ── Bearer token authentication (SEC-011 + D1) ──
|
||||
// D1: localhost is NO LONGER trusted by default. Waggle is a desktop app that
|
||||
// coexists with browsers/extensions/other local apps, so "any loopback caller is
|
||||
// trusted" let any of them drive the authenticated API (e.g. the PATCH /api/tier
|
||||
// free upgrade). The Tauri webview obtains the token from the auth-exempt,
|
||||
// trusted" let any of them drive the authenticated API (e.g. change settings or
|
||||
// provider keys). The Tauri webview obtains the token from the auth-exempt,
|
||||
// same-origin-gated /api/auth/session-token bootstrap and sends it as a Bearer.
|
||||
// Set WAGGLE_TRUST_LOCALHOST=1 to restore legacy loopback trust (emergency escape).
|
||||
if (sessionToken) {
|
||||
|
||||
@@ -10,7 +10,6 @@ import type { LlmHealthStatus } from './index.js';
|
||||
import { startLiteLLM, stopLiteLLM, type LiteLLMStatus } from './lifecycle.js';
|
||||
import { createLogger } from './logger.js';
|
||||
import { resolveBindHost } from './net-config.js';
|
||||
import { readTierFromDataDir } from '../middleware/assert-tier.js';
|
||||
import { listOllamaChatModelIds } from './model-availability.js';
|
||||
import {
|
||||
readEraseMarker,
|
||||
@@ -245,9 +244,9 @@ export async function startService(options?: ServiceOptions): Promise<ServiceRes
|
||||
}
|
||||
|
||||
// D11: ONE startup line answering "which state am I running against?" —
|
||||
// resolved dataDir + effective tier. Logged after wipe/migration so it
|
||||
// reflects the directory the server will actually serve.
|
||||
log.info(`Data dir: ${dataDir} · tier: ${readTierFromDataDir(dataDir)}`);
|
||||
// the resolved dataDir. Logged after wipe/migration so it reflects the
|
||||
// directory the server will actually serve.
|
||||
log.info(`Data dir: ${dataDir}`);
|
||||
|
||||
// 3. Ensure personal.mind exists
|
||||
const personalPath = path.join(dataDir, 'personal.mind');
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import type { Tier } from '@waggle/shared';
|
||||
|
||||
export function maxWorkspaceSessionsForTier(tier: Tier): number {
|
||||
if (tier === 'FREE') return 10;
|
||||
if (tier === 'TEAMS') return 25;
|
||||
return 100;
|
||||
}
|
||||
@@ -8,12 +8,15 @@
|
||||
* state (the "Option Y" fix from docs/plans/phase-a-the-room.md §9).
|
||||
*
|
||||
* Max concurrent sessions configurable (default: 3) to prevent resource exhaustion.
|
||||
* Tier-gate via setMaxSessions() at startup once the user's subscription is known.
|
||||
* The sidecar starts the manager with MAX_WORKSPACE_SESSIONS.
|
||||
*/
|
||||
|
||||
import type { MindDB } from '@waggle/core';
|
||||
import type { ToolDefinition, Orchestrator } from '@waggle/agent';
|
||||
|
||||
/** Concurrent workspace sessions the sidecar allows. */
|
||||
export const MAX_WORKSPACE_SESSIONS = 100;
|
||||
|
||||
export interface WorkspaceSession {
|
||||
workspaceId: string;
|
||||
mind: MindDB;
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
/**
|
||||
* Tier enforcement middleware for Fastify routes.
|
||||
*
|
||||
* Usage:
|
||||
* server.post('/api/team/connect', { preHandler: [requireTier('TEAMS')] }, handler)
|
||||
*
|
||||
* Reads the current tier from config.json (same source as GET /api/tier).
|
||||
* Returns 403 with structured error when tier is insufficient.
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { type Tier, assertTierCapability, TierError, parseTier, getEffectiveTier } from '@waggle/shared';
|
||||
|
||||
/**
|
||||
* Read the effective tier for a data directory.
|
||||
* Uses the same config.json source as the GET /api/tier route in settings.ts.
|
||||
* Also consumed by startService's D11 startup log line (no request in scope there).
|
||||
*/
|
||||
export function readTierFromDataDir(dataDir: string | undefined): Tier {
|
||||
try {
|
||||
if (!dataDir) return 'FREE';
|
||||
const configPath = path.join(dataDir, 'config.json');
|
||||
if (fs.existsSync(configPath)) {
|
||||
const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
const parsed = parseTier(String(raw.tier ?? ''));
|
||||
if (parsed) return getEffectiveTier(parsed, raw.trialStartedAt ?? null);
|
||||
}
|
||||
} catch { /* unreadable config → fail closed to FREE */ }
|
||||
return 'FREE';
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the current tier from the server's data directory.
|
||||
*/
|
||||
export function readTierFromRequest(request: FastifyRequest): Tier {
|
||||
return readTierFromDataDir(request.server.localConfig?.dataDir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fastify preHandler that enforces a minimum tier.
|
||||
* Returns 403 TIER_INSUFFICIENT if the current tier is below the required level.
|
||||
*/
|
||||
export function requireTier(minimumTier: Tier) {
|
||||
return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {
|
||||
const userTier = readTierFromRequest(request);
|
||||
try {
|
||||
assertTierCapability(userTier, minimumTier);
|
||||
} catch (e) {
|
||||
if (e instanceof TierError) {
|
||||
return void reply.code(403).send({
|
||||
error: 'TIER_INSUFFICIENT',
|
||||
message: `This feature requires the ${e.required} tier. You are on ${e.actual}.`,
|
||||
required: e.required,
|
||||
actual: e.actual,
|
||||
upgradeUrl: 'https://waggle-os.ai/upgrade',
|
||||
});
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
/**
|
||||
* Stripe Checkout — creates a checkout session for tier upgrades.
|
||||
*
|
||||
* POST /api/stripe/create-checkout-session
|
||||
* Body: { tier: 'TEAMS', billingPeriod?: 'monthly' | 'annual' }
|
||||
* Returns: { url: string }
|
||||
*/
|
||||
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import type { Tier } from '@waggle/shared';
|
||||
import { getStripe, priceIdForTier } from './index.js';
|
||||
import { validateBody } from '../validate-body.js';
|
||||
|
||||
/** POST /api/stripe/create-checkout-session body — a billing action. `tier` is
|
||||
* shape-validated here (required string); the TEAMS-only business rule stays in
|
||||
* the handler so it can return the specific INVALID_TIER envelope. */
|
||||
const createCheckoutSchema = z.object({
|
||||
tier: z.string().min(1),
|
||||
billingPeriod: z.enum(['monthly', 'annual']).optional(),
|
||||
});
|
||||
|
||||
export const checkoutRoutes: FastifyPluginAsync = async (server) => {
|
||||
server.post<{
|
||||
Body: { tier: string; billingPeriod?: 'monthly' | 'annual' };
|
||||
}>('/api/stripe/create-checkout-session', { preHandler: validateBody(createCheckoutSchema) }, async (request, reply) => {
|
||||
const stripe = getStripe();
|
||||
if (!stripe) {
|
||||
return reply.code(503).send({ error: 'STRIPE_NOT_CONFIGURED', message: 'Stripe is not configured. Set STRIPE_SECRET_KEY.' });
|
||||
}
|
||||
|
||||
const { tier, billingPeriod } = request.body ?? {};
|
||||
|
||||
// TEAMS is the only paid tier with a Stripe price (PRO removed — Solo is free).
|
||||
if (tier !== 'TEAMS') {
|
||||
return reply.code(400).send({ error: 'INVALID_TIER', message: 'Only the Team tier supports Stripe checkout.' });
|
||||
}
|
||||
|
||||
const priceId = priceIdForTier(tier as Tier, billingPeriod);
|
||||
if (!priceId) {
|
||||
return reply.code(400).send({ error: 'NO_PRICE_CONFIGURED', message: `No Stripe price configured for ${tier} (${billingPeriod ?? 'monthly'}).` });
|
||||
}
|
||||
|
||||
try {
|
||||
const origin = request.headers['origin']
|
||||
?? process.env['APP_URL']
|
||||
?? 'http://localhost:1420';
|
||||
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
mode: 'subscription',
|
||||
line_items: [{ price: priceId, quantity: 1 }],
|
||||
success_url: `${origin}/payment-success?session_id={CHECKOUT_SESSION_ID}`,
|
||||
cancel_url: `${origin}/payment-cancelled`,
|
||||
allow_promotion_codes: true,
|
||||
metadata: {
|
||||
tier,
|
||||
billingPeriod: billingPeriod ?? 'monthly',
|
||||
},
|
||||
});
|
||||
|
||||
return { url: session.url };
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Stripe session creation failed';
|
||||
return reply.code(502).send({ error: 'STRIPE_ERROR', message });
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1,140 +0,0 @@
|
||||
/**
|
||||
* Stripe integration — checkout, webhook, and customer portal.
|
||||
*
|
||||
* All Stripe functionality is gated behind STRIPE_SECRET_KEY env var.
|
||||
* When not set, all /api/stripe/* routes return 503 STRIPE_NOT_CONFIGURED.
|
||||
*/
|
||||
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import Stripe from 'stripe';
|
||||
import { type Tier, TIER_CAPABILITIES } from '@waggle/shared';
|
||||
|
||||
export { checkoutRoutes } from './checkout.js';
|
||||
export { webhookRoutes } from './webhook.js';
|
||||
export { portalRoutes } from './portal.js';
|
||||
export { syncRoutes } from './sync.js';
|
||||
|
||||
// ── Stripe SDK singleton ─────────────────────────────────────────────
|
||||
|
||||
let stripeInstance: Stripe | null = null;
|
||||
let stripeSecretKey: string | null = null;
|
||||
|
||||
/**
|
||||
* Get the Stripe SDK instance (lazy-initialized).
|
||||
* Returns null if STRIPE_SECRET_KEY is not set.
|
||||
*/
|
||||
export function getStripe(): Stripe | null {
|
||||
const secretKey = process.env['STRIPE_SECRET_KEY'] ?? null;
|
||||
if (secretKey === stripeSecretKey) return stripeInstance;
|
||||
|
||||
stripeSecretKey = secretKey;
|
||||
stripeInstance = secretKey
|
||||
? new Stripe(secretKey, { apiVersion: '2026-03-25.dahlia' })
|
||||
: null;
|
||||
|
||||
return stripeInstance;
|
||||
}
|
||||
|
||||
// ── Tier ↔ Price ID mapping ──────────────────────────────────────────
|
||||
|
||||
/** Collect non-empty env values for the given keys, preserving order. */
|
||||
function readPriceEnvs(...keys: string[]): string[] {
|
||||
const out: string[] = [];
|
||||
for (const k of keys) {
|
||||
const v = process.env[k];
|
||||
if (v) out.push(v);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a Stripe price ID back to a canonical Tier.
|
||||
*
|
||||
* Supports two env-var contracts that can coexist:
|
||||
* - **New 4-var contract** (matches `apps/www` Next.js port):
|
||||
* STRIPE_PRICE_PRO_MONTHLY / STRIPE_PRICE_PRO_ANNUAL
|
||||
* STRIPE_PRICE_TEAMS_MONTHLY / STRIPE_PRICE_TEAMS_ANNUAL
|
||||
* - **Legacy single-var contract** (older desktop sidecar env):
|
||||
* STRIPE_PRICE_PRO / STRIPE_PRICE_TEAMS
|
||||
* STRIPE_PRICE_BASIC (oldest alias)
|
||||
*
|
||||
* New contract is checked first; legacy vars act as additional fallbacks.
|
||||
* Resolution is synchronous and offline-safe — no Stripe API round-trip.
|
||||
*
|
||||
* PRO removed (Solo/Team collapse): the legacy PRO/BASIC price vars are still
|
||||
* READ, but now resolve to `'FREE'` so a legacy PRO subscriber lands on Solo
|
||||
* (never null, never locked out). Only TEAMS mints a paid tier.
|
||||
*/
|
||||
export function tierFromPriceId(priceId: string): Tier | null {
|
||||
const proPrices = readPriceEnvs(
|
||||
'STRIPE_PRICE_PRO_MONTHLY',
|
||||
'STRIPE_PRICE_PRO_ANNUAL',
|
||||
'STRIPE_PRICE_PRO',
|
||||
'STRIPE_PRICE_BASIC',
|
||||
);
|
||||
const teamsPrices = readPriceEnvs(
|
||||
'STRIPE_PRICE_TEAMS_MONTHLY',
|
||||
'STRIPE_PRICE_TEAMS_ANNUAL',
|
||||
'STRIPE_PRICE_TEAMS',
|
||||
);
|
||||
|
||||
if (proPrices.includes(priceId)) return 'FREE';
|
||||
if (teamsPrices.includes(priceId)) return 'TEAMS';
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Resolve the Stripe price ID for a (tier, billingPeriod). Prefers the 4-var
|
||||
* period-specific contract, falls back to legacy single-var, then TIER_CAPABILITIES. */
|
||||
export function priceIdForTier(tier: Tier, billingPeriod: 'monthly' | 'annual' = 'monthly'): string | null {
|
||||
const period = billingPeriod === 'annual' ? 'ANNUAL' : 'MONTHLY';
|
||||
// The period-specific 4-var price is always preferred. TEAMS is the only
|
||||
// paid tier post-PRO-removal, so it is the only tier with a checkout price.
|
||||
const periodSpecific = tier === 'TEAMS'
|
||||
? process.env[`STRIPE_PRICE_TEAMS_${period}`]
|
||||
: undefined;
|
||||
if (periodSpecific) return periodSpecific;
|
||||
// F9 fail-closed: for ANNUAL, never fall back to a monthly-priced var. The legacy
|
||||
// single-var (STRIPE_PRICE_PRO/TEAMS/BASIC) and the TIER_CAPABILITIES default are
|
||||
// all monthly prices; charging one for an annual selection — while the UI shows the
|
||||
// annual price — is a billing lie. Returning null yields an honest 400
|
||||
// NO_PRICE_CONFIGURED (checkout.ts:30) instead of a wrong charge.
|
||||
if (billingPeriod === 'annual') return null;
|
||||
const candidates = tier === 'TEAMS'
|
||||
? [process.env.STRIPE_PRICE_TEAMS]
|
||||
: [];
|
||||
for (const c of candidates) if (c) return c;
|
||||
return TIER_CAPABILITIES[tier]?.stripePriceId ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/stripe/status → { configured } — a secret-free probe of whether Stripe
|
||||
* checkout is wired (STRIPE_SECRET_KEY present + stripe SDK loadable). Lets the
|
||||
* billing UI render the F8 honest "not configured" disabled state BEFORE a click,
|
||||
* instead of only surfacing the 503 after the user tries to subscribe.
|
||||
*/
|
||||
export const statusRoutes: FastifyPluginAsync = async (server) => {
|
||||
server.get('/api/stripe/status', async () => ({ configured: !!getStripe() }));
|
||||
};
|
||||
|
||||
// ── Combined route registration ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Register all Stripe routes on a Fastify server.
|
||||
* Safe to call even when Stripe is not configured — routes will return 503.
|
||||
*/
|
||||
export const stripeRoutes: FastifyPluginAsync = async (server) => {
|
||||
// Webhook needs its own content type parser, so register in isolated context
|
||||
await server.register(async (webhookScope) => {
|
||||
const { webhookRoutes } = await import('./webhook.js');
|
||||
await webhookScope.register(webhookRoutes);
|
||||
});
|
||||
|
||||
// Checkout, portal, sync, and the config-status probe use standard JSON parsing
|
||||
const { checkoutRoutes } = await import('./checkout.js');
|
||||
const { portalRoutes } = await import('./portal.js');
|
||||
const { syncRoutes } = await import('./sync.js');
|
||||
await server.register(checkoutRoutes);
|
||||
await server.register(portalRoutes);
|
||||
await server.register(syncRoutes);
|
||||
await server.register(statusRoutes);
|
||||
};
|
||||
@@ -1,54 +0,0 @@
|
||||
/**
|
||||
* Stripe Customer Portal — lets paid users manage their subscription.
|
||||
*
|
||||
* POST /api/stripe/create-portal-session
|
||||
* Returns: { url: string }
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { requireTier } from '../middleware/assert-tier.js';
|
||||
import { getStripe } from './index.js';
|
||||
|
||||
export const portalRoutes: FastifyPluginAsync = async (server) => {
|
||||
// Ungated to any authenticated user (requireTier('FREE') is a no-op floor): a
|
||||
// legacy PRO subscriber (now Solo/FREE) must still reach the portal to self-cancel.
|
||||
// Non-subscribers are handled by the route's own NO_STRIPE_CUSTOMER 400 below.
|
||||
server.post('/api/stripe/create-portal-session', { preHandler: [requireTier('FREE')] }, async (request, reply) => {
|
||||
const stripe = getStripe();
|
||||
if (!stripe) {
|
||||
return reply.code(503).send({ error: 'STRIPE_NOT_CONFIGURED' });
|
||||
}
|
||||
|
||||
// Read stripe_customer_id from config.json
|
||||
const dataDir = server.localConfig?.dataDir;
|
||||
let customerId: string | null = null;
|
||||
try {
|
||||
const configPath = path.join(dataDir, 'config.json');
|
||||
if (fs.existsSync(configPath)) {
|
||||
const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
customerId = raw.stripe_customer_id ?? null;
|
||||
}
|
||||
} catch { /* no config */ }
|
||||
|
||||
if (!customerId) {
|
||||
return reply.code(400).send({ error: 'NO_STRIPE_CUSTOMER', message: 'No Stripe customer found. Complete a checkout first.' });
|
||||
}
|
||||
|
||||
try {
|
||||
const origin = request.headers['origin']
|
||||
?? process.env['APP_URL']
|
||||
?? 'http://localhost:1420';
|
||||
|
||||
const session = await stripe.billingPortal.sessions.create({
|
||||
customer: customerId,
|
||||
return_url: `${origin}/settings`,
|
||||
});
|
||||
return { url: session.url };
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Portal session creation failed';
|
||||
return reply.code(502).send({ error: 'STRIPE_ERROR', message });
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1,90 +0,0 @@
|
||||
/**
|
||||
* Stripe Sync — poll-based tier synchronization for desktop apps.
|
||||
*
|
||||
* POST /api/stripe/sync
|
||||
* Body: { sessionId: string }
|
||||
* Returns: { tier: string, customerId: string }
|
||||
*
|
||||
* Desktop apps behind NAT cannot receive webhooks reliably.
|
||||
* The frontend calls this endpoint after Stripe checkout redirect
|
||||
* to confirm payment and update the local tier.
|
||||
*/
|
||||
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { type Tier, parseTier } from '@waggle/shared';
|
||||
import { getStripe, tierFromPriceId } from './index.js';
|
||||
import { updateUserTier } from './webhook.js';
|
||||
|
||||
export const syncRoutes: FastifyPluginAsync = async (server) => {
|
||||
server.post<{
|
||||
Body: { sessionId: string };
|
||||
}>('/api/stripe/sync', async (request, reply) => {
|
||||
const stripe = getStripe();
|
||||
if (!stripe) {
|
||||
return reply.code(503).send({ error: 'STRIPE_NOT_CONFIGURED' });
|
||||
}
|
||||
|
||||
const { sessionId } = request.body ?? {};
|
||||
if (!sessionId || typeof sessionId !== 'string') {
|
||||
return reply.code(400).send({ error: 'MISSING_SESSION_ID', message: 'sessionId is required.' });
|
||||
}
|
||||
|
||||
const dataDir = server.localConfig?.dataDir;
|
||||
if (!dataDir) {
|
||||
return reply.code(500).send({ error: 'SERVER_MISCONFIGURED' });
|
||||
}
|
||||
|
||||
try {
|
||||
const session = await stripe.checkout.sessions.retrieve(sessionId, {
|
||||
expand: ['subscription'],
|
||||
});
|
||||
|
||||
// Payment gate: never grant a paid tier from an unpaid session.
|
||||
// metadata.tier is set at session creation (before payment), so an
|
||||
// unpaid sessionId would otherwise grant a free paid tier. 'no_payment_required'
|
||||
// covers 100%-off promo codes enabled via allow_promotion_codes.
|
||||
const paid = session.payment_status === 'paid' || session.payment_status === 'no_payment_required';
|
||||
if (session.status !== 'complete' || !paid) {
|
||||
return reply.code(402).send({ error: 'PAYMENT_NOT_COMPLETED', message: 'Checkout session is not paid yet.' });
|
||||
}
|
||||
|
||||
const customerId = typeof session.customer === 'string'
|
||||
? session.customer
|
||||
: undefined;
|
||||
|
||||
// Resolve tier from subscription price or session metadata
|
||||
let tier: Tier | null = null;
|
||||
|
||||
// Try subscription price first (most reliable)
|
||||
const subscription = session.subscription;
|
||||
if (subscription && typeof subscription === 'object' && 'items' in subscription) {
|
||||
const sub = subscription as { items?: { data?: Array<{ price?: { id?: string } }> } };
|
||||
const priceId = sub.items?.data?.[0]?.price?.id;
|
||||
if (priceId) {
|
||||
tier = tierFromPriceId(priceId);
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to session metadata
|
||||
if (!tier) {
|
||||
const tierRaw = session.metadata?.tier;
|
||||
if (tierRaw) {
|
||||
tier = parseTier(tierRaw);
|
||||
}
|
||||
}
|
||||
|
||||
if (!tier) {
|
||||
return reply.code(400).send({ error: 'TIER_NOT_RESOLVED', message: 'Could not determine tier from checkout session.' });
|
||||
}
|
||||
|
||||
updateUserTier(dataDir, tier, customerId);
|
||||
server.log.info({ event: 'stripe_sync', tier, customerId });
|
||||
|
||||
return { tier, customerId: customerId ?? null };
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Stripe sync failed';
|
||||
server.log.error({ event: 'stripe_sync_error', error: message });
|
||||
return reply.code(502).send({ error: 'STRIPE_ERROR', message });
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1,189 +0,0 @@
|
||||
/**
|
||||
* Stripe Webhook — handles subscription lifecycle events.
|
||||
*
|
||||
* POST /api/stripe/webhook
|
||||
* Validates stripe-signature header, updates tier in config.json.
|
||||
*
|
||||
* CRITICAL: This route needs raw body for signature validation.
|
||||
* Fastify's addContentTypeParser is used to capture raw bytes.
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { type Tier, parseTier, getCapabilities } from '@waggle/shared';
|
||||
import { getStripe, tierFromPriceId } from './index.js';
|
||||
|
||||
/**
|
||||
* Atomically write JSON to disk: write to a unique temp file in the same
|
||||
* directory, then rename over the target. rename(2) is atomic on the same
|
||||
* volume, so a crash mid-write leaves the previous complete file intact
|
||||
* instead of a torn/partial one. A module-scoped counter (not a timestamp)
|
||||
* keeps the temp name unique even within the same millisecond.
|
||||
*/
|
||||
let __tmpSeq = 0;
|
||||
function atomicWriteJson(filePath: string, data: unknown): void {
|
||||
const tmp = `${filePath}.${process.pid}.${__tmpSeq++}.tmp`;
|
||||
fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf-8');
|
||||
const waitBuffer = new Int32Array(new SharedArrayBuffer(4));
|
||||
|
||||
try {
|
||||
for (let attempt = 1; attempt <= 4; attempt++) {
|
||||
try {
|
||||
fs.renameSync(tmp, filePath);
|
||||
return;
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
const transient = code === 'EPERM' || code === 'EACCES' || code === 'EBUSY';
|
||||
if (!transient || attempt === 4) throw error;
|
||||
// Windows antivirus and indexers can briefly hold an exclusive handle.
|
||||
Atomics.wait(waitBuffer, 0, 0, 25 * attempt);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
try { fs.rmSync(tmp, { force: true }); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* R1-011: serialize the webhook critical section. atomicWriteJson prevents torn
|
||||
* files, but two concurrent deliveries of the SAME event (a real Stripe retry
|
||||
* scenario) could both read .stripe-processed-events.json before either wrote,
|
||||
* both pass the idempotency check, and both run updateUserTier — a TOCTOU race
|
||||
* that can write contradictory tiers. This module-scoped promise queue makes the
|
||||
* read-check-process-write sequence mutually exclusive; one failure never wedges
|
||||
* the queue (the tail swallows rejections).
|
||||
*/
|
||||
let __webhookTail: Promise<void> = Promise.resolve();
|
||||
function serializeWebhook<T>(fn: () => Promise<T>): Promise<T> {
|
||||
const result = __webhookTail.then(() => fn());
|
||||
__webhookTail = result.then(() => undefined, () => undefined);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the user's tier (and optionally Stripe customer ID) in config.json.
|
||||
* This is the same storage used by readTierFromRequest() in the tier middleware
|
||||
* and by the portal route to read stripe_customer_id.
|
||||
*/
|
||||
function updateUserTier(dataDir: string, tier: Tier, customerId?: string): void {
|
||||
const configPath = path.join(dataDir, 'config.json');
|
||||
let raw: Record<string, unknown> = {};
|
||||
try {
|
||||
if (fs.existsSync(configPath)) {
|
||||
raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
}
|
||||
} catch { /* fresh config */ }
|
||||
const updated = { ...raw, tier, ...(customerId ? { stripe_customer_id: customerId } : {}) };
|
||||
atomicWriteJson(configPath, updated);
|
||||
}
|
||||
|
||||
export const webhookRoutes: FastifyPluginAsync = async (server) => {
|
||||
// Register raw body parser for this route only
|
||||
server.addContentTypeParser(
|
||||
'application/json',
|
||||
{ parseAs: 'buffer' },
|
||||
(_req, body, done) => {
|
||||
done(null, body);
|
||||
},
|
||||
);
|
||||
|
||||
server.post('/api/stripe/webhook', async (request, reply) => {
|
||||
const stripe = getStripe();
|
||||
const webhookSecret = process.env['STRIPE_WEBHOOK_SECRET'];
|
||||
if (!stripe || !webhookSecret) {
|
||||
return reply.code(503).send({ error: 'STRIPE_NOT_CONFIGURED' });
|
||||
}
|
||||
|
||||
const signature = request.headers['stripe-signature'];
|
||||
if (!signature) {
|
||||
return reply.code(400).send({ error: 'MISSING_SIGNATURE' });
|
||||
}
|
||||
|
||||
let event;
|
||||
try {
|
||||
event = stripe.webhooks.constructEvent(
|
||||
request.body as Buffer,
|
||||
signature as string,
|
||||
webhookSecret,
|
||||
);
|
||||
} catch {
|
||||
return reply.code(400).send({ error: 'INVALID_SIGNATURE' });
|
||||
}
|
||||
|
||||
const dataDir = server.localConfig?.dataDir;
|
||||
if (!dataDir) {
|
||||
return reply.code(500).send({ error: 'SERVER_MISCONFIGURED' });
|
||||
}
|
||||
|
||||
// R1-011: run idempotency-check + processing + processed-write as ONE
|
||||
// serialized critical section so concurrent retries of the same event cannot
|
||||
// both slip past the dedup check and double-process a tier change.
|
||||
const processedPath = path.join(dataDir, '.stripe-processed-events.json');
|
||||
const outcome = await serializeWebhook<'duplicate' | 'processed'>(async () => {
|
||||
let processedIds: string[] = [];
|
||||
try { processedIds = JSON.parse(fs.readFileSync(processedPath, 'utf-8')); } catch { /* first run */ }
|
||||
if (processedIds.includes(event.id)) {
|
||||
server.log.info({ event: 'webhook_duplicate_skipped', eventId: event.id });
|
||||
return 'duplicate';
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case 'checkout.session.completed': {
|
||||
const session = event.data.object as { payment_status?: string; metadata?: Record<string, string>; customer?: string };
|
||||
// R1-002 (webhook path): checkout.session.completed also fires for
|
||||
// UNPAID sessions (async/delayed payment methods, incomplete
|
||||
// checkouts). Only grant a tier once payment has actually settled —
|
||||
// same gate as the /api/stripe/sync path (sync.ts). 'paid' covers
|
||||
// normal purchases; 'no_payment_required' covers 100%-off coupons.
|
||||
const paid = session.payment_status === 'paid' || session.payment_status === 'no_payment_required';
|
||||
const tierRaw = session.metadata?.tier;
|
||||
if (paid && tierRaw) {
|
||||
const parsed = parseTier(tierRaw);
|
||||
if (parsed) {
|
||||
const customerId = typeof session.customer === 'string' ? session.customer : undefined;
|
||||
updateUserTier(dataDir, parsed, customerId);
|
||||
server.log.info({ event: 'checkout_completed', tier: parsed, customerId });
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'customer.subscription.updated': {
|
||||
const subscription = event.data.object as { customer?: string; items?: { data?: Array<{ price?: { id?: string } }> } };
|
||||
const priceId = subscription.items?.data?.[0]?.price?.id;
|
||||
if (priceId) {
|
||||
const newTier = tierFromPriceId(priceId);
|
||||
if (newTier) {
|
||||
const customerId = typeof subscription.customer === 'string' ? subscription.customer : undefined;
|
||||
updateUserTier(dataDir, newTier, customerId);
|
||||
server.log.info({ event: 'subscription_updated', tier: newTier, customerId });
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'customer.subscription.deleted': {
|
||||
updateUserTier(dataDir, 'FREE');
|
||||
server.log.info({ event: 'subscription_cancelled' });
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
// Unknown event types are silently acknowledged
|
||||
break;
|
||||
}
|
||||
|
||||
// Mark event as processed (keep last 500 IDs to avoid unbounded growth)
|
||||
processedIds.push(event.id);
|
||||
if (processedIds.length > 500) processedIds.splice(0, processedIds.length - 500);
|
||||
try { atomicWriteJson(processedPath, processedIds); } catch { /* best effort */ }
|
||||
return 'processed';
|
||||
});
|
||||
|
||||
if (outcome === 'duplicate') return reply.send({ received: true, duplicate: true });
|
||||
return { received: true };
|
||||
});
|
||||
};
|
||||
|
||||
export { updateUserTier };
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user