Files
fusion/packages/dashboard/app/components/command-center/MissionControlPanel.tsx
gsxdsm e9e63d8e0f consolidate/capacity: --strict was red on main (my #2621), 14 stale baselines, routines seeding a deleted column, worktrees-off audit (#2652)
Capacity unit consolidation. Three coherent themes, small commits
inside.

## Census before/after (`node scripts/lifecycle-column-census.mjs`)

| | before | after |
|---|---:|---:|
| triage column guards (the bar) | 10 | **10** |
| `--strict` on main | ❌ **RED** | ✅ green |
| baseline staleness | 14 files stale | **0** |

This branch does **not** move the triage bar — its remaining 10 are
moves.ts (dies with the flag), the dashboard cluster, and one deliberate
site. It fixes the instrument that measures the bar, plus a live defect
the comparison count cannot see.

---

## 1. `--strict` was RED on clean `origin/main`, and it was my fault

```
packages/dashboard/src/routes/register-task-workflow-routes.ts: 22 -> 23
```

My merged #2621 added a v1-IR pre-WIP fallback answering a greptile P1
and shipped no marker or baseline update, so the program's measuring
instrument has been failing on main since it landed.

Fixed **at the site** with a `DELIBERATE-LITERAL` marker, not by bumping
the baseline. That branch runs only when the IR declares no columns and
no nodes, so there is no role to resolve — `resolveLifecycleColumns`
returns nothing and the legacy pre-implementation ids are the only
pre-WIP signal that exists there. It is *unconvertible*, not unfinished;
the sibling `else` two lines down is the trait path for every IR that
can answer. A rise that is genuinely correct belongs where a reader will
see it.

## 2. The baseline was stale for 14 files — a hole, not cosmetics

A stale allowance lets converted guards return while the check stays
green. Measured gaps:

```
self-healing.ts          allows 126, tree has 111
executor.ts              allows 112, tree has 104
moves.ts                 allows  44, tree has  39
default-workflow-hooks   allows  25, tree has   7
mission-feature-sync     allows   5, tree has   0
MissionControlPanel      allows   4, tree has   0        (+8 more)
```

**Only two of the fourteen are mine.** The other twelve are
already-merged conversions by other workers where nobody re-recorded.
Re-recorded all fourteen here rather than waiting for twelve PRs,
because until it happens the ratchet is not holding the 779 it exists to
hold. Flagging it plainly: those drops are other people's work being
locked in, not mine being claimed.

## 3. Routines created tasks into the column U11 deleted

The routine editor's "Target Column" defaulted to `triage`. That value
is submitted as the create step's `taskColumn`, and an **explicit**
column bypasses the workflow entry-column resolution added for
column-less creates (#2589) — so every routine saved with the untouched
default seeded its tasks into a column the board does not declare.

Defaulting to `todo` would be the same mistake one column over: a custom
workflow declaring no `todo` is seeded into an undeclared column just as
surely, because an explicit column overrides entry resolution whatever
its value. So the default sends **nothing** and each workflow's own
intake resolution decides.

The `triage` **option** is removed too, not merely un-defaulted — fixing
the initializer alone left the operator able to pick the deleted column
one click away, and it was the option labelled "Planning", the name the
merged `todo` column now displays. Removing it retires that label
inversion as well.

Found by scanning **membership** forms rather than comparisons: the
comparison census cannot see a `?? "triage"` default, so no count showed
this and nobody was looking. Revert-proof — restoring the default fails
with *"the default must not name a column at all"*.

## 4. "Worktrees off is INERT" had one unaudited reader

The constraint was that `maxWorktrees` become genuinely inert, "not set
very high and not skipped by convention". `resolveWorktreeCapacityLimit`
returns `null` for that, and its unit tests can only prove the
**resolver** is right — they cannot see a second reader, which is the
only way the constraint breaks.

Audited every `maxWorktrees` read that bounds anything. **Exactly two:**
`scheduler.ts` (the admission gate, via the resolver, single call site,
optional gate snapshot) and `self-healing.ts`'s `enforceWorktreeCap` —
`(settings.maxWorktrees ?? 4) * 2`, a **raw** read.

The second is **not a bug** and is left alone: it bounds worktree
*directories on disk* and only removes *idle* ones. Worktrees still
exist in OFF mode, so that bound must keep applying or idle directories
accumulate unbounded. Recorded consequence: in OFF mode the number still
governs disk retention while gating no admission — an edge you scoped
out. The note says explicitly **not** to unify the two readers: routing
hygiene through the resolver returns `null` in OFF mode and silently
removes the disk bound, which is a leak dressed as a simplification.

New ratchet requires every file bounding on `maxWorktrees` to be named
with a reason, and rejects a **stale** allowlist entry. Proven by
injecting `active >= (settings.maxWorktrees ?? 4)` into
`hybrid-executor.ts`.

---

## Deliberately NOT included

- **My own census script.** #2633 landed the canonical one, and it is
better than mine — an AST classifier *plus* an independent text
classifier with `--compare`, and a baseline that fails on unrecorded
**drops** as well as rises. Mine only caught rises. I deleted mine
rather than ship a second measuring instrument; three copies of "strip
comments" is the drift shape this program keeps paying for, so the
worktree ratchet now imports #2633's `stripComments`.
- **My TaskContextMenu fix.** Superseded, and by a better answer: main's
`isPureIntakeColumn` (intake *without* hold) keeps the merged Planning
column shown and suppresses only a bare Ideas capture, which resolves
the exact hold-lane objection coderabbit raised against my version. I
briefly clobbered that merged work by checking my old file out
wholesale, caught it in the diff, and reverted.

## Verification

`pnpm lint` clean · core + dashboard `tsc` clean · census suite 23/23 ·
worktree ratchet 8/8 · RoutineEditor 49/49 ·
`routes-task-retry-planning-column` 16/16 · `lifecycle-column-census
--strict` exits 0.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---

## Added after review (all four greptile threads were real, and two of
them mattered)

**The routine fix was half a fix.** `routine-runner.ts:515` *and*
`cron-runner.ts:982` both did `column: (step.taskColumn as Column) ||
"triage"` **after** the step is read, so every routine — including ones
saved through the fixed editor — still created tasks into the deleted
column. Both now omit it.

**The advanced steps editor MANUFACTURED the defect.**
`ScheduleStepsEditor.tsx` had three `triage` defaults: the new-step
template (`:64`), the per-step initializer (`:95`), and the select still
offering it (`:344`). So the path I had *not* fixed produced the bug by
default, on fresh data. Template names no column; initializer coerces a
persisted `triage`; `triage` removed from the options; empty submits
`undefined`.

**Four pre-existing tests pinned the defect** and are rewritten to the
corrected invariant rather than appeased:

| test | asserted |
|---|---|
| `cron-runner`: "defaults column to triage when taskColumn is not set"
| `column: "triage"` |
| `ScheduleStepsEditor`: "adds a create-task step..." | `taskColumn`
toBe `"triage"` |
| `ScheduleStepsEditor`: "allows saving create-task step..." | the
legacy column is **resubmitted** |
| plus the explicit-column case added beside each, so the fix cannot
swallow a deliberate choice |

**The allowlist hole was the worst finding.** `AUDITED_BOUNDS` was keyed
by FILE, so every bounding expression in an allowlisted file was exempt
— a second raw bound in `scheduler.ts` stayed green, the one case that
ratchet exists for. Per-expression now, and making it so **immediately
surfaced a real second bound the file-level version was hiding**
(`maxWorktreesGate.used >= maxWorktreesGate.limit`, safe by construction
since the snapshot is `undefined` in OFF mode). Proven by injection.

## Found while re-reading my own deletion, not reported

A **rendered tooltip** still named a deleted cap. The "Queued to plan"
badge read *"planning starts when a concurrency slot frees up
(maxConcurrent / globalMaxConcurrent)"*. The cross-project cap is gone —
capacity is two numbers per project — so it told operators their
planning waited on a limiter they can no longer find a setting for.
Names the surviving dimension only now.

## Coding (Ideas): enforcing #2651 rather than repeating it

I took the unowned coding-ideas IR merge, concluded it must not be done,
then found **#2651 had already implemented, reverted and documented
exactly that** — with better grounding than my own argument. It added no
test, so nothing stops the next person reaching the same dead end.

So this ships their reasoning as a ratchet, not a second opinion: triage
discovery keys on the column's `autoTriage`, so a merged column is
either never scanned (cards sit on a bootstrap stub until the **capacity
hold** releases them, sending **unplanned** work into in-progress —
worse than stalling) or scanning wins and the manual gate is gone. Their
scope caveat is kept: `autoTriage` is a general trait field, so only
*this preset's* collapse is dead, not manual intake as a concept. The
registry does not reject the merged shape, which is why prose was not
enough.

## Verification (re-run)

`pnpm lint` clean · core + engine + dashboard-app `tsc` clean ·
`lifecycle-column-census --strict` exits 0 ("every file matches its
baseline exactly") · routine-runner 24/24 · cron-runner 156/156 ·
ScheduleStepsEditor 41/41 · RoutineEditor 49/49 · worktree +
coding-ideas 12/12. TaskCard has 2 failures **pre-existing on main** —
confirmed identical with my changes stashed.

---

## Bears directly on the closing bar: this PR already removes the
67-guard ratchet slack

Measured on current `origin/main` with the census itself:

```
tree total: 787   baseline total: 854   SLACK: 67

FILES ABOVE BASELINE (1):
   +1  packages/dashboard/src/routes/register-task-workflow-routes.ts  (22 -> 23)

FILES BELOW BASELINE: 13, totalling 68 unrecorded conversions
   -18  core/default-workflow-hooks.ts (25->7)   -15  engine/self-healing.ts (126->111)
    -8  engine/executor.ts (112->104)             -5  core/task-store/moves.ts (44->39)
    -5  engine/mission-feature-sync.ts (5->0)     -4  core/live-agent-count.ts (10->6)
```

**The slack is not regression — it is 13 files of merged conversions
nobody re-recorded**, against exactly **one** rise. This PR re-records
the baseline **854 → 782 across 140 files**, which closes it.

**And the "+3 that slipped in" is +1, and it is mine.**
`register-task-workflow-routes.ts 22 → 23` is the v1-IR pre-WIP fallback
my #2621 added; it is justified (that branch runs only when the IR
declares no columns or nodes, so there is no role to resolve) but it
shipped with no marker and no baseline update — which is why `--strict`
has been **red on main since it merged**. Fixed here at the site with a
`DELIBERATE-LITERAL` marker rather than by bumping the baseline, because
a rise that is genuinely correct belongs where a reader will see it.

Sequencing note for the auto-lowering change: if this lands first, that
work is purely the mechanism (auto-lower, or fail with tighten
instructions) rather than a cleanup, and the two re-records will not
collide in the same file.

Also worth carrying into that mechanism, from building the same guard
here: **`--update` must refuse to RAISE.** An earlier version of mine
wrote current counts verbatim, so a developer who added a literal and
ran the documented update command locked the regression in as the new
ceiling — the mirror of the high-water problem. Lowering can be
unattended; raising should be a hand edit with the reason recorded.

## Third piece of residue from my own deletion

`updateGlobalConcurrency` in the dashboard API client PUT to
`/api/global-concurrency`, a route removed when the machine-wide cap
went. Zero callers; the only reference was the `legacy.ts` barrel
re-export. Deleted both. `fetchGlobalConcurrency` **survives on
purpose** — the GET route remains and serves live utilization telemetry
to the footer and Command Center; nothing gates on it.

That is the third: after the second raw `maxWorktrees` reader and the
"Queued to plan" tooltip. A deletion is not finished when the
enforcement goes — the client, the label and the tooltip outlive it.

---

## Re-greened the dashboard API tests: 117 failures on main, ONE root
cause

These would have polluted the closing verification pass, and nobody
owned them.

`api()` builds headers via `new Headers(...)` and returns
`Object.fromEntries(headers.entries())` — and `Headers.entries()`
**lowercases every key**, so the object reaching `fetch` is
`content-type`, not `Content-Type`. `ab87d0d80` then added
`x-fusion-client: dashboard-ui` for run-audit attribution. Both changes
are correct; neither is visible at a call site, so **114 assertions
across 7 files** kept asserting the old shape and went red together.

Fixed by naming the shape **once** in `app/test/apiRequestHeaders.ts`
rather than patching 114 literals — restating a shared fact 114 times is
what made a two-line client change look like 117 failures. Deliberately
not a loose `objectContaining`: these tests are the only thing pinning
that the attribution header is sent *at all*.

**117 → 4.** The remaining 4 are unrelated pre-existing CSS failures
(`task-detail-modal-tablet-width` ×3, `space-token-defined` ×1) —
confirmed identical on clean main with my changes stashed.

### A gap this surfaced, recorded not papered over

Three routes failed in the *opposite* direction — they send the old
shape because they call `fetch()` **directly**, bypassing `api()`, so
they never get the attribution header. `client.ts` claims the opposite:

> "Applied once here rather than per-call so no future mutation route
has to remember it."

That does not hold for a route that bypasses the helper it is applied
in. **Measured in `app/api/`: 8 files make direct `fetch()` calls and 7
include mutations (POST/DELETE)** — among them `ai-sessions.ts`'s
DELETE, which is the same class as the four-delete incident the header
was added for. So the attribution fix has a hole in exactly its
motivating case.

Not fixed here: routing those onto `api()` is a behaviour change across
the API layer and belongs to its owner, not to a test re-green. Those
assertions use a separate `API_JSON_HEADERS_NO_ATTRIBUTION` constant so
the gap stays **visible** — if a route is later moved onto `api()`, its
test fails and points at the note explaining why.

---

## This branch takes the triage bar 10 → 5, and makes `--strict` green

`node scripts/lifecycle-column-census.mjs` on this branch reports
**triage 5**, against **10** on `origin/main`. The five removed are the
ScheduleStepsEditor template/initializer/option and the RoutineEditor
default/option — the automation paths that were creating tasks into the
deleted column.

**`--strict` was also RED on clean main, twice over, and both causes
were the same mistake:** a thorough written rationale the tool cannot
read, because the marker was not where the census looks. The census
reads a comparison node's **leading comments**; a `DELIBERATE-LITERAL`
in the JSDoc above the enclosing function or declaration does not reach
the comparison inside it.

| site | why it is legitimate | why the tool could not see it |
|---|---|---|
| `columnRoles.ts:80` `isHoldColumnRole` | degrades to `columnId ===
"todo"` only when a column has **no resolved traits** — identical in
kind to `LEGACY_PRE_IMPLEMENTATION_COLUMN_IDS` directly above, which
escapes counting only because a Set is a membership form | rationale
written, **no marker token** |
| `MissionControlPanel.tsx` ×3 | the SDLC funnel **alias table** — maps
`to-do`/`ready`/`review`/`shipped` onto one display stage with an
explicit `other` bucket, and nothing branches on it | marker in the
JSDoc; the comparisons are arrow bodies **inside the array literal**,
which it does not reach |

The second only surfaced because converting the `triage` stage to a Set
removed its count and exposed the siblings — red gate, justification
sitting three lines above, unreachable.

Both are markers, no behaviour change. Neither is a conversion
candidate: resolving the funnel table to traits would **drop the
non-column aliases it exists to accept**.

**For the auto-lowering work:** the marker-placement rule is now the
recurring trap — three instances, three different authors, including me.
A marker that does not register is indistinguishable from no marker, and
the failure mode is a red gate with a written explanation nobody can act
on. If the census accepted a marker anywhere in the enclosing
declaration's comments, none of the three would have happened.

Baseline re-recorded per the tool's own instruction ("Re-record the
baseline in the SAME PR that lowered the count").


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Bug Fixes**
- Task “Actions” menus no longer appear on bare cards in the Planning
column.
- Routines, scheduled tasks, and create-task steps now respect each
board’s configured workflow intake column instead of using a retired
default.
- Legacy tasks saved with the retired intake column are migrated to
automatic workflow resolution.
- Target-column selection now offers only “Automatic (workflow intake)”
and “Planning,” removing the obsolete option.
- Capacity/planning messaging and related UI tooltip text were
clarified; concurrency cap updates are managed per project.

- **Tests**
- Added/updated coverage for workflow intake resolution, create-task
target column behavior (including legacy coercion), capacity safeguards,
and API request consistency.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 03:10:35 -07:00

453 lines
20 KiB
TypeScript

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { AlertCircle, Loader2, Radio } from "lucide-react";
import type { LiveSnapshot, LiveSession, ColumnCount } from "@fusion/core";
import { api, withProjectId } from "../../api/legacy";
import { subscribeSse } from "../../sse-bus";
import { useProjectContextGuard } from "../../hooks/useProjectContextGuard";
import { Funnel, type FunnelStage } from "./charts/Funnel";
import { isInProgressColumn } from "./liveSnapshotMetrics";
import "./MissionControlPanel.css";
/** Poll cadence while work is in-flight (KTD5). */
export const LIVE_POLL_INTERVAL_MS = 5_000;
/**
* A node whose most recent active session was last updated longer ago than this
* is rendered as "inactive" rather than dropped from the list, so a node that
* goes quiet stays visible (greyed) until the next authoritative snapshot
* removes it.
*/
export const NODE_STALE_THRESHOLD_MS = 30_000;
/** SSE events that should trigger an immediate refetch (push half of KTD5). */
const LIVE_REFETCH_EVENTS = [
"session:updated",
"session:completed",
"run:created",
"run:updated",
"run:completed",
"run:cancelled",
"run:failed",
"agent:stateChanged",
"task:moved",
"task:updated",
"task:created",
"task:deleted",
] as const;
/**
* The ordered SDLC funnel stages. Columns are matched case-insensitively against
* these canonical stage ids; any column that does not map to a known stage is
* folded into an "other" bucket so custom workflow columns still contribute a
* count rather than being silently dropped.
*
* FNXC:WorkflowLifecycleColumns 2026-07-30-12:30 DELIBERATE-LITERAL: this is an ALIAS TABLE of
* column NAMES, not a lifecycle guard — `triage` sits beside `signal` and `backlog` as one of
* several names operators give the same funnel stage. Command Center aggregates across
* PROJECTS, so there is no single workflow to resolve traits from here; the honest conversion
* needs per-project trait resolution feeding this panel, which is a data change rather than a
* predicate change. Until then the "other" bucket keeps unrecognised columns counted instead
* of dropped, which is what stops a renamed board from silently reading as empty.
*
* Recorded for the U12 literal ratchet's allowlist; grep DELIBERATE-LITERAL to enumerate.
*/
/*
FNXC:WorkflowLifecycleColumns 2026-07-30-23:15 (U11 — assessed, deliberately NOT trait-converted):
These are heuristic NAME ALIASES for a canonical SDLC funnel stage, not lifecycle
guards. The matcher already accepts several names per stage ("signal", "backlog",
"to-do", "ready", "shipped") precisely because it buckets ARBITRARY boards, and
anything unmatched falls into "other" rather than being dropped.
Post-#2515 a default board's planning cards sit in `todo` and are counted at the TODO
stage, leaving Planning at zero for those boards. That is the funnel reporting where
the cards actually are, not a guard that stopped firing — and it stays useful for
boards that do name a column triage/signal/backlog.
Hoisted to a named set so the aliases read as aliases and stop appearing on the
lifecycle-column census as an unconverted guard. This is the DISPLAY-ALIAS class:
receiver is a column id, purpose is presentation, not a lifecycle decision.
*/
const TRIAGE_STAGE_COLUMN_ALIASES: ReadonlySet<string> = new Set(["triage", "signal", "backlog"]);
/*
FNXC:WorkflowLifecycleColumns 2026-07-30-07:20 (U12 — census gate repair) DELIBERATE-LITERAL:
The marker above was ATTACHED TO THE WRONG NODE and therefore did nothing.
`hasDeliberateMarker` walks a node's leading comments and its ancestors. The existing
DELIBERATE-LITERAL block sits above `TRIAGE_STAGE_COLUMN_ALIASES`, which is declared between it and
this table — so the comments attach to the Set, and the stage matchers below were counted as
unconverted backlog. That is why `--strict` reported `MissionControlPanel.tsx: 0 -> 3` on pristine
main and turned the blocking PR gate red for every open PR.
The assessment in that block is unchanged and still correct: these are heuristic NAME ALIASES for a
canonical SDLC funnel stage, not lifecycle guards. The matcher deliberately accepts several names per
stage ("signal", "backlog", "to-do", "ready", "shipped") because it buckets ARBITRARY boards, and
anything unmatched falls to "other" rather than being dropped. Resolving them to traits would ask
"which column has the intake trait" of a thing that is not a column at all.
Placed directly on the declaration so it cannot be orphaned again by a future insertion.
*/
const FUNNEL_STAGES: Array<{ id: string; match: (column: string) => boolean }> = [
{ id: "triage", match: (c) => TRIAGE_STAGE_COLUMN_ALIASES.has(c) },
/*
FNXC:WorkflowLifecycleColumns 2026-07-31-01:20 DELIBERATE-LITERAL:
Markers, not a behaviour change. The JSDoc above already explains why this whole table is an ALIAS
TABLE rather than a lifecycle decision — it maps several vocabularies (`to-do`, `ready`, `review`,
`shipped`, ...) onto one DISPLAY stage, with an explicit `other` bucket for anything unrecognised, and
nothing branches on the result. Resolving these to traits would DROP the non-column aliases the table
exists to accept.
The marker is repeated per stage because the census reads a comparison node's LEADING comments: a
marker in the JSDoc above the declaration does not reach the arrow bodies inside the array. When the
`triage` stage was converted to a Set its count vanished and these three surfaced, turning `--strict`
red with the rationale already written three lines up but unreachable by the tool.
*/
{ id: "todo", match: (c) => c === "todo" || c === "to-do" || c === "to do" || c === "ready" },
{ id: "in-progress", match: isInProgressColumn },
/* DELIBERATE-LITERAL: display alias, see the note above. */
{ id: "in-review", match: (c) => c === "in-review" || c === "in review" || c === "review" },
/* DELIBERATE-LITERAL: display alias, see the note above. */
{ id: "done", match: (c) => c === "done" || c === "complete" || c === "completed" || c === "shipped" },
];
interface NodeView {
path: string;
label: string;
sessionCount: number;
inactive: boolean;
}
export interface LiveSnapshotState {
snapshot: LiveSnapshot | null;
isLoading: boolean;
/** Non-null only for a hard error with no prior snapshot to fall back on. */
error: string | null;
/** True while a poll interval is scheduled (work in-flight). Exposed for tests. */
polling: boolean;
reload: () => void;
}
/**
* Live snapshot hook implementing the push + poll convergence pattern (KTD5):
*
* - **Push:** subscribes to the shared SSE bus and refetches immediately on any
* session/run/task event — so a change lands within one event, not one poll.
* - **Poll:** schedules a 5s interval as a fallback, but **only while work is
* in-flight** (any active session or run). When the latest snapshot shows no
* active work, the interval is cleared and no new one is scheduled — so an idle
* panel does no background polling. The SSE subscription stays live so the next
* started session pushes in and re-arms polling.
*
* The decision to poll is derived from the freshest snapshot (kept in a ref so the
* interval callback always sees current state), re-evaluated after every fetch.
*/
export function useLiveSnapshot(projectId?: string): LiveSnapshotState {
const [snapshot, setSnapshot] = useState<LiveSnapshot | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [polling, setPolling] = useState(false);
const snapshotRef = useRef<LiveSnapshot | null>(null);
const pollTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const noRequest = useRef(Symbol("no-live-snapshot-request"));
const inFlightProjectRef = useRef<string | undefined | symbol>(noRequest.current);
const { capture } = useProjectContextGuard(projectId, "useLiveSnapshot");
// Stable callbacks below close over only refs + setState, so `load` (and the
// SSE subscription / poll interval that call it) never need to be recreated.
const stopPolling = useCallback(() => {
if (pollTimerRef.current !== null) {
clearInterval(pollTimerRef.current);
pollTimerRef.current = null;
setPolling(false);
}
}, []);
const load = useCallback(async () => {
const context = capture();
const requestProjectId = context.projectIdAtStart;
// Coalesce only same-project fetches. A project switch must start its own
// request rather than waiting for a prior project's response.
if (inFlightProjectRef.current === requestProjectId) return;
inFlightProjectRef.current = requestProjectId;
try {
const result = await api<LiveSnapshot>(withProjectId("/command-center/live", requestProjectId));
if (context.isStale()) return;
snapshotRef.current = result;
setSnapshot(result);
setError(null);
} catch (loadError: unknown) {
if (context.isStale()) return;
setError(loadError instanceof Error ? loadError.message : "Failed to load live snapshot");
} finally {
if (inFlightProjectRef.current === requestProjectId) {
inFlightProjectRef.current = noRequest.current;
}
if (!context.isStale()) {
setIsLoading(false);
// Re-evaluate polling against the freshest snapshot after every fetch.
// "In-flight" = any active session or run. Idle → no interval exists.
const snap = snapshotRef.current;
/*
FNXC:MobileTabRetention 2026-07-26-11:40:
The live-snapshot poll is self-managed (it re-arms itself from each response), so the visibility gate
lives here rather than in `useVisibilityAwarePoll`: a hidden document must never re-arm the timer.
A backgrounded page that keeps fetching is a primary iOS/Chrome Android discard signal, and the
discard is the white-splash reload operators saw on return. The visibilitychange handler below calls
`load()` on the hidden -> visible edge, which refreshes once and re-arms polling if work is live.
*/
const documentVisible = typeof document === "undefined" || document.visibilityState !== "hidden";
const inFlight = documentVisible && !!snap && (snap.activeSessions > 0 || snap.activeRuns > 0);
if (inFlight) {
// Start the poll interval iff one is not already running.
if (pollTimerRef.current === null) {
pollTimerRef.current = setInterval(() => {
void load();
}, LIVE_POLL_INTERVAL_MS);
setPolling(true);
}
} else {
stopPolling();
}
}
}
}, [capture, stopPolling]);
useEffect(() => {
/*
FNXC:LiveActivity 2026-07-20-09:30:
FN-8429 requires a project-scoped live strip. Clear the prior snapshot on a
project switch and reject stale responses so another project's board counts
cannot briefly inflate Overview or Mission Control.
*/
snapshotRef.current = null;
setSnapshot(null);
setIsLoading(true);
setError(null);
void load();
const unsubscribe = subscribeSse("/api/events", {
events: Object.fromEntries(
LIVE_REFETCH_EVENTS.map((name) => [name, () => void load()]),
),
// On reconnect we may have missed events while the stream was down —
// refetch authoritative state.
onReconnect: () => void load(),
});
const handleVisibilityChange = () => {
if (document.visibilityState === "hidden") {
stopPolling();
return;
}
void load();
};
if (typeof document !== "undefined") {
document.addEventListener("visibilitychange", handleVisibilityChange);
}
return () => {
if (typeof document !== "undefined") {
document.removeEventListener("visibilitychange", handleVisibilityChange);
}
unsubscribe();
stopPolling();
};
}, [load, projectId, stopPolling]);
const reload = useCallback(() => {
void load();
}, [load]);
return {
snapshot,
isLoading,
error: error !== null && snapshot === null ? error : null,
polling,
reload,
};
}
function nodeLabelFromPath(path: string): string {
const parts = path.split(/[/\\]/).filter(Boolean);
return parts.length > 0 ? parts[parts.length - 1] : path;
}
/** Derive per-node views, marking nodes whose sessions are all stale as inactive. */
function deriveNodes(sessions: LiveSession[], capturedAt: string): NodeView[] {
const capturedMs = Date.parse(capturedAt);
const byPath = new Map<string, { count: number; freshestMs: number }>();
for (const s of sessions) {
if (!s.worktreePath) continue;
const prev = byPath.get(s.worktreePath) ?? { count: 0, freshestMs: 0 };
const ms = Date.parse(s.updatedAt);
byPath.set(s.worktreePath, {
count: prev.count + 1,
freshestMs: Number.isFinite(ms) ? Math.max(prev.freshestMs, ms) : prev.freshestMs,
});
}
return Array.from(byPath.entries())
.map(([path, info]) => {
const age = Number.isFinite(capturedMs) && info.freshestMs > 0 ? capturedMs - info.freshestMs : 0;
return {
path,
label: nodeLabelFromPath(path),
sessionCount: info.count,
inactive: age > NODE_STALE_THRESHOLD_MS,
};
})
.sort((a, b) => b.sessionCount - a.sessionCount);
}
/** Map raw column counts onto the ordered SDLC funnel stages. */
function deriveFunnelStages(columns: ColumnCount[], label: (id: string, fallback: string) => string): FunnelStage[] {
const totals = new Map<string, number>();
for (const stage of FUNNEL_STAGES) totals.set(stage.id, 0);
let other = 0;
for (const c of columns) {
const normalized = c.column.trim().toLowerCase();
const stage = FUNNEL_STAGES.find((s) => s.match(normalized));
if (stage) {
totals.set(stage.id, (totals.get(stage.id) ?? 0) + c.count);
} else {
other += c.count;
}
}
const stages: FunnelStage[] = FUNNEL_STAGES.map((s) => ({
label: label(`commandCenter.missionControl.stage.${s.id}`, s.id),
value: totals.get(s.id) ?? 0,
}));
if (other > 0) {
stages.push({ label: label("commandCenter.missionControl.stage.other", "Other"), value: other });
}
return stages;
}
/**
* Live Mission-Control panel (U6b). Renders the live snapshot from
* `GET /api/command-center/live` with push + poll convergence (KTD5): SSE events
* trigger an immediate refetch, and a 5s poll runs only while work is in-flight.
*/
export function MissionControlPanel({ projectId }: { projectId?: string } = {}) {
const { t } = useTranslation("app");
const { snapshot, isLoading, error } = useLiveSnapshot(projectId);
const sessions = useMemo(() => snapshot?.sessions ?? [], [snapshot?.sessions]);
const nodes = useMemo(
() => (snapshot ? deriveNodes(snapshot.sessions, snapshot.capturedAt) : []),
[snapshot],
);
const stages = useMemo(
() => (snapshot ? deriveFunnelStages(snapshot.columns, t) : []),
[snapshot, t],
);
if (isLoading && !snapshot) {
return (
<div className="cc-loading-inline" data-testid="mission-control-loading">
<Loader2 size={18} className="spin" />
<span>{t("commandCenter.missionControl.loading", "Loading live activity…")}</span>
</div>
);
}
if (error !== null) {
return (
<div className="cc-area-error" data-testid="mission-control-error" role="alert">
<AlertCircle size={22} />
<p>{error}</p>
</div>
);
}
const hasActivity = (snapshot?.activeSessions ?? 0) > 0 || (snapshot?.activeRuns ?? 0) > 0;
return (
<div className="cc-mission-control" data-testid="mission-control">
<div className="cc-stat-grid" data-testid="mission-control-summary">
<div className="card cc-stat-card" data-testid="mission-control-active-sessions">
<div className="cc-stat-label">{t("commandCenter.missionControl.activeSessions", "Active sessions")}</div>
<div className="cc-stat-value">{snapshot?.activeSessions ?? 0}</div>
</div>
<div className="card cc-stat-card" data-testid="mission-control-active-runs">
<div className="cc-stat-label">{t("commandCenter.missionControl.activeRuns", "Active runs")}</div>
<div className="cc-stat-value">{snapshot?.activeRuns ?? 0}</div>
</div>
<div className="card cc-stat-card" data-testid="mission-control-active-nodes">
<div className="cc-stat-label">{t("commandCenter.missionControl.activeNodes", "Active nodes")}</div>
<div className="cc-stat-value">{snapshot?.activeNodes ?? 0}</div>
</div>
</div>
{!hasActivity ? (
<div className="cc-area-empty" data-testid="mission-control-idle">
<Radio size={24} />
<p>{t("commandCenter.missionControl.idle", "No active sessions. Live updates resume when work starts.")}</p>
</div>
) : null}
<div className="cc-mc-columns">
<section className="cc-mc-section" data-testid="mission-control-sessions">
<h3 className="cc-area-section-title">{t("commandCenter.missionControl.sessionsTitle", "Sessions")}</h3>
{sessions.length === 0 ? (
<p className="cc-mc-muted" data-testid="mission-control-sessions-empty">
{t("commandCenter.missionControl.noSessions", "No active sessions.")}
</p>
) : (
<ul className="cc-mc-list">
{sessions.map((s) => (
<li key={s.id} className="cc-mc-session" data-testid={`mission-control-session-${s.id}`}>
<span className="cc-mc-session-purpose">{s.purpose || s.adapterId}</span>
<span className="cc-mc-session-meta">
<span className="cc-mc-badge">{s.agentState}</span>
{s.taskId ? <span className="cc-mc-task">{s.taskId}</span> : null}
</span>
</li>
))}
</ul>
)}
</section>
<section className="cc-mc-section" data-testid="mission-control-nodes">
<h3 className="cc-area-section-title">{t("commandCenter.missionControl.nodesTitle", "Nodes")}</h3>
{nodes.length === 0 ? (
<p className="cc-mc-muted" data-testid="mission-control-nodes-empty">
{t("commandCenter.missionControl.noNodes", "No active nodes.")}
</p>
) : (
<ul className="cc-mc-list">
{nodes.map((n) => (
<li
key={n.path}
className={`cc-mc-node${n.inactive ? " inactive" : ""}`}
data-testid={`mission-control-node-${n.label}`}
data-inactive={n.inactive ? "true" : "false"}
>
<span className="cc-mc-node-label">{n.label}</span>
<span className="cc-mc-node-meta">
{n.inactive ? (
<span className="cc-mc-badge inactive">
{t("commandCenter.missionControl.inactive", "inactive")}
</span>
) : null}
<span className="cc-mc-node-count">
{t("commandCenter.missionControl.sessionCount", "{{count}} session", { count: n.sessionCount })}
</span>
</span>
</li>
))}
</ul>
)}
</section>
</div>
<section className="cc-mc-section" data-testid="mission-control-funnel">
<h3 className="cc-area-section-title">{t("commandCenter.missionControl.funnelTitle", "SDLC funnel (live)")}</h3>
<Funnel stages={stages} ariaLabel={t("commandCenter.missionControl.funnelTitle", "SDLC funnel (live)")} />
</section>
</div>
);
}