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

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

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

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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