This commit is contained in:
302
apps/web/src/providers/InstallProvider.tsx
Normal file
302
apps/web/src/providers/InstallProvider.tsx
Normal file
@@ -0,0 +1,302 @@
|
||||
/**
|
||||
* InstallProvider — the PR4 shared install store ("sync"). The single FE
|
||||
* source of truth for what is installed / mid-flight, subscribed to by the
|
||||
* Marketplace grid (Variation A), agent-pick, and inline-in-chat (Variation
|
||||
* B). Installing in ANY view reflects in ALL, and the count bar reads one
|
||||
* place (D1 honest global count).
|
||||
*
|
||||
* Design notes:
|
||||
* - `installed` is a Set of namespaced catalog ids; the id prefix already
|
||||
* encodes the kind, so no Map value is needed. Only togglable kinds
|
||||
* (package / connector / catalog-mcp) ever enter it → `size` IS the count.
|
||||
* - 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,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { adapter } from '@/lib/adapter';
|
||||
import { useService } from '@/providers/ServiceProvider';
|
||||
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,
|
||||
type InstallCredentials, type InstallOutcome, type InstallTarget,
|
||||
} from '@/lib/install-store';
|
||||
|
||||
export interface InstallStore {
|
||||
/** Namespaced ids currently installed/connected/enabled (togglable kinds only). */
|
||||
installed: ReadonlySet<string>;
|
||||
/** Namespaced ids with an install/uninstall in flight. */
|
||||
installing: ReadonlySet<string>;
|
||||
/** Honest global count of user-added capabilities (D1) = installed.size. */
|
||||
installedCount: number;
|
||||
hydrating: boolean;
|
||||
isInstalled: (id: string) => boolean;
|
||||
isInstalling: (id: string) => boolean;
|
||||
/** Type-aware install dispatcher. Optimistic-on-success + reconcile + toasts. */
|
||||
install: (target: InstallTarget, credentials?: InstallCredentials) => Promise<InstallOutcome>;
|
||||
uninstall: (target: InstallTarget) => Promise<InstallOutcome>;
|
||||
/** Re-read server truth (initial, on connect-settled, and on nav per D4). */
|
||||
hydrate: () => Promise<void>;
|
||||
}
|
||||
|
||||
const InstallContext = createContext<InstallStore | null>(null);
|
||||
|
||||
export const useInstallStore = (): InstallStore => {
|
||||
const ctx = useContext(InstallContext);
|
||||
if (!ctx) throw new Error('useInstallStore must be used within InstallProvider');
|
||||
return ctx;
|
||||
};
|
||||
|
||||
/** SecurityGate-block message shared by the install/enable branches. */
|
||||
function securityMessage(e: { severity?: string; message?: string }): string {
|
||||
return `Security scan blocked it (severity: ${e.severity ?? 'unknown'}). ${e.message ?? ''}`.trim();
|
||||
}
|
||||
|
||||
function mcpOptsFrom(c?: InstallCredentials): { settings?: Record<string, string>; force?: boolean; forceInsecure?: boolean } | undefined {
|
||||
if (!c) return undefined;
|
||||
const opts: { settings?: Record<string, string>; force?: boolean; forceInsecure?: boolean } = {};
|
||||
if (c.settings) opts.settings = c.settings;
|
||||
if (c.force) opts.force = c.force;
|
||||
if (c.forceInsecure) opts.forceInsecure = c.forceInsecure;
|
||||
return Object.keys(opts).length > 0 ? opts : undefined;
|
||||
}
|
||||
|
||||
export const InstallProvider = ({ children }: { children: ReactNode }) => {
|
||||
const { connecting } = useService();
|
||||
const { toast } = useToast();
|
||||
const [installed, setInstalled] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const [installing, setInstalling] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const [hydrating, setHydrating] = useState(false);
|
||||
// Monotonic guard — only the latest hydrate may commit (rapid nav / reconnect bursts).
|
||||
const hydrateSeq = useRef(0);
|
||||
// The initial settle fires BOTH the connecting flip and the connect-settled
|
||||
// event; this gate keeps the cold-boot hydrate to ONE (the event path only
|
||||
// re-hydrates on a genuine RE-connect, once the initial has run).
|
||||
const didInitialHydrate = useRef(false);
|
||||
|
||||
const addInstalling = useCallback((id: string) => {
|
||||
setInstalling(prev => { const n = new Set(prev); n.add(id); return n; });
|
||||
}, []);
|
||||
const clearInstalling = useCallback((id: string) => {
|
||||
setInstalling(prev => { const n = new Set(prev); n.delete(id); return n; });
|
||||
}, []);
|
||||
// A confirmed flip invalidates any in-flight hydrate: bumping the seq makes a
|
||||
// hydrate whose reads predate this flip fail its commit guard (line below),
|
||||
// so a stale reconcile can never clobber a just-confirmed install/uninstall.
|
||||
const markInstalled = useCallback((id: string) => {
|
||||
hydrateSeq.current += 1;
|
||||
setInstalled(prev => { const n = new Set(prev); n.add(id); return n; });
|
||||
}, []);
|
||||
const markUninstalled = useCallback((id: string) => {
|
||||
hydrateSeq.current += 1;
|
||||
setInstalled(prev => { const n = new Set(prev); n.delete(id); return n; });
|
||||
}, []);
|
||||
|
||||
const hydrate = useCallback(async () => {
|
||||
const seq = ++hydrateSeq.current;
|
||||
setHydrating(true);
|
||||
const [conn, mcps, skillPkgs, mcpPkgs] = await Promise.allSettled([
|
||||
adapter.getConnectors(),
|
||||
adapter.getMcps(),
|
||||
adapter.getMarketplace({ type: 'skill', limit: 50 }),
|
||||
adapter.getMarketplace({ type: 'mcp', limit: 50 }),
|
||||
]);
|
||||
if (seq !== hydrateSeq.current) return; // a newer hydrate owns the state
|
||||
// Per-domain reconcile: a rejected domain carries over its previous ids
|
||||
// (by prefix) instead of dropping known-installed state on a transient fail.
|
||||
setInstalled(prev => {
|
||||
const next = new Set<string>();
|
||||
if (conn.status === 'fulfilled') {
|
||||
for (const c of conn.value ?? []) if (c?.status === 'connected') next.add(`connector:${c.id}`);
|
||||
} else {
|
||||
for (const id of prev) if (id.startsWith('connector:')) next.add(id);
|
||||
}
|
||||
if (mcps.status === 'fulfilled') {
|
||||
for (const m of mcps.value ?? []) if (m?.installed) next.add(`mcp:${m.id}`);
|
||||
} else {
|
||||
for (const id of prev) if (id.startsWith('mcp:')) next.add(id);
|
||||
}
|
||||
// Add every fulfilled package read as authoritative for its type.
|
||||
for (const r of [skillPkgs, mcpPkgs]) {
|
||||
if (r.status !== 'fulfilled') continue;
|
||||
const pkgs = (r.value?.packages ?? []) as MarketplacePackageRow[];
|
||||
for (const p of pkgs) if (p?.installed) next.add(`pkg:${p.id}`);
|
||||
}
|
||||
// The two package reads are disjoint type-filtered sets sharing ONE `pkg:`
|
||||
// namespace, so a single failed read leaves the namespace incomplete. If
|
||||
// EITHER rejected, carry over prior pkg ids — over-retaining a stale pkg
|
||||
// (corrected on the next clean hydrate) is safer than dropping a confirmed
|
||||
// install from the count. Mirrors the connector/mcp per-domain carry-over.
|
||||
if (skillPkgs.status === 'rejected' || mcpPkgs.status === 'rejected') {
|
||||
for (const id of prev) if (id.startsWith('pkg:')) next.add(id);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
setHydrating(false);
|
||||
}, []);
|
||||
|
||||
const install = useCallback(async (target: InstallTarget, credentials?: InstallCredentials): Promise<InstallOutcome> => {
|
||||
if (!isTogglable(target)) return { ok: false, reason: 'unsupported' };
|
||||
const { id } = target;
|
||||
|
||||
// CONNECTOR — vault connect (UNGATED). Token-paste supplied by the caller;
|
||||
// OAuth-only connectors can't finish inline (caller routes to the Hub).
|
||||
if (target.kind === 'federated' && target.type === 'connector') {
|
||||
if (!credentials?.token && !credentials?.apiKey) return { ok: false, reason: 'needs-credentials' };
|
||||
addInstalling(id);
|
||||
try {
|
||||
await adapter.connectConnector(rawId(id), {
|
||||
...(credentials.token ? { token: credentials.token } : {}),
|
||||
...(credentials.apiKey ? { apiKey: credentials.apiKey } : {}),
|
||||
});
|
||||
markInstalled(id);
|
||||
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 {
|
||||
clearInstalling(id);
|
||||
}
|
||||
}
|
||||
|
||||
// CATALOG MCP — enable (PRO-gated; SecurityGate). Body envelope is load-bearing.
|
||||
if (target.kind === 'federated' && target.type === 'mcp') {
|
||||
addInstalling(id);
|
||||
try {
|
||||
const result = (await adapter.installMcp(rawId(id), mcpOptsFrom(credentials))) as {
|
||||
installed: boolean; requiresApproval?: boolean; blocked?: boolean;
|
||||
error?: string; severity?: string; message?: string;
|
||||
};
|
||||
if (result.installed) {
|
||||
markInstalled(id);
|
||||
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' };
|
||||
}
|
||||
toast({ title: 'Enable failed', description: result.message ?? result.error ?? 'Unknown error', variant: 'destructive' });
|
||||
return { ok: false, reason: 'error' };
|
||||
} catch (e) {
|
||||
toast({ title: 'Enable failed', description: describeError(e), variant: 'destructive' });
|
||||
return { ok: false, reason: 'error' };
|
||||
} finally {
|
||||
clearInstalling(id);
|
||||
}
|
||||
}
|
||||
|
||||
// PACKAGE — marketplace install (PRO-gated; SecurityGate). RAW Response.
|
||||
if (target.kind === 'package') {
|
||||
if (target.packageId == null) return { ok: false, reason: 'unsupported' };
|
||||
addInstalling(id);
|
||||
try {
|
||||
const res = await adapter.installMarketplacePackage(target.packageId);
|
||||
if (res.ok) {
|
||||
markInstalled(id);
|
||||
toast({ title: 'Added', description: `${target.name} is installed.` });
|
||||
return { ok: true };
|
||||
}
|
||||
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' };
|
||||
}
|
||||
toast({ title: 'Install failed', description: err.error ?? err.message ?? 'Unknown error', variant: 'destructive' });
|
||||
return { ok: false, reason: 'error' };
|
||||
} catch (e) {
|
||||
toast({ title: 'Install failed', description: describeError(e), variant: 'destructive' });
|
||||
return { ok: false, reason: 'error' };
|
||||
} finally {
|
||||
clearInstalling(id);
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: false, reason: 'unsupported' };
|
||||
}, [toast, addInstalling, clearInstalling, markInstalled]);
|
||||
|
||||
const uninstall = useCallback(async (target: InstallTarget): Promise<InstallOutcome> => {
|
||||
if (!isTogglable(target)) return { ok: false, reason: 'unsupported' };
|
||||
const { id } = target;
|
||||
addInstalling(id);
|
||||
try {
|
||||
if (target.kind === 'package' && target.packageId != null) {
|
||||
await adapter.uninstallMarketplacePackage(target.packageId); // throws on !ok
|
||||
markUninstalled(id);
|
||||
toast({ title: 'Removed', description: `${target.name} was uninstalled.` });
|
||||
return { ok: true };
|
||||
}
|
||||
if (target.type === 'connector') {
|
||||
await adapter.disconnectConnector(rawId(id)); // throws on !ok
|
||||
markUninstalled(id);
|
||||
toast({ title: 'Disconnected', description: `${target.name} was disconnected.` });
|
||||
return { ok: true };
|
||||
}
|
||||
if (target.type === 'mcp') {
|
||||
const r = await adapter.revokeMcp(rawId(id)); // resolves { ok } as data
|
||||
if (r.ok) {
|
||||
markUninstalled(id);
|
||||
toast({ title: 'Disabled', description: `${target.name} was disabled.` });
|
||||
return { ok: true };
|
||||
}
|
||||
toast({ title: 'Disable failed', variant: 'destructive' });
|
||||
return { ok: false, reason: 'error' };
|
||||
}
|
||||
return { ok: false, reason: 'unsupported' };
|
||||
} catch (e) {
|
||||
toast({ title: 'Remove failed', description: describeError(e), variant: 'destructive' });
|
||||
return { ok: false, reason: 'error' };
|
||||
} finally {
|
||||
clearInstalling(id);
|
||||
}
|
||||
}, [toast, addInstalling, clearInstalling, markUninstalled]);
|
||||
|
||||
// Initial hydrate once the connect attempt has settled (gate on `connecting`,
|
||||
// not `connected`: a failed connect still hydrates so its rejection surfaces).
|
||||
useEffect(() => {
|
||||
if (!connecting && !didInitialHydrate.current) {
|
||||
didInitialHydrate.current = true;
|
||||
void hydrate();
|
||||
}
|
||||
}, [connecting, hydrate]);
|
||||
|
||||
// Reconnect revalidation — the same bus the other Stage-B surfaces use. Only
|
||||
// re-hydrates AFTER the initial run, so the cold-boot settle (which fires this
|
||||
// event too) doesn't double-hydrate with the connecting-gated effect above.
|
||||
useEffect(() => {
|
||||
const onSettled = () => { if (didInitialHydrate.current) void hydrate(); };
|
||||
window.addEventListener(CONNECT_SETTLED_EVENT, onSettled);
|
||||
return () => window.removeEventListener(CONNECT_SETTLED_EVENT, onSettled);
|
||||
}, [hydrate]);
|
||||
|
||||
const value = useMemo<InstallStore>(() => ({
|
||||
installed,
|
||||
installing,
|
||||
installedCount: installed.size,
|
||||
hydrating,
|
||||
isInstalled: (id: string) => installed.has(id),
|
||||
isInstalling: (id: string) => installing.has(id),
|
||||
install,
|
||||
uninstall,
|
||||
hydrate,
|
||||
}), [installed, installing, hydrating, install, uninstall, hydrate]);
|
||||
|
||||
return <InstallContext.Provider value={value}>{children}</InstallContext.Provider>;
|
||||
};
|
||||
79
apps/web/src/providers/ServiceProvider.tsx
Normal file
79
apps/web/src/providers/ServiceProvider.tsx
Normal file
@@ -0,0 +1,79 @@
|
||||
import { createContext, useContext, useState, useEffect, useRef, type ReactNode } from 'react';
|
||||
import { adapter } from '@/lib/adapter';
|
||||
import type { LocalAdapter } from '@/lib/adapter';
|
||||
import { CONNECT_SETTLED_EVENT } from '@/hooks/useRevalidateOnError';
|
||||
|
||||
interface ServiceContextValue {
|
||||
adapter: LocalAdapter;
|
||||
connected: boolean;
|
||||
connecting: boolean;
|
||||
error: string | null;
|
||||
reconnect: () => void;
|
||||
}
|
||||
|
||||
const ServiceContext = createContext<ServiceContextValue | null>(null);
|
||||
|
||||
export const useService = () => {
|
||||
const ctx = useContext(ServiceContext);
|
||||
if (!ctx) throw new Error('useService must be used within ServiceProvider');
|
||||
return ctx;
|
||||
};
|
||||
|
||||
/** P1b D3: backoff schedule for the cold-sidecar boot window (the default
|
||||
* desktop path — webview up before the sidecar listens; the boot-connect
|
||||
* kickoff fails fast with ECONNREFUSED). Capped: steady-state recovery is
|
||||
* owned by the adapter gate's re-arm + the 401-refresh leg, not a poll. */
|
||||
const RETRY_DELAYS_MS = [1000, 3000, 9000];
|
||||
|
||||
export const ServiceProvider = ({ children }: { children: ReactNode }) => {
|
||||
const [connected, setConnected] = useState(false);
|
||||
const [connecting, setConnecting] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const retryTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
// Review fix: a connect rejection landing AFTER unmount must not schedule a
|
||||
// new timer (the unmount cleanup already ran) or setState on a dead tree.
|
||||
const mounted = useRef(true);
|
||||
|
||||
// P1b D3: every settlement (success or failure) is broadcast so errored
|
||||
// Stage-B surfaces (tier, 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.
|
||||
const connect = async (attempt = 0, force = false) => {
|
||||
if (retryTimer.current) { clearTimeout(retryTimer.current); retryTimer.current = null; }
|
||||
setConnecting(true);
|
||||
setError(null);
|
||||
try {
|
||||
// Dedups onto the boot-connect.ts kickoff via the adapter's memo.
|
||||
await (force ? adapter.forceReconnect() : adapter.connect());
|
||||
if (!mounted.current) return;
|
||||
setConnected(true);
|
||||
setConnecting(false);
|
||||
window.dispatchEvent(new CustomEvent(CONNECT_SETTLED_EVENT, { detail: { connected: true } }));
|
||||
} catch (e) {
|
||||
if (!mounted.current) return;
|
||||
setError(e instanceof Error ? e.message : 'Failed to connect');
|
||||
setConnected(false);
|
||||
setConnecting(false);
|
||||
window.dispatchEvent(new CustomEvent(CONNECT_SETTLED_EVENT, { detail: { connected: false } }));
|
||||
if (attempt < RETRY_DELAYS_MS.length) {
|
||||
retryTimer.current = setTimeout(() => { void connect(attempt + 1); }, RETRY_DELAYS_MS[attempt]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
connect();
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
if (retryTimer.current) clearTimeout(retryTimer.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ServiceContext.Provider value={{ adapter: adapter as LocalAdapter, connected, connecting, error, reconnect: () => connect(0, true) }}>
|
||||
{children}
|
||||
</ServiceContext.Provider>
|
||||
);
|
||||
};
|
||||
231
apps/web/src/providers/ShellContext.tsx
Normal file
231
apps/web/src/providers/ShellContext.tsx
Normal file
@@ -0,0 +1,231 @@
|
||||
/**
|
||||
* UX Refactor v2.1 P1a — ShellContext (conversion plan §5.1).
|
||||
*
|
||||
* Relocates Desktop.tsx's cross-cutting integrator state (Desktop.tsx:119-230)
|
||||
* into a provider so AppShell (StatusBar + nav + overlays) and the route
|
||||
* wrappers consume ONE instance of each hook. The SHAPE is Desktop's, moved —
|
||||
* no new state is invented here:
|
||||
* - 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
|
||||
* (Desktop.tsx:122-125)
|
||||
* - useOverlayState bundle (Desktop.tsx:214 — overlays mount in AppShell,
|
||||
* wrappers trigger them, e.g. HomeCockpit's onCreateWorkspace)
|
||||
* - Context Rail target (Desktop.tsx:226 — rail mounts in AppShell,
|
||||
* surfaces feed it via onContextRail)
|
||||
*
|
||||
* Surface-local hooks (useMemory / useKnowledgeGraph / useEvents) deliberately
|
||||
* do NOT live here — they move into their route wrappers (§5.1 table).
|
||||
*
|
||||
* 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 { 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 { ContextRailTarget } from '@/components/os/overlays/ContextRail';
|
||||
import { useWorkspaces } from '@/hooks/useWorkspaces';
|
||||
import { useAgentStatus } from '@/hooks/useAgentStatus';
|
||||
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>;
|
||||
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'];
|
||||
activeWorkspace: WorkspacesBundle['activeWorkspace'];
|
||||
activeWorkspaceId: WorkspacesBundle['activeWorkspaceId'];
|
||||
selectWorkspace: WorkspacesBundle['selectWorkspace'];
|
||||
createWorkspace: WorkspacesBundle['createWorkspace'];
|
||||
patchWorkspace: WorkspacesBundle['patchWorkspace'];
|
||||
/** G3 (UX-Northstar 2026-06-13): existed in useWorkspaces but was never
|
||||
* forwarded by the P1a provider extraction — workspace delete was
|
||||
* unreachable from any UI. */
|
||||
deleteWorkspace: WorkspacesBundle['deleteWorkspace'];
|
||||
refreshWorkspaces: WorkspacesBundle['refresh'];
|
||||
/** P1b D3: load-failure surface — an errored empty list must not render as "no workspaces". */
|
||||
workspacesError: WorkspacesBundle['error'];
|
||||
/** R15-V3 s03 fix: existed in useWorkspaces but was never forwarded, so the
|
||||
* 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) ──
|
||||
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) ──
|
||||
notifications: NotificationsBundle['notifications'];
|
||||
unreadCount: NotificationsBundle['unreadCount'];
|
||||
markRead: NotificationsBundle['markRead'];
|
||||
markAllRead: NotificationsBundle['markAllRead'];
|
||||
// ── Onboarding (Desktop.tsx:124) ──
|
||||
onboardingState: OnboardingBundle['state'];
|
||||
updateOnboarding: OnboardingBundle['update'];
|
||||
completeOnboarding: OnboardingBundle['complete'];
|
||||
// ── Offline / agent status (Desktop.tsx:122, 125) ──
|
||||
offline: boolean;
|
||||
agentStatus: AgentStatusBundle;
|
||||
// ── Overlay open/close state (Desktop.tsx:214) ──
|
||||
overlays: OverlayBundle;
|
||||
// ── Context Rail (Desktop.tsx:226) ──
|
||||
contextRailTarget: ContextRailTarget | null;
|
||||
setContextRailTarget: (target: ContextRailTarget | null) => void;
|
||||
}
|
||||
|
||||
const ShellContext = createContext<ShellContextValue | null>(null);
|
||||
|
||||
export const useShell = () => {
|
||||
const ctx = useContext(ShellContext);
|
||||
if (!ctx) throw new Error('useShell must be used within ShellProvider');
|
||||
return ctx;
|
||||
};
|
||||
|
||||
export const ShellProvider = ({ children }: { children: ReactNode }) => {
|
||||
const {
|
||||
workspaces, activeWorkspace, activeWorkspaceId,
|
||||
selectWorkspace, createWorkspace, patchWorkspace, deleteWorkspace, refresh: refreshWorkspaces,
|
||||
error: workspacesError, loading: workspacesLoading,
|
||||
} = useWorkspaces();
|
||||
const agentStatus = useAgentStatus();
|
||||
const { notifications, unreadCount, markRead, markAllRead } = useNotifications();
|
||||
const { state: onboardingState, update: updateOnboarding, complete: completeOnboarding } = useOnboarding();
|
||||
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
|
||||
// fresh chat widget. Existing widgets keep their own state.
|
||||
const [defaultAutonomy, setDefaultAutonomy] = useState<'normal' | 'trusted' | 'yolo'>('normal');
|
||||
useEffect(() => {
|
||||
adapter.getPermissions().then(p => setDefaultAutonomy(p.defaultAutonomy)).catch(() => {});
|
||||
}, []);
|
||||
|
||||
// Overlay state (relocated from Desktop.tsx:214)
|
||||
const overlays = useOverlayState();
|
||||
|
||||
// Phase C.1 Context Rail target (relocated from Desktop.tsx:226)
|
||||
const [contextRailTarget, setContextRailTarget] = useState<ContextRailTarget | null>(null);
|
||||
|
||||
return (
|
||||
<ShellContext.Provider value={{
|
||||
workspaces, activeWorkspace, activeWorkspaceId,
|
||||
selectWorkspace, createWorkspace, patchWorkspace, deleteWorkspace, refreshWorkspaces, workspacesError, workspacesLoading,
|
||||
currentTier, billingTier, tierResolved, tierError, trialInfo, refreshTier, showTrialExpired, setShowTrialExpired,
|
||||
defaultAutonomy,
|
||||
notifications, unreadCount, markRead, markAllRead,
|
||||
onboardingState, updateOnboarding, completeOnboarding,
|
||||
offline, agentStatus,
|
||||
overlays,
|
||||
contextRailTarget, setContextRailTarget,
|
||||
}}>
|
||||
{children}
|
||||
</ShellContext.Provider>
|
||||
);
|
||||
};
|
||||
208
apps/web/src/providers/ThemeProvider.tsx
Normal file
208
apps/web/src/providers/ThemeProvider.tsx
Normal file
@@ -0,0 +1,208 @@
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { DUR } from "@/lib/motion/tokens";
|
||||
|
||||
/**
|
||||
* Warm-Hive theme provider.
|
||||
*
|
||||
* Owns the single source of truth for the app's theme: the `data-theme`
|
||||
* attribute on `<html>` (`light` = warm paper; absent = warm graphite / dark,
|
||||
* matching the design CSS `:root` vs `:root[data-theme="light"]` selectors) plus
|
||||
* the persisted user choice in `localStorage['waggle-theme']`.
|
||||
*
|
||||
* Replaces the previous ad-hoc theme plumbing (boot snippet in App.tsx + inline
|
||||
* toggle in SettingsApp + scattered DOM writes). Readers that only need the
|
||||
* resolved value can keep using `useIsLightTheme()` — it reactively observes the
|
||||
* same `data-theme` attribute this provider writes.
|
||||
*/
|
||||
|
||||
export type ThemeMode = "dark" | "light" | "system";
|
||||
export type ResolvedTheme = "dark" | "light";
|
||||
|
||||
interface ThemeContextValue {
|
||||
/** The user's chosen mode (may be "system"). */
|
||||
theme: ThemeMode;
|
||||
/** The actual applied theme after resolving "system". */
|
||||
resolvedTheme: ResolvedTheme;
|
||||
setTheme: (mode: ThemeMode) => void;
|
||||
/** Convenience flip between light and dark (resolves "system" first). */
|
||||
toggleTheme: () => void;
|
||||
}
|
||||
|
||||
const STORAGE_KEY = "waggle-theme";
|
||||
|
||||
// Default context value. Lets `useTheme()` work without a wrapping provider —
|
||||
// e.g. isolated unit tests that render a single app (SettingsApp) outside the
|
||||
// full provider tree, mirroring SettingsApp's previous standalone behaviour.
|
||||
// Reads are live (getters re-read the DOM/storage on access); writes still apply
|
||||
// to `data-theme` + localStorage. Inside <ThemeProvider>, the reactive value
|
||||
// below takes over and re-renders consumers on change.
|
||||
const standaloneTheme: ThemeContextValue = {
|
||||
get theme() {
|
||||
return readStored();
|
||||
},
|
||||
get resolvedTheme() {
|
||||
return resolve(readStored());
|
||||
},
|
||||
setTheme(mode) {
|
||||
applyTheme(resolve(mode), true);
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, mode);
|
||||
} catch {
|
||||
/* storage disabled — non-fatal */
|
||||
}
|
||||
},
|
||||
toggleTheme() {
|
||||
const next: ResolvedTheme = resolve(readStored()) === "light" ? "dark" : "light";
|
||||
applyTheme(next, true);
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, next);
|
||||
} catch {
|
||||
/* storage disabled — non-fatal */
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
const ThemeContext = createContext<ThemeContextValue>(standaloneTheme);
|
||||
|
||||
function readStored(): ThemeMode {
|
||||
if (typeof localStorage === "undefined") return "dark";
|
||||
const v = localStorage.getItem(STORAGE_KEY);
|
||||
return v === "light" || v === "dark" || v === "system" ? v : "dark";
|
||||
}
|
||||
|
||||
function systemPrefersDark(): boolean {
|
||||
return (
|
||||
typeof window !== "undefined" &&
|
||||
typeof window.matchMedia === "function" &&
|
||||
window.matchMedia("(prefers-color-scheme: dark)").matches
|
||||
);
|
||||
}
|
||||
|
||||
function resolve(mode: ThemeMode): ResolvedTheme {
|
||||
if (mode === "system") return systemPrefersDark() ? "dark" : "light";
|
||||
return mode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lane D (Wave V) — signature theme crossfade ("sunset over the hive"). On a
|
||||
* REAL theme change we stamp `.theme-transition` on <html> for one swap window;
|
||||
* the CSS rule (index.css, motion-safe) interpolates the color tokens, then the
|
||||
* class is removed so it never lingers on ordinary hover/interaction. The
|
||||
* animation is pure CSS transition — JS only toggles a class. Reduced-motion
|
||||
* users never get the class (belt) AND the CSS is `no-preference`-gated
|
||||
* (suspenders), so their swap stays instant.
|
||||
*/
|
||||
// The theme crossfade rides the standard "slow" motion tier: sourced from the
|
||||
// motion vocabulary (DUR.slow → --mo-slow = 320ms) so the JS cleanup window and
|
||||
// the CSS `.theme-transition` duration in index.css share ONE source of truth
|
||||
// (was a bespoke 360ms literal). `Math.round` keeps the float-scaled ms an
|
||||
// integer. The +60ms buffer below outlives the CSS transition regardless of
|
||||
// whether index.css resolves `.theme-transition` to var(--mo-slow) (320) yet.
|
||||
const THEME_TRANSITION_MS = Math.round(DUR.slow * 1000);
|
||||
let themeTransitionTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
// Last theme actually stamped onto <html>. Lets applyTheme distinguish a real
|
||||
// swap (crossfade) from the initial apply / a no-op re-apply (instant), so the
|
||||
// crossfade never fires on load or on a StrictMode double-invoke.
|
||||
let lastAppliedTheme: ResolvedTheme | undefined;
|
||||
|
||||
function prefersReducedMotion(): boolean {
|
||||
return (
|
||||
typeof window !== "undefined" &&
|
||||
typeof window.matchMedia === "function" &&
|
||||
window.matchMedia("(prefers-reduced-motion: reduce)").matches
|
||||
);
|
||||
}
|
||||
|
||||
function beginThemeTransition(root: HTMLElement): void {
|
||||
if (prefersReducedMotion()) return;
|
||||
root.classList.add("theme-transition");
|
||||
if (themeTransitionTimer) clearTimeout(themeTransitionTimer);
|
||||
themeTransitionTimer = setTimeout(() => {
|
||||
root.classList.remove("theme-transition");
|
||||
themeTransitionTimer = undefined;
|
||||
}, THEME_TRANSITION_MS + 60);
|
||||
}
|
||||
|
||||
function applyTheme(resolved: ResolvedTheme, animate = false): void {
|
||||
if (typeof document === "undefined") return;
|
||||
const root = document.documentElement;
|
||||
// Crossfade only when a caller opted in AND the value truly changes from what
|
||||
// is on <html> — the class must be present before the tokens swap for the CSS
|
||||
// transition to capture the change (both happen in this one synchronous tick).
|
||||
if (animate && lastAppliedTheme !== undefined && lastAppliedTheme !== resolved) {
|
||||
beginThemeTransition(root);
|
||||
}
|
||||
if (resolved === "light") root.setAttribute("data-theme", "light");
|
||||
else root.removeAttribute("data-theme");
|
||||
lastAppliedTheme = resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the persisted theme synchronously, before React mounts, to avoid a
|
||||
* flash of the wrong theme on load. Call once from `main.tsx` ahead of
|
||||
* `createRoot(...).render()`.
|
||||
*/
|
||||
export function applyStoredThemeEarly(): void {
|
||||
applyTheme(resolve(readStored()));
|
||||
}
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const [theme, setThemeState] = useState<ThemeMode>(readStored);
|
||||
const [resolvedTheme, setResolvedTheme] = useState<ResolvedTheme>(() =>
|
||||
resolve(readStored()),
|
||||
);
|
||||
|
||||
// Apply + persist whenever the chosen mode changes. useLayoutEffect runs
|
||||
// before paint, so the first render after a toggle is never the old theme.
|
||||
useLayoutEffect(() => {
|
||||
const r = resolve(theme);
|
||||
setResolvedTheme(r);
|
||||
// animate: the initial apply / re-apply is a no-op vs. the pre-paint stamp
|
||||
// (applyStoredThemeEarly), so applyTheme's change-guard suppresses the
|
||||
// crossfade on mount; only a genuine mode change fades.
|
||||
applyTheme(r, true);
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, theme);
|
||||
} catch {
|
||||
/* private mode / storage disabled — non-fatal, theme still applies */
|
||||
}
|
||||
}, [theme]);
|
||||
|
||||
// In "system" mode, follow OS preference changes live.
|
||||
useEffect(() => {
|
||||
if (theme !== "system") return;
|
||||
if (typeof window === "undefined" || typeof window.matchMedia !== "function") return;
|
||||
const mql = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
const onChange = () => {
|
||||
const r: ResolvedTheme = mql.matches ? "dark" : "light";
|
||||
setResolvedTheme(r);
|
||||
applyTheme(r, true);
|
||||
};
|
||||
mql.addEventListener("change", onChange);
|
||||
return () => mql.removeEventListener("change", onChange);
|
||||
}, [theme]);
|
||||
|
||||
const setTheme = useCallback((mode: ThemeMode) => setThemeState(mode), []);
|
||||
const toggleTheme = useCallback(
|
||||
() => setThemeState((prev) => (resolve(prev) === "light" ? "dark" : "light")),
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={{ theme, resolvedTheme, setTheme, toggleTheme }}>
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useTheme(): ThemeContextValue {
|
||||
return useContext(ThemeContext);
|
||||
}
|
||||
35
apps/web/src/providers/WaggleClerkProvider.tsx
Normal file
35
apps/web/src/providers/WaggleClerkProvider.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* WaggleClerkProvider — PR7b/D2(b) optional Clerk wrapper.
|
||||
*
|
||||
* With hosted auth enabled and a valid publishable key present, wraps the app in a
|
||||
* ClerkProvider (routerPush/replace → react-router's navigate, per the Clerk v5 docs,
|
||||
* to avoid flicker/reload). Otherwise renders children untouched so the desktop
|
||||
* stays fully accountless — never crashes, never fabricates a user (F1).
|
||||
*
|
||||
* MUST live INSIDE <BrowserRouter> (it calls useNavigate). Appearance follows the live
|
||||
* ThemeProvider value so Clerk's components track the warm dark/light themes.
|
||||
*/
|
||||
import type { ReactNode } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { ClerkProvider } from '@clerk/clerk-react';
|
||||
import { useTheme } from '@/providers/ThemeProvider';
|
||||
import { clerkPublishableKey, clerkAppearance } from '@/lib/clerk';
|
||||
|
||||
export default function WaggleClerkProvider({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const pk = clerkPublishableKey();
|
||||
|
||||
if (!pk) return <>{children}</>;
|
||||
|
||||
return (
|
||||
<ClerkProvider
|
||||
publishableKey={pk}
|
||||
routerPush={(to) => navigate(to)}
|
||||
routerReplace={(to) => navigate(to, { replace: true })}
|
||||
appearance={clerkAppearance(resolvedTheme === 'dark')}
|
||||
>
|
||||
{children}
|
||||
</ClerkProvider>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user