From 2ef7806f9ac9d7d1876e3ba756273af5c8232612 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 12:51:44 -0400 Subject: [PATCH 01/13] docs(program): wave 3 briefs Co-Authored-By: Claude Fable 5 --- tasks/2026-07-20-fw3-shell-brief.md | 29 +++++++++++++++++++++++ tasks/2026-07-20-fw3-tmux-ui-brief.md | 33 +++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 tasks/2026-07-20-fw3-shell-brief.md create mode 100644 tasks/2026-07-20-fw3-tmux-ui-brief.md diff --git a/tasks/2026-07-20-fw3-shell-brief.md b/tasks/2026-07-20-fw3-shell-brief.md new file mode 100644 index 00000000..a30e4295 --- /dev/null +++ b/tasks/2026-07-20-fw3-shell-brief.md @@ -0,0 +1,29 @@ +# FW3-SHELL — Command Center landing + navigation + attention unification + launch rail (Wave 3) + +Lane: FW3-SHELL · Machine: homelinux · Worktree: `~/dev/wt/ac-fw3-shell` · Branch: `refactor/fw3-shell` (off `refactor/frontend-command-center`; local, do NOT push) +Plan: `tasks/2026-07-20-frontend-tmux-ux-master-plan.md` (Workstream A) · Evidence: `tasks/2026-07-20-frontend-ux-study-findings.md` §§0-1 (read first) · Acceptance: `tasks/frontend-ux-acceptance-checklist.md` Wave 3. + +## Mission + +Make the first paint of the app the fleet. Kill the v0.2.0 landing, unify the duplicated navigation and attention surfaces, and give launch a persistent home. This is the wave the owner SEES — mobile-first quality matters. Load the `frontend-product-design` skill approach you normally use; keep the existing design tokens. + +## Work items + +1. **Command Center landing.** `/` becomes the Command Center: promote the current `/tmux` experience (`TmuxPageClient`) to the root route, framed with an attention summary strip (count + top item, tapping opens the attention surface) and the launch rail (item 4). Delete the legacy hero-card page; relocate its quick stats/usage into `/settings` (usage section) — do not lose data surfaces, move them. `/tmux` becomes a redirect to `/`. Signin `callbackUrl` and PWA `manifest.json` `start_url` point at `/`. Push deep links that used `/orchestrator` keep working (item 3 owns where they land). +2. **Navigation unification.** Bottom tabs become: Command Center (`/`), Attention, Sessions, More. Remove the header hamburger — the drawer opens ONLY from More; the header slims to logo + connection state + attention bell + theme/account. One breakpoint contract: a single `useIsMobile` source with named constants (nav/mobile detection 768; the Command Center's internal desktop/mobile shell switch may keep 1024 but must consume the same hook with an explicit parameter, no ad-hoc `md:`-vs-JS divergence for the shell). Consistent ≥44px tap targets on all nav. +3. **One attention surface.** Merge `OrchestratorModal` (header-bell bottom sheet) and `OrchestratorPageClient` (full page) into ONE component tree fed by `useAttentionQueue`: rendered as a sheet on desktop (bell) and a full page on mobile (tab + bell both route there). Delete the duplicated implementation. `/orchestrator` stays as the route for the page presentation (deep links unchanged). The Fleet tab content stays as-is inside it (Wave 4 reworks fleet internals). +4. **Launch rail.** A persistent launch entry visible on Command Center and Sessions: New (opens `MobileLaunchSheet` — now the single launch surface on ALL form factors), Recent (recent-launch store), Open existing (tmux open flow). Delete `components/SpawnSessionDialog.tsx` (legacy, unreferenced). Centralize provider/template definitions: one module exporting `LAUNCH_PROVIDERS` + `SESSION_TEMPLATES`, consumed by `MobileLaunchSheet` and `session-generator` (make `RepoPicker` recent-first while you're in there; keep its tree browse as secondary). +5. **Tests.** Update/extend Playwright smoke + unit tests for: `/` renders Command Center on mobile+desktop viewports, `/tmux` redirects, bell and tab reach the same attention surface, launch rail opens the sheet, deleted surfaces gone. All existing suites green. + +## Ownership firewall + +You may edit: `apps/dashboard/src/app/**` (route files, layout.tsx, manifest/signin bits), `src/components/layout/**`, `src/components/orchestrator/**`, `src/components/launch/**`, `src/components/session-generator/**`, `src/components/SpawnSessionDialog.tsx` (delete), `src/components/notifications/**`, `src/stores/ui.ts` + `src/stores/orchestrator.ts` (modal/nav state), `src/hooks/useIsMobile.ts`, `public/manifest.json`, related tests. You may NOT edit: `src/components/tmux/**` (FW3-TMUX-UI owns it — consume `TmuxPageClient` as-is via import/move of the ROUTE file only), `src/components/terminal/**`, `src/components/session/**`, terminal hooks, `packages/**`, `services/**`, `agents/**`, `deploy/**`. If promoting `TmuxPageClient` to `/` requires a prop change inside it, propose it in your handoff instead of editing the file. + +## Gates + +`pnpm lint && pnpm typecheck && pnpm test:ci && pnpm test:smoke:dashboard && pnpm build`. Commit per work item, prefix `feat(shell):`. ≤3 attempts per failure then hold. + +## Done + +Handoff `tasks/frontend-ux-handoffs/fw3-shell.md`, committed, then print exactly: +`FW3-SHELL FROZEN ` diff --git a/tasks/2026-07-20-fw3-tmux-ui-brief.md b/tasks/2026-07-20-fw3-tmux-ui-brief.md new file mode 100644 index 00000000..48c85ba8 --- /dev/null +++ b/tasks/2026-07-20-fw3-tmux-ui-brief.md @@ -0,0 +1,33 @@ +# FW3-TMUX-UI — Window strip, in-app tmux management, multi-terminal, scrollback pager (Wave 3) + +Lane: FW3-TMUX-UI · Machine: homelinux · Worktree: `~/dev/wt/ac-fw3-tmux-ui` · Branch: `refactor/fw3-tmux-ui` (off `refactor/frontend-command-center`; local, do NOT push) +Plan: Workstreams B/C · Evidence: findings doc §2 · Acceptance: checklist Wave 3. + +## Backend already available (Waves 1-2 — use it, don't rebuild it) + +- UI WebSocket topic `tmux.topology` relays debounced full-host topology snapshots (shape: `tests/fixtures/protocol/tmux-topology.json`) — emitted only by hosts whose agentd has `topology_events: true`; MOST HOSTS MAY NOT EMIT YET. +- 8 commands dispatchable via `POST /v1/sessions/:id/commands`: `new_window`, `kill_window`, `rename_window`, `split_pane` (direction/percent/cwd), `select_window`, `select_pane`, `resize_pane`, `zoom_pane`. +- `POST /v1/sessions/:id/scrollback` — capture modes visible/last_n/range/full, ≤5000 lines/request. + +## Work items + +1. **Topology store + fallback.** A store fed by the `tmux.topology` topic (per host). When a host emits no topology (old agentd / flag off), derive equivalent window/pane structure from the existing roster data (`useTmuxRosterData`) — the UI must be fully functional either way, with topology giving it real-time freshness. Feature-detect per host, no config. +2. **Window strip.** A compact tab strip above the terminal in the workbench (mobile + desktop): one tab per window of the attached pane's tmux session — name, index, active state, bell/activity dots (topology-fed when available). Tap = `select_window`. Long-press/context = rename (inline input → `rename_window`), close (`kill_window` — and when it's the session's LAST window, a hard confirm: "This ends the whole tmux session"). A "+" tab = `new_window` (optional cwd from the session's path). All dispatches optimistic with rollback on command error toast. +3. **Pane controls.** In the terminal toolbar/action sheet: split horizontal, split vertical (use percent only when the host tmux ≥ 3.1 — read the host/agent version from roster/host data; below that, plain split without `-l`), zoom toggle, select-pane arrows (mobile sheet), kill-pane (confirm). Desktop gets the collapsible `TmuxKeyBar` (currently mobile-only, `TerminalSurface.tsx` gates it): default collapsed, expansion persisted in settings store. +4. **Desktop 2-up multi-terminal.** The desktop workbench can split into two side-by-side independent terminals (two sessions/panes, each its own WS attach). Simple model: primary + secondary slot, close button on secondary, remembered per session pair. Do NOT touch the mobile single-terminal + persistent-host model; verify composition with `PersistentTerminalHost` (the background-terminal budget stays 1 — the visible pair are both foreground). +5. **Mobile quick-switch strip.** A horizontal strip of recent panes (chips w/ session title + status dot) above the mobile terminal for one-tap switching (feeds the same recents the launch rail uses). +6. **Scrollback pager.** "View history" action → overlay/sheet with virtualized older history fetched via the scrollback endpoint (range paging, "load older" at top, monospace, selectable/copyable, searchable via simple text filter). Do NOT attempt to prepend into the xterm buffer. +7. **Tests.** Unit tests for the topology store (topology-fed and roster-fallback paths), window-strip actions (dispatch payloads + last-window confirm), version gating of percent splits; Playwright smoke for strip render + pager open on mobile viewport. All suites green. + +## Ownership firewall + +You may edit: `apps/dashboard/src/components/tmux/**`, `src/components/terminal/**`, `src/components/session/**`, `src/hooks/**` (tmux/terminal hooks + new ones), `src/lib/tmuxKeys.ts`, `src/lib/api.ts` (additive client functions only), `src/lib/ws.ts` (additive topic only), a new store file (e.g. `src/stores/tmuxTopology.ts`) + `src/stores/settings.ts` (additive key-bar/recents prefs), related tests. You may NOT edit: `src/app/**` route files, `src/components/layout/**`, `src/components/orchestrator/**`, `src/components/launch/**` (FW3-SHELL owns those), `packages/**`, `services/**`, `agents/**`, `tests/fixtures/protocol/**`. No new dependencies. + +## Gates + +`pnpm lint && pnpm typecheck && pnpm test:ci && pnpm test:smoke:dashboard && pnpm build`. Commit per work item, prefix `feat(tmux-ui):`. ≤3 attempts per failure then hold. + +## Done + +Handoff `tasks/frontend-ux-handoffs/fw3-tmux-ui.md`, committed, then print exactly: +`FW3-TMUX-UI FROZEN ` From cf5bc54d8d12cc28d7d8d7fc373d783b24ae11f4 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 12:54:54 -0400 Subject: [PATCH 02/13] chore(program): wave 2 deployed; agentd rollout staged (held); wave 3 launched Co-Authored-By: Claude Fable 5 --- tasks/frontend-ux-log.md | 3 +++ tasks/frontend-ux-metrics.jsonl | 2 ++ 2 files changed, 5 insertions(+) diff --git a/tasks/frontend-ux-log.md b/tasks/frontend-ux-log.md index f1ed17bc..482a1ea7 100644 --- a/tasks/frontend-ux-log.md +++ b/tasks/frontend-ux-log.md @@ -22,3 +22,6 @@ - ~20:30Z FW2-TERM froze at `9b34dfb` (attempt 1): gate re-run green, firewall clean (LayoutShell diff = 2 lines, addon-search only dep, protocol untouched), per-claim tests (250-frame zero-writes, same-instance persistence, scroll anchor). INTEGRATED @ e31f2d3 (lockfile auto-merge verified via frozen install). - ~20:45Z Wave-2 adversarial review: SHIP-WITH-NOTES, zero criticals; risk surfaces explicitly cleared (Zod semantics, tolerance ordering incl. known-type-invalid-payload still terminating, endpoint authz, terminal lifecycle, SSR). W1/W2 (fleet endpoint scan+N+1, auth-only role) + N2/N3 fixed via FW2-CONTRACTS-R2 `38c1a12` (scoped loads, bounded concurrency 4, operator role, terminate-invariant test, host_id ordering) — integrated @ bd934ef. N1/N4/N5 recorded as skipped (cosmetic/documented design). Final wave gate green. - WAVE 2 COMPLETE. PR to main next; after deploy: agentd binary rollout on heavisidelinux proceeds (CP tolerance now live). +- ~21:20Z Wave-2 MERGED (effab04) + DEPLOYED (SOURCE_COMMIT verified, health ok). PR-review fixes: scrollback 502 on agent-side failure; board policy text synced. +- agentd rollout: new binary BUILT at effab04 and staged at /tmp/agentd-new on heavisidelinux (temp worktree /tmp/ac-build-effab04; backup ~/.local/bin/agentd.bak-fw2 exists). In-place replacement of the RUNNING binary was blocked by the local permission policy — HELD FOR OWNER: run `rm ~/.local/bin/agentd && cp /tmp/agentd-new ~/.local/bin/agentd && systemctl --user restart agentd` on heavisidelinux, then optionally set `topology_events: true` under tmux: in ~/.config/agentd/config.yaml. Program continues regardless (Wave-3 UI has roster fallback). +- Wave 3 launched: FW3-SHELL + FW3-TMUX-UI codex lanes active on homelinux (activation verified). diff --git a/tasks/frontend-ux-metrics.jsonl b/tasks/frontend-ux-metrics.jsonl index d2631562..58776e12 100644 --- a/tasks/frontend-ux-metrics.jsonl +++ b/tasks/frontend-ux-metrics.jsonl @@ -8,3 +8,5 @@ {"ts":"2026-07-20T18:30:00Z","event":"wave_deployed","wave":1,"sha":"d565b00"} {"ts":"2026-07-20T19:10:00Z","event":"lane_frozen","lane":"FW2-CONTRACTS","attempt":1,"frozen_sha":"40bbd14","verdict":"accepted"} {"ts":"2026-07-20T20:50:00Z","event":"wave_complete","wave":2,"reviewer_verdict":"SHIP-WITH-NOTES","notes_closed_in":"FW2-CONTRACTS-R2","gate":"green"} +{"ts":"2026-07-20T21:20:00Z","event":"wave_deployed","wave":2,"sha":"effab04"} +{"ts":"2026-07-20T21:25:00Z","event":"wave_launched","wave":3,"lanes":["FW3-SHELL","FW3-TMUX-UI"]} From a5788afc62973c1727837338a30b4cbd39141613 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 13:26:54 -0400 Subject: [PATCH 03/13] feat(shell): Command Center landing at /, unified nav + attention surface, launch rail, legacy surfaces deleted (FW3-SHELL 5bba177) Co-Authored-By: Claude Fable 5 --- apps/dashboard/public/manifest.json | 2 +- apps/dashboard/src/app/(dashboard)/layout.tsx | 15 +- .../orchestrator/OrchestratorPageClient.tsx | 197 ---------- .../src/app/(dashboard)/orchestrator/page.tsx | 6 +- apps/dashboard/src/app/(dashboard)/page.tsx | 362 ++---------------- .../sessions/SessionsPageClient.tsx | 26 +- .../(dashboard)/settings/UsageOverview.tsx | 110 ++++++ .../src/app/(dashboard)/settings/page.tsx | 2 + .../app/(dashboard)/tmux/TmuxPageClient.tsx | 4 +- .../src/app/(dashboard)/tmux/page.tsx | 29 +- .../src/components/SpawnSessionDialog.tsx | 324 ---------------- .../src/components/launch/LaunchRail.tsx | 82 ++++ .../components/launch/MobileLaunchSheet.tsx | 75 ++-- .../src/components/launch/definitions.test.ts | 28 ++ .../templates.ts => launch/definitions.ts} | 28 +- .../components/launch/recentLaunchStore.ts | 65 ++++ .../components/layout/AttentionSettings.tsx | 6 +- .../components/layout/AttentionSummary.tsx | 69 ++++ .../src/components/layout/GlobalSidebar.tsx | 4 +- .../layout/HeaderConnectionStatus.tsx | 37 ++ .../src/components/layout/MobileBottomNav.tsx | 17 +- .../src/components/layout/MobileHeader.tsx | 27 -- .../src/components/layout/QuickSpawn.tsx | 8 +- .../src/components/layout/RecentSessions.tsx | 3 +- .../src/components/layout/SidebarNav.tsx | 42 +- apps/dashboard/src/components/layout/index.ts | 3 +- .../components/layout/shellContracts.test.ts | 35 ++ .../orchestrator/OrchestratorButton.tsx | 28 +- .../orchestrator/OrchestratorModal.tsx | 201 ---------- .../orchestrator/OrchestratorSurface.tsx | 284 ++++++++++++++ .../src/components/orchestrator/index.ts | 2 +- .../session-generator/RepoPicker.tsx | 47 ++- .../session-generator/SessionConfigStep.tsx | 20 +- .../src/components/session-generator/index.ts | 12 +- apps/dashboard/src/hooks/useIsMobile.ts | 5 +- apps/dashboard/src/stores/ui.ts | 2 - tasks/frontend-ux-handoffs/fw3-shell.md | 52 +++ tests/smoke/dashboard.spec.ts | 113 +++++- 38 files changed, 1121 insertions(+), 1251 deletions(-) delete mode 100644 apps/dashboard/src/app/(dashboard)/orchestrator/OrchestratorPageClient.tsx create mode 100644 apps/dashboard/src/app/(dashboard)/settings/UsageOverview.tsx delete mode 100644 apps/dashboard/src/components/SpawnSessionDialog.tsx create mode 100644 apps/dashboard/src/components/launch/LaunchRail.tsx create mode 100644 apps/dashboard/src/components/launch/definitions.test.ts rename apps/dashboard/src/components/{session-generator/templates.ts => launch/definitions.ts} (56%) create mode 100644 apps/dashboard/src/components/launch/recentLaunchStore.ts create mode 100644 apps/dashboard/src/components/layout/AttentionSummary.tsx create mode 100644 apps/dashboard/src/components/layout/HeaderConnectionStatus.tsx delete mode 100644 apps/dashboard/src/components/layout/MobileHeader.tsx create mode 100644 apps/dashboard/src/components/layout/shellContracts.test.ts delete mode 100644 apps/dashboard/src/components/orchestrator/OrchestratorModal.tsx create mode 100644 apps/dashboard/src/components/orchestrator/OrchestratorSurface.tsx create mode 100644 tasks/frontend-ux-handoffs/fw3-shell.md diff --git a/apps/dashboard/public/manifest.json b/apps/dashboard/public/manifest.json index bf762edf..0b80a631 100644 --- a/apps/dashboard/public/manifest.json +++ b/apps/dashboard/public/manifest.json @@ -3,7 +3,7 @@ "name": "Agent Commander", "short_name": "Commander", "description": "Mission control for AI agent sessions", - "start_url": "/orchestrator", + "start_url": "/", "scope": "/", "display": "standalone", "background_color": "#020617", diff --git a/apps/dashboard/src/app/(dashboard)/layout.tsx b/apps/dashboard/src/app/(dashboard)/layout.tsx index 3ae44126..958bffd4 100644 --- a/apps/dashboard/src/app/(dashboard)/layout.tsx +++ b/apps/dashboard/src/app/(dashboard)/layout.tsx @@ -1,10 +1,10 @@ import { Inter } from 'next/font/google'; +import Link from 'next/link'; import { ThemeToggle } from '@/components/ThemeToggle'; import { LayoutShell } from '@/components/layout'; -import { MobileHeader } from '@/components/layout/MobileHeader'; -import { SettingsButton } from '@/components/settings'; +import { HeaderConnectionStatus } from '@/components/layout/HeaderConnectionStatus'; import { AuthControls } from '@/components/auth/AuthControls'; -import { OrchestratorButton, OrchestratorModal } from '@/components/orchestrator'; +import { OrchestratorButton, OrchestratorSheet } from '@/components/orchestrator'; const inter = Inter({ subsets: ['latin'] }); @@ -19,16 +19,15 @@ export default function DashboardLayout({
@@ -38,7 +37,7 @@ export default function DashboardLayout({ {children} {/* Global overlay */} - + ); } diff --git a/apps/dashboard/src/app/(dashboard)/orchestrator/OrchestratorPageClient.tsx b/apps/dashboard/src/app/(dashboard)/orchestrator/OrchestratorPageClient.tsx deleted file mode 100644 index 5e719b11..00000000 --- a/apps/dashboard/src/app/(dashboard)/orchestrator/OrchestratorPageClient.tsx +++ /dev/null @@ -1,197 +0,0 @@ -'use client'; - -import { useMemo, useState } from 'react'; -import { - AlertTriangle, - Bell, - Bot, - ChevronDown, - ChevronRight, - Loader2, - Moon, - RefreshCw, -} from 'lucide-react'; -import { Button } from '@/components/ui/button'; -import { OrchestratorItem } from '@/components/orchestrator/OrchestratorItem'; -import { useAttentionQueue } from '@/hooks/useAttentionQueue'; -import { useOrchestratorFleet } from '@/hooks/useOrchestratorFleet'; -import { OrchestratorFleetCard } from '@/components/orchestrator/OrchestratorFleetCard'; -import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; -import { assignAttentionToOrchestrators } from '@/lib/attentionMerge'; - -export default function OrchestratorPageClient() { - const [idleExpanded, setIdleExpanded] = useState(false); - const [activeTab, setActiveTab] = useState('fleet'); - const { - items, - idledItems, - errors, - isLoading, - isRefreshing, - refresh, - dismissItem, - handleIdle, - handleUnidle, - summariesEnabled, - summaryStatusLoading, - } = useAttentionQueue(); - const fleet = useOrchestratorFleet(); - const runSessionById = useMemo(() => Object.fromEntries( - fleet.runs.map((run) => [run.id, run.session_id]) - ), [fleet.runs]); - const attentionByOrchestrator = useMemo(() => assignAttentionToOrchestrators( - items, - fleet.cards.map((card) => ({ - orchestratorId: card.session.id, - sessionIds: card.children.map((child) => child.id), - })), - runSessionById - ), [fleet.cards, items, runSessionById]); - - const refreshAll = async () => { - await Promise.all([refresh(), fleet.refresh()]); - }; - - return ( -
-
-
-
- -

Orchestrators

- {items.length > 0 && ( - - {items.length} - - )} -
-

- Supervise agent fleets, make decisions, and steer work without terminal focus. -

-
- -
- - {[...errors, ...fleet.errors].length > 0 && ( -
- - Some fleet sources are unavailable. Showing the data that loaded successfully. -
- )} - - - - - Fleet ({fleet.cards.length}) - - - Attention ({items.length}) - - - - - {fleet.isLoading && ( -
- Loading orchestrator fleet… -
- )} - {!fleet.isLoading && fleet.cards.length === 0 && ( -
- -

No orchestrator sessions are online

-

Sessions with the orchestrator role will appear here.

-
- )} - {fleet.cards.map((card) => ( - void refreshAll()} - /> - ))} -
- - - {!summaryStatusLoading && !summariesEnabled && ( -
- AI summaries are unavailable; queue actions and captured context still work. -
- )} -
- {isLoading && ( -
- - Loading attention sources… -
- )} - - {!isLoading && items.length === 0 && ( -
- -

Nothing needs your attention

-

New prompts, approvals, and failed runs will appear here.

-
- )} - - {items.length > 0 && ( -
- {items.map((item) => ( - void refresh()} - summariesEnabled={summariesEnabled} - /> - ))} -
- )} -
- - {idledItems.length > 0 && ( -
- - {idleExpanded && ( -
- {idledItems.map((item) => ( - void refresh()} - summariesEnabled={summariesEnabled} - /> - ))} -
- )} -
- )} -
-
-
- ); -} diff --git a/apps/dashboard/src/app/(dashboard)/orchestrator/page.tsx b/apps/dashboard/src/app/(dashboard)/orchestrator/page.tsx index 2c019bd0..9b63cf67 100644 --- a/apps/dashboard/src/app/(dashboard)/orchestrator/page.tsx +++ b/apps/dashboard/src/app/(dashboard)/orchestrator/page.tsx @@ -1,12 +1,12 @@ import { Suspense } from 'react'; -import OrchestratorPageClient from './OrchestratorPageClient'; +import { OrchestratorSurface } from '@/components/orchestrator/OrchestratorSurface'; export const dynamic = 'force-dynamic'; export default function OrchestratorPage() { return ( - Loading orchestrator...}> - + Loading attention...}> + ); } diff --git a/apps/dashboard/src/app/(dashboard)/page.tsx b/apps/dashboard/src/app/(dashboard)/page.tsx index 69eb18be..7beda5bf 100644 --- a/apps/dashboard/src/app/(dashboard)/page.tsx +++ b/apps/dashboard/src/app/(dashboard)/page.tsx @@ -1,349 +1,31 @@ -'use client'; +import { Suspense } from 'react'; +import { LayoutDashboard } from 'lucide-react'; +import { AttentionSummary } from '@/components/layout/AttentionSummary'; +import { LaunchRail } from '@/components/launch/LaunchRail'; +import TmuxPageClient from './tmux/TmuxPageClient'; -import { useCallback, useEffect, useMemo, useState } from 'react'; -import Link from 'next/link'; -import { useQuery, useQueryClient } from '@tanstack/react-query'; -import { Plus, RefreshCw, AlertCircle, Activity, Clock, Users } from 'lucide-react'; -import type { ServerToUIMessage, Session } from '@agent-command/schema'; -import { Button } from '@/components/ui/button'; -import { Card, CardContent } from '@/components/ui/card'; -import { SessionCard } from '@/components/SessionCard'; -import { SessionGenerator } from '@/components/session-generator'; -import { AccountUsage } from '@/components/analytics'; -import { getSessions, getHosts } from '@/lib/api'; -import { isHostOnline } from '@/lib/utils'; -import { useWebSocket } from '@/hooks/useWebSocket'; -import { useSessionStore } from '@/stores/session'; -import { useOrchestratorStore } from '@/stores/orchestrator'; - -export default function Dashboard() { - const queryClient = useQueryClient(); - const [showSpawnDialog, setShowSpawnDialog] = useState(false); - const { sessions, setSessions, updateSessions } = useSessionStore(); - const { getWaitingItems } = useOrchestratorStore(); - const workflowStatuses = 'RUNNING,STARTING,WAITING_FOR_INPUT,WAITING_FOR_APPROVAL,ERROR,IDLE'; - - // Fetch initial data - const { data: sessionData, isLoading: sessionsLoading } = useQuery({ - queryKey: ['sessions', 'dashboard'], - queryFn: () => getSessions({ include_archived: false, status: workflowStatuses }), - refetchInterval: false, - }); - - const { data: hostsData } = useQuery({ - queryKey: ['hosts'], - queryFn: getHosts, - }); - - // Update local state when query data changes - useEffect(() => { - if (sessionData?.sessions) { - setSessions(sessionData.sessions); - } - }, [sessionData, setSessions]); - - // WebSocket for real-time updates - const handleWebSocketMessage = useCallback((message: ServerToUIMessage) => { - if (message.type === 'sessions.changed') { - const payload = message.payload as { sessions: Session[]; deleted?: string[] }; - updateSessions(payload.sessions, payload.deleted); - } - }, [updateSessions]); - - useWebSocket( - [ - { type: 'sessions', filter: { include_archived: false, status: workflowStatuses } }, - ], - handleWebSocketMessage - ); - - const waitingOrchestratorItems = getWaitingItems(); - const waitingSessions = useMemo(() => { - if (waitingOrchestratorItems.length === 0) return []; - const byId = new Map(sessions.map((session) => [session.id, session])); - return waitingOrchestratorItems - .map((item) => item.sessionId ? byId.get(item.sessionId) : undefined) - .filter((session): session is (typeof sessions)[number] => Boolean(session)); - }, [sessions, waitingOrchestratorItems]); - - // Compute dashboard sections - const waitingSessionIds = useMemo(() => { - return new Set(waitingOrchestratorItems.map((item) => item.sessionId)); - }, [waitingOrchestratorItems]); - - const needsAttentionSessions = useMemo(() => { - return sessions.filter(s => - !s.idled_at && - (s.status === 'WAITING_FOR_INPUT' || - s.status === 'WAITING_FOR_APPROVAL' || - s.status === 'ERROR') && - !waitingSessionIds.has(s.id) - ); - }, [sessions, waitingSessionIds]); - - const activeSessions = useMemo(() => { - return sessions.filter(s => - !s.idled_at && - (s.status === 'RUNNING' || s.status === 'STARTING') - ); - }, [sessions]); - - const idleSessions = useMemo(() => { - return sessions.filter(s => s.status === 'IDLE' || s.idled_at); - }, [sessions]); - - const onlineHosts = useMemo(() => { - if (!hostsData?.hosts) return 0; - return hostsData.hosts.filter((h) => isHostOnline(h.last_seen_at || null)).length; - }, [hostsData]); - - const handleRefresh = () => { - queryClient.invalidateQueries({ queryKey: ['sessions'] }); - queryClient.invalidateQueries({ queryKey: ['hosts'] }); - }; - - const isLoading = sessionsLoading; +export const dynamic = 'force-dynamic'; +export default function CommandCenterPage() { return ( -
- {/* Header */} -
-

Dashboard

-
- - -
-
- -
- - -

New in v0.2.0

-

Tmux-first work, scoped memory, and safer autonomy

-

- Agent Commander now has a dedicated tmux manager, repo and global memory for every session, - and autonomous orchestrators with governance, budgets, and runtime reuse. -

-
- Open tmux - View automation - Search memory -
-
-
- - - - -

tmux

-

- Windows-first pane manager with the inline workbench. -

-
-
- - - - - -

Automation

-

- Orchestrators, workers, wakeups, governance, and run timelines. -

-
-
- - - - - -

Memory

-

- Repo and global memory with procedural and trajectory-backed knowledge. -

-
-
- -
- - {/* Quick Stats */} -
- - - -
- -
-
-

Active Sessions

-

{activeSessions.length}

-
-
-
- - - - -
- -
-
-

Needs Attention

-

{needsAttentionSessions.length}

-
-
-
- - - - -
- -
-
-

Hosts Online

-

{onlineHosts}

-
-
-
- - - - -
- -
-
-

Idle Sessions

-

{idleSessions.length}

-
-
-
- -
- - {/* Usage Widget */} -
- -
- - {/* Waiting Section */} -
-
-

- - Waiting -

- - - -
- {waitingSessions.length > 0 ? ( -
- {waitingSessions.slice(0, 6).map((session) => ( - host.id === session.host_id)} - /> - ))} +
+
+
+ + +
+

Command Center

+

Your live tmux fleet, ready for the next operator action.

- ) : ( -

No waiting sessions.

- )} +
+ +
- {/* Active Sessions Section */} - {activeSessions.length > 0 && ( -
-
-

- - Active Sessions -

- - - -
-
- {activeSessions.slice(0, 6).map(session => ( - h.id === session.host_id)} - /> - ))} -
-
- )} - - {/* Needs Attention Section removed from dashboard to keep focus on active flow */} - - {/* Idle Sessions Section */} - {idleSessions.length > 0 && ( -
-
-

- - Recently Idle -

- - - -
-
- {idleSessions.slice(0, 4).map(session => ( - h.id === session.host_id)} - /> - ))} -
-
- )} - - {/* Empty State */} - {!isLoading && sessions.length === 0 && ( - - - -

No Active Sessions

-

- Get started by creating a new session or check if your hosts are connected. -

-
- - - - -
-
-
- )} - - {/* Session Generator */} - setShowSpawnDialog(false)} - /> + Loading Command Center…
}> + +
); } diff --git a/apps/dashboard/src/app/(dashboard)/sessions/SessionsPageClient.tsx b/apps/dashboard/src/app/(dashboard)/sessions/SessionsPageClient.tsx index cb6fa17b..e4ee5f03 100644 --- a/apps/dashboard/src/app/(dashboard)/sessions/SessionsPageClient.tsx +++ b/apps/dashboard/src/app/(dashboard)/sessions/SessionsPageClient.tsx @@ -3,7 +3,7 @@ import { useSearchParams, useRouter } from 'next/navigation'; import { useState, useEffect, useCallback, useRef, useMemo } from 'react'; import { useQuery, useQueryClient } from '@tanstack/react-query'; -import { Search, Keyboard, CheckSquare, Square, Archive, GripVertical, Download, Plus } from 'lucide-react'; +import { Search, Keyboard, CheckSquare, Square, Archive, GripVertical, Download } from 'lucide-react'; import { DndContext, DragEndEvent, useSensor, useSensors, PointerSensor } from '@dnd-kit/core'; import { SessionList } from '@/components/SessionList'; import { Button } from '@/components/ui/button'; @@ -11,7 +11,7 @@ import { BulkActionToolbar } from '@/components/BulkActionToolbar'; import { CommandPalette, useCommandPalette } from '@/components/search/CommandPalette'; import { ShortcutsHelp, useShortcutsHelp } from '@/components/shortcuts/ShortcutsHelp'; import { ImportOrphanPanesModal, useImportModal } from '@/components/import/ImportOrphanPanesModal'; -import { SessionGenerator } from '@/components/session-generator'; +import { LaunchRail } from '@/components/launch/LaunchRail'; import { getHosts, assignSessionGroup } from '@/lib/api'; import { setSessionsPerfEnabled, @@ -90,9 +90,6 @@ export default function SessionsPageClient() { ] ); - // Modal states - const [showSpawnDialog, setShowSpawnDialog] = useState(false); - // Selection state const [selectionMode, setSelectionMode] = useState(false); const [selectedIds, setSelectedIds] = useState>(new Set()); @@ -467,18 +464,14 @@ export default function SessionsPageClient() { Archived -
+ queryClient.invalidateQueries({ queryKey: ['sessions'] })} + /> +
queryClient.invalidateQueries({ queryKey: ['sessions'] })} /> - setShowSpawnDialog(false)} - /> - {/* Bulk Action Toolbar */} {selectionMode && ( + + {icon} + + + {value ?? '—'} + {label} + {context} + + + ); +} + +export function UsageOverview() { + const sessionsQuery = useQuery({ + queryKey: ['sessions', 'settings-usage'], + queryFn: () => getSessions({ include_archived: false, status: WORKFLOW_STATUSES }), + }); + const hostsQuery = useQuery({ + queryKey: ['hosts'], + queryFn: getHosts, + }); + + const metrics = useMemo(() => { + const sessions = sessionsQuery.data?.sessions; + const hosts = hostsQuery.data?.hosts; + return { + active: sessions ? sessions.filter((session) => ['RUNNING', 'STARTING'].includes(session.status)).length : null, + attention: sessions ? sessions.filter((session) => ['WAITING_FOR_INPUT', 'WAITING_FOR_APPROVAL', 'ERROR'].includes(session.status)).length : null, + idle: sessions ? sessions.filter((session) => session.status === 'IDLE' || session.idled_at).length : null, + onlineHosts: hosts ? hosts.filter((host) => isHostOnline(host.last_seen_at || null)).length : null, + }; + }, [hostsQuery.data?.hosts, sessionsQuery.data?.sessions]); + const partialError = sessionsQuery.error || hostsQuery.error; + + return ( +
+
+

Usage & fleet snapshot

+

+ Current workflow counts and provider usage. Provider limits refresh every minute. +

+
+ + {partialError && ( +
+ Part of the live snapshot is unavailable. Loaded metrics remain visible. +
+ )} + +
+ } + /> + } + /> + } + /> + } + /> +
+ + +
+ ); +} diff --git a/apps/dashboard/src/app/(dashboard)/settings/page.tsx b/apps/dashboard/src/app/(dashboard)/settings/page.tsx index 6df9df1d..5096a9af 100644 --- a/apps/dashboard/src/app/(dashboard)/settings/page.tsx +++ b/apps/dashboard/src/app/(dashboard)/settings/page.tsx @@ -1,5 +1,6 @@ import { Settings } from 'lucide-react'; import { SettingsPanel } from '@/components/settings/SettingsPanel'; +import { UsageOverview } from './UsageOverview'; export default function SettingsPage() { return ( @@ -13,6 +14,7 @@ export default function SettingsPage() {

+ ); diff --git a/apps/dashboard/src/app/(dashboard)/tmux/TmuxPageClient.tsx b/apps/dashboard/src/app/(dashboard)/tmux/TmuxPageClient.tsx index dd7d1084..7e787944 100644 --- a/apps/dashboard/src/app/(dashboard)/tmux/TmuxPageClient.tsx +++ b/apps/dashboard/src/app/(dashboard)/tmux/TmuxPageClient.tsx @@ -19,14 +19,14 @@ import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { cn, getSessionDisplayName } from '@/lib/utils'; import { useHydrated } from '@/hooks/useHydrated'; -import { useIsMobile } from '@/hooks/useIsMobile'; +import { COMMAND_CENTER_SHELL_BREAKPOINT, useIsMobile } from '@/hooks/useIsMobile'; import { useTmuxRosterData } from '@/hooks/useTmuxRosterData'; export default function TmuxPageClient() { const queryClient = useQueryClient(); const searchParams = useSearchParams(); const hydrated = useHydrated(); - const isMobileLayout = useIsMobile(1024); + const isMobileLayout = useIsMobile(COMMAND_CENTER_SHELL_BREAKPOINT); const mcpManager = useMCPManager(); const terminalControllerRef = useRef(null); const { setSessionIdle, isSessionIdlePending } = useSessionIdle(); diff --git a/apps/dashboard/src/app/(dashboard)/tmux/page.tsx b/apps/dashboard/src/app/(dashboard)/tmux/page.tsx index 6ffd1852..d23efcd3 100644 --- a/apps/dashboard/src/app/(dashboard)/tmux/page.tsx +++ b/apps/dashboard/src/app/(dashboard)/tmux/page.tsx @@ -1,12 +1,23 @@ -import { Suspense } from 'react'; -import TmuxPageClient from './TmuxPageClient'; +import { redirect } from 'next/navigation'; -export const dynamic = 'force-dynamic'; +type RedirectSearchParams = Promise>; -export default function TmuxPage() { - return ( - Loading...}> - - - ); +export default async function TmuxRedirectPage({ + searchParams, +}: { + searchParams: RedirectSearchParams; +}) { + const resolvedParams = await searchParams; + const nextParams = new URLSearchParams(); + + Object.entries(resolvedParams).forEach(([key, value]) => { + if (Array.isArray(value)) { + value.forEach((entry) => nextParams.append(key, entry)); + } else if (value !== undefined) { + nextParams.set(key, value); + } + }); + + const query = nextParams.toString(); + redirect(query ? `/?${query}` : '/'); } diff --git a/apps/dashboard/src/components/SpawnSessionDialog.tsx b/apps/dashboard/src/components/SpawnSessionDialog.tsx deleted file mode 100644 index 098ea5db..00000000 --- a/apps/dashboard/src/components/SpawnSessionDialog.tsx +++ /dev/null @@ -1,324 +0,0 @@ -'use client'; - -import { useState, useEffect, useMemo } from 'react'; -import { useRouter } from 'next/navigation'; -import { useMutation, useQuery } from '@tanstack/react-query'; -import { X, Server, FolderOpen, Play } from 'lucide-react'; -import { Button } from '@/components/ui/button'; -import { getHosts, getGroups, getProjects, spawnSession, type SpawnProvider } from '@/lib/api'; -import { isHostOffline } from '@/components/StatusBadge'; - -const PROVIDERS: Array<{ id: SpawnProvider; name: string; description: string }> = [ - { id: 'claude_code', name: 'Claude Code', description: 'Anthropic Claude CLI agent' }, - { id: 'codex', name: 'Codex', description: 'OpenAI Codex CLI agent' }, - { id: 'gemini_cli', name: 'Gemini CLI', description: 'Google Gemini CLI agent' }, - { id: 'opencode', name: 'OpenCode', description: 'OpenCode CLI agent (Minimax)' }, - { id: 'aider', name: 'Aider', description: 'GPT-powered coding assistant' }, - { id: 'shell', name: 'Shell', description: 'Plain bash shell' }, -]; - -interface SpawnSessionDialogProps { - isOpen: boolean; - onClose: () => void; - defaultHostId?: string; - defaultWorkingDirectory?: string; - defaultGroupId?: string; -} - -export function SpawnSessionDialog({ - isOpen, - onClose, - defaultHostId, - defaultWorkingDirectory = '~', - defaultGroupId, -}: SpawnSessionDialogProps) { - const router = useRouter(); - - // Form state - const [hostId, setHostId] = useState(defaultHostId || ''); - const [provider, setProvider] = useState('claude_code'); - const [workingDirectory, setWorkingDirectory] = useState(defaultWorkingDirectory); - const [title, setTitle] = useState(''); - const [flags, setFlags] = useState(''); - const [groupId, setGroupId] = useState(defaultGroupId || ''); - const [error, setError] = useState(null); - - // Fetch hosts - const { data: hostsData, isLoading: hostsLoading } = useQuery({ - queryKey: ['hosts'], - queryFn: getHosts, - enabled: isOpen, - }); - - // Fetch groups - const { data: groupsData, isLoading: groupsLoading } = useQuery({ - queryKey: ['groups'], - queryFn: getGroups, - enabled: isOpen, - }); - - // Fetch projects for selected host (autocomplete) - const { data: projectsData } = useQuery({ - queryKey: ['projects', hostId], - queryFn: () => (hostId ? getProjects({ host_id: hostId, limit: 50 }) : Promise.resolve({ projects: [] })), - enabled: isOpen && !!hostId, - }); - - // Filter to online hosts only - const onlineHosts = useMemo(() => { - return hostsData?.hosts.filter((h) => !isHostOffline(h)) || []; - }, [hostsData]); - - // Reset form when modal opens - useEffect(() => { - if (isOpen) { - setHostId(defaultHostId || onlineHosts[0]?.id || ''); - setProvider('claude_code'); - setWorkingDirectory(defaultWorkingDirectory); - setTitle(''); - setFlags(''); - setGroupId(defaultGroupId || ''); - setError(null); - } - }, [isOpen, defaultHostId, defaultWorkingDirectory, defaultGroupId, onlineHosts]); - - // Spawn mutation - const spawnMutation = useMutation({ - mutationFn: spawnSession, - onSuccess: (result) => { - onClose(); - // Navigate to the new session - router.push(`/sessions/${result.session.id}`); - }, - onError: (err: Error) => { - setError(err.message); - }, - }); - - const handleSubmit = (e: React.FormEvent) => { - e.preventDefault(); - setError(null); - - if (!hostId) { - setError('Please select a host'); - return; - } - - if (!workingDirectory.trim()) { - setError('Working directory is required'); - return; - } - - // Parse flags - const flagsArray = flags - .split(/\s+/) - .map((f) => f.trim()) - .filter(Boolean); - const trimmedWorkingDir = workingDirectory.trim().replace(/\/+$/, ''); - const targetSession = trimmedWorkingDir - .split('/') - .filter(Boolean) - .pop(); - const windowName = title.trim() || provider; - - spawnMutation.mutate({ - host_id: hostId, - provider, - working_directory: workingDirectory.trim(), - title: title.trim() || undefined, - flags: flagsArray.length > 0 ? flagsArray : undefined, - group_id: groupId || undefined, - tmux: { - target_session: targetSession || undefined, - window_name: windowName, - }, - }); - }; - - const isLoading = spawnMutation.isPending || hostsLoading || groupsLoading; - const projects = projectsData?.projects || []; - - if (!isOpen) return null; - - return ( -
-
-
-
- -

Spawn New Session

-
- -
- -
- {/* Host selection */} -
- - {hostsLoading ? ( -
Loading hosts...
- ) : onlineHosts.length === 0 ? ( -
- No online hosts available. Please start an agent first. -
- ) : ( - - )} -
- - {/* Provider selection */} -
- -
- {PROVIDERS.map((p) => ( - - ))} -
-
- - {/* Working directory */} -
- - setWorkingDirectory(e.target.value)} - className="w-full px-3 py-2 border rounded-md bg-background font-mono text-sm" - placeholder="/path/to/project" - list="project-paths" - disabled={isLoading} - /> - - {projects.map((project) => ( - - ))} - - {projects.length > 0 && ( -

- Suggestions from recently used projects on this host. -

- )} -
- - {/* Title (optional) */} -
- - setTitle(e.target.value)} - className="w-full px-3 py-2 border rounded-md bg-background" - placeholder="My coding session" - disabled={isLoading} - /> -
- - {/* Flags (optional) */} -
- - setFlags(e.target.value)} - className="w-full px-3 py-2 border rounded-md bg-background font-mono text-sm" - placeholder="--model sonnet --dangerously-skip-permissions" - disabled={isLoading} - /> -

- Additional CLI flags for the provider -

-
- - {/* Group (optional) */} -
- - -
- - {/* Error */} - {error && ( -
- {error} -
- )} - - {/* Actions */} -
- - -
-
-
-
- ); -} diff --git a/apps/dashboard/src/components/launch/LaunchRail.tsx b/apps/dashboard/src/components/launch/LaunchRail.tsx new file mode 100644 index 00000000..71345576 --- /dev/null +++ b/apps/dashboard/src/components/launch/LaunchRail.tsx @@ -0,0 +1,82 @@ +'use client'; + +import { useState } from 'react'; +import { Clock3, FolderOpen, Plus } from 'lucide-react'; +import { cn } from '@/lib/utils'; +import { MobileLaunchSheet, type LaunchSheetView } from './MobileLaunchSheet'; +import { getLaunchProvider } from './definitions'; +import { useRecentLaunch } from './recentLaunchStore'; + +interface LaunchRailProps { + className?: string; + selectedHostId?: string; + onLaunched?: () => void; +} + +export function LaunchRail({ className, selectedHostId, onLaunched }: LaunchRailProps) { + const recentLaunch = useRecentLaunch(); + const [open, setOpen] = useState(false); + const [initialView, setInitialView] = useState('new'); + + const openSheet = (view: LaunchSheetView) => { + setInitialView(view); + setOpen(true); + }; + + const recentLabel = recentLaunch + ? `${getLaunchProvider(recentLaunch.provider)?.shortName ?? recentLaunch.provider} · ${recentLaunch.working_directory.split('/').filter(Boolean).pop() ?? recentLaunch.working_directory}` + : 'Previous projects'; + + return ( + <> +
+
+

Launch

+

Start work or return to a known tmux target.

+
+
+ + + +
+
+ + setOpen(false)} + onLaunched={onLaunched} + /> + + ); +} diff --git a/apps/dashboard/src/components/launch/MobileLaunchSheet.tsx b/apps/dashboard/src/components/launch/MobileLaunchSheet.tsx index d7b3ecc1..61ac70a0 100644 --- a/apps/dashboard/src/components/launch/MobileLaunchSheet.tsx +++ b/apps/dashboard/src/components/launch/MobileLaunchSheet.tsx @@ -9,18 +9,19 @@ import { launchAgent, openTmuxTarget } from '@/lib/api'; import { cn } from '@/lib/utils'; import { useSettingsStore } from '@/stores/settings'; import { Button } from '@/components/ui/button'; +import { MOBILE_LAUNCH_PROVIDERS, getLaunchProvider } from './definitions'; +import { + type RecentLaunch, + useRecentLaunch, + writeRecentLaunch, +} from './recentLaunchStore'; type LaunchMode = 'new' | 'existing'; - -interface LastLaunch { - host_id: string; - provider: MobileLaunchProvider; - working_directory: string; - tmux_target?: string | null; -} +export type LaunchSheetView = LaunchMode | 'recent'; interface MobileLaunchSheetProps { open: boolean; + initialView?: LaunchSheetView; selectedHostId?: string; onClose: () => void; onLaunched?: () => void; @@ -31,14 +32,20 @@ function projectLabel(path: string): string { } function providerLabel(provider: MobileLaunchProvider): string { - return provider === 'claude_code' ? 'Claude' : 'Codex'; + return getLaunchProvider(provider)?.shortName ?? provider; } function targetSupportsProvider(target: LaunchTarget | undefined, provider: MobileLaunchProvider): boolean { return Boolean(target?.providers[provider]); } -export function MobileLaunchSheet({ open, selectedHostId, onClose, onLaunched }: MobileLaunchSheetProps) { +export function MobileLaunchSheet({ + open, + initialView = 'new', + selectedHostId, + onClose, + onLaunched, +}: MobileLaunchSheetProps) { const router = useRouter(); const defaultMobileLaunchProvider = useSettingsStore((state) => state.defaultMobileLaunchProvider); const defaultMobileLaunchHostId = useSettingsStore((state) => state.defaultMobileLaunchHostId); @@ -56,7 +63,7 @@ export function MobileLaunchSheet({ open, selectedHostId, onClose, onLaunched }: const [advancedOpen, setAdvancedOpen] = useState(false); const [tmuxTarget, setTmuxTarget] = useState(''); const [existingTarget, setExistingTarget] = useState(''); - const [lastLaunch, setLastLaunch] = useState(null); + const lastLaunch = useRecentLaunch(open); const [openingExistingId, setOpeningExistingId] = useState(null); const [launching, setLaunching] = useState(false); const [launchError, setLaunchError] = useState(null); @@ -78,35 +85,10 @@ export function MobileLaunchSheet({ open, selectedHostId, onClose, onLaunched }: useEffect(() => { if (!open) return; - try { - const raw = window.localStorage.getItem('agent-command:last-launch'); - if (!raw) { - setLastLaunch(null); - return; - } - const parsed = JSON.parse(raw) as Partial; - if ( - typeof parsed.host_id === 'string' && - (parsed.provider === 'codex' || parsed.provider === 'claude_code') && - typeof parsed.working_directory === 'string' - ) { - setLastLaunch({ - host_id: parsed.host_id, - provider: parsed.provider, - working_directory: parsed.working_directory, - tmux_target: typeof parsed.tmux_target === 'string' ? parsed.tmux_target : null, - }); - } - } catch { - setLastLaunch(null); - } - }, [open]); - - useEffect(() => { - if (!open) return; + setMode(initialView === 'existing' ? 'existing' : 'new'); setProvider(defaultMobileLaunchProvider); setTmuxTarget(defaultMobileLaunchTmuxTarget || ''); - }, [defaultMobileLaunchProvider, defaultMobileLaunchTmuxTarget, open]); + }, [defaultMobileLaunchProvider, defaultMobileLaunchTmuxTarget, initialView, open]); useEffect(() => { if (!selectedTarget) return; @@ -150,12 +132,7 @@ export function MobileLaunchSheet({ open, selectedHostId, onClose, onLaunched }: working_directory: workingDirectory.trim(), tmux_target: tmuxTarget.trim() || null, }; - try { - window.localStorage.setItem('agent-command:last-launch', JSON.stringify(nextLastLaunch)); - } catch { - // localStorage can be unavailable in restricted browsers. - } - setLastLaunch(nextLastLaunch); + writeRecentLaunch(nextLastLaunch); setDefaultMobileLaunchProvider(provider); setDefaultMobileLaunchHostId(selectedTarget.host_id); setDefaultMobileLaunchTmuxTarget(tmuxTarget.trim() || null); @@ -181,7 +158,7 @@ export function MobileLaunchSheet({ open, selectedHostId, onClose, onLaunched }: workingDirectory, ]); - const handleRepeatLaunch = useCallback(async (launch: LastLaunch) => { + const handleRepeatLaunch = useCallback(async (launch: RecentLaunch) => { const target = targets.find((candidate) => candidate.host_id === launch.host_id); if (!target) return; setLaunching(true); @@ -195,6 +172,7 @@ export function MobileLaunchSheet({ open, selectedHostId, onClose, onLaunched }: wait: true, wait_timeout_ms: 10000, }); + writeRecentLaunch(launch); onLaunched?.(); setDefaultMobileLaunchProvider(launch.provider); setDefaultMobileLaunchHostId(target.host_id); @@ -258,7 +236,9 @@ export function MobileLaunchSheet({ open, selectedHostId, onClose, onLaunched }:
-

Launch agent

+

+ {initialView === 'existing' ? 'Open existing' : initialView === 'recent' ? 'Recent launches' : 'Launch agent'} +

{selectedTarget?.alias || 'Choose a machine'}
@@ -488,7 +468,8 @@ export function MobileLaunchSheet({ open, selectedHostId, onClose, onLaunched }:
Agent
- {(['codex', 'claude_code'] as const).map((candidate) => { + {MOBILE_LAUNCH_PROVIDERS.map((providerOption) => { + const candidate = providerOption.id; const supported = targetSupportsProvider(selectedTarget, candidate); return ( ); })} diff --git a/apps/dashboard/src/components/launch/definitions.test.ts b/apps/dashboard/src/components/launch/definitions.test.ts new file mode 100644 index 00000000..57a1502b --- /dev/null +++ b/apps/dashboard/src/components/launch/definitions.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest'; +import { + LAUNCH_PROVIDERS, + MOBILE_LAUNCH_PROVIDERS, + SESSION_TEMPLATES, +} from './definitions'; + +describe('launch definitions', () => { + it('keeps provider ids unique and exposes the mobile launch pair', () => { + const providerIds = LAUNCH_PROVIDERS.map((provider) => provider.id); + + expect(new Set(providerIds).size).toBe(providerIds.length); + expect(MOBILE_LAUNCH_PROVIDERS.map((provider) => provider.id)).toEqual([ + 'claude_code', + 'codex', + ]); + }); + + it('only references centralized providers from session templates', () => { + const providerIds = new Set(LAUNCH_PROVIDERS.map((provider) => provider.id)); + const templateProviders = Object.values(SESSION_TEMPLATES) + .flatMap((template) => template.sessions) + .map((session) => session.provider); + + expect(templateProviders.every((provider) => providerIds.has(provider))).toBe(true); + expect(Object.keys(SESSION_TEMPLATES)).toEqual(['single', 'claude_codex', 'full_dev']); + }); +}); diff --git a/apps/dashboard/src/components/session-generator/templates.ts b/apps/dashboard/src/components/launch/definitions.ts similarity index 56% rename from apps/dashboard/src/components/session-generator/templates.ts rename to apps/dashboard/src/components/launch/definitions.ts index bb4467b8..f5943eb3 100644 --- a/apps/dashboard/src/components/session-generator/templates.ts +++ b/apps/dashboard/src/components/launch/definitions.ts @@ -1,4 +1,30 @@ -import type { SpawnProvider, SessionLinkType } from '@/lib/api'; +import type { MobileLaunchProvider } from '@agent-command/schema'; +import type { SessionLinkType, SpawnProvider } from '@/lib/api'; + +export interface LaunchProviderDefinition { + id: SpawnProvider; + name: string; + shortName: string; + mobile: boolean; +} + +export const LAUNCH_PROVIDERS = [ + { id: 'claude_code', name: 'Claude Code', shortName: 'Claude', mobile: true }, + { id: 'codex', name: 'Codex', shortName: 'Codex', mobile: true }, + { id: 'gemini_cli', name: 'Gemini CLI', shortName: 'Gemini', mobile: false }, + { id: 'opencode', name: 'OpenCode', shortName: 'OpenCode', mobile: false }, + { id: 'aider', name: 'Aider', shortName: 'Aider', mobile: false }, + { id: 'shell', name: 'Shell', shortName: 'Shell', mobile: false }, +] as const satisfies readonly LaunchProviderDefinition[]; + +export const MOBILE_LAUNCH_PROVIDERS = LAUNCH_PROVIDERS.filter( + (provider): provider is (typeof LAUNCH_PROVIDERS)[number] & { id: MobileLaunchProvider } => + provider.mobile +); + +export function getLaunchProvider(providerId: SpawnProvider) { + return LAUNCH_PROVIDERS.find((provider) => provider.id === providerId); +} export interface SessionTemplateSession { provider: SpawnProvider; diff --git a/apps/dashboard/src/components/launch/recentLaunchStore.ts b/apps/dashboard/src/components/launch/recentLaunchStore.ts new file mode 100644 index 00000000..a60cb1ee --- /dev/null +++ b/apps/dashboard/src/components/launch/recentLaunchStore.ts @@ -0,0 +1,65 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import type { MobileLaunchProvider } from '@agent-command/schema'; + +export const RECENT_LAUNCH_STORAGE_KEY = 'agent-command:last-launch'; +const RECENT_LAUNCH_EVENT = 'agent-command:recent-launch-changed'; + +export interface RecentLaunch { + host_id: string; + provider: MobileLaunchProvider; + working_directory: string; + tmux_target?: string | null; +} + +export function readRecentLaunch(): RecentLaunch | null { + if (typeof window === 'undefined') return null; + try { + const raw = window.localStorage.getItem(RECENT_LAUNCH_STORAGE_KEY); + if (!raw) return null; + const parsed = JSON.parse(raw) as Partial; + if ( + typeof parsed.host_id !== 'string' || + (parsed.provider !== 'codex' && parsed.provider !== 'claude_code') || + typeof parsed.working_directory !== 'string' + ) { + return null; + } + return { + host_id: parsed.host_id, + provider: parsed.provider, + working_directory: parsed.working_directory, + tmux_target: typeof parsed.tmux_target === 'string' ? parsed.tmux_target : null, + }; + } catch { + return null; + } +} + +export function writeRecentLaunch(launch: RecentLaunch): void { + if (typeof window === 'undefined') return; + try { + window.localStorage.setItem(RECENT_LAUNCH_STORAGE_KEY, JSON.stringify(launch)); + window.dispatchEvent(new CustomEvent(RECENT_LAUNCH_EVENT)); + } catch { + // localStorage can be unavailable in restricted browsers. + } +} + +export function useRecentLaunch(refreshKey?: unknown): RecentLaunch | null { + const [recentLaunch, setRecentLaunch] = useState(null); + + useEffect(() => { + const refresh = () => setRecentLaunch(readRecentLaunch()); + refresh(); + window.addEventListener('storage', refresh); + window.addEventListener(RECENT_LAUNCH_EVENT, refresh); + return () => { + window.removeEventListener('storage', refresh); + window.removeEventListener(RECENT_LAUNCH_EVENT, refresh); + }; + }, [refreshKey]); + + return recentLaunch; +} diff --git a/apps/dashboard/src/components/layout/AttentionSettings.tsx b/apps/dashboard/src/components/layout/AttentionSettings.tsx index 4b76b11a..b54b1c00 100644 --- a/apps/dashboard/src/components/layout/AttentionSettings.tsx +++ b/apps/dashboard/src/components/layout/AttentionSettings.tsx @@ -50,7 +50,8 @@ export function AttentionSettings({ compact = false }: AttentionSettingsProps) { type="button" onClick={handleToggleNotifications} className={cn( - 'flex items-center justify-between w-full rounded-md border px-2 py-1 text-xs', + 'flex min-h-11 w-full items-center justify-between rounded-md border px-2 py-1 text-xs', + 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring', notificationsEnabled ? 'bg-primary/10 border-primary/40' : 'bg-background' )} > @@ -66,7 +67,8 @@ export function AttentionSettings({ compact = false }: AttentionSettingsProps) { type="button" onClick={() => setAlertChannelEnabled('audio', !audioEnabled)} className={cn( - 'flex items-center justify-between w-full rounded-md border px-2 py-1 text-xs', + 'flex min-h-11 w-full items-center justify-between rounded-md border px-2 py-1 text-xs', + 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring', audioEnabled ? 'bg-primary/10 border-primary/40' : 'bg-background' )} > diff --git a/apps/dashboard/src/components/layout/AttentionSummary.tsx b/apps/dashboard/src/components/layout/AttentionSummary.tsx new file mode 100644 index 00000000..df27447c --- /dev/null +++ b/apps/dashboard/src/components/layout/AttentionSummary.tsx @@ -0,0 +1,69 @@ +'use client'; + +import { useMemo } from 'react'; +import { useRouter } from 'next/navigation'; +import { Bell, ChevronRight } from 'lucide-react'; +import { useIsMobile } from '@/hooks/useIsMobile'; +import { mergeAttentionItems } from '@/lib/attentionMerge'; +import { cn } from '@/lib/utils'; +import { useOrchestratorStore, type OrchestratorItem } from '@/stores/orchestrator'; + +function itemLabel(item: OrchestratorItem): string { + return item.action?.question + || item.attentionReason + || item.sessionTitle + || item.governanceApproval?.type?.replace(/_/g, ' ') + || 'Operator decision required'; +} + +export function AttentionSummary() { + const router = useRouter(); + const isMobile = useIsMobile(); + const rawItems = useOrchestratorStore((state) => state.items); + const open = useOrchestratorStore((state) => state.open); + const queue = useMemo(() => mergeAttentionItems(rawItems), [rawItems]); + const topItem = queue[0]; + + const handleOpen = () => { + if (isMobile) { + router.push('/orchestrator?tab=attention'); + return; + } + open(); + }; + + return ( + + ); +} diff --git a/apps/dashboard/src/components/layout/GlobalSidebar.tsx b/apps/dashboard/src/components/layout/GlobalSidebar.tsx index 7df63f09..e9144c89 100644 --- a/apps/dashboard/src/components/layout/GlobalSidebar.tsx +++ b/apps/dashboard/src/components/layout/GlobalSidebar.tsx @@ -70,7 +70,7 @@ export function GlobalSidebar({ Navigate to the rest of Agent Commander. - @@ -121,7 +121,7 @@ export function GlobalSidebar({ - ); -} diff --git a/apps/dashboard/src/components/layout/QuickSpawn.tsx b/apps/dashboard/src/components/layout/QuickSpawn.tsx index b8ec1257..3407237c 100644 --- a/apps/dashboard/src/components/layout/QuickSpawn.tsx +++ b/apps/dashboard/src/components/layout/QuickSpawn.tsx @@ -3,7 +3,7 @@ import { useState } from 'react'; import { Plus } from 'lucide-react'; import { Button } from '@/components/ui/button'; -import { SessionGenerator } from '@/components/session-generator'; +import { MobileLaunchSheet } from '@/components/launch/MobileLaunchSheet'; export function QuickSpawn() { const [showDialog, setShowDialog] = useState(false); @@ -12,15 +12,15 @@ export function QuickSpawn() { <> - setShowDialog(false)} /> diff --git a/apps/dashboard/src/components/layout/RecentSessions.tsx b/apps/dashboard/src/components/layout/RecentSessions.tsx index a313e7e1..843b2f8e 100644 --- a/apps/dashboard/src/components/layout/RecentSessions.tsx +++ b/apps/dashboard/src/components/layout/RecentSessions.tsx @@ -52,7 +52,8 @@ function SessionList({ key={session.id} href={getRecentSessionHref(session)} className={cn( - 'flex items-center gap-2 px-2 py-1.5 rounded-md text-sm', + 'flex min-h-11 items-center gap-2 rounded-md px-2 py-1.5 text-sm', + 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring', 'text-muted-foreground hover:bg-accent hover:text-foreground', 'transition-colors group' )} diff --git a/apps/dashboard/src/components/layout/SidebarNav.tsx b/apps/dashboard/src/components/layout/SidebarNav.tsx index e6ab8bda..f977eb3d 100644 --- a/apps/dashboard/src/components/layout/SidebarNav.tsx +++ b/apps/dashboard/src/components/layout/SidebarNav.tsx @@ -1,5 +1,6 @@ 'use client'; +import Link from 'next/link'; import { usePathname } from 'next/navigation'; import { LayoutDashboard, @@ -9,7 +10,6 @@ import { Boxes, Workflow, Brain, - Rows3, Settings, } from 'lucide-react'; import { cn } from '@/lib/utils'; @@ -34,14 +34,19 @@ export function SidebarNav({ collapsed }: SidebarNavProps) { const navItems: NavItem[] = [ { href: '/', - label: 'Dashboard', + label: 'Command Center', icon: , }, { - href: '/orchestrator', - label: 'Orchestrator', + href: '/orchestrator?tab=attention', + label: 'Attention', icon: , }, + { + href: '/sessions', + label: 'Sessions', + icon: , + }, { href: '/automation', label: 'Automation', @@ -52,16 +57,6 @@ export function SidebarNav({ collapsed }: SidebarNavProps) { label: 'Memory', icon: , }, - { - href: '/tmux', - label: 'tmux', - icon: , - }, - { - href: '/sessions', - label: 'Sessions', - icon: , - }, ...(showVisualizerInSidebar ? [ { @@ -85,10 +80,11 @@ export function SidebarNav({ collapsed }: SidebarNavProps) { ]; const isActive = (href: string) => { - if (href === '/') { + const path = href.split('?')[0]; + if (path === '/') { return pathname === '/'; } - return pathname.startsWith(href); + return pathname.startsWith(path); }; if (collapsed) { @@ -97,17 +93,18 @@ export function SidebarNav({ collapsed }: SidebarNavProps) { {navItems.map((item) => ( - {item.icon} - +

{item.label}

@@ -121,11 +118,12 @@ export function SidebarNav({ collapsed }: SidebarNavProps) { return ( ); diff --git a/apps/dashboard/src/components/layout/index.ts b/apps/dashboard/src/components/layout/index.ts index 5004a792..b7ab341b 100644 --- a/apps/dashboard/src/components/layout/index.ts +++ b/apps/dashboard/src/components/layout/index.ts @@ -4,6 +4,7 @@ export { RecentSessions } from './RecentSessions'; export { QuickSpawn } from './QuickSpawn'; export { LayoutShell } from './LayoutShell'; export { ConnectionBanner } from './ConnectionBanner'; -export { MobileHeader } from './MobileHeader'; +export { HeaderConnectionStatus } from './HeaderConnectionStatus'; +export { AttentionSummary } from './AttentionSummary'; export { AttentionTitle } from './AttentionTitle'; export { AttentionSettings } from './AttentionSettings'; diff --git a/apps/dashboard/src/components/layout/shellContracts.test.ts b/apps/dashboard/src/components/layout/shellContracts.test.ts new file mode 100644 index 00000000..711184cc --- /dev/null +++ b/apps/dashboard/src/components/layout/shellContracts.test.ts @@ -0,0 +1,35 @@ +import { existsSync, readFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; +import { + COMMAND_CENTER_SHELL_BREAKPOINT, + NAV_MOBILE_BREAKPOINT, +} from '@/hooks/useIsMobile'; + +const dashboardRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../..'); + +describe('Command Center shell contracts', () => { + it('locks navigation and internal shell breakpoints', () => { + expect(NAV_MOBILE_BREAKPOINT).toBe(768); + expect(COMMAND_CENTER_SHELL_BREAKPOINT).toBe(1024); + }); + + it('keeps legacy duplicate surfaces deleted', () => { + expect(existsSync(resolve(dashboardRoot, 'src/components/SpawnSessionDialog.tsx'))).toBe(false); + expect(existsSync(resolve(dashboardRoot, 'src/components/orchestrator/OrchestratorModal.tsx'))).toBe(false); + expect(existsSync(resolve(dashboardRoot, 'src/app/(dashboard)/orchestrator/OrchestratorPageClient.tsx'))).toBe(false); + + const rootPage = readFileSync(resolve(dashboardRoot, 'src/app/(dashboard)/page.tsx'), 'utf8'); + expect(rootPage).toContain('Command Center'); + expect(rootPage).not.toContain('New in v0.2.0'); + }); + + it('starts the installed PWA at the Command Center', () => { + const manifest = JSON.parse( + readFileSync(resolve(dashboardRoot, 'public/manifest.json'), 'utf8') + ) as { start_url?: string }; + + expect(manifest.start_url).toBe('/'); + }); +}); diff --git a/apps/dashboard/src/components/orchestrator/OrchestratorButton.tsx b/apps/dashboard/src/components/orchestrator/OrchestratorButton.tsx index 2f7cea22..57c1e12b 100644 --- a/apps/dashboard/src/components/orchestrator/OrchestratorButton.tsx +++ b/apps/dashboard/src/components/orchestrator/OrchestratorButton.tsx @@ -1,6 +1,7 @@ 'use client'; import { useEffect, useCallback } from 'react'; +import { usePathname, useRouter } from 'next/navigation'; import { Bell } from 'lucide-react'; import type { Approval, @@ -18,6 +19,7 @@ import { getSessions, } from '@/lib/api'; import { useWebSocket } from '@/hooks/useWebSocket'; +import { useIsMobile } from '@/hooks/useIsMobile'; import { useOrchestratorStore } from '@/stores/orchestrator'; /** @@ -25,8 +27,12 @@ import { useOrchestratorStore } from '@/stores/orchestrator'; * Also handles background session monitoring via WebSocket. */ export function OrchestratorButton() { + const router = useRouter(); + const pathname = usePathname(); + const isMobile = useIsMobile(); const attentionStatusFilter = 'RUNNING,STARTING,WAITING_FOR_INPUT,WAITING_FOR_APPROVAL,ERROR,IDLE'; const toggle = useOrchestratorStore((s) => s.toggle); + const close = useOrchestratorStore((s) => s.close); const isOpen = useOrchestratorStore((s) => s.isOpen); const itemCount = useOrchestratorStore((s) => s.getItemCount()); const ingestSessions = useOrchestratorStore((s) => s.ingestSessions); @@ -204,6 +210,15 @@ export function OrchestratorButton() { 'attention' ); + const openAttention = useCallback(() => { + if (isMobile || pathname.startsWith('/orchestrator')) { + close(); + router.push('/orchestrator?tab=attention'); + return; + } + toggle(); + }, [close, isMobile, pathname, router, toggle]); + // Shift+O keyboard shortcut useEffect(() => { const handleKeyDown = (e: KeyboardEvent) => { @@ -221,25 +236,26 @@ export function OrchestratorButton() { // Shift+O to toggle orchestrator if (e.key === 'O' && e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) { e.preventDefault(); - toggle(); + openAttention(); } }; document.addEventListener('keydown', handleKeyDown); return () => document.removeEventListener('keydown', handleKeyDown); - }, [toggle]); + }, [openAttention]); return ( - -
-
- -
- {errors.length > 0 && ( -
- - Some sources are unavailable; loaded items remain actionable. -
- )} - - {isLoading && ( -
- - Loading attention… -
- )} - - {!isLoading && items.length === 0 && idledItems.length === 0 && ( -
- -

Nothing needs your attention

-

This queue updates as agents and runs change.

-
- )} - - {items.map((item) => ( - void refresh()} - summariesEnabled={summariesEnabled} - showSummary={false} - /> - ))} - - {idledItems.length > 0 && ( -
- - {idleExpanded && ( -
- {idledItems.map((item) => ( - void refresh()} - summariesEnabled={summariesEnabled} - showSummary={false} - /> - ))} -
- )} -
- )} -
- -
- Press Shift+O to toggle -
- - - ); -} diff --git a/apps/dashboard/src/components/orchestrator/OrchestratorSurface.tsx b/apps/dashboard/src/components/orchestrator/OrchestratorSurface.tsx new file mode 100644 index 00000000..81212df6 --- /dev/null +++ b/apps/dashboard/src/components/orchestrator/OrchestratorSurface.tsx @@ -0,0 +1,284 @@ +'use client'; + +import { useEffect, useMemo, useState } from 'react'; +import { useSearchParams } from 'next/navigation'; +import * as Dialog from '@radix-ui/react-dialog'; +import { + AlertTriangle, + Bell, + Bot, + ChevronDown, + ChevronRight, + Loader2, + Moon, + RefreshCw, + X, +} from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; +import { useAttentionQueue } from '@/hooks/useAttentionQueue'; +import { useOrchestratorFleet } from '@/hooks/useOrchestratorFleet'; +import { useIsMobile } from '@/hooks/useIsMobile'; +import { assignAttentionToOrchestrators } from '@/lib/attentionMerge'; +import { cn } from '@/lib/utils'; +import { useOrchestratorStore } from '@/stores/orchestrator'; +import { OrchestratorFleetCard } from './OrchestratorFleetCard'; +import { OrchestratorItem } from './OrchestratorItem'; + +type AttentionTab = 'fleet' | 'attention'; + +interface OrchestratorSurfaceProps { + presentation: 'page' | 'sheet'; + initialTab?: AttentionTab; + onClose?: () => void; +} + +export function OrchestratorSurface({ + presentation, + initialTab, + onClose, +}: OrchestratorSurfaceProps) { + const searchParams = useSearchParams(); + const requestedTab = searchParams.get('tab') === 'attention' ? 'attention' : 'fleet'; + const [idleExpanded, setIdleExpanded] = useState(false); + const [activeTab, setActiveTab] = useState(initialTab ?? requestedTab); + const closeStoreSurface = useOrchestratorStore((state) => state.close); + const { + items, + idledItems, + errors, + isLoading, + isRefreshing, + refresh, + dismissItem, + handleIdle, + handleUnidle, + summariesEnabled, + summaryStatusLoading, + } = useAttentionQueue(); + const fleet = useOrchestratorFleet(); + + useEffect(() => { + setActiveTab(initialTab ?? requestedTab); + }, [initialTab, requestedTab]); + + useEffect(() => { + if (presentation === 'page') closeStoreSurface(); + }, [closeStoreSurface, presentation]); + + const runSessionById = useMemo(() => Object.fromEntries( + fleet.runs.map((run) => [run.id, run.session_id]) + ), [fleet.runs]); + const attentionByOrchestrator = useMemo(() => assignAttentionToOrchestrators( + items, + fleet.cards.map((card) => ({ + orchestratorId: card.session.id, + sessionIds: card.children.map((child) => child.id), + })), + runSessionById + ), [fleet.cards, items, runSessionById]); + + const refreshAll = async () => { + await Promise.all([refresh(), fleet.refresh()]); + }; + const allErrors = [...errors, ...fleet.errors]; + + return ( +
+
+
+
+
+

+ Review urgent work, then inspect the orchestrator fleet without changing context. +

+
+
+ + {presentation === 'sheet' && onClose && ( + + )} +
+
+ +
+ {allErrors.length > 0 && ( +
+ + Some sources are unavailable. Showing the actionable data that loaded. +
+ )} + + setActiveTab(value as AttentionTab)} className="space-y-4"> + + + Attention ({items.length}) + + + Fleet ({fleet.cards.length}) + + + + + {!summaryStatusLoading && !summariesEnabled && ( +
+ AI summaries are unavailable; queue actions and captured context still work. +
+ )} + +
+ {isLoading && ( +
+ + Loading attention sources… +
+ )} + + {!isLoading && items.length === 0 && ( +
+ +

Nothing needs your attention

+

New prompts, approvals, and failed runs will appear here.

+
+ )} + + {items.length > 0 && ( +
+ {items.map((item) => ( + void refresh()} + summariesEnabled={summariesEnabled} + showSummary={presentation === 'page'} + /> + ))} +
+ )} +
+ + {idledItems.length > 0 && ( +
+ + {idleExpanded && ( +
+ {idledItems.map((item) => ( + void refresh()} + summariesEnabled={summariesEnabled} + showSummary={presentation === 'page'} + /> + ))} +
+ )} +
+ )} +
+ + + {fleet.isLoading && ( +
+ Loading orchestrator fleet… +
+ )} + {!fleet.isLoading && fleet.cards.length === 0 && ( +
+ +

No orchestrator sessions are online

+

Sessions with the orchestrator role will appear here.

+
+ )} + {fleet.cards.map((card) => ( + void refreshAll()} + /> + ))} +
+
+
+
+ ); +} + +export function OrchestratorSheet() { + const isOpen = useOrchestratorStore((state) => state.isOpen); + const close = useOrchestratorStore((state) => state.close); + const isMobile = useIsMobile(); + + useEffect(() => { + if (isMobile && isOpen) close(); + }, [close, isMobile, isOpen]); + + if (isMobile) return null; + + return ( + !open && close()}> + + + { + event.preventDefault(); + document.getElementById('attention-bell')?.focus(); + }} + > + Attention + + + + + ); +} diff --git a/apps/dashboard/src/components/orchestrator/index.ts b/apps/dashboard/src/components/orchestrator/index.ts index 284605aa..88c6f287 100644 --- a/apps/dashboard/src/components/orchestrator/index.ts +++ b/apps/dashboard/src/components/orchestrator/index.ts @@ -1,4 +1,4 @@ -export { OrchestratorModal } from './OrchestratorModal'; +export { OrchestratorSheet, OrchestratorSurface } from './OrchestratorSurface'; export { OrchestratorItem } from './OrchestratorItem'; export { OrchestratorButton } from './OrchestratorButton'; export { diff --git a/apps/dashboard/src/components/session-generator/RepoPicker.tsx b/apps/dashboard/src/components/session-generator/RepoPicker.tsx index 7845412f..e2f00133 100644 --- a/apps/dashboard/src/components/session-generator/RepoPicker.tsx +++ b/apps/dashboard/src/components/session-generator/RepoPicker.tsx @@ -2,7 +2,7 @@ import { useState, useMemo, useEffect } from 'react'; import { useQuery } from '@tanstack/react-query'; -import { Server, FolderPlus, ChevronRight, Home, Settings } from 'lucide-react'; +import { Server, FolderGit, FolderPlus, ChevronRight, Home, Settings } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { cn } from '@/lib/utils'; import { getHosts, type DirectoryEntry } from '@/lib/api'; @@ -66,6 +66,19 @@ export function RepoPicker({ () => devFolders.filter((f) => f.hostId === hostId), [devFolders, hostId] ); + const recentRepos = useMemo(() => Object.entries(repoLastUsed) + .filter(([key]) => key.startsWith(`${hostId}:`)) + .sort(([, left], [, right]) => right - left) + .slice(0, 5) + .map(([key]) => { + const path = key.slice(hostId.length + 1); + return { + name: path.split('/').filter(Boolean).pop() || path, + path, + is_directory: true, + is_git_repo: true, + } satisfies DirectoryEntry; + }), [hostId, repoLastUsed]); // Current path to browse const currentPath = useMemo(() => { @@ -222,6 +235,33 @@ export function RepoPicker({ )} + {hostId && recentRepos.length > 0 && ( +
+
+ Recent repositories +
+
+ {recentRepos.map((repo) => ( + + ))} +
+
+ )} + {/* Breadcrumb */} {hostId && currentPath && (
@@ -246,6 +286,11 @@ export function RepoPicker({ {/* Directory tree */}
+ {hostId && ( +
+ Browse folders +
+ )} {hostId && currentPath ? ( = [ - { id: 'claude_code', name: 'Claude Code' }, - { id: 'codex', name: 'Codex' }, - { id: 'gemini_cli', name: 'Gemini CLI' }, - { id: 'opencode', name: 'OpenCode' }, - { id: 'aider', name: 'Aider' }, - { id: 'shell', name: 'Shell' }, -]; +import { + LAUNCH_PROVIDERS, + SESSION_TEMPLATES, + TEMPLATE_OPTIONS, + type SessionTemplateSession, +} from '@/components/launch/definitions'; export interface SessionConfig { provider: SpawnProvider; @@ -180,7 +176,7 @@ export function SessionConfigStep({ } className="text-sm px-2 py-1 border rounded bg-background" > - {PROVIDERS.map((p) => ( + {LAUNCH_PROVIDERS.map((p) => ( @@ -189,7 +185,7 @@ export function SessionConfigStep({ )} {selectedTemplate !== 'single' && ( - {PROVIDERS.find((p) => p.id === session.provider)?.name} + {LAUNCH_PROVIDERS.find((p) => p.id === session.provider)?.name} )}
diff --git a/apps/dashboard/src/components/session-generator/index.ts b/apps/dashboard/src/components/session-generator/index.ts index 2738b43b..1bb7be68 100644 --- a/apps/dashboard/src/components/session-generator/index.ts +++ b/apps/dashboard/src/components/session-generator/index.ts @@ -3,5 +3,13 @@ export { RepoPicker } from './RepoPicker'; export { DirectoryTree } from './DirectoryTree'; export { SessionConfigStep } from './SessionConfigStep'; export type { SessionConfig } from './SessionConfigStep'; -export { SESSION_TEMPLATES, TEMPLATE_OPTIONS, getTemplate } from './templates'; -export type { SessionTemplate, SessionTemplateSession } from './templates'; +export { + LAUNCH_PROVIDERS, + SESSION_TEMPLATES, + TEMPLATE_OPTIONS, + getTemplate, +} from '@/components/launch/definitions'; +export type { + SessionTemplate, + SessionTemplateSession, +} from '@/components/launch/definitions'; diff --git a/apps/dashboard/src/hooks/useIsMobile.ts b/apps/dashboard/src/hooks/useIsMobile.ts index 13838070..551e67cc 100644 --- a/apps/dashboard/src/hooks/useIsMobile.ts +++ b/apps/dashboard/src/hooks/useIsMobile.ts @@ -2,12 +2,15 @@ import { useState, useEffect } from 'react'; +export const NAV_MOBILE_BREAKPOINT = 768; +export const COMMAND_CENTER_SHELL_BREAKPOINT = 1024; + /** * Hook to detect mobile viewport. * @param breakpoint - The max-width breakpoint in pixels (default: 768) * @returns true if viewport is below the breakpoint */ -export function useIsMobile(breakpoint = 768) { +export function useIsMobile(breakpoint = NAV_MOBILE_BREAKPOINT) { const [isMobile, setIsMobile] = useState(false); useEffect(() => { diff --git a/apps/dashboard/src/stores/ui.ts b/apps/dashboard/src/stores/ui.ts index e5d317ca..7cb10af6 100644 --- a/apps/dashboard/src/stores/ui.ts +++ b/apps/dashboard/src/stores/ui.ts @@ -20,7 +20,6 @@ interface UIStore { setSidebarCollapsed: (collapsed: boolean) => void; mobileMenuOpen: boolean; setMobileMenuOpen: (open: boolean) => void; - toggleMobileMenu: () => void; recentSessions: RecentSession[]; addRecentSession: (session: { id: string; @@ -48,7 +47,6 @@ export const useUIStore = create()( mobileMenuOpen: false, setMobileMenuOpen: (open) => set({ mobileMenuOpen: open }), - toggleMobileMenu: () => set((state) => ({ mobileMenuOpen: !state.mobileMenuOpen })), recentSessions: [], addRecentSession: (session) => diff --git a/tasks/frontend-ux-handoffs/fw3-shell.md b/tasks/frontend-ux-handoffs/fw3-shell.md new file mode 100644 index 00000000..8b594705 --- /dev/null +++ b/tasks/frontend-ux-handoffs/fw3-shell.md @@ -0,0 +1,52 @@ +--- +lane: FW3-SHELL +frozen_sha: 5bba177668402700f393fa9b64b64d8dc9dc83f5 +attempt: 1 +state: frozen +gates: + lint: pass + typecheck: pass + test_ci: pass + smoke: pass + build: pass + go: n/a +proof: + - "pnpm install → completed before implementation; lockfile unchanged" + - "pnpm lint → 5/5 Turbo tasks passed" + - "pnpm typecheck → 5/5 Turbo tasks passed; Next route types generated" + - "pnpm test:ci → 5/5 Turbo tasks passed, including the new launch-definition and shell-contract tests" + - "PLAYWRIGHT_DASHBOARD_PORT=3320 CHOKIDAR_USEPOLLING=1 WATCHPACK_POLLING=true pnpm test:smoke:dashboard → 13/13 passed" + - "CHOKIDAR_USEPOLLING=1 WATCHPACK_POLLING=true pnpm build → 4/4 Turbo tasks passed; Next production build completed" + - "PLAYWRIGHT_DASHBOARD_PORT=3321 CHOKIDAR_USEPOLLING=1 WATCHPACK_POLLING=true pnpm verify:launch → schema 48/48, control-plane 198/198, typechecks, and dashboard smoke 13/13 passed" + - "Browser screenshots → test-results/dashboard-renders-Command--3c155-redirects-legacy-tmux-links-chromium/command-center-{mobile,tablet,desktop}.png" + - "Orchestrator browser screenshots → test-results/dashboard-uses-unified-bot-6e796-orchestrator-card-on-mobile-chromium/orchestrator-mobile{-top,}.png" + - "Frontend quality audit → 93/100, no hard fails" +assumptions: + - "The existing design tokens and tmux component behavior remain the source of truth; this lane changes only shell-owned composition around them." + - "The /orchestrator route remains the durable deep-link target while its presentation is shared with the desktop attention sheet." +uncertainties: + - "useTmuxRosterData still emits /tmux query URLs. The canonical redirect preserves every query parameter, but a plain mobile roster selection remounts at / and leaves the operator on Roster with Terminal enabled; the verified path uses the Terminal tab. A sibling tmux lane can remove that extra tap by letting TmuxPageClient/useTmuxRosterData accept the canonical route base without duplicating shell state." +blockers: [] +--- + +# FW3-SHELL handoff + +## What changed + +- Command Center: `/` now frames the live tmux fleet with the top attention item and persistent launch rail. The v0.2 landing was removed, `/tmux` redirects to `/` while retaining query parameters, PWA/sign-in entry points are canonical, and the displaced usage/quick-stat surfaces live under Settings. +- Navigation: desktop and mobile share the Command Center, Attention, and Sessions destinations. Mobile has a single More-owned drawer, the hamburger is gone, the header is reduced to identity, connection, attention, theme, and account controls, and nav targets meet the 44px minimum. +- Attention: page and desktop-sheet presentations now render one `OrchestratorSurface` tree fed by `useAttentionQueue`; the prior modal/page duplication is deleted. Mobile bell and tab both route to the page, while desktop bell opens the focus-restoring sheet. +- Launch: Command Center and Sessions use one `LaunchRail` and one `MobileLaunchSheet` for New, Recent, and Open existing. Provider/template definitions and recent-launch persistence are centralized, repository recents lead the picker, and the legacy spawn dialog is deleted. +- Tests: added shell-contract and definition unit coverage plus mobile/tablet/desktop smoke coverage for canonical routing, unified navigation, shared attention presentation, launch entry points, tap sizes, and horizontal overflow. + +## Decisions and quality review + +- Kept the 768px navigation contract and the explicit 1024px Command Center shell switch in the shared `useIsMobile` source. +- Preserved the tmux ownership firewall. No files under `src/components/tmux/**`, terminal/session internals, packages, services, agents, or deploy were edited. +- Frontend audit: Product fit 15/15, information architecture 15/15, visual design 13/15, dashboard clarity 14/15, interaction states 9/10, accessibility 13/15, responsive behavior 10/10, performance polish 4/5 = 93/100. No hard fails. Chromium screenshots were visually inspected at 390x844, 768x1024, and 1280x720. + +## Deferred to the tmux owner + +Expose a canonical route-base option for `TmuxPageClient`/`useTmuxRosterData` so root-mounted selection updates `/?...` directly. That will preserve the existing automatic mobile roster-to-terminal transition without this lane changing tmux internals. + +FW3-SHELL FROZEN 5bba177668402700f393fa9b64b64d8dc9dc83f5 diff --git a/tests/smoke/dashboard.spec.ts b/tests/smoke/dashboard.spec.ts index facf617d..ce2c7167 100644 --- a/tests/smoke/dashboard.spec.ts +++ b/tests/smoke/dashboard.spec.ts @@ -71,6 +71,7 @@ const tmuxSessions = [ latest_snapshot: { created_at: '2026-05-19T18:00:00.000Z', capture_text: 'pnpm test:ci', + capture_hash: 'capture-codex-implementation', }, }, { @@ -107,6 +108,7 @@ const tmuxSessions = [ latest_snapshot: { created_at: '2026-05-19T17:55:00.000Z', capture_text: 'Need input', + capture_hash: 'capture-mobile-ux-review', }, }, { @@ -144,6 +146,7 @@ const tmuxSessions = [ latest_snapshot: { created_at: '2026-05-19T17:00:00.000Z', capture_text: 'tail -f logs', + capture_hash: 'capture-deploy-logs', }, }, ]; @@ -168,6 +171,7 @@ const orchestratorSessions = [ latest_snapshot: { created_at: '2026-05-19T18:00:00.000Z', capture_text: 'Approve the production verification command?', + capture_hash: 'capture-release-orchestrator', }, }, { @@ -307,6 +311,7 @@ function apiBody(pathname: string): unknown { return { sessions: tmuxSessions, total: tmuxSessions.length, + groups: [], }; } if (pathname === '/v1/launch/targets') { @@ -478,7 +483,7 @@ async function mockControlPlane(page: Page): Promise { const sessions = url.searchParams.get('host_id') === secondTmuxHost.id ? [remoteTmuxSession] : tmuxSessions; - await fulfillJson(route, { sessions, total: sessions.length }); + await fulfillJson(route, { sessions, total: sessions.length, groups: [] }); return; } if (route.request().method() === 'POST' && url.pathname === '/v1/launch') { @@ -604,14 +609,14 @@ test('protects operator routes behind credentials sign-in', async ({ page }) => await expect(page).toHaveURL(/\/signin/); await signIn(page); - await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); + await expect(page.getByRole('heading', { name: 'Command Center' })).toBeVisible(); }); test('renders key operator pages with mocked control-plane data', async ({ page }) => { await signIn(page); const pages = [ - ['/', 'Dashboard'], + ['/', 'Command Center'], ['/sessions', 'Sessions'], ['/automation', 'Automation'], ['/memory', 'Memory'], @@ -626,6 +631,94 @@ test('renders key operator pages with mocked control-plane data', async ({ page } }); +test('renders Command Center at mobile and desktop widths and redirects legacy tmux links', async ({ page }, testInfo) => { + await signIn(page); + + for (const viewport of [ + { name: 'mobile', width: 390, height: 844 }, + { name: 'tablet', width: 768, height: 1024 }, + { name: 'desktop', width: 1280, height: 720 }, + ]) { + await page.setViewportSize({ width: viewport.width, height: viewport.height }); + await page.goto('/'); + await expect(page.getByRole('heading', { name: 'Command Center' })).toBeVisible(); + await expect(page.getByRole('heading', { name: 'tmux', exact: true })).toBeVisible(); + await expect(page.getByRole('region', { name: 'Launch' })).toBeVisible(); + await expect(page.getByText('New in v0.2.0')).toHaveCount(0); + await expect(page.getByRole('button', { name: 'Open menu' })).toHaveCount(0); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true); + + if (viewport.name === 'mobile') { + const mobileTargets = page.getByRole('navigation', { name: 'Primary mobile navigation' }).locator('a, button'); + await expect(mobileTargets).toHaveCount(4); + const targetSizes = await mobileTargets.evaluateAll((targets) => ( + targets.map((target) => { + const { width, height } = target.getBoundingClientRect(); + return { width, height }; + }) + )); + expect(targetSizes.every(({ width, height }) => width >= 44 && height >= 44)).toBe(true); + } + + if (process.env.PLAYWRIGHT_CAPTURE_UI === '1') { + await page.screenshot({ path: testInfo.outputPath(`command-center-${viewport.name}.png`), fullPage: true }); + } + } + + await page.goto('/tmux?filter=waiting&host_id=all'); + await expect(page).toHaveURL(/\/\?filter=waiting&host_id=all$/); + await expect(page.getByRole('heading', { name: 'Command Center' })).toBeVisible(); + await expect(page.getByRole('button', { name: 'Waiting', exact: true })).toBeVisible(); +}); + +test('opens the single launch sheet from Command Center and Sessions rails', async ({ page }) => { + await signIn(page); + + const commandCenterRail = page.getByRole('region', { name: 'Launch' }); + await commandCenterRail.getByRole('button', { name: 'New', exact: true }).click(); + await expect(page.getByRole('dialog', { name: 'Launch agent' })).toBeVisible(); + await page.getByRole('button', { name: 'Close launch sheet' }).click(); + + await commandCenterRail.getByRole('button', { name: 'Recent', exact: true }).click(); + await expect(page.getByRole('dialog', { name: 'Recent launches' })).toBeVisible(); + await page.getByRole('button', { name: 'Close launch sheet' }).click(); + + await commandCenterRail.getByRole('button', { name: /Open existing/ }).click(); + await expect(page.getByRole('dialog', { name: 'Open existing' })).toBeVisible(); + await expect(page.getByPlaceholder('agents:0.0 or %1')).toBeVisible(); + await page.getByRole('button', { name: 'Close launch sheet' }).click(); + + await page.goto('/sessions'); + await expect(page.getByRole('region', { name: 'Launch' })).toBeVisible(); +}); + +test('uses the same attention surface for the mobile bell, tab, and desktop sheet', async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + await signIn(page); + + await page.getByRole('button', { name: /^Attention -/ }).click(); + await expect(page).toHaveURL(/\/orchestrator\?tab=attention/); + await expect(page.getByTestId('attention-surface')).toHaveAttribute('data-presentation', 'page'); + await expect(page.getByRole('tab', { name: /Attention/ })).toHaveAttribute('data-state', 'active'); + + await page.goto('/'); + const mobileNav = page.getByRole('navigation', { name: 'Primary mobile navigation' }); + await mobileNav.getByRole('link', { name: 'Attention' }).click(); + await expect(page).toHaveURL(/\/orchestrator\?tab=attention/); + await expect(page.getByTestId('attention-surface')).toHaveAttribute('data-presentation', 'page'); + + await page.setViewportSize({ width: 1280, height: 720 }); + await page.goto('/'); + const desktopBell = page.getByRole('button', { name: /^Attention -/ }); + await desktopBell.click(); + const sheet = page.getByRole('dialog', { name: 'Attention' }); + await expect(sheet).toBeVisible(); + await expect(sheet.getByTestId('attention-surface')).toHaveAttribute('data-presentation', 'sheet'); + await page.keyboard.press('Escape'); + await expect(sheet).not.toBeVisible(); + await expect(desktopBell).toBeFocused(); +}); + test('renders tmux roster with windows and panes, supports selection and filtering', async ({ page }) => { await signIn(page); @@ -677,6 +770,8 @@ test('keeps the tmux roster usable on mobile viewport', async ({ page }) => { await page.getByText('Mobile UX review').click(); await expect(page).toHaveURL(/session_id=33333333-3333-4333-8333-333333333333/); + await expect(page.getByRole('button', { name: 'Terminal', exact: true })).toBeEnabled(); + await page.getByRole('button', { name: 'Terminal', exact: true }).click(); await expect(page.getByText('agents:0.1').first()).toBeVisible(); await expect(page.getByRole('button', { name: 'Actions', exact: true })).toBeEnabled(); @@ -758,18 +853,20 @@ test('opens an existing tmux target from the mobile launch sheet', async ({ page await expect(page).toHaveURL(/mode=terminal/); }); -test('uses bottom navigation to steer an orchestrator card on mobile', async ({ page }, testInfo) => { +test('uses unified bottom navigation to steer an orchestrator card on mobile', async ({ page }, testInfo) => { await page.setViewportSize({ width: 390, height: 844 }); await signIn(page); const mobileNav = page.getByRole('navigation', { name: 'Primary mobile navigation' }); - await expect(mobileNav.getByRole('link', { name: 'tmux' })).toBeVisible(); - await expect(mobileNav.getByRole('link', { name: 'Orchestrator' })).toBeVisible(); + await expect(mobileNav.getByRole('link', { name: 'Command Center' })).toBeVisible(); + await expect(mobileNav.getByRole('link', { name: 'Attention' })).toBeVisible(); await expect(mobileNav.getByRole('link', { name: 'Sessions' })).toBeVisible(); await expect(mobileNav.getByRole('button', { name: 'More' })).toBeVisible(); - await mobileNav.getByRole('link', { name: 'Orchestrator' }).click(); - await expect(page).toHaveURL(/\/orchestrator/); + await mobileNav.getByRole('link', { name: 'Attention' }).click(); + await expect(page).toHaveURL(/\/orchestrator\?tab=attention/); + await expect(page.getByRole('tab', { name: /Attention/ })).toHaveAttribute('data-state', 'active'); + await page.getByRole('tab', { name: /Fleet/ }).click(); const card = page.getByTestId('orchestrator-card'); await expect(card).toContainText('Release orchestrator'); await expect(card).toContainText('Verification worker'); From 7dfcf787523e524ed48ed42b5b27d3fc922e92f5 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 13:27:05 -0400 Subject: [PATCH 04/13] chore(program): FW3-SHELL accepted and integrated Co-Authored-By: Claude Fable 5 --- tasks/frontend-ux-log.md | 1 + tasks/frontend-ux-metrics.jsonl | 1 + 2 files changed, 2 insertions(+) diff --git a/tasks/frontend-ux-log.md b/tasks/frontend-ux-log.md index 482a1ea7..27d94ff1 100644 --- a/tasks/frontend-ux-log.md +++ b/tasks/frontend-ux-log.md @@ -25,3 +25,4 @@ - ~21:20Z Wave-2 MERGED (effab04) + DEPLOYED (SOURCE_COMMIT verified, health ok). PR-review fixes: scrollback 502 on agent-side failure; board policy text synced. - agentd rollout: new binary BUILT at effab04 and staged at /tmp/agentd-new on heavisidelinux (temp worktree /tmp/ac-build-effab04; backup ~/.local/bin/agentd.bak-fw2 exists). In-place replacement of the RUNNING binary was blocked by the local permission policy — HELD FOR OWNER: run `rm ~/.local/bin/agentd && cp /tmp/agentd-new ~/.local/bin/agentd && systemctl --user restart agentd` on heavisidelinux, then optionally set `topology_events: true` under tmux: in ~/.config/agentd/config.yaml. Program continues regardless (Wave-3 UI has roster fallback). - Wave 3 launched: FW3-SHELL + FW3-TMUX-UI codex lanes active on homelinux (activation verified). +- ~22:20Z FW3-SHELL froze at `5bba177` (attempt 1): gate re-run green, firewall clean, net-negative diff (legacy landing + SpawnSessionDialog + OrchestratorModal duplication deleted; launch definitions centralized). Flagged cross-lane seam (useTmuxRosterData /tmux URLs) steered to FW3-TMUX-UI mid-flight. INTEGRATED @ a5788af. diff --git a/tasks/frontend-ux-metrics.jsonl b/tasks/frontend-ux-metrics.jsonl index 58776e12..58a612d7 100644 --- a/tasks/frontend-ux-metrics.jsonl +++ b/tasks/frontend-ux-metrics.jsonl @@ -10,3 +10,4 @@ {"ts":"2026-07-20T20:50:00Z","event":"wave_complete","wave":2,"reviewer_verdict":"SHIP-WITH-NOTES","notes_closed_in":"FW2-CONTRACTS-R2","gate":"green"} {"ts":"2026-07-20T21:20:00Z","event":"wave_deployed","wave":2,"sha":"effab04"} {"ts":"2026-07-20T21:25:00Z","event":"wave_launched","wave":3,"lanes":["FW3-SHELL","FW3-TMUX-UI"]} +{"ts":"2026-07-20T22:20:00Z","event":"lane_frozen","lane":"FW3-SHELL","attempt":1,"frozen_sha":"5bba177","verdict":"accepted","integrated_sha":"a5788af"} From bab4c5f905aa31b422d4e338343160d8ff4e1d17 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 13:43:37 -0400 Subject: [PATCH 05/13] feat(tmux-ui): topology-fed window strip + pane controls, desktop 2-up terminals, mobile quick-switch, scrollback pager, desktop key bar (FW3-TMUX-UI 6526629) Co-Authored-By: Claude Fable 5 --- .../components/session/SessionWorkbench.tsx | 11 +- .../components/terminal/ScrollbackPager.tsx | 303 ++++++++++++++++ .../components/terminal/TerminalSurface.tsx | 4 +- .../terminal/scrollbackPaging.test.ts | 13 + .../components/terminal/scrollbackPaging.ts | 21 ++ .../src/components/tmux/TmuxActionSheet.tsx | 5 +- .../src/components/tmux/TmuxKeyBar.tsx | 44 ++- .../src/components/tmux/TmuxMobileShell.tsx | 7 + .../src/components/tmux/TmuxPaneControls.tsx | 271 ++++++++++++++ .../components/tmux/TmuxQuickSwitchStrip.tsx | 74 ++++ .../components/tmux/TmuxTerminalWorkspace.tsx | 189 ++++++++++ .../src/components/tmux/TmuxWindowStrip.tsx | 339 ++++++++++++++++++ .../src/components/tmux/paneActions.test.ts | 41 +++ .../src/components/tmux/paneActions.ts | 41 +++ .../src/components/tmux/quickSwitch.test.ts | 24 ++ .../src/components/tmux/quickSwitch.ts | 32 ++ .../src/components/tmux/windowActions.test.ts | 99 +++++ .../src/components/tmux/windowActions.ts | 63 ++++ .../src/hooks/useTmuxRosterData.test.ts | 18 + apps/dashboard/src/hooks/useTmuxRosterData.ts | 146 +++++--- apps/dashboard/src/hooks/useTmuxTopology.ts | 53 +++ apps/dashboard/src/lib/api.ts | 12 + apps/dashboard/src/stores/settings.ts | 14 + .../dashboard/src/stores/tmuxTopology.test.ts | 157 ++++++++ apps/dashboard/src/stores/tmuxTopology.ts | 231 ++++++++++++ tasks/frontend-ux-handoffs/fw3-tmux-ui.md | 70 ++++ tasks/lessons.md | 4 + tests/smoke/dashboard.spec.ts | 82 ++++- 28 files changed, 2290 insertions(+), 78 deletions(-) create mode 100644 apps/dashboard/src/components/terminal/ScrollbackPager.tsx create mode 100644 apps/dashboard/src/components/terminal/scrollbackPaging.test.ts create mode 100644 apps/dashboard/src/components/terminal/scrollbackPaging.ts create mode 100644 apps/dashboard/src/components/tmux/TmuxPaneControls.tsx create mode 100644 apps/dashboard/src/components/tmux/TmuxQuickSwitchStrip.tsx create mode 100644 apps/dashboard/src/components/tmux/TmuxTerminalWorkspace.tsx create mode 100644 apps/dashboard/src/components/tmux/TmuxWindowStrip.tsx create mode 100644 apps/dashboard/src/components/tmux/paneActions.test.ts create mode 100644 apps/dashboard/src/components/tmux/paneActions.ts create mode 100644 apps/dashboard/src/components/tmux/quickSwitch.test.ts create mode 100644 apps/dashboard/src/components/tmux/quickSwitch.ts create mode 100644 apps/dashboard/src/components/tmux/windowActions.test.ts create mode 100644 apps/dashboard/src/components/tmux/windowActions.ts create mode 100644 apps/dashboard/src/hooks/useTmuxRosterData.test.ts create mode 100644 apps/dashboard/src/hooks/useTmuxTopology.ts create mode 100644 apps/dashboard/src/stores/tmuxTopology.test.ts create mode 100644 apps/dashboard/src/stores/tmuxTopology.ts create mode 100644 tasks/frontend-ux-handoffs/fw3-tmux-ui.md diff --git a/apps/dashboard/src/components/session/SessionWorkbench.tsx b/apps/dashboard/src/components/session/SessionWorkbench.tsx index 965de359..11bc325c 100644 --- a/apps/dashboard/src/components/session/SessionWorkbench.tsx +++ b/apps/dashboard/src/components/session/SessionWorkbench.tsx @@ -9,7 +9,7 @@ import { ConsoleView } from '@/components/ConsoleView'; import { LinkedSessionsPanel } from '@/components/LinkedSessionsPanel'; import { SessionAnalytics } from '@/components/analytics/SessionAnalytics'; import type { TerminalController } from '@/components/TerminalView'; -import { PersistentTerminalSlot } from '@/components/terminal/PersistentTerminalHost'; +import { TmuxTerminalWorkspace } from '@/components/tmux/TmuxTerminalWorkspace'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { useHydrated } from '@/hooks/useHydrated'; @@ -187,11 +187,10 @@ export function SessionWorkbench({ provider={session.provider} /> ) : ( - )} diff --git a/apps/dashboard/src/components/terminal/ScrollbackPager.tsx b/apps/dashboard/src/components/terminal/ScrollbackPager.tsx new file mode 100644 index 00000000..b735cd41 --- /dev/null +++ b/apps/dashboard/src/components/terminal/ScrollbackPager.tsx @@ -0,0 +1,303 @@ +'use client'; + +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import * as Dialog from '@radix-ui/react-dialog'; +import { Clipboard, History, Loader2, Search, X } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { getSessionScrollback } from '@/lib/api'; +import { useNotifications } from '@/stores/notifications'; +import { + SCROLLBACK_PAGE_LINES, + initialScrollbackRange, + olderScrollbackRange, + type ScrollbackRange, +} from './scrollbackPaging'; + +interface ScrollbackPagerProps { + sessionId: string; + open: boolean; + onClose: () => void; +} + +interface HistoryPage { + range: ScrollbackRange; + lines: string[]; +} + +const LINE_HEIGHT = 20; +const OVERSCAN = 12; +const VIEWPORT_LINE_ESTIMATE = 36; + +function contentLines(content: unknown): string[] { + if (typeof content !== 'string' || content.length === 0) return []; + const lines = content.split('\n'); + if (content.endsWith('\n')) lines.pop(); + return lines; +} + +export function ScrollbackPager({ sessionId, open, onClose }: ScrollbackPagerProps) { + const [pages, setPages] = useState([]); + const [filter, setFilter] = useState(''); + const [loadingInitial, setLoadingInitial] = useState(false); + const [loadingOlder, setLoadingOlder] = useState(false); + const [hasOlder, setHasOlder] = useState(true); + const [error, setError] = useState(null); + const [scrollTop, setScrollTop] = useState(0); + const [copied, setCopied] = useState(false); + const scrollRef = useRef(null); + const generationRef = useRef(0); + const notifications = useNotifications(); + + const fetchPage = useCallback( + async (range: ScrollbackRange): Promise => { + const response = await getSessionScrollback(sessionId, { + mode: 'range', + start_line: range.startLine, + end_line: range.endLine, + strip_ansi: true, + }); + if (!response.ok) { + throw new Error(response.error?.message || 'Scrollback capture failed.'); + } + return { + range, + lines: contentLines(response.result?.content), + }; + }, + [sessionId] + ); + + const loadInitial = useCallback(async () => { + const generation = ++generationRef.current; + setLoadingInitial(true); + setError(null); + setPages([]); + setHasOlder(true); + setScrollTop(0); + try { + const page = await fetchPage(initialScrollbackRange()); + if (generationRef.current !== generation) return; + setPages([page]); + setHasOlder(page.lines.length >= SCROLLBACK_PAGE_LINES); + requestAnimationFrame(() => { + const element = scrollRef.current; + if (element) element.scrollTop = element.scrollHeight; + }); + } catch (loadError) { + if (generationRef.current !== generation) return; + setError( + loadError instanceof Error ? loadError.message : 'Terminal history could not be loaded.' + ); + } finally { + if (generationRef.current === generation) setLoadingInitial(false); + } + }, [fetchPage]); + + useEffect(() => { + if (!open) { + generationRef.current += 1; + return; + } + setFilter(''); + setCopied(false); + void loadInitial(); + }, [loadInitial, open]); + + const loadOlder = async () => { + if (loadingOlder || !hasOlder) return; + const currentOldest = pages[0]?.range ?? initialScrollbackRange(); + const range = olderScrollbackRange(currentOldest); + const element = scrollRef.current; + const previousHeight = element?.scrollHeight ?? 0; + setLoadingOlder(true); + setError(null); + try { + const page = await fetchPage(range); + setPages((current) => [page, ...current]); + setHasOlder(page.lines.length >= SCROLLBACK_PAGE_LINES); + requestAnimationFrame(() => { + if (element) element.scrollTop += element.scrollHeight - previousHeight; + }); + } catch (loadError) { + setError( + loadError instanceof Error ? loadError.message : 'Older history could not be loaded.' + ); + } finally { + setLoadingOlder(false); + } + }; + + const allLines = useMemo(() => pages.flatMap((page) => page.lines), [pages]); + const filteredLines = useMemo(() => { + const query = filter.trim().toLowerCase(); + return allLines + .map((text, index) => ({ text, originalIndex: index })) + .filter((line) => !query || line.text.toLowerCase().includes(query)); + }, [allLines, filter]); + const startIndex = Math.max(0, Math.floor(scrollTop / LINE_HEIGHT) - OVERSCAN); + const endIndex = Math.min( + filteredLines.length, + startIndex + VIEWPORT_LINE_ESTIMATE + OVERSCAN * 2 + ); + const visibleLines = filteredLines.slice(startIndex, endIndex); + + const changeFilter = (value: string) => { + setFilter(value); + setScrollTop(0); + if (scrollRef.current) scrollRef.current.scrollTop = 0; + }; + + const copyHistory = async () => { + try { + await navigator.clipboard.writeText(filteredLines.map((line) => line.text).join('\n')); + setCopied(true); + window.setTimeout(() => setCopied(false), 1600); + } catch (copyError) { + notifications.error( + 'Could not copy terminal history', + copyError instanceof Error ? copyError.message : 'Clipboard access was denied.', + { sessionId } + ); + } + }; + + return ( + !nextOpen && onClose()}> + + + +
+
+ +
+ + + {filteredLines.length.toLocaleString()} {filter ? 'matches' : 'lines'} + + +
+ + {error && ( +
+ {error} + {pages.length === 0 && ( + + )} +
+ )} + +
setScrollTop(event.currentTarget.scrollTop)} + className="min-h-0 flex-1 overflow-auto bg-[#0a0a0a] text-[#f2f2f2] selection:bg-sky-600/70" + tabIndex={0} + aria-label="Captured terminal history" + > +
+ +
+ + {loadingInitial ? ( +
+
+ ) : filteredLines.length === 0 ? ( +
+ {allLines.length === 0 + ? 'No older history was captured.' + : 'No history lines match this filter.'} +
+ ) : ( +
+ {visibleLines.map((line, offset) => { + const virtualIndex = startIndex + offset; + return ( +
+ {line.text || ' '} +
+ ); + })} +
+ )} +
+
+
+
+ ); +} diff --git a/apps/dashboard/src/components/terminal/TerminalSurface.tsx b/apps/dashboard/src/components/terminal/TerminalSurface.tsx index efb9fdce..7417b48d 100644 --- a/apps/dashboard/src/components/terminal/TerminalSurface.tsx +++ b/apps/dashboard/src/components/terminal/TerminalSurface.tsx @@ -128,8 +128,8 @@ export function TerminalSurface({ {status === 'connected' && !readOnly && (
- {isMobile && paneId && ( - + {paneId && ( + )} { + it('requests contiguous older ranges without touching the live xterm buffer', () => { + const initial = initialScrollbackRange(); + const older = olderScrollbackRange(initial); + + expect(initial).toEqual({ startLine: -500, endLine: -1 }); + expect(older).toEqual({ startLine: -1000, endLine: -501 }); + expect(older.endLine + 1).toBe(initial.startLine); + }); +}); diff --git a/apps/dashboard/src/components/terminal/scrollbackPaging.ts b/apps/dashboard/src/components/terminal/scrollbackPaging.ts new file mode 100644 index 00000000..a54508c7 --- /dev/null +++ b/apps/dashboard/src/components/terminal/scrollbackPaging.ts @@ -0,0 +1,21 @@ +export const SCROLLBACK_PAGE_LINES = 500; + +export interface ScrollbackRange { + startLine: number; + endLine: number; +} + +export function initialScrollbackRange(): ScrollbackRange { + return { + startLine: -SCROLLBACK_PAGE_LINES, + endLine: -1, + }; +} + +export function olderScrollbackRange(range: ScrollbackRange): ScrollbackRange { + const endLine = range.startLine - 1; + return { + startLine: endLine - SCROLLBACK_PAGE_LINES + 1, + endLine, + }; +} diff --git a/apps/dashboard/src/components/tmux/TmuxActionSheet.tsx b/apps/dashboard/src/components/tmux/TmuxActionSheet.tsx index 5bcd6043..6a199d0d 100644 --- a/apps/dashboard/src/components/tmux/TmuxActionSheet.tsx +++ b/apps/dashboard/src/components/tmux/TmuxActionSheet.tsx @@ -22,6 +22,7 @@ import type { Session } from '@agent-command/schema'; import type { TerminalController } from '@/components/TerminalView'; import { Button } from '@/components/ui/button'; import { getSessionDisplayName } from '@/lib/utils'; +import { TmuxPaneControls } from './TmuxPaneControls'; interface TmuxActionSheetProps { open: boolean; @@ -111,6 +112,8 @@ export function TmuxActionSheet({
+ {session && } +
diff --git a/apps/dashboard/src/components/tmux/TmuxKeyBar.tsx b/apps/dashboard/src/components/tmux/TmuxKeyBar.tsx index 8d3eef99..75c4ca91 100644 --- a/apps/dashboard/src/components/tmux/TmuxKeyBar.tsx +++ b/apps/dashboard/src/components/tmux/TmuxKeyBar.tsx @@ -1,13 +1,15 @@ 'use client'; -import { ChevronDown, ChevronLeft, ChevronRight, ChevronUp } from 'lucide-react'; +import { ChevronDown, ChevronLeft, ChevronRight, ChevronUp, Keyboard } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { TMUX_SHORTCUT_KEYS, type TmuxShortcutKey } from '@/lib/tmuxKeys'; import { cn } from '@/lib/utils'; +import { useSettingsStore } from '@/stores/settings'; interface TmuxKeyBarProps { onInput: (data: string) => void; className?: string; + collapsible?: boolean; } function renderIcon(icon: TmuxShortcutKey['icon']) { @@ -25,13 +27,51 @@ function renderIcon(icon: TmuxShortcutKey['icon']) { } } -export function TmuxKeyBar({ onInput, className }: TmuxKeyBarProps) { +export function TmuxKeyBar({ onInput, className, collapsible = false }: TmuxKeyBarProps) { + const expanded = useSettingsStore((state) => state.tmuxKeyBarExpanded); + const setExpanded = useSettingsStore((state) => state.setTmuxKeyBarExpanded); + + if (collapsible && !expanded) { + return ( +
+ +
+ ); + } + return (
+ {collapsible && ( +
+ tmux keys + +
+ )}
{TMUX_SHORTCUT_KEYS.map((key) => ( + + + + + {variant === 'sheet' && ( +
+ + + + +
+ )} + + {variant === 'desktop' && ( + <> +
+ + + )} +
+ setHistoryOpen(false)} + /> + + ); +} diff --git a/apps/dashboard/src/components/tmux/TmuxQuickSwitchStrip.tsx b/apps/dashboard/src/components/tmux/TmuxQuickSwitchStrip.tsx new file mode 100644 index 00000000..6aaef856 --- /dev/null +++ b/apps/dashboard/src/components/tmux/TmuxQuickSwitchStrip.tsx @@ -0,0 +1,74 @@ +'use client'; + +import type { SessionWithSnapshot } from '@agent-command/schema'; +import { cn, getSessionDisplayName } from '@/lib/utils'; +import { useUIStore } from '@/stores/ui'; +import { getRecentTmuxPanes } from './quickSwitch'; + +interface TmuxQuickSwitchStripProps { + sessions: SessionWithSnapshot[]; + selectedSessionId: string; + onSelectSession: (sessionId: string) => void; +} + +function statusColor(status: string): string { + switch (status) { + case 'RUNNING': + case 'STARTING': + return 'bg-emerald-500'; + case 'WAITING_FOR_INPUT': + case 'WAITING_FOR_APPROVAL': + return 'bg-amber-500'; + case 'ERROR': + return 'bg-red-500'; + case 'IDLE': + return 'bg-slate-400'; + default: + return 'bg-gray-400'; + } +} + +export function TmuxQuickSwitchStrip({ + sessions, + selectedSessionId, + onSelectSession, +}: TmuxQuickSwitchStripProps) { + const recentSessions = useUIStore((state) => state.recentSessions); + const panes = getRecentTmuxPanes(recentSessions, sessions, selectedSessionId); + if (panes.length === 0) return null; + + return ( +
+
+ {panes.map((session) => { + const selected = session.id === selectedSessionId; + return ( + + ); + })} +
+
+ ); +} diff --git a/apps/dashboard/src/components/tmux/TmuxTerminalWorkspace.tsx b/apps/dashboard/src/components/tmux/TmuxTerminalWorkspace.tsx new file mode 100644 index 00000000..f9fae872 --- /dev/null +++ b/apps/dashboard/src/components/tmux/TmuxTerminalWorkspace.tsx @@ -0,0 +1,189 @@ +'use client'; + +import { useEffect, useMemo, type MutableRefObject } from 'react'; +import { useQuery } from '@tanstack/react-query'; +import { Columns2, X } from 'lucide-react'; +import type { Session } from '@agent-command/schema'; +import { TerminalView, type TerminalController } from '@/components/TerminalView'; +import { PersistentTerminalSlot } from '@/components/terminal/PersistentTerminalHost'; +import { Button } from '@/components/ui/button'; +import { useHydrated } from '@/hooks/useHydrated'; +import { useIsMobile } from '@/hooks/useIsMobile'; +import { getSession, getTmuxRoster } from '@/lib/api'; +import { getSessionDisplayName } from '@/lib/utils'; +import { useSettingsStore } from '@/stores/settings'; +import { TmuxPaneControls } from './TmuxPaneControls'; +import { TmuxWindowStrip } from './TmuxWindowStrip'; + +interface TmuxTerminalWorkspaceProps { + primarySession: Session; + autoAttachPrimary?: boolean; + primaryControllerRef?: MutableRefObject; +} + +function TerminalLabel({ + label, + session, + onClose, +}: { + label: string; + session: Session; + onClose?: () => void; +}) { + return ( +
+ + {label} + + + {getSessionDisplayName(session)} + + {onClose && ( + + )} +
+ ); +} + +export function TmuxTerminalWorkspace({ + primarySession, + autoAttachPrimary = false, + primaryControllerRef, +}: TmuxTerminalWorkspaceProps) { + const hydrated = useHydrated(); + const belowDesktop = useIsMobile(1024); + const rememberedSecondaryId = useSettingsStore( + (state) => state.tmuxSecondaryByPrimary[primarySession.id] ?? '' + ); + const setSecondary = useSettingsStore((state) => state.setTmuxSecondary); + const { data: rosterData } = useQuery({ + queryKey: ['sessions', 'tmux', primarySession.host_id, 'two-up-options'], + queryFn: () => getTmuxRoster({ host_id: primarySession.host_id }), + staleTime: 30_000, + }); + const options = useMemo( + () => + (rosterData?.sessions ?? []).filter( + (session) => + session.id !== primarySession.id && Boolean(session.tmux_pane_id) && !session.archived_at + ), + [primarySession.id, rosterData?.sessions] + ); + const secondaryId = hydrated && !belowDesktop ? rememberedSecondaryId : ''; + const { + data: secondaryDetail, + isLoading: secondaryLoading, + isError: secondaryError, + } = useQuery({ + queryKey: ['session', secondaryId], + queryFn: () => getSession(secondaryId), + enabled: Boolean(secondaryId), + }); + const secondarySession = secondaryDetail?.session; + + useEffect(() => { + if (!rosterData || !rememberedSecondaryId) return; + if (options.some((session) => session.id === rememberedSecondaryId)) return; + setSecondary(primarySession.id, null); + }, [options, primarySession.id, rememberedSecondaryId, rosterData, setSecondary]); + + const showSecondary = Boolean(secondaryId); + + return ( +
+
+
+ +
+
+ {showSecondary && } + + + +
+ + {showSecondary && ( +
+ {secondarySession ? ( + <> + setSecondary(primarySession.id, null)} + /> + + + + + ) : ( +
+ {secondaryError + ? 'The secondary terminal could not be loaded.' + : secondaryLoading + ? 'Loading secondary terminal…' + : 'Secondary terminal unavailable.'} +
+ )} +
+ )} +
+
+ ); +} diff --git a/apps/dashboard/src/components/tmux/TmuxWindowStrip.tsx b/apps/dashboard/src/components/tmux/TmuxWindowStrip.tsx new file mode 100644 index 00000000..7424ba3e --- /dev/null +++ b/apps/dashboard/src/components/tmux/TmuxWindowStrip.tsx @@ -0,0 +1,339 @@ +'use client'; + +import { useEffect, useMemo, useRef, useState } from 'react'; +import { Bell, MoreHorizontal, Plus, Radio, X } from 'lucide-react'; +import type { Session } from '@agent-command/schema'; +import { Button } from '@/components/ui/button'; +import { useTmuxHostTopology } from '@/hooks/useTmuxTopology'; +import { cn } from '@/lib/utils'; +import { useNotifications } from '@/stores/notifications'; +import type { TmuxWindowTopologyView } from '@/stores/tmuxTopology'; +import { runTmuxWindowAction, type TmuxWindowAction } from './windowActions'; + +interface TmuxWindowStripProps { + session: Session; + className?: string; +} + +function sessionIdentity(session: Session) { + const tmux = session.metadata?.tmux; + const targetIndexes = session.tmux_target?.match(/:(\d+)(?:\.(\d+))?$/); + const windowIndex = + session.tmux_window_index ?? tmux?.window_index ?? Number(targetIndexes?.[1] ?? 0); + return { + sessionName: + session.tmux_session_name || + tmux?.session_name || + session.tmux_target?.split(':')[0] || + 'tmux', + windowIndex, + paneIndex: session.tmux_pane_index ?? tmux?.pane_index ?? Number(targetIndexes?.[2] ?? 0), + windowName: tmux?.window_name || `window ${windowIndex}`, + }; +} + +function fallbackWindow(session: Session): TmuxWindowTopologyView { + const identity = sessionIdentity(session); + return { + windowIndex: identity.windowIndex, + windowName: identity.windowName, + active: true, + zoomed: false, + layout: '', + bell: false, + activity: false, + panes: [ + { + paneId: session.tmux_pane_id || session.id, + paneIndex: identity.paneIndex, + active: true, + title: session.title || '', + currentCommand: session.metadata?.tmux?.current_command || '', + currentPath: session.cwd || '', + sessionId: session.id, + sessionStatus: session.status, + sessionTitle: session.title, + }, + ], + }; +} + +function optimisticWindows( + windows: TmuxWindowTopologyView[], + action: TmuxWindowAction +): TmuxWindowTopologyView[] { + switch (action.type) { + case 'select': + return windows.map((window) => ({ + ...window, + active: window.windowIndex === action.windowIndex, + })); + case 'rename': + return windows.map((window) => + window.windowIndex === action.windowIndex ? { ...window, windowName: action.name } : window + ); + case 'close': + return windows.filter((window) => window.windowIndex !== action.windowIndex); + case 'new': { + const windowIndex = Math.max(-1, ...windows.map((window) => window.windowIndex)) + 1; + return [ + ...windows.map((window) => ({ ...window, active: false })), + { + windowIndex, + windowName: 'new', + active: true, + zoomed: false, + layout: '', + bell: false, + activity: false, + panes: [], + }, + ]; + } + } +} + +export function TmuxWindowStrip({ session, className }: TmuxWindowStripProps) { + const identity = useMemo(() => sessionIdentity(session), [session]); + const hostTopology = useTmuxHostTopology(session.host_id); + const topologySession = hostTopology?.sessions.find( + (candidate) => candidate.sessionName === identity.sessionName + ); + const sourceWindows = useMemo(() => { + const windows = topologySession?.windows ?? [fallbackWindow(session)]; + if (hostTopology?.source === 'topology') return windows; + return windows.map((window) => ({ + ...window, + active: window.windowIndex === identity.windowIndex, + panes: window.panes.map((pane) => ({ + ...pane, + active: pane.sessionId === session.id, + })), + })); + }, [hostTopology?.source, identity.windowIndex, session, topologySession?.windows]); + const [windows, setWindows] = useState(sourceWindows); + const [contextWindowIndex, setContextWindowIndex] = useState(null); + const [editingWindowIndex, setEditingWindowIndex] = useState(null); + const [renameValue, setRenameValue] = useState(''); + const [pending, setPending] = useState(false); + const longPressTimerRef = useRef(null); + const longPressTriggeredRef = useRef(false); + const notifications = useNotifications(); + + useEffect(() => { + setWindows(sourceWindows); + }, [sourceWindows]); + + useEffect( + () => () => { + if (longPressTimerRef.current !== null) window.clearTimeout(longPressTimerRef.current); + }, + [] + ); + + const clearLongPress = () => { + if (longPressTimerRef.current !== null) { + window.clearTimeout(longPressTimerRef.current); + longPressTimerRef.current = null; + } + }; + + const dispatchAction = async (action: TmuxWindowAction) => { + if (pending) return; + const previous = windows; + setPending(true); + try { + await runTmuxWindowAction({ + sessionId: session.id, + windowCount: windows.length, + action, + optimistic: () => setWindows(optimisticWindows(windows, action)), + rollback: () => setWindows(previous), + }); + } catch (error) { + notifications.error( + 'tmux command failed', + error instanceof Error ? error.message : 'The window change could not be applied.', + { sessionId: session.id } + ); + } finally { + setPending(false); + } + }; + + const beginRename = (window: TmuxWindowTopologyView) => { + setContextWindowIndex(null); + setEditingWindowIndex(window.windowIndex); + setRenameValue(window.windowName); + }; + + const commitRename = (window: TmuxWindowTopologyView) => { + const name = renameValue.trim(); + setEditingWindowIndex(null); + if (!name || name === window.windowName) return; + void dispatchAction({ type: 'rename', windowIndex: window.windowIndex, name }); + }; + + if (!session.tmux_pane_id) return null; + + return ( +
+
+ {windows.map((window) => { + const editing = editingWindowIndex === window.windowIndex; + const contextOpen = contextWindowIndex === window.windowIndex; + return ( +
+ {editing ? ( + setRenameValue(event.target.value)} + onBlur={() => commitRename(window)} + onKeyDown={(event) => { + if (event.key === 'Enter') { + event.preventDefault(); + event.currentTarget.blur(); + } else if (event.key === 'Escape') { + event.preventDefault(); + setEditingWindowIndex(null); + } + }} + className="h-8 w-28 bg-background px-2 text-xs outline-none ring-inset focus:ring-2 focus:ring-primary" + aria-label={`Rename window ${window.windowIndex}`} + disabled={pending} + /> + ) : ( + + )} + {!editing && ( + + )} +
+ ); + })} + +
+ + {contextWindowIndex !== null && + (() => { + const window = windows.find((candidate) => candidate.windowIndex === contextWindowIndex); + if (!window) return null; + return ( +
+ + {window.windowIndex} · {window.windowName} + + + + +
+ ); + })()} +
+ ); +} diff --git a/apps/dashboard/src/components/tmux/paneActions.test.ts b/apps/dashboard/src/components/tmux/paneActions.test.ts new file mode 100644 index 00000000..fe76c98a --- /dev/null +++ b/apps/dashboard/src/components/tmux/paneActions.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from 'vitest'; +import type { Host } from '@agent-command/schema'; +import { buildSplitPaneCommand } from './paneActions'; + +const baseHost = { + id: '11111111-1111-4111-8111-111111111111', + name: 'builder', + capabilities: { tmux: true }, + created_at: '2026-07-20T12:00:00.000Z', + updated_at: '2026-07-20T12:00:00.000Z', +} as Host; + +describe('tmux pane actions', () => { + it('includes a percent split only when the host reports tmux 3.1 or newer', () => { + const modern = { + ...baseHost, + capabilities: { ...baseHost.capabilities, tmux_version: 'tmux 3.4' }, + } as Host; + const old = { + ...baseHost, + capabilities: { ...baseHost.capabilities, tmux_version: 'tmux 3.0a' }, + } as Host; + + expect(buildSplitPaneCommand(modern, 'horizontal', '/work/repo')).toEqual({ + type: 'split_pane', + payload: { direction: 'horizontal', percent: 50, cwd: '/work/repo' }, + }); + expect(buildSplitPaneCommand(old, 'vertical', '/work/repo')).toEqual({ + type: 'split_pane', + payload: { direction: 'vertical', cwd: '/work/repo' }, + }); + expect(buildSplitPaneCommand({ ...baseHost, agent_version: 'unknown' }, 'vertical')).toEqual({ + type: 'split_pane', + payload: { direction: 'vertical' }, + }); + expect(buildSplitPaneCommand({ ...baseHost, agent_version: '3.1.2' }, 'vertical')).toEqual({ + type: 'split_pane', + payload: { direction: 'vertical', percent: 50 }, + }); + }); +}); diff --git a/apps/dashboard/src/components/tmux/paneActions.ts b/apps/dashboard/src/components/tmux/paneActions.ts new file mode 100644 index 00000000..8591a613 --- /dev/null +++ b/apps/dashboard/src/components/tmux/paneActions.ts @@ -0,0 +1,41 @@ +import type { CommandRequest, Host } from '@agent-command/schema'; + +export type SplitDirection = 'horizontal' | 'vertical'; + +function reportedTmuxVersion(host?: Host | null): string | undefined { + if (!host) return undefined; + const capabilities = host.capabilities as Record; + const extendedHost = host as Host & { tmux_version?: unknown }; + const candidates = [ + capabilities.tmux_version, + capabilities.tmuxVersion, + extendedHost.tmux_version, + host.agent_version, + ]; + return candidates.find((candidate): candidate is string => typeof candidate === 'string'); +} + +export function hostSupportsPercentSplits(host?: Host | null): boolean { + const version = reportedTmuxVersion(host); + if (!version) return false; + const match = version.match(/(\d+)\.(\d+)/); + if (!match) return false; + const major = Number(match[1]); + const minor = Number(match[2]); + return major > 3 || (major === 3 && minor >= 1); +} + +export function buildSplitPaneCommand( + host: Host | null | undefined, + direction: SplitDirection, + cwd?: string +): CommandRequest { + return { + type: 'split_pane', + payload: { + direction, + ...(hostSupportsPercentSplits(host) ? { percent: 50 } : {}), + ...(cwd ? { cwd } : {}), + }, + }; +} diff --git a/apps/dashboard/src/components/tmux/quickSwitch.test.ts b/apps/dashboard/src/components/tmux/quickSwitch.test.ts new file mode 100644 index 00000000..6ab43aa6 --- /dev/null +++ b/apps/dashboard/src/components/tmux/quickSwitch.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest'; +import type { SessionWithSnapshot } from '@agent-command/schema'; +import type { RecentSession } from '@/stores/ui'; +import { getRecentTmuxPanes } from './quickSwitch'; + +describe('mobile tmux quick switch', () => { + it('keeps the selected pane first and follows shared recent-session order', () => { + const live = [ + { id: 'current', tmux_pane_id: '%1', status: 'RUNNING' }, + { id: 'recent', tmux_pane_id: '%2', status: 'WAITING_FOR_INPUT' }, + { id: 'not-recent', tmux_pane_id: '%3', status: 'IDLE' }, + ] as SessionWithSnapshot[]; + const recent = [ + { id: 'recent', visitedAt: '2026-07-20T13:00:00.000Z' }, + { id: 'missing', visitedAt: '2026-07-20T12:00:00.000Z' }, + { id: 'current', visitedAt: '2026-07-20T11:00:00.000Z' }, + ] as RecentSession[]; + + expect(getRecentTmuxPanes(recent, live, 'current').map((session) => session.id)).toEqual([ + 'current', + 'recent', + ]); + }); +}); diff --git a/apps/dashboard/src/components/tmux/quickSwitch.ts b/apps/dashboard/src/components/tmux/quickSwitch.ts new file mode 100644 index 00000000..86353b12 --- /dev/null +++ b/apps/dashboard/src/components/tmux/quickSwitch.ts @@ -0,0 +1,32 @@ +import type { SessionWithSnapshot } from '@agent-command/schema'; +import type { RecentSession } from '@/stores/ui'; + +const MAX_QUICK_SWITCH_PANES = 5; + +export function getRecentTmuxPanes( + recentSessions: RecentSession[], + liveSessions: SessionWithSnapshot[], + selectedSessionId: string +): SessionWithSnapshot[] { + const liveById = new Map( + liveSessions + .filter((session) => Boolean(session.tmux_pane_id)) + .map((session) => [session.id, session]) + ); + const orderedIds = [ + ...(selectedSessionId ? [selectedSessionId] : []), + ...recentSessions.map((session) => session.id), + ]; + const seen = new Set(); + const panes: SessionWithSnapshot[] = []; + + for (const sessionId of orderedIds) { + if (seen.has(sessionId)) continue; + seen.add(sessionId); + const session = liveById.get(sessionId); + if (!session) continue; + panes.push(session); + if (panes.length === MAX_QUICK_SWITCH_PANES) break; + } + return panes; +} diff --git a/apps/dashboard/src/components/tmux/windowActions.test.ts b/apps/dashboard/src/components/tmux/windowActions.test.ts new file mode 100644 index 00000000..6926d8b6 --- /dev/null +++ b/apps/dashboard/src/components/tmux/windowActions.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, it, vi } from 'vitest'; +import { runTmuxWindowAction } from './windowActions'; + +describe('tmux window actions', () => { + it('dispatches window selection through the attached session', async () => { + const dispatch = vi.fn().mockResolvedValue({ cmd_id: 'command-1' }); + + const result = await runTmuxWindowAction({ + sessionId: '22222222-2222-4222-8222-222222222222', + windowCount: 2, + action: { type: 'select', windowIndex: 3 }, + dispatch, + }); + + expect(result).toBe('dispatched'); + expect(dispatch).toHaveBeenCalledWith('22222222-2222-4222-8222-222222222222', { + type: 'select_window', + payload: { window_index: 3 }, + }); + }); + + it.each([ + [ + { type: 'rename' as const, windowIndex: 3, name: 'review' }, + { type: 'rename_window', payload: { window_index: 3, name: 'review' } }, + ], + [ + { type: 'close' as const, windowIndex: 3 }, + { type: 'kill_window', payload: { window_index: 3 } }, + ], + [ + { type: 'new' as const, cwd: '/work/agent-command' }, + { type: 'new_window', payload: { cwd: '/work/agent-command' } }, + ], + ])('dispatches %s with the command schema payload', async (action, command) => { + const dispatch = vi.fn().mockResolvedValue({ cmd_id: 'command-1' }); + + await runTmuxWindowAction({ + sessionId: '22222222-2222-4222-8222-222222222222', + windowCount: 2, + action, + dispatch, + }); + + expect(dispatch).toHaveBeenCalledWith('22222222-2222-4222-8222-222222222222', command); + }); + + it('requires the hard session-ending confirmation before closing the last window', async () => { + const dispatch = vi.fn().mockResolvedValue({ cmd_id: 'command-1' }); + const confirm = vi.fn().mockReturnValue(false); + + const cancelled = await runTmuxWindowAction({ + sessionId: '22222222-2222-4222-8222-222222222222', + windowCount: 1, + action: { type: 'close', windowIndex: 0 }, + dispatch, + confirm, + }); + + expect(cancelled).toBe('cancelled'); + expect(confirm).toHaveBeenCalledWith('This ends the whole tmux session'); + expect(dispatch).not.toHaveBeenCalled(); + + confirm.mockReturnValue(true); + const dispatched = await runTmuxWindowAction({ + sessionId: '22222222-2222-4222-8222-222222222222', + windowCount: 1, + action: { type: 'close', windowIndex: 0 }, + dispatch, + confirm, + }); + + expect(dispatched).toBe('dispatched'); + expect(dispatch).toHaveBeenCalledWith('22222222-2222-4222-8222-222222222222', { + type: 'kill_window', + payload: { window_index: 0 }, + }); + }); + + it('rolls an optimistic window change back when command dispatch fails', async () => { + const error = new Error('Agent not connected'); + const optimistic = vi.fn(); + const rollback = vi.fn(); + + await expect( + runTmuxWindowAction({ + sessionId: '22222222-2222-4222-8222-222222222222', + windowCount: 2, + action: { type: 'rename', windowIndex: 1, name: 'review' }, + dispatch: vi.fn().mockRejectedValue(error), + optimistic, + rollback, + }) + ).rejects.toThrow('Agent not connected'); + + expect(optimistic).toHaveBeenCalledOnce(); + expect(rollback).toHaveBeenCalledWith(error); + }); +}); diff --git a/apps/dashboard/src/components/tmux/windowActions.ts b/apps/dashboard/src/components/tmux/windowActions.ts new file mode 100644 index 00000000..a63812a7 --- /dev/null +++ b/apps/dashboard/src/components/tmux/windowActions.ts @@ -0,0 +1,63 @@ +import type { CommandRequest } from '@agent-command/schema'; +import { sendCommand } from '@/lib/api'; + +export type TmuxWindowAction = + | { type: 'select'; windowIndex: number } + | { type: 'rename'; windowIndex: number; name: string } + | { type: 'close'; windowIndex: number } + | { type: 'new'; cwd?: string }; + +interface RunTmuxWindowActionOptions { + sessionId: string; + windowCount: number; + action: TmuxWindowAction; + dispatch?: typeof sendCommand; + confirm?: (message: string) => boolean; + optimistic?: () => void; + rollback?: (error: unknown) => void; +} + +function commandForAction(action: TmuxWindowAction): CommandRequest { + switch (action.type) { + case 'select': + return { type: 'select_window', payload: { window_index: action.windowIndex } }; + case 'rename': + return { + type: 'rename_window', + payload: { window_index: action.windowIndex, name: action.name }, + }; + case 'close': + return { type: 'kill_window', payload: { window_index: action.windowIndex } }; + case 'new': + return { + type: 'new_window', + payload: action.cwd ? { cwd: action.cwd } : {}, + }; + } +} + +export async function runTmuxWindowAction({ + sessionId, + windowCount, + action, + dispatch = sendCommand, + confirm = (message) => window.confirm(message), + optimistic, + rollback, +}: RunTmuxWindowActionOptions): Promise<'dispatched' | 'cancelled'> { + if ( + action.type === 'close' && + windowCount === 1 && + !confirm('This ends the whole tmux session') + ) { + return 'cancelled'; + } + optimistic?.(); + try { + await dispatch(sessionId, commandForAction(action)); + } catch (error) { + rollback?.(error); + throw error; + } + return 'dispatched'; +} diff --git a/apps/dashboard/src/hooks/useTmuxRosterData.test.ts b/apps/dashboard/src/hooks/useTmuxRosterData.test.ts new file mode 100644 index 00000000..1eebc272 --- /dev/null +++ b/apps/dashboard/src/hooks/useTmuxRosterData.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; +import { buildCanonicalTmuxHref } from './useTmuxRosterData'; + +describe('buildCanonicalTmuxHref', () => { + it('targets the root command center while preserving legacy redirect query state', () => { + const legacyUrl = new URL( + 'https://command.example/tmux?host_id=host-1&session_id=session-1&mode=terminal&attach=1' + ); + + expect(buildCanonicalTmuxHref(legacyUrl.searchParams.toString())).toBe( + '/?host_id=host-1&session_id=session-1&mode=terminal&attach=1' + ); + }); + + it('uses the bare root when no tmux state is active', () => { + expect(buildCanonicalTmuxHref('')).toBe('/'); + }); +}); diff --git a/apps/dashboard/src/hooks/useTmuxRosterData.ts b/apps/dashboard/src/hooks/useTmuxRosterData.ts index 718dcbfb..3117bc42 100644 --- a/apps/dashboard/src/hooks/useTmuxRosterData.ts +++ b/apps/dashboard/src/hooks/useTmuxRosterData.ts @@ -19,9 +19,14 @@ import { } from '@/lib/fleetRoster'; import { isHostOnline } from '@/lib/utils'; import { useWebSocket } from '@/hooks/useWebSocket'; +import { useTmuxTopologyFeed } from '@/hooks/useTmuxTopology'; export const ALL_TMUX_HOSTS_ID = 'all'; +export function buildCanonicalTmuxHref(search: string): string { + return `/${search ? `?${search}` : ''}`; +} + interface TmuxRosterQueryData { sessions: SessionWithSnapshot[]; total: number; @@ -65,9 +70,10 @@ export function useTmuxRosterData() { queryFn: getHosts, }); - const tmuxHosts = useMemo(() => ( - hostsData?.hosts?.filter((host) => host.capabilities.tmux) ?? [] - ), [hostsData]); + const tmuxHosts = useMemo( + () => hostsData?.hosts?.filter((host) => host.capabilities.tmux) ?? [], + [hostsData] + ); const onlineTmuxHosts = useMemo( () => tmuxHosts.filter((host) => isHostOnline(host.last_seen_at ?? null)), [tmuxHosts] @@ -90,22 +96,27 @@ export function useTmuxRosterData() { const allHostsSelected = effectiveHostId === ALL_TMUX_HOSTS_ID && onlineTmuxHosts.length > 0; const selectedHostId = allHostsSelected ? ALL_TMUX_HOSTS_ID - : hostById.has(effectiveHostId) ? effectiveHostId : fallbackHostId; + : hostById.has(effectiveHostId) + ? effectiveHostId + : fallbackHostId; const selectedHost = selectedHostId ? hostById.get(selectedHostId) : undefined; - const updateTmuxParams = useCallback((updates: Record) => { - const params = new URLSearchParams(pendingSearchRef.current); - for (const [key, value] of Object.entries(updates)) { - if (!value) { - params.delete(key); - } else { - params.set(key, value); + const updateTmuxParams = useCallback( + (updates: Record) => { + const params = new URLSearchParams(pendingSearchRef.current); + for (const [key, value] of Object.entries(updates)) { + if (!value) { + params.delete(key); + } else { + params.set(key, value); + } } - } - const next = params.toString(); - pendingSearchRef.current = next; - router.replace(`/tmux${next ? `?${next}` : ''}`); - }, [router]); + const next = params.toString(); + pendingSearchRef.current = next; + router.replace(buildCanonicalTmuxHref(next)); + }, + [router] + ); const { data: sessionsData, @@ -129,14 +140,19 @@ export function useTmuxRosterData() { })) ); const successful = results - .filter((result): result is PromiseFulfilledResult<{ hostId: string; roster: TmuxRosterQueryData }> => result.status === 'fulfilled') + .filter( + ( + result + ): result is PromiseFulfilledResult<{ hostId: string; roster: TmuxRosterQueryData }> => + result.status === 'fulfilled' + ) .map((result) => result.value); if (successful.length === 0) { throw new Error('Could not load the tmux roster from any online machine.'); } - const failedHostIds = results.flatMap((result, index) => ( + const failedHostIds = results.flatMap((result, index) => result.status === 'rejected' ? [onlineTmuxHosts[index]?.id ?? 'unknown'] : [] - )); + ); const sessions = successful.flatMap(({ roster }) => roster.sessions); return { sessions: [...new Map(sessions.map((session) => [session.id, session])).values()], @@ -147,15 +163,19 @@ export function useTmuxRosterData() { enabled: Boolean(selectedHostId), }); - const tmuxSessions = useMemo(() => ( - sessionsData?.sessions ?? [] - ), [sessionsData]); + const tmuxSessions = useMemo(() => sessionsData?.sessions ?? [], [sessionsData]); + useTmuxTopologyFeed( + allHostsSelected + ? onlineTmuxHosts.map((host) => host.id) + : selectedHostId + ? [selectedHostId] + : [], + tmuxSessions + ); const matchesActiveFilter = useCallback( - (session: SessionWithSnapshot) => ( - matchesTmuxRosterFilter(session, activeFilter) - && matchesTmuxFilter(session, query) - ), + (session: SessionWithSnapshot) => + matchesTmuxRosterFilter(session, activeFilter) && matchesTmuxFilter(session, query), [activeFilter, query] ); @@ -170,19 +190,25 @@ export function useTmuxRosterData() { })), }); const sessionEdges = useMemo( - () => [...new Map( - graphQueries - .flatMap((result) => result.data?.edges ?? []) - .map((edge) => [`${edge.parent_session_id}:${edge.child_session_id}:${edge.edge_type}`, edge]) - ).values()], + () => [ + ...new Map( + graphQueries + .flatMap((result) => result.data?.edges ?? []) + .map((edge) => [ + `${edge.parent_session_id}:${edge.child_session_id}:${edge.edge_type}`, + edge, + ]) + ).values(), + ], [graphQueries] ); const rosterGroups = useMemo( - () => buildFleetRosterGroups(tmuxSessions, sessionEdges, { - allHosts: allHostsSelected, - waitingFirst: allHostsSelected, - }), + () => + buildFleetRosterGroups(tmuxSessions, sessionEdges, { + allHosts: allHostsSelected, + waitingFirst: allHostsSelected, + }), [allHostsSelected, sessionEdges, tmuxSessions] ); const groups = useMemo( @@ -190,9 +216,9 @@ export function useTmuxRosterData() { [matchesActiveFilter, rosterGroups] ); const filteredSessions = useMemo( - () => [...new Map( - groups.flatMap(groupSessions).map((session) => [session.id, session]) - ).values()], + () => [ + ...new Map(groups.flatMap(groupSessions).map((session) => [session.id, session])).values(), + ], [groups] ); @@ -217,7 +243,9 @@ export function useTmuxRosterData() { }, [groups]); const selectedSessionId = availableSessionIds.has(sessionIdParam) ? sessionIdParam : ''; - const selectedClusterKey = selectedSessionId ? sessionToClusterKey.get(selectedSessionId) ?? null : null; + const selectedClusterKey = selectedSessionId + ? (sessionToClusterKey.get(selectedSessionId) ?? null) + : null; useEffect(() => { if (!selectedHostId) return; @@ -227,9 +255,9 @@ export function useTmuxRosterData() { }, [availableSessionIds, selectedHostId, sessionIdParam, updateTmuxParams]); useEffect(() => { - setExpandedClusterKey((current) => ( + setExpandedClusterKey((current) => current && groups.some((group) => group.key === current) ? current : null - )); + ); }, [groups]); useEffect(() => { @@ -307,21 +335,27 @@ export function useTmuxRosterData() { } }, [refetchHosts, refetchSessions, selectedHostId]); - const selectHost = useCallback((hostId: string) => { - setRequestedHostId(hostId); - updateTmuxParams({ - host_id: hostId, - session_id: null, - }); - }, [updateTmuxParams]); - - const selectSession = useCallback((sessionId: string) => { - const clusterKey = sessionToClusterKey.get(sessionId); - if (clusterKey) { - setExpandedClusterKey(clusterKey); - } - updateTmuxParams({ session_id: sessionId }); - }, [sessionToClusterKey, updateTmuxParams]); + const selectHost = useCallback( + (hostId: string) => { + setRequestedHostId(hostId); + updateTmuxParams({ + host_id: hostId, + session_id: null, + }); + }, + [updateTmuxParams] + ); + + const selectSession = useCallback( + (sessionId: string) => { + const clusterKey = sessionToClusterKey.get(sessionId); + if (clusterKey) { + setExpandedClusterKey(clusterKey); + } + updateTmuxParams({ session_id: sessionId }); + }, + [sessionToClusterKey, updateTmuxParams] + ); return { query, diff --git a/apps/dashboard/src/hooks/useTmuxTopology.ts b/apps/dashboard/src/hooks/useTmuxTopology.ts new file mode 100644 index 00000000..bdda3c28 --- /dev/null +++ b/apps/dashboard/src/hooks/useTmuxTopology.ts @@ -0,0 +1,53 @@ +'use client'; + +import { useEffect, useMemo } from 'react'; +import { useQuery } from '@tanstack/react-query'; +import type { ServerToUIMessage, SessionWithSnapshot } from '@agent-command/schema'; +import { getTmuxRoster } from '@/lib/api'; +import { useTmuxTopologyStore } from '@/stores/tmuxTopology'; +import { useWebSocket } from './useWebSocket'; + +export function useTmuxTopologyFeed(hostIds: string[], rosterSessions: SessionWithSnapshot[]) { + const setRoster = useTmuxTopologyStore((state) => state.setRoster); + const receiveTopology = useTmuxTopologyStore((state) => state.receiveTopology); + const hostIdsKey = [...hostIds].sort().join(','); + const stableHostIds = useMemo(() => (hostIdsKey ? hostIdsKey.split(',') : []), [hostIdsKey]); + + useEffect(() => { + const grouped = new Map(); + for (const hostId of stableHostIds) grouped.set(hostId, []); + for (const session of rosterSessions) { + const sessions = grouped.get(session.host_id) ?? []; + sessions.push(session); + grouped.set(session.host_id, sessions); + } + for (const [hostId, sessions] of grouped) setRoster(hostId, sessions); + }, [rosterSessions, setRoster, stableHostIds]); + + useWebSocket( + [{ type: 'tmux.topology' }], + (message: ServerToUIMessage) => { + if (message.type !== 'tmux.topology') return; + receiveTopology(message.payload.host_id, message.payload, message.ts); + }, + stableHostIds.length > 0, + 'tmux-topology' + ); +} + +export function useTmuxHostTopology(hostId: string, seedSessions?: SessionWithSnapshot[]) { + const storedRoster = useTmuxTopologyStore((state) => state.rosterByHost[hostId]); + const { data } = useQuery({ + queryKey: ['sessions', 'tmux', hostId, 'topology-fallback'], + queryFn: () => getTmuxRoster({ host_id: hostId }), + enabled: Boolean(hostId && !seedSessions), + staleTime: 30_000, + }); + const fallbackSessions = useMemo( + () => seedSessions ?? data?.sessions ?? storedRoster ?? [], + [data?.sessions, seedSessions, storedRoster] + ); + + useTmuxTopologyFeed(hostId ? [hostId] : [], fallbackSessions); + return useTmuxTopologyStore((state) => state.hosts[hostId]); +} diff --git a/apps/dashboard/src/lib/api.ts b/apps/dashboard/src/lib/api.ts index bd12bb12..6806d315 100644 --- a/apps/dashboard/src/lib/api.ts +++ b/apps/dashboard/src/lib/api.ts @@ -61,6 +61,8 @@ import type { ToolStat, AgentTask, AutomationAgentMessageRequest, + ScrollbackRequest, + ScrollbackResponse, } from '@agent-command/schema'; export type { CaptureMode, @@ -382,6 +384,16 @@ export async function sendCommand( }); } +export async function getSessionScrollback( + sessionId: string, + request: ScrollbackRequest +): Promise { + return fetchAPI(`/v1/sessions/${sessionId}/scrollback`, { + method: 'POST', + body: JSON.stringify(request), + }); +} + export async function deleteSession(id: string): Promise<{ success: boolean }> { return fetchAPI(`/v1/sessions/${id}`, { method: 'DELETE' }); } diff --git a/apps/dashboard/src/stores/settings.ts b/apps/dashboard/src/stores/settings.ts index 9716d550..24c1e8da 100644 --- a/apps/dashboard/src/stores/settings.ts +++ b/apps/dashboard/src/stores/settings.ts @@ -379,6 +379,10 @@ interface SettingsStore { // Virtual keyboard virtualKeyboardKeys: VirtualKeyboardKey[]; setVirtualKeyboardKeys: (keys: VirtualKeyboardKey[]) => void; + tmuxKeyBarExpanded: boolean; + setTmuxKeyBarExpanded: (expanded: boolean) => void; + tmuxSecondaryByPrimary: Record; + setTmuxSecondary: (primarySessionId: string, secondarySessionId: string | null) => void; // Repo Picker settings devFolders: DevFolder[]; @@ -626,6 +630,16 @@ export const useSettingsStore = create()( // Virtual keyboard defaults virtualKeyboardKeys: [...DEFAULT_VIRTUAL_KEY_ORDER], setVirtualKeyboardKeys: (keys) => set({ virtualKeyboardKeys: keys }), + tmuxKeyBarExpanded: false, + setTmuxKeyBarExpanded: (expanded) => set({ tmuxKeyBarExpanded: expanded }), + tmuxSecondaryByPrimary: {}, + setTmuxSecondary: (primarySessionId, secondarySessionId) => + set((state) => { + const next = { ...state.tmuxSecondaryByPrimary }; + if (secondarySessionId) next[primarySessionId] = secondarySessionId; + else delete next[primarySessionId]; + return { tmuxSecondaryByPrimary: next }; + }), // Repo Picker defaults devFolders: [], diff --git a/apps/dashboard/src/stores/tmuxTopology.test.ts b/apps/dashboard/src/stores/tmuxTopology.test.ts new file mode 100644 index 00000000..d4394c3d --- /dev/null +++ b/apps/dashboard/src/stores/tmuxTopology.test.ts @@ -0,0 +1,157 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import type { SessionWithSnapshot, TmuxTopologyPayload } from '@agent-command/schema'; +import { useTmuxTopologyStore } from './tmuxTopology'; + +const hostId = '11111111-1111-4111-8111-111111111111'; + +function rosterSession(overrides: Partial = {}): SessionWithSnapshot { + return { + id: '22222222-2222-4222-8222-222222222222', + host_id: hostId, + kind: 'tmux_pane', + provider: 'codex', + status: 'RUNNING', + title: 'Builder', + cwd: '/work/agent-command', + tmux_pane_id: '%12', + tmux_target: 'agents:1.0', + tmux_session_name: 'agents', + tmux_window_index: 1, + tmux_pane_index: 0, + metadata: { + tmux: { + pane_id: '%12', + session_name: 'agents', + window_name: 'fallback-name', + window_index: 1, + pane_index: 0, + }, + }, + created_at: '2026-07-20T12:00:00.000Z', + updated_at: '2026-07-20T12:00:00.000Z', + fork_depth: 0, + ...overrides, + }; +} + +describe('tmux topology store', () => { + beforeEach(() => useTmuxTopologyStore.getState().reset()); + + it('uses a host topology snapshot and joins its panes to roster sessions', () => { + const payload: TmuxTopologyPayload = { + reason: 'hook:window-renamed', + tmux_sessions: [ + { + session_name: 'agents', + attached: true, + windows: [ + { + window_index: 1, + window_name: 'live-name', + active: true, + zoomed: false, + layout: 'tiled', + bell: true, + activity: true, + panes: [ + { + pane_id: '%12', + pane_index: 0, + active: true, + width: 190, + height: 45, + title: 'codex', + current_command: 'codex', + current_path: '/work/agent-command', + }, + ], + }, + ], + }, + ], + }; + + useTmuxTopologyStore.getState().setRoster(hostId, [rosterSession()]); + useTmuxTopologyStore.getState().receiveTopology(hostId, payload, '2026-07-20T14:00:00.000Z'); + + expect(useTmuxTopologyStore.getState().hosts[hostId]).toMatchObject({ + hostId, + source: 'topology', + receivedAt: '2026-07-20T14:00:00.000Z', + sessions: [ + { + sessionName: 'agents', + attached: true, + windows: [ + { + windowIndex: 1, + windowName: 'live-name', + active: true, + bell: true, + activity: true, + panes: [{ paneId: '%12', sessionId: rosterSession().id, active: true }], + }, + ], + }, + ], + }); + }); + + it('derives sorted window and pane structure from roster data until a host emits topology', () => { + const secondPane = rosterSession({ + id: '33333333-3333-4333-8333-333333333333', + tmux_pane_id: '%13', + tmux_target: 'agents:1.1', + tmux_pane_index: 1, + title: 'Reviewer', + metadata: { + tmux: { + pane_id: '%13', + session_name: 'agents', + window_name: 'fallback-name', + window_index: 1, + pane_index: 1, + }, + }, + }); + const earlierWindow = rosterSession({ + id: '44444444-4444-4444-8444-444444444444', + tmux_pane_id: '%14', + tmux_target: 'agents:0.0', + tmux_window_index: 0, + title: 'Shell', + metadata: { + tmux: { + pane_id: '%14', + session_name: 'agents', + window_name: 'shell', + window_index: 0, + pane_index: 0, + }, + }, + }); + + useTmuxTopologyStore.getState().setRoster(hostId, [secondPane, rosterSession(), earlierWindow]); + + const host = useTmuxTopologyStore.getState().hosts[hostId]; + expect(host?.source).toBe('roster'); + expect(host?.sessions[0]?.windows.map((window) => window.windowIndex)).toEqual([0, 1]); + expect(host?.sessions[0]?.windows[1]?.panes.map((pane) => pane.paneId)).toEqual(['%12', '%13']); + expect(host?.sessions[0]?.windows[1]?.panes[1]).toMatchObject({ + sessionId: secondPane.id, + sessionTitle: 'Reviewer', + }); + }); + + it('does not publish a new snapshot when a feed repeats the same roster session objects', () => { + const session = rosterSession(); + useTmuxTopologyStore.getState().setRoster(hostId, [session]); + const firstHosts = useTmuxTopologyStore.getState().hosts; + const firstRoster = useTmuxTopologyStore.getState().rosterByHost; + + useTmuxTopologyStore.getState().setRoster(hostId, [session]); + + expect(useTmuxTopologyStore.getState().hosts).toBe(firstHosts); + expect(useTmuxTopologyStore.getState().rosterByHost).toBe(firstRoster); + }); +}); diff --git a/apps/dashboard/src/stores/tmuxTopology.ts b/apps/dashboard/src/stores/tmuxTopology.ts new file mode 100644 index 00000000..283e9991 --- /dev/null +++ b/apps/dashboard/src/stores/tmuxTopology.ts @@ -0,0 +1,231 @@ +import { create } from 'zustand'; +import type { + SessionWithSnapshot, + TmuxTopologyPayload, + TmuxTopologySession, +} from '@agent-command/schema'; + +export interface TmuxPaneTopologyView { + paneId: string; + paneIndex: number; + active: boolean; + width?: number; + height?: number; + title: string; + currentCommand: string; + currentPath: string; + sessionId?: string; + sessionStatus?: SessionWithSnapshot['status']; + sessionTitle?: string | null; +} + +export interface TmuxWindowTopologyView { + windowIndex: number; + windowName: string; + active: boolean; + zoomed: boolean; + layout: string; + bell: boolean; + activity: boolean; + panes: TmuxPaneTopologyView[]; +} + +export interface TmuxSessionTopologyView { + sessionName: string; + attached: boolean; + windows: TmuxWindowTopologyView[]; +} + +export interface TmuxHostTopologyView { + hostId: string; + source: 'topology' | 'roster'; + receivedAt?: string; + sessions: TmuxSessionTopologyView[]; +} + +interface LiveSnapshot { + payload: TmuxTopologyPayload; + receivedAt: string; +} + +interface TmuxTopologyStore { + hosts: Record; + rosterByHost: Record; + liveByHost: Record; + setRoster: (hostId: string, sessions: SessionWithSnapshot[]) => void; + receiveTopology: (hostId: string, payload: TmuxTopologyPayload, receivedAt?: string) => void; + reset: () => void; +} + +function rosterIdentity(session: SessionWithSnapshot) { + const tmux = session.metadata?.tmux; + const indexes = session.tmux_target?.match(/:(\d+)(?:\.(\d+))?$/); + return { + paneId: tmux?.pane_id || session.tmux_pane_id || session.id, + paneIndex: session.tmux_pane_index ?? tmux?.pane_index ?? Number(indexes?.[2] ?? 0), + sessionName: + session.tmux_session_name || + tmux?.session_name || + session.tmux_target?.split(':')[0] || + 'tmux', + windowIndex: session.tmux_window_index ?? tmux?.window_index ?? Number(indexes?.[1] ?? 0), + windowName: + tmux?.window_name || + `window ${session.tmux_window_index ?? tmux?.window_index ?? Number(indexes?.[1] ?? 0)}`, + }; +} + +export function buildRosterTopology( + hostId: string, + sessions: SessionWithSnapshot[] +): TmuxHostTopologyView { + const sessionGroups = new Map>(); + + for (const session of sessions) { + if (session.host_id !== hostId) continue; + const identity = rosterIdentity(session); + const windows = + sessionGroups.get(identity.sessionName) ?? new Map(); + const window = windows.get(identity.windowIndex) ?? { + windowIndex: identity.windowIndex, + windowName: identity.windowName, + active: false, + zoomed: false, + layout: '', + bell: false, + activity: false, + panes: [], + }; + window.panes.push({ + paneId: identity.paneId, + paneIndex: identity.paneIndex, + active: false, + title: session.title || '', + currentCommand: session.metadata?.tmux?.current_command || '', + currentPath: session.cwd || '', + sessionId: session.id, + sessionStatus: session.status, + sessionTitle: session.title, + }); + windows.set(identity.windowIndex, window); + sessionGroups.set(identity.sessionName, windows); + } + + return { + hostId, + source: 'roster', + sessions: [...sessionGroups.entries()] + .map(([sessionName, windows]) => ({ + sessionName, + attached: false, + windows: [...windows.values()] + .map((window) => ({ + ...window, + panes: [...window.panes].sort((left, right) => left.paneIndex - right.paneIndex), + })) + .sort((left, right) => left.windowIndex - right.windowIndex), + })) + .sort((left, right) => left.sessionName.localeCompare(right.sessionName)), + }; +} + +function joinLiveSession( + topologySession: TmuxTopologySession, + rosterByPaneId: Map +): TmuxSessionTopologyView { + return { + sessionName: topologySession.session_name, + attached: topologySession.attached, + windows: topologySession.windows + .map((window) => ({ + windowIndex: window.window_index, + windowName: window.window_name, + active: window.active, + zoomed: window.zoomed, + layout: window.layout, + bell: window.bell, + activity: window.activity, + panes: window.panes + .map((pane) => { + const rosterSession = rosterByPaneId.get(pane.pane_id); + return { + paneId: pane.pane_id, + paneIndex: pane.pane_index, + active: pane.active, + width: pane.width, + height: pane.height, + title: pane.title, + currentCommand: pane.current_command, + currentPath: pane.current_path, + sessionId: rosterSession?.id, + sessionStatus: rosterSession?.status, + sessionTitle: rosterSession?.title, + }; + }) + .sort((left, right) => left.paneIndex - right.paneIndex), + })) + .sort((left, right) => left.windowIndex - right.windowIndex), + }; +} + +export function buildLiveTopology( + hostId: string, + payload: TmuxTopologyPayload, + roster: SessionWithSnapshot[], + receivedAt: string +): TmuxHostTopologyView { + const rosterByPaneId = new Map( + roster.map((session) => [rosterIdentity(session).paneId, session]) + ); + return { + hostId, + source: 'topology', + receivedAt, + sessions: payload.tmux_sessions + .map((session) => joinLiveSession(session, rosterByPaneId)) + .sort((left, right) => left.sessionName.localeCompare(right.sessionName)), + }; +} + +const initialState = { + hosts: {} as Record, + rosterByHost: {} as Record, + liveByHost: {} as Record, +}; + +export const useTmuxTopologyStore = create((set) => ({ + ...initialState, + setRoster: (hostId, sessions) => + set((state) => { + const currentRoster = state.rosterByHost[hostId]; + if ( + currentRoster && + currentRoster.length === sessions.length && + currentRoster.every((session, index) => session === sessions[index]) + ) { + return state; + } + const live = state.liveByHost[hostId]; + return { + rosterByHost: { ...state.rosterByHost, [hostId]: sessions }, + hosts: { + ...state.hosts, + [hostId]: live + ? buildLiveTopology(hostId, live.payload, sessions, live.receivedAt) + : buildRosterTopology(hostId, sessions), + }, + }; + }), + receiveTopology: (hostId, payload, receivedAt = new Date().toISOString()) => + set((state) => ({ + liveByHost: { + ...state.liveByHost, + [hostId]: { payload, receivedAt }, + }, + hosts: { + ...state.hosts, + [hostId]: buildLiveTopology(hostId, payload, state.rosterByHost[hostId] ?? [], receivedAt), + }, + })), + reset: () => set(initialState), +})); diff --git a/tasks/frontend-ux-handoffs/fw3-tmux-ui.md b/tasks/frontend-ux-handoffs/fw3-tmux-ui.md new file mode 100644 index 00000000..4fce0a88 --- /dev/null +++ b/tasks/frontend-ux-handoffs/fw3-tmux-ui.md @@ -0,0 +1,70 @@ +--- +lane: FW3-TMUX-UI +frozen_sha: 6526629f258aca0d6bc16e0b02f4a21d57c0ede6 +attempt: 1 +state: frozen +gates: + lint: pass + typecheck: pass + test_ci: pass + smoke: pass + build: pass + go: n/a +proof: + - "pnpm install → completed before repository inspection or changes; lockfile unchanged and no dependencies added" + - "CHOKIDAR_USEPOLLING=1 WATCHPACK_POLLING=true pnpm lint && pnpm typecheck && pnpm test:ci && pnpm test:smoke:dashboard && pnpm build → complete mandatory gate passed in order on the accepted FW3-SHELL integration" + - "pnpm lint → 5/5 Turbo tasks passed" + - "pnpm typecheck → 5/5 Turbo tasks passed; Next route types generated successfully" + - "pnpm test:ci → 389 tests passed: dashboard 99, control-plane 198, schema 48, CLI 44" + - "pnpm test:smoke:dashboard → 14/14 Chromium scenarios passed, including canonical root routing, desktop tmux controls, mobile selection, the window strip, and the scrollback pager" + - "pnpm build → 4/4 Turbo build tasks passed; Next.js 16.2.10 production build completed" + - "focused tmux Vitest run → 14/14 topology, window-action, pane-version, quick-switch, scrollback-paging, and canonical-route tests passed" + - "focused integrated Playwright rerun after minimizing the smoke diff → 3/3 desktop/mobile tmux scenarios passed" + - "PLAYWRIGHT_CAPTURE_UI=1 focused Playwright run → desktop terminal and 390x844 mobile history screenshots captured and visually inspected" + - "frontend-product-design audit_frontend.sh → lint, typecheck, and tests passed; manual responsive/state audit scored 95/100 with no hard fails" + - "git diff --name-only 7dfcf787523e524ed48ed42b5b27d3fc922e92f5..6526629f258aca0d6bc16e0b02f4a21d57c0ede6 -- forbidden ownership paths → empty" +assumptions: + - "A host supports percentage splits only when tmux_version/tmuxVersion or a parseable agent version proves tmux >= 3.1; unknown versions conservatively receive a plain split." + - "Receipt of tmux.topology feature-detects live topology independently per host; hosts that emit nothing remain fully functional through roster-derived windows and panes." + - "The existing UI recent-session store is the shared source for the launch rail and mobile pane switcher." +uncertainties: + - "The command endpoint confirms dispatch acceptance but exposes no UI command-result topic. Optimistic state rolls back on immediate HTTP failure and later authoritative topology reconciles remote execution outcomes." + - "Real iOS hardware was unavailable; touch targets, horizontal strips, the action sheet, and the history overlay were verified in Chromium at 390x844." + - "Backend launch/open responses still return legacy /tmux hrefs. The sibling redirect preserves their query state, while roster navigation now targets / directly and avoids that remount." +blockers: [] +--- + +# FW3-TMUX-UI handoff + +## What changed + +- Topology: a per-host Zustand store consumes `tmux.topology`, joins panes to tracked roster sessions, and derives equivalent sessions/windows/panes from roster metadata until each host actually emits live topology. Repeated identical rosters are reference-stable to avoid subscription render loops. +- Window management: the workbench terminal has an accessible tab strip for active state, activity/bell indicators, select, inline rename, close, and new-window actions. Mutations are optimistic with HTTP-error rollback/toasts, and closing the last window requires the exact hard confirmation that the whole tmux session will end. +- Pane management: desktop and mobile controls dispatch horizontal/vertical splits, zoom, directional selection, and confirmed pane kill. Percentage split payloads are capability-gated. The desktop tmux key bar is collapsible, defaults closed, and persists its preference. +- Terminal composition: desktop can mount one independent secondary foreground terminal beside the persistent primary terminal, remembers a same-host secondary per primary session, and closes without expanding the one-background-terminal budget. Mobile remains single-terminal and adds a horizontally scrollable recent-pane strip sourced from the shared recent-session state. +- History: `View history` opens a responsive, searchable, selectable overlay that requests 500-line ranges, loads older ranges from the top, virtualizes rendered rows, and supports copying all content or matches without mutating the xterm buffer. +- Tests: unit coverage locks topology live/fallback behavior, reference stability, optimistic action payloads/rollback/last-window confirmation, version-gated splits, recent ordering, range paging, and canonical route construction. Playwright covers desktop strip/two-up composition plus mobile strip/history and canonical-root pane selection. + +## Decisions within lane latitude + +- Live topology is feature-detected by event receipt, not configuration or optimistic assumptions, because most deployed hosts may still have topology events disabled. +- Unknown or old tmux versions omit the split percentage rather than risking an unsupported command flag. +- The primary terminal retains `PersistentTerminalHost`; only the visible desktop secondary uses an additional direct `TerminalView`. The secondary is never mounted on mobile or while hidden. +- Scrollback stays in a separate pager by design; older content is never prepended into xterm. +- Following the AI Lead addendum, `useTmuxRosterData` now builds in-app navigation from `/` while retaining every query parameter. Incoming `/tmux?...` compatibility remains owned by and verified with the sibling query-preserving redirect. + +## Frontend quality audit + +The integrated surface scored 95/100 with no hard failures: product fit 15/15, information architecture 14/15, visual design 13/15, dashboard/data clarity 15/15, interaction states 9/10, accessibility 14/15, responsive behavior 10/10, and performance polish 5/5. Desktop and mobile screenshots were inspected after rebasing onto the accepted root Command Center shell; compact desktop controls no longer clip at 1280px, and the mobile history sheet has no horizontal overflow. + +## Phase commits + +- `57f46f6` — `feat(tmux-ui): add live topology store with roster fallback` +- `0932c1c` — `feat(tmux-ui): add optimistic tmux window strip` +- `07e19e5` — `feat(tmux-ui): add pane controls and desktop key bar` +- `ef3746b` — `feat(tmux-ui): add remembered desktop two-up terminals` +- `7a8ecbf` — `feat(tmux-ui): add mobile recent pane switcher` +- `4aca3da` — `feat(tmux-ui): add virtualized scrollback pager` +- `6526629` — `feat(tmux-ui): add tmux interaction coverage` + +FW3-TMUX-UI FROZEN 6526629f258aca0d6bc16e0b02f4a21d57c0ede6 diff --git a/tasks/lessons.md b/tasks/lessons.md index 48cde574..d4743ca8 100644 --- a/tasks/lessons.md +++ b/tasks/lessons.md @@ -35,3 +35,7 @@ - Date: 2026-07-20 Correction: Independent review found that the fleet aggregate over-fetched all sessions, exposed snapshot and budget data below operator role, and lacked regression locks for known-invalid agent envelopes and trusted topology host identity. Rule: Scope aggregate queries to their actual entity graph, page or concurrency-bound every fan-out, require operator role for snapshot/cost aggregates, test both tolerant and terminating protocol paths, and spread trusted server identity fields after untrusted agent payloads. + +- Date: 2026-07-20 + Correction: The Command Center moved from `/tmux` to `/`, but tmux roster navigation still targeted the legacy redirect. + Rule: Treat `/` as the canonical Command Center route for new tmux navigation while preserving query parameters so incoming `/tmux` redirects remain compatible without adding an avoidable remount to in-app selections. diff --git a/tests/smoke/dashboard.spec.ts b/tests/smoke/dashboard.spec.ts index ce2c7167..6db699a8 100644 --- a/tests/smoke/dashboard.spec.ts +++ b/tests/smoke/dashboard.spec.ts @@ -520,6 +520,21 @@ async function mockControlPlane(page: Page): Promise { await fulfillJson(route, { cmd_id: '01JCOMMANDSMOKE000000000000' }); return; } + if ( + route.request().method() === 'POST' + && /^\/v1\/sessions\/[^/]+\/scrollback$/.test(url.pathname) + ) { + await fulfillJson(route, { + cmd_id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + ok: true, + result: { + content: 'older terminal line\npnpm test:ci passed\nwaiting for next command\n', + line_count: 3, + capture_mode: 'range', + }, + }); + return; + } if ( route.request().method() === 'POST' && /^\/v1\/approvals\/[^/]+\/decide$/.test(url.pathname) @@ -719,25 +734,30 @@ test('uses the same attention surface for the mobile bell, tab, and desktop shee await expect(desktopBell).toBeFocused(); }); -test('renders tmux roster with windows and panes, supports selection and filtering', async ({ page }) => { +test('renders tmux roster with windows and panes, supports selection and filtering', async ({ page }, testInfo) => { await signIn(page); await page.goto('/tmux'); await expect(page.getByRole('heading', { name: 'tmux', exact: true })).toBeVisible(); await expect(page.getByText('2 sessions · 3 panes')).toBeVisible(); - await expect(page.getByText('agents')).toBeVisible(); + await expect(page.getByText('agents', { exact: true })).toBeVisible(); await expect(page.getByText('ops')).toBeVisible(); await expect(page.getByRole('button', { name: 'Waiting', exact: true })).toBeVisible(); - await page.getByText('agents').click(); + await page.getByText('agents', { exact: true }).click(); await expect(page.getByText('0 · agent-command')).toBeVisible(); await expect(page.getByText('Codex implementation')).toBeVisible(); - await expect(page.getByText('Mobile UX review')).toBeVisible(); + await expect(page.getByText('Mobile UX review', { exact: true })).toBeVisible(); - await page.getByText('Mobile UX review').click(); + await page.getByText('Mobile UX review', { exact: true }).click(); await expect(page).toHaveURL(/session_id=33333333-3333-4333-8333-333333333333/); await expect(page.getByRole('heading', { name: 'Mobile UX review' })).toBeVisible(); + await expect(page.getByTestId('tmux-window-strip')).toBeVisible(); + await expect(page.getByLabel('Secondary terminal')).toBeVisible(); + if (process.env.PLAYWRIGHT_CAPTURE_UI === '1') { + await page.screenshot({ path: testInfo.outputPath('tmux-terminal-desktop.png'), fullPage: true }); + } await page.getByRole('button', { name: 'Waiting', exact: true }).click(); await expect(page).toHaveURL(/filter=waiting/); @@ -763,15 +783,18 @@ test('keeps the tmux roster usable on mobile viewport', async ({ page }) => { await expect(page.getByRole('button', { name: 'Untracked', exact: true })).toBeVisible(); await expect(page.getByPlaceholder('Filter by tmux session, cwd, branch, repo, provider...')).toBeVisible(); await expect(page.getByText('2 sessions · 3 panes')).toBeVisible(); - await expect(page.getByText('agents')).toBeVisible(); + await expect(page.getByText('agents', { exact: true })).toBeVisible(); - await page.getByText('agents').click(); + await page.getByText('agents', { exact: true }).click(); await expect(page.getByText('Codex implementation')).toBeVisible(); - await page.getByText('Mobile UX review').click(); + await page.getByText('Mobile UX review', { exact: true }).click(); await expect(page).toHaveURL(/session_id=33333333-3333-4333-8333-333333333333/); - await expect(page.getByRole('button', { name: 'Terminal', exact: true })).toBeEnabled(); - await page.getByRole('button', { name: 'Terminal', exact: true }).click(); + await expect.poll(() => new URL(page.url()).pathname).toBe('/'); + const mobileSegments = page.getByRole('button', { name: 'Roster', exact: true }).locator('..'); + const terminalSegment = mobileSegments.getByRole('button', { name: 'Terminal', exact: true }); + await expect(terminalSegment).toBeEnabled(); + await terminalSegment.click(); await expect(page.getByText('agents:0.1').first()).toBeVisible(); await expect(page.getByRole('button', { name: 'Actions', exact: true })).toBeEnabled(); @@ -786,10 +809,47 @@ test('keeps the tmux roster usable on mobile viewport', async ({ page }) => { await expect(dialog.getByRole('button', { name: 'Copy last 50' })).toBeVisible(); await expect(dialog.getByRole('button', { name: 'Copy all' })).toBeVisible(); await expect(dialog.getByRole('button', { name: 'Paste' })).toBeVisible(); - await expect(dialog.getByRole('button', { name: 'Terminate pane session' })).toBeVisible(); + await expect(dialog.getByRole('button', { name: 'Kill pane', exact: true })).toBeVisible(); await expect(dialog.getByRole('button', { name: 'Close actions' })).toBeVisible(); }); +test('renders the tmux window strip and opens range-paged history on mobile', async ({ page }, testInfo) => { + await page.setViewportSize({ width: 390, height: 844 }); + await signIn(page); + + await page.goto('/tmux'); + await page.getByText('agents', { exact: true }).click(); + await page.getByText('Mobile UX review', { exact: true }).click(); + + const windowStrip = page.getByTestId('tmux-window-strip').first(); + await expect(windowStrip).toBeVisible(); + await expect(windowStrip.getByRole('tab', { name: 'Window 0: agent-command' })).toBeVisible(); + + await page.getByRole('button', { name: 'Actions', exact: true }).click(); + const actions = page.getByRole('dialog').filter({ hasText: 'Pane actions' }); + const historyRequest = page.waitForRequest((request) => ( + request.method() === 'POST' + && request.url().includes(`/v1/sessions/${tmuxSessions[1].id}/scrollback`) + )); + await actions.getByRole('button', { name: 'View history' }).click(); + + expect((await historyRequest).postDataJSON()).toEqual({ + mode: 'range', + start_line: -500, + end_line: -1, + strip_ansi: true, + }); + const pager = page.getByRole('dialog', { name: 'Terminal history' }); + await expect(pager).toBeVisible(); + await expect(pager.getByText('pnpm test:ci passed')).toBeVisible(); + await pager.getByPlaceholder('Filter captured history…').fill('passed'); + await expect(pager.getByText('1 matches')).toBeVisible(); + + if (process.env.PLAYWRIGHT_CAPTURE_UI === '1') { + await page.screenshot({ path: testInfo.outputPath('tmux-history-mobile.png') }); + } +}); + test('opens mobile launch sheet and launches a coding agent from a recent project', async ({ page }) => { await page.setViewportSize({ width: 390, height: 844 }); await signIn(page); From af8352eb5dbf611717204fa8bcd6a2b0b8dfc0c3 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 13:57:00 -0400 Subject: [PATCH 06/13] fix(shell): internal session links target canonical root; drop dead SettingsButton (wave-3 review W3/N5) Co-Authored-By: Claude Fable 5 --- .../automation/AutomationAgentCard.tsx | 2 +- .../src/components/layout/RecentSessions.tsx | 2 +- .../orchestrator/OrchestratorFleetCard.tsx | 4 +-- .../orchestrator/OrchestratorItem.tsx | 2 +- .../components/settings/SettingsButton.tsx | 26 ------------------- .../src/components/settings/index.ts | 1 - 6 files changed, 5 insertions(+), 32 deletions(-) delete mode 100644 apps/dashboard/src/components/settings/SettingsButton.tsx diff --git a/apps/dashboard/src/components/automation/AutomationAgentCard.tsx b/apps/dashboard/src/components/automation/AutomationAgentCard.tsx index 68144730..1c5db0dd 100644 --- a/apps/dashboard/src/components/automation/AutomationAgentCard.tsx +++ b/apps/dashboard/src/components/automation/AutomationAgentCard.tsx @@ -134,7 +134,7 @@ export function AutomationAgentCard({ {runtimeSessionId && ( diff --git a/apps/dashboard/src/components/layout/RecentSessions.tsx b/apps/dashboard/src/components/layout/RecentSessions.tsx index 843b2f8e..fa1b697d 100644 --- a/apps/dashboard/src/components/layout/RecentSessions.tsx +++ b/apps/dashboard/src/components/layout/RecentSessions.tsx @@ -12,7 +12,7 @@ function getRecentSessionHref(session: RecentSession) { const params = new URLSearchParams(); if (session.hostId) params.set('host_id', session.hostId); params.set('session_id', session.id); - return `/tmux?${params.toString()}`; + return `/?${params.toString()}`; } return `/sessions/${session.id}`; diff --git a/apps/dashboard/src/components/orchestrator/OrchestratorFleetCard.tsx b/apps/dashboard/src/components/orchestrator/OrchestratorFleetCard.tsx index d7b3f40a..660ec8a9 100644 --- a/apps/dashboard/src/components/orchestrator/OrchestratorFleetCard.tsx +++ b/apps/dashboard/src/components/orchestrator/OrchestratorFleetCard.tsx @@ -71,7 +71,7 @@ export function OrchestratorFleetCard({ const [prompt, setPrompt] = useState(''); const [sending, setSending] = useState(false); const [sendState, setSendState] = useState<{ type: 'success' | 'error'; message: string } | null>(null); - const terminalHref = `/tmux?host_id=${encodeURIComponent(session.host_id)}&session_id=${encodeURIComponent(session.id)}&mode=terminal&attach=1`; + const terminalHref = `/?host_id=${encodeURIComponent(session.host_id)}&session_id=${encodeURIComponent(session.id)}&mode=terminal&attach=1`; const pendingApprovals = attentionItems.filter((item) => ( item.source === 'governance' || ( @@ -167,7 +167,7 @@ export function OrchestratorFleetCard({ {children.map((child) => ( diff --git a/apps/dashboard/src/components/orchestrator/OrchestratorItem.tsx b/apps/dashboard/src/components/orchestrator/OrchestratorItem.tsx index 4741a4dc..2e8881fb 100644 --- a/apps/dashboard/src/components/orchestrator/OrchestratorItem.tsx +++ b/apps/dashboard/src/components/orchestrator/OrchestratorItem.tsx @@ -207,7 +207,7 @@ export function OrchestratorItem({ ? `host_id=${encodeURIComponent(item.sessionHostId)}&` : ''; return ( - + - setIsOpen(false)} /> - - ); -} diff --git a/apps/dashboard/src/components/settings/index.ts b/apps/dashboard/src/components/settings/index.ts index 915e1c53..7e73fe94 100644 --- a/apps/dashboard/src/components/settings/index.ts +++ b/apps/dashboard/src/components/settings/index.ts @@ -1,3 +1,2 @@ -export { SettingsButton } from './SettingsButton'; export { SettingsModal } from './SettingsModal'; export { SettingsSync } from './SettingsSync'; From 29d3ca376855d4481f166a9072b7dfb12ac36e28 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 13:57:27 -0400 Subject: [PATCH 07/13] docs(program): FW3-TMUX-UI R2 correction brief Co-Authored-By: Claude Fable 5 --- tasks/2026-07-20-fw3-tmux-ui-corrections-brief.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 tasks/2026-07-20-fw3-tmux-ui-corrections-brief.md diff --git a/tasks/2026-07-20-fw3-tmux-ui-corrections-brief.md b/tasks/2026-07-20-fw3-tmux-ui-corrections-brief.md new file mode 100644 index 00000000..8e6eebe5 --- /dev/null +++ b/tasks/2026-07-20-fw3-tmux-ui-corrections-brief.md @@ -0,0 +1,12 @@ +# FW3-TMUX-UI — Correction round R2 (Wave 3) + +Lane: FW3-TMUX-UI (attempt 2) · Same worktree/branch/firewall. Your `6526629` is integrated; the independent reviewer returned SHIP-WITH-NOTES with two warnings + two gating nitpicks assigned here. First: `git fetch origin && git rebase origin/refactor/frontend-command-center` (the AI Lead landed canonical-link fixes on top of your work). Fix only these four items. + +1. **W1 — Topology staleness TTL** (`src/stores/tmuxTopology.ts` ~208-229): once a host emits one `tmux.topology`, roster fallback is disabled forever — `receivedAt` is stored but never read, so a host that emits once then goes silent freezes its window/pane structure permanently. Fix: in `setRoster`, when the live snapshot is older than a TTL (suggest 30s — topology coalesces at 500ms and polls reconcile, so anything older is dead), rebuild from roster (and clear the stale `liveByHost` entry). Test: emit → advance past TTL → roster update restores fallback structure. +2. **W2 — Duplicate roster fetch + store thrash** (`src/hooks/useTmuxTopology.ts` ~38-52): `useTmuxHostTopology` runs its own `getTmuxRoster` query per mount (up to 4 with 2-up terminals) and its differently-identical arrays fight the page-level feed in `setRoster`, rebuilding derived state repeatedly. Fix: pass `seedSessions` from the page-level roster into `TmuxWindowStrip`/`TmuxPaneControls` (they have access via the workbench), or make the hook skip its own query when the store already has a roster feed for that host. Zero duplicate HTTP requests on the Command Center path; test asserting no rebuild churn when the same roster identity flows twice. +3. **N1 — Last-window confirm gating** (`windowActions.ts` ~48-54, `TmuxWindowStrip.tsx` ~148-150): only show "This ends the whole tmux session" when the window count is authoritative (`source === 'topology'`); in roster-fallback mode use a softer confirm ("Close this window?") since untracked windows may exist. +4. **N4 — Percent-split version gating** (`paneActions.ts` ~9-15): stop falling back to `agent_version` as a tmux version proxy; unknown tmux version ⇒ plain split (no `-l N%`). + +Gates as before (full TS chain). Commit prefix `fix(tmux-ui):`. Update your handoff (attempt: 2, new frozen_sha, R2 section), then print exactly: + +`FW3-TMUX-UI-R2 FROZEN ` From 22dbf8c6590cfad400600e4c46abdece649381e8 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 13:58:55 -0400 Subject: [PATCH 08/13] docs(program): wave 4 briefs Co-Authored-By: Claude Fable 5 --- tasks/2026-07-20-fw4-fleet-brief.md | 31 ++++++++++++++++++++++++++ tasks/2026-07-20-fw4-surfaces-brief.md | 26 +++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 tasks/2026-07-20-fw4-fleet-brief.md create mode 100644 tasks/2026-07-20-fw4-surfaces-brief.md diff --git a/tasks/2026-07-20-fw4-fleet-brief.md b/tasks/2026-07-20-fw4-fleet-brief.md new file mode 100644 index 00000000..ae0da3cf --- /dev/null +++ b/tasks/2026-07-20-fw4-fleet-brief.md @@ -0,0 +1,31 @@ +# FW4-FLEET — Unified fleet model, terminal attention overlay, prompt composer, badges/filters (Wave 4) + +Lane: FW4-FLEET · Machine: homelinux · Worktree: `~/dev/wt/ac-fw4-fleet` · Branch: `refactor/fw4-fleet` (off `refactor/frontend-command-center`; local, do NOT push) +Plan: Workstream D · Evidence: findings doc §§1,5 · Acceptance: checklist Wave 4. + +## Backend available (use it) + +- `GET /v1/orchestrator/fleet` — one-call aggregate: orchestrator sessions + children rollups + work-item counts + latest report + budget (operator role). Built in Wave 2 exactly to replace the dashboard's per-orchestrator fetch pattern. +- `tmux.topology` UI topic + `POST /v1/sessions/:id/commands` (send_input etc.), attention/approvals stores and endpoints as today. + +## Work items + +1. **One fleet model.** Replace `useOrchestratorFleet`'s per-orchestrator bundle fetches (and its 4-concurrent cap) with the aggregate endpoint. Merge the two fleet representations — `lib/fleetRoster.ts` (+`TmuxOrchestratorRow`) and `useOrchestratorFleet` (+`OrchestratorFleetCard`) — into ONE store/selector set with two presentations (roster tree row; fleet card). Data flows: aggregate endpoint + `sessions.changed` + `tmux.topology` incrementally update the store; eliminate the 750ms-debounced full roster refetch on every `sessions.changed` (`useTmuxRosterData.ts` ~263-269) in favor of targeted updates with a slow reconciliation refetch (e.g. 30s). +2. **Terminal attention overlay.** When the ATTACHED session has a pending attention item (approval, question, error), show a compact inline card overlaying the terminal bottom edge: item summary + approve/deny/respond actions (respond focuses the composer). Dismissable, reappears on new items; never steals typing focus uninvited. +3. **Prompt composer.** In the workbench (mobile + desktop): a multi-line composer as an alternative to raw terminal typing — textarea with send button (dispatches `send_input` with trailing newline), prompt history (persisted recents, up-arrow recall on desktop), and a "send to other session" affordance reusing the existing copy-to flow. Collapsed by default to a single affordance; never covers the terminal when collapsed. +4. **Health badges + saved filters.** Tune session badges for scanning: waiting-input, waiting-approval, error, idle, dirty-git, host-offline, unmanaged — consistent iconography/colors in roster rows AND fleet cards (one badge component). Roster filter chips: persist last-used filter; add "this host" and "recent" saved filters (settings-store persisted). +5. **Decompose `OrchestratorItem.tsx` (952 lines)** into per-item-type renderers + shared action hooks while you're unifying the attention actions (the overlay in item 2 must reuse these, not fork them). +6. **Tests.** Store unit tests (aggregate ingestion, incremental updates, badge derivation, filter persistence); overlay + composer interaction tests; existing suites green. + +## Ownership firewall + +You may edit: `src/components/orchestrator/**`, `src/components/tmux/**`, `src/components/session/**`, `src/components/automation/AutomationAgentCard.tsx`, `src/hooks/**` (fleet/roster/attention), `src/lib/fleetRoster.ts`, `src/lib/api.ts` (additive), `src/stores/**` (orchestrator/settings additive + new fleet store), related tests. You may NOT edit: `src/app/**` routes, `src/components/layout/**`, `src/components/ui/**`, `src/components/settings/**`, `src/components/SessionList.tsx`, `src/components/search/**` (FW4-SURFACES owns those), `packages/**`, `services/**`, `agents/**`. No new dependencies. + +## Gates + +`pnpm lint && pnpm typecheck && pnpm test:ci && pnpm test:smoke:dashboard && pnpm build`. Commit per work item, prefix `feat(fleet):`. ≤3 attempts per failure then hold. + +## Done + +Handoff `tasks/frontend-ux-handoffs/fw4-fleet.md`, committed, then print exactly: +`FW4-FLEET FROZEN ` diff --git a/tasks/2026-07-20-fw4-surfaces-brief.md b/tasks/2026-07-20-fw4-surfaces-brief.md new file mode 100644 index 00000000..144adab0 --- /dev/null +++ b/tasks/2026-07-20-fw4-surfaces-brief.md @@ -0,0 +1,26 @@ +# FW4-SURFACES — Design-system primitives, surface migration, decomposition, command palette (Wave 4) + +Lane: FW4-SURFACES · Machine: homelinux · Worktree: `~/dev/wt/ac-fw4-surfaces` · Branch: `refactor/fw4-surfaces` (off `refactor/frontend-command-center`; local, do NOT push) +Plan: Workstream E · Evidence: findings doc §§1,4,5 · Acceptance: checklist Wave 4. Load your frontend-product-design approach; the existing HSL-token system is the source of truth. + +## Work items + +1. **Complete `components/ui` primitives.** Add shadcn-style `dialog`, `sheet`, `dropdown-menu`, and `command` primitives on Radix (Radix deps that are already in the tree; if a new Radix package is genuinely required, it is the ONLY allowed dependency addition — list it in the handoff). Migrate the hand-rolled modals/sheets in YOUR owned surfaces (below) onto them. Do not touch other lanes' modals. +2. **Surface migration.** Restyle `/sessions`, `/memory`, `/hosts`, `/automation` to the design system: one container/spacing convention, ≥44px tap targets, mobile-fit toolbars (Sessions' ~10-button toolbar collapses into a mobile overflow sheet keeping Select/Search/New visible). Preserve all functionality — this is composition/presentation, not feature change. +3. **Decomposition.** `SettingsPanel.tsx` (1125) → per-domain panels (alerts, session defaults, launch, workspace, notifications, usage) under `components/settings/`, one route shell; `SessionsPageClient.tsx` (666) → filter/selection/dnd hooks + presentational list components; `SessionList.tsx` (643) → row + list + virtualization concerns split. Behavior-identical; existing tests keep passing (add targeted tests for extracted hooks). +4. **Command palette.** `components/ui/command`-based ⌘K/Ctrl-K palette (desktop; long-press search affordance opens it on mobile via the existing search entry): jump to session (fuzzy by title/host), jump to host, launch (opens launch sheet), toggle theme, go to route. One minimal mount allowed in `components/layout/LayoutShell.tsx` (single line, like the terminal host) + a keyboard listener. Palette actions route through existing stores/APIs — no new data paths. +5. **A11y pass on your surfaces**: focus traps in new sheet/dialog usages, aria labels on icon buttons, focus-visible states. +6. **Tests.** Palette open/navigate test, settings panels render test, sessions toolbar overflow test at 390×844, all suites green. + +## Ownership firewall + +You may edit: `src/app/(dashboard)/(sessions|memory|hosts|automation|settings)/**` (page/shell files), `src/components/ui/**`, `src/components/settings/**`, `src/components/SessionList.tsx`, `src/components/search/**`, `src/components/groups/**`, `src/components/import/**`, `src/components/analytics/**`, related tests; single-line palette mount + listener in `components/layout/LayoutShell.tsx`. You may NOT edit: `src/components/(orchestrator|tmux|terminal|session|launch|automation)/**` except `automation` PAGE shell (`app/(dashboard)/automation/**` yes; `components/automation/**` no — FW4-FLEET owns it), `src/app/(dashboard)/page.tsx` / orchestrator routes, `packages/**`, `services/**`, `agents/**`. + +## Gates + +`pnpm lint && pnpm typecheck && pnpm test:ci && pnpm test:smoke:dashboard && pnpm build`. Commit per work item, prefix `feat(surfaces):`. ≤3 attempts per failure then hold. + +## Done + +Handoff `tasks/frontend-ux-handoffs/fw4-surfaces.md`, committed, then print exactly: +`FW4-SURFACES FROZEN ` From 86ce697c6f928e1d5d855e43aa4da5e614cb6742 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 14:10:14 -0400 Subject: [PATCH 09/13] fix(tmux-ui): topology staleness TTL, single roster feed, confirm/version gating (FW3-TMUX-UI-R2 c2bcfbe) Co-Authored-By: Claude Fable 5 --- .../components/tmux/TmuxTerminalWorkspace.tsx | 19 ++++--- .../src/components/tmux/TmuxWindowStrip.tsx | 1 + .../src/components/tmux/paneActions.test.ts | 2 +- .../src/components/tmux/paneActions.ts | 1 - .../src/components/tmux/windowActions.test.ts | 39 +++++++++++++++ .../src/components/tmux/windowActions.ts | 16 +++--- apps/dashboard/src/hooks/useTmuxTopology.ts | 2 +- .../dashboard/src/stores/tmuxTopology.test.ts | 49 +++++++++++++++++-- apps/dashboard/src/stores/tmuxTopology.ts | 48 +++++++++++++++--- tasks/frontend-ux-handoffs/fw3-tmux-ui.md | 38 +++++++++----- tasks/lessons.md | 4 ++ tests/smoke/dashboard.spec.ts | 8 +++ 12 files changed, 187 insertions(+), 40 deletions(-) diff --git a/apps/dashboard/src/components/tmux/TmuxTerminalWorkspace.tsx b/apps/dashboard/src/components/tmux/TmuxTerminalWorkspace.tsx index f9fae872..b06e34cd 100644 --- a/apps/dashboard/src/components/tmux/TmuxTerminalWorkspace.tsx +++ b/apps/dashboard/src/components/tmux/TmuxTerminalWorkspace.tsx @@ -9,9 +9,10 @@ import { PersistentTerminalSlot } from '@/components/terminal/PersistentTerminal import { Button } from '@/components/ui/button'; import { useHydrated } from '@/hooks/useHydrated'; import { useIsMobile } from '@/hooks/useIsMobile'; -import { getSession, getTmuxRoster } from '@/lib/api'; +import { getSession } from '@/lib/api'; import { getSessionDisplayName } from '@/lib/utils'; import { useSettingsStore } from '@/stores/settings'; +import { useTmuxTopologyStore } from '@/stores/tmuxTopology'; import { TmuxPaneControls } from './TmuxPaneControls'; import { TmuxWindowStrip } from './TmuxWindowStrip'; @@ -65,18 +66,16 @@ export function TmuxTerminalWorkspace({ (state) => state.tmuxSecondaryByPrimary[primarySession.id] ?? '' ); const setSecondary = useSettingsStore((state) => state.setTmuxSecondary); - const { data: rosterData } = useQuery({ - queryKey: ['sessions', 'tmux', primarySession.host_id, 'two-up-options'], - queryFn: () => getTmuxRoster({ host_id: primarySession.host_id }), - staleTime: 30_000, - }); + const rosterSessions = useTmuxTopologyStore( + (state) => state.rosterByHost[primarySession.host_id] + ); const options = useMemo( () => - (rosterData?.sessions ?? []).filter( + (rosterSessions ?? []).filter( (session) => session.id !== primarySession.id && Boolean(session.tmux_pane_id) && !session.archived_at ), - [primarySession.id, rosterData?.sessions] + [primarySession.id, rosterSessions] ); const secondaryId = hydrated && !belowDesktop ? rememberedSecondaryId : ''; const { @@ -91,10 +90,10 @@ export function TmuxTerminalWorkspace({ const secondarySession = secondaryDetail?.session; useEffect(() => { - if (!rosterData || !rememberedSecondaryId) return; + if (!rosterSessions || !rememberedSecondaryId) return; if (options.some((session) => session.id === rememberedSecondaryId)) return; setSecondary(primarySession.id, null); - }, [options, primarySession.id, rememberedSecondaryId, rosterData, setSecondary]); + }, [options, primarySession.id, rememberedSecondaryId, rosterSessions, setSecondary]); const showSecondary = Boolean(secondaryId); diff --git a/apps/dashboard/src/components/tmux/TmuxWindowStrip.tsx b/apps/dashboard/src/components/tmux/TmuxWindowStrip.tsx index 7424ba3e..b8b4310e 100644 --- a/apps/dashboard/src/components/tmux/TmuxWindowStrip.tsx +++ b/apps/dashboard/src/components/tmux/TmuxWindowStrip.tsx @@ -146,6 +146,7 @@ export function TmuxWindowStrip({ session, className }: TmuxWindowStripProps) { await runTmuxWindowAction({ sessionId: session.id, windowCount: windows.length, + windowSource: hostTopology?.source ?? 'roster', action, optimistic: () => setWindows(optimisticWindows(windows, action)), rollback: () => setWindows(previous), diff --git a/apps/dashboard/src/components/tmux/paneActions.test.ts b/apps/dashboard/src/components/tmux/paneActions.test.ts index fe76c98a..46c2e4bc 100644 --- a/apps/dashboard/src/components/tmux/paneActions.test.ts +++ b/apps/dashboard/src/components/tmux/paneActions.test.ts @@ -35,7 +35,7 @@ describe('tmux pane actions', () => { }); expect(buildSplitPaneCommand({ ...baseHost, agent_version: '3.1.2' }, 'vertical')).toEqual({ type: 'split_pane', - payload: { direction: 'vertical', percent: 50 }, + payload: { direction: 'vertical' }, }); }); }); diff --git a/apps/dashboard/src/components/tmux/paneActions.ts b/apps/dashboard/src/components/tmux/paneActions.ts index 8591a613..553439cf 100644 --- a/apps/dashboard/src/components/tmux/paneActions.ts +++ b/apps/dashboard/src/components/tmux/paneActions.ts @@ -10,7 +10,6 @@ function reportedTmuxVersion(host?: Host | null): string | undefined { capabilities.tmux_version, capabilities.tmuxVersion, extendedHost.tmux_version, - host.agent_version, ]; return candidates.find((candidate): candidate is string => typeof candidate === 'string'); } diff --git a/apps/dashboard/src/components/tmux/windowActions.test.ts b/apps/dashboard/src/components/tmux/windowActions.test.ts index 6926d8b6..eb3b89c8 100644 --- a/apps/dashboard/src/components/tmux/windowActions.test.ts +++ b/apps/dashboard/src/components/tmux/windowActions.test.ts @@ -8,6 +8,7 @@ describe('tmux window actions', () => { const result = await runTmuxWindowAction({ sessionId: '22222222-2222-4222-8222-222222222222', windowCount: 2, + windowSource: 'topology', action: { type: 'select', windowIndex: 3 }, dispatch, }); @@ -38,6 +39,7 @@ describe('tmux window actions', () => { await runTmuxWindowAction({ sessionId: '22222222-2222-4222-8222-222222222222', windowCount: 2, + windowSource: 'topology', action, dispatch, }); @@ -52,6 +54,7 @@ describe('tmux window actions', () => { const cancelled = await runTmuxWindowAction({ sessionId: '22222222-2222-4222-8222-222222222222', windowCount: 1, + windowSource: 'topology', action: { type: 'close', windowIndex: 0 }, dispatch, confirm, @@ -65,6 +68,41 @@ describe('tmux window actions', () => { const dispatched = await runTmuxWindowAction({ sessionId: '22222222-2222-4222-8222-222222222222', windowCount: 1, + windowSource: 'topology', + action: { type: 'close', windowIndex: 0 }, + dispatch, + confirm, + }); + + expect(dispatched).toBe('dispatched'); + expect(dispatch).toHaveBeenCalledWith('22222222-2222-4222-8222-222222222222', { + type: 'kill_window', + payload: { window_index: 0 }, + }); + }); + + it('uses a softer confirmation when roster fallback cannot prove the last window', async () => { + const dispatch = vi.fn().mockResolvedValue({ cmd_id: 'command-1' }); + const confirm = vi.fn().mockReturnValue(false); + + const cancelled = await runTmuxWindowAction({ + sessionId: '22222222-2222-4222-8222-222222222222', + windowCount: 1, + windowSource: 'roster', + action: { type: 'close', windowIndex: 0 }, + dispatch, + confirm, + }); + + expect(cancelled).toBe('cancelled'); + expect(confirm).toHaveBeenCalledWith('Close this window?'); + expect(dispatch).not.toHaveBeenCalled(); + + confirm.mockReturnValue(true); + const dispatched = await runTmuxWindowAction({ + sessionId: '22222222-2222-4222-8222-222222222222', + windowCount: 1, + windowSource: 'roster', action: { type: 'close', windowIndex: 0 }, dispatch, confirm, @@ -86,6 +124,7 @@ describe('tmux window actions', () => { runTmuxWindowAction({ sessionId: '22222222-2222-4222-8222-222222222222', windowCount: 2, + windowSource: 'topology', action: { type: 'rename', windowIndex: 1, name: 'review' }, dispatch: vi.fn().mockRejectedValue(error), optimistic, diff --git a/apps/dashboard/src/components/tmux/windowActions.ts b/apps/dashboard/src/components/tmux/windowActions.ts index a63812a7..7a698db0 100644 --- a/apps/dashboard/src/components/tmux/windowActions.ts +++ b/apps/dashboard/src/components/tmux/windowActions.ts @@ -10,6 +10,7 @@ export type TmuxWindowAction = interface RunTmuxWindowActionOptions { sessionId: string; windowCount: number; + windowSource: 'topology' | 'roster'; action: TmuxWindowAction; dispatch?: typeof sendCommand; confirm?: (message: string) => boolean; @@ -39,18 +40,21 @@ function commandForAction(action: TmuxWindowAction): CommandRequest { export async function runTmuxWindowAction({ sessionId, windowCount, + windowSource, action, dispatch = sendCommand, confirm = (message) => window.confirm(message), optimistic, rollback, }: RunTmuxWindowActionOptions): Promise<'dispatched' | 'cancelled'> { - if ( - action.type === 'close' && - windowCount === 1 && - !confirm('This ends the whole tmux session') - ) { - return 'cancelled'; + if (action.type === 'close') { + const confirmation = + windowSource === 'topology' + ? windowCount === 1 + ? 'This ends the whole tmux session' + : null + : 'Close this window?'; + if (confirmation && !confirm(confirmation)) return 'cancelled'; } optimistic?.(); try { diff --git a/apps/dashboard/src/hooks/useTmuxTopology.ts b/apps/dashboard/src/hooks/useTmuxTopology.ts index bdda3c28..633d11aa 100644 --- a/apps/dashboard/src/hooks/useTmuxTopology.ts +++ b/apps/dashboard/src/hooks/useTmuxTopology.ts @@ -40,7 +40,7 @@ export function useTmuxHostTopology(hostId: string, seedSessions?: SessionWithSn const { data } = useQuery({ queryKey: ['sessions', 'tmux', hostId, 'topology-fallback'], queryFn: () => getTmuxRoster({ host_id: hostId }), - enabled: Boolean(hostId && !seedSessions), + enabled: Boolean(hostId && !seedSessions && !storedRoster), staleTime: 30_000, }); const fallbackSessions = useMemo( diff --git a/apps/dashboard/src/stores/tmuxTopology.test.ts b/apps/dashboard/src/stores/tmuxTopology.test.ts index d4394c3d..504d005f 100644 --- a/apps/dashboard/src/stores/tmuxTopology.test.ts +++ b/apps/dashboard/src/stores/tmuxTopology.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { SessionWithSnapshot, TmuxTopologyPayload } from '@agent-command/schema'; import { useTmuxTopologyStore } from './tmuxTopology'; @@ -36,6 +36,7 @@ function rosterSession(overrides: Partial = {}): SessionWit describe('tmux topology store', () => { beforeEach(() => useTmuxTopologyStore.getState().reset()); + afterEach(() => vi.useRealTimers()); it('uses a host topology snapshot and joins its panes to roster sessions', () => { const payload: TmuxTopologyPayload = { @@ -143,13 +144,55 @@ describe('tmux topology store', () => { }); }); - it('does not publish a new snapshot when a feed repeats the same roster session objects', () => { + it('returns to roster fallback after a host topology snapshot goes stale', () => { + vi.useFakeTimers(); + vi.setSystemTime('2026-07-20T14:00:00.000Z'); + const session = rosterSession(); + useTmuxTopologyStore.getState().setRoster(hostId, [session]); + useTmuxTopologyStore.getState().receiveTopology( + hostId, + { + reason: 'poll', + tmux_sessions: [ + { + session_name: 'agents', + attached: true, + windows: [ + { + window_index: 1, + window_name: 'live-name', + active: true, + zoomed: false, + layout: 'tiled', + bell: false, + activity: false, + panes: [], + }, + ], + }, + ], + }, + '2026-07-20T14:00:00.000Z' + ); + + vi.advanceTimersByTime(30_001); + useTmuxTopologyStore.getState().setRoster(hostId, [session]); + + const state = useTmuxTopologyStore.getState(); + expect(state.hosts[hostId]).toMatchObject({ + source: 'roster', + sessions: [{ windows: [{ windowName: 'fallback-name' }] }], + }); + expect(state.liveByHost[hostId]).toBeUndefined(); + }); + + it('does not publish a new snapshot when a feed repeats the same roster identity', () => { const session = rosterSession(); useTmuxTopologyStore.getState().setRoster(hostId, [session]); const firstHosts = useTmuxTopologyStore.getState().hosts; const firstRoster = useTmuxTopologyStore.getState().rosterByHost; - useTmuxTopologyStore.getState().setRoster(hostId, [session]); + useTmuxTopologyStore.getState().setRoster(hostId, [rosterSession()]); expect(useTmuxTopologyStore.getState().hosts).toBe(firstHosts); expect(useTmuxTopologyStore.getState().rosterByHost).toBe(firstRoster); diff --git a/apps/dashboard/src/stores/tmuxTopology.ts b/apps/dashboard/src/stores/tmuxTopology.ts index 283e9991..c6628406 100644 --- a/apps/dashboard/src/stores/tmuxTopology.ts +++ b/apps/dashboard/src/stores/tmuxTopology.ts @@ -48,6 +48,8 @@ interface LiveSnapshot { receivedAt: string; } +export const TMUX_TOPOLOGY_STALE_AFTER_MS = 30_000; + interface TmuxTopologyStore { hosts: Record; rosterByHost: Record; @@ -193,24 +195,58 @@ const initialState = { liveByHost: {} as Record, }; +function liveSnapshotIsFresh(snapshot: LiveSnapshot): boolean { + const receivedAt = Date.parse(snapshot.receivedAt); + return Number.isFinite(receivedAt) && Date.now() - receivedAt <= TMUX_TOPOLOGY_STALE_AFTER_MS; +} + +function sameRosterSession( + left: SessionWithSnapshot, + right: SessionWithSnapshot +): boolean { + if (left === right) return true; + const leftIdentity = rosterIdentity(left); + const rightIdentity = rosterIdentity(right); + return ( + left.id === right.id && + left.host_id === right.host_id && + left.status === right.status && + left.title === right.title && + left.cwd === right.cwd && + left.archived_at === right.archived_at && + left.metadata?.tmux?.current_command === right.metadata?.tmux?.current_command && + leftIdentity.paneId === rightIdentity.paneId && + leftIdentity.paneIndex === rightIdentity.paneIndex && + leftIdentity.sessionName === rightIdentity.sessionName && + leftIdentity.windowIndex === rightIdentity.windowIndex && + leftIdentity.windowName === rightIdentity.windowName + ); +} + export const useTmuxTopologyStore = create((set) => ({ ...initialState, setRoster: (hostId, sessions) => set((state) => { const currentRoster = state.rosterByHost[hostId]; - if ( + const sameRoster = currentRoster && currentRoster.length === sessions.length && - currentRoster.every((session, index) => session === sessions[index]) - ) { + currentRoster.every((session, index) => sameRosterSession(session, sessions[index])); + const live = state.liveByHost[hostId]; + const staleLive = live && !liveSnapshotIsFresh(live); + if (sameRoster && !staleLive) { return state; } - const live = state.liveByHost[hostId]; + const nextLiveByHost = staleLive ? { ...state.liveByHost } : state.liveByHost; + if (staleLive) delete nextLiveByHost[hostId]; return { - rosterByHost: { ...state.rosterByHost, [hostId]: sessions }, + rosterByHost: sameRoster + ? state.rosterByHost + : { ...state.rosterByHost, [hostId]: sessions }, + liveByHost: nextLiveByHost, hosts: { ...state.hosts, - [hostId]: live + [hostId]: live && !staleLive ? buildLiveTopology(hostId, live.payload, sessions, live.receivedAt) : buildRosterTopology(hostId, sessions), }, diff --git a/tasks/frontend-ux-handoffs/fw3-tmux-ui.md b/tasks/frontend-ux-handoffs/fw3-tmux-ui.md index 4fce0a88..bed89834 100644 --- a/tasks/frontend-ux-handoffs/fw3-tmux-ui.md +++ b/tasks/frontend-ux-handoffs/fw3-tmux-ui.md @@ -1,7 +1,7 @@ --- lane: FW3-TMUX-UI -frozen_sha: 6526629f258aca0d6bc16e0b02f4a21d57c0ede6 -attempt: 1 +frozen_sha: c2bcfbecec86b13cc7b2da80a0b4182a3838eb81 +attempt: 2 state: frozen gates: lint: pass @@ -12,20 +12,22 @@ gates: go: n/a proof: - "pnpm install → completed before repository inspection or changes; lockfile unchanged and no dependencies added" - - "CHOKIDAR_USEPOLLING=1 WATCHPACK_POLLING=true pnpm lint && pnpm typecheck && pnpm test:ci && pnpm test:smoke:dashboard && pnpm build → complete mandatory gate passed in order on the accepted FW3-SHELL integration" + - "git fetch origin && git rebase origin/refactor/frontend-command-center → R2 rebased successfully before correction work" + - "CHOKIDAR_USEPOLLING=1 WATCHPACK_POLLING=true pnpm lint && pnpm typecheck && pnpm test:ci && pnpm test:smoke:dashboard && pnpm build → complete R2 mandatory gate passed in order on the accepted Command Center integration" - "pnpm lint → 5/5 Turbo tasks passed" - "pnpm typecheck → 5/5 Turbo tasks passed; Next route types generated successfully" - - "pnpm test:ci → 389 tests passed: dashboard 99, control-plane 198, schema 48, CLI 44" - - "pnpm test:smoke:dashboard → 14/14 Chromium scenarios passed, including canonical root routing, desktop tmux controls, mobile selection, the window strip, and the scrollback pager" + - "pnpm test:ci → 391 tests passed: dashboard 101, control-plane 198, schema 48, CLI 44" + - "pnpm test:smoke:dashboard → 14/14 Chromium scenarios passed, including zero duplicate roster requests after Command Center selection" - "pnpm build → 4/4 Turbo build tasks passed; Next.js 16.2.10 production build completed" - - "focused tmux Vitest run → 14/14 topology, window-action, pane-version, quick-switch, scrollback-paging, and canonical-route tests passed" + - "focused R2 Vitest runs → topology TTL/reference stability 4/4, source-aware window actions 7/7, and tmux-version split gating 1/1 passed" + - "focused R2 Playwright regression → 1/1 tmux roster scenario passed after first proving two duplicate roster requests on the old implementation" - "focused integrated Playwright rerun after minimizing the smoke diff → 3/3 desktop/mobile tmux scenarios passed" - "PLAYWRIGHT_CAPTURE_UI=1 focused Playwright run → desktop terminal and 390x844 mobile history screenshots captured and visually inspected" - "frontend-product-design audit_frontend.sh → lint, typecheck, and tests passed; manual responsive/state audit scored 95/100 with no hard fails" - - "git diff --name-only 7dfcf787523e524ed48ed42b5b27d3fc922e92f5..6526629f258aca0d6bc16e0b02f4a21d57c0ede6 -- forbidden ownership paths → empty" + - "git diff --name-only origin/refactor/frontend-command-center...c2bcfbecec86b13cc7b2da80a0b4182a3838eb81 → only lane-owned tmux components/hooks/store/tests changed" assumptions: - - "A host supports percentage splits only when tmux_version/tmuxVersion or a parseable agent version proves tmux >= 3.1; unknown versions conservatively receive a plain split." - - "Receipt of tmux.topology feature-detects live topology independently per host; hosts that emit nothing remain fully functional through roster-derived windows and panes." + - "A host supports percentage splits only when tmux_version/tmuxVersion proves tmux >= 3.1; agent_version and unknown tmux versions conservatively receive a plain split." + - "Receipt of tmux.topology feature-detects live topology independently per host; a snapshot older than 30 seconds is discarded and the next roster poll restores fallback structure." - "The existing UI recent-session store is the shared source for the launch rail and mobile pane switcher." uncertainties: - "The command endpoint confirms dispatch acceptance but exposes no UI command-result topic. Optimistic state rolls back on immediate HTTP failure and later authoritative topology reconciles remote execution outcomes." @@ -38,8 +40,8 @@ blockers: [] ## What changed -- Topology: a per-host Zustand store consumes `tmux.topology`, joins panes to tracked roster sessions, and derives equivalent sessions/windows/panes from roster metadata until each host actually emits live topology. Repeated identical rosters are reference-stable to avoid subscription render loops. -- Window management: the workbench terminal has an accessible tab strip for active state, activity/bell indicators, select, inline rename, close, and new-window actions. Mutations are optimistic with HTTP-error rollback/toasts, and closing the last window requires the exact hard confirmation that the whole tmux session will end. +- Topology: a per-host Zustand store consumes `tmux.topology`, joins panes to tracked roster sessions, and derives equivalent sessions/windows/panes from roster metadata until each host actually emits live topology. Live snapshots expire after 30 seconds, and semantically identical roster clones remain reference-stable to avoid subscription render loops. +- Window management: the workbench terminal has an accessible tab strip for active state, activity/bell indicators, select, inline rename, close, and new-window actions. Mutations are optimistic with HTTP-error rollback/toasts. Only an authoritative one-window topology uses the hard session-ending confirmation; roster fallback uses `Close this window?`. - Pane management: desktop and mobile controls dispatch horizontal/vertical splits, zoom, directional selection, and confirmed pane kill. Percentage split payloads are capability-gated. The desktop tmux key bar is collapsible, defaults closed, and persists its preference. - Terminal composition: desktop can mount one independent secondary foreground terminal beside the persistent primary terminal, remembers a same-host secondary per primary session, and closes without expanding the one-background-terminal budget. Mobile remains single-terminal and adds a horizontally scrollable recent-pane strip sourced from the shared recent-session state. - History: `View history` opens a responsive, searchable, selectable overlay that requests 500-line ranges, loads older ranges from the top, virtualizes rendered rows, and supports copying all content or matches without mutating the xterm buffer. @@ -53,6 +55,14 @@ blockers: [] - Scrollback stays in a separate pager by design; older content is never prepended into xterm. - Following the AI Lead addendum, `useTmuxRosterData` now builds in-app navigation from `/` while retaining every query parameter. Incoming `/tmux?...` compatibility remains owned by and verified with the sibling query-preserving redirect. +## R2 corrections + +- Stale `tmux.topology` snapshots now expire after a 30-second TTL. A roster update clears the stale live entry and rebuilds the host from fallback data. +- Command Center child surfaces consume the page-fed roster store. The standalone topology hook still fetches a fallback when mounted without that feed, while semantically identical roster arrays no longer rebuild state. +- Window-close confirmation copy is gated by topology authority: only a proven last window warns that the whole session will end; roster fallback uses the softer close warning. +- Percentage splits require an explicit tmux version capability at 3.1 or newer. Agent versions are no longer treated as tmux versions. +- The canonical navigation base remains `/` for mobile roster selection, preserving query state and avoiding the `/tmux` redirect remount; redirect compatibility remains covered by the integrated smoke suite. + ## Frontend quality audit The integrated surface scored 95/100 with no hard failures: product fit 15/15, information architecture 14/15, visual design 13/15, dashboard/data clarity 15/15, interaction states 9/10, accessibility 14/15, responsive behavior 10/10, and performance polish 5/5. Desktop and mobile screenshots were inspected after rebasing onto the accepted root Command Center shell; compact desktop controls no longer clip at 1280px, and the mobile history sheet has no horizontal overflow. @@ -66,5 +76,9 @@ The integrated surface scored 95/100 with no hard failures: product fit 15/15, i - `7a8ecbf` — `feat(tmux-ui): add mobile recent pane switcher` - `4aca3da` — `feat(tmux-ui): add virtualized scrollback pager` - `6526629` — `feat(tmux-ui): add tmux interaction coverage` +- `650f117` — `fix(tmux-ui): expire stale topology snapshots` +- `9a5912f` — `fix(tmux-ui): eliminate duplicate roster feeds` +- `3d65086` — `fix(tmux-ui): gate last-window confirmation by topology` +- `c2bcfbe` — `fix(tmux-ui): require reported tmux version for percent splits` -FW3-TMUX-UI FROZEN 6526629f258aca0d6bc16e0b02f4a21d57c0ede6 +FW3-TMUX-UI-R2 FROZEN c2bcfbecec86b13cc7b2da80a0b4182a3838eb81 diff --git a/tasks/lessons.md b/tasks/lessons.md index d4743ca8..7bc0adc6 100644 --- a/tasks/lessons.md +++ b/tasks/lessons.md @@ -39,3 +39,7 @@ - Date: 2026-07-20 Correction: The Command Center moved from `/tmux` to `/`, but tmux roster navigation still targeted the legacy redirect. Rule: Treat `/` as the canonical Command Center route for new tmux navigation while preserving query parameters so incoming `/tmux` redirects remain compatible without adding an avoidable remount to in-app selections. + +- Date: 2026-07-20 + Correction: Wave 3 review found that live topology never expired, child roster consumers duplicated fetches and rebuilds, and destructive/version-gated actions trusted non-authoritative signals. + Rule: Expire optional live feeds back to polling, share page-level query results with child consumers, and gate destructive copy or protocol flags only on authoritative source metadata. diff --git a/tests/smoke/dashboard.spec.ts b/tests/smoke/dashboard.spec.ts index 6db699a8..e10dd484 100644 --- a/tests/smoke/dashboard.spec.ts +++ b/tests/smoke/dashboard.spec.ts @@ -744,6 +744,13 @@ test('renders tmux roster with windows and panes, supports selection and filteri await expect(page.getByText('agents', { exact: true })).toBeVisible(); await expect(page.getByText('ops')).toBeVisible(); await expect(page.getByRole('button', { name: 'Waiting', exact: true })).toBeVisible(); + let duplicateRosterRequests = 0; + page.on('request', (request) => { + const url = new URL(request.url()); + if (request.method() === 'GET' && url.pathname === '/v1/tmux/roster') { + duplicateRosterRequests += 1; + } + }); await page.getByText('agents', { exact: true }).click(); await expect(page.getByText('0 · agent-command')).toBeVisible(); @@ -755,6 +762,7 @@ test('renders tmux roster with windows and panes, supports selection and filteri await expect(page.getByRole('heading', { name: 'Mobile UX review' })).toBeVisible(); await expect(page.getByTestId('tmux-window-strip')).toBeVisible(); await expect(page.getByLabel('Secondary terminal')).toBeVisible(); + await expect.poll(() => duplicateRosterRequests).toBe(0); if (process.env.PLAYWRIGHT_CAPTURE_UI === '1') { await page.screenshot({ path: testInfo.outputPath('tmux-terminal-desktop.png'), fullPage: true }); } From 86f201c4f3f8afd261e58b0518bfc8edec364bd1 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 14:30:14 -0400 Subject: [PATCH 10/13] chore(program): R2 integrated; stale .next cache diagnosis logged Co-Authored-By: Claude Fable 5 --- tasks/frontend-ux-log.md | 2 ++ tasks/frontend-ux-metrics.jsonl | 1 + 2 files changed, 3 insertions(+) diff --git a/tasks/frontend-ux-log.md b/tasks/frontend-ux-log.md index 27d94ff1..adc56e61 100644 --- a/tasks/frontend-ux-log.md +++ b/tasks/frontend-ux-log.md @@ -26,3 +26,5 @@ - agentd rollout: new binary BUILT at effab04 and staged at /tmp/agentd-new on heavisidelinux (temp worktree /tmp/ac-build-effab04; backup ~/.local/bin/agentd.bak-fw2 exists). In-place replacement of the RUNNING binary was blocked by the local permission policy — HELD FOR OWNER: run `rm ~/.local/bin/agentd && cp /tmp/agentd-new ~/.local/bin/agentd && systemctl --user restart agentd` on heavisidelinux, then optionally set `topology_events: true` under tmux: in ~/.config/agentd/config.yaml. Program continues regardless (Wave-3 UI has roster fallback). - Wave 3 launched: FW3-SHELL + FW3-TMUX-UI codex lanes active on homelinux (activation verified). - ~22:20Z FW3-SHELL froze at `5bba177` (attempt 1): gate re-run green, firewall clean, net-negative diff (legacy landing + SpawnSessionDialog + OrchestratorModal duplication deleted; launch definitions centralized). Flagged cross-lane seam (useTmuxRosterData /tmux URLs) steered to FW3-TMUX-UI mid-flight. INTEGRATED @ a5788af. +- ~23:30Z FW3-TMUX-UI-R2 froze at `c2bcfbe` (attempt 2): clean rebase onto integration tip, 4 fix commits (topology TTL 30s w/ stale-live eviction — verified in diff; single roster feed; last-window confirm gated on authoritative topology; percent splits require reported tmux version). INTEGRATED @ 86ce697. AI Lead separately fixed reviewer W3+N5 (canonical internal links, dead SettingsButton) @ af8352e. +- Final wave-3 gate initially failed twice on a smoke webServer tailwind @config resolution error; orchestrator session died mid-diagnosis (runaway dev-server probe). Root cause found on resume: STALE `.next` Turbopack cache in the main repo vs wave-3 route restructure — fresh compile clean after cache removal. Lesson: clear `apps/dashboard/.next` in the integration repo after route-topology changes. diff --git a/tasks/frontend-ux-metrics.jsonl b/tasks/frontend-ux-metrics.jsonl index 58a612d7..257352ed 100644 --- a/tasks/frontend-ux-metrics.jsonl +++ b/tasks/frontend-ux-metrics.jsonl @@ -11,3 +11,4 @@ {"ts":"2026-07-20T21:20:00Z","event":"wave_deployed","wave":2,"sha":"effab04"} {"ts":"2026-07-20T21:25:00Z","event":"wave_launched","wave":3,"lanes":["FW3-SHELL","FW3-TMUX-UI"]} {"ts":"2026-07-20T22:20:00Z","event":"lane_frozen","lane":"FW3-SHELL","attempt":1,"frozen_sha":"5bba177","verdict":"accepted","integrated_sha":"a5788af"} +{"ts":"2026-07-20T23:30:00Z","event":"lane_frozen","lane":"FW3-TMUX-UI","attempt":2,"frozen_sha":"c2bcfbe","verdict":"accepted","integrated_sha":"86ce697"} From 772218c6dd132a8df3467c2ae7eff3d6d70ddca3 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 14:31:19 -0400 Subject: [PATCH 11/13] chore(program): wave 3 complete Co-Authored-By: Claude Fable 5 --- tasks/frontend-ux-log.md | 1 + tasks/frontend-ux-metrics.jsonl | 1 + 2 files changed, 2 insertions(+) diff --git a/tasks/frontend-ux-log.md b/tasks/frontend-ux-log.md index adc56e61..61780b59 100644 --- a/tasks/frontend-ux-log.md +++ b/tasks/frontend-ux-log.md @@ -28,3 +28,4 @@ - ~22:20Z FW3-SHELL froze at `5bba177` (attempt 1): gate re-run green, firewall clean, net-negative diff (legacy landing + SpawnSessionDialog + OrchestratorModal duplication deleted; launch definitions centralized). Flagged cross-lane seam (useTmuxRosterData /tmux URLs) steered to FW3-TMUX-UI mid-flight. INTEGRATED @ a5788af. - ~23:30Z FW3-TMUX-UI-R2 froze at `c2bcfbe` (attempt 2): clean rebase onto integration tip, 4 fix commits (topology TTL 30s w/ stale-live eviction — verified in diff; single roster feed; last-window confirm gated on authoritative topology; percent splits require reported tmux version). INTEGRATED @ 86ce697. AI Lead separately fixed reviewer W3+N5 (canonical internal links, dead SettingsButton) @ af8352e. - Final wave-3 gate initially failed twice on a smoke webServer tailwind @config resolution error; orchestrator session died mid-diagnosis (runaway dev-server probe). Root cause found on resume: STALE `.next` Turbopack cache in the main repo vs wave-3 route restructure — fresh compile clean after cache removal. Lesson: clear `apps/dashboard/.next` in the integration repo after route-topology changes. +- WAVE 3 COMPLETE: final gate green after .next cache fix (14/14 smoke). Reviewer verdict SHIP-WITH-NOTES; W1/W2/N1/N4 closed in R2, W3/N5 by AI Lead, N2/N3/N6 recorded-skipped (self-healing/cosmetic). PR to main next. diff --git a/tasks/frontend-ux-metrics.jsonl b/tasks/frontend-ux-metrics.jsonl index 257352ed..0e69f9a4 100644 --- a/tasks/frontend-ux-metrics.jsonl +++ b/tasks/frontend-ux-metrics.jsonl @@ -12,3 +12,4 @@ {"ts":"2026-07-20T21:25:00Z","event":"wave_launched","wave":3,"lanes":["FW3-SHELL","FW3-TMUX-UI"]} {"ts":"2026-07-20T22:20:00Z","event":"lane_frozen","lane":"FW3-SHELL","attempt":1,"frozen_sha":"5bba177","verdict":"accepted","integrated_sha":"a5788af"} {"ts":"2026-07-20T23:30:00Z","event":"lane_frozen","lane":"FW3-TMUX-UI","attempt":2,"frozen_sha":"c2bcfbe","verdict":"accepted","integrated_sha":"86ce697"} +{"ts":"2026-07-21T00:05:00Z","event":"wave_complete","wave":3,"reviewer_verdict":"SHIP-WITH-NOTES","notes_closed_in":"FW3-TMUX-UI-R2 + AI Lead","gate":"green"} From 2d64726c2296908352add804d23b52a5b6815f04 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 14:45:29 -0400 Subject: [PATCH 12/13] =?UTF-8?q?fix(shell,tmux-ui):=20PR-review=20?= =?UTF-8?q?=E2=80=94=20idle/active=20bucket=20exclusivity,=20exact=20nav?= =?UTF-8?q?=20matching,=20confirm=20on=20every=20topology=20window=20close?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5 --- apps/dashboard/src/app/(dashboard)/settings/UsageOverview.tsx | 2 +- apps/dashboard/src/components/layout/SidebarNav.tsx | 2 +- apps/dashboard/src/components/tmux/windowActions.test.ts | 1 + apps/dashboard/src/components/tmux/windowActions.ts | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) diff --git a/apps/dashboard/src/app/(dashboard)/settings/UsageOverview.tsx b/apps/dashboard/src/app/(dashboard)/settings/UsageOverview.tsx index 26cc27cc..127e5b52 100644 --- a/apps/dashboard/src/app/(dashboard)/settings/UsageOverview.tsx +++ b/apps/dashboard/src/app/(dashboard)/settings/UsageOverview.tsx @@ -50,7 +50,7 @@ export function UsageOverview() { const sessions = sessionsQuery.data?.sessions; const hosts = hostsQuery.data?.hosts; return { - active: sessions ? sessions.filter((session) => ['RUNNING', 'STARTING'].includes(session.status)).length : null, + active: sessions ? sessions.filter((session) => ['RUNNING', 'STARTING'].includes(session.status) && !session.idled_at).length : null, attention: sessions ? sessions.filter((session) => ['WAITING_FOR_INPUT', 'WAITING_FOR_APPROVAL', 'ERROR'].includes(session.status)).length : null, idle: sessions ? sessions.filter((session) => session.status === 'IDLE' || session.idled_at).length : null, onlineHosts: hosts ? hosts.filter((host) => isHostOnline(host.last_seen_at || null)).length : null, diff --git a/apps/dashboard/src/components/layout/SidebarNav.tsx b/apps/dashboard/src/components/layout/SidebarNav.tsx index f977eb3d..6bd2d6d1 100644 --- a/apps/dashboard/src/components/layout/SidebarNav.tsx +++ b/apps/dashboard/src/components/layout/SidebarNav.tsx @@ -84,7 +84,7 @@ export function SidebarNav({ collapsed }: SidebarNavProps) { if (path === '/') { return pathname === '/'; } - return pathname.startsWith(path); + return pathname === path || pathname.startsWith(`${path}/`); }; if (collapsed) { diff --git a/apps/dashboard/src/components/tmux/windowActions.test.ts b/apps/dashboard/src/components/tmux/windowActions.test.ts index eb3b89c8..5c5d2392 100644 --- a/apps/dashboard/src/components/tmux/windowActions.test.ts +++ b/apps/dashboard/src/components/tmux/windowActions.test.ts @@ -42,6 +42,7 @@ describe('tmux window actions', () => { windowSource: 'topology', action, dispatch, + confirm: () => true, }); expect(dispatch).toHaveBeenCalledWith('22222222-2222-4222-8222-222222222222', command); diff --git a/apps/dashboard/src/components/tmux/windowActions.ts b/apps/dashboard/src/components/tmux/windowActions.ts index 7a698db0..c80b43d3 100644 --- a/apps/dashboard/src/components/tmux/windowActions.ts +++ b/apps/dashboard/src/components/tmux/windowActions.ts @@ -52,7 +52,7 @@ export async function runTmuxWindowAction({ windowSource === 'topology' ? windowCount === 1 ? 'This ends the whole tmux session' - : null + : 'Close this window?' : 'Close this window?'; if (confirmation && !confirm(confirmation)) return 'cancelled'; } From e3f229521516fc74dae0a539e7c9324c95db4b9f Mon Sep 17 00:00:00 2001 From: cvsloane Date: Mon, 20 Jul 2026 14:45:45 -0400 Subject: [PATCH 13/13] docs(program): carry topology stale-timer item into FW4-FLEET brief Co-Authored-By: Claude Fable 5 --- tasks/2026-07-20-fw4-fleet-brief.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tasks/2026-07-20-fw4-fleet-brief.md b/tasks/2026-07-20-fw4-fleet-brief.md index ae0da3cf..cc7ae729 100644 --- a/tasks/2026-07-20-fw4-fleet-brief.md +++ b/tasks/2026-07-20-fw4-fleet-brief.md @@ -10,7 +10,7 @@ Plan: Workstream D · Evidence: findings doc §§1,5 · Acceptance: checklist Wa ## Work items -1. **One fleet model.** Replace `useOrchestratorFleet`'s per-orchestrator bundle fetches (and its 4-concurrent cap) with the aggregate endpoint. Merge the two fleet representations — `lib/fleetRoster.ts` (+`TmuxOrchestratorRow`) and `useOrchestratorFleet` (+`OrchestratorFleetCard`) — into ONE store/selector set with two presentations (roster tree row; fleet card). Data flows: aggregate endpoint + `sessions.changed` + `tmux.topology` incrementally update the store; eliminate the 750ms-debounced full roster refetch on every `sessions.changed` (`useTmuxRosterData.ts` ~263-269) in favor of targeted updates with a slow reconciliation refetch (e.g. 30s). +1. **One fleet model.** Replace `useOrchestratorFleet`'s per-orchestrator bundle fetches (and its 4-concurrent cap) with the aggregate endpoint. Merge the two fleet representations — `lib/fleetRoster.ts` (+`TmuxOrchestratorRow`) and `useOrchestratorFleet` (+`OrchestratorFleetCard`) — into ONE store/selector set with two presentations (roster tree row; fleet card). Data flows: aggregate endpoint + `sessions.changed` + `tmux.topology` incrementally update the store; eliminate the 750ms-debounced full roster refetch on every `sessions.changed` (`useTmuxRosterData.ts` ~263-269) in favor of targeted updates with a slow reconciliation refetch (e.g. 30s). Include a timer-based check so a stale live-topology snapshot (host stopped emitting) falls back to roster WITHOUT waiting for the next roster fetch (carried PR-88 review item). 2. **Terminal attention overlay.** When the ATTACHED session has a pending attention item (approval, question, error), show a compact inline card overlaying the terminal bottom edge: item summary + approve/deny/respond actions (respond focuses the composer). Dismissable, reappears on new items; never steals typing focus uninvited. 3. **Prompt composer.** In the workbench (mobile + desktop): a multi-line composer as an alternative to raw terminal typing — textarea with send button (dispatches `send_input` with trailing newline), prompt history (persisted recents, up-arrow recall on desktop), and a "send to other session" affordance reusing the existing copy-to flow. Collapsed by default to a single affordance; never covers the terminal when collapsed. 4. **Health badges + saved filters.** Tune session badges for scanning: waiting-input, waiting-approval, error, idle, dirty-git, host-offline, unmanaged — consistent iconography/colors in roster rows AND fleet cards (one badge component). Roster filter chips: persist last-used filter; add "this host" and "recent" saved filters (settings-store persisted).