moving
Some checks failed
Installer Smoke / installer-smoke (push) Has been cancelled

This commit is contained in:
Oleg Maslov
2026-09-02 10:10:29 +02:00
commit 0c3e2ead3b
3841 changed files with 970576 additions and 0 deletions

View File

@@ -0,0 +1,36 @@
import type { ChatMessage } from '@/lib/types';
/**
* Lane C (Pillar 2.6-chat) — session-scoped cache of chat thread messages.
*
* Mirrors `memory/memory-list-cache.ts`: the last-known message list per
* (workspace, session) is held at MODULE scope so a re-mount (or a session
* switch back to a visited thread) can seed its initial state INSTANTLY and
* refresh in the background — no re-skeleton on return. The keep-alive ChatHost
* already preserves an in-session thread across tab-away/return; this cache adds
* the same instant paint for a genuine remount and for switching between two
* already-visited sessions.
*
* Only SETTLED threads are cached (never mid-stream partials or queued turns) —
* useChat guards the write. Not persisted across reloads: a page reload starts a
* fresh session by design, and history re-fetches from the sidecar.
*/
const cache = new Map<string, ChatMessage[]>();
/** Stable per-thread key from the two dimensions that select a message list. */
export function chatThreadCacheKey(workspaceId: string, sessionId: string): string {
return `${workspaceId}|${sessionId}`;
}
export function readChatThreadCache(key: string): ChatMessage[] | undefined {
return cache.get(key);
}
export function writeChatThreadCache(key: string, messages: ChatMessage[]): void {
cache.set(key, messages);
}
/** Test-only: drop all cached threads so module state can't leak across tests. */
export function clearChatThreadCache(): void {
cache.clear();
}

View File

@@ -0,0 +1,19 @@
import * as React from "react";
const MOBILE_BREAKPOINT = 768;
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined);
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
};
mql.addEventListener("change", onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
return () => mql.removeEventListener("change", onChange);
}, []);
return !!isMobile;
}

View File

@@ -0,0 +1,186 @@
import * as React from "react";
import type { ToastActionElement, ToastProps } from "@/components/ui/toast";
const TOAST_LIMIT = 1;
const TOAST_REMOVE_DELAY = 1000000;
type ToasterToast = ToastProps & {
id: string;
title?: React.ReactNode;
description?: React.ReactNode;
action?: ToastActionElement;
};
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const;
let count = 0;
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER;
return count.toString();
}
type ActionType = typeof actionTypes;
type Action =
| {
type: ActionType["ADD_TOAST"];
toast: ToasterToast;
}
| {
type: ActionType["UPDATE_TOAST"];
toast: Partial<ToasterToast>;
}
| {
type: ActionType["DISMISS_TOAST"];
toastId?: ToasterToast["id"];
}
| {
type: ActionType["REMOVE_TOAST"];
toastId?: ToasterToast["id"];
};
interface State {
toasts: ToasterToast[];
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>();
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return;
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId);
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
});
}, TOAST_REMOVE_DELAY);
toastTimeouts.set(toastId, timeout);
};
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
};
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) => (t.id === action.toast.id ? { ...t, ...action.toast } : t)),
};
case "DISMISS_TOAST": {
const { toastId } = action;
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId);
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id);
});
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t,
),
};
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
};
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
};
}
};
const listeners: Array<(state: State) => void> = [];
let memoryState: State = { toasts: [] };
function dispatch(action: Action) {
memoryState = reducer(memoryState, action);
listeners.forEach((listener) => {
listener(memoryState);
});
}
type Toast = Omit<ToasterToast, "id">;
function toast({ ...props }: Toast) {
const id = genId();
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
});
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id });
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss();
},
},
});
return {
id: id,
dismiss,
update,
};
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState);
React.useEffect(() => {
listeners.push(setState);
return () => {
const index = listeners.indexOf(setState);
if (index > -1) {
listeners.splice(index, 1);
}
};
}, [state]);
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
};
}
export { useToast, toast };

View File

@@ -0,0 +1,49 @@
import { useState, useEffect, useRef } from 'react';
import { adapter } from '@/lib/adapter';
import type { AgentStatus } from '@/lib/types';
export const useAgentStatus = () => {
const [status, setStatus] = useState<AgentStatus>({
model: 'unknown',
tokensUsed: 0,
costUsd: 0,
isActive: false,
});
const [offline, setOffline] = useState(false);
const failCount = useRef(0);
useEffect(() => {
let cancelled = false;
const poll = async () => {
try {
const data = await adapter.getAgentStatus();
if (cancelled) return;
setStatus(data);
setOffline(false);
failCount.current = 0;
} catch (err) {
if (cancelled) return;
console.error('[useAgentStatus] poll failed:', err);
failCount.current++;
setOffline(true);
}
};
poll();
// Exponential backoff: 30s, 60s, 120s, max 5min
const getInterval = () => Math.min(30000 * Math.pow(2, failCount.current), 300000);
let timer: ReturnType<typeof setTimeout>;
const schedule = () => {
timer = setTimeout(async () => {
await poll();
if (!cancelled) schedule();
}, getInterval());
};
schedule();
return () => {
cancelled = true;
clearTimeout(timer);
};
}, []);
return { ...status, offline };
};

View File

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

View File

@@ -0,0 +1,498 @@
import { useState, useCallback, useRef, useEffect } from 'react';
import { adapter } from '@/lib/adapter';
import { GENERATION_FAILED_PREFIX } from '@waggle/shared';
import {
chatThreadCacheKey,
readChatThreadCache,
writeChatThreadCache,
} from '@/hooks/chat-thread-cache';
import type {
ChatMessage, StreamEvent, ApprovalRequest,
ContentBlock, TextContentBlock, ToolExecution,
} from '@/lib/types';
let blockCounter = 0;
function nextBlockId(prefix: string): string {
return `${prefix}-${++blockCounter}-${Date.now()}`;
}
/** Convert legacy messages (from history API) that lack blocks */
function ensureBlocks(msg: ChatMessage): ChatMessage {
if (msg.blocks && msg.blocks.length > 0) {
// Backfill blockId on legacy blocks that were persisted without one
const patched = msg.blocks.map((b, i) => {
if (b.type === 'tool_use') return b; // tool_use uses `id` as key
if ('blockId' in b && b.blockId) return b;
return { ...b, blockId: `legacy-${msg.id}-${i}` };
});
return { ...msg, blocks: patched };
}
const blocks: ContentBlock[] = [];
if (msg.content) {
// W2G: a persisted failed assistant turn ("Generation failed: …") arrives
// from /api/history as flat text with no block typing. Decode it back into
// an error block so a reloaded failure renders the same ErrorBlock (with its
// Retry / Open-API-key-settings actions) as the live SSE path — stripping the
// prefix restores the bare message the live 'error' event carried.
if (msg.role === 'assistant' && msg.content.startsWith(GENERATION_FAILED_PREFIX)) {
blocks.push({
type: 'error',
blockId: nextBlockId('error'),
message: msg.content.slice(GENERATION_FAILED_PREFIX.length),
});
} else {
blocks.push({ type: 'text', blockId: nextBlockId('text'), content: msg.content });
}
}
if (msg.tools) {
for (const t of msg.tools) {
blocks.push({
type: 'tool_use',
id: t.id,
name: t.name,
input: t.input,
status: t.status === 'pending' ? 'running' : (t.status as 'running' | 'done' | 'error' | 'denied'),
result: t.output as string | undefined,
duration: t.duration,
});
}
}
return { ...msg, blocks };
}
/** Rebuild flat content string from text blocks (for copy, pins, search) */
function flattenBlocks(blocks: ContentBlock[]): string {
return blocks
.filter((b): b is TextContentBlock => b.type === 'text')
.map(b => b.content)
.join('');
}
export type AutonomyLevel = 'normal' | 'trusted' | 'yolo';
export interface AutonomyState {
level: AutonomyLevel;
/** Epoch ms after which the elevated level auto-reverts. null = until session end. */
expiresAt: number | null;
}
interface UseChatOptions {
workspaceId: string | null;
sessionId: string | null;
persona?: string;
/**
* Phase B.5: per-window autonomy. When set to 'trusted' or 'yolo' (and not
* expired), the server's pre-tool gate skips confirmation for the matching
* tool set. The server owns the final check — client state is advisory.
*/
autonomy?: AutonomyState;
}
export const useChat = ({ workspaceId, sessionId, persona, autonomy }: UseChatOptions) => {
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [pendingApproval, setPendingApproval] = useState<ApprovalRequest | null>(null);
// F2: true only after a real session's history fetch has landed. The wizard
// auto-send waits on this so its optimistic turn isn't clobbered by the
// history-replace that fires when the session id resolves.
const [historyLoaded, setHistoryLoaded] = useState(false);
const abortRef = useRef<AbortController | null>(null);
// Lane C (Pillar 2.2/2.5): a send fired while a reply is still streaming must
// NOT lock the composer or spawn a second concurrent SSE stream. Such sends
// QUEUE behind the in-flight one — the optimistic user turn renders at once
// with a truthful `queued` marker and dispatches when the current reply ends.
const inFlightRef = useRef(false);
const queueRef = useRef<Array<{ id: string; content: string; retry?: boolean }>>([]);
// Late-bound so the dispatch loop can flush its own queue without a self-dep.
const runDispatchRef = useRef<
(content: string, opts: { retry?: boolean } | undefined, optimisticId?: string) => Promise<boolean>
>(async () => false);
// Cancel any in-flight stream on unmount
useEffect(() => {
return () => { abortRef.current?.abort(); };
}, []);
// Load history when session changes
useEffect(() => {
// Lane C: a message queued into the previous thread must never dispatch into
// a freshly loaded one — drop the pending queue on every thread change.
queueRef.current = [];
if (workspaceId && sessionId) {
const cacheKey = chatThreadCacheKey(workspaceId, sessionId);
// Lane C (2.6-chat) cache-first paint: seed from the last-known thread so a
// return to a visited session renders instantly, then refresh silently.
const cached = readChatThreadCache(cacheKey);
if (cached) setMessages(cached);
setHistoryLoaded(false);
adapter.getHistory(workspaceId, sessionId)
.then((history) => {
const shaped = history.map(ensureBlocks);
setMessages(shaped);
writeChatThreadCache(cacheKey, shaped);
})
.catch((err) => {
console.error('[useChat] history fetch failed:', err);
// Keep a good cached paint on a transient refresh failure; only clear
// when there was nothing to show.
if (!cached) setMessages([]);
})
.finally(() => setHistoryLoaded(true));
} else {
// No session yet — leave historyLoaded false so an auto-send waits for a
// real session's history to land (never race the replace below).
setMessages([]);
}
}, [workspaceId, sessionId]);
// Lane C: persist the SETTLED thread (never mid-stream partials or queued
// turns) so a remount/return paints instantly from the cache above.
useEffect(() => {
if (!workspaceId || !sessionId) return;
if (isLoading) return;
if (messages.length === 0) return;
if (messages.some((m) => m.queued)) return;
writeChatThreadCache(chatThreadCacheKey(workspaceId, sessionId), messages);
}, [messages, workspaceId, sessionId, isLoading]);
const runDispatch = useCallback(async (
content: string,
opts?: { retry?: boolean },
optimisticId?: string,
): Promise<boolean> => {
if (!workspaceId || !content.trim()) return false;
inFlightRef.current = true;
// F2: report send success so the wizard auto-send knows whether to clear
// the composer or leave the text for a manual retry. Error handling below
// is unchanged — this only observes it.
let failed = false;
const trimmed = content.trim();
const assistantMsg: ChatMessage = {
id: crypto.randomUUID(),
role: 'assistant',
content: '',
blocks: [],
timestamp: new Date().toISOString(),
tools: [],
};
// Target the assistant turn BY ID (not "last message"): a queued turn may
// sit after it in the list, so position is not stable during streaming.
const assistantId = assistantMsg.id;
if (optimisticId) {
// Flush path: the optimistic user turn is already rendered (queued while a
// prior reply streamed). Promote it (clear `queued`) and insert the
// assistant placeholder directly after it — position-stable so any later
// queued turn keeps its order. If the turn was dropped (a thread switch
// between queueing and flush — which also clears the queue, so an edge),
// append the assistant at the end so streaming still has a target.
setMessages(prev => {
const idx = prev.findIndex(m => m.id === optimisticId);
if (idx === -1) return [...prev, assistantMsg];
const next = [...prev];
next[idx] = { ...next[idx], queued: false };
next.splice(idx + 1, 0, assistantMsg);
return next;
});
} else {
const userMsg: ChatMessage = {
id: crypto.randomUUID(),
role: 'user',
content: trimmed,
blocks: [{ type: 'text', blockId: nextBlockId('text'), content: trimmed }],
timestamp: new Date().toISOString(),
};
setMessages(prev => [...prev, userMsg, assistantMsg]);
}
setIsLoading(true);
abortRef.current?.abort();
// Lane S2 (Pillar 3.1): capture THIS stream's controller locally. The break
// guard below reads the local `controller`, not the shared `abortRef.current`
// — so a stop (or a fresh dispatch that reassigns abortRef) reliably halts
// THIS loop instead of racing whatever the ref now points at.
const controller = new AbortController();
abortRef.current = controller;
try {
// Phase B.5: only forward autonomy when elevated — Normal is the
// server default, so passing `undefined` keeps the wire payload lean.
const autonomyPayload = autonomy && autonomy.level !== 'normal'
? { level: autonomy.level, expiresAt: autonomy.expiresAt ?? undefined }
: undefined;
for await (const event of adapter.sendMessage(workspaceId, content, sessionId || undefined, persona, autonomyPayload, opts?.retry)) {
if (controller.signal.aborted) break;
const evt = event as StreamEvent;
const data = evt.data as Record<string, unknown>;
setMessages(prev => {
const msgs = [...prev];
const targetIdx = msgs.findIndex(m => m.id === assistantId);
const last = targetIdx >= 0 ? msgs[targetIdx] : undefined;
// Guard the missing-target case: a session/workspace switch mid-stream
// resets messages via the load effect, after which a late stream event
// would read `last.role` off undefined and crash the updater.
if (!last || last.role !== 'assistant') return msgs;
const blocks = [...(last.blocks || [])];
let toolsUpdate: ToolExecution[] | null = null;
switch (evt.type) {
case 'token': {
const tokenContent = typeof data === 'string' ? data : (data?.content as string ?? '');
const lastBlock = blocks[blocks.length - 1];
if (lastBlock?.type === 'text') {
blocks[blocks.length - 1] = { ...lastBlock, content: lastBlock.content + tokenContent };
} else {
blocks.push({ type: 'text', blockId: nextBlockId('text'), content: tokenContent });
}
break;
}
case 'step': {
const description = typeof data === 'string' ? data : (data?.content as string ?? '');
// PR3.5: carry memory-recall provenance (distinct raw source
// values) onto the step block; absent on non-memory steps.
const stepProvenance = (data?.provenance as { sources?: string[] } | undefined);
const stepSources = Array.isArray(stepProvenance?.sources) ? stepProvenance.sources : undefined;
if (description) {
// Mark previous running steps as done
for (let i = 0; i < blocks.length; i++) {
const b = blocks[i];
if (b.type === 'step' && b.status === 'running') {
blocks[i] = { ...b, status: 'done' };
}
}
blocks.push({
type: 'step',
blockId: nextBlockId('step'),
description,
status: 'running',
...(stepSources && stepSources.length > 0 ? { provenance: { sources: stepSources } } : {}),
});
}
break;
}
case 'tool_start': {
const toolName = (data?.name as string) ?? 'unknown';
const toolId = toolName + '-' + Date.now();
blocks.push({
type: 'tool_use',
id: toolId,
name: toolName,
input: data?.input as Record<string, unknown>,
status: 'running',
});
// Legacy tools[] — immutable accumulation
const prevTools = last.tools || [];
toolsUpdate = [...prevTools, { id: toolId, name: toolName, status: 'running' as const, input: data?.input as Record<string, unknown> }];
break;
}
case 'tool_end': {
const toolName = data?.name as string;
const result = data?.result as string;
const duration = data?.duration as number | undefined;
for (let i = blocks.length - 1; i >= 0; i--) {
const b = blocks[i];
if (b.type === 'tool_use' && b.name === toolName && b.status === 'running') {
blocks[i] = { ...b, status: 'done', result, duration };
break;
}
}
// Mark most recent running step as done
for (let i = blocks.length - 1; i >= 0; i--) {
const b = blocks[i];
if (b.type === 'step' && b.status === 'running') {
blocks[i] = { ...b, status: 'done' };
break;
}
}
// Legacy tools[] — immutable update
if (last.tools && toolName) {
const idx = last.tools.findIndex(t => t.name === toolName && t.status === 'running');
if (idx >= 0) {
toolsUpdate = last.tools.map((t, ti) =>
ti === idx ? { ...t, status: 'done' as const, output: result, duration } : t
);
}
}
break;
}
case 'model_switch': {
blocks.push({
type: 'model_switch',
blockId: nextBlockId('model'),
from: (data as Record<string, string>).primary ?? 'primary',
to: (data as Record<string, string>).model ?? 'fallback',
reason: (data as Record<string, string>).reason ?? 'primary unavailable',
});
break;
}
case 'error': {
const errorMsg = typeof data === 'string' ? data : (data?.message as string ?? 'Unknown error');
blocks.push({ type: 'error', blockId: nextBlockId('error'), message: errorMsg });
break;
}
case 'done': {
// Mark all running blocks as done — type-narrowed, no unsafe cast
for (let i = 0; i < blocks.length; i++) {
const b = blocks[i];
if (b.type === 'step' && b.status === 'running') {
blocks[i] = { ...b, status: 'done' };
} else if (b.type === 'tool_use' && b.status === 'running') {
blocks[i] = { ...b, status: 'done' };
}
}
const doneContent = data?.content as string;
if (doneContent && !blocks.some(b => b.type === 'text' && b.content)) {
blocks.push({ type: 'text', blockId: nextBlockId('text'), content: doneContent });
}
break;
}
case 'approval_request':
case 'approval_required':
// Backend emits `approval_required` as the SSE event name;
// legacy clients sent `approval_request`. Accept both.
setPendingApproval(data as unknown as ApprovalRequest);
return msgs; // Don't update blocks for approval
}
const content = flattenBlocks(blocks);
return msgs.map((m, i) =>
i === targetIdx
? { ...m, blocks, content, ...(toolsUpdate && { tools: toolsUpdate }) }
: m
);
});
}
} catch (e) {
failed = true;
// P1b D3: sendMessage now THROWS AdapterHttpError on HTTP failure (it
// used to parse the error body as an empty SSE stream — silent dead
// chat). 'Backend is offline' is reserved for genuine network failures;
// a tier 403 already opened the UpgradeModal via the adapter's global
// dispatch, so its inline copy points there instead of duplicating the
// upsell. Duck-typed on error.name (NOT instanceof an imported class) so
// component tests that vi.mock('@/lib/adapter') wholesale stay decoupled.
const httpErr = e instanceof Error && e.name === 'AdapterHttpError'
? (e as Error & { status?: number; body?: unknown })
: null;
const isTier403 = (httpErr?.body as { error?: string } | undefined)?.error === 'TIER_INSUFFICIENT';
const message = isTier403
? 'This action needs a higher plan — see the upgrade window.'
: httpErr
? `Chat request failed (${httpErr.status}): ${httpErr.message}`
: 'Backend is offline. Connect to a Waggle server to start chatting.';
setMessages(prev => {
const msgs = [...prev];
const targetIdx = msgs.findIndex(m => m.id === assistantId);
const last = targetIdx >= 0 ? msgs[targetIdx] : undefined;
// Same missing-target guard as the stream updater: a session/workspace
// switch mid-flight resets messages. Return prev (not the clone) so
// React's setState bail-out skips the no-op re-render.
if (!last || last.role !== 'assistant') return prev;
const blocks = [...(last.blocks || []), { type: 'error' as const, blockId: nextBlockId('error'), message }];
return msgs.map((m, i) =>
i === targetIdx ? { ...m, blocks, content: message } : m
);
});
} finally {
setIsLoading(false);
inFlightRef.current = false;
// Flush the next queued send (FIFO) now that the stream has ended.
const next = queueRef.current.shift();
if (next) void runDispatchRef.current(next.content, { retry: next.retry }, next.id);
}
return !failed;
}, [workspaceId, sessionId, persona, autonomy]);
runDispatchRef.current = runDispatch;
const sendMessage = useCallback(async (content: string, opts?: { retry?: boolean }): Promise<boolean> => {
if (!workspaceId || !content.trim()) return false;
const trimmed = content.trim();
// Lane C: if a reply is already streaming, QUEUE this send behind it instead
// of racing a second SSE stream. The optimistic user turn renders now with a
// truthful `queued` marker; it dispatches when the current reply finishes.
if (inFlightRef.current) {
const id = crypto.randomUUID();
queueRef.current.push({ id, content: trimmed, retry: opts?.retry });
setMessages(prev => [...prev, {
id,
role: 'user',
content: trimmed,
blocks: [{ type: 'text', blockId: nextBlockId('text'), content: trimmed }],
timestamp: new Date().toISOString(),
queued: true,
}]);
return true;
}
return runDispatch(content, opts);
}, [workspaceId, runDispatch]);
// F4: re-issue the last user turn after a failure. Drops the failed
// user+assistant pair from local state first, then sendMessage re-appends a
// fresh pair — avoiding a duplicate user bubble.
const retryLastFailed = useCallback(() => {
if (isLoading) return;
let idx = -1;
for (let i = messages.length - 1; i >= 0; i--) {
if (messages[i].role === 'user') { idx = i; break; }
}
if (idx === -1) return;
const content = messages[idx].content;
setMessages(prev => prev.slice(0, idx));
void sendMessage(content, { retry: true });
}, [messages, isLoading, sendMessage]);
// Lane S2 (Pillar 3.1): user-initiated halt of the in-flight reply. Aborts THIS
// stream's controller (the for-await breaks before appending the next event),
// flips the composer back to send at once, and best-effort tells the server
// agent loop to stop. The partial answer already rendered stays untouched — no
// rollback. Idempotent: the stream's own `finally` also clears these.
const stopStreaming = useCallback(() => {
if (!inFlightRef.current) return;
abortRef.current?.abort();
inFlightRef.current = false;
setIsLoading(false);
if (workspaceId) {
try {
void Promise.resolve(adapter.abortAgent(workspaceId)).catch(() => { /* best-effort */ });
} catch { /* adapter unavailable */ }
}
}, [workspaceId]);
const clearHistory = useCallback(async () => {
if (sessionId) {
try {
await adapter.clearHistory(sessionId);
} catch (err) { console.error('[useChat] clear history failed:', err); }
setMessages([]);
}
}, [sessionId]);
const approveAction = useCallback(async (
requestId: string,
approved: boolean,
opts: { always?: boolean } = {},
) => {
try {
await adapter.respondApproval(requestId, approved, {
always: opts.always,
// Phase B.3: echo the source workspace we received on the SSE event
// back to the backend so the grant stays scoped to this workspace.
sourceWorkspaceId: pendingApproval?.sourceWorkspaceId ?? null,
});
} catch (err) {
console.error('[useChat] approval response failed:', err);
}
setPendingApproval(null);
}, [pendingApproval]);
return { messages, isLoading, historyLoaded, sendMessage, retryLastFailed, stopStreaming, clearHistory, pendingApproval, approveAction };
};

View File

@@ -0,0 +1,303 @@
/**
* UX Refactor v2.1 P1a Stage B — per-workspace chat-widget state
* (conversion plan §3.2 / §4.2).
*
* Relocates the SURVIVING slice of useWindowManager (its §3.1 deletion is
* Stage C): WindowState.personaId/autonomyLevel/autonomyExpiresAt +
* setWindowPersona/setWindowAutonomy + the 10s autonomy auto-revert interval
* (useWindowManager.ts:316-361). Logic moves verbatim; the keying changes
* from instanceId to workspaceId, persisted under the NEW versioned key
* 'waggle-chat-state-v1' (seeded once by the §3.3 migration,
* lib/window-state-migration.ts).
*
* Also hosts:
* - the §4.2 one-shot imperative chat seed API: seedChat(workspaceId,
* {personaId?, initialMessage?}) — the post-conversion carrier for what
* WindowState.initialMessage/personaId (useWindowManager.ts:30) carried
* into ChatWindowInstance's initialPersona/initialMessage props. It is
* transient intent, NOT part of the persisted key. Sole conversion-time
* caller: the wizard onFinish retarget (§2.2); consumed by ChatHost on
* the widget's first mount for that workspace.
* - the chat-title composition (§3.2: useWindowManager.ts:428-436 → widget
* header label) + the PERSONA_SHORT/TEMPLATE_SHORT maps it derives from.
* - the §3.3.3 'local-default' placeholder re-key contract, performed once
* when the store first sees the real workspace list (mirrors the deleted
* reconciliation sweep, useWindowManager.ts:167-172).
*/
import { useCallback, useEffect, useSyncExternalStore } from 'react';
export const CHAT_STATE_KEY = 'waggle-chat-state-v1';
export type AutonomyLevel = 'normal' | 'trusted' | 'yolo';
/** The persisted per-workspace slice of the old WindowState (§3.2). */
export interface ChatWidgetEntry {
personaId?: string;
personaLabel?: string;
autonomyLevel?: AutonomyLevel;
autonomyExpiresAt?: number | null;
}
/** §4.2 one-shot seed payload (transient — never persisted). */
export interface ChatSeed {
personaId?: string;
initialMessage?: string;
/** F2: auto-send the initialMessage once the chat is ready (wizard "Let's go"). */
autoSend?: boolean;
}
// Relocated verbatim from useWindowManager.ts:86-105.
const TEMPLATE_SHORT: Record<string, string> = {
'sales-pipeline': 'Sales',
'research-project': 'Research',
'code-review': 'Code',
'marketing-campaign': 'Marketing',
'product-launch': 'Launch',
'legal-review': 'Legal',
'agency-consulting': 'Consulting',
};
const PERSONA_SHORT: Record<string, string> = {
'researcher': 'Researcher',
'writer': 'Writer',
'analyst': 'Analyst',
'coder': 'Coder',
'project-manager': 'PM',
'executive-assistant': 'EA',
'sales-rep': 'Sales',
'marketer': 'Marketer',
};
// Relocated verbatim from useWindowManager.ts:49-52.
export function personaLabelFor(personaId?: string): string | undefined {
if (!personaId) return undefined;
return PERSONA_SHORT[personaId] || personaId;
}
/**
* §3.2: getWindowTitle's chat-title composition (useWindowManager.ts:428-436)
* → the widget header label. The template label derives live from the
* workspace's templateId exactly as openChatForWorkspace stamped it onto the
* window at creation (useWindowManager.ts:231).
*/
export function composeChatTitle(workspaceName?: string, templateId?: string, personaId?: string): string {
const parts = [workspaceName || 'Chat'];
const templateLabel = templateId && templateId !== 'blank'
? (TEMPLATE_SHORT[templateId] || templateId)
: undefined;
if (templateLabel) parts.push(templateLabel);
const personaLabel = personaLabelFor(personaId);
if (personaLabel) parts.push(personaLabel);
return parts.join(' · ');
}
// ── Persisted store (waggle-chat-state-v1) ────────────────────────────────
const AUTONOMY_LEVELS: ReadonlySet<string> = new Set(['normal', 'trusted', 'yolo']);
/** Shallow per-field validation — drop unknown shapes, keep valid fields. */
function sanitizeEntry(value: unknown): ChatWidgetEntry | null {
if (!value || typeof value !== 'object') return null;
const rec = value as Record<string, unknown>;
const entry: ChatWidgetEntry = {};
if (typeof rec.personaId === 'string') entry.personaId = rec.personaId;
if (typeof rec.personaLabel === 'string') entry.personaLabel = rec.personaLabel;
if (typeof rec.autonomyLevel === 'string' && AUTONOMY_LEVELS.has(rec.autonomyLevel)) {
entry.autonomyLevel = rec.autonomyLevel as AutonomyLevel;
}
const expiresAt = rec.autonomyExpiresAt;
if (typeof expiresAt === 'number') {
entry.autonomyExpiresAt = expiresAt;
} else if (expiresAt === null) {
entry.autonomyExpiresAt = null;
}
return entry;
}
function parseChatState(raw: string | null): Record<string, ChatWidgetEntry> {
if (!raw) return {};
try {
const parsed = JSON.parse(raw) as { version?: number; chats?: Record<string, unknown> };
if (parsed.version !== 1 || !parsed.chats || typeof parsed.chats !== 'object') return {};
const chats: Record<string, ChatWidgetEntry> = {};
for (const [wsId, value] of Object.entries(parsed.chats)) {
const entry = sanitizeEntry(value);
if (entry) chats[wsId] = entry;
}
return chats;
} catch {
return {};
}
}
// Read-through cache keyed on the raw string so getSnapshot returns a stable
// reference between writes (useSyncExternalStore requirement) while direct
// localStorage resets (tests, fresh sessions) still invalidate naturally.
let cacheRaw: string | null = null;
let cache: Record<string, ChatWidgetEntry> | null = null;
const listeners = new Set<() => void>();
function subscribeChatState(listener: () => void): () => void {
listeners.add(listener);
return () => { listeners.delete(listener); };
}
export function loadChatEntries(): Record<string, ChatWidgetEntry> {
if (typeof window === 'undefined' || !window.localStorage) return cache ?? {};
const raw = window.localStorage.getItem(CHAT_STATE_KEY);
if (cache === null || raw !== cacheRaw) {
cacheRaw = raw;
cache = parseChatState(raw);
}
return cache;
}
function persistChatEntries(chats: Record<string, ChatWidgetEntry>): void {
try {
window.localStorage.setItem(CHAT_STATE_KEY, JSON.stringify({ version: 1, chats }));
} catch {
// Quota exceeded / Safari private mode — non-fatal; the in-memory cache
// still serves this session (parity with savePersistedWindows,
// useWindowManager.ts:74-84).
}
cacheRaw = window.localStorage.getItem(CHAT_STATE_KEY);
cache = chats;
listeners.forEach(l => l());
}
/** Immutable per-workspace patch write (the store's single mutation path). */
export function writeChatEntry(workspaceId: string, patch: Partial<ChatWidgetEntry>): void {
const chats = loadChatEntries();
persistChatEntries({ ...chats, [workspaceId]: { ...chats[workspaceId], ...patch } });
}
/**
* §3.3 step 3 writer for the migration: merge salvaged entries into the
* store. Migrated entries win per workspace (last-write-wins).
*/
export function mergeChatEntries(entries: Record<string, ChatWidgetEntry>): void {
persistChatEntries({ ...loadChatEntries(), ...entries });
}
/**
* §3.3.3: one-shot legacy re-key mirroring the deleted reconciliation sweep
* (useWindowManager.ts:167-172) — an entry stamped with the 'local-default'
* pre-fetch placeholder moves onto the first REAL workspace when the store
* first sees the workspace list (ChatHost calls this). If the real workspace
* already has its own entry, that more-specific entry wins and the
* placeholder is dropped. New widget state is never placeholder-stamped, so
* this re-key dies with the §2.3 shim cleanup.
*/
export function rekeyLocalDefaultChatState(firstRealWorkspaceId: string): void {
const chats = loadChatEntries();
const placeholder = chats['local-default'];
if (!placeholder) return;
const rest = Object.fromEntries(
Object.entries(chats).filter(([wsId]) => wsId !== 'local-default'),
) as Record<string, ChatWidgetEntry>;
persistChatEntries(
rest[firstRealWorkspaceId] ? rest : { ...rest, [firstRealWorkspaceId]: placeholder },
);
}
// ── §4.2 one-shot imperative seed API ─────────────────────────────────────
const pendingSeeds = new Map<string, ChatSeed>();
/** Stage a one-shot seed for a workspace's chat widget (wizard onFinish, §2.2). */
export function seedChat(workspaceId: string, seed: ChatSeed): void {
pendingSeeds.set(workspaceId, seed);
}
/** Destructive read — returns the pending seed exactly once, then clears it. */
export function takeChatSeed(workspaceId: string): ChatSeed | undefined {
const seed = pendingSeeds.get(workspaceId);
pendingSeeds.delete(workspaceId);
return seed;
}
// ── The hook ──────────────────────────────────────────────────────────────
export interface UseChatWidgetStateOptions {
/**
* P4 (relocated from useWindowManager.ts:107-115 + openChatForWorkspace's
* inheritAutonomy stamp, :249-264): default autonomy inherited the FIRST
* time a workspace gets a chat widget (no persisted autonomy level yet —
* a persona-only entry does NOT count as "seen"). 'normal' is treated as
* "no inheritance"; any elevated level is stamped with expiresAt:null so
* it sticks until explicitly lowered (the widget-world equivalent of the
* per-window "Until I close" TTL choice — restored windows persisted their
* elevated grants the same way; the §3.3 migration stamps them with an
* explicit autonomyLevel:'normal' marker so they never retro-inherit).
*/
defaultAutonomy?: AutonomyLevel;
}
const EMPTY_ENTRY: ChatWidgetEntry = {};
export function useChatWidgetState(workspaceId: string, opts: UseChatWidgetStateOptions = {}) {
const { defaultAutonomy = 'normal' } = opts;
const chats = useSyncExternalStore(subscribeChatState, loadChatEntries);
const entry = chats[workspaceId] ?? EMPTY_ENTRY;
// P4 inheritance for a workspace that has never carried an autonomy level
// (option doc above). The gate is autonomy-specific, NOT entry-existence:
// a persona-only entry (PersonaSwitcher can write one for a never-visited
// workspace, AppShell §1.2) must not count as "seen" and permanently skip
// inheritance — migrated chats carry an explicit 'normal' marker instead
// (§3.3). defaultAutonomy is in the deps because ShellContext fetches it
// asynchronously (getPermissions): a widget mounted before the fetch
// resolves (deep-link boot) receives the stamp when the elevated value
// arrives; the autonomy-exists guard keeps that late stamp from overriding
// migrated or user-set state.
useEffect(() => {
if (defaultAutonomy === 'normal') return;
if (loadChatEntries()[workspaceId]?.autonomyLevel !== undefined) return;
writeChatEntry(workspaceId, { autonomyLevel: defaultAutonomy, autonomyExpiresAt: null });
}, [workspaceId, defaultAutonomy]);
/**
* Phase A.2 (relocated verbatim from setWindowPersona,
* useWindowManager.ts:316-320, re-keyed instanceId → workspaceId): update
* the persona on this widget without touching the underlying workspace
* record. Used by PersonaSwitcher and ChatWindowInstance's inline picker.
*/
const setPersona = useCallback((personaId: string) => {
writeChatEntry(workspaceId, { personaId, personaLabel: personaLabelFor(personaId) });
}, [workspaceId]);
/**
* Phase B.5 (relocated verbatim from setWindowAutonomy,
* useWindowManager.ts:327-338): elevated levels (trusted / yolo)
* auto-revert to 'normal' after `ttlMinutes` unless ttlMinutes is null.
*/
const setAutonomy = useCallback((
level: AutonomyLevel,
ttlMinutes: number | null = 30,
) => {
const expiresAt = level === 'normal' || ttlMinutes === null
? null
: Date.now() + ttlMinutes * 60_000;
writeChatEntry(workspaceId, { autonomyLevel: level, autonomyExpiresAt: expiresAt });
}, [workspaceId]);
// Phase B.5 (relocated from useWindowManager.ts:340-361): auto-revert
// expired autonomy grants. Runs every 10 seconds so the elevated banner in
// ChatApp's header always reflects reality.
useEffect(() => {
const interval = setInterval(() => {
const now = Date.now();
const e = loadChatEntries()[workspaceId];
if (
e?.autonomyLevel && e.autonomyLevel !== 'normal'
&& e.autonomyExpiresAt && e.autonomyExpiresAt < now
) {
writeChatEntry(workspaceId, { autonomyLevel: 'normal', autonomyExpiresAt: null });
}
}, 10_000);
return () => clearInterval(interval);
}, [workspaceId]);
return { entry, setPersona, setAutonomy };
}

View File

@@ -0,0 +1,34 @@
/**
* Reports the content-box width of a DOM element via ResizeObserver.
*
* Returns `null` until the first observation fires so consumers can
* distinguish "not measured yet" from "0 px wide" and avoid layout
* thrash on mount.
*/
import { useEffect, useState, type RefObject } from 'react';
export function useContainerWidth<T extends HTMLElement>(ref: RefObject<T>): number | null {
const [width, setWidth] = useState<number | null>(null);
useEffect(() => {
const element = ref.current;
if (!element) return;
if (typeof ResizeObserver === 'undefined') {
// Fallback for non-browser / SSR contexts — measure once on mount.
setWidth(element.clientWidth);
return;
}
const ro = new ResizeObserver(entries => {
for (const entry of entries) {
setWidth(entry.contentRect.width);
}
});
ro.observe(element);
// Seed with the current width so consumers see a value on the next
// render rather than waiting for the first resize event.
setWidth(element.clientWidth);
return () => ro.disconnect();
}, [ref]);
return width;
}

View File

@@ -0,0 +1,71 @@
/**
* M-20 / UX-5 — Developer mode storage contract regression.
*
* The React hook is a thin wrapper around three stable pieces we can
* exercise without booting React:
* 1. `readDeveloperMode()` — pure snapshot reader.
* 2. localStorage key contract — `waggle:developer-mode` ← "true" | absent.
* 3. Cross-component sync — `waggle:developer-mode-change` custom event
* fires on every writer path.
*
* (Full render-level hook behaviour is covered by the forthcoming
* Playwright E2E; @testing-library/react 16 ships for React 19 while
* this app is on React 18.3, so `renderHook` mixes React copies.)
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
import {
readDeveloperMode,
DEVELOPER_MODE_STORAGE_KEY,
} from './useDeveloperMode';
describe('developer mode storage contract', () => {
beforeEach(() => {
window.localStorage.removeItem(DEVELOPER_MODE_STORAGE_KEY);
});
it('readDeveloperMode returns false when the key is absent', () => {
expect(readDeveloperMode()).toBe(false);
});
it('readDeveloperMode returns true when the key is literally "true"', () => {
window.localStorage.setItem(DEVELOPER_MODE_STORAGE_KEY, 'true');
expect(readDeveloperMode()).toBe(true);
});
it('readDeveloperMode returns false for any non-"true" value', () => {
// Defensive against stale data from a prior storage contract.
for (const value of ['1', 'yes', 'on', 'TRUE', ' true', '']) {
window.localStorage.setItem(DEVELOPER_MODE_STORAGE_KEY, value);
expect(readDeveloperMode(), `input: ${JSON.stringify(value)}`).toBe(false);
}
});
it('the storage key is the exact documented literal', () => {
// If this constant ever changes, a migration step must run first;
// pinning it here prevents a silent rename from wiping every
// user's preference.
expect(DEVELOPER_MODE_STORAGE_KEY).toBe('waggle:developer-mode');
});
});
describe('developer mode cross-component change event', () => {
const CHANGE_EVENT = 'waggle:developer-mode-change';
beforeEach(() => {
window.localStorage.removeItem(DEVELOPER_MODE_STORAGE_KEY);
});
it('a manually dispatched change event is observable in the same tab', () => {
// The hook relies on this event to notify other instances in the
// same tab (the `storage` event only fires in OTHER tabs). This
// test pins the channel name so a rename breaks loudly.
const listener = vi.fn();
window.addEventListener(CHANGE_EVENT, listener);
try {
window.dispatchEvent(new Event(CHANGE_EVENT));
expect(listener).toHaveBeenCalledTimes(1);
} finally {
window.removeEventListener(CHANGE_EVENT, listener);
}
});
});

View File

@@ -0,0 +1,54 @@
/**
* M-20 / UX-5 — Developer mode hook. Persisted in localStorage,
* cross-tab reactive via the `storage` event, and cross-component
* reactive within one tab via a custom event. Default off.
*
* When enabled, UI surfaces that would otherwise hide developer-only
* signal (token counts, cost, debug chips) can render. The canonical
* read site is `useDeveloperMode()` — no prop plumbing needed.
*/
import { useEffect, useState } from 'react';
export const DEVELOPER_MODE_STORAGE_KEY = 'waggle:developer-mode';
const CHANGE_EVENT = 'waggle:developer-mode-change';
/** Non-hook snapshot — safe to call from module scope. */
export function readDeveloperMode(): boolean {
try {
return window.localStorage.getItem(DEVELOPER_MODE_STORAGE_KEY) === 'true';
} catch {
return false;
}
}
function writeDeveloperMode(value: boolean): void {
try {
window.localStorage.setItem(DEVELOPER_MODE_STORAGE_KEY, String(value));
} catch {
// no-op — storage disabled / private mode
}
// Notify in-tab subscribers (the `storage` event only fires in OTHER
// tabs, not the one that made the write).
window.dispatchEvent(new Event(CHANGE_EVENT));
}
export function useDeveloperMode(): readonly [boolean, (value: boolean) => void] {
const [enabled, setEnabledState] = useState<boolean>(() => readDeveloperMode());
useEffect(() => {
const sync = () => setEnabledState(readDeveloperMode());
window.addEventListener('storage', sync);
window.addEventListener(CHANGE_EVENT, sync);
return () => {
window.removeEventListener('storage', sync);
window.removeEventListener(CHANGE_EVENT, sync);
};
}, []);
const set = (value: boolean) => {
writeDeveloperMode(value);
setEnabledState(value);
};
return [enabled, set] as const;
}

View File

@@ -0,0 +1,122 @@
/**
* Dock-label visibility hook (M-19 / UX-4). Owns the localStorage
* plumbing around the pure `shouldShowDockLabels` rule.
*
* Storage keys:
* - waggle:session-count — integer, incremented on each page load
* - waggle:first-launch-at — unix ms, first write wins
* - waggle:dock-labels — override: 'auto' | 'always' | 'never'
*
* The session counter increments exactly once per page load (mount of
* the hook). useRef guards against StrictMode double-effects in dev.
*/
import { useEffect, useRef, useState } from 'react';
import {
shouldShowDockLabels,
type DockLabelsMode,
} from '@/lib/dock-labels';
export const SESSION_COUNT_KEY = 'waggle:session-count';
export const FIRST_LAUNCH_KEY = 'waggle:first-launch-at';
export const DOCK_LABELS_MODE_KEY = 'waggle:dock-labels';
const MODE_CHANGE_EVENT = 'waggle:dock-labels-change';
function readSessionCount(): number {
try {
const raw = window.localStorage.getItem(SESSION_COUNT_KEY);
const n = raw ? parseInt(raw, 10) : 0;
return Number.isFinite(n) && n >= 0 ? n : 0;
} catch {
return 0;
}
}
function readFirstLaunch(): number | null {
try {
const raw = window.localStorage.getItem(FIRST_LAUNCH_KEY);
if (!raw) return null;
const n = parseInt(raw, 10);
return Number.isFinite(n) ? n : null;
} catch {
return null;
}
}
export function readDockLabelsMode(): DockLabelsMode {
try {
const raw = window.localStorage.getItem(DOCK_LABELS_MODE_KEY);
if (raw === 'always' || raw === 'never' || raw === 'auto') return raw;
return 'auto';
} catch {
return 'auto';
}
}
function writeDockLabelsMode(mode: DockLabelsMode): void {
try {
window.localStorage.setItem(DOCK_LABELS_MODE_KEY, mode);
} catch {
// no-op
}
window.dispatchEvent(new Event(MODE_CHANGE_EVENT));
}
/**
* Increments session counter + seeds first-launch timestamp exactly
* once per mount. Separated from the visibility read so tests can
* exercise each side independently.
*
* Exported since the P1a AppShell conversion: the Dock (which mounted
* useDockLabels once per page load) is retired, so AppShell calls this
* directly to keep the per-session counter — the data source for the
* M-24/ENG-3 nudges — ticking.
*/
export function useBumpSessionCount(): void {
const bumpedRef = useRef(false);
useEffect(() => {
if (bumpedRef.current) return;
bumpedRef.current = true;
try {
const next = readSessionCount() + 1;
window.localStorage.setItem(SESSION_COUNT_KEY, String(next));
if (window.localStorage.getItem(FIRST_LAUNCH_KEY) === null) {
window.localStorage.setItem(FIRST_LAUNCH_KEY, String(Date.now()));
}
} catch {
// no-op
}
}, []);
}
export function useDockLabels(): {
visible: boolean;
mode: DockLabelsMode;
setMode: (mode: DockLabelsMode) => void;
} {
useBumpSessionCount();
const [mode, setModeState] = useState<DockLabelsMode>(() => readDockLabelsMode());
useEffect(() => {
const sync = () => setModeState(readDockLabelsMode());
window.addEventListener('storage', sync);
window.addEventListener(MODE_CHANGE_EVENT, sync);
return () => {
window.removeEventListener('storage', sync);
window.removeEventListener(MODE_CHANGE_EVENT, sync);
};
}, []);
const visible = shouldShowDockLabels({
sessionCount: readSessionCount(),
firstLaunchAt: readFirstLaunch(),
now: Date.now(),
mode,
});
const setMode = (next: DockLabelsMode) => {
writeDockLabelsMode(next);
setModeState(next);
};
return { visible, mode, setMode };
}

View File

@@ -0,0 +1,81 @@
/**
* Dock unlock nudge driver (M-24 / ENG-3).
*
* Reads the session counter written by useDockLabels, plus a
* persisted list of dismissed milestones, and fires the user-supplied
* `onNudge` callback exactly once per page load with the pending
* milestone. Guards against StrictMode double-effects via a ref.
*/
import { useEffect, useRef } from 'react';
import {
copyForMilestone,
findPendingMilestone,
type DockNudgeCopy,
} from '@/lib/dock-nudge';
import { SESSION_COUNT_KEY } from './useDockLabels';
export const DOCK_NUDGE_DISMISSED_KEY = 'waggle:dock-nudge-dismissed';
function readSessionCount(): number {
try {
const raw = window.localStorage.getItem(SESSION_COUNT_KEY);
const n = raw ? parseInt(raw, 10) : 0;
return Number.isFinite(n) && n >= 0 ? n : 0;
} catch {
return 0;
}
}
export function readDismissedMilestones(): number[] {
try {
const raw = window.localStorage.getItem(DOCK_NUDGE_DISMISSED_KEY);
if (!raw) return [];
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
return parsed.filter((n: unknown): n is number => typeof n === 'number' && Number.isFinite(n));
} catch {
return [];
}
}
function writeDismissedMilestones(milestones: readonly number[]): void {
try {
window.localStorage.setItem(DOCK_NUDGE_DISMISSED_KEY, JSON.stringify([...milestones]));
} catch {
// no-op
}
}
export interface UseDockNudgeOptions {
/**
* Called when a pending milestone is found. Receives the milestone
* number and the copy to render. The callback is expected to show a
* toast (or similar) and return a function that marks the milestone
* as dismissed when the user closes the toast. If no teardown is
* needed, the milestone is marked dismissed immediately after the
* callback returns (so the nudge doesn't re-fire on next mount).
*/
onNudge: (milestone: number, copy: DockNudgeCopy) => void;
}
export function useDockNudge({ onNudge }: UseDockNudgeOptions): void {
const firedRef = useRef(false);
useEffect(() => {
if (firedRef.current) return;
firedRef.current = true;
const sessionCount = readSessionCount();
const dismissed = readDismissedMilestones();
const milestone = findPendingMilestone(sessionCount, dismissed);
if (milestone == null) return;
onNudge(milestone, copyForMilestone(milestone));
// Mark dismissed immediately — we don't want the same milestone to
// reappear across page reloads. If we later want "dismiss on user
// action" semantics instead, gate on a user-supplied callback.
if (!dismissed.includes(milestone)) {
writeDismissedMilestones([...dismissed, milestone]);
}
}, [onNudge]);
}

View File

@@ -0,0 +1,36 @@
import { useState, useEffect, useCallback } from 'react';
import { adapter } from '@/lib/adapter';
import type { AgentStep } from '@/lib/types';
export const useEvents = (workspaceId: string | null) => {
const [steps, setSteps] = useState<AgentStep[]>([]);
const [autoScroll, setAutoScroll] = useState(true);
const [filter, setFilter] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!workspaceId) {
setSteps([]);
setError(null);
return;
}
adapter.getEvents(workspaceId)
.then((data) => { setSteps(data); setError(null); })
.catch((err) => { console.error('[useEvents] fetch failed:', err); setSteps([]); setError(err instanceof Error ? err.message : 'Failed to load'); });
let unsub: (() => void) | undefined;
try {
unsub = adapter.subscribeEvents((step) => {
setSteps(prev => [...prev, step]);
});
} catch (err) { console.error('[useEvents] SSE subscribe failed:', err); }
return () => unsub?.();
}, [workspaceId]);
const filteredSteps = filter ? steps.filter(s => s.type === filter) : steps;
const toggleAutoScroll = useCallback(() => setAutoScroll(p => !p), []);
return { steps: filteredSteps, autoScroll, toggleAutoScroll, filter, setFilter, error };
};

View File

@@ -0,0 +1,64 @@
/**
* useFocusTrap — WCAG 2.1.1 / 2.4.3 modal focus management.
*
* Drives the hook through a minimal dialog component and asserts the four
* behaviors: focus-in on open, Escape callback, Tab/Shift+Tab cycling, and
* focus restore on unmount.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, fireEvent, cleanup } from '@testing-library/react';
import { useFocusTrap } from './useFocusTrap';
afterEach(cleanup);
function Dialog({ onEscape }: { onEscape?: () => void }) {
const ref = useFocusTrap<HTMLDivElement>(true, onEscape);
return (
<div ref={ref} role="dialog" aria-modal="true" tabIndex={-1} data-testid="dialog">
<button data-testid="first">First</button>
<button data-testid="middle">Middle</button>
<button data-testid="last">Last</button>
</div>
);
}
describe('useFocusTrap', () => {
it('moves focus into the dialog on open', () => {
const { getByTestId } = render(<Dialog />);
expect(document.activeElement).toBe(getByTestId('dialog'));
});
it('invokes onEscape when Escape is pressed', () => {
const onEscape = vi.fn();
const { getByTestId } = render(<Dialog onEscape={onEscape} />);
fireEvent.keyDown(getByTestId('dialog'), { key: 'Escape' });
expect(onEscape).toHaveBeenCalledTimes(1);
});
it('Tab from the last element wraps to the first (forward trap)', () => {
const { getByTestId } = render(<Dialog />);
getByTestId('last').focus();
fireEvent.keyDown(getByTestId('dialog'), { key: 'Tab' });
expect(document.activeElement).toBe(getByTestId('first'));
});
it('Shift+Tab from the first element wraps to the last (backward trap)', () => {
const { getByTestId } = render(<Dialog />);
getByTestId('first').focus();
fireEvent.keyDown(getByTestId('dialog'), { key: 'Tab', shiftKey: true });
expect(document.activeElement).toBe(getByTestId('last'));
});
it('restores focus to the previously-focused element on close', () => {
const opener = document.createElement('button');
document.body.appendChild(opener);
opener.focus();
expect(document.activeElement).toBe(opener);
const { unmount } = render(<Dialog />);
unmount();
expect(document.activeElement).toBe(opener);
document.body.removeChild(opener);
});
});

View File

@@ -0,0 +1,117 @@
import { useEffect, useRef } from 'react';
/**
* useFocusTrap — WCAG 2.1.1 / 2.4.3 modal focus management.
*
* When `active` is true, on the returned container ref:
* - moves focus into the dialog on open (the container itself if it is
* focusable, else its first tabbable descendant);
* - traps Tab / Shift+Tab so focus cycles within the dialog instead of
* escaping to the page behind it;
* - invokes `onEscape` on the Escape key;
* - restores focus to the previously-focused element on close.
*
* Single source of focus-trap correctness shared by all modal overlays so the
* behavior is implemented (and fixed) once.
*/
const TABBABLE = [
'a[href]',
'button:not([disabled])',
'textarea:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
].join(',');
export function useFocusTrap<T extends HTMLElement = HTMLDivElement>(
active: boolean,
onEscape?: () => void,
) {
const containerRef = useRef<T | null>(null);
// Hold the escape callback in a ref so its identity is NOT an effect dep:
// consumers pass inline closures, and re-running the trap on every parent
// re-render (e.g. a toast anywhere in the app) tears it down (cleanup
// refocuses the opener behind the backdrop) and re-runs it (setup refocuses
// the first tabbable) — stealing focus from whatever field the user was
// typing in. Phase-3C review finding, empirically reproduced.
const onEscapeRef = useRef(onEscape);
onEscapeRef.current = onEscape;
useEffect(() => {
if (!active) return;
const container = containerRef.current;
if (!container) return;
const previouslyFocused = document.activeElement as HTMLElement | null;
const isHidden = (el: HTMLElement): boolean => {
// Skip elements explicitly hidden. Avoid offsetParent (always null in
// jsdom, and null for position:fixed in real browsers) — use the
// hidden attribute + aria-hidden, which is reliable in both.
if (el.hasAttribute('hidden') || el.getAttribute('aria-hidden') === 'true') return true;
return el.closest('[hidden],[aria-hidden="true"]') !== null && el !== document.activeElement;
};
const tabbables = (): HTMLElement[] =>
Array.from(container.querySelectorAll<HTMLElement>(TABBABLE)).filter(el => !isHidden(el));
// Move focus inside — unless it is ALREADY inside (e.g. an autoFocus
// field that React committed before this effect ran; without this guard
// the trap would immediately steal focus to the first tabbable, which in
// the builder shells is the header Close button).
if (!container.contains(document.activeElement)) {
// Prefer the dialog container itself when it is focusable (tabIndex
// set, incl. the conventional -1 for programmatic focus) so screen
// readers announce the dialog and Escape is heard even with no
// focusable children; otherwise focus the first tabbable child.
const first = tabbables()[0];
if (typeof container.focus === 'function' && container.hasAttribute('tabindex')) {
container.focus();
} else if (first) {
first.focus();
} else {
container.tabIndex = -1;
container.focus();
}
}
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
onEscapeRef.current?.();
return;
}
if (e.key !== 'Tab') return;
const items = tabbables();
if (items.length === 0) {
e.preventDefault();
return;
}
const firstEl = items[0];
const lastEl = items[items.length - 1];
const current = document.activeElement;
if (e.shiftKey) {
if (current === firstEl || !container.contains(current)) {
e.preventDefault();
lastEl.focus();
}
} else {
if (current === lastEl || !container.contains(current)) {
e.preventDefault();
firstEl.focus();
}
}
};
container.addEventListener('keydown', onKeyDown);
return () => {
container.removeEventListener('keydown', onKeyDown);
// Restore focus to where it was before the modal opened.
if (previouslyFocused && typeof previouslyFocused.focus === 'function') {
previouslyFocused.focus();
}
};
}, [active]);
return containerRef;
}

View File

@@ -0,0 +1,77 @@
/**
* PR5 Phase A — the shared "≥1 working model" gate signal (cloud key OR local
* model), composed from the same /api/providers data the Settings Models tab
* reads.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, waitFor, cleanup } from '@testing-library/react';
const mocks = vi.hoisted(() => ({
adapter: {
getProviders: vi.fn(),
getLocalInferenceStatus: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import { useHasWorkingModel } from './useHasWorkingModel';
const providers = (...withKey: boolean[]) => ({
providers: withKey.map((hasKey, i) => ({ id: `p${i}`, name: `P${i}`, hasKey, badge: null, keyUrl: null, requiresKey: true, models: [] })),
search: [],
activeSearch: 'duckduckgo',
});
const providerRows = (...rows: Array<{ id: string; hasKey: boolean; requiresKey: boolean }>) => ({
providers: rows.map((row) => ({ ...row, name: row.id, badge: null, keyUrl: null, models: [] })),
search: [],
activeSearch: 'duckduckgo',
});
beforeEach(() => {
mocks.adapter.getProviders.mockResolvedValue(providers());
mocks.adapter.getLocalInferenceStatus.mockResolvedValue({ servers: [], ollamaInstalled: false, totalLocalModels: 0 });
});
afterEach(() => { cleanup(); vi.clearAllMocks(); });
describe('useHasWorkingModel', () => {
it('no key and no local model → not ready', async () => {
const { result } = renderHook(() => useHasWorkingModel());
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current).toMatchObject({ hasWorkingModel: false, cloudReady: false, localReady: false });
});
it('a keyed cloud provider → cloudReady → working', async () => {
mocks.adapter.getProviders.mockResolvedValue(providers(false, true));
const { result } = renderHook(() => useHasWorkingModel());
await waitFor(() => expect(result.current.hasWorkingModel).toBe(true));
expect(result.current.cloudReady).toBe(true);
expect(result.current.localReady).toBe(false);
});
it('a detected local model (no cloud key) → localReady → working', async () => {
mocks.adapter.getLocalInferenceStatus.mockResolvedValue({ servers: [], ollamaInstalled: true, totalLocalModels: 2 });
const { result } = renderHook(() => useHasWorkingModel());
await waitFor(() => expect(result.current.hasWorkingModel).toBe(true));
expect(result.current.cloudReady).toBe(false);
expect(result.current.localReady).toBe(true);
});
it('does not count keyless local providers as cloud keys', async () => {
mocks.adapter.getProviders.mockResolvedValue(providerRows({ id: 'ollama', hasKey: true, requiresKey: false }));
mocks.adapter.getLocalInferenceStatus.mockResolvedValue({ servers: [], ollamaInstalled: true, totalLocalModels: 2 });
const { result } = renderHook(() => useHasWorkingModel());
await waitFor(() => expect(result.current.hasWorkingModel).toBe(true));
expect(result.current.cloudReady).toBe(false);
expect(result.current.localReady).toBe(true);
});
it('a local-inference probe failure degrades to no-local (cloud can still pass)', async () => {
mocks.adapter.getLocalInferenceStatus.mockRejectedValue(new Error('ollama down'));
mocks.adapter.getProviders.mockResolvedValue(providers(true));
const { result } = renderHook(() => useHasWorkingModel());
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.localReady).toBe(false);
expect(result.current.hasWorkingModel).toBe(true); // cloud key carries it
});
});

View File

@@ -0,0 +1,59 @@
import { useCallback, useEffect, useState } from 'react';
import { adapter } from '@/lib/adapter';
import { useProviders } from './useProviders';
/**
* useHasWorkingModel — the shared "≥1 working model" signal for the PR5 model
* gate (Onboarding step 3's HARD gate AND the Settings→Models banner). A model
* is "working" if either a cloud provider has a key configured OR a local model
* is detected. This is a UX affordance, not a security boundary — the real
* LLM-availability enforcement happens server-side at chat time — so it derives
* from already-fetched data (no live key-probe required to compute readiness).
*
* Composing useProviders keeps a single source of truth (the same /api/providers
* hasKey data the Settings Models tab reads), so the gate and the banner can
* never disagree about what counts as ready.
*/
export interface WorkingModelState {
/** cloudReady || localReady — the hard-gate predicate. */
hasWorkingModel: boolean;
/** ≥1 cloud provider has a key in the vault. */
cloudReady: boolean;
/** ≥1 local model detected (Ollama/vLLM). */
localReady: boolean;
loading: boolean;
refresh: () => void;
}
export function useHasWorkingModel(): WorkingModelState {
const { activeProviders, loading: providersLoading, refresh: refreshProviders } = useProviders();
const [localModelCount, setLocalModelCount] = useState(0);
const [localLoading, setLocalLoading] = useState(true);
const refreshLocal = useCallback(async () => {
setLocalLoading(true);
try {
const status = await adapter.getLocalInferenceStatus();
setLocalModelCount(status?.totalLocalModels ?? 0);
} catch {
// Local-inference probe failed (Ollama not installed / unreachable) —
// treat as "no local model"; a cloud key can still make the gate pass.
setLocalModelCount(0);
} finally {
setLocalLoading(false);
}
}, []);
useEffect(() => { void refreshLocal(); }, [refreshLocal]);
const cloudReady = activeProviders.length > 0;
const localReady = localModelCount > 0;
return {
hasWorkingModel: cloudReady || localReady,
cloudReady,
localReady,
loading: providersLoading || localLoading,
refresh: () => { refreshProviders(); void refreshLocal(); },
};
}

View File

@@ -0,0 +1,32 @@
import { useEffect, useState } from 'react';
/**
* Subscribe to the live `data-theme` attribute on <html>. Returns `true` when
* the user is in light mode, `false` in dark. Updates reactively when the
* theme toggles elsewhere in the app.
*
* Single source of truth: `document.documentElement.getAttribute('data-theme')`.
* Dark is the implicit default (no attribute set).
*/
export function useIsLightTheme(): boolean {
const read = () =>
typeof document !== 'undefined' &&
document.documentElement.getAttribute('data-theme') === 'light';
const [isLight, setIsLight] = useState<boolean>(read);
useEffect(() => {
if (typeof document === 'undefined') return;
const sync = () => setIsLight(read());
const observer = new MutationObserver(sync);
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ['data-theme'],
});
// Catch any change that slipped in between initial read and observer attach.
sync();
return () => observer.disconnect();
}, []);
return isLight;
}

View File

@@ -0,0 +1,140 @@
import { useEffect, useRef } from 'react';
import type { AppId } from '@/lib/dock-tiers';
interface UseKeyboardShortcutsOptions {
onOpenApp: (id: AppId) => void;
onToggleGlobalSearch: () => void;
onTogglePersonaSwitcher: () => void;
onToggleWorkspaceSwitcher: () => void;
onToggleKeyboardHelp: () => void;
/**
* Phase A.3 — originally "new chat window on the active workspace"; since
* the P1a AppShell conversion (§4.2) this navigates to the active
* workspace's chat tab instead (Ctrl+W / Ctrl+Shift+M window handlers
* retired with the window manager, plan §3.1).
*/
onNewChatWindow?: () => void;
}
const APP_SHORTCUTS: Record<string, AppId> = {
'0': 'dashboard',
'1': 'chat',
'2': 'agents',
'3': 'files',
'4': 'cockpit',
'5': 'memory',
'6': 'events',
'7': 'settings',
'8': 'capabilities',
'9': 'waggle-dance',
};
/** Shortcuts that work even when an input/textarea is focused */
function isGlobalShortcut(e: KeyboardEvent): boolean {
const ctrl = e.ctrlKey || e.metaKey;
return (
(ctrl && e.key === 'k')
|| (ctrl && e.shiftKey && (e.key === 'N' || e.key === 'n'))
// Pillar 2.7: "open last workspace" is a from-anywhere power path, so it
// survives an input focus (parity with new-chat above).
|| (ctrl && e.shiftKey && (e.key === 'O' || e.key === 'o'))
|| e.key === 'Escape'
);
}
function isInputFocused(): boolean {
const active = document.activeElement;
if (!active) return false;
const tag = active.tagName.toLowerCase();
return tag === 'input' || tag === 'textarea' || (active as HTMLElement).isContentEditable;
}
export const useKeyboardShortcuts = (options: UseKeyboardShortcutsOptions) => {
// Store callbacks in refs so the event listener never re-registers
const optsRef = useRef(options);
optsRef.current = options;
useEffect(() => {
const handler = (e: KeyboardEvent) => {
const ctrl = e.ctrlKey || e.metaKey;
const opts = optsRef.current;
// Skip non-global shortcuts when typing in an input
if (isInputFocused() && !isGlobalShortcut(e)) return;
// Ctrl+Shift+R: Open the Room (Phase A.3 — sub-agent visibility canvas)
if (ctrl && e.shiftKey && (e.key === 'R' || e.key === 'r')) {
e.preventDefault();
opts.onOpenApp('room');
return;
}
// Ctrl+Shift+N: Open chat on the active workspace.
// Matches the cornerstone's Phase A.3 acceptance test flow:
// "Cmd+Shift+N → pick Researcher → ..."
if (ctrl && e.shiftKey && (e.key === 'N' || e.key === 'n')) {
e.preventDefault();
opts.onNewChatWindow?.();
return;
}
// Ctrl+Shift+O: Open the last / active workspace's desktop from anywhere
// (Pillar 2.7 ≤2-keystroke power path). onOpenApp('workspace-desktop')
// resolves through routeFor, which lands the persisted active workspace
// (or Home when nothing is selected — Home IS the workspace selector).
if (ctrl && e.shiftKey && (e.key === 'O' || e.key === 'o')) {
e.preventDefault();
opts.onOpenApp('workspace-desktop');
return;
}
// Ctrl+Shift+0-9: Open apps
if (ctrl && e.shiftKey && APP_SHORTCUTS[e.key]) {
e.preventDefault();
opts.onOpenApp(APP_SHORTCUTS[e.key]);
return;
}
// Ctrl+K: Global search
if (ctrl && e.key === 'k') {
e.preventDefault();
opts.onToggleGlobalSearch();
return;
}
// Ctrl+Shift+P: Persona switcher
if (ctrl && e.shiftKey && e.key === 'P') {
e.preventDefault();
opts.onTogglePersonaSwitcher();
return;
}
// Ctrl+Tab: Workspace switcher
if (ctrl && e.key === 'Tab') {
e.preventDefault();
opts.onToggleWorkspaceSwitcher();
return;
}
// Ctrl+/ or Ctrl+?: Keyboard help. Browsers/OS layouts disagree on the
// reported key for the shifted slash shortcut, so accept both forms.
if (ctrl && (e.key === '?' || e.key === '/')) {
e.preventDefault();
opts.onToggleKeyboardHelp();
return;
}
// `?` (no modifier): the conventional "press ? for help" discoverability
// path (Pillar 2.7 cheat-sheet). The input-focus early return above keeps
// it from ever hijacking a literal "?" typed into a field.
if (!ctrl && e.key === '?') {
e.preventDefault();
opts.onToggleKeyboardHelp();
return;
}
};
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, []); // Empty deps — handler is stable via ref
};

View File

@@ -0,0 +1,38 @@
import { useState, useCallback, useEffect } from 'react';
import { adapter } from '@/lib/adapter';
import type { KGNode, KGEdge } from '@/lib/types';
export type KGScope = 'current' | 'personal' | 'all';
export const useKnowledgeGraph = (workspaceId: string | null) => {
const [nodes, setNodes] = useState<KGNode[]>([]);
const [edges, setEdges] = useState<KGEdge[]>([]);
const [loading, setLoading] = useState(false);
const [selectedNode, setSelectedNode] = useState<KGNode | null>(null);
const [error, setError] = useState<string | null>(null);
const [scope, setScope] = useState<KGScope>('current');
const fetchKG = useCallback(async () => {
// W2D: with no real workspace, 'current' has nothing to point at — used to
// silently return (a permanently empty graph). Fall back to the Personal
// mind and reflect that in the scope select so the UI tells the truth.
const noRealWorkspace = !workspaceId || workspaceId === 'local-default';
if (noRealWorkspace && scope === 'current') {
setScope('personal');
return;
}
setLoading(true);
try {
const data = await adapter.getKnowledgeGraph(workspaceId ?? '', scope);
setNodes(data.nodes);
setEdges(data.edges);
setError(null);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load');
} finally { setLoading(false); }
}, [workspaceId, scope]);
useEffect(() => { fetchKG(); }, [fetchKG]);
return { nodes, edges, loading, error, selectedNode, setSelectedNode, scope, setScope, refresh: fetchKG };
};

View File

@@ -0,0 +1,84 @@
import { useState, useCallback, useEffect } from 'react';
import { adapter } from '@/lib/adapter';
import type { MemoryFrame } from '@/lib/types';
interface MemoryFilters {
types: string[];
minImportance: number;
searchQuery: string;
}
export const useMemory = (workspaceId: string | null) => {
const [frames, setFrames] = useState<MemoryFrame[]>([]);
const [selectedFrame, setSelectedFrame] = useState<MemoryFrame | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [filters, setFilters] = useState<MemoryFilters>({ types: [], minImportance: 0, searchQuery: '' });
const [entityCount, setEntityCount] = useState(0);
const [relationCount, setRelationCount] = useState(0);
const fetchFrames = useCallback(async () => {
if (!workspaceId) return;
setLoading(true);
try {
const data = filters.searchQuery
? await adapter.searchMemory(filters.searchQuery, workspaceId)
: await adapter.getMemoryFrames(workspaceId);
setFrames(data);
setError(null);
// W2D: scope entity/relation counts to THIS workspace so the Timeline
// header is one scope (frames are already per-workspace). Previously read
// the all-minds `total`, so "50 of 50 frames · 617 entities · 9420
// relations" mixed per-workspace frames with global entities/relations.
adapter.getMemoryStats(workspaceId).then(s => {
setEntityCount(s.workspace.entities);
setRelationCount(s.workspace.relations);
}).catch(() => {});
} catch (e) {
console.error('[useMemory] fetch failed:', e);
setError(e instanceof Error ? e.message : 'Failed to load');
} finally {
setLoading(false);
}
}, [workspaceId, filters.searchQuery]);
useEffect(() => { fetchFrames(); }, [fetchFrames]);
const addFrame = useCallback(async (frame: Omit<MemoryFrame, 'id'>) => {
const created = await adapter.addMemoryFrame(frame);
setFrames(prev => [created, ...prev]);
}, []);
const editFrame = useCallback(async (id: string, data: Partial<MemoryFrame>) => {
const updated = await adapter.updateMemoryFrame(id, data);
setFrames(prev => prev.map(f => f.id === id ? updated : f));
}, []);
const incrementAccess = useCallback(async (id: string) => {
try {
const { accessCount } = await adapter.incrementFrameAccess(id, workspaceId ?? undefined);
setFrames(prev => prev.map(f => f.id === id ? { ...f, metadata: { ...f.metadata, accessCount } } : f));
} catch (err) {
console.error('[useMemory] incrementAccess failed:', err);
}
}, [workspaceId]);
const deleteFrame = useCallback(async (id: string) => {
await adapter.deleteMemoryFrame(id);
setFrames(prev => prev.filter(f => f.id !== id));
if (selectedFrame?.id === id) setSelectedFrame(null);
}, [selectedFrame]);
const filteredFrames = frames.filter(f => {
if (filters.types.length && !filters.types.includes(f.type)) return false;
if (f.importance < filters.minImportance) return false;
return true;
});
return {
frames: filteredFrames, selectedFrame, setSelectedFrame,
loading, error, filters, setFilters,
addFrame, editFrame, deleteFrame, incrementAccess, refresh: fetchFrames,
stats: { total: frames.length, filtered: filteredFrames.length, entities: entityCount, relations: relationCount },
};
};

View File

@@ -0,0 +1,45 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
import { adapter } from '@/lib/adapter';
import type { Notification } from '@/lib/types';
export const useNotifications = () => {
const [notifications, setNotifications] = useState<Notification[]>([]);
useEffect(() => {
adapter.getNotificationHistory()
.then(data => {
setNotifications(data);
})
.catch((err) => {
console.error('[useNotifications] fetch failed:', err);
setNotifications([]);
});
let unsub: (() => void) | undefined;
try {
unsub = adapter.subscribeNotifications((n: Notification) => {
setNotifications(prev => [n, ...prev]);
});
} catch (err) { console.error('[useNotifications] SSE subscribe failed:', err); }
return () => unsub?.();
}, []);
// W4C/F25: derive the badge count from the list instead of tracking it as a
// second independent state. This makes "badge count === visible unread count"
// a structural invariant — the old 4-call-site manual sync could drift (e.g.
// an optimistic markRead on a live SSE notification with no server id).
const unreadCount = useMemo(() => notifications.filter(n => !n.read).length, [notifications]);
const markRead = useCallback(async (id: string) => {
try { await adapter.markNotificationRead(id); } catch (err) { console.error('[useNotifications] mark read failed:', err); }
setNotifications(prev => prev.map(n => n.id === id ? { ...n, read: true } : n));
}, []);
const markAllRead = useCallback(async () => {
try { await adapter.markAllNotificationsRead(); } catch (err) { console.error('[useNotifications] mark all read failed:', err); }
setNotifications(prev => prev.map(n => ({ ...n, read: true })));
}, []);
return { notifications, unreadCount, markRead, markAllRead };
};

View File

@@ -0,0 +1,100 @@
import { useState, useEffect, useRef } from 'react';
import { adapter } from '@/lib/adapter';
/**
* Tracks whether the backend health endpoint is reachable.
*
* FR #17 hardening (initial):
* - Tolerance: requires 2 consecutive failures before flipping `offline = true`,
* so a single transient timeout (heavy operation, momentary network blip)
* does not surface the Offline pill.
* - Cap max backoff at 60s (was 5min) so recovery is detected within a minute
* instead of leaving the pill stale long after the backend is healthy again.
* - Event-driven re-checks: a fresh probe runs on `window.online` and on tab
* `visibilitychange` → 'visible'. After reconnecting WiFi or refocusing the
* tab, the pill clears within one HTTP roundtrip rather than waiting for the
* next scheduled tick.
*
* FR #17 follow-up (this iteration):
* - Drop exponential after the flip. Once we're in the offline state, poll
* every RECOVERY_INTERVAL_MS (15s) regardless of how many consecutive misses
* came before. The exponential ramp made sense BEFORE the pill flipped (avoid
* spamming a server we just hit), but AFTER it flipped we want fast recovery
* detection — sustained outage means a cheap idempotent /health hit every
* 15s, well under any rate limit.
* - Add a `window.focus` listener as a third re-check trigger. `visibilitychange`
* only fires when the tab itself was hidden; `focus` fires whenever the
* browser window/tab regains focus (e.g., user clicks back from a different
* app). Caught the case PM hit where the tab stayed visible the whole time
* and recovery was delayed.
*/
const FAILURE_TOLERANCE = 2;
const BASE_INTERVAL_MS = 15_000;
const MAX_INTERVAL_MS = 60_000;
const RECOVERY_INTERVAL_MS = 15_000;
export const useOfflineStatus = () => {
const [offline, setOffline] = useState(false);
const failCount = useRef(0);
useEffect(() => {
let cancelled = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const check = async () => {
try {
await adapter.getSystemHealth();
if (cancelled) return;
setOffline(false);
failCount.current = 0;
} catch (err) {
if (cancelled) return;
console.error('[useOfflineStatus] health check failed:', err);
failCount.current++;
if (failCount.current >= FAILURE_TOLERANCE) {
setOffline(true);
}
}
};
const schedule = () => {
// Once flipped offline, poll fast for recovery (15s). Pre-flip we still
// ramp exponentially so a single bad blip doesn't pummel the server.
const interval = failCount.current >= FAILURE_TOLERANCE
? RECOVERY_INTERVAL_MS
: Math.min(BASE_INTERVAL_MS * Math.pow(2, failCount.current), MAX_INTERVAL_MS);
timer = setTimeout(async () => {
await check();
if (!cancelled) schedule();
}, interval);
};
// Kick an immediate probe so the recovery side of any event-triggered
// re-check observes the result quickly. Used by both initial mount and
// event handlers.
const probeNow = () => {
if (timer) clearTimeout(timer);
void check().then(() => { if (!cancelled) schedule(); });
};
probeNow();
const onOnline = () => probeNow();
const onVisible = () => { if (document.visibilityState === 'visible') probeNow(); };
const onFocus = () => probeNow();
window.addEventListener('online', onOnline);
document.addEventListener('visibilitychange', onVisible);
window.addEventListener('focus', onFocus);
return () => {
cancelled = true;
if (timer) clearTimeout(timer);
window.removeEventListener('online', onOnline);
document.removeEventListener('visibilitychange', onVisible);
window.removeEventListener('focus', onFocus);
};
}, []);
return offline;
};

View File

@@ -0,0 +1,334 @@
import { useState, useCallback, useEffect } from 'react';
import type { UserTier } from '@/lib/dock-tiers';
import { adapter } from '@/lib/adapter';
import { ONBOARDED_THIS_SESSION_KEY, COACH_MARKS_FORCE_KEY } from '@/lib/coach-marks-gate';
import {
isTauri,
isFirstLaunch as tauriIsFirstLaunch,
markFirstLaunchComplete as tauriMarkFirstLaunchComplete,
} from '@/lib/tauri-bindings';
export interface OnboardingState {
completed: boolean;
step: number;
tier?: UserTier;
workspaceId?: string;
apiKeySet?: boolean;
templateId?: string;
personaId?: string;
tooltipsDismissed?: boolean;
/** Epoch ms the wizard was completed via update() (F1/F5). Legacy/returning
* profiles that auto-complete leave this undefined on purpose. */
completedAt?: number;
// --- Phase 2D additive fields (localStorage only, back-compat) ---
/** Set once the Who-Are-You step has written profile + seeded identity (B8). */
profileSeeded?: boolean;
/** Tool/connector ids the user said they use (S14, deferred; reserved). */
toolsUsed?: string[];
}
const STORAGE_KEY = 'waggle:onboarding';
const defaultState: OnboardingState = {
completed: false,
step: 0,
};
// P2 fix (acceptance check 8 live-run): the ?forceWizard reset must fire ONCE
// per page load, not on every loadState() call. loadState() also runs in the
// 'waggle:onboarding-sync' listener — without this latch, every wizard save
// (e.g. workspace-create persisting workspaceId) triggered a sync reload that
// reset state to {completed:false, step:0} AND wiped the just-saved fields,
// so onFinish ran with a fallback local-* id and the seeding/navigation chain
// silently broke.
let forceWizardConsumed = false;
function forceWizardParamAllowed(): boolean {
return import.meta.env.DEV || import.meta.env.VITE_WAGGLE_E2E === '1';
}
function loadState(): OnboardingState {
try {
// E2E test bypass: ?skipOnboarding=true skips wizard and sets tier to 'power'
const params = new URLSearchParams(window.location.search);
if (params.get('skipOnboarding') === 'true') {
const tier = (params.get('tier') as UserTier) || 'power';
const done: OnboardingState = { ...defaultState, completed: true, step: 7, tier, tooltipsDismissed: true };
localStorage.setItem(STORAGE_KEY, JSON.stringify(done));
return done;
}
// PM walkthrough bypass (DEV/E2E only): ?forceWizard=true forces the wizard to
// render at step 0 regardless of localStorage state OR the auto-complete
// branch in this hook (which fires when /api/onboarding/status says a
// prior client completed the wizard against this dataDir — P4). Mirrors
// ?skipOnboarding=true above as the symmetric "always run" counterpart.
// Gated so a production deployment can't accidentally re-trigger onboarding
// for returning users via a stray URL.
if (forceWizardParamAllowed() && params.get('forceWizard') === 'true' && !forceWizardConsumed) {
forceWizardConsumed = true;
const fresh: OnboardingState = { ...defaultState, completed: false, step: 0 };
localStorage.setItem(STORAGE_KEY, JSON.stringify(fresh));
// FR #47: also clear the tour completion flag so the post-wizard Tour
// renders fresh after the wizard completes. Without this clear, a
// second walkthrough run would skip Tour because OnboardingTooltips
// reads localStorage independently of `tooltipsDismissed` in the
// onboarding state object. Symmetric reset for both surfaces.
localStorage.removeItem('waggle:tooltips_done');
return fresh;
}
// Migrate from old key
if (localStorage.getItem('waggle_onboarding_complete') === 'true') {
localStorage.removeItem('waggle_onboarding_complete');
const done: OnboardingState = { ...defaultState, completed: true, step: 7 };
localStorage.setItem(STORAGE_KEY, JSON.stringify(done));
return done;
}
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) {
const parsed = JSON.parse(raw);
const state = { ...defaultState, ...parsed };
// Existing completed users without a tier default to 'simple'
if (parsed.completed && !parsed.tier) {
state.tier = 'simple';
}
return state;
}
} catch { /* ignore */ }
return defaultState;
}
function saveState(state: OnboardingState) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
// Notify other hook instances in the same tab via custom event
window.dispatchEvent(new CustomEvent('waggle:onboarding-sync'));
}
/**
* Wave T Lane A (item 1): can we decide wizard-vs-shell WITHOUT the server?
* True when localStorage already settles it (completed, or mid-wizard step>0), or
* a DEV forceWizard / E2E skipOnboarding param forces the decision. False only
* for a fresh localStorage that must ask /api/onboarding/status — the exact case
* where the wizard flashes for ~1s before the async auto-complete lands. Reads
* raw localStorage with no side effects (does NOT consume the forceWizard latch),
* so AppShell can gate the boot screen on it.
*/
export function isOnboardingStatusKnownSync(): boolean {
try {
const params = new URLSearchParams(window.location.search);
if (params.get('skipOnboarding') === 'true') return true;
if (forceWizardParamAllowed() && params.get('forceWizard') === 'true') return true;
if (localStorage.getItem('waggle_onboarding_complete') === 'true') return true;
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) {
const parsed = JSON.parse(raw) as Partial<OnboardingState>;
if (parsed?.completed) return true;
if (typeof parsed?.step === 'number' && parsed.step > 0) return true;
}
return false;
} catch {
return false;
}
}
/**
* Wave T Lane A (item 1): resolve a fresh-localStorage user's onboarding against
* the server BEFORE the shell mounts, and persist the completed flag so
* useOnboarding reads it synchronously (the wizard never paints for a
* server-onboarded returning user). No-op when the decision is already known
* locally. The boot-time counterpart of the in-hook auto-complete effect below;
* never throws — a dead sidecar leaves the wizard in place for a truly new user.
*/
export async function resolveReturningUserOnboarding(): Promise<void> {
if (isOnboardingStatusKnownSync()) return;
try {
const status = await adapter.getOnboardingStatus();
if (status?.completed) {
const next: OnboardingState = {
...defaultState,
completed: true,
step: 7,
tier: 'power',
tooltipsDismissed: true,
apiKeySet: true,
};
saveState(next);
}
} catch {
/* sidecar unreachable — stay on the wizard so a truly new user can set up */
}
}
export const useOnboarding = () => {
const [state, setState] = useState<OnboardingState>(loadState);
// Re-sync when another hook instance writes to localStorage
useEffect(() => {
const handler = () => setState(loadState());
window.addEventListener('waggle:onboarding-sync', handler);
return () => window.removeEventListener('waggle:onboarding-sync', handler);
}, []);
// CC Sesija A §2.3 A11: Tauri filesystem-flag fast-path for returning users.
// Runs in Tauri mode only; if ~/.waggle/first-launch.flag exists the user
// has completed onboarding before (even if this WebView profile is fresh).
// Auto-completes the wizard in that case. Complementary to the workspaces-
// check below — flag is faster + doesn't need sidecar; either trigger is
// sufficient.
useEffect(() => {
if (state.completed) return;
if (!isTauri()) return;
let cancelled = false;
tauriIsFirstLaunch()
.then((firstLaunch) => {
if (cancelled || firstLaunch) return;
console.info(
'[useOnboarding] Tauri filesystem flag indicates returning user — auto-completing wizard',
);
const next: OnboardingState = {
...defaultState,
completed: true,
step: 7,
tier: state.tier || 'power',
tooltipsDismissed: true,
apiKeySet: true,
};
saveState(next);
setState(next);
})
.catch(() => {
/* command unavailable — fall through to existing returning-user check */
});
return () => {
cancelled = true;
};
// Run once on mount.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Bug #2: auto-complete onboarding for returning users.
// The localStorage flag is per-webview, so a fresh Tauri webview (or a
// browser switch) always looks "new" even when the sidecar has existing
// memory and workspaces. Ask the sidecar on mount.
//
// P4 fix (S4 founder flag, confirmed): the evidence used to be
// `getWorkspaces().length > 0` — but buildLocalServer's wsManager
// .ensureDefault() seeds a default workspace at BOOT, so a clean production
// install always had ≥1 workspace and a brand-new user NEVER saw the wizard.
// /api/onboarding/status is the server-authoritative signal instead: the
// completion flag (stamped below on complete) or legacy usage evidence
// (frames in the personal mind / user-created workspaces) — the seeded stub
// alone is not evidence.
useEffect(() => {
if (state.completed) return;
// Mid-wizard guard: step > 0 means THIS webview is actively onboarding —
// not a fresh-localStorage returning user. Without it, a C33 import run
// during the wizard writes personal-mind frames (= legacy evidence), and
// a refresh would auto-complete the wizard out from under the user,
// skipping the remaining steps.
if (state.step > 0) return;
// PM walkthrough bypass (DEV/E2E only): when ?forceWizard=true is set, skip
// the auto-complete branch so the wizard renders even for a returning
// user. Symmetric with the loadState() bypass above.
if (forceWizardParamAllowed()) {
const params = new URLSearchParams(window.location.search);
if (params.get('forceWizard') === 'true') return;
}
let cancelled = false;
(async () => {
try {
const status = await adapter.getOnboardingStatus();
if (cancelled) return;
if (status?.completed) {
console.info(
`[useOnboarding] returning user detected (server onboarding status: ${status.source ?? 'flag'}) — auto-completing wizard`
);
const next: OnboardingState = {
...defaultState,
completed: true,
step: 7,
tier: state.tier || 'power',
tooltipsDismissed: true,
apiKeySet: true,
};
saveState(next);
setState(next);
}
} catch {
/* sidecar unreachable — stay on the wizard so a truly new user can set up */
}
})();
return () => { cancelled = true; };
// Run once on mount — we intentionally don't re-run on state changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const update = useCallback((updates: Partial<OnboardingState>) => {
setState(prev => {
const next = { ...prev, ...updates };
// F1/F5: stamp the completion time on the transition ONLY (immutable copy)
// so the trial-modal gate + coach-marks gate can quiet themselves right
// after the wizard. The two returning-user auto-complete effects use
// saveState() directly and deliberately leave completedAt unset.
const justCompleted = next.completed && !prev.completed;
const stamped = justCompleted ? { ...next, completedAt: Date.now() } : next;
saveState(stamped);
if (justCompleted) {
// F5: per-session latch so the coach-mark carousel defers on the very
// first landing right after finishing the wizard.
try {
sessionStorage.setItem(ONBOARDED_THIS_SESSION_KEY, '1');
} catch { /* storage disabled — the completedAt window still covers first-run */ }
// P4: stamp the server-side completion flag — the durable signal the
// auto-complete effect above keys on. Fire-and-forget; failure is
// non-fatal (localStorage still says completed for this webview).
adapter.markOnboardingComplete().catch((err) => {
console.warn('[useOnboarding] markOnboardingComplete failed:', err);
});
// CC Sesija A §2.3 A11: Tauri filesystem flag too (default ~/.waggle
// installs share the same file; the IPC path works even when the
// sidecar is mid-restart).
if (isTauri()) {
tauriMarkFirstLaunchComplete().catch((err) => {
console.warn('[useOnboarding] markFirstLaunchComplete failed:', err);
});
}
}
return stamped;
});
}, []);
const complete = useCallback(() => {
update({ completed: true, step: 7 });
}, [update]);
const reset = useCallback(() => {
const fresh = { ...defaultState };
saveState(fresh);
setState(fresh);
}, []);
// Phase 1 #6 — replay just the post-wizard Tour without rerunning the full
// wizard. Clears the OnboardingTooltips localStorage flag (read independently
// of the onboarding state object) AND flips `tooltipsDismissed` so Desktop's
// gate fires the Tour overlay on next render. Wizard completion remains
// intact — workspaces, persona, tier all preserved.
const replayTour = useCallback(() => {
try {
window.localStorage.removeItem('waggle:tooltips_done');
} catch { /* storage disabled — state-side flip still triggers re-render */ }
// F5: force the coach-marks gate to show immediately, bypassing the
// post-completion deferral (this is an explicit user "replay" action).
try {
sessionStorage.setItem(COACH_MARKS_FORCE_KEY, '1');
} catch { /* storage disabled — tooltipsDismissed flip still re-renders */ }
setState(prev => {
const next = { ...prev, tooltipsDismissed: false };
saveState(next);
return next;
});
}, []);
return { state, update, complete, reset, replayTour };
};

View File

@@ -0,0 +1,52 @@
import { useState, useCallback } from 'react';
import {
shouldShowLoginBriefing,
readLoginBriefingDismissed,
readMinutesSinceLastDismiss,
readSkipBriefingParam,
} from '@/lib/login-briefing';
/**
* Briefing visibility is decided once on mount and persists until the
* user dismisses. Per-session behaviour is implicit: React state resets
* on every page load, so the briefing reappears each session unless
* the user has permanently opted out via "Don't show again"
* (localStorage `waggle:login-briefing-dismissed`).
*
* `?skipBriefing=true` stays as an E2E escape hatch so Playwright can
* interact with the dock without tearing down overlays.
*/
export function useOverlayState() {
const [showGlobalSearch, setShowGlobalSearch] = useState(false);
const [showCreateWorkspace, setShowCreateWorkspace] = useState(false);
const [showPersonaSwitcher, setShowPersonaSwitcher] = useState(false);
const [showWorkspaceSwitcher, setShowWorkspaceSwitcher] = useState(false);
const [showNotifications, setShowNotifications] = useState(false);
const [showKeyboardHelp, setShowKeyboardHelp] = useState(false);
const [showSpawnAgent, setShowSpawnAgent] = useState(false);
const [showLoginBriefing, setShowLoginBriefing] = useState(() =>
shouldShowLoginBriefing({
skipBriefing: readSkipBriefingParam(),
permanentlyDismissed: readLoginBriefingDismissed(),
minutesSinceLastDismiss: readMinutesSinceLastDismiss(),
}),
);
const toggleGlobalSearch = useCallback(() => setShowGlobalSearch(p => !p), []);
const togglePersonaSwitcher = useCallback(() => setShowPersonaSwitcher(p => !p), []);
const toggleWorkspaceSwitcher = useCallback(() => setShowWorkspaceSwitcher(p => !p), []);
const toggleNotifications = useCallback(() => setShowNotifications(p => !p), []);
const toggleKeyboardHelp = useCallback(() => setShowKeyboardHelp(p => !p), []);
return {
showGlobalSearch, setShowGlobalSearch, toggleGlobalSearch,
showCreateWorkspace, setShowCreateWorkspace,
showPersonaSwitcher, setShowPersonaSwitcher, togglePersonaSwitcher,
showWorkspaceSwitcher, setShowWorkspaceSwitcher, toggleWorkspaceSwitcher,
showNotifications, setShowNotifications, toggleNotifications,
showKeyboardHelp, setShowKeyboardHelp, toggleKeyboardHelp,
showSpawnAgent, setShowSpawnAgent,
showLoginBriefing, setShowLoginBriefing,
};
}

View File

@@ -0,0 +1,61 @@
import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
getProviders: vi.fn(),
}));
vi.mock('@/lib/adapter', () => ({
adapter: { getProviders: mocks.getProviders },
}));
import { useProviders } from './useProviders';
function catalog(modelId: string) {
return {
providers: [{
id: 'openai',
name: 'OpenAI',
hasKey: true,
badge: null,
keyUrl: null,
requiresKey: true,
models: [{ id: modelId, name: modelId, cost: '$$', speed: 'medium' }],
modelsSource: 'provider-api' as const,
}],
search: [],
activeSearch: 'duckduckgo',
};
}
beforeEach(() => {
mocks.getProviders.mockResolvedValue(catalog('openai/existing-model'));
});
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
describe('useProviders live catalog refresh', () => {
it('pulls the provider API again when Waggle regains focus', async () => {
mocks.getProviders
.mockResolvedValueOnce(catalog('openai/existing-model'))
.mockResolvedValueOnce(catalog('openai/model-released-while-open'));
const { result, unmount } = renderHook(() => useProviders());
await waitFor(() => expect(result.current.availableModels[0]?.id)
.toBe('openai/existing-model'));
await act(async () => {
window.dispatchEvent(new Event('focus'));
});
await waitFor(() => expect(result.current.availableModels[0]?.id)
.toBe('openai/model-released-while-open'));
expect(mocks.getProviders).toHaveBeenCalledTimes(2);
unmount();
window.dispatchEvent(new Event('focus'));
expect(mocks.getProviders).toHaveBeenCalledTimes(2);
});
});

View File

@@ -0,0 +1,100 @@
import { useState, useEffect, useCallback } from 'react';
import { adapter } from '@/lib/adapter';
export interface ProviderModel {
id: string;
name: string;
cost: string;
speed: string;
}
export interface Provider {
id: string;
name: string;
hasKey: boolean;
badge: string | null;
keyUrl: string | null;
requiresKey: boolean;
models: ProviderModel[];
modelsSource?: 'provider-api' | 'stale-provider-api' | 'unavailable' | 'requires-key' | 'local-runtime';
modelsUpdatedAt?: string;
modelsError?: string;
}
export interface SearchProvider {
id: string;
name: string;
hasKey: boolean;
priority: number;
}
/**
* Hook to fetch providers, models, and key status from /api/providers.
* Single source of truth — use this everywhere a model needs to be selected.
*/
export const useProviders = () => {
const [providers, setProviders] = useState<Provider[]>([]);
const [search, setSearch] = useState<SearchProvider[]>([]);
const [activeSearch, setActiveSearch] = useState('duckduckgo');
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const refresh = useCallback(async () => {
try {
const data = await adapter.getProviders();
setProviders(data.providers);
setSearch(data.search);
setActiveSearch(data.activeSearch);
setError(null);
return data;
} catch (err) {
console.error('[useProviders] fetch failed:', err);
setError(err instanceof Error ? err.message : 'Failed to load');
return null;
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
void refresh();
const refreshWhenVisible = () => {
if (document.visibilityState === 'visible') void refresh();
};
const refreshOnFocus = () => { void refresh(); };
document.addEventListener('visibilitychange', refreshWhenVisible);
window.addEventListener('focus', refreshOnFocus);
return () => {
document.removeEventListener('visibilitychange', refreshWhenVisible);
window.removeEventListener('focus', refreshOnFocus);
};
}, [refresh]);
/** All models across all providers, flat list */
const allModels = providers.flatMap(p =>
p.models.map(m => ({
...m,
providerId: p.id,
providerName: p.name,
hasKey: p.hasKey,
}))
);
/** Cloud providers that have a key configured. Keyless local runtimes are handled separately. */
const activeProviders = providers.filter(p => p.hasKey && p.requiresKey);
/** Models from providers with keys (available for use) */
const availableModels = allModels.filter(m => m.hasKey);
return {
providers,
search,
activeSearch,
allModels,
activeProviders,
availableModels,
loading,
error,
refresh,
};
};

View File

@@ -0,0 +1,62 @@
/**
* P1b D3 plus-clause — useRevalidateOnError listener mechanics: fires only
* while errored, on all four triggers (online / visibilitychange→visible /
* focus / waggle:connect-settled), and detaches on recovery.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { renderHook, cleanup } from '@testing-library/react';
import { useRevalidateOnError, CONNECT_SETTLED_EVENT } from './useRevalidateOnError';
afterEach(cleanup);
describe('useRevalidateOnError', () => {
it('does nothing while healthy', () => {
const fn = vi.fn();
renderHook(() => useRevalidateOnError(false, fn));
window.dispatchEvent(new Event('focus'));
window.dispatchEvent(new CustomEvent(CONNECT_SETTLED_EVENT));
expect(fn).not.toHaveBeenCalled();
});
it.each(['online', 'focus', CONNECT_SETTLED_EVENT])('fires on %s while errored', (eventName) => {
const fn = vi.fn();
renderHook(() => useRevalidateOnError(true, fn));
window.dispatchEvent(new Event(eventName));
expect(fn).toHaveBeenCalledOnce();
});
it('fires on visibilitychange only when the document becomes visible', () => {
const fn = vi.fn();
renderHook(() => useRevalidateOnError(true, fn));
const visibility = vi.spyOn(document, 'visibilityState', 'get');
visibility.mockReturnValue('hidden');
document.dispatchEvent(new Event('visibilitychange'));
expect(fn).not.toHaveBeenCalled();
visibility.mockReturnValue('visible');
document.dispatchEvent(new Event('visibilitychange'));
expect(fn).toHaveBeenCalledOnce();
visibility.mockRestore();
});
it('detaches when errored flips false (recovery)', () => {
const fn = vi.fn();
const { rerender } = renderHook(({ errored }) => useRevalidateOnError(errored, fn), {
initialProps: { errored: true },
});
rerender({ errored: false });
window.dispatchEvent(new Event('focus'));
expect(fn).not.toHaveBeenCalled();
});
it('always invokes the LATEST callback (ref pattern survives re-renders)', () => {
const first = vi.fn();
const second = vi.fn();
const { rerender } = renderHook(({ fn }) => useRevalidateOnError(true, fn), {
initialProps: { fn: first },
});
rerender({ fn: second });
window.dispatchEvent(new Event('focus'));
expect(first).not.toHaveBeenCalled();
expect(second).toHaveBeenCalledOnce();
});
});

View File

@@ -0,0 +1,43 @@
/**
* UX Refactor v2.1 P1b (D3 plus-clause) — revalidate an ERRORED surface when
* the user comes back or the connection recovers.
*
* Mirrors the useOfflineStatus triple-listener (window 'online' +
* document 'visibilitychange'→visible + window 'focus' — focus is needed
* because visibilitychange misses window-level refocus while the tab stays
* visible) and adds the P1b 'waggle:connect-settled' bus event dispatched by
* ServiceProvider on every connect settlement — the only trigger that fires
* on the default desktop launch path, where the window already has focus and
* none of the DOM events ever arrive.
*
* Keyed to `errored`: healthy surfaces never refetch on focus. The callback
* is kept in a ref so callers can pass a fresh closure each render without
* tearing down the listeners.
*/
import { useEffect, useRef } from 'react';
export const CONNECT_SETTLED_EVENT = 'waggle:connect-settled';
export function useRevalidateOnError(errored: boolean, revalidate: () => void): void {
const fnRef = useRef(revalidate);
fnRef.current = revalidate;
useEffect(() => {
if (!errored) return;
const fire = () => fnRef.current();
const onVisible = () => { if (document.visibilityState === 'visible') fire(); };
window.addEventListener('online', fire);
document.addEventListener('visibilitychange', onVisible);
window.addEventListener('focus', fire);
window.addEventListener(CONNECT_SETTLED_EVENT, fire);
return () => {
window.removeEventListener('online', fire);
document.removeEventListener('visibilitychange', onVisible);
window.removeEventListener('focus', fire);
window.removeEventListener(CONNECT_SETTLED_EVENT, fire);
};
}, [errored]);
}

View File

@@ -0,0 +1,178 @@
/**
* useRoomState — subscribes to `subagent_status` SSE events and maintains
* a per-workspace map of live sub-agents for the Room canvas.
*
* Legacy chat subagents arrive as SSE deltas. Durable external/Fleet/group
* runs hydrate from the AgentRun snapshot and replay journal, so reconnects
* do not lose participants or results. Completed agents remain in "recent"
* for 15 minutes.
*/
import { useCallback, useEffect, useMemo, useState } from 'react';
import { adapter } from '@/lib/adapter';
import {
applyCanonicalRunEvents,
applyRunEvent,
applyStatusEvent,
filterWorkspaceMapByRoom,
hydrateCanonicalRuns,
hydrateRunSnapshot,
indexCanonicalRooms,
pruneRecent,
type CanonicalRunMap,
type RoomAgent as _RoomAgent,
type WorkspaceAgents,
} from '@/lib/room-state-reducer';
// Re-export the type at the old import path so RoomApp doesn't need changes.
export type RoomAgent = _RoomAgent;
export function useRoomState(focusedRoomId?: string) {
const [workspaceMap, setWorkspaceMap] = useState<Map<string, WorkspaceAgents>>(() => new Map());
const [runsById, setRunsById] = useState<CanonicalRunMap>(() => new Map());
// P7/D15 B2: a broken SSE channel must be distinguishable from an idle room.
// `connecting` covers the brief subscribe window; `error` flags a subscribe
// failure so RoomApp can show reconnect instead of "no agents running".
const [connecting, setConnecting] = useState(true);
const [streamError, setStreamError] = useState<string | null>(null);
const [syncError, setSyncError] = useState<string | null>(null);
const [reconnectNonce, setReconnectNonce] = useState(0);
const reconnect = useCallback(() => setReconnectNonce((n) => n + 1), []);
useEffect(() => {
let unsub: (() => void) | undefined;
let disposed = false;
let syncing = false;
let lastSeq: number | null = null;
setConnecting(true);
setStreamError(null);
setSyncError(null);
try {
unsub = adapter.subscribeSubagentStatus((event) => {
setWorkspaceMap(prev => {
const next = new Map(prev);
const current = next.get(event.workspaceId);
// Pure reducer drives the actual state math; see room-state-reducer.ts.
const updated = applyStatusEvent(current, event);
next.set(event.workspaceId, updated);
return next;
});
});
} catch (err) {
setStreamError(err instanceof Error ? err.message : 'Failed to connect to the Room');
setConnecting(false);
console.error('[useRoomState] SSE subscribe failed:', err);
}
const syncRuns = async () => {
if (syncing || disposed) return;
syncing = true;
try {
if (lastSeq === null) {
const snapshot = await adapter.getAgentRunSnapshot();
if (disposed) return;
lastSeq = snapshot.lastSeq;
setRunsById(hydrateCanonicalRuns(snapshot.runs));
setWorkspaceMap((prev) => hydrateRunSnapshot(prev, snapshot.runs));
} else {
const replay = await adapter.getAgentRunEvents(lastSeq);
if (disposed) return;
lastSeq = replay.lastSeq;
setRunsById((prev) => {
if (replay.resetRequired && replay.snapshot) {
return hydrateCanonicalRuns(replay.snapshot.runs);
}
return applyCanonicalRunEvents(prev, replay.events);
});
setWorkspaceMap((prev) => {
if (replay.resetRequired && replay.snapshot) {
return hydrateRunSnapshot(prev, replay.snapshot.runs);
}
return replay.events.reduce(
(state, event) => applyRunEvent(state, event),
prev,
);
});
}
setSyncError(null);
} catch (err) {
if (!disposed) setSyncError(err instanceof Error ? err.message : 'Failed to sync Room runs');
} finally {
syncing = false;
if (!disposed) setConnecting(false);
}
};
void syncRuns();
const poll = setInterval(() => { void syncRuns(); }, 1_000);
return () => {
disposed = true;
clearInterval(poll);
unsub?.();
};
}, [reconnectNonce]);
// Periodically prune recent entries so stale ones fall off even without new events.
useEffect(() => {
const interval = setInterval(() => {
setWorkspaceMap(prev => {
let changed = false;
const next = new Map(prev);
for (const [wsId, data] of prev) {
const pruned = pruneRecent(data.recent);
if (pruned.length !== data.recent.length) {
next.set(wsId, { ...data, recent: pruned });
changed = true;
}
}
return changed ? next : prev;
});
}, 60_000);
return () => clearInterval(interval);
}, []);
const canonicalRooms = useMemo(() => indexCanonicalRooms(runsById), [runsById]);
const focusedRoom = focusedRoomId ? canonicalRooms.roomsById.get(focusedRoomId) : undefined;
const focusedWorkers = focusedRoomId
? (canonicalRooms.childrenByRoomId.get(focusedRoom?.id ?? focusedRoomId) ?? [])
: [];
const visibleWorkspaceMap = useMemo(
() => focusedRoomId
? filterWorkspaceMapByRoom(workspaceMap, focusedRoom?.roomId ?? focusedRoomId)
: workspaceMap,
[focusedRoom, focusedRoomId, workspaceMap],
);
const allWorkspaceIds = useMemo(() => [...visibleWorkspaceMap.keys()], [visibleWorkspaceMap]);
const totalLive = useMemo(() => {
let count = 0;
for (const data of visibleWorkspaceMap.values()) count += data.live.length;
return count;
}, [visibleWorkspaceMap]);
const getWorkspace = (workspaceId: string): WorkspaceAgents | undefined => visibleWorkspaceMap.get(workspaceId);
const getRoomWorkers = (roomId: string) => {
const rootId = canonicalRooms.roomsById.get(roomId)?.id ?? roomId;
return canonicalRooms.childrenByRoomId.get(rootId) ?? [];
};
const error = syncError ?? streamError;
return {
workspaceMap: visibleWorkspaceMap,
allWorkspaceMap: workspaceMap,
allWorkspaceIds,
totalLive,
getWorkspace,
runsById,
rooms: canonicalRooms.rooms,
roomsById: canonicalRooms.roomsById,
childrenByRoomId: canonicalRooms.childrenByRoomId,
getRoomWorkers,
focusedRoomId,
focusedRoom,
focusedWorkers,
connecting,
error,
reconnect,
};
}

View File

@@ -0,0 +1,86 @@
import { useState, useCallback, useEffect } from 'react';
import { adapter } from '@/lib/adapter';
import type { Session } from '@/lib/types';
const makeDefaultSession = (workspaceId: string): Session => ({
id: `local-session-${workspaceId}`,
workspaceId,
title: 'New Session',
messageCount: 0,
lastActive: new Date().toISOString(),
});
export const useSessions = (workspaceId: string | null) => {
const [sessions, setSessions] = useState<Session[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!workspaceId) { setSessions([]); setActiveSessionId(null); return; }
// Reset active session on workspace change to avoid stale cross-workspace refs
setActiveSessionId(null);
setLoading(true);
adapter.getSessions(workspaceId)
.then(data => {
if (data.length > 0) {
setSessions(data);
setActiveSessionId(data[0].id);
} else {
const def = makeDefaultSession(workspaceId);
setSessions([def]);
setActiveSessionId(def.id);
}
})
.catch((err) => {
console.error('[useSessions] fetch failed:', err);
setError(err instanceof Error ? err.message : 'Failed to load');
const def = makeDefaultSession(workspaceId);
setSessions([def]);
setActiveSessionId(def.id);
})
.finally(() => setLoading(false));
}, [workspaceId]);
const createSession = useCallback(async () => {
if (!workspaceId) return;
try {
const session = await adapter.createSession(workspaceId);
setSessions(prev => [session, ...prev]);
setActiveSessionId(session.id);
return session;
} catch (err) {
console.error('[useSessions] create failed, using local fallback:', err);
const local: Session = {
id: `local-session-${Date.now()}`,
workspaceId,
title: 'New Session',
messageCount: 0,
lastActive: new Date().toISOString(),
};
setSessions(prev => [local, ...prev]);
setActiveSessionId(local.id);
return local;
}
}, [workspaceId]);
const deleteSession = useCallback(async (sessionId: string) => {
if (!workspaceId) return;
try { await adapter.deleteSession(sessionId, workspaceId); } catch (err) { console.error('[useSessions] delete failed:', err); }
setSessions(prev => prev.filter(s => s.id !== sessionId));
if (activeSessionId === sessionId) {
setActiveSessionId(sessions.find(s => s.id !== sessionId)?.id || null);
}
}, [workspaceId, activeSessionId, sessions]);
const renameSession = useCallback(async (sessionId: string, title: string) => {
if (!workspaceId) return;
try { await adapter.renameSession(workspaceId, sessionId, title); } catch (err) { console.error('[useSessions] rename failed:', err); }
setSessions(prev => prev.map(s => s.id === sessionId ? { ...s, title } : s));
}, [workspaceId]);
return {
sessions, activeSessionId, setActiveSessionId,
loading, error, createSession, deleteSession, renameSession,
};
};

View File

@@ -0,0 +1,151 @@
/**
* Pillar 3.1 — render-side streaming cadence buffer.
*
* Locks the four contract points from the lane spec:
* 1. Not-streaming / history text is whole on first paint (no cadence).
* 2. Zero added latency: the first chunk's first chars reveal within one rAF,
* and a live stream drains fully within ≤1 frame of stream end.
* 3. Reduced-motion snaps to full text (REDUCED.streamingCaret = static).
* 4. A chunked code-block + list reveals monotonically as an escaped prefix —
* no whole-block pop, never chars beyond the accumulated raw.
*
* rAF is stubbed with a manual queue so the reveal is deterministic frame-by-frame.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { renderHook, act, cleanup } from '@testing-library/react';
const motionMock = vi.hoisted(() => ({ reduce: false }));
vi.mock('framer-motion', () => ({ useReducedMotion: () => motionMock.reduce }));
import { useStreamCadence, MIN_CHARS_PER_FRAME } from './useStreamCadence';
let rafQueue: Map<number, FrameRequestCallback>;
let rafId: number;
let vt: number;
beforeEach(() => {
motionMock.reduce = false;
rafQueue = new Map();
rafId = 0;
vt = 0;
vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
const id = ++rafId;
rafQueue.set(id, cb);
return id;
});
vi.stubGlobal('cancelAnimationFrame', (id: number) => {
rafQueue.delete(id);
});
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
/** Advance `n` animation frames, running each pending callback inside act(). */
function flushFrames(n = 1) {
for (let i = 0; i < n; i++) {
vt += 16;
const pending = [...rafQueue.entries()];
rafQueue.clear();
act(() => {
for (const [, cb] of pending) cb(vt);
});
}
}
describe('useStreamCadence', () => {
it('renders settled / history text whole on the first paint (no cadence when not streaming)', () => {
const { result } = renderHook(() => useStreamCadence('A finished reply.', false));
expect(result.current.shown).toBe('A finished reply.');
expect(result.current.caretVisible).toBe(false);
});
it('shows the first chars within a single rAF — zero buffering before first paint', () => {
const { result } = renderHook(() => useStreamCadence('Hello', true));
// Nothing buffered on mount; the reveal begins on the first frame, not before.
expect(result.current.shown).toBe('');
expect(result.current.caretVisible).toBe(false);
flushFrames(1);
expect(result.current.shown.length).toBeGreaterThanOrEqual(MIN_CHARS_PER_FRAME);
expect('Hello'.startsWith(result.current.shown)).toBe(true);
expect(result.current.caretVisible).toBe(true);
});
it('reduced-motion snaps to full text with a (static) caret while streaming', () => {
motionMock.reduce = true;
const { result } = renderHook(() => useStreamCadence('Reduced stream', true));
// No frame flush needed — reduced motion reveals everything at once.
expect(result.current.shown).toBe('Reduced stream');
expect(result.current.caretVisible).toBe(true);
});
it('backlog scales the per-frame reveal so a whole-block dump accretes (never pops)', () => {
const dump = 'x'.repeat(600); // an echo-provider whole-block arrival
const { result } = renderHook(() => useStreamCadence(dump, true));
flushFrames(1);
const afterOne = result.current.shown.length;
// First frame reveals far more than the per-char floor (backlog / CATCHUP),
// yet never the whole block at once — a smooth accretion, not a pop.
expect(afterOne).toBeGreaterThan(MIN_CHARS_PER_FRAME);
expect(afterOne).toBeLessThan(dump.length);
});
it('reveals a chunked code block + list monotonically as an escaped prefix', () => {
const chunks = [
'Here is a snippet:\n',
'```\nconst x = 1;\n',
'console.log(x);\n```\n',
'- first item\n',
'- second item',
];
let acc = '';
const { result, rerender } = renderHook(
({ r, s }: { r: string; s: boolean }) => useStreamCadence(r, s),
{ initialProps: { r: '', s: true } },
);
const lengths: number[] = [result.current.shown.length];
for (const c of chunks) {
acc += c;
rerender({ r: acc, s: true });
for (let f = 0; f < 8; f++) {
flushFrames(1);
// `shown` is always a prefix of the accumulated raw — the cadence never
// reveals unbuffered chars, so partial markdown can only form as text.
expect(acc.startsWith(result.current.shown)).toBe(true);
lengths.push(result.current.shown.length);
}
}
for (let i = 1; i < lengths.length; i++) {
expect(lengths[i]).toBeGreaterThanOrEqual(lengths[i - 1]);
}
// Stream end snaps to the whole text within ≤1 frame; caret clears.
rerender({ r: acc, s: false });
expect(result.current.shown).toBe(acc);
expect(result.current.caretVisible).toBe(false);
});
it('drains to the whole text within ≤1 frame of stream end', () => {
const full = 'partial reveal that is still in progress here';
const { result, rerender } = renderHook(
({ r, s }: { r: string; s: boolean }) => useStreamCadence(r, s),
{ initialProps: { r: full, s: true } },
);
flushFrames(1); // only a small prefix revealed so far
expect(result.current.shown.length).toBeLessThan(full.length);
rerender({ r: full, s: false }); // stream ends
expect(result.current.shown).toBe(full);
});
it('never reveals past a shrunk target (defensive prefix clamp on reset)', () => {
const { result, rerender } = renderHook(
({ r, s }: { r: string; s: boolean }) => useStreamCadence(r, s),
{ initialProps: { r: 'a long streaming string here', s: true } },
);
flushFrames(30); // caught up to the long target
rerender({ r: 'short', s: true }); // target shrank underneath us
expect(result.current.shown.length).toBeLessThanOrEqual('short'.length);
expect('short'.startsWith(result.current.shown)).toBe(true);
});
});

View File

@@ -0,0 +1,81 @@
import { useEffect, useRef, useState } from 'react';
import { useReducedMotion } from 'framer-motion';
/**
* Render-side streaming cadence buffer (path-to-9 Pillar 3.1 — the #1 gap).
*
* The SSE path delivers text in chunks (in the dev echo provider, often a whole
* block at once). Rendering `block.content` verbatim makes the reveal read as
* "line/chunk pop", not the per-character rhythm judges score at Claude/ChatGPT
* level. This hook smooths the *render* of an already-accumulated raw string
* into a steady per-character reveal with ZERO added latency to the first token:
* `rawText` already holds every delivered chunk, so nothing is buffered on the
* wire — this only paces how the prefix is painted.
*
* Cadence: on each animation frame the shown length advances toward the target
* by `max(MIN_CHARS_PER_FRAME, ceil(backlog / CATCHUP_FRAMES))`. The backlog
* term makes a whole-block dump drain in ~CATCHUP_FRAMES (a smooth accretion,
* never a pop) while a slow trickle reveals a couple of chars a frame — the lag
* never exceeds a small window and drains fully within ~1 frame of stream end.
*
* Not streaming (settled turn / history) or `prefers-reduced-motion: reduce`:
* the text is whole on first paint (REDUCED.streamingCaret = 'static'); no rAF,
* no flicker.
*/
export interface StreamCadence {
/** The smoothed prefix of `rawText` to render this frame. */
shown: string;
/** Whether the trailing honey caret should render (streaming + has content). */
caretVisible: boolean;
}
/** Per-frame reveal floor — the steady per-character rhythm on a slow trickle
* (~3 chars/frame ≈ 180 chars/sec at 60fps, a readable typewriter pace). */
export const MIN_CHARS_PER_FRAME = 3;
/** Backlog is cleared over ~this many frames — bounds the lag to a small window.
* Tuned to ~40 (≈670ms) so a WHOLE-BLOCK echo dump reveals over ~8 frames at the
* 12fps judge sampling (unambiguously per-token, gentler markdown reflow) rather
* than a fast pop, while a real slow stream still keeps pace via the MIN floor. */
export const CATCHUP_FRAMES = 40;
export function useStreamCadence(rawText: string, isStreaming: boolean): StreamCadence {
const reduced = !!useReducedMotion();
const targetLen = rawText.length;
// Read the live target inside the rAF loop without re-subscribing the effect
// on every chunk (the loop must stay one continuous animation, not restart).
const targetLenRef = useRef(targetLen);
targetLenRef.current = targetLen;
// Start already whole for settled/history/reduced text so the first paint is
// complete; start at 0 only for a live stream so the reveal accretes.
const [shownLen, setShownLen] = useState(() =>
isStreaming && !reduced ? 0 : targetLen,
);
useEffect(() => {
if (!isStreaming || reduced) {
// Snap to the whole target: stream end drains ≤1 frame after the last
// chunk, and reduced-motion reveals everything at once (REDUCED map).
setShownLen(targetLenRef.current);
return;
}
let raf = 0;
const tick = () => {
setShownLen((prev) => {
const target = targetLenRef.current;
if (prev >= target) return prev; // caught up — idle-poll for more backlog
const backlog = target - prev;
const step = Math.max(MIN_CHARS_PER_FRAME, Math.ceil(backlog / CATCHUP_FRAMES));
return Math.min(target, prev + step);
});
raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [isStreaming, reduced]);
// `rawText` only grows within a turn, but slice clamps defensively so a reset
// to a shorter string can never reveal past the new (shorter) target.
const shown = rawText.slice(0, Math.min(shownLen, targetLen));
return { shown, caretVisible: isStreaming && shown.length > 0 };
}

View File

@@ -0,0 +1,59 @@
import { useState, useEffect, useCallback } from 'react';
import { adapter } from '@/lib/adapter';
import type { WaggleSignal } from '@/lib/types';
export const useWaggleDance = () => {
const [signals, setSignals] = useState<WaggleSignal[]>([]);
const [loading, setLoading] = useState(true);
const [filter, setFilter] = useState<WaggleSignal['type'] | 'all'>('all');
const [error, setError] = useState<string | null>(null);
const refresh = useCallback(async () => {
setLoading(true);
try {
const data = await adapter.getWaggleSignals();
setSignals(data);
setError(null);
} catch (err) {
console.error('[useWaggleDance] refresh failed:', err);
setSignals([]);
setError(err instanceof Error ? err.message : 'Failed to load');
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
refresh();
let unsub: (() => void) | undefined;
try {
unsub = adapter.subscribeWaggleDance?.((signal) => {
setSignals(prev => [signal, ...prev]);
}) || undefined;
} catch (err) {
console.error('[useWaggleDance] SSE subscribe failed:', err);
}
return () => { try { unsub?.(); } catch (err) { console.error('[useWaggleDance] cleanup failed:', err); } };
}, [refresh]);
const publishSignal = useCallback(async (data: Omit<WaggleSignal, 'id' | 'timestamp'>) => {
try {
const signal = await adapter.publishWaggleSignal(data);
setSignals(prev => [signal, ...prev]);
return signal;
} catch (e) {
throw e;
}
}, []);
const acknowledge = useCallback(async (id: string) => {
try {
await adapter.acknowledgeWaggleSignal(id);
setSignals(prev => prev.map(s => s.id === id ? { ...s, acknowledged: true } : s));
} catch (err) { console.error('[useWaggleDance] acknowledge failed:', err); }
}, []);
const filtered = filter === 'all' ? signals : signals.filter(s => s.type === filter);
return { signals: filtered, allSignals: signals, loading, error, filter, setFilter, refresh, publishSignal, acknowledge };
};

View File

@@ -0,0 +1,116 @@
import { useState, useCallback, useEffect } from 'react';
import { adapter } from '@/lib/adapter';
import type { Workspace } from '@/lib/types';
import { useRevalidateOnError } from '@/hooks/useRevalidateOnError';
import {
resolveActiveWorkspaceId,
readPersistedWorkspaceId,
persistWorkspaceId,
clearPersistedWorkspaceId,
} from '@/lib/workspace-selection';
export const useWorkspaces = () => {
const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
// W2A: selection is explicit-only + survives full page loads. Seed from
// localStorage so a typed-URL visit to / or /workspaces keeps the workspace.
const [activeWorkspaceId, setActiveWorkspaceId] = useState<string | null>(() => readPersistedWorkspaceId());
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchWorkspaces = useCallback(async () => {
setLoading(true);
try {
const data = await adapter.getWorkspaces();
setWorkspaces(data);
// W2A: NO auto-select. Validate the existing selection against the fresh
// list (dropping a stale/deleted id to null); never promote data[0].
setActiveWorkspaceId(prev => resolveActiveWorkspaceId(prev, data.map(w => w.id)));
setError(null);
} catch (err) {
console.error('[useWorkspaces] fetch failed:', err);
// P1b D3: surface the failure (this channel existed but was never set —
// a lost boot race meant an empty workspace list for the whole session)
// and keep any previously good list rather than clobbering it.
setError(err instanceof Error ? err.message : 'Failed to load workspaces');
} finally {
setLoading(false);
}
}, []);
useEffect(() => { fetchWorkspaces(); }, []);
// P1b D3 plus-clause: errored list revalidates on focus/online/connect-settled.
useRevalidateOnError(error !== null, fetchWorkspaces);
const createWorkspace = useCallback(async (data: { name: string; group: string; persona?: string; agentGroupId?: string; shared?: boolean; templateId?: string }) => {
try {
const ws = await adapter.createWorkspace(data);
setWorkspaces(prev => [...prev, ws]);
setActiveWorkspaceId(ws.id);
persistWorkspaceId(ws.id);
return ws;
} catch (err) {
console.error('[useWorkspaces] create failed, using local fallback:', err);
const localWs: Workspace = {
id: `local-${Date.now()}`,
name: data.name,
group: data.group,
persona: data.persona,
shared: data.shared,
templateId: data.templateId,
health: 'healthy',
memoryCount: 0,
sessionCount: 0,
lastActive: new Date().toISOString(),
};
setWorkspaces(prev => [...prev, localWs]);
setActiveWorkspaceId(localWs.id);
persistWorkspaceId(localWs.id);
return localWs;
}
}, []);
// G4 (UX-Northstar 2026-06-13): state mutates ONLY on server success — a failed
// delete/patch must not pretend it happened (error-as-empty antipattern).
// Returns success so menu-style callers can toast; legacy fire-and-forget
// callers (AppShell persona/group switch) keep working without throw.
const deleteWorkspace = useCallback(async (id: string): Promise<boolean> => {
try {
await adapter.deleteWorkspace(id);
} catch (err) {
console.error('[useWorkspaces] delete failed:', err);
return false;
}
setWorkspaces(prev => prev.filter(w => w.id !== id));
// W2A: deleting the active workspace clears the selection (no silent
// successor-pick) — the shell then prompts the user to choose one.
if (activeWorkspaceId === id) {
setActiveWorkspaceId(null);
clearPersistedWorkspaceId();
}
return true;
}, [activeWorkspaceId]);
const patchWorkspace = useCallback(async (id: string, data: Partial<Pick<Workspace, 'persona' | 'agentGroupId' | 'name' | 'group' | 'model' | 'status' | 'description'>>): Promise<boolean> => {
try {
await adapter.patchWorkspace(id, data);
} catch (err) {
console.error('[useWorkspaces] patch failed:', err);
return false;
}
setWorkspaces(prev => prev.map(w => w.id === id ? { ...w, ...data } : w));
return true;
}, []);
const selectWorkspace = useCallback((id: string) => {
setActiveWorkspaceId(id);
persistWorkspaceId(id);
}, []);
const activeWorkspace = workspaces.find(w => w.id === activeWorkspaceId) || null;
return {
workspaces, activeWorkspace, activeWorkspaceId,
loading, error, createWorkspace, deleteWorkspace,
patchWorkspace, selectWorkspace, refresh: fetchWorkspaces,
};
};