mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 14:47:44 +01:00
* refactor(shell): organise navigation around the operator loop, and give the header an account menu The sidebar carried 27 destinations in four sections, one of which was named "More" and held Approvals, Terminal, Prompts, Activity, System, Thoughts and the PUBLIC /fleet register — seven pages whose only shared property was that nobody had decided where they went. Alongside them sat a "Site" section: Mission, Philosophy, Roadmap, Whitepaper and Investors, in the signed-in app navigation. Loki is an operator console. Its surface answers three questions, so the sidebar now has exactly three sections and each one states its question: Now — what needs me? Today, Approvals, Feedback Fleet — what is my fleet doing? Control, Projects, Activity, System Command — how do I act on it? Loki, Terminal, Prompts Private stays PIN-gated below them. The marketing pages left the signed-in shell and stay reachable through Cmd-K, which now indexes NAV directly rather than whatever happens to be in the sidebar — curating the sidebar must never make a page unfindable. Alongside that, identity: - There was no way to sign out from the header, and nothing anywhere in the top bar said who was signed in. A grep of components/shell/ for "avatar", "UserMenu" or "ProfileMenu" returned nothing. Sign out, Settings and the private-zone lock lived in the sidebar footer, which is `hidden md:flex`, and were duplicated in the mobile Menu sheet's footer: two account menus, neither called one, and none where users look first. - AccountMenu now owns all of it, in the top bar, on every viewport. - The theme toggle moved inside it. It was the only control in the top bar drawn with a border and a fill (ui-theme-cycle-btn) while every signal beside it was a bare ghost circle (ui-topbar-btn) — a preference outweighing every piece of live state on the page. - SidebarFooter is deleted. Its collapse button was marked `md:hidden` inside a panel marked `hidden md:flex`, so it could never render on any viewport; SidebarBrand has always owned the working toggle. Two retired NAV entries are deleted rather than hidden: `agents` → /control and `atlas` → /projects pointed at the pages that replaced them, and since NAV_ITEMS is what AppTopBar and PageTitle scan for "which page am I on?", the first match won — /control would have been titled "Agents". Their redirect pages reference the targets, so the redirects stay honest. scripts/test/navigation.ts is rewritten to defend the new structure: every section must state its question, "more"/"misc"/"tools"/"site" are rejected by name, account items may not appear in the sidebar, marketing items may not, no two items may share an href, and the bottom bar must carry one entry point per loop section. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0159PhgGrn6ccwfwVTJoTuYx * fix(control): stop the hero claiming "Idle" over a queue of six things Observed on prod: the Control hero read "Idle — nothing queued" while a panel titled "Needs you", badged 6, sat roughly a screen and a half below it, under a 23-project list. One page, one question — is anything waiting on me? — and two answers, with the confident wrong one on top. Two distinct faults, fixed together because either alone leaves the page contradicting itself. 1. The hero could not see the queue. deriveFleetPulse read agents, run outcomes and projects awaiting input, and nothing else, so the one queue on the page that literally counts things waiting on the operator was invisible to the headline that summarises them. It now takes `inbox` and ranks it last among the states that say something is up — a stall, a failure, a half-finished run and a blocked project all still outrank chores — but comfortably above "Idle". `unknown` is a separate state from `count: 0` on purpose. A queue we failed to read is not a queue we know to be empty; ControlInbox already refused to render silence as the answer "no", and the hero now refuses too. The count could not be lifted while it lived inside the panel rendering it, so the fetches moved to `useControlInbox`, called once in ControlPanel and passed down. One read, two consumers, one truth. It also removes a third copy of the /api/feedback/summary request from the page. 2. The panel was filed in the wrong tier. ControlPanel's own ordering rule says tiers 1-2 are about a human being blocked and "reporting never renders above blocking" — and a queue titled "Needs you" with a count badge is the definition of tier 2. It sat in tier 4. It now sits with AttentionBar and AgentEscalations, which it can afford because of how it was built: one line per group until opened, nothing auto-expanding, and nothing at all rendered when the queue is empty. Two rows above the fleet, not the ~1,400px of unbounded strips it replaced. The `inbox` state takes the warning dot rather than neutral grey, for the reason the `partial` state already does: grey beside the words "Waiting on you" is the page agreeing with itself in tone while disagreeing in substance. `unknown` stays neutral — that one really is "no idea". Four tests pin it: a non-empty queue is never Idle, an empty one still is, an unreadable one is not a claim of emptiness, and real trouble still outranks chores. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0159PhgGrn6ccwfwVTJoTuYx * fix(design): un-invert the dark text ramp, and make token drift a build failure @bitbaum/design-tokens calls itself "the design single source of truth for OrangeCat, Loki and Solon". Solon proves it — its globals.css is 19 lines and imports the package. Loki's is ~5,800 and declares its own ramp, with the package present only as a devDependency used to generate the widget theme. A comment here said the quiet part out loud: "Loki still declares its ramp locally, so the value is kept in step by hand." Nothing was keeping it in step. Measured: Loki and the package disagree on 32 of the 36 tokens they both define, and the disagreement has a shape — someone transcribed the DIGITS between colour spaces without converting them. `--text-secondary` is `oklch(0.4 0 0)` here and `0 0% 40%` there; those are 30 of 255 apart. light: surfaces agree within 5/255; the TEXT ramp is 20-30 apart dark: text agrees within 7/255; the SURFACE ramp is 17-30 apart (Loki's ground is #010101, the fleet's is #121212) Comparing them exposed a real bug, which this commit fixes. Loki's documented ramp is primary → secondary → tertiary → muted, each quieter than the last. The light block follows it (0.1 → 0.4 → 0.58 → 0.72). The DARK block was written in the order primary/secondary/muted/tertiary with values descending in THAT order — so `--text-muted` sat at 0.65 while `--text-tertiary` sat at 0.59, and text marked muted rendered BRIGHTER than text marked tertiary. The two quietest tiers in the system, inverted, on the theme that is the default. The two values are swapped rather than retuned, so no new colour enters the system and the contrast range is unchanged. The rest is a gate, not a migration. Some of the divergence is deliberate: Loki is an operator console that sits beside a terminal, its near-black ground is a product decision, its borders are translucent overlays rather than opaque greys, and its typeface is Geist where the fleet's is Inter + Instrument Serif. Adopting the package wholesale would restyle every surface and every glyph of a running product in one unreviewable step. So scripts/test/token-drift.ts requires every difference to be DECLARED. A divergence listed in DIVERGENCES is a decision somebody signed; one that is not listed fails the build. Tokens that currently agree are pinned, so agreement cannot quietly lapse. It also asserts the text ramp descends in both themes, and complains if a token listed as divergent has since converged — which is how the list shrinks, one reviewable token at a time. It is picked up automatically by scripts/test-unit.ts (which globs scripts/test/*.ts), so it runs in `verify` and in CI without further wiring. Verified to bite: re-introducing the ramp inversion and silently retuning a pinned token each exit 1. Docs corrected to match the shell as it now is: CLAUDE.md claimed ThemeToggle ships in 8 places and described a "Today/Control/Projects + Loki + More" mobile nav; responsive-design.md described sidebar sections "Work / Private / Site" with account actions in two different footers. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0159PhgGrn6ccwfwVTJoTuYx * refactor(shell): stop two navigation surfaces answering a question already answered Loki ran six navigation surfaces at once — sidebar, top bar, the Profile/Chat/Control/Terminal strip, the mobile bottom bar, the Menu sheet and the command palette. On a phone at /control, four were on screen together and three were answering "where am I?". Two of them now stand down where they add nothing. FleetSurfaceGuide renders only with an active project. Its whole claim is that the four tabs are views of ONE project and that moving between them preserves it — but `fleetSurfaceHref(surface, null)` falls back to /projects, /loki, /control and /terminal, which are four sidebar entries. So with no project it was rendering the sidebar a second time, above every Control, Terminal and Projects page, preserving nothing. A navigation surface that carries no information the others lack is not a shortcut; it is a fifth nav system charging rent. AppTopBar drops its mobile page label on pages the bottom bar already names. Below md the bar shows Today / Loki / Control as labelled, highlighted tabs, so on those three the top bar's title was the third simultaneous answer after the bottom tab and the page's own heading. It still speaks on all 15 other destinations, where the bottom bar can only show "Menu" and genuinely cannot say. scripts/test/nav-surfaces.ts pins both, and pins them against the config rather than against a screenshot: it derives the projectless hrefs from fleetSurfaceHref and asserts each is a real sidebar destination (the premise the first fix rests on), checks every tab carries the project when there is one, and checks the label suppression uses the same isCurrentPath the bottom bar does — otherwise it would silently never fire. It also holds the Menu sheet to having no account footer, now that AccountMenu owns those actions. Verified to bite: reverting the strip gate fails the suite. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0159PhgGrn6ccwfwVTJoTuYx * fix(ci): pre-push ran the wrong suite for scripts/test/ The hook classifies changed paths into three arms and runs the gates each one can break. `scripts/test/` was in the `_ops` arm, and that was backwards in both directions at once: • test:ops runs `scripts/hetzner/test-*.sh` and nothing else — verified: all 18 scripts it invokes are under scripts/hetzner/. No file under scripts/test/ can affect its result, so editing a unit test ran eighteen Hetzner shell suites for nothing. • scripts/test/ holds the 218 .ts files that ARE the unit suite (scripts/test-unit.ts globs the directory). The unit suite runs in the `_app` arm, which scripts/test/ did not trigger. So a broken unit test added under scripts/test/ passed pre-push: the hook never ran the suite that file is a member of. Now: `scripts/test/*.ts` → `_app` (tsc, lint, design, desktop, test:unit, test:home). `scripts/test/*gate.sh` → `_register`, the arm that actually runs the deploy-ref / not-behind / client-ledger / deploy-ready gates; they had no arm that ran them before either. `_ops` keeps hetzner and site-template. scripts/test/pre-push-routing.ts pins it by deriving both sides rather than restating them: it parses the hook's own `touches '<regex>' && _arm=1` lines, reads the scripts test:ops actually invokes out of package.json, and asserts each path reaches the arm that covers it. The failure mode this guards is invisible — a gate running the wrong suite still prints a wall of green. Disclosure, because it matters for how this commit is read: this also unblocks pushing this branch. test:ops fails 4 of 92 checks in a container running as root (the .env-repair cases assert file ownership against a systemd unit's User=), and that is not caused by this branch — confirmed by running it on a clean worktree of origin/main, where it fails identically, 88 passed / 4 failed. The routing above is a defect on its own merits and the fix is the same one either way; the side effect is stated rather than left to be noticed. Those 4 ops failures remain, unaddressed by this branch, on main. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0159PhgGrn6ccwfwVTJoTuYx * chore(design): ratchet the dead ui-* rules in globals.css check-loki-classes.mjs holds `ui-loki-*` to zero in both directions — a class used but undefined, and a class defined but unused. The other ~1,000 `ui-*` rules had never been checked at all, and 35 of them are referenced by nothing. That matters more here than in most codebases. This repo's Layer 3 contract is that every recurring visual pattern gets a named class, so the class IS the decision. Someone looking for "how do we draw a metric card" finds .ui-control-metric-card, -value, -label and .ui-control-metrics-grid sitting in globals.css and reasonably concludes that is the house style. Nothing has used them in months. Dead CSS in a system built on that premise does not read as dead; it reads as load-bearing, and the next person builds to match it. It is a ratchet, not a hard zero, for the reason the dead-exports ratchet already is one: 35 rules is real work to remove safely, and a check that fails on day one is a check that gets switched off on day two. The number may not rise, and each deletion lowers it for good — the script fails in BOTH directions, so cleaning up without lowering the baseline is also an error and the gained ground cannot be given back. Dynamic class names are honoured: `ui-dot-${kind}` appears in source as the literal `ui-dot-`, so a token ending in a hyphen marks every matching rule used. Without that the check reports ~77 false orphans, which is how a lint earns being ignored. Eight such prefixes are in play. Also deletes .ui-mobile-nav-sheet-footer, which the previous commit orphaned when the Menu sheet's account footer moved into AccountMenu. Verified in both directions: adding an unreferenced rule fails with "rose to 36", and deleting a genuinely dead one fails with "fell to 34 — lower the baseline". The first attempt at that second test was itself wrong and is worth recording: deleting `.ui-btn-pill {` changed nothing, because the class is also targeted by a compound selector 2,500 lines further down. The checker was right and the test was wrong — which is exactly the sort of thing a rule counted by hand gets wrong. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0159PhgGrn6ccwfwVTJoTuYx --------- Co-authored-by: Claude <noreply@anthropic.com>
1082 lines
41 KiB
TypeScript
1082 lines
41 KiB
TypeScript
/**
|
|
* Inline self-tests for control-presenter live tab mapping.
|
|
* Run: npm run test:control-presenter
|
|
*/
|
|
import {
|
|
buildControlPageState,
|
|
buildLiveTabRows,
|
|
buildProjectOperationsSnapshot,
|
|
buildProjectOperationsSnapshots,
|
|
deriveFleetPulse,
|
|
deriveRunnerPresence,
|
|
findProjectForOpenTab,
|
|
formatAgentRuntimeLabel,
|
|
inferAgentLabelFromTabName,
|
|
getProjectDisplayState,
|
|
isProjectTabOpen,
|
|
isCurrentPromptStale,
|
|
} from "@/components/control/control-presenter";
|
|
// From lib/, NOT db/queries — importing the query module would pull in the
|
|
// database connection and fail this suite at import time with no DATABASE_URL.
|
|
import { bucketTurnsByProject } from "@/lib/agent-turns";
|
|
import type { ProjectState } from "@/lib/control-types";
|
|
|
|
function stubProject(overrides: Partial<ProjectState> & Pick<ProjectState, "tab">): ProjectState {
|
|
return {
|
|
id: "1",
|
|
projectId: null,
|
|
liveTab: overrides.tab,
|
|
dir: "/tmp/proj",
|
|
agentPref: "claude",
|
|
modelPref: null,
|
|
session: null,
|
|
git: null,
|
|
sessionLifecycleSignals: true,
|
|
agentRunning: false,
|
|
verifiedRunActive: false,
|
|
activeAgents: [],
|
|
profile: null,
|
|
currentPrompt: null,
|
|
readyAt: null,
|
|
lockAt: null,
|
|
closingAt: null,
|
|
closedAt: null,
|
|
recentCustomPrompts: [],
|
|
recentActivity: [],
|
|
recentOutcomes: [],
|
|
liveAgentTurns: null,
|
|
latestOrchestrationRun: null,
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
/** An agent that reported a turn start `minutesAgo` and no end. */
|
|
function openTurn(minutesAgo: number, count = 1) {
|
|
return {
|
|
count,
|
|
startedAt: new Date(Date.now() - minutesAgo * 60_000).toISOString(),
|
|
cwds: ["/tmp/proj"],
|
|
};
|
|
}
|
|
|
|
function assert(condition: boolean, message: string): void {
|
|
if (!condition) throw new Error(message);
|
|
}
|
|
|
|
function runTests(): void {
|
|
let passed = 0;
|
|
const check = (label: string, fn: () => void) => {
|
|
fn();
|
|
passed += 1;
|
|
console.log(` ✓ ${label}`);
|
|
};
|
|
|
|
check("findProjectForOpenTab exact match", () => {
|
|
const projects = [stubProject({ tab: "Loki", liveTab: "Loki" })];
|
|
assert(findProjectForOpenTab("Loki", projects)?.tab === "Loki", "expected Loki");
|
|
});
|
|
|
|
check("findProjectForOpenTab prefix match (agent suffix tab)", () => {
|
|
const projects = [stubProject({ tab: "Loki", liveTab: "Loki Claude" })];
|
|
assert(findProjectForOpenTab("Loki Claude", projects)?.tab === "Loki", "expected prefix match");
|
|
});
|
|
|
|
check("isProjectTabOpen accepts agent-suffixed live tabs", () => {
|
|
const project = stubProject({ tab: "Loki", liveTab: "Loki" });
|
|
assert(isProjectTabOpen(project, ["Loki Claude"]), "expected suffix tab to count as open");
|
|
assert(!isProjectTabOpen(project, ["Cockpit2 Claude"]), "must not match unrelated prefixes");
|
|
});
|
|
|
|
check("isProjectTabOpen accepts a different live agent suffix than cached liveTab", () => {
|
|
const project = stubProject({ tab: "Loki", liveTab: "Loki Claude" });
|
|
assert(
|
|
isProjectTabOpen(project, ["Loki Codex"]),
|
|
"expected canonical project suffix to count as open",
|
|
);
|
|
});
|
|
|
|
check("buildLiveTabRows sorts Working before Open and drops unregistered tabs", () => {
|
|
// 2026-05-31: unregistered ("Tab #1 Unlinked") tabs are filtered out
|
|
// of the default rows — they were visible noise that mapped to no
|
|
// project. Test asserts the new filter behavior.
|
|
const nowS = 1_700_000_000;
|
|
const projects = [
|
|
stubProject({
|
|
tab: "IdleProj",
|
|
liveTab: "IdleProj",
|
|
agentRunning: false,
|
|
}),
|
|
stubProject({
|
|
tab: "Active",
|
|
liveTab: "Active",
|
|
agentRunning: true,
|
|
currentPrompt: { key: "k", label: "Fix tests", startedAt: nowS - 10 },
|
|
activeAgents: ["claude"],
|
|
}),
|
|
];
|
|
const rows = buildLiveTabRows(["Active", "IdleProj", "Mystery"], projects, nowS);
|
|
assert(
|
|
rows.length === 2,
|
|
`expected 2 rows (Mystery dropped as unregistered), got ${rows.length}`,
|
|
);
|
|
assert(rows[0]?.tabName === "Active", "working tab first");
|
|
assert(rows[0]?.stateLabel === "Working", "working state");
|
|
assert(rows[1]?.tabName === "IdleProj", "registered idle tab second");
|
|
assert(
|
|
rows.every((r) => r.registered === true),
|
|
"no unregistered tabs in output",
|
|
);
|
|
});
|
|
|
|
check("formatAgentRuntimeLabel maps cursor agent id", () => {
|
|
const label = formatAgentRuntimeLabel(
|
|
stubProject({
|
|
tab: "X",
|
|
activeAgents: ["cursor"],
|
|
}),
|
|
);
|
|
assert(label === "Cursor", `expected Cursor, got ${label}`);
|
|
});
|
|
|
|
check("formatAgentRuntimeLabel maps legacy agent basename", () => {
|
|
const label = formatAgentRuntimeLabel(
|
|
stubProject({
|
|
tab: "X",
|
|
activeAgents: ["agent"],
|
|
}),
|
|
);
|
|
assert(label === "Cursor", `expected Cursor, got ${label}`);
|
|
});
|
|
|
|
check("inferAgentLabelFromTabName reads common agent suffixes", () => {
|
|
assert(inferAgentLabelFromTabName("Loki Codex") === "Codex", "expected Codex suffix");
|
|
assert(inferAgentLabelFromTabName("ops-grok") === "Grok", "expected Grok suffix");
|
|
assert(inferAgentLabelFromTabName("scratch") === null, "expected no inferred agent");
|
|
});
|
|
|
|
check("unknown runner state suppresses cached working and ready signals", () => {
|
|
const nowS = 1_700_000_000;
|
|
const project = stubProject({
|
|
tab: "Disconnected",
|
|
agentRunning: true,
|
|
currentPrompt: { key: "custom", label: "Never delivered", startedAt: nowS - 10 },
|
|
readyAt: nowS - 10,
|
|
activeAgents: ["claude"],
|
|
});
|
|
const state = getProjectDisplayState(project, ["Disconnected"], nowS, false, false);
|
|
assert(state.stateLabel === "Offline", "disconnected card must say Offline");
|
|
assert(
|
|
!state.isRunning && !state.isReady && !state.tabOpen,
|
|
"stale live signals must be hidden",
|
|
);
|
|
});
|
|
|
|
check("no detected process is reported as not running, not inferred activity", () => {
|
|
const project = stubProject({ tab: "Loki" });
|
|
const state = getProjectDisplayState(project, [], 1_700_000_000);
|
|
assert(
|
|
state.stateLabel === "Not running",
|
|
"inactive project must describe the absent live signal",
|
|
);
|
|
});
|
|
|
|
check("snapshot separates saved context from current operational state", () => {
|
|
const nowS = 1_700_000_000;
|
|
const snapshot = buildProjectOperationsSnapshot(
|
|
stubProject({
|
|
tab: "Loki",
|
|
session: {
|
|
done: "Done earlier",
|
|
next: "Continue later",
|
|
tests: "",
|
|
todos: "",
|
|
health: "",
|
|
mtime: (nowS - 300) * 1000,
|
|
},
|
|
}),
|
|
[],
|
|
nowS,
|
|
);
|
|
assert(snapshot.phase === "not_running", "handoff must not imply a running agent");
|
|
// Names the SIGNAL, like its "Last run" / "Last dispatch" siblings — "Idle"
|
|
// described a state while the other two named their evidence.
|
|
assert(
|
|
snapshot.evidenceLabel === "Last handoff",
|
|
`handoff evidence must name the handoff, got '${snapshot.evidenceLabel}'`,
|
|
);
|
|
assert(snapshot.evidenceKind === "historical", "handoff provenance must be historical");
|
|
});
|
|
|
|
check("a recent dispatch beats 'Not running' — work happens in tabs Loki can't see", () => {
|
|
// The user runs 5-10 parallel sessions in kitty with unnamed tabs, so
|
|
// live process detection sees nothing — yet hook-captured dispatches
|
|
// prove the project was worked on. "Not running" contradicted the
|
|
// recorded facts on the same card (loki, 2026-08-13).
|
|
const nowS = 1_700_000_000;
|
|
const state = getProjectDisplayState(
|
|
stubProject({
|
|
tab: "loki",
|
|
recentActivity: [
|
|
{
|
|
id: "d1",
|
|
projectKey: "loki",
|
|
at: new Date((nowS - 2_640) * 1000).toISOString(),
|
|
kind: "dispatch",
|
|
source: "user",
|
|
adapter: "claude",
|
|
intent: "custom",
|
|
title: "keep going",
|
|
detail: null,
|
|
status: "neutral",
|
|
},
|
|
],
|
|
}),
|
|
[],
|
|
nowS,
|
|
);
|
|
assert(
|
|
state.stateKey === "recently_active",
|
|
`recent dispatch must not read as dead, got '${state.stateKey}'`,
|
|
);
|
|
assert(state.stateLabel === "Active recently", "badge names the honest state");
|
|
});
|
|
|
|
check("an old dispatch does NOT keep a project looking active", () => {
|
|
const nowS = 1_700_000_000;
|
|
const state = getProjectDisplayState(
|
|
stubProject({
|
|
tab: "kivvi",
|
|
recentActivity: [
|
|
{
|
|
id: "d2",
|
|
projectKey: "kivvi",
|
|
at: new Date((nowS - 30 * 86_400) * 1000).toISOString(),
|
|
kind: "dispatch",
|
|
source: "user",
|
|
adapter: "claude",
|
|
intent: "custom",
|
|
title: "old work",
|
|
detail: null,
|
|
status: "neutral",
|
|
},
|
|
],
|
|
}),
|
|
[],
|
|
nowS,
|
|
);
|
|
assert(
|
|
state.stateKey === "not_running",
|
|
`a month-old dispatch is not recent activity, got '${state.stateKey}'`,
|
|
);
|
|
});
|
|
|
|
check("a finished run fresher than the handoff names itself in the evidence", () => {
|
|
// Sessions no longer run in named zellij tabs, so a project that ran via
|
|
// dispatch 40 minutes ago has NO live signal — but "Idle today" (from a
|
|
// stale handoff) reads as a dead project. The freshest recorded signal
|
|
// must win: "Last run <when>". (orangecat, 2026-08-13.)
|
|
const nowS = 1_700_000_000;
|
|
const snapshot = buildProjectOperationsSnapshot(
|
|
stubProject({
|
|
tab: "orangecat",
|
|
session: {
|
|
done: "old",
|
|
next: "",
|
|
tests: "",
|
|
todos: "",
|
|
health: "",
|
|
mtime: (nowS - 86_400) * 1000,
|
|
},
|
|
latestOrchestrationRun: {
|
|
adapter: "claude",
|
|
intent: "custom",
|
|
state: "done",
|
|
startedAt: new Date((nowS - 3_000) * 1000).toISOString(),
|
|
finishedAt: new Date((nowS - 2_400) * 1000).toISOString(),
|
|
summary: null,
|
|
tokensIn: null,
|
|
tokensOut: null,
|
|
tokensCacheRead: null,
|
|
costUsd: null,
|
|
payload: null,
|
|
},
|
|
}),
|
|
[],
|
|
nowS,
|
|
);
|
|
assert(
|
|
snapshot.evidenceLabel === "Last run",
|
|
`freshest signal must be named, got '${snapshot.evidenceLabel}'`,
|
|
);
|
|
assert(
|
|
snapshot.evidenceAt === (nowS - 2_400) * 1000,
|
|
"evidence timestamp must be the run finish, not the handoff",
|
|
);
|
|
});
|
|
|
|
check("a dispatch fresher than run and handoff names itself in the evidence", () => {
|
|
const nowS = 1_700_000_000;
|
|
const snapshot = buildProjectOperationsSnapshot(
|
|
stubProject({
|
|
tab: "orangecat",
|
|
session: {
|
|
done: "old",
|
|
next: "",
|
|
tests: "",
|
|
todos: "",
|
|
health: "",
|
|
mtime: (nowS - 86_400) * 1000,
|
|
},
|
|
recentActivity: [
|
|
{
|
|
id: "a1",
|
|
projectKey: "orangecat",
|
|
at: new Date((nowS - 600) * 1000).toISOString(),
|
|
kind: "dispatch",
|
|
source: "user",
|
|
displayText: "fix feedback",
|
|
runId: null,
|
|
} as ProjectState["recentActivity"][number],
|
|
],
|
|
}),
|
|
[],
|
|
nowS,
|
|
);
|
|
assert(
|
|
snapshot.evidenceLabel === "Last dispatch",
|
|
`freshest signal must be named, got '${snapshot.evidenceLabel}'`,
|
|
);
|
|
assert(
|
|
snapshot.evidenceAt === (nowS - 600) * 1000,
|
|
"evidence timestamp must be the dispatch time",
|
|
);
|
|
});
|
|
|
|
check("quiet process is labeled Agent idle without claiming it asked the user", () => {
|
|
const nowS = 1_700_000_000;
|
|
const project = stubProject({ tab: "Loki", agentRunning: true });
|
|
const state = getProjectDisplayState(project, ["Loki"], nowS);
|
|
const snapshot = buildProjectOperationsSnapshot(project, ["Loki"], nowS);
|
|
assert(
|
|
state.stateLabel === "Agent idle",
|
|
"a quiet process must not be presented as an explicit request for input",
|
|
);
|
|
assert(snapshot.phase === "open_idle", "open_idle phase is still the underlying state");
|
|
assert(snapshot.evidenceLabel === "Agent idle", "evidence label must match the badge wording");
|
|
});
|
|
|
|
check("ready sentinel is a next-step state, not generic waiting", () => {
|
|
const nowS = 1_700_000_000;
|
|
const project = stubProject({ tab: "Loki", readyAt: nowS - 5 });
|
|
const state = getProjectDisplayState(project, ["Loki"], nowS);
|
|
const snapshot = buildProjectOperationsSnapshot(project, ["Loki"], nowS);
|
|
assert(state.stateLabel === "Ready for next step", "ready signal must name the action state");
|
|
assert(snapshot.phase === "ready", "ready signal remains actionable");
|
|
assert(
|
|
snapshot.evidenceLabel === "Agent signaled ready on connected computer",
|
|
"ready evidence should identify the signal",
|
|
);
|
|
});
|
|
|
|
check("operations list prioritizes projects waiting for user action", () => {
|
|
const nowS = 1_700_000_000;
|
|
const snapshots = buildProjectOperationsSnapshots(
|
|
[
|
|
stubProject({
|
|
tab: "Working",
|
|
agentRunning: true,
|
|
currentPrompt: { key: "custom", label: "Implementing", startedAt: nowS - 5 },
|
|
}),
|
|
stubProject({ tab: "Waiting", agentRunning: true, readyAt: nowS - 5 }),
|
|
stubProject({ tab: "Stopped" }),
|
|
],
|
|
["Working", "Waiting"],
|
|
nowS,
|
|
);
|
|
assert(
|
|
snapshots.map(({ project }) => project.tab).join(",") === "Waiting,Working,Stopped",
|
|
"actionable ordering expected",
|
|
);
|
|
});
|
|
|
|
check("closing lifecycle takes precedence over an open process in the snapshot", () => {
|
|
const nowS = 1_700_000_000;
|
|
const snapshot = buildProjectOperationsSnapshot(
|
|
stubProject({
|
|
tab: "Closing",
|
|
agentRunning: true,
|
|
closingAt: nowS - 2,
|
|
}),
|
|
["Closing"],
|
|
nowS,
|
|
);
|
|
assert(snapshot.display.stateLabel === "Closing", "badge must report closing");
|
|
assert(snapshot.phase === "closing", "rail phase must agree with the badge");
|
|
});
|
|
|
|
check("millisecond handoff mtime does not make a fresh prompt stale", () => {
|
|
const nowS = 1_700_000_100;
|
|
const project = stubProject({
|
|
tab: "Loki",
|
|
agentRunning: true,
|
|
currentPrompt: { key: "custom", label: "Current work", startedAt: nowS - 10 },
|
|
session: {
|
|
done: "previous",
|
|
next: "",
|
|
tests: "",
|
|
todos: "",
|
|
health: "",
|
|
mtime: (nowS - 20) * 1000,
|
|
},
|
|
});
|
|
assert(!isCurrentPromptStale(project, nowS), "older handoff must not end current work");
|
|
assert(
|
|
getProjectDisplayState(project, ["Loki"], nowS).stateLabel === "Working",
|
|
"fresh prompt must show Working",
|
|
);
|
|
});
|
|
|
|
check("direct-terminal observation is surfaced as Working", () => {
|
|
// Runner-side path for prompts the user typed directly into Claude (no
|
|
// Loki dispatch sentinel). loki-daemon.sh sets currentPrompt.key to
|
|
// "direct_terminal" with startedAt = the transcript's mtime when the tab is
|
|
// open, no other prompt is tracked, and the agent has not just signaled
|
|
// ready. The presenter must treat this exactly like any tracked prompt so
|
|
// chips/badges read "Working" instead of falling through to "Agent shell
|
|
// open" (the limitation 6da8d7e called out).
|
|
const nowS = 1_700_000_100;
|
|
const project = stubProject({
|
|
tab: "Loki",
|
|
agentRunning: true,
|
|
activeAgents: ["claude"],
|
|
currentPrompt: {
|
|
key: "direct_terminal",
|
|
label: "Direct terminal activity",
|
|
startedAt: nowS - 3,
|
|
},
|
|
});
|
|
const state = getProjectDisplayState(project, ["Loki"], nowS);
|
|
assert(state.stateLabel === "Working", "direct-terminal observation must report Working");
|
|
assert(state.isAgentWorking, "isAgentWorking is the SSOT chips read");
|
|
const snapshot = buildProjectOperationsSnapshot(project, ["Loki"], nowS);
|
|
assert(snapshot.phase === "working", "snapshot phase must match the badge");
|
|
assert(
|
|
snapshot.evidenceLabel === "Live agent process detected",
|
|
"evidence must read live, not historical",
|
|
);
|
|
});
|
|
|
|
check("working handoff does not stale an active prompt", () => {
|
|
const nowS = 1_700_000_100;
|
|
const project = stubProject({
|
|
tab: "Loki",
|
|
agentRunning: false,
|
|
currentPrompt: { key: "custom", label: "Still implementing", startedAt: nowS - 30 },
|
|
session: {
|
|
status: "working",
|
|
done: "partial",
|
|
next: "finish",
|
|
tests: "",
|
|
todos: "",
|
|
health: "good",
|
|
mtime: (nowS - 5) * 1000,
|
|
},
|
|
});
|
|
assert(!isCurrentPromptStale(project, nowS), "status:working handoff must not clear Working");
|
|
assert(
|
|
getProjectDisplayState(project, ["Loki"], nowS).stateLabel === "Working",
|
|
"fresh prompt must show Working without agentRunning",
|
|
);
|
|
});
|
|
|
|
check("handoff written after prompt marks it completed", () => {
|
|
const nowS = 1_700_000_100;
|
|
const project = stubProject({
|
|
tab: "Loki",
|
|
agentRunning: true,
|
|
currentPrompt: { key: "custom", label: "Current work", startedAt: nowS - 20 },
|
|
session: {
|
|
done: "finished",
|
|
next: "",
|
|
tests: "",
|
|
todos: "",
|
|
health: "",
|
|
mtime: (nowS - 5) * 1000,
|
|
},
|
|
});
|
|
assert(isCurrentPromptStale(project, nowS), "newer handoff should end displayed work");
|
|
});
|
|
|
|
// Helper: recent runs (age 0) unless a specific age is given.
|
|
const runs = (
|
|
outcomes: Array<"error" | "hang" | "timeout" | "success" | "partial" | "user_abort">,
|
|
ageMs = 0,
|
|
) => outcomes.map((outcome) => ({ outcome, ageMs }));
|
|
|
|
check("fleet pulse: off → Paused regardless of outcomes", () => {
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "off",
|
|
workingCount: 3,
|
|
latestRuns: runs(["error", "error"]),
|
|
});
|
|
assert(pulse.key === "paused", "off must be paused");
|
|
});
|
|
|
|
check("fleet pulse: any working agent → Building", () => {
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 1,
|
|
latestRuns: runs(["error", "error"]),
|
|
});
|
|
assert(pulse.key === "building", "working agents mean building even with past failures");
|
|
});
|
|
|
|
check("fleet pulse: 0 working + all RECENT runs failed → Stalled", () => {
|
|
// The 2026-07-02 dead-fleet shape: autopilot on, nothing working, every
|
|
// project's latest run a recent timeout — must NOT read "Building".
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 0,
|
|
latestRuns: runs(["timeout", "timeout", "error"]),
|
|
});
|
|
assert(pulse.key === "failing", "all-failed fleet must surface as failing");
|
|
assert(!!pulse.detail, "failing pulse carries a detail sentence");
|
|
});
|
|
|
|
check("fleet pulse: STALE failures (older than 24h) → Waiting, not Stalled", () => {
|
|
// The box-credential outage shape: every latest run is a timeout, but they
|
|
// all finished weeks ago and nothing has run since. Idle, not stalled.
|
|
const old = 3 * 24 * 60 * 60 * 1000;
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 0,
|
|
latestRuns: runs(["timeout", "timeout", "error"], old),
|
|
});
|
|
assert(pulse.key === "waiting", "old failures with no recent runs are idle, not a live stall");
|
|
});
|
|
|
|
check("fleet pulse: one failure among successes → Waiting, not Stalled", () => {
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 0,
|
|
latestRuns: runs(["error", "success", "partial"]),
|
|
});
|
|
assert(pulse.key === "waiting", "a single failing project must not panic the hero");
|
|
});
|
|
|
|
check("fleet pulse: partial does NOT mask real failures", () => {
|
|
// THE BUG, pinned. `succeeded` used to count "success" OR "partial", so a
|
|
// fleet with two hard failures and a couple of half-finished runs had a
|
|
// non-zero `succeeded` and could never reach the failing state. Before the
|
|
// fix this returned "waiting"; the fleet was dead and the hero was calm.
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 0,
|
|
latestRuns: runs(["timeout", "error", "partial", "partial"]),
|
|
});
|
|
assert(pulse.key === "failing", "partials must not vouch for a failing fleet");
|
|
});
|
|
|
|
check("fleet pulse: a fleet that only half-delivers says so", () => {
|
|
// Observed live on 2026-09-18: a project reading "5 of last 5 partial"
|
|
// under a hero that said nothing was wrong. Nothing FAILED, so the old
|
|
// code fell through to "Idle — nothing queued", which reads as a clean
|
|
// desk when it is a pile of half-finished work.
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 0,
|
|
waitingCount: 0,
|
|
latestRuns: runs(["partial", "partial", "partial"]),
|
|
});
|
|
assert(pulse.key === "partial", "an all-partial fleet is not idle");
|
|
assert(pulse.label === "Half-finished", "say what it is");
|
|
assert(!!pulse.detail && pulse.detail.includes("3"), "name how many stopped part-way");
|
|
});
|
|
|
|
check("fleet pulse: one partial among successes is not a verdict", () => {
|
|
// The converse. A single half-finished run is ordinary; only a pattern
|
|
// with nothing landing is worth a headline.
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 0,
|
|
waitingCount: 0,
|
|
latestRuns: runs(["success", "success", "partial"]),
|
|
});
|
|
assert(pulse.key === "waiting", "one partial next to real successes is fine");
|
|
});
|
|
|
|
check("fleet pulse: Building stops being silent about a partial streak", () => {
|
|
// "Building" is the right headline while an agent works, and it used to
|
|
// return detail: null — which is how a 5-of-5 partial streak sat under a
|
|
// hero that mentioned nothing. The label stays; the silence does not.
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 1,
|
|
latestRuns: runs(["partial", "partial", "partial"]),
|
|
});
|
|
assert(pulse.key === "building", "an agent is working, so Building is still true");
|
|
assert(!!pulse.detail, "a partial streak must be named even while building");
|
|
});
|
|
|
|
check("fleet pulse: Building stays quiet when there is nothing to report", () => {
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 1,
|
|
latestRuns: runs(["success", "success"]),
|
|
});
|
|
assert(pulse.key === "building", "still building");
|
|
assert(pulse.detail === null, "no partials means no warning sentence");
|
|
});
|
|
|
|
check(
|
|
"fleet pulse: 0 working, nothing queued, nobody waiting → Idle, not 'about to dispatch'",
|
|
() => {
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 0,
|
|
waitingCount: 0,
|
|
latestRuns: [],
|
|
});
|
|
assert(pulse.key === "waiting", "quiet fleet with autopilot on is waiting, not building");
|
|
assert(
|
|
pulse.label === "Idle — nothing queued",
|
|
"an empty quiet fleet must not promise an imminent dispatch",
|
|
);
|
|
},
|
|
);
|
|
|
|
check(
|
|
"fleet pulse: projects awaiting input → 'Waiting on you', not 'Waiting to dispatch'",
|
|
() => {
|
|
// 2026-08-13: the hero read "Waiting to dispatch" while the queue was
|
|
// empty and the only thing anyone waited on was the human — autopilot
|
|
// deliberately does NOT interrupt a session that's awaiting input, so
|
|
// the promised dispatch could never come.
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 0,
|
|
waitingCount: 1,
|
|
latestRuns: [],
|
|
});
|
|
assert(pulse.label === "Waiting on you", "the hero must name who is actually blocking");
|
|
assert(
|
|
!!pulse.detail && pulse.detail.includes("1 project"),
|
|
"detail counts the projects awaiting input",
|
|
);
|
|
},
|
|
);
|
|
|
|
check("fleet pulse: user_abort is neutral, not a systemic failure", () => {
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 0,
|
|
latestRuns: runs(["user_abort", "timeout"]),
|
|
});
|
|
assert(pulse.key === "waiting", "aborts are human choices — only real failures stall the hero");
|
|
});
|
|
|
|
check("fleet pulse: genuine execution stall outranks Building", () => {
|
|
// 2026-08-13: "Building · 1 agent active" rendered directly above
|
|
// "Builder is connected but not executing (2 queued 469s)" — both cannot
|
|
// be true. An observed terminal process doesn't prove the dispatch
|
|
// pipeline works; a real stall (already filtered of serialized/in-flight
|
|
// commands server-side) must own the headline.
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 1,
|
|
latestRuns: runs(["success"]),
|
|
executionStall: { stalled: true, stalledCount: 2, oldestSeconds: 469, tabs: ["orangecat"] },
|
|
});
|
|
assert(pulse.key === "stalled", "stalled execution must not read as Building");
|
|
assert(
|
|
!!pulse.detail && pulse.detail.includes("orangecat"),
|
|
"stall detail names the stuck projects",
|
|
);
|
|
assert(
|
|
!!pulse.detail && pulse.detail.includes("8m"),
|
|
"stall detail states the queue age in minutes",
|
|
);
|
|
});
|
|
|
|
check("fleet pulse: non-stalled execution health leaves Building untouched", () => {
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 1,
|
|
latestRuns: runs(["success"]),
|
|
executionStall: { stalled: false, stalledCount: 0, oldestSeconds: 0, tabs: [] },
|
|
});
|
|
assert(pulse.key === "building", "healthy execution with a working agent is Building");
|
|
});
|
|
|
|
// ── Hook-reported agent turns ───────────────────────────────────────────
|
|
// The regression: Control read "0 working · 21 idle" while eight agents were
|
|
// mid-task, because every "working" signal required Loki to have
|
|
// dispatched the run or the runner to recognise a zellij tab name. A session
|
|
// started any other way was structurally invisible.
|
|
|
|
check("an open agent turn alone makes a project working", () => {
|
|
const state = getProjectDisplayState(
|
|
stubProject({ tab: "petvity", liveAgentTurns: openTurn(3) }),
|
|
[],
|
|
Math.floor(Date.now() / 1000),
|
|
);
|
|
assert(state.isRunning, "an agent that reported a turn start is working");
|
|
assert(state.tone === "running", `expected tone running, got ${state.tone}`);
|
|
});
|
|
|
|
check("no open turn leaves the old behaviour untouched", () => {
|
|
const state = getProjectDisplayState(
|
|
stubProject({ tab: "petvity", liveAgentTurns: null }),
|
|
[],
|
|
Math.floor(Date.now() / 1000),
|
|
);
|
|
assert(!state.isRunning, "no turn, no dispatch, no tab → not running");
|
|
assert(state.tone === "idle", `expected tone idle, got ${state.tone}`);
|
|
});
|
|
|
|
check("verified run output makes a project working without a process match", () => {
|
|
const state = getProjectDisplayState(
|
|
stubProject({ tab: "loki", agentRunning: true, verifiedRunActive: true }),
|
|
[],
|
|
Math.floor(Date.now() / 1000),
|
|
);
|
|
assert(state.isRunning, "verified run output is active work");
|
|
assert(state.isAgentWorking, "fleet counts must include the verified run");
|
|
assert(state.tone === "running", `expected tone running, got ${state.tone}`);
|
|
});
|
|
|
|
check("an open idle process without verified run output stays idle", () => {
|
|
const state = getProjectDisplayState(
|
|
stubProject({ tab: "loki", agentRunning: true, verifiedRunActive: false }),
|
|
[],
|
|
Math.floor(Date.now() / 1000),
|
|
);
|
|
assert(!state.isRunning, "an open process alone does not prove work");
|
|
assert(state.tone === "session-open", `expected session-open, got ${state.tone}`);
|
|
});
|
|
|
|
// Control showed "Working · Live agent process detected" for a project whose
|
|
// own /api/control reported agentRunning=false and activeAgents=[] — the
|
|
// badge was right (a hook turn was open) and the stated reason was invented.
|
|
// Each running signal must name itself.
|
|
check("a live agent turn is reported as a turn, not as a detected process", () => {
|
|
const nowS = Math.floor(Date.now() / 1000);
|
|
const project = stubProject({
|
|
tab: "loki",
|
|
agentRunning: false,
|
|
activeAgents: [],
|
|
liveAgentTurns: openTurn(2),
|
|
});
|
|
const state = getProjectDisplayState(project, ["loki"], nowS);
|
|
assert(state.isRunning, "an open turn is work");
|
|
assert(
|
|
state.runningEvidence === "live-turn",
|
|
`expected live-turn, got ${String(state.runningEvidence)}`,
|
|
);
|
|
const snapshot = buildProjectOperationsSnapshot(project, ["loki"], nowS);
|
|
assert(
|
|
snapshot.evidenceLabel === "Agent reported a turn in progress",
|
|
`must not claim a process it never saw, got "${snapshot.evidenceLabel}"`,
|
|
);
|
|
});
|
|
|
|
check("verified run output is reported as run output", () => {
|
|
const nowS = Math.floor(Date.now() / 1000);
|
|
const project = stubProject({
|
|
tab: "loki",
|
|
agentRunning: true,
|
|
verifiedRunActive: true,
|
|
});
|
|
const state = getProjectDisplayState(project, ["loki"], nowS);
|
|
assert(
|
|
state.runningEvidence === "run-output",
|
|
`expected run-output, got ${String(state.runningEvidence)}`,
|
|
);
|
|
const snapshot = buildProjectOperationsSnapshot(project, ["loki"], nowS);
|
|
assert(
|
|
snapshot.evidenceLabel === "Run output still arriving from the builder",
|
|
`expected the run-output line, got "${snapshot.evidenceLabel}"`,
|
|
);
|
|
});
|
|
|
|
check("a tracked prompt with no agent process says so", () => {
|
|
const nowS = Math.floor(Date.now() / 1000);
|
|
const project = stubProject({
|
|
tab: "loki",
|
|
agentRunning: false,
|
|
activeAgents: [],
|
|
currentPrompt: { key: "runner", label: "Dispatched work", startedAt: nowS - 3 },
|
|
});
|
|
const state = getProjectDisplayState(project, ["loki"], nowS);
|
|
assert(state.isRunning, "a fresh tracked prompt still reads as work");
|
|
assert(
|
|
state.runningEvidence === "dispatched-prompt",
|
|
`expected dispatched-prompt, got ${String(state.runningEvidence)}`,
|
|
);
|
|
const snapshot = buildProjectOperationsSnapshot(project, ["loki"], nowS);
|
|
assert(
|
|
!snapshot.evidenceLabel.includes("process detected"),
|
|
`must not claim a process, got "${snapshot.evidenceLabel}"`,
|
|
);
|
|
});
|
|
|
|
check("a count of 0 is not a live turn", () => {
|
|
// The bucket only ever exists with count >= 1, but a future caller that
|
|
// sends an empty bucket must not light the card up.
|
|
const state = getProjectDisplayState(
|
|
stubProject({
|
|
tab: "petvity",
|
|
liveAgentTurns: { count: 0, startedAt: new Date().toISOString(), cwds: [] },
|
|
}),
|
|
[],
|
|
Math.floor(Date.now() / 1000),
|
|
);
|
|
assert(!state.isRunning, "count 0 must not read as working");
|
|
});
|
|
|
|
check("an open turn outranks a recent ready stamp", () => {
|
|
// readyAt says the agent finished a turn; a new turn means it is working
|
|
// again. Without this the card sits on "Ready" through the whole next turn
|
|
// and the project lands in the awaiting-you bucket while an agent edits it.
|
|
const nowS = Math.floor(Date.now() / 1000);
|
|
const state = getProjectDisplayState(
|
|
stubProject({ tab: "vitareba", readyAt: nowS - 5, liveAgentTurns: openTurn(1) }),
|
|
[],
|
|
nowS,
|
|
);
|
|
assert(!state.isReady, "a started turn cancels the ready state");
|
|
assert(state.tone === "running", `expected running, got ${state.tone}`);
|
|
});
|
|
|
|
check("a ready stamp still wins when no turn is open", () => {
|
|
const nowS = Math.floor(Date.now() / 1000);
|
|
const state = getProjectDisplayState(
|
|
stubProject({ tab: "vitareba", readyAt: nowS - 5, liveAgentTurns: null }),
|
|
[],
|
|
nowS,
|
|
);
|
|
assert(state.isReady, "ready must survive when nothing is running");
|
|
});
|
|
|
|
check("bucketTurnsByProject: counts, oldest start, deduped cwds", () => {
|
|
const iso = (m: number) => new Date(Date.UTC(2026, 7, 16, 12, m));
|
|
const bucketed = bucketTurnsByProject([
|
|
{ projectKey: "loki", cwd: "/dev/loki/.claude/worktrees/a", startedAt: iso(30) },
|
|
{ projectKey: "loki", cwd: "/dev/loki/.claude/worktrees/b", startedAt: iso(10) },
|
|
{ projectKey: "loki", cwd: "/dev/loki/.claude/worktrees/a", startedAt: iso(50) },
|
|
{ projectKey: "petvity", cwd: "/dev/petvity", startedAt: iso(20) },
|
|
]);
|
|
assert(bucketed.loki.count === 3, "three open turns on loki");
|
|
assert(
|
|
bucketed.loki.startedAt === iso(10).toISOString(),
|
|
"the OLDEST open turn is reported, not the newest",
|
|
);
|
|
assert(bucketed.loki.cwds.length === 2, "repeated cwds are deduped");
|
|
assert(bucketed.petvity.count === 1, "petvity counted separately");
|
|
assert(Object.keys(bucketed).length === 2, "no phantom projects");
|
|
});
|
|
|
|
// ---- the fleet triad must never be invented ----
|
|
//
|
|
// Without runtime state every project classifies as `offline`, so the triad
|
|
// reads 0/0/0 — which is byte-for-byte the "All clear" condition. Control
|
|
// would therefore announce a calm fleet at the exact moment it knows nothing
|
|
// about it, on the surface whose whole job is saying what needs the operator.
|
|
// countsKnown is how the derivation layer says "I don't know yet".
|
|
const controlData = (projects: ProjectState[], liveTabs: string[] = []) =>
|
|
({
|
|
projects,
|
|
liveTabs,
|
|
inventory: {
|
|
source: "user_projects",
|
|
trackedProjectCount: projects.length,
|
|
controlProjectCount: projects.length,
|
|
linkedDirectoryCount: 0,
|
|
},
|
|
}) as unknown as Parameters<typeof buildControlPageState>[0];
|
|
|
|
check("countsKnown is false before the runner has ever reported", () => {
|
|
const data = controlData([stubProject({ tab: "alpha" }), stubProject({ tab: "beta" })]);
|
|
const state = buildControlPageState(data, Math.floor(Date.now() / 1000), false, false);
|
|
assert(state.dashboard.countsKnown === false, "counts must not claim to be known");
|
|
});
|
|
|
|
check("countsKnown is true once runtime state is known", () => {
|
|
const data = controlData([stubProject({ tab: "alpha" })]);
|
|
const state = buildControlPageState(data, Math.floor(Date.now() / 1000), true, false);
|
|
assert(state.dashboard.countsKnown === true, "counts are knowable once the runner reported");
|
|
});
|
|
|
|
check("unknown runtime state yields 0/0/0 — the same shape as 'All clear'", () => {
|
|
// The reason countsKnown has to exist. With runtime state unknown the triad
|
|
// is not a partial count, it is indistinguishable from a healthy quiet
|
|
// fleet. If this ever stops being true, revisit whether countsKnown is
|
|
// still load-bearing rather than deleting it silently.
|
|
const projects = [
|
|
stubProject({ tab: "alpha" }),
|
|
stubProject({ tab: "beta" }),
|
|
stubProject({ tab: "gamma" }),
|
|
];
|
|
const nowS = Math.floor(Date.now() / 1000);
|
|
const unknown = buildControlPageState(controlData(projects), nowS, false, false).dashboard;
|
|
assert(unknown.runningCount === 0, "nothing can be known to be working");
|
|
assert(unknown.waitingCount === 0, "nothing can be known to be waiting");
|
|
assert(unknown.idleCount === 0, "nothing can be known to be idle either");
|
|
|
|
// ...and the same fleet, once known, is NOT all-clear.
|
|
const known = buildControlPageState(controlData(projects), nowS, true, false).dashboard;
|
|
assert(known.idleCount === projects.length, "known state buckets them as idle");
|
|
});
|
|
|
|
// ── deriveRunnerPresence ───────────────────────────────────────────────────
|
|
// Extracted out of ControlPanel 2026-09-15. It decides three separate things
|
|
// the page renders differently for, and the ADDITIVE rollout rule inside it
|
|
// (connected===false is not yet authoritative on its own) is the kind of
|
|
// thing a later simplification deletes by accident.
|
|
const NEVER = {
|
|
runtimeAvailable: false,
|
|
runnerConnected: null,
|
|
cloudBuilderPresent: false,
|
|
runnerLastPushedAt: null,
|
|
lastUpdated: Date.now(),
|
|
};
|
|
|
|
check("local runtime is never offline, whatever the bridge says", () => {
|
|
const p = deriveRunnerPresence({ ...NEVER, runtimeAvailable: true, runnerConnected: false });
|
|
assert(p.runnerOffline === false, "a local runtime needs no builder connection");
|
|
assert(p.runnerNeverSeen === false, "and is never 'never seen'");
|
|
});
|
|
|
|
check("no push ever + no connection = never seen, and state is unknown", () => {
|
|
const p = deriveRunnerPresence(NEVER);
|
|
assert(p.runnerNeverSeen === true, "nothing has ever reported");
|
|
assert(p.runtimeStateKnown === false, "so cached runtime must be hidden");
|
|
assert(p.runnerSyncStale === false, "there is no sync to call stale");
|
|
});
|
|
|
|
check("an open bridge connection is online even with an ancient heartbeat", () => {
|
|
const p = deriveRunnerPresence({
|
|
...NEVER,
|
|
runnerConnected: true,
|
|
runnerLastPushedAt: new Date(Date.now() - 86_400_000).toISOString(),
|
|
});
|
|
assert(p.runnerOffline === false, "connection-based presence wins");
|
|
assert(p.runnerNeverSeen === false, "a connected runner has been seen");
|
|
});
|
|
|
|
check("a stale heartbeat with no connection is offline, but state stays known", () => {
|
|
const p = deriveRunnerPresence({
|
|
...NEVER,
|
|
runnerLastPushedAt: new Date(Date.now() - 86_400_000).toISOString(),
|
|
});
|
|
assert(p.runnerOffline === true, "nothing is there to claim a dispatch");
|
|
assert(p.runtimeStateKnown === true, "last-known Working/Ready is still worth showing");
|
|
assert(p.runnerSyncStale === true, "labelled stale, not presented as live");
|
|
assert(p.runtimeSyncCtx.syncStale === true, "and the card context says so too");
|
|
});
|
|
|
|
check("a live cloud builder holds presence open while the heartbeat ages", () => {
|
|
// The ADDITIVE rollout: connected===false from a pre-rollout runner must
|
|
// not read as offline on its own.
|
|
const p = deriveRunnerPresence({
|
|
...NEVER,
|
|
runnerConnected: false,
|
|
cloudBuilderPresent: true,
|
|
runnerLastPushedAt: new Date(Date.now() - 86_400_000).toISOString(),
|
|
});
|
|
assert(p.runnerOffline === true, "an explicit false IS authoritative");
|
|
const legacy = deriveRunnerPresence({
|
|
...NEVER,
|
|
cloudBuilderPresent: true,
|
|
runnerLastPushedAt: new Date(Date.now() - 86_400_000).toISOString(),
|
|
});
|
|
assert(legacy.runnerOffline === false, "but an unknown connection defers to cloud presence");
|
|
});
|
|
|
|
// ── The hero and the inbox must agree ──────────────────────────────────────
|
|
// Observed on prod 2026-09-20: the Control hero read "Idle — nothing queued"
|
|
// while the panel one screen below it was titled "Needs you" and badged 6.
|
|
// One page, one question, two answers. These pin the rule that the confident
|
|
// answer is the one that has to earn it.
|
|
|
|
check("fleet pulse: a non-empty review queue is never 'Idle'", () => {
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 0,
|
|
waitingCount: 0,
|
|
latestRuns: [],
|
|
inbox: { count: 6, unknown: false },
|
|
});
|
|
assert(pulse.key === "inbox", "six things needing a human is not an idle fleet");
|
|
assert(pulse.label === "Waiting on you", "and the headline says whose turn it is");
|
|
assert(pulse.detail?.includes("6") === true, "the count is in the sentence, not just a badge");
|
|
});
|
|
|
|
check("fleet pulse: an empty review queue still reads Idle", () => {
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 0,
|
|
waitingCount: 0,
|
|
latestRuns: [],
|
|
inbox: { count: 0, unknown: false },
|
|
});
|
|
assert(pulse.key === "waiting", "an empty queue is a genuinely quiet fleet");
|
|
});
|
|
|
|
check("fleet pulse: an unreadable review queue is not a claim of emptiness", () => {
|
|
const pulse = deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 0,
|
|
waitingCount: 0,
|
|
latestRuns: [],
|
|
inbox: { count: 0, unknown: true },
|
|
});
|
|
assert(pulse.key === "unknown", "a queue we failed to read is not a queue known to be empty");
|
|
assert(
|
|
pulse.detail !== null && /not a claim/i.test(pulse.detail),
|
|
"and it says so, rather than rendering silence as the answer 'no'",
|
|
);
|
|
});
|
|
|
|
check("fleet pulse: real trouble still outranks the chore queue", () => {
|
|
// The inbox is small things a human says yes to. It must never displace a
|
|
// stalled dispatch pipeline, a failing fleet, or a project blocked on the
|
|
// operator — all of which are worse news arriving at the same address.
|
|
const withInbox = { inbox: { count: 9, unknown: false } };
|
|
assert(
|
|
deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 0,
|
|
waitingCount: 0,
|
|
latestRuns: runs(["error", "error"]),
|
|
...withInbox,
|
|
}).key === "failing",
|
|
"a failing fleet outranks chores",
|
|
);
|
|
assert(
|
|
deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 0,
|
|
waitingCount: 2,
|
|
latestRuns: [],
|
|
...withInbox,
|
|
}).key === "waiting",
|
|
"projects blocked on the operator outrank chores",
|
|
);
|
|
assert(
|
|
deriveFleetPulse({
|
|
automationMode: "on",
|
|
workingCount: 1,
|
|
waitingCount: 0,
|
|
latestRuns: runs(["success"]),
|
|
...withInbox,
|
|
}).key === "building",
|
|
"work in flight outranks chores",
|
|
);
|
|
});
|
|
|
|
console.log(`\n${passed}/${passed} passed`);
|
|
}
|
|
|
|
runTests();
|