diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml new file mode 100644 index 0000000000..9b9224d149 --- /dev/null +++ b/.github/workflows/ui.yml @@ -0,0 +1,34 @@ +# UI test lanes — phase-0 §7 (CI skeleton). Runs on every commit touching +# ui/**; never touches the product's own npm test gates. +name: ui + +on: + push: + paths: + - 'ui/**' + - '.github/workflows/ui.yml' + pull_request: + paths: + - 'ui/**' + - '.github/workflows/ui.yml' + +jobs: + test: + runs-on: ubuntu-latest + defaults: + run: + working-directory: ui + steps: + - uses: actions/checkout@v4 + with: + # The version handshake and spine tests read git history/tags. + fetch-depth: 0 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - uses: pnpm/action-setup@v4 + with: + version: 10 + - run: pnpm install --frozen-lockfile + - run: pnpm typecheck + - run: pnpm test diff --git a/.gitignore b/.gitignore index 75f4830324..0ba7375de0 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,6 @@ node_modules/ .npm-cache/ .workflows/.knowledge/store.msp + +# Local test-harness workflow project (not part of the UI deliverable) +/ui/demo/ diff --git a/ui/.gitignore b/ui/.gitignore new file mode 100644 index 0000000000..f59ba78446 --- /dev/null +++ b/ui/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +dist/ +bridge-state/ +*.tsbuildinfo +.tmp/ diff --git a/ui/README.md b/ui/README.md new file mode 100644 index 0000000000..438bb748e1 --- /dev/null +++ b/ui/README.md @@ -0,0 +1,149 @@ +# Workflow Bridge UI + +The web UI for the agentic-workflows process — a read-only-first veneer over a +project's `.workflows/`, git, and the engine's in-process `lib.cjs`. It adds no +new workflow state: everything renders from the engine, gates are never guessed, +and never-auto gates require a typed confirm. Plans and specs live in +[`plans/`](plans/) — start at [`plans/README.md`](plans/README.md) (the intent +baseline); the phase-by-phase review history is in +[`plans/REVIEW.md`](plans/REVIEW.md). + +Implemented across phases 0–7: **rails** (event model, spine, watcher, version +handshake) · **mirror** (the read-only SPA) · **gates** (sessions, the needs-you +queue, threads) · **attention** (escalation, digests) · **artifact lenses** +(Read/Structure/History) · **delivery telemetry** · **multiplayer** (auth, +ownership, capture, presence, comments) · **MCP Apps** (the gate card inside +Claude). + +## Design artefacts + +Self-contained HTML design/presentation pages (open directly in a browser) — +snapshots of the visual language and screen designs the build follows: + +- [`artefacts/the-workflow-bridge.html`](artefacts/the-workflow-bridge.html) — + the overview: what the bridge is and the design intent behind it. +- [`artefacts/workflow-bridge-screens.html`](artefacts/workflow-bridge-screens.html) + — the screen mockups (lobby, channel, queue, thread, lenses, and the rest). +- [`artefacts/agentic-workflows-field-guide.html`](artefacts/agentic-workflows-field-guide.html) + — a field guide to the workflow system the bridge surfaces. + +## Layout + +- `bridge/` — the bridge daemon: turns the project's existing surfaces (engine + `lib.cjs`, manifests, git, presence, the agent store) into a typed event + stream, drives headless workflow sessions, serves the SPA, and hosts the MCP + server (`bridge mcp`). +- `app/` — the SPA (React + Vite): lobby, channels, the needs-you queue, session + threads, artifact lenses, delivery telemetry, and the multiplayer surfaces + (identity, gate ownership, the capture gesture, presence, comments). +- `shared/` — the gate-card schema and event vocabulary as zod schemas, frozen + at the end of Phase 2. +- `fixtures/` — replay fixtures per `plans/specs/fixture-format.md`. Recorded + through the harness, never hand-edited (the authored `fixtures/adversarial/` + corpus is the one carve-out). + +## Running + +Prototype distribution is a repo checkout. Build once so the bridge can serve +the SPA, then run it against a project: + +```sh +cd ui && pnpm install && pnpm build # build the SPA + packages + +# Live mode — stream a real project's domain events and serve the app: +pnpm bridge -- --project /path/to/project + +# Replay mode — stream a recorded fixture: +pnpm bridge -- --replay fixtures/mid-discussion + +# Convert a terminal-driven session into a fixture (spec 4, Phase 0 form): +pnpm --filter @workflow-ui/bridge exec tsx src/cli.ts convert \ + --session ~/.claude/projects//.jsonl \ + --out ../fixtures/my-fixture --world-from /path/to/project +``` + +Open **http://127.0.0.1:4870/** for the app (it follows live over SSE); the +observability console is at `/debug`. During UI development, `pnpm --filter app +dev` runs Vite with HMR against a running bridge. + +- **Engine discovery**: `/.claude/skills/workflow-engine/scripts/` + (dev-repo fallback: `/skills/workflow-engine/scripts/`). Override + with `--engine `. +- **Width pin**: every engine invocation pins `WORKFLOWS_DISPLAY_WIDTH=65` — + renders are terminal-width-sensitive; unpinned output encodes whatever width + was detected. +- **Config file**: `~/.config/workflow-bridge/config.json` (override with + `--config `), schema in `shared/src/config.ts` — projects, width pin, + notification settings (quiet hours, escalation, roll-up, stuck/grace), auth + mode, port, daily budget warning. Argv flags override per run. +- **Bridge state**: UI-native SQLite lives OUT of tree at + `~/.cache/workflow-bridge/-/` (override with `--state-dir`). + The bridge never writes into `.workflows/` — the one exception is a chat + attachment, materialized into the gitignored `.workflows/.cache/` so the + session's Read tool can pick it up (transient user-input-in-transit, not + bridge state). +- **Debug console**: `http://127.0.0.1:4870/debug` — health/banner, event stream + (live vs durable), structured logs, cost counters. `/health`, `/events` (SSE, + `?since=`), `/costs`, `/logs` are named surfaces the SPA is built on. + +### Sessions and API keys (Phase 2+) + +The bridge drives headless workflow sessions — answering gates, the capture +gesture, resuming an interrupted session — one SDK query per human turn, with a +programmatic permission policy (allowlisted Bash, project-confined file writes, +non-Anthropic secrets redacted). The Anthropic API key resolves from the +environment (`ANTHROPIC_API_KEY`) or the OS keychain — **never the browser, +never this repo** — following the product's own credentials doctrine +(`~/.config/workflows/credentials.json`, mode 0600; keys never transit chat or +argv). + +### Auth (Phase 6) + +Single-user mode is **zero-config** — every request is the sentinel human +("You"), and the per-install bearer token is the whole trust boundary. Multi-user +mode (`auth.mode: "github"` in the config, with `auth.repo`) authenticates via a +GitHub login and treats **push access to the origin repo as membership**, checked +at login and cached per auth session. Gate ownership, comments, and capture are +**UI-side routing, never process authority** — the engine enforces none of it, +and a terminal answer bypasses the UI entirely (resolving the card as "answered +outside the UI"). The OAuth redirect flow is deployment wiring; the prototype +ships the identity + member-check contract it wraps (see `plans/REVIEW.md`). + +### MCP server (Phase 7) + +`bridge mcp` exposes the gate card and the needs-you queue to an MCP host (Claude +web/desktop) as a **third client of a running bridge** — no second card +implementation, the frozen `shared/` schema rendered as `ui://` resources: + +```sh +WORKFLOW_BRIDGE_TOKEN= \ + pnpm --filter @workflow-ui/bridge exec tsx src/cli.ts mcp \ + --bridge-url http://127.0.0.1:4870 +``` + +In github mode also set `WORKFLOW_BRIDGE_COOKIE` (a per-user auth cookie). +Typed-confirm (never-auto) gates require a UI-origin gesture and render read-only +in the MCP widget with a deep link to the SPA — a plain model tool call answering +one is rejected at the bridge. + +### Version handshake + +The bridge reads the installed product's version from its git tag and declares a +supported range; outside it — or on a repo with pending migrations (diff of +`.workflows/.state/migrations` against the install's migrations directory) — it +degrades to **read-only raw-embed mode with a banner and no events**. The bridge +never runs migrations; that is `workflow-start`'s boot, in a session. Both +detection mechanisms are fragile by design and are replaced when the proposed +read-only currency verb lands (`plans/UPSTREAM.md` #2). Shallow/grafted clones +degrade to live-only mode (no durable spine). + +## Tests + +```sh +pnpm test # all packages (vitest) +pnpm typecheck # tsc --noEmit +pnpm build # shared + the SPA +``` + +UI tests are self-contained — they never touch the product's `npm test` gates. +CI runs `.github/workflows/ui.yml` on every commit touching `ui/`. diff --git a/ui/app/index.html b/ui/app/index.html new file mode 100644 index 0000000000..08c58445cb --- /dev/null +++ b/ui/app/index.html @@ -0,0 +1,12 @@ + + + + + + workflow bridge + + +
+ + + diff --git a/ui/app/package.json b/ui/app/package.json new file mode 100644 index 0000000000..abf1e6335e --- /dev/null +++ b/ui/app/package.json @@ -0,0 +1,38 @@ +{ + "name": "@workflow-ui/app", + "private": true, + "version": "0.0.0", + "description": "The SPA — Phase 1: the read-only mirror.", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "test": "vitest run", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@workflow-ui/shared": "workspace:*", + "clsx": "^2.1.0", + "cmdk": "^1.0.4", + "mermaid": "^11.4.0", + "react": "^18.3.0", + "react-dom": "^18.3.0", + "react-markdown": "^9.0.0", + "react-router-dom": "^6.28.0", + "remark-gfm": "^4.0.0", + "shiki": "^1.24.0" + }, + "devDependencies": { + "@testing-library/react": "^16.1.0", + "@types/react": "^18.3.0", + "@types/react-dom": "^18.3.0", + "@vitejs/plugin-react": "^4.3.0", + "autoprefixer": "^10.4.20", + "jsdom": "^25.0.0", + "postcss": "^8.4.49", + "tailwindcss": "^3.4.15", + "typescript": "^5.6.0", + "vite": "^6.0.0", + "vitest": "^2.1.0" + } +} diff --git a/ui/app/postcss.config.js b/ui/app/postcss.config.js new file mode 100644 index 0000000000..2aa7205d4b --- /dev/null +++ b/ui/app/postcss.config.js @@ -0,0 +1,6 @@ +export default { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +}; diff --git a/ui/app/src/App.tsx b/ui/app/src/App.tsx new file mode 100644 index 0000000000..8e9b2c32a6 --- /dev/null +++ b/ui/app/src/App.tsx @@ -0,0 +1,220 @@ +// The app frame (spec 6): project rail · active surface · context panel. +// Phase 1 is the read-only mirror — the palette navigates, nothing acts. +import { useEffect, useState } from 'react'; +import { Routes, Route, NavLink, Navigate, useNavigate, useLocation } from 'react-router-dom'; +import { api, useLive, type Health, type LobbyData, type QueueRowData } from './api'; +import { BridgeBanner, causesFromHealth } from './components/BridgeBanner'; +import { Lobby } from './screens/Lobby'; +import { Channel } from './screens/Channel'; +import { Artifact } from './screens/Artifact'; +import { Queue } from './screens/Queue'; +import { SessionThread } from './screens/SessionThread'; +import { Roadmap } from './screens/Roadmap'; +import { Palette } from './Palette'; +import { IdentityBadge } from './components/IdentityBadge'; +import { CaptureButton } from './components/CaptureButton'; + +// Storage and matchMedia can be absent or throwing (privacy modes, test +// environments) — the theme must still resolve. +function safeStorage(op: () => string | null): string | null { + try { + return op(); + } catch { + return null; + } +} + +function useTheme(): [boolean, () => void] { + const [dark, setDark] = useState(() => { + const stored = safeStorage(() => localStorage.getItem('theme')); + if (stored) return stored === 'dark'; + try { + return window.matchMedia('(prefers-color-scheme: dark)').matches; + } catch { + return false; + } + }); + useEffect(() => { + document.documentElement.classList.toggle('dark', dark); + safeStorage(() => (localStorage.setItem('theme', dark ? 'dark' : 'light'), null)); + }, [dark]); + return [dark, () => setDark((d) => !d)]; +} + +export default function App() { + const { data: health } = useLive(() => api.health()); + const { data: lobby } = useLive(() => api.lobby()); + const { data: queue } = useLive<{ rows: QueueRowData[] }>(() => api.queue()); + const [dark, toggleTheme] = useTheme(); + const [paletteOpen, setPaletteOpen] = useState(false); + const navigate = useNavigate(); + const location = useLocation(); + const [bridgeSeenAt, setBridgeSeenAt] = useState(Date.now()); + + // Report focus for time-based, thread-scoped suppression (spec 5). The + // focused thread is derived from the route (/s/:id maps to no topic here; + // /c/:wu is the channel). Health polling doubles as the watchdog heartbeat. + useEffect(() => { + const channel = location.pathname.match(/^\/c\/([^/]+)/)?.[1] ?? null; + // A genuine interaction (navigating here counts) re-arms escalation and + // records focus. The heartbeat only keeps app-connected fresh — and only + // while the tab is VISIBLE, so a backgrounded tab neither suppresses a + // push nor re-arms a stuck gate (round-9 finding). + api.reportActivity(channel, true); + const iv = setInterval(() => { + if (document.visibilityState === 'visible') api.reportActivity(channel, false); + }, 60_000); + const onInteract = () => api.reportActivity(channel, true); + const onVis = () => document.visibilityState === 'visible' && api.reportActivity(channel, true); + window.addEventListener('pointerdown', onInteract, { passive: true }); + window.addEventListener('keydown', onInteract); + document.addEventListener('visibilitychange', onVis); + return () => { + clearInterval(iv); + window.removeEventListener('pointerdown', onInteract); + window.removeEventListener('keydown', onInteract); + document.removeEventListener('visibilitychange', onVis); + }; + }, [location.pathname]); + + useEffect(() => { + if (health) setBridgeSeenAt(Date.now()); + }, [health]); + // Watchdog: if health hasn't refreshed within 90s, the bridge may be down. + const [bridgeStale, setBridgeStale] = useState(false); + useEffect(() => { + const iv = setInterval(() => setBridgeStale(Date.now() - bridgeSeenAt > 90_000), 15_000); + return () => clearInterval(iv); + }, [bridgeSeenAt]); + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if ((e.metaKey || e.ctrlKey) && e.key === 'k') { + e.preventDefault(); + setPaletteOpen((o) => !o); + } + }; + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }, []); + + const units: { name: string; type: string }[] = []; + if (lobby && !lobby.empty && lobby.detail) { + for (const [group, type] of Object.entries({ + epics: 'epic', + features: 'feature', + bugfixes: 'bugfix', + quick_fixes: 'quick-fix', + cross_cutting: 'cross-cutting', + })) { + for (const u of lobby.detail[group]?.work_units ?? []) units.push({ name: u.name, type }); + } + } + const durableCounts = lobby && !lobby.empty ? lobby.durable.counts : {}; + + return ( +
+ {/* Project rail */} + + + {/* Active surface */} +
+ {bridgeStale && } + {health && + causesFromHealth(health).map((c) => )} + + } /> + } /> + } /> + } /> + } /> + } /> + } /> + +
+ + setPaletteOpen(false)} + units={units} + onNavigate={(to) => { + setPaletteOpen(false); + navigate(to); + }} + /> +
+ ); +} diff --git a/ui/app/src/Palette.tsx b/ui/app/src/Palette.tsx new file mode 100644 index 0000000000..028ebddab3 --- /dev/null +++ b/ui/app/src/Palette.tsx @@ -0,0 +1,58 @@ +// cmdk palette — navigation only (Phase 1: it does not act). +import { Command } from 'cmdk'; + +export function Palette({ + open, + onClose, + units, + onNavigate, +}: { + open: boolean; + onClose: () => void; + units: { name: string; type: string }[]; + onNavigate: (to: string) => void; +}) { + if (!open) return null; + return ( +
+
e.stopPropagation()}> + + + + Nothing matches. + {/* The top-level destinations — the same set the rail offers. */} + {[ + { to: '/lobby', label: 'Lobby' }, + { to: '/queue', label: 'Queue' }, + { to: '/roadmap', label: 'Roadmap' }, + ].map((r) => ( + onNavigate(r.to)} + > + {r.label} + + ))} + {units.map((u) => ( + onNavigate(`/c/${u.name}`)} + > + #{u.name} {u.type} + + ))} + + +
+
+ ); +} diff --git a/ui/app/src/api.ts b/ui/app/src/api.ts new file mode 100644 index 0000000000..737efae3c0 --- /dev/null +++ b/ui/app/src/api.ts @@ -0,0 +1,372 @@ +// Data layer: fetch + the bridge's SSE stream. Live-follow works by +// event-driven refetch — the SSE stream signals change, the API answers with +// engine-sourced state; the app never derives workflow state itself. +import { useEffect, useState, useCallback, useRef } from 'react'; + +export type Health = { + ok: boolean; + mode: 'live' | 'replay'; + bridgeMode: 'full' | 'read-only' | 'live-only'; + project: string; + epoch: string | null; + bannerReasons: string[]; + version: { productVersion: string | null; supported: boolean; pendingMigrations: string[]; shallow: boolean }; + replay?: { state: string; atTurn: number; fixture: string }; +}; + +export type LobbyData = + | { empty: true; reason: string } + | { + empty: false; + detail: any; + overviewRender: string | null; + knowledge: { state: 'ready' | 'not-ready' | 'unknown' }; + durable: { counts: Record; rows: any[] }; + failedCaptures?: FailedCapture[]; + roadmap: { horizons: any[]; totals: Record; itemCount: number } | null; + baseline: { status: string } | null; + }; + +export type ChannelData = { + name: string; + workType: string; + status: string; + spine: any[]; + drawer: any[]; + threads: { name: string; lifecycle: string; phase: string | null; cues: any }[]; + embed: string | null; + artifacts: { path: string; phase: string }[]; + presence?: { phase?: string; topic?: string; held?: boolean; live?: boolean; session_id?: string }[]; + humansViewing?: { humanId: string; name: string; lastSeenAt: string }[]; + inferredSessions?: { phase: string; topic: string; mtime: string; inferred: true }[]; + telemetry?: TopicTelemetry[]; + planFormat?: string; + agentsReading?: number; +}; + +// Phase 6: who the request is (single-user is always the sentinel "You"). +export type WhoamiData = { + mode: 'single' | 'github'; + human: { id: string; name: string; member: boolean; sentinel: boolean; githubLogin: string | null }; +}; + +// Phase 6: the ownership + comment overlay the bridge joins onto a gate card. +export type GateOwnership = { + owner?: { id: string | null; name: string | null; stuck?: boolean; isYou: boolean }; + canAnswer?: boolean; + watching?: boolean; + unreadComments?: number; + commentCount?: number; + resolvedExternallyAt?: string; +}; + +export type CommentData = { id: number; humanId: string; author: string; body: string; createdAt: string; read: boolean }; + +export type FailedCapture = { + id: string; + kind: string; + payload: string; + provenance: { source: string; author?: string } | null; + error: string | null; + failedAt: string; +}; + +export type TopicTelemetry = { + topic: string; + status: string; + currentPhase: string | null; + currentTask: string | null; + completedPhases: string[]; + completedTasks: string[]; + fixAttempts: number; + analysisCycles: number; + depBlocked: { topic: string; reason?: string }[]; + consolidation: { + gated: boolean; + bank: any[]; + staging: Record; + consolidatedPhases: string[]; + }; + commitsLanded: { sha: string; subject: string }[]; + agentsActive: number; +}; + +export type PlanTask = { id: string; title: string; phase: string | null; status: string; priority: number; dependsOn: string[] }; +export type PlanDagData = + | { format: 'local-markdown' | 'tick'; tasks: PlanTask[] } + | { format: 'linear'; linkOut: string | null } + | { format: 'unknown'; tasks: [] }; + +export type StructureNode = { label: string; status?: string; anchor?: string; detail?: string }; +export type ClaimChipData = { command: string; result?: string; anchor?: string; verified?: boolean }; +export type ArtifactStructure = { + kind: string; + sections: StructureNode[]; + sources?: StructureNode[]; + consultReferences?: StructureNode[]; + claims: ClaimChipData[]; + available: boolean; +}; +export type WhatMovedData = + | { state: 'none' } + | { state: 'unread'; base: string; diff: string } + | { state: 'lost' }; + +export type ArtifactData = { + workUnit: string; + path: string; + phase: string; + content: string; + structure: ArtifactStructure; + whatMoved: WhatMovedData; +}; + +export type HistoryEntry = { sha: string; date: string; subject: string; author: string }; +export type RoadmapData = + | { exists: false } + | { + exists: true; + horizons: any[]; + items: any[]; + totals: Record; + sessions: any[]; + activeSession: any; + }; + +async function getJson(url: string): Promise { + const res = await fetch(url); + if (!res.ok) throw new Error(`${url}: ${res.status}`); + return res.json(); +} + +// The bearer token for mutating calls and the event stream (trust boundary). +let tokenPromise: Promise | null = null; +export function bridgeToken(): Promise { + if (!tokenPromise) { + tokenPromise = fetch('/api/token') + .then((r) => r.json()) + .then((b) => b.token ?? null) + .catch(() => null); + } + return tokenPromise; +} + +async function postJson(url: string, body: Record): Promise { + const token = await bridgeToken(); + const res = await fetch(url, { + method: 'POST', + headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) }, + body: JSON.stringify(body), + }); + const json = await res.json().catch(() => ({})); + if (!res.ok && res.status !== 409) throw new Error(json.error ?? `${url}: ${res.status}`); + return json; +} + +export type GateCardData = { + id: string; + kind: string; + source: string; + surface?: string; + question?: string; + context: string; + options: { key: string; word?: string; label: string; recommended: boolean; form: string }[]; + confirm: 'tap' | 'typed'; + state: string; + address: { workUnit?: string; topic?: string; phase?: string }; + session: { bridgeSessionId: string; askOrdinal: number }; + openedAt: string; + relayDiverged?: boolean; +} & GateOwnership; + +export type QueueRowData = { + tier: 'live' | 'durable'; + kind: string; + address: { workUnit?: string; topic?: string; phase?: string }; + stage: 0 | 1 | 2; + since: string; + detail: string; + gateId?: string; + bridgeSessionId?: string; + askPreview?: string; + escalated?: boolean; + stuck?: boolean; + buildOrderPos?: number; + owner?: { id: string | null; name: string | null; isYou: boolean }; + watching?: boolean; + unreadComments?: number; +}; + +export type SessionData = { + bridgeSessionId: string; + address: { workUnit?: string; topic?: string; phase?: string }; + state: string; + openGate: GateCardData | null; + lastError?: string; +}; + +export type ThreadData = { + state: string; + openGate: GateCardData | null; + lastError?: string; + records: Record[]; + asks: { ordinal: number; gateId: string; answered: boolean; kind: string; turn: number }[]; +}; + +export type DigestStripEntry = { + channel: string; + landed: { commits: { sha: string; subject: string }[]; artifacts: string[] }; + next: string | null; + emittedAt: string; +}; + +export const api = { + health: () => getJson('/health'), + lobby: () => getJson('/api/lobby'), + digests: () => getJson<{ strip: DigestStripEntry[] }>('/api/digests'), + reportActivity: (focusedThread: string | null, interaction = false) => + postJson('/api/activity', { appConnected: true, focusedThread, interaction }).catch(() => ({})), + channel: (wu: string) => getJson(`/api/channel/${encodeURIComponent(wu)}`), + artifact: (wu: string, path: string) => + getJson(`/api/artifact/${encodeURIComponent(wu)}?path=${encodeURIComponent(path)}`), + history: (wu: string, path: string) => + getJson<{ timeline: HistoryEntry[] }>(`/api/history/${encodeURIComponent(wu)}?path=${encodeURIComponent(path)}`), + roadmap: () => getJson('/api/roadmap'), + plan: (wu: string, topic: string) => + getJson<{ dag: PlanDagData }>(`/api/plan/${encodeURIComponent(wu)}/${encodeURIComponent(topic)}`), + // Advance the read-ref for the what-moved diff base — a deliberate view. + markArtifactRead: (wu: string, path: string) => + postJson(`/api/artifact/${encodeURIComponent(wu)}/read`, { path }).catch(() => ({})), + queue: () => getJson<{ rows: QueueRowData[] }>('/api/queue'), + sessions: () => getJson<{ sessions: SessionData[] }>('/api/sessions'), + thread: (id: string) => getJson(`/api/session/${encodeURIComponent(id)}/thread`), + startSession: (address: Record, entryPrompt?: string) => + postJson<{ bridgeSessionId: string; state: string }>(`/api/session/start`, { address, entryPrompt }), + // Every SPA answer IS a real user gesture (a click / Enter), so it attests + // UI-origin — the typed-confirm attestation the bridge requires (Phase 7). + answerGate: (gateId: string, text: string, bridgeSessionId?: string) => + postJson<{ ok: boolean; state: string; reason?: string; error?: string; unreadComments?: number; deepLink?: string }>( + `/api/gate/${gateId}/answer`, + { text, bridgeSessionId, attestation: 'ui-gesture' }, + ), + endSession: (id: string) => postJson<{ ok: boolean }>(`/api/session/${encodeURIComponent(id)}/end`, {}), + // Resume an interrupted/errored session (no open ask) with a free-text turn. + resumeSession: (id: string, text: string) => + postJson<{ ok: boolean; state: string; reason?: string; error?: string }>(`/api/session/${encodeURIComponent(id)}/resume`, { text }), + // Phase 6 — identity. + whoami: () => getJson('/api/whoami'), + login: (githubLogin: string, token?: string) => + postJson<{ human?: { id: string; name: string; member: boolean }; warning?: string; error?: string }>('/api/login', { githubLogin, token }), + logout: () => postJson<{ ok: boolean }>('/api/logout', {}), + // Phase 6 — gate ownership (routing). + claimGate: (gateId: string) => postJson<{ ok: boolean; ownerId: string }>(`/api/gate/${gateId}/claim`, {}), + claimChannel: (wu: string) => postJson<{ ok: boolean }>(`/api/channel/${encodeURIComponent(wu)}/claim`, {}), + // Phase 6 — comments (never push). + comments: (target: { gateId?: string; artifact?: string }) => { + const q = target.gateId ? `gateId=${target.gateId}` : `artifact=${encodeURIComponent(target.artifact ?? '')}`; + return getJson<{ comments: CommentData[] }>(`/api/comments?${q}`); + }, + addComment: (target: { gateId?: string; artifact?: string }, body: string) => + postJson<{ id: number }>('/api/comments', { ...target, body }), + markCommentsRead: (target: { gateId?: string; artifact?: string }) => + postJson<{ ok: boolean }>('/api/comments/read', target).catch(() => ({ ok: false })), + // Phase 6 — the capture gesture. + capture: (kind: string, payload: string, provenance: Record) => + postJson<{ ok: boolean; captureId?: string; error?: string }>('/api/capture', { kind, payload, provenance }), + captures: () => getJson<{ failed: FailedCapture[] }>('/api/captures'), + retryCapture: (id: string) => postJson<{ ok: boolean }>(`/api/capture/${encodeURIComponent(id)}/retry`, {}), + discardCapture: (id: string) => postJson<{ ok: boolean }>(`/api/capture/${encodeURIComponent(id)}/discard`, {}), + // Attachments — materialize a file into the gitignored cache and get back its + // project-relative path; the caller references it in the turn so the session's + // Read tool picks it up. + uploadAttachment: async ( + file: File, + ctx: { workUnit?: string; bridgeSessionId?: string }, + ): Promise<{ path?: string; error?: string }> => { + const dataBase64 = await fileToBase64(file); + return postJson<{ path?: string; error?: string }>('/api/attachments', { name: file.name, dataBase64, ...ctx }); + }, +}; + +function fileToBase64(file: File): Promise { + return new Promise((resolve, reject) => { + const r = new FileReader(); + r.onload = () => resolve(String(r.result).split(',')[1] ?? ''); + r.onerror = () => reject(new Error('read failed')); + r.readAsDataURL(file); + }); +} + +// One shared SSE subscription; consumers register a refetch callback that +// fires (debounced) on any domain event, and a hard-reset on epoch change. +type Listener = () => void; +const listeners = new Set(); +let source: EventSource | null = null; + +async function openStream(): Promise { + // EventSource is absent in some environments (jsdom tests, older embeds) — + // degrade to fetch-on-mount without live-follow rather than crashing. + if (typeof EventSource === 'undefined') return; + const token = await bridgeToken(); + source = new EventSource(token ? `/events?token=${token}` : '/events'); + let timer: ReturnType | null = null; + const poke = () => { + if (timer) clearTimeout(timer); + timer = setTimeout(() => { + for (const l of listeners) l(); + }, 250); + }; + source.onmessage = poke; + source.addEventListener('control', (ev) => { + try { + const msg = JSON.parse((ev as MessageEvent).data); + if (msg.control === 'epoch-changed') window.location.reload(); + else poke(); + } catch { + poke(); + } + }); + source.onerror = () => { + // EventSource auto-reconnects; nothing to do but wait. + }; +} + +let streamStarted = false; +function ensureStream(): void { + if (streamStarted) return; + streamStarted = true; + void openStream(); +} + +export function useLive(fetcher: () => Promise, deps: unknown[] = []): { + data: T | null; + error: string | null; + reload: () => void; +} { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + const fetcherRef = useRef(fetcher); + fetcherRef.current = fetcher; + + const reload = useCallback(() => { + fetcherRef + .current() + .then((d) => { + setData(d); + setError(null); + }) + .catch((e) => setError(String(e.message ?? e))); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, deps); + + useEffect(() => { + ensureStream(); + reload(); + listeners.add(reload); + return () => { + listeners.delete(reload); + }; + }, [reload]); + + return { data, error, reload }; +} diff --git a/ui/app/src/components/BatchScreenCard.tsx b/ui/app/src/components/BatchScreenCard.tsx new file mode 100644 index 0000000000..ecb2f4f3be --- /dev/null +++ b/ui/app/src/components/BatchScreenCard.tsx @@ -0,0 +1,28 @@ +// BatchScreenCard (catalog: P2, intent 3) — the lanes' batch shape: the +// finding-batch DISPLAY rendered above its approval menu, a stop, never +// auto-advanced. The findings are ALWAYS visible before the approve/veto row +// (the "answered without seeing it" failure this component exists to prevent). +import { GateCard } from './GateCard'; +import { EngineEmbed } from './EngineEmbed'; +import type { GateCardData } from '../api'; + +export function BatchScreenCard({ + card, + onAnswer, + busy, +}: { + card: GateCardData; + onAnswer: (text: string) => void; + busy?: boolean; +}) { + return ( +
+ {/* The findings, verbatim from the engine (mono truth) — the context + carries the DISPLAY: finding batch body the parser paired in. */} + {card.context && } + {/* The approve/veto row reuses the GateCard mechanics but without a + second copy of the context. */} + +
+ ); +} diff --git a/ui/app/src/components/BridgeBanner.tsx b/ui/app/src/components/BridgeBanner.tsx new file mode 100644 index 0000000000..cab7fbfee8 --- /dev/null +++ b/ui/app/src/components/BridgeBanner.tsx @@ -0,0 +1,45 @@ +// BridgeBanner (catalog: 0/2, N5) — degraded states, a CLOSED list extended +// whenever any spec adds a degradation. One banner per cause. +export type BannerCause = + | 'version-skew' + | 'pending-migrations' + | 'read-only-mirror' + | 'bridge-unreachable' + | 'live-only'; + +const COPY: Record string> = { + 'version-skew': (d) => `Product version outside the bridge's supported range${d ? ` — ${d}` : ''}. Read-only.`, + 'pending-migrations': (d) => + `This project has pending migrations${d ? ` (${d})` : ''} — run /workflow-start in a terminal session to migrate. Read-only until then.`, + 'read-only-mirror': (d) => `Another bridge is driving this project${d ? ` from ${d}` : ''} — this one mirrors, read-only.`, + 'bridge-unreachable': () => 'The bridge is unreachable — showing the last known state.', + 'live-only': () => 'Incomplete git history (shallow/partial clone) — live view only, no durable spine.', +}; + +export function causesFromHealth(h: { + bridgeMode: string; + version: { supported: boolean; pendingMigrations: string[]; shallow: boolean }; + bannerReasons?: string[]; +}): { cause: BannerCause; detail?: string }[] { + const causes: { cause: BannerCause; detail?: string }[] = []; + if (!h.version.supported) causes.push({ cause: 'version-skew' }); + if (h.version.pendingMigrations.length > 0) { + causes.push({ cause: 'pending-migrations', detail: `${h.version.pendingMigrations.length} pending` }); + } + if (h.bridgeMode === 'live-only') causes.push({ cause: 'live-only' }); + // The lease-lost read-only mirror — its reason string names the host. + const mirror = (h.bannerReasons ?? []).find((r) => /read-only mirror/.test(r)); + if (mirror) { + const host = mirror.match(/from (\S+)/)?.[1]; + causes.push({ cause: 'read-only-mirror', detail: host }); + } + return causes; +} + +export function BridgeBanner({ cause, detail }: { cause: BannerCause; detail?: string }) { + return ( +
+ {COPY[cause](detail)} +
+ ); +} diff --git a/ui/app/src/components/CaptureButton.tsx b/ui/app/src/components/CaptureButton.tsx new file mode 100644 index 0000000000..ebeabfe9c7 --- /dev/null +++ b/ui/app/src/components/CaptureButton.tsx @@ -0,0 +1,123 @@ +// Phase 6 §3 — the capture gesture. Any human parks a note as an inbox item. +// Acknowledge OPTIMISTICALLY (the toast appears the instant you submit, before +// the ephemeral capture session finishes), reconcile on completion. A failure +// is never a vanishing toast — it becomes a durable lobby row (server-side), +// and the toast says so. +import { useState } from 'react'; +import { api } from '../api'; + +type Toast = { text: string; tone: 'pending' | 'ok' | 'fail' }; + +const KINDS: { value: string; label: string }[] = [ + { value: 'idea', label: 'idea' }, + { value: 'bug', label: 'bug' }, + { value: 'quickfix', label: 'quick-fix' }, + { value: 'roadmap', label: 'roadmap (→ inbox)' }, +]; + +export function CaptureButton({ + provenance, + seed, + label = '✦ capture', + compact = false, + align = 'left', + direction = 'down', +}: { + provenance?: Record; + seed?: string; // prefill (e.g. a message or selection being parked) + label?: string; + compact?: boolean; + // Where the popover opens relative to the trigger — so a left-rail / bottom + // button doesn't push a fixed-width popover off-screen (it did: clipped past + // the left edge from the rail). `left` opens rightward; `up` opens above. + align?: 'left' | 'right'; + direction?: 'up' | 'down'; +}) { + const popPos = `${align === 'right' ? 'right-0' : 'left-0'} ${direction === 'up' ? 'bottom-full mb-1' : 'top-full mt-1'}`; + const [open, setOpen] = useState(false); + const [kind, setKind] = useState('idea'); + const [payload, setPayload] = useState(seed ?? ''); + const [toast, setToast] = useState(null); + + const submit = async () => { + const text = payload.trim(); + if (text === '') return; + setOpen(false); + setPayload(seed ?? ''); + // Optimistic: the gesture is acknowledged at once (seconds, not ms, for the + // ephemeral session — spec risk: latency must never block the gesture). + setToast({ text: 'Capturing…', tone: 'pending' }); + try { + const res = await api.capture(kind, text, { source: 'capture-gesture', ...provenance }); + if (res.ok) setToast({ text: 'Captured to the inbox.', tone: 'ok' }); + else setToast({ text: 'Capture failed — kept on the lobby to retry.', tone: 'fail' }); + } catch { + setToast({ text: 'Capture failed — kept on the lobby to retry.', tone: 'fail' }); + } + setTimeout(() => setToast(null), 4000); + }; + + return ( +
+ + {open && ( +
+ +