feat(dashboard): add agent dashboard popout (#9604)
* feat(dashboard): add agent dashboard popout * fix(dashboard): gate and harden agent popout * test(ipc): isolate dashboard handler registration * fix(dashboard): drop diff status from bucket counts * fix(dashboard): address review feedback * perf(dashboard): ignore unrelated store churn
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
# How people like to see all their agents at once — research + how it shaped the mocks
|
||||
|
||||
Grounded in shipping tools (Warp Agent Panel, herdr, Claude Code Agent View, Claude Squad, uzi, Conductor/Crystal, Vibe Kanban, k9s/Lens, Datadog Host Map, Buildkite, pm2/btop) and notification/triage UX literature. This drives `index.html`.
|
||||
|
||||
## The core finding
|
||||
**"Waiting for input" is the whole reason this view exists.** Everything else is ambient. Every serious tool makes the needs-a-human state the loudest thing on screen and lets you resolve it without a full context switch (Warp "jump to pane", Claude Agent View "reply without attaching"). Practical parallelism tops out around **4–8 agents** (occasionally ~30), so the default should optimize glanceability for a handful, with a density fallback for many.
|
||||
|
||||
## Design principles applied to the mocks
|
||||
1. **Waiting-for-input is loudest.** Amber + gentle pulse, top-of-sort priority, an always-visible aggregate ("2 need you"), a one-line *reason label*, and inline **Answer**/**Open** actions. → the **Needs you** inbox is the purest form; every other view surfaces it too.
|
||||
2. **State is the primary channel, encoded redundantly.** Color + icon + text label (never color alone — accessibility). Colors map to Orca's `main.css` tokens (success green, destructive red) with a mock-local amber/blue for waiting/working.
|
||||
3. **Motion = "needs you or is changing," never decoration.** Only *working* (subtle) and *waiting* (pulse) animate; done/idle/error are static. Respects `prefers-reduced-motion`.
|
||||
4. **Density adapts to count.** Cards (≤8) → table (8–20) → tiles/grid (20+). The switcher lets you feel each.
|
||||
5. **Group by project with roll-up, but let urgency flatten it.** Gallery/tree group by repo; the inbox is the flat, urgency-sorted triage view.
|
||||
6. **Per-agent info priority:** state → reason (when blocked) → what it's working on → last activity → elapsed → provider badge → branch. Shown progressively (1–4 always, 5–7 on hover/detail).
|
||||
7. **Live preview on hover, dots at rest.** Don't mount 30 live xterms (perf) — rest = status; **hover → terminal tail popover** with a jump-in affordance. This is the shared popover in every variant.
|
||||
8. **Notify on transitions, tiered.** waiting/error = interruptive (toast + unread badge, and Orca's mobile push); done = ambient; working/idle = silent.
|
||||
|
||||
## The seven variants ↔ research concepts
|
||||
| Variant | Maps to | Best for |
|
||||
|---|---|---|
|
||||
| **Repo › worktree › agent** (nested, default) | herdr state roll-up; k9s XRay tree; your own idea | Mirrors Orca's real hierarchy; roll-up dot on each repo/worktree tells you if anything inside needs you; agents sorted by urgency |
|
||||
| **Needs you** (inbox) | Inbox-zero triage; Warp attention state | Any count — the "just tell me what needs me" view |
|
||||
| **Card gallery** (default) | Conductor/Lens cards + progressive disclosure | Typical 5–12 — best glanceability/info balance |
|
||||
| **Kanban board** | Vibe Kanban (columns = state) | 8–15; managing rather than co-coding |
|
||||
| **Mission control** (table) | uzi `ls -w`, k9s | 15–30; terminal-native power users |
|
||||
| **Terminal wall** (mosaic) | tmux wall, Claude Squad panes | 2–6; comparison runs / ambient monitor |
|
||||
| **Tree + focus** (master-detail) | k9s XRay tree, Conductor, herdr roll-up | Supervise + dive-in; strong general default |
|
||||
| **Radial map** | Datadog Host Map / your original concentric dashboard | Stretch/overview concept; homage to the movable-UI branch |
|
||||
|
||||
**Recommendation from the research:** ship **Card gallery** as default + **Tree + focus** as the working surface, with **Needs you** as a one-key filter and **Mission control** as the "I have 25 agents" density toggle. Wall/radial are focus/overview modes.
|
||||
|
||||
## Sources
|
||||
Warp [managing-agents](https://docs.warp.dev/agents/using-agents/managing-agents) · herdr [github](https://github.com/ogulcancelik/herdr), [docs](https://herdr.dev/docs/agents/) · Claude Code [agent-teams](https://code.claude.com/docs/en/agent-teams), [Agent View cockpit](https://www.contextstudios.ai/blog/claude-code-agent-view-multi-agent-cockpit) · Claude Squad [github](https://github.com/smtg-ai/claude-squad) · uzi [github](https://github.com/devflowinc/uzi) · Conductor [docs](https://www.conductor.build/docs/guides/parallel-agents/run-multiple-claude-code-sessions) · Vibe Kanban [github](https://github.com/BloopAI/vibe-kanban) · k9s [site](https://k9scli.io/), [palark](https://palark.com/blog/k9s-the-powerful-terminal-ui-for-kubernetes/) · Datadog [host map](https://docs.datadoghq.com/dashboards/widgets/hostmap/), [widget colors](https://docs.datadoghq.com/dashboards/guide/widget_colors/) · Buildkite [dashboard](https://buildkite.com/docs/pipelines/dashboard-walkthrough) · pm2/btop [monitoring](https://pm2.keymetrics.io/docs/usage/monitoring/) · Triage UX [Smart Interface Design Patterns](https://smart-interface-design-patterns.com/articles/notifications/), [Missive inbox zero](https://missiveapp.com/blog/inbox-zero)
|
||||
@@ -0,0 +1,788 @@
|
||||
<!doctype html>
|
||||
<html lang="en" class="dark">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Orca · Agent Dashboard — UI explorations</title>
|
||||
<style>
|
||||
/*
|
||||
Orca "all my agents at once" — UI mock gallery.
|
||||
Six distinct layouts share one dataset + one terminal-popover system.
|
||||
Colors mirror Orca tokens (src/renderer/src/assets/main.css); state colors
|
||||
are mock-local since Orca reserves color for state and has no agent-state palette yet.
|
||||
*/
|
||||
:root {
|
||||
--font-sans: "Geist", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
--font-mono: "Geist Mono", ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;
|
||||
--radius: 0.625rem;
|
||||
|
||||
/* Orca light tokens */
|
||||
--background: #fff;
|
||||
--foreground: #0a0a0a;
|
||||
--card: #fff;
|
||||
--card-foreground: #0a0a0a;
|
||||
--popover: #fff;
|
||||
--popover-foreground: #0a0a0a;
|
||||
--muted: #f5f5f5;
|
||||
--muted-foreground: #737373;
|
||||
--accent: #f5f5f5;
|
||||
--accent-foreground: #171717;
|
||||
--border: #e5e5e5;
|
||||
--ring: #a1a1a1;
|
||||
--primary: #171717;
|
||||
|
||||
/* Agent-state palette (mock-local, adapts to theme) */
|
||||
--st-attention: #b45309; /* needs you — loudest */
|
||||
--st-attention-bg: #fef3c7;
|
||||
--st-working: #2563eb; /* streaming / running */
|
||||
--st-working-bg: #dbeafe;
|
||||
--st-idle: #737373; /* alive but quiet */
|
||||
--st-idle-bg: #f5f5f5;
|
||||
--st-done: #15803d; /* finished, unseen */
|
||||
--st-done-bg: #dcfce7;
|
||||
--st-error: #e40014; /* crashed / failed */
|
||||
--st-error-bg: #fee2e2;
|
||||
|
||||
/* terminal surface */
|
||||
--term-bg: #0b0b0c;
|
||||
--term-fg: #d6d6d6;
|
||||
--term-dim: #8a8a8a;
|
||||
--shadow-float: 0 10px 30px rgba(0,0,0,0.22), 0 2px 8px rgba(0,0,0,0.12);
|
||||
}
|
||||
html.dark {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #fafafa;
|
||||
--card: #171717;
|
||||
--card-foreground: #fafafa;
|
||||
--popover: #171717;
|
||||
--popover-foreground: #fafafa;
|
||||
--muted: #262626;
|
||||
--muted-foreground: #a1a1a1;
|
||||
--accent: #404040;
|
||||
--accent-foreground: #fafafa;
|
||||
--border: rgba(255,255,255,0.09);
|
||||
--ring: #737373;
|
||||
--primary: #e5e5e5;
|
||||
|
||||
--st-attention: #fbbf24;
|
||||
--st-attention-bg: rgba(251,191,36,0.14);
|
||||
--st-working: #60a5fa;
|
||||
--st-working-bg: rgba(96,165,250,0.15);
|
||||
--st-idle: #a1a1a1;
|
||||
--st-idle-bg: rgba(255,255,255,0.05);
|
||||
--st-done: #86efac;
|
||||
--st-done-bg: rgba(134,239,172,0.13);
|
||||
--st-error: #ff6568;
|
||||
--st-error-bg: rgba(255,101,104,0.14);
|
||||
|
||||
--term-bg: #08090b;
|
||||
--term-fg: #d6d6d6;
|
||||
--term-dim: #7d7d7d;
|
||||
--shadow-float: 0 12px 34px rgba(0,0,0,0.55), 0 2px 10px rgba(0,0,0,0.4);
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html, body { height: 100%; }
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: var(--font-sans);
|
||||
letter-spacing: 0.01em;
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
button { font-family: inherit; }
|
||||
|
||||
/* ---------- top chrome ---------- */
|
||||
.topbar {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 10px 18px; border-bottom: 1px solid var(--border);
|
||||
position: sticky; top: 0; z-index: 40; background: var(--background);
|
||||
}
|
||||
.brand { display: flex; align-items: baseline; gap: 9px; }
|
||||
.brand b { font-size: 14px; font-weight: 650; }
|
||||
.brand span { font-size: 12px; color: var(--muted-foreground); }
|
||||
.spacer { flex: 1; }
|
||||
.tabs { display: flex; gap: 2px; background: var(--muted); padding: 3px; border-radius: 9px; }
|
||||
.tabs button {
|
||||
border: 0; background: transparent; color: var(--muted-foreground);
|
||||
font-size: 12.5px; font-weight: 550; padding: 6px 11px; border-radius: 7px; cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.tabs button:hover { color: var(--foreground); }
|
||||
.tabs button.active { background: var(--card); color: var(--foreground); box-shadow: 0 1px 2px rgba(0,0,0,0.1); }
|
||||
.iconbtn {
|
||||
border: 1px solid var(--border); background: var(--card); color: var(--foreground);
|
||||
width: 34px; height: 34px; border-radius: 8px; cursor: pointer; font-size: 15px;
|
||||
display: grid; place-items: center;
|
||||
}
|
||||
.iconbtn:hover { background: var(--accent); }
|
||||
|
||||
/* ---------- summary strip ---------- */
|
||||
.summary { display: flex; gap: 8px; align-items: center; padding: 12px 18px 0; flex-wrap: wrap; }
|
||||
.pill {
|
||||
display: inline-flex; align-items: center; gap: 7px; font-size: 12px; font-weight: 550;
|
||||
padding: 5px 10px 5px 8px; border-radius: 999px; border: 1px solid var(--border); background: var(--card);
|
||||
cursor: default;
|
||||
}
|
||||
.pill .dot { width: 8px; height: 8px; border-radius: 50%; }
|
||||
.pill b { font-variant-numeric: tabular-nums; }
|
||||
.pill.attn { border-color: color-mix(in srgb, var(--st-attention) 45%, var(--border)); background: var(--st-attention-bg); color: var(--st-attention); }
|
||||
.intro { padding: 8px 18px 0; color: var(--muted-foreground); font-size: 12.5px; max-width: 880px; line-height: 1.5; }
|
||||
.intro code { font-family: var(--font-mono); font-size: 11.5px; background: var(--muted); padding: 1px 5px; border-radius: 5px; }
|
||||
|
||||
.stage { padding: 16px 18px 60px; }
|
||||
|
||||
/* ---------- state atoms ---------- */
|
||||
.dot { width: 9px; height: 9px; border-radius: 50%; flex: none; }
|
||||
.s-attention { background: var(--st-attention); }
|
||||
.s-working { background: var(--st-working); }
|
||||
.s-idle { background: var(--st-idle); }
|
||||
.s-done { background: var(--st-done); }
|
||||
.s-error { background: var(--st-error); }
|
||||
.pulse { box-shadow: 0 0 0 0 currentColor; animation: pulse 1.8s infinite; color: var(--st-attention); }
|
||||
@keyframes pulse { 0%{box-shadow:0 0 0 0 color-mix(in srgb,var(--st-attention) 55%,transparent)} 70%{box-shadow:0 0 0 7px transparent} 100%{box-shadow:0 0 0 0 transparent} }
|
||||
.spin { animation: spin 1s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
@media (prefers-reduced-motion: reduce) { .pulse,.spin,.caret { animation: none !important; } }
|
||||
|
||||
.badge {
|
||||
display: inline-flex; align-items: center; gap: 5px; font-size: 10.5px; font-weight: 600;
|
||||
padding: 2px 7px; border-radius: 999px; text-transform: uppercase; letter-spacing: 0.04em;
|
||||
}
|
||||
.badge.attention { background: var(--st-attention-bg); color: var(--st-attention); }
|
||||
.badge.working { background: var(--st-working-bg); color: var(--st-working); }
|
||||
.badge.idle { background: var(--st-idle-bg); color: var(--st-idle); }
|
||||
.badge.done { background: var(--st-done-bg); color: var(--st-done); }
|
||||
.badge.error { background: var(--st-error-bg); color: var(--st-error); }
|
||||
|
||||
.prov { width: 22px; height: 22px; border-radius: 6px; display: grid; place-items: center; font-size: 11px; font-weight: 700; color: #fff; flex: none; }
|
||||
.prov.claude { background: #d97757; }
|
||||
.prov.codex { background: #10a37f; }
|
||||
.prov.gemini { background: linear-gradient(135deg,#4f86f7,#9b6cf5); }
|
||||
.prov.opencode { background: #0ea5a4; }
|
||||
|
||||
.meta { color: var(--muted-foreground); font-size: 11.5px; }
|
||||
.mono { font-family: var(--font-mono); }
|
||||
.truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
/* an agent target: anything hoverable that opens the terminal popover */
|
||||
[data-agent] { cursor: pointer; }
|
||||
[data-agent].hot { outline: 2px solid var(--ring); outline-offset: 2px; }
|
||||
|
||||
/* =================================================================== */
|
||||
/* VARIANT: Kanban board (by state) */
|
||||
/* =================================================================== */
|
||||
.kanban { display: grid; grid-auto-flow: column; grid-auto-columns: minmax(240px, 1fr); gap: 12px; align-items: start; overflow-x: auto; }
|
||||
.kcol { background: var(--card); border: 1px solid var(--border); border-radius: 12px; padding: 10px; min-height: 120px; }
|
||||
.kcol.attn { border-color: color-mix(in srgb, var(--st-attention) 40%, var(--border)); box-shadow: 0 0 0 1px color-mix(in srgb,var(--st-attention) 22%, transparent); }
|
||||
.kcol h3 { margin: 2px 4px 10px; font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted-foreground); display: flex; align-items: center; gap: 7px; }
|
||||
.kcol h3 .count { margin-left: auto; background: var(--muted); color: var(--foreground); border-radius: 999px; font-size: 10.5px; padding: 1px 7px; }
|
||||
.kcard { background: var(--background); border: 1px solid var(--border); border-radius: 10px; padding: 9px 10px; margin-bottom: 8px; }
|
||||
.kcard:hover { border-color: var(--ring); }
|
||||
.kcard .row1 { display: flex; align-items: center; gap: 8px; }
|
||||
.kcard .name { font-size: 12.5px; font-weight: 600; }
|
||||
.kcard .task { margin: 6px 0 7px; font-size: 12px; color: var(--foreground); line-height: 1.35; }
|
||||
.kcard .row2 { display: flex; align-items: center; gap: 8px; }
|
||||
.kcard .wt { font-family: var(--font-mono); font-size: 10.5px; color: var(--muted-foreground); }
|
||||
|
||||
/* =================================================================== */
|
||||
/* VARIANT: Card gallery (grouped by project) */
|
||||
/* =================================================================== */
|
||||
.projgroup { margin-bottom: 22px; }
|
||||
.projhead { display: flex; align-items: center; gap: 9px; margin: 0 2px 10px; }
|
||||
.projhead .pname { font-size: 12.5px; font-weight: 650; }
|
||||
.projhead .pmeta { font-size: 11.5px; color: var(--muted-foreground); }
|
||||
.projhead .line { flex: 1; height: 1px; background: var(--border); }
|
||||
.gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 12px; }
|
||||
.gcard { position: relative; background: var(--card); border: 1px solid var(--border); border-radius: 12px; padding: 12px; overflow: hidden; }
|
||||
.gcard:hover { border-color: var(--ring); box-shadow: 0 4px 14px rgba(0,0,0,0.08); }
|
||||
.gcard .accent { position: absolute; left: 0; top: 0; bottom: 0; width: 3px; }
|
||||
.gcard.attention .accent { background: var(--st-attention); }
|
||||
.gcard.working .accent { background: var(--st-working); }
|
||||
.gcard.idle .accent { background: var(--st-idle); }
|
||||
.gcard.done .accent { background: var(--st-done); }
|
||||
.gcard.error .accent { background: var(--st-error); }
|
||||
.gcard .top { display: flex; align-items: center; gap: 9px; }
|
||||
.gcard .name { font-size: 13px; font-weight: 620; }
|
||||
.gcard .sub { font-family: var(--font-mono); font-size: 10.5px; color: var(--muted-foreground); }
|
||||
.gcard .task { margin: 10px 0 12px; font-size: 12.5px; line-height: 1.4; min-height: 34px; }
|
||||
.gcard .foot { display: flex; align-items: center; gap: 10px; }
|
||||
.spark { display: flex; align-items: flex-end; gap: 2px; height: 16px; }
|
||||
.spark i { width: 3px; background: color-mix(in srgb, var(--st-working) 60%, transparent); border-radius: 1px; }
|
||||
.attnbar { margin-top: 10px; background: var(--st-attention-bg); color: var(--st-attention); border-radius: 8px; padding: 7px 9px; font-size: 11.5px; display: flex; gap: 7px; align-items: flex-start; }
|
||||
|
||||
/* =================================================================== */
|
||||
/* VARIANT: Mission control (dense table) */
|
||||
/* =================================================================== */
|
||||
.mc { width: 100%; border-collapse: collapse; font-size: 12.5px; }
|
||||
.mc th { text-align: left; font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted-foreground); font-weight: 600; padding: 8px 10px; border-bottom: 1px solid var(--border); position: sticky; top: 56px; background: var(--background); cursor: pointer; user-select: none; }
|
||||
.mc th.num, .mc td.num { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.mc td { padding: 9px 10px; border-bottom: 1px solid var(--border); vertical-align: middle; }
|
||||
.mc tr:hover td { background: var(--accent); }
|
||||
.mc tr.attention td { box-shadow: inset 3px 0 0 var(--st-attention); }
|
||||
.mc tr.attention td:first-child { background: var(--st-attention-bg); }
|
||||
.mc .cell-name { display: flex; align-items: center; gap: 8px; }
|
||||
.mc .cell-name b { font-weight: 600; }
|
||||
.mc .wt { font-family: var(--font-mono); font-size: 11px; color: var(--muted-foreground); }
|
||||
.mc .tasktext { max-width: 360px; }
|
||||
|
||||
/* =================================================================== */
|
||||
/* VARIANT: Terminal wall (live mosaic) */
|
||||
/* =================================================================== */
|
||||
.wall { display: grid; grid-template-columns: repeat(auto-fill, minmax(310px, 1fr)); gap: 12px; }
|
||||
.tile { border: 1px solid var(--border); border-radius: 11px; overflow: hidden; background: var(--term-bg); }
|
||||
.tile:hover { border-color: var(--ring); }
|
||||
.tile.attention { border-color: color-mix(in srgb, var(--st-attention) 55%, var(--border)); }
|
||||
.tile .tbar { display: flex; align-items: center; gap: 8px; padding: 7px 9px; background: var(--card); border-bottom: 1px solid var(--border); }
|
||||
.tile .tbar .name { font-size: 11.5px; font-weight: 600; color: var(--card-foreground); }
|
||||
.tile .tbar .wt { font-family: var(--font-mono); font-size: 10px; color: var(--muted-foreground); margin-left: auto; }
|
||||
.tile .screen { font-family: var(--font-mono); font-size: 10.5px; line-height: 1.5; color: var(--term-fg); padding: 9px 10px; height: 128px; overflow: hidden; }
|
||||
.tile .screen .l { white-space: pre; overflow: hidden; text-overflow: ellipsis; }
|
||||
|
||||
/* =================================================================== */
|
||||
/* VARIANT: Radial / concentric */
|
||||
/* =================================================================== */
|
||||
.radialwrap { position: relative; width: 100%; height: 620px; }
|
||||
.radial { position: absolute; inset: 0; }
|
||||
.ring { position: absolute; border: 1px dashed var(--border); border-radius: 50%; left: 50%; top: 50%; transform: translate(-50%,-50%); }
|
||||
.ring .rlabel { position: absolute; top: -10px; left: 50%; transform: translateX(-50%); font-size: 10px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted-foreground); background: var(--background); padding: 0 6px; }
|
||||
.rcenter { position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); text-align: center; width: 120px; }
|
||||
.rcenter .big { font-size: 26px; font-weight: 700; font-variant-numeric: tabular-nums; }
|
||||
.rcenter .lab { font-size: 11px; color: var(--muted-foreground); }
|
||||
.node { position: absolute; transform: translate(-50%,-50%); display: grid; place-items: center; }
|
||||
.node .chip { width: 40px; height: 40px; border-radius: 11px; display: grid; place-items: center; font-size: 12px; font-weight: 700; color: #fff; border: 2px solid var(--background); box-shadow: 0 0 0 2px transparent; }
|
||||
.node[data-st="attention"] .chip { box-shadow: 0 0 0 3px var(--st-attention); }
|
||||
.node[data-st="working"] .chip { box-shadow: 0 0 0 3px var(--st-working); }
|
||||
.node[data-st="idle"] .chip { box-shadow: 0 0 0 3px var(--st-idle); }
|
||||
.node[data-st="done"] .chip { box-shadow: 0 0 0 3px var(--st-done); }
|
||||
.node[data-st="error"] .chip { box-shadow: 0 0 0 3px var(--st-error); }
|
||||
.node .nlab { font-size: 10px; color: var(--muted-foreground); margin-top: 3px; max-width: 78px; text-align: center; }
|
||||
|
||||
/* =================================================================== */
|
||||
/* VARIANT: Focus (tree + detail) */
|
||||
/* =================================================================== */
|
||||
.focus { display: grid; grid-template-columns: 320px 1fr; gap: 14px; align-items: start; }
|
||||
.tree { background: var(--card); border: 1px solid var(--border); border-radius: 12px; padding: 8px; }
|
||||
.tree .prow { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted-foreground); padding: 8px 8px 4px; display: flex; gap: 7px; align-items: center; }
|
||||
.tree .arow { display: flex; align-items: center; gap: 8px; padding: 7px 8px; border-radius: 8px; margin: 1px 2px; }
|
||||
.tree .arow:hover { background: var(--accent); }
|
||||
.tree .arow.sel { background: var(--accent); box-shadow: inset 0 0 0 1px var(--border); }
|
||||
.tree .arow .nm { font-size: 12.5px; font-weight: 550; }
|
||||
.tree .arow .wt { font-family: var(--font-mono); font-size: 10px; color: var(--muted-foreground); margin-left: auto; }
|
||||
.detail { background: var(--card); border: 1px solid var(--border); border-radius: 12px; overflow: hidden; }
|
||||
.detail .dhead { display: flex; align-items: center; gap: 10px; padding: 13px 14px; border-bottom: 1px solid var(--border); }
|
||||
.detail .dhead .name { font-size: 14px; font-weight: 650; }
|
||||
.detail .dbody { display: grid; grid-template-columns: 1fr 220px; }
|
||||
.detail .screenbig { font-family: var(--font-mono); font-size: 11.5px; line-height: 1.55; color: var(--term-fg); background: var(--term-bg); padding: 12px 14px; height: 340px; overflow: auto; }
|
||||
.detail .side { padding: 13px 14px; border-left: 1px solid var(--border); font-size: 12px; }
|
||||
.detail .side .k { color: var(--muted-foreground); font-size: 11px; margin-top: 12px; }
|
||||
.detail .side .k:first-child { margin-top: 0; }
|
||||
.detail .side .v { margin-top: 2px; }
|
||||
|
||||
/* =================================================================== */
|
||||
/* VARIANT: Nested cards — repo > worktree > agent */
|
||||
/* Surfaces alternate (card > muted > card) so 3 levels read in both */
|
||||
/* themes without relying on shadows. */
|
||||
/* =================================================================== */
|
||||
.repogrid { display: grid; grid-template-columns: repeat(auto-fill, minmax(370px, 1fr)); gap: 14px; align-items: start; }
|
||||
.repo { background: var(--card); border: 1px solid var(--border); border-radius: 14px; padding: 12px; }
|
||||
.repohead { display: flex; align-items: center; gap: 9px; margin: 2px 3px 12px; }
|
||||
.repohead .rn { font-size: 13.5px; font-weight: 680; }
|
||||
.repohead .rmeta { font-size: 11px; color: var(--muted-foreground); margin-left: auto; font-variant-numeric: tabular-nums; }
|
||||
.wtpanel { background: var(--muted); border: 1px solid var(--border); border-radius: 11px; padding: 9px; margin-bottom: 10px; }
|
||||
.wtpanel:last-child { margin-bottom: 0; }
|
||||
.wthead { display: flex; align-items: center; gap: 8px; margin: 1px 3px 8px; }
|
||||
.wthead .wn { font-family: var(--font-mono); font-size: 11px; font-weight: 600; }
|
||||
.wthead .wc { font-size: 10px; color: var(--muted-foreground); background: var(--card); border: 1px solid var(--border); border-radius: 999px; padding: 1px 6px; }
|
||||
.wthead .wd { margin-left: auto; }
|
||||
.acard { position: relative; display: flex; align-items: flex-start; gap: 8px; background: var(--card); border: 1px solid var(--border); border-radius: 9px; padding: 8px 9px 8px 12px; margin-bottom: 6px; overflow: hidden; }
|
||||
.acard:last-child { margin-bottom: 0; }
|
||||
.acard:hover { border-color: var(--ring); }
|
||||
.acard .aacc { position: absolute; left: 0; top: 0; bottom: 0; width: 3px; }
|
||||
.acard.attention .aacc { background: var(--st-attention); }
|
||||
.acard.working .aacc { background: var(--st-working); }
|
||||
.acard.idle .aacc { background: var(--st-idle); }
|
||||
.acard.done .aacc { background: var(--st-done); }
|
||||
.acard.error .aacc { background: var(--st-error); }
|
||||
.acard .abody { flex: 1; min-width: 0; }
|
||||
.acard .arow { display: flex; align-items: center; gap: 7px; }
|
||||
.acard .an { font-size: 12px; font-weight: 600; }
|
||||
.acard .at { font-size: 11.5px; margin-top: 3px; line-height: 1.35; }
|
||||
.acard .am { font-size: 10.5px; color: var(--muted-foreground); margin-top: 4px; }
|
||||
|
||||
/* =================================================================== */
|
||||
/* VARIANT: Needs-you inbox (triage-first) */
|
||||
/* =================================================================== */
|
||||
.inbox { max-width: 860px; margin: 0 auto; }
|
||||
.inbox .lead { font-size: 12.5px; color: var(--muted-foreground); margin: 0 2px 12px; }
|
||||
.irow { display: flex; align-items: center; gap: 12px; padding: 12px 14px; border: 1px solid var(--border); border-radius: 11px; margin-bottom: 9px; background: var(--card); }
|
||||
.irow.attention { border-color: color-mix(in srgb, var(--st-attention) 45%, var(--border)); background: color-mix(in srgb, var(--st-attention-bg) 60%, var(--card)); }
|
||||
.irow.error { border-color: color-mix(in srgb, var(--st-error) 40%, var(--border)); }
|
||||
.irow:hover { box-shadow: 0 3px 12px rgba(0,0,0,0.09); }
|
||||
.irow .who { min-width: 150px; }
|
||||
.irow .who .nm { font-size: 12.5px; font-weight: 620; display: flex; align-items: center; gap: 7px; }
|
||||
.irow .who .wt { font-family: var(--font-mono); font-size: 10.5px; color: var(--muted-foreground); margin-top: 2px; }
|
||||
.irow .reason { flex: 1; font-size: 12.5px; line-height: 1.4; }
|
||||
.irow .reason .lbl { font-size: 10px; text-transform: uppercase; letter-spacing: 0.05em; font-weight: 650; margin-right: 6px; }
|
||||
.irow.attention .reason .lbl { color: var(--st-attention); }
|
||||
.irow.error .reason .lbl { color: var(--st-error); }
|
||||
.irow .acts { display: flex; gap: 7px; }
|
||||
.quiet { margin-top: 22px; }
|
||||
.quiet h4 { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted-foreground); margin: 0 2px 8px; }
|
||||
.qrow { display: flex; align-items: center; gap: 9px; padding: 7px 10px; border-radius: 8px; font-size: 12px; }
|
||||
.qrow:hover { background: var(--accent); }
|
||||
.qrow .wt { font-family: var(--font-mono); font-size: 10.5px; color: var(--muted-foreground); }
|
||||
.emptyz { text-align: center; padding: 40px; color: var(--muted-foreground); }
|
||||
|
||||
/* ---------- terminal popover ---------- */
|
||||
#pop {
|
||||
position: fixed; z-index: 100; width: 440px; max-width: 92vw;
|
||||
background: var(--popover); color: var(--popover-foreground);
|
||||
border: 1px solid var(--border); border-radius: 12px; box-shadow: var(--shadow-float);
|
||||
opacity: 0; transform: translateY(4px) scale(0.99); pointer-events: none;
|
||||
transition: opacity .12s ease, transform .12s ease; overflow: hidden;
|
||||
}
|
||||
#pop.show { opacity: 1; transform: none; pointer-events: auto; }
|
||||
#pop .phead { display: flex; align-items: center; gap: 9px; padding: 10px 12px; border-bottom: 1px solid var(--border); }
|
||||
#pop .phead .name { font-size: 13px; font-weight: 620; }
|
||||
#pop .phead .wt { font-family: var(--font-mono); font-size: 10.5px; color: var(--muted-foreground); }
|
||||
#pop .pscreen { font-family: var(--font-mono); font-size: 11.5px; line-height: 1.55; background: var(--term-bg); color: var(--term-fg); padding: 11px 13px; height: 240px; overflow: auto; }
|
||||
#pop .pscreen .l { white-space: pre-wrap; word-break: break-word; }
|
||||
#pop .cmd { color: #9ece6a; }
|
||||
#pop .path { color: #7aa2f7; }
|
||||
#pop .warn { color: #e0af68; }
|
||||
#pop .err { color: #f7768e; }
|
||||
#pop .dim { color: var(--term-dim); }
|
||||
#pop .ok { color: #9ece6a; }
|
||||
.caret { display: inline-block; width: 7px; height: 14px; background: var(--term-fg); vertical-align: text-bottom; animation: blink 1s steps(1) infinite; }
|
||||
@keyframes blink { 50% { opacity: 0; } }
|
||||
#pop .askbar { background: var(--st-attention-bg); color: var(--st-attention); padding: 9px 13px; font-size: 12px; display: flex; gap: 8px; align-items: flex-start; border-top: 1px solid var(--border); }
|
||||
#pop .pfoot { display: flex; align-items: center; gap: 8px; padding: 9px 12px; border-top: 1px solid var(--border); }
|
||||
#pop .pfoot input { flex: 1; background: var(--muted); border: 1px solid var(--border); border-radius: 8px; padding: 7px 9px; color: var(--foreground); font-size: 12px; font-family: var(--font-mono); }
|
||||
.btn { border: 1px solid var(--border); background: var(--card); color: var(--foreground); font-size: 12px; font-weight: 550; padding: 7px 11px; border-radius: 8px; cursor: pointer; white-space: nowrap; }
|
||||
.btn:hover { background: var(--accent); }
|
||||
.btn.primary { background: var(--primary); color: var(--background); border-color: var(--primary); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="topbar">
|
||||
<div class="brand"><b>Orca</b><span>Agents</span></div>
|
||||
<div class="spacer"></div>
|
||||
<div class="tabs" id="tabs"></div>
|
||||
<button class="iconbtn" id="themeToggle" title="Toggle light / dark">◐</button>
|
||||
</div>
|
||||
|
||||
<div class="summary" id="summary"></div>
|
||||
<div class="intro" id="intro">
|
||||
Eight ways to see every agent across all your worktrees at once. <b>Hover any agent</b> to peek its live terminal
|
||||
in a popover (move into the popover to interact). Layout switcher is top-right; <code>◐</code> toggles light/dark.
|
||||
</div>
|
||||
|
||||
<div class="stage" id="stage"></div>
|
||||
|
||||
<!-- shared terminal popover -->
|
||||
<div id="pop" role="dialog" aria-label="Agent terminal preview"></div>
|
||||
|
||||
<script>
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Mock data: agents across 4 projects / worktrees, weighted states. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
const AGENTS = [
|
||||
{ id:'a1', name:'Claude', prov:'claude', project:'orca', worktree:'agent-canvas-view', branch:'brennanb2025/agent-canvas', state:'attention',
|
||||
task:'Refactor the concentric dashboard into a movable panel', elapsed:'7m', last:'waiting 40s', add:214, del:63, files:9,
|
||||
ask:'Move AgentDashboard mount to the right rail, or keep it as a floating window?',
|
||||
term:[['dim','$ '],['cmd','claude'],['',' Read src/renderer/.../AgentDashboard.tsx'],['',' Edit dashboard-panel.tsx (+214 −63)'],['',' 9 files staged'],['warn',' ? I need a decision before continuing:'],['warn',' Right-rail mount vs floating window?']] },
|
||||
{ id:'a2', name:'Codex', prov:'codex', project:'orca', worktree:'pty-backpressure', branch:'brennanb2025/pty-queue', state:'working',
|
||||
task:'Bound PTY output queues under backpressure', elapsed:'12m', last:'2s ago', add:88, del:12, files:4,
|
||||
term:[['dim','$ '],['cmd','codex exec'],['path',' daemon/pty-queue.ts'],['',' applying patch… hunk 3/5'],['ok',' ✓ typecheck passed'],['',' running vitest pty-queue.test.ts'],['dim',' › 14 passed, streaming…']] },
|
||||
{ id:'a3', name:'Gemini', prov:'gemini', project:'orca', worktree:'git-graph-view', branch:'brennanb2025/git-graph', state:'idle',
|
||||
task:'Add Git Graph view showing all branches', elapsed:'1h 3m', last:'idle 9m', add:402, del:120, files:15,
|
||||
term:[['dim','$ '],['cmd','gemini'],['ok',' ✓ built GitGraphView'],['dim',' waiting for next instruction'],['dim',' (idle — no output for 9m)']] },
|
||||
{ id:'a4', name:'Claude', prov:'claude', project:'orca-internal', worktree:'skill-freshness', branch:'skill-freshness-rail', state:'done',
|
||||
task:'Safe skill freshness detection + update rail', elapsed:'22m', last:'done 3m', add:640, del:210, files:18,
|
||||
term:[['dim','$ '],['cmd','claude'],['ok',' ✓ all checks green'],['ok',' ✓ 217 tests passed'],['',' Summary: added freshness rail, 5 fixes'],['dim',' ── agent finished ──']] },
|
||||
{ id:'a5', name:'Codex', prov:'codex', project:'orca-internal', worktree:'posthog-dash', branch:'posthog-dashboard-edit', state:'error',
|
||||
task:'Add chart-density design rules', elapsed:'4m', last:'error 30s', add:12, del:4, files:2,
|
||||
term:[['dim','$ '],['cmd','codex exec'],['',' writing references/palette.md'],['err',' ✗ ENOENT: references/ does not exist'],['err',' Error: build step failed (exit 1)'],['dim',' process exited — needs retry']] },
|
||||
{ id:'a6', name:'OpenCode', prov:'opencode', project:'mobile', worktree:'quick-commands', branch:'mobile-quick-cmds', state:'working',
|
||||
task:'Terminal Quick Commands launcher', elapsed:'18m', last:'just now', add:333, del:41, files:11,
|
||||
term:[['dim','$ '],['cmd','opencode run'],['path',' mobile/src/terminal/QuickCommands.tsx'],['',' rendering tab-strip launcher'],['dim',' hot-reloading sim…'],['ok',' ✓ mounted on iPhone 15 sim']] },
|
||||
{ id:'a7', name:'Claude', prov:'claude', project:'mobile', worktree:'native-chat-toggle', branch:'mobile-native-chat', state:'attention',
|
||||
task:'Per-device native chat default-view toggle', elapsed:'9m', last:'waiting 1m', add:120, del:30, files:6,
|
||||
ask:'Default the toggle ON for new installs, or leave OFF until opt-in?',
|
||||
term:[['dim','$ '],['cmd','claude'],['',' Edit Settings/NativeChat.tsx'],['warn',' ? Default new installs to ON or OFF?'],['warn',' (tri-state map ready either way)']] },
|
||||
{ id:'a8', name:'Gemini', prov:'gemini', project:'mobile', worktree:'ws-accept-wedge', branch:'mobile-ws-6768', state:'working',
|
||||
task:'Fix :6768 WS accept wedge (no notifications)', elapsed:'31m', last:'5s ago', add:76, del:22, files:3,
|
||||
term:[['dim','$ '],['cmd','gemini'],['path',' runtime/ws-server.ts'],['',' adding maxConnections cap + accept-error handler'],['dim',' restarting :6768 listener…'],['ok',' ✓ heartbeat liveness log added']] },
|
||||
{ id:'a9', name:'Codex', prov:'codex', project:'orca', worktree:'dialog-maxw', branch:'dialog-content-maxw', state:'idle',
|
||||
task:'Let caller max-width override DialogContent cap', elapsed:'2h 11m', last:'idle 44m', add:9, del:3, files:1,
|
||||
term:[['dim','$ '],['cmd','codex exec'],['ok',' ✓ patch applied'],['dim',' awaiting review'],['dim',' (idle 44m)']] },
|
||||
{ id:'a10', name:'Claude', prov:'claude', project:'orca', worktree:'prune-registrations', branch:'space-prune', state:'done',
|
||||
task:'Prune stale worktree registrations', elapsed:'14m', last:'done 20m', add:180, del:64, files:7,
|
||||
term:[['dim','$ '],['cmd','claude'],['ok',' ✓ prune action wired to relay op'],['ok',' ✓ i18n auto-keys synced'],['dim',' ── agent finished ──']] },
|
||||
{ id:'a11', name:'OpenCode', prov:'opencode', project:'orca-internal', worktree:'pr-review-alert', branch:'pr-review-scope', state:'working',
|
||||
task:'Alert on changes outside PR stated feature', elapsed:'6m', last:'1s ago', add:54, del:8, files:2,
|
||||
term:[['dim','$ '],['cmd','opencode run'],['',' scanning diff for scope creep'],['dim',' 3 files outside stated feature…'],['warn',' flagging status-bar change']] },
|
||||
{ id:'a12', name:'Gemini', prov:'gemini', project:'mobile', worktree:'create-ws-dropdown', branch:'mobile-create-ws', state:'error',
|
||||
task:'Fix Create Workspace dropdown unresponsive', elapsed:'3m', last:'error 1m', add:20, del:15, files:2,
|
||||
term:[['dim','$ '],['cmd','gemini'],['',' wiring BottomDrawerModalHost'],['err',' ✗ esbuild: cannot resolve ./probe'],['err',' Error: bundling failed'],['dim',' exited — retry needed']] },
|
||||
// split-pane cases: a second agent sharing a worktree (proves the innermost nesting)
|
||||
{ id:'a2b', name:'Claude', prov:'claude', project:'orca', worktree:'pty-backpressure', branch:'brennanb2025/pty-queue', state:'attention',
|
||||
task:'Review the queue-bound patch in a split pane', elapsed:'5m', last:'waiting 25s', add:0, del:0, files:0,
|
||||
ask:'Cap the queue at 64KiB, or make it a setting?',
|
||||
term:[['dim','$ '],['cmd','claude'],['',' reviewing daemon/pty-queue.ts'],['warn',' ? Cap at 64KiB or expose as a setting?']] },
|
||||
{ id:'a8b', name:'OpenCode', prov:'opencode', project:'mobile', worktree:'ws-accept-wedge', branch:'mobile-ws-6768', state:'working',
|
||||
task:'Run the :6768 socket soak test', elapsed:'12m', last:'3s ago', add:18, del:2, files:1,
|
||||
term:[['dim','$ '],['cmd','opencode run'],['',' soak: 500 connect/disconnect cycles'],['dim',' cycle 213/500…'],['ok',' ✓ no wedge so far']] },
|
||||
];
|
||||
|
||||
// urgency rank for sorting + roll-up (attention & error bubble to the top)
|
||||
const URG = { attention:0, error:1, working:2, done:3, idle:4 };
|
||||
|
||||
const STATE_ORDER = ['attention','working','idle','done','error'];
|
||||
const STATE_LABEL = { attention:'Needs you', working:'Working', idle:'Idle', done:'Done', error:'Error' };
|
||||
const STATE_ICON = { attention:'✋', working:'⟳', idle:'○', done:'✓', error:'✗' };
|
||||
const byState = s => AGENTS.filter(a => a.state === s);
|
||||
const projects = [...new Set(AGENTS.map(a => a.project))];
|
||||
const initials = p => ({claude:'C',codex:'Cx',gemini:'G',opencode:'oc'})[p] || '?';
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Terminal popover */
|
||||
/* ------------------------------------------------------------------ */
|
||||
const pop = document.getElementById('pop');
|
||||
let hideTimer = null, showTimer = null, streamTimer = null, activeId = null;
|
||||
|
||||
function termHTML(a){
|
||||
const lines = a.term.map(([cls,txt]) => `<div class="l"><span class="${cls}">${escapeHTML(txt)}</span></div>`).join('');
|
||||
return lines;
|
||||
}
|
||||
function escapeHTML(s){ return s.replace(/[&<>]/g, c => ({'&':'&','<':'<','>':'>'}[c])); }
|
||||
|
||||
function renderPop(a){
|
||||
const askbar = a.ask ? `<div class="askbar">✋ <div><b>Waiting for you.</b> ${escapeHTML(a.ask)}</div></div>` : '';
|
||||
pop.innerHTML = `
|
||||
<div class="phead">
|
||||
<div class="prov ${a.prov}">${initials(a.prov)}</div>
|
||||
<div>
|
||||
<div class="name">${a.name} · <span class="wt">${escapeHTML(a.worktree)}</span></div>
|
||||
<div class="meta">${a.project} · ${a.elapsed}</div>
|
||||
</div>
|
||||
<div style="margin-left:auto"><span class="badge ${a.state}">${STATE_LABEL[a.state]}</span></div>
|
||||
</div>
|
||||
<div class="pscreen" id="pscreen">${termHTML(a)}<div class="l"><span class="dim">$ </span><span class="caret"></span></div></div>
|
||||
${askbar}
|
||||
<div class="pfoot">
|
||||
<input placeholder="Type a message to ${a.name}…" />
|
||||
<button class="btn">Focus worktree</button>
|
||||
<button class="btn primary">Open terminal</button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function positionPop(target){
|
||||
const r = target.getBoundingClientRect();
|
||||
const pw = pop.offsetWidth, ph = pop.offsetHeight;
|
||||
const gap = 10;
|
||||
let left = r.right + gap;
|
||||
if (left + pw > window.innerWidth - 8) left = r.left - pw - gap; // flip left
|
||||
if (left < 8) left = Math.min(Math.max(8, r.left), window.innerWidth - pw - 8); // clamp
|
||||
let top = r.top + r.height/2 - ph/2;
|
||||
top = Math.max(8, Math.min(top, window.innerHeight - ph - 8));
|
||||
pop.style.left = left + 'px';
|
||||
pop.style.top = top + 'px';
|
||||
}
|
||||
|
||||
function openPop(target){
|
||||
const a = AGENTS.find(x => x.id === target.dataset.agent);
|
||||
if (!a) return;
|
||||
clearTimeout(hideTimer);
|
||||
activeId = a.id;
|
||||
renderPop(a);
|
||||
pop.classList.add('show');
|
||||
positionPop(target);
|
||||
// fake a little "live" streaming for working agents
|
||||
clearInterval(streamTimer);
|
||||
if (a.state === 'working') {
|
||||
const extra = [' · touched '+a.worktree, ' · '+a.last, ' › streaming output…', ' · '+a.files+' files changed'];
|
||||
let i = 0;
|
||||
streamTimer = setInterval(() => {
|
||||
const sc = document.getElementById('pscreen'); if(!sc) return;
|
||||
const line = document.createElement('div'); line.className='l';
|
||||
line.innerHTML = `<span class="dim">${escapeHTML(extra[i % extra.length])}</span>`;
|
||||
sc.insertBefore(line, sc.lastElementChild);
|
||||
sc.scrollTop = sc.scrollHeight; i++;
|
||||
}, 1400);
|
||||
}
|
||||
}
|
||||
function scheduleHide(){
|
||||
clearTimeout(hideTimer);
|
||||
hideTimer = setTimeout(() => { pop.classList.remove('show'); clearInterval(streamTimer); activeId=null; }, 220);
|
||||
}
|
||||
|
||||
function wireHovers(root){
|
||||
root.querySelectorAll('[data-agent]').forEach(el => {
|
||||
el.addEventListener('mouseenter', () => { clearTimeout(showTimer); showTimer = setTimeout(() => openPop(el), 120); el.classList.add('hot'); });
|
||||
el.addEventListener('mouseleave', () => { clearTimeout(showTimer); el.classList.remove('hot'); scheduleHide(); });
|
||||
});
|
||||
}
|
||||
pop.addEventListener('mouseenter', () => clearTimeout(hideTimer));
|
||||
pop.addEventListener('mouseleave', scheduleHide);
|
||||
window.addEventListener('scroll', () => { if(activeId){ const t=document.querySelector(`[data-agent="${activeId}"]`); if(t) positionPop(t);} }, true);
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Summary strip */
|
||||
/* ------------------------------------------------------------------ */
|
||||
function renderSummary(){
|
||||
const el = document.getElementById('summary');
|
||||
const parts = STATE_ORDER.map(s => {
|
||||
const n = byState(s).length;
|
||||
const attn = s === 'attention';
|
||||
return `<div class="pill ${attn?'attn':''}"><span class="dot s-${s} ${attn?'pulse':''}"></span>${STATE_LABEL[s]} <b>${n}</b></div>`;
|
||||
}).join('');
|
||||
el.innerHTML = `<div class="pill" style="font-weight:650"><b>${AGENTS.length}</b> agents · ${projects.length} projects</div>` + parts;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Variant renderers */
|
||||
/* ------------------------------------------------------------------ */
|
||||
function vKanban(stage){
|
||||
stage.innerHTML = `<div class="kanban">` + STATE_ORDER.map(s => {
|
||||
const list = byState(s);
|
||||
const cards = list.map(a => `
|
||||
<div class="kcard" data-agent="${a.id}">
|
||||
<div class="row1"><div class="prov ${a.prov}">${initials(a.prov)}</div><span class="name">${a.name}</span>
|
||||
<span style="margin-left:auto" class="dot s-${s} ${s==='attention'?'pulse':''}"></span></div>
|
||||
<div class="task">${a.task}</div>
|
||||
<div class="row2"><span class="wt">${a.project}/${a.worktree}</span></div>
|
||||
</div>`).join('') || `<div class="meta" style="padding:6px 4px">None</div>`;
|
||||
return `<div class="kcol ${s==='attention'?'attn':''}"><h3><span class="dot s-${s}"></span>${STATE_LABEL[s]}<span class="count">${list.length}</span></h3>${cards}</div>`;
|
||||
}).join('') + `</div>`;
|
||||
wireHovers(stage);
|
||||
}
|
||||
|
||||
function vGallery(stage){
|
||||
stage.innerHTML = projects.map(p => {
|
||||
const list = AGENTS.filter(a => a.project === p);
|
||||
const attn = list.filter(a => a.state==='attention').length;
|
||||
const cards = list.map(a => {
|
||||
const spark = `<div class="spark">`+Array.from({length:12},()=>`<i style="height:${4+Math.round(Math.random()*14)}px"></i>`).join('')+`</div>`;
|
||||
const ask = a.ask ? `<div class="attnbar">✋ <div>${escapeHTML(a.ask)}</div></div>` : '';
|
||||
return `<div class="gcard ${a.state}" data-agent="${a.id}">
|
||||
<div class="accent"></div>
|
||||
<div class="top"><div class="prov ${a.prov}">${initials(a.prov)}</div>
|
||||
<div><div class="name">${a.name}</div><div class="sub">${a.worktree}</div></div>
|
||||
<div style="margin-left:auto"><span class="badge ${a.state}">${STATE_LABEL[a.state]}</span></div></div>
|
||||
<div class="task">${a.task}</div>
|
||||
${ask}
|
||||
<div class="foot"><span class="meta">${a.last}</span>
|
||||
<span style="margin-left:auto">${a.state==='working'?spark:`<span class="meta">${a.elapsed}</span>`}</span></div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
return `<div class="projgroup"><div class="projhead"><span class="pname">${p}</span>
|
||||
<span class="pmeta">${list.length} agents${attn?` · ${attn} need you`:''}</span><span class="line"></span></div>
|
||||
<div class="gallery">${cards}</div></div>`;
|
||||
}).join('');
|
||||
wireHovers(stage);
|
||||
}
|
||||
|
||||
function vMissionControl(stage){
|
||||
const rows = [...AGENTS].sort((a,b)=>STATE_ORDER.indexOf(a.state)-STATE_ORDER.indexOf(b.state)).map(a => `
|
||||
<tr class="${a.state}" data-agent="${a.id}">
|
||||
<td><div class="cell-name"><span class="dot s-${a.state} ${a.state==='attention'?'pulse':''}"></span><div class="prov ${a.prov}" style="width:18px;height:18px;font-size:9px;border-radius:5px">${initials(a.prov)}</div><b>${a.name}</b></div></td>
|
||||
<td><span class="wt">${a.project}/${a.worktree}</span></td>
|
||||
<td class="tasktext truncate">${a.ask ? '✋ '+escapeHTML(a.ask) : a.task}</td>
|
||||
<td class="num meta">${a.elapsed}</td>
|
||||
<td class="num meta">${a.last}</td>
|
||||
</tr>`).join('');
|
||||
stage.innerHTML = `<table class="mc"><thead><tr>
|
||||
<th>Agent</th><th>Project / Worktree</th><th>Task</th><th class="num">Elapsed</th><th class="num">Last activity</th>
|
||||
</tr></thead><tbody>${rows}</tbody></table>`;
|
||||
wireHovers(stage);
|
||||
}
|
||||
|
||||
function vWall(stage){
|
||||
stage.innerHTML = `<div class="wall">` + AGENTS.map(a => {
|
||||
const screen = a.term.slice(-6).map(([cls,txt])=>`<div class="l"><span class="${cls}" style="color:inherit">${escapeHTML(txt)}</span></div>`).join('');
|
||||
return `<div class="tile ${a.state}" data-agent="${a.id}">
|
||||
<div class="tbar"><span class="dot s-${a.state} ${a.state==='attention'?'pulse':''}"></span>
|
||||
<div class="prov ${a.prov}" style="width:18px;height:18px;font-size:9px;border-radius:5px">${initials(a.prov)}</div>
|
||||
<span class="name">${a.name}</span><span class="wt">${a.worktree}</span></div>
|
||||
<div class="screen">${screen}<div class="l"><span style="color:var(--term-dim)">$ </span><span class="caret"></span></div></div>
|
||||
</div>`;
|
||||
}).join('') + `</div>`;
|
||||
wireHovers(stage);
|
||||
}
|
||||
|
||||
function vRadial(stage){
|
||||
stage.innerHTML = `<div class="radialwrap"><div class="radial" id="radial"></div></div>`;
|
||||
const wrap = document.getElementById('radial');
|
||||
const W = wrap.clientWidth, H = 620, cx = W/2, cy = H/2;
|
||||
// radii kept < cy (310) so no ring clips into the header
|
||||
const RAD = { attention:95, working:170, quiet:235, error:288 };
|
||||
[[RAD.attention,'Needs you'],[RAD.working,'Working'],[RAD.quiet,'Idle / Done'],[RAD.error,'Error']].forEach(([rad,lab])=>{
|
||||
const d=document.createElement('div'); d.className='ring'; d.style.width=d.style.height=(rad*2)+'px';
|
||||
d.innerHTML=`<span class="rlabel">${lab}</span>`; wrap.appendChild(d);
|
||||
});
|
||||
const center=document.createElement('div'); center.className='rcenter';
|
||||
const attn=byState('attention').length;
|
||||
center.innerHTML=`<div class="big">${AGENTS.length}</div><div class="lab">agents<br>${attn} need you</div>`;
|
||||
wrap.appendChild(center);
|
||||
// per-ring angular offset so small groups don't collapse onto the vertical axis
|
||||
const groups = [
|
||||
['attention', byState('attention'), RAD.attention, 30],
|
||||
['working', byState('working'), RAD.working, -20],
|
||||
['quiet', [...byState('idle'),...byState('done')], RAD.quiet, 15],
|
||||
['error', byState('error'), RAD.error, -45],
|
||||
];
|
||||
groups.forEach(([g,list,rad,off])=>{
|
||||
list.forEach((a,i)=>{
|
||||
const ang = (off + (360/Math.max(list.length,1))*i) * Math.PI/180;
|
||||
const x = cx + rad*Math.cos(ang), y = cy + rad*Math.sin(ang);
|
||||
const n=document.createElement('div'); n.className='node'; n.dataset.agent=a.id; n.dataset.st=a.state;
|
||||
n.style.left=x+'px'; n.style.top=y+'px';
|
||||
n.innerHTML=`<div class="chip ${a.prov}">${initials(a.prov)}</div><div class="nlab">${a.worktree}</div>`;
|
||||
wrap.appendChild(n);
|
||||
});
|
||||
});
|
||||
wireHovers(wrap);
|
||||
}
|
||||
|
||||
function vNested(stage){
|
||||
// build repo -> worktree -> [agents]
|
||||
const repos = {};
|
||||
AGENTS.forEach(a => { (repos[a.project] ??= {}); (repos[a.project][a.worktree] ??= []).push(a); });
|
||||
const rollup = list => list.slice().sort((x,y)=>URG[x.state]-URG[y.state])[0].state; // most-urgent child
|
||||
const byUrg = key => (a,b) => URG[key(a)]-URG[key(b)];
|
||||
|
||||
const repoEntries = Object.entries(repos)
|
||||
.map(([p,wts]) => { const all = Object.values(wts).flat(); return { p, wts, all, roll: rollup(all) }; })
|
||||
.sort((a,b) => URG[a.roll]-URG[b.roll] || a.p.localeCompare(b.p));
|
||||
|
||||
stage.innerHTML = `<div class="repogrid">` + repoEntries.map(({p,wts,all,roll}) => {
|
||||
const attn = all.filter(a=>a.state==='attention').length;
|
||||
const wtEntries = Object.entries(wts)
|
||||
.map(([w,list]) => ({ w, list, roll: rollup(list) }))
|
||||
.sort((a,b) => URG[a.roll]-URG[b.roll] || a.w.localeCompare(b.w));
|
||||
|
||||
const wtHTML = wtEntries.map(({w,list,roll}) => {
|
||||
const agents = list.slice().sort(byUrg(a=>a.state)).map(a => `
|
||||
<div class="acard ${a.state}" data-agent="${a.id}">
|
||||
<div class="aacc"></div>
|
||||
<div class="prov ${a.prov}" style="width:20px;height:20px;font-size:10px;border-radius:6px">${initials(a.prov)}</div>
|
||||
<div class="abody">
|
||||
<div class="arow"><span class="an">${a.name}</span>
|
||||
<span style="margin-left:auto" class="badge ${a.state}">${STATE_LABEL[a.state]}</span></div>
|
||||
<div class="at truncate">${a.ask ? '✋ '+escapeHTML(a.ask) : a.task}</div>
|
||||
<div class="am">${a.last}</div>
|
||||
</div>
|
||||
</div>`).join('');
|
||||
return `<div class="wtpanel">
|
||||
<div class="wthead"><span class="dot s-${roll} ${roll==='attention'?'pulse':''}"></span>
|
||||
<span class="wn">${w}</span>${list.length>1?`<span class="wc">${list.length} agents</span>`:''}</div>
|
||||
${agents}</div>`;
|
||||
}).join('');
|
||||
|
||||
return `<div class="repo">
|
||||
<div class="repohead"><span class="dot s-${roll} ${roll==='attention'?'pulse':''}"></span>
|
||||
<span class="rn">${p}</span>
|
||||
<span class="rmeta">${all.length} agents${attn?` · <span style="color:var(--st-attention);font-weight:600">${attn} need you</span>`:''}</span></div>
|
||||
${wtHTML}</div>`;
|
||||
}).join('') + `</div>`;
|
||||
wireHovers(stage);
|
||||
}
|
||||
|
||||
function vInbox(stage){
|
||||
const urgent = [...byState('attention'), ...byState('error')];
|
||||
const quiet = AGENTS.filter(a => !['attention','error'].includes(a.state))
|
||||
.sort((a,b)=>STATE_ORDER.indexOf(a.state)-STATE_ORDER.indexOf(b.state));
|
||||
const urgentHTML = urgent.length ? urgent.map(a=>{
|
||||
const isErr = a.state==='error';
|
||||
const reason = isErr
|
||||
? `<span class="lbl">Error</span>${escapeHTML(a.term.find(t=>t[0]==='err')?.[1]?.trim() || 'process exited — needs retry')}`
|
||||
: `<span class="lbl">Waiting</span>${escapeHTML(a.ask || 'needs your input')}`;
|
||||
const acts = isErr
|
||||
? `<button class="btn">View log</button><button class="btn primary">Retry</button>`
|
||||
: `<button class="btn">Open</button><button class="btn primary">Answer</button>`;
|
||||
return `<div class="irow ${a.state}" data-agent="${a.id}">
|
||||
<span class="dot s-${a.state} ${a.state==='attention'?'pulse':''}"></span>
|
||||
<div class="who"><div class="nm"><div class="prov ${a.prov}" style="width:18px;height:18px;font-size:9px;border-radius:5px">${initials(a.prov)}</div>${a.name}</div>
|
||||
<div class="wt">${a.project}/${a.worktree}</div></div>
|
||||
<div class="reason">${reason}</div>
|
||||
<div class="acts">${acts}</div></div>`;
|
||||
}).join('') : `<div class="emptyz">✓ Nothing needs you right now. ${AGENTS.length} agents running.</div>`;
|
||||
const quietHTML = quiet.map(a=>`<div class="qrow" data-agent="${a.id}">
|
||||
<span class="dot s-${a.state}"></span><span class="badge ${a.state}">${STATE_LABEL[a.state]}</span>
|
||||
<span style="font-weight:550">${a.name}</span><span class="wt">${a.worktree}</span>
|
||||
<span style="margin-left:auto" class="meta">${a.last}</span></div>`).join('');
|
||||
stage.innerHTML = `<div class="inbox">
|
||||
<p class="lead">${urgent.length} of ${AGENTS.length} agents need a human — sorted by urgency. Everything else is running fine below.</p>
|
||||
${urgentHTML}
|
||||
<div class="quiet"><h4>Running quietly · ${quiet.length}</h4>${quietHTML}</div>
|
||||
</div>`;
|
||||
wireHovers(stage);
|
||||
}
|
||||
|
||||
function vFocus(stage){
|
||||
let sel = AGENTS.find(a=>a.state==='attention') || AGENTS[0];
|
||||
const treeHTML = projects.map(p=>{
|
||||
const list = AGENTS.filter(a=>a.project===p);
|
||||
return `<div class="prow"><span>${p}</span><span style="margin-left:auto" class="meta">${list.length}</span></div>` +
|
||||
list.map(a=>`<div class="arow" data-agent="${a.id}" data-sel="${a.id}">
|
||||
<span class="dot s-${a.state} ${a.state==='attention'?'pulse':''}"></span>
|
||||
<span class="nm">${a.name}</span><span class="wt">${a.worktree}</span></div>`).join('');
|
||||
}).join('');
|
||||
stage.innerHTML = `<div class="focus"><div class="tree">${treeHTML}</div><div class="detail" id="detail"></div></div>`;
|
||||
const renderDetail = (a)=>{
|
||||
const scr = a.term.map(([cls,txt])=>`<div><span class="${cls}" style="color:inherit">${escapeHTML(txt)}</span></div>`).join('');
|
||||
document.getElementById('detail').innerHTML = `
|
||||
<div class="dhead"><div class="prov ${a.prov}">${initials(a.prov)}</div>
|
||||
<div><div class="name">${a.name}</div><div class="meta mono">${a.project}/${a.worktree}</div></div>
|
||||
<div style="margin-left:auto" class="badge ${a.state}">${STATE_LABEL[a.state]}</div></div>
|
||||
<div class="dbody"><div class="screenbig">${scr}<div><span class="dim">$ </span><span class="caret"></span></div></div>
|
||||
<div class="side">
|
||||
<div class="k">Task</div><div class="v">${a.task}</div>
|
||||
${a.ask?`<div class="k">Waiting on you</div><div class="v" style="color:var(--st-attention)">${escapeHTML(a.ask)}</div>`:''}
|
||||
<div class="k">Branch</div><div class="v mono" style="font-size:11px">${a.branch}</div>
|
||||
<div class="k">Elapsed</div><div class="v">${a.elapsed} · ${a.last}</div>
|
||||
<div style="margin-top:14px;display:flex;gap:8px"><button class="btn">Focus worktree</button><button class="btn primary">Open</button></div>
|
||||
</div></div>`;
|
||||
};
|
||||
renderDetail(sel);
|
||||
stage.querySelectorAll('.arow').forEach(row=>{
|
||||
row.addEventListener('click',()=>{ stage.querySelectorAll('.arow').forEach(r=>r.classList.remove('sel')); row.classList.add('sel');
|
||||
renderDetail(AGENTS.find(a=>a.id===row.dataset.sel)); });
|
||||
});
|
||||
stage.querySelector(`.arow[data-sel="${sel.id}"]`)?.classList.add('sel');
|
||||
wireHovers(stage);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Tabs / routing */
|
||||
/* ------------------------------------------------------------------ */
|
||||
const VARIANTS = [
|
||||
['nested','Repo › worktree › agent', vNested],
|
||||
['inbox','Needs you', vInbox],
|
||||
['gallery','Card gallery', vGallery],
|
||||
['board','Kanban board', vKanban],
|
||||
['mission','Mission control', vMissionControl],
|
||||
['wall','Terminal wall', vWall],
|
||||
['focus','Tree + focus', vFocus],
|
||||
['radial','Radial map', vRadial],
|
||||
];
|
||||
let current = 'nested';
|
||||
function renderTabs(){
|
||||
document.getElementById('tabs').innerHTML = VARIANTS.map(([k,l]) =>
|
||||
`<button data-k="${k}" class="${k===current?'active':''}">${l}</button>`).join('');
|
||||
document.querySelectorAll('#tabs button').forEach(b => b.addEventListener('click',()=>{ current=b.dataset.k; renderTabs(); renderStage(); }));
|
||||
}
|
||||
function renderStage(){
|
||||
pop.classList.remove('show'); clearInterval(streamTimer);
|
||||
const stage = document.getElementById('stage');
|
||||
VARIANTS.find(v=>v[0]===current)[2](stage);
|
||||
}
|
||||
document.getElementById('themeToggle').addEventListener('click',()=>{ document.documentElement.classList.toggle('dark'); if(current==='radial') renderStage(); });
|
||||
window.addEventListener('resize',()=>{ if(current==='radial') renderStage(); });
|
||||
|
||||
renderSummary(); renderTabs(); renderStage();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -239,6 +239,19 @@ export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
worker: {
|
||||
format: 'es'
|
||||
},
|
||||
build: {
|
||||
// Why: the pop-out dashboard is a second top-level window with its own
|
||||
// React root. It gets its own HTML entry so it can boot independently of
|
||||
// the main window while reusing the same preload/window.api. `index` must
|
||||
// stay listed — overriding input otherwise drops electron-vite's default
|
||||
// renderer entry.
|
||||
rollupOptions: {
|
||||
input: {
|
||||
index: resolve('src/renderer/index.html'),
|
||||
popout: resolve('src/renderer/popout.html')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -53,7 +53,8 @@ const REACT_ERROR_BOUNDARY_SURFACES = new Set<ReactErrorBoundaryReportArgs['surf
|
||||
'page',
|
||||
'modal',
|
||||
'overlay',
|
||||
'rich-markdown-editor'
|
||||
'rich-markdown-editor',
|
||||
'dashboard-popout'
|
||||
])
|
||||
|
||||
function stringField(value: unknown, maxLength: number): string | undefined {
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { DashboardSnapshot } from '../../shared/dashboard-snapshot'
|
||||
import { isDashboardRevealAgentArgs, isDashboardSnapshot } from './dashboard-payload-validation'
|
||||
|
||||
const SNAPSHOT = {
|
||||
generatedAt: 1_700_000_000_000,
|
||||
cards: [
|
||||
{
|
||||
paneKey: 'tab-1:leaf-1',
|
||||
ptyId: 'pty-1',
|
||||
agentType: 'codex',
|
||||
bucket: 'attention',
|
||||
dotState: 'waiting',
|
||||
task: 'Review the dashboard',
|
||||
lastUserMessage: 'Please review this',
|
||||
lastAgentMessage: 'I need a decision.',
|
||||
repoId: 'repo-1',
|
||||
worktreeId: 'worktree-1',
|
||||
tabId: 'tab-1',
|
||||
leafId: 'leaf-1',
|
||||
repoName: 'Orca',
|
||||
worktreeName: 'Dashboard',
|
||||
startedAt: 1_699_999_000_000,
|
||||
stateChangedAt: 1_699_999_500_000,
|
||||
unseen: true,
|
||||
askSummary: '{"question":"Proceed?"}'
|
||||
}
|
||||
]
|
||||
} satisfies DashboardSnapshot
|
||||
|
||||
describe('dashboard payload validation', () => {
|
||||
it('accepts a complete dashboard snapshot', () => {
|
||||
expect(isDashboardSnapshot(SNAPSHOT)).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects malformed or unbounded snapshot fields', () => {
|
||||
expect(isDashboardSnapshot({ ...SNAPSHOT, generatedAt: Number.NaN })).toBe(false)
|
||||
expect(
|
||||
isDashboardSnapshot({
|
||||
...SNAPSHOT,
|
||||
cards: [{ ...SNAPSHOT.cards[0], bucket: 'unexpected' }]
|
||||
})
|
||||
).toBe(false)
|
||||
expect(
|
||||
isDashboardSnapshot({
|
||||
...SNAPSHOT,
|
||||
cards: [{ ...SNAPSHOT.cards[0], lastAgentMessage: 'x'.repeat(8_001) }]
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('requires complete bounded reveal routing', () => {
|
||||
expect(
|
||||
isDashboardRevealAgentArgs({
|
||||
repoId: 'repo-1',
|
||||
worktreeId: 'worktree-1',
|
||||
tabId: 'tab-1',
|
||||
leafId: null
|
||||
})
|
||||
).toBe(true)
|
||||
expect(
|
||||
isDashboardRevealAgentArgs({ repoId: 'repo-1', worktreeId: 'worktree-1', tabId: '' })
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { DashboardRevealAgentArgs, DashboardSnapshot } from '../../shared/dashboard-snapshot'
|
||||
import {
|
||||
AGENT_STATUS_ASSISTANT_MESSAGE_MAX_LENGTH,
|
||||
AGENT_STATUS_INTERACTIVE_PROMPT_MAX_LENGTH,
|
||||
AGENT_STATUS_MAX_FIELD_LENGTH,
|
||||
AGENT_TYPE_MAX_LENGTH
|
||||
} from '../../shared/agent-status-types'
|
||||
|
||||
const MAX_DASHBOARD_CARDS = 1_000
|
||||
const MAX_ID_LENGTH = 4_096
|
||||
const MAX_LABEL_LENGTH = 1_024
|
||||
const DASHBOARD_BUCKETS = new Set(['attention', 'working', 'idle'])
|
||||
const DASHBOARD_DOT_STATES = new Set(['working', 'blocked', 'waiting', 'done', 'idle'])
|
||||
|
||||
function isBoundedString(value: unknown, maxLength: number, allowEmpty = false): value is string {
|
||||
return typeof value === 'string' && value.length <= maxLength && (allowEmpty || value.length > 0)
|
||||
}
|
||||
|
||||
function isOptionalBoundedString(value: unknown, maxLength: number): boolean {
|
||||
return value === undefined || isBoundedString(value, maxLength, true)
|
||||
}
|
||||
|
||||
function isFiniteNumber(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isFinite(value)
|
||||
}
|
||||
|
||||
export function isDashboardRevealAgentArgs(value: unknown): value is DashboardRevealAgentArgs {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
return false
|
||||
}
|
||||
const args = value as Record<string, unknown>
|
||||
return (
|
||||
isBoundedString(args.repoId, MAX_ID_LENGTH) &&
|
||||
isBoundedString(args.worktreeId, MAX_ID_LENGTH) &&
|
||||
isBoundedString(args.tabId, MAX_ID_LENGTH) &&
|
||||
(args.leafId === null || isBoundedString(args.leafId, MAX_ID_LENGTH))
|
||||
)
|
||||
}
|
||||
|
||||
export function isDashboardPaneKey(value: unknown): value is string {
|
||||
return isBoundedString(value, MAX_ID_LENGTH)
|
||||
}
|
||||
|
||||
export function isDashboardSnapshot(value: unknown): value is DashboardSnapshot {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
return false
|
||||
}
|
||||
const snapshot = value as Record<string, unknown>
|
||||
return (
|
||||
isFiniteNumber(snapshot.generatedAt) &&
|
||||
Array.isArray(snapshot.cards) &&
|
||||
snapshot.cards.length <= MAX_DASHBOARD_CARDS &&
|
||||
snapshot.cards.every(isDashboardCard)
|
||||
)
|
||||
}
|
||||
|
||||
function isDashboardCard(value: unknown): boolean {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
return false
|
||||
}
|
||||
const card = value as Record<string, unknown>
|
||||
return (
|
||||
isBoundedString(card.paneKey, MAX_ID_LENGTH) &&
|
||||
(card.ptyId === null || isBoundedString(card.ptyId, MAX_ID_LENGTH)) &&
|
||||
isBoundedString(card.agentType, AGENT_TYPE_MAX_LENGTH) &&
|
||||
typeof card.bucket === 'string' &&
|
||||
DASHBOARD_BUCKETS.has(card.bucket) &&
|
||||
typeof card.dotState === 'string' &&
|
||||
DASHBOARD_DOT_STATES.has(card.dotState) &&
|
||||
isBoundedString(card.task, AGENT_STATUS_MAX_FIELD_LENGTH, true) &&
|
||||
isOptionalBoundedString(card.lastUserMessage, AGENT_STATUS_MAX_FIELD_LENGTH) &&
|
||||
isOptionalBoundedString(card.lastAgentMessage, AGENT_STATUS_ASSISTANT_MESSAGE_MAX_LENGTH) &&
|
||||
isBoundedString(card.repoId, MAX_ID_LENGTH) &&
|
||||
isBoundedString(card.worktreeId, MAX_ID_LENGTH) &&
|
||||
isBoundedString(card.tabId, MAX_ID_LENGTH) &&
|
||||
(card.leafId === null || isBoundedString(card.leafId, MAX_ID_LENGTH)) &&
|
||||
isBoundedString(card.repoName, MAX_LABEL_LENGTH, true) &&
|
||||
isBoundedString(card.worktreeName, MAX_LABEL_LENGTH, true) &&
|
||||
isFiniteNumber(card.startedAt) &&
|
||||
isFiniteNumber(card.stateChangedAt) &&
|
||||
typeof card.unseen === 'boolean' &&
|
||||
isOptionalBoundedString(card.askSummary, AGENT_STATUS_INTERACTIVE_PROMPT_MAX_LENGTH)
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
handlers,
|
||||
ipcMainMock,
|
||||
appMock,
|
||||
createPopoutMock,
|
||||
closePopoutMock,
|
||||
getPopoutMock,
|
||||
isPopoutRendererMock,
|
||||
isTrustedUIRendererMock,
|
||||
getTrustedWindowMock,
|
||||
sendToTrustedMock,
|
||||
safelyRevealMock
|
||||
} = vi.hoisted(() => {
|
||||
const map = new Map<string, (...args: unknown[]) => unknown>()
|
||||
return {
|
||||
handlers: map,
|
||||
ipcMainMock: {
|
||||
removeHandler: vi.fn(),
|
||||
handle: (channel: string, fn: (...args: unknown[]) => unknown) => map.set(channel, fn)
|
||||
},
|
||||
appMock: { focus: vi.fn() },
|
||||
createPopoutMock: vi.fn(),
|
||||
closePopoutMock: vi.fn(),
|
||||
getPopoutMock: vi.fn((): unknown => null),
|
||||
isPopoutRendererMock: vi.fn((_sender: unknown) => false),
|
||||
isTrustedUIRendererMock: vi.fn((_sender: unknown) => false),
|
||||
getTrustedWindowMock: vi.fn((): unknown => null),
|
||||
sendToTrustedMock: vi.fn(),
|
||||
safelyRevealMock: vi.fn()
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('electron', () => ({ app: appMock, ipcMain: ipcMainMock }))
|
||||
vi.mock('../window/dashboard-popout-window', () => ({
|
||||
createOrFocusDashboardPopout: createPopoutMock,
|
||||
closeDashboardPopout: closePopoutMock,
|
||||
getDashboardPopoutWindow: getPopoutMock,
|
||||
isDashboardPopoutRenderer: isPopoutRendererMock,
|
||||
onDashboardPopoutOpenChanged: vi.fn()
|
||||
}))
|
||||
vi.mock('../window/focus-existing-window', () => ({ safelyRevealWindow: safelyRevealMock }))
|
||||
vi.mock('./ui', () => ({
|
||||
getTrustedUIRendererWindow: getTrustedWindowMock,
|
||||
isTrustedUIRenderer: isTrustedUIRendererMock,
|
||||
sendToTrustedUIRenderer: sendToTrustedMock
|
||||
}))
|
||||
|
||||
import { registerDashboardPopoutHandlers } from './dashboard-popout'
|
||||
|
||||
const mainSender = { id: 1, send: vi.fn() }
|
||||
const popoutSender = { id: 2, send: vi.fn() }
|
||||
const untrustedSender = { id: 3, send: vi.fn() }
|
||||
const SNAPSHOT = { generatedAt: 1, cards: [] }
|
||||
|
||||
function makeWindow(sender: typeof mainSender) {
|
||||
return {
|
||||
isDestroyed: () => false,
|
||||
webContents: sender
|
||||
}
|
||||
}
|
||||
|
||||
function makeStore(enabled = true) {
|
||||
let settingsListener:
|
||||
| ((updates: Record<string, unknown>, settings: Record<string, unknown>) => void)
|
||||
| null = null
|
||||
return {
|
||||
getSettings: vi.fn(() => ({ experimentalAgentDashboardPopout: enabled })),
|
||||
onSettingsChanged: vi.fn((listener) => {
|
||||
settingsListener = listener
|
||||
return vi.fn()
|
||||
}),
|
||||
fireSettingsChanged: (nextEnabled: boolean) =>
|
||||
settingsListener?.(
|
||||
{ experimentalAgentDashboardPopout: nextEnabled },
|
||||
{ experimentalAgentDashboardPopout: nextEnabled }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
describe('registerDashboardPopoutHandlers', () => {
|
||||
let store: ReturnType<typeof makeStore>
|
||||
|
||||
beforeEach(() => {
|
||||
handlers.clear()
|
||||
store = makeStore()
|
||||
isTrustedUIRendererMock.mockImplementation((sender) => sender === mainSender)
|
||||
isPopoutRendererMock.mockImplementation((sender) => sender === popoutSender)
|
||||
registerDashboardPopoutHandlers(store as never)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
getPopoutMock.mockReturnValue(null)
|
||||
getTrustedWindowMock.mockReturnValue(null)
|
||||
})
|
||||
|
||||
it('opens only for the trusted main renderer while the feature is enabled', () => {
|
||||
handlers.get('dashboardPopout:open')!({ sender: untrustedSender } as never)
|
||||
expect(createPopoutMock).not.toHaveBeenCalled()
|
||||
|
||||
store.getSettings.mockReturnValue({ experimentalAgentDashboardPopout: false })
|
||||
handlers.get('dashboardPopout:open')!({ sender: mainSender } as never)
|
||||
expect(createPopoutMock).not.toHaveBeenCalled()
|
||||
|
||||
store.getSettings.mockReturnValue({ experimentalAgentDashboardPopout: true })
|
||||
handlers.get('dashboardPopout:open')!({ sender: mainSender } as never)
|
||||
expect(createPopoutMock).toHaveBeenCalledWith(store)
|
||||
})
|
||||
|
||||
it('auto-closes the popout when the feature is disabled', () => {
|
||||
store.fireSettingsChanged(false)
|
||||
expect(closePopoutMock).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('caches and forwards only valid trusted snapshots', () => {
|
||||
const popout = makeWindow(popoutSender)
|
||||
getPopoutMock.mockReturnValue(popout)
|
||||
|
||||
handlers.get('dashboard:publishSnapshot')!({ sender: untrustedSender } as never, SNAPSHOT)
|
||||
handlers.get('dashboard:publishSnapshot')!({ sender: mainSender } as never, {
|
||||
generatedAt: Number.NaN,
|
||||
cards: []
|
||||
})
|
||||
expect(popoutSender.send).not.toHaveBeenCalled()
|
||||
|
||||
handlers.get('dashboard:publishSnapshot')!({ sender: mainSender } as never, SNAPSHOT)
|
||||
expect(popoutSender.send).toHaveBeenCalledWith('dashboard:snapshot', SNAPSHOT)
|
||||
})
|
||||
|
||||
it('replays the cached snapshot only to the popout and nudges only the trusted main renderer', () => {
|
||||
const popout = makeWindow(popoutSender)
|
||||
getPopoutMock.mockReturnValue(popout)
|
||||
handlers.get('dashboard:publishSnapshot')!({ sender: mainSender } as never, SNAPSHOT)
|
||||
|
||||
handlers.get('dashboard:requestSnapshot')!({ sender: untrustedSender } as never)
|
||||
expect(untrustedSender.send).not.toHaveBeenCalled()
|
||||
|
||||
handlers.get('dashboard:requestSnapshot')!({ sender: popoutSender } as never)
|
||||
expect(popoutSender.send).toHaveBeenCalledWith('dashboard:snapshot', SNAPSHOT)
|
||||
expect(sendToTrustedMock).toHaveBeenCalledWith('dashboard:snapshotRequested', null)
|
||||
})
|
||||
|
||||
it('reports open state only to the trusted main renderer', () => {
|
||||
getPopoutMock.mockReturnValue(makeWindow(popoutSender))
|
||||
expect(handlers.get('dashboard:getPopoutOpen')!({ sender: untrustedSender } as never)).toBe(
|
||||
false
|
||||
)
|
||||
expect(handlers.get('dashboard:getPopoutOpen')!({ sender: mainSender } as never)).toBe(true)
|
||||
})
|
||||
|
||||
it('relays valid seen acknowledgements from only the popout', () => {
|
||||
handlers.get('dashboardPopout:ackAgent')!({ sender: untrustedSender } as never, {
|
||||
paneKey: 'tab1:leaf1'
|
||||
})
|
||||
handlers.get('dashboardPopout:ackAgent')!({ sender: popoutSender } as never, { paneKey: '' })
|
||||
expect(sendToTrustedMock).not.toHaveBeenCalled()
|
||||
|
||||
handlers.get('dashboardPopout:ackAgent')!({ sender: popoutSender } as never, {
|
||||
paneKey: 'tab1:leaf1'
|
||||
})
|
||||
expect(sendToTrustedMock).toHaveBeenCalledWith('ui:ackDashboardAgent', 'tab1:leaf1')
|
||||
})
|
||||
|
||||
it('reveals an agent in only the trusted main window', () => {
|
||||
const main = makeWindow(mainSender)
|
||||
getTrustedWindowMock.mockReturnValue(main)
|
||||
const args = { repoId: 'r1', worktreeId: 'w1', tabId: 't1', leafId: 'l1' }
|
||||
|
||||
handlers.get('dashboardPopout:revealAgent')!({ sender: untrustedSender } as never, args)
|
||||
handlers.get('dashboardPopout:revealAgent')!({ sender: popoutSender } as never, {
|
||||
...args,
|
||||
tabId: ''
|
||||
})
|
||||
expect(safelyRevealMock).not.toHaveBeenCalled()
|
||||
|
||||
handlers.get('dashboardPopout:revealAgent')!({ sender: popoutSender } as never, args)
|
||||
expect(safelyRevealMock).toHaveBeenCalledWith(main)
|
||||
expect(mainSender.send).toHaveBeenCalledWith('ui:revealDashboardAgent', args)
|
||||
expect(appMock.focus).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,125 @@
|
||||
import { app, ipcMain } from 'electron'
|
||||
import type { Store } from '../persistence'
|
||||
import type { DashboardSnapshot } from '../../shared/dashboard-snapshot'
|
||||
import {
|
||||
createOrFocusDashboardPopout,
|
||||
closeDashboardPopout,
|
||||
getDashboardPopoutWindow,
|
||||
isDashboardPopoutRenderer,
|
||||
onDashboardPopoutOpenChanged
|
||||
} from '../window/dashboard-popout-window'
|
||||
import { safelyRevealWindow } from '../window/focus-existing-window'
|
||||
import { getTrustedUIRendererWindow, isTrustedUIRenderer, sendToTrustedUIRenderer } from './ui'
|
||||
import {
|
||||
isDashboardPaneKey,
|
||||
isDashboardRevealAgentArgs,
|
||||
isDashboardSnapshot
|
||||
} from './dashboard-payload-validation'
|
||||
|
||||
// The most recent snapshot the main renderer published, replayed to the popout
|
||||
// the instant it mounts so the board paints without waiting for the next tick.
|
||||
// Cleared on close so a reopened popout never flashes a previous session.
|
||||
let lastSnapshot: DashboardSnapshot | null = null
|
||||
|
||||
function isDashboardEnabled(store: Store): boolean {
|
||||
return store.getSettings().experimentalAgentDashboardPopout === true
|
||||
}
|
||||
|
||||
export function registerDashboardPopoutHandlers(store: Store): void {
|
||||
ipcMain.removeHandler('dashboardPopout:open')
|
||||
ipcMain.removeHandler('dashboard:publishSnapshot')
|
||||
ipcMain.removeHandler('dashboard:requestSnapshot')
|
||||
ipcMain.removeHandler('dashboard:getPopoutOpen')
|
||||
ipcMain.removeHandler('dashboardPopout:revealAgent')
|
||||
ipcMain.removeHandler('dashboardPopout:ackAgent')
|
||||
|
||||
onDashboardPopoutOpenChanged((open) => {
|
||||
if (!open) {
|
||||
lastSnapshot = null
|
||||
}
|
||||
})
|
||||
store.onSettingsChanged((updates, settings) => {
|
||||
if (
|
||||
'experimentalAgentDashboardPopout' in updates &&
|
||||
settings.experimentalAgentDashboardPopout !== true
|
||||
) {
|
||||
lastSnapshot = null
|
||||
closeDashboardPopout()
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle('dashboardPopout:open', (event): void => {
|
||||
if (!isTrustedUIRenderer(event.sender) || !isDashboardEnabled(store)) {
|
||||
return
|
||||
}
|
||||
createOrFocusDashboardPopout(store)
|
||||
})
|
||||
|
||||
// Relay: the main renderer publishes derived snapshots; forward to the popout.
|
||||
ipcMain.handle('dashboard:publishSnapshot', (event, snapshot: unknown): void => {
|
||||
if (
|
||||
!isTrustedUIRenderer(event.sender) ||
|
||||
!isDashboardEnabled(store) ||
|
||||
!isDashboardSnapshot(snapshot)
|
||||
) {
|
||||
return
|
||||
}
|
||||
lastSnapshot = snapshot
|
||||
getDashboardPopoutWindow()?.webContents.send('dashboard:snapshot', snapshot)
|
||||
})
|
||||
|
||||
// The popout asks for a snapshot on mount: replay the cache immediately, then
|
||||
// nudge the main renderer to publish a fresh one.
|
||||
ipcMain.handle('dashboard:requestSnapshot', (event): void => {
|
||||
if (!isDashboardPopoutRenderer(event.sender) || !isDashboardEnabled(store)) {
|
||||
return
|
||||
}
|
||||
if (lastSnapshot) {
|
||||
event.sender.send('dashboard:snapshot', lastSnapshot)
|
||||
}
|
||||
sendToTrustedUIRenderer('dashboard:snapshotRequested', null)
|
||||
})
|
||||
|
||||
ipcMain.handle('dashboard:getPopoutOpen', (event): boolean =>
|
||||
isTrustedUIRenderer(event.sender) && isDashboardEnabled(store)
|
||||
? getDashboardPopoutWindow() !== null
|
||||
: false
|
||||
)
|
||||
|
||||
// Seen-sync: opening a card's terminal dialog acknowledges the agent in the
|
||||
// main renderer's store — the same ack that mutes its sidebar row.
|
||||
ipcMain.handle('dashboardPopout:ackAgent', (event, args: unknown): void => {
|
||||
if (
|
||||
!isDashboardPopoutRenderer(event.sender) ||
|
||||
!isDashboardEnabled(store) ||
|
||||
!args ||
|
||||
typeof args !== 'object' ||
|
||||
!isDashboardPaneKey((args as { paneKey?: unknown }).paneKey)
|
||||
) {
|
||||
return
|
||||
}
|
||||
sendToTrustedUIRenderer('ui:ackDashboardAgent', (args as { paneKey: string }).paneKey)
|
||||
})
|
||||
|
||||
// Click-to-focus: raise the main window and route it to the agent's pane.
|
||||
ipcMain.handle('dashboardPopout:revealAgent', (event, args: unknown): void => {
|
||||
if (
|
||||
!isDashboardPopoutRenderer(event.sender) ||
|
||||
!isDashboardEnabled(store) ||
|
||||
!isDashboardRevealAgentArgs(args)
|
||||
) {
|
||||
return
|
||||
}
|
||||
const mainWindow = getTrustedUIRendererWindow()
|
||||
if (!mainWindow) {
|
||||
return
|
||||
}
|
||||
safelyRevealWindow(mainWindow)
|
||||
mainWindow.webContents.send('ui:revealDashboardAgent', args)
|
||||
try {
|
||||
app.focus({ steal: true })
|
||||
} catch {
|
||||
// Best-effort; the per-window focus above may still bring it forward.
|
||||
}
|
||||
})
|
||||
}
|
||||
+1
-1
@@ -1605,7 +1605,7 @@ export function registerPtyHandlers(
|
||||
const backgroundedDeliverySyncByPty = new Map<string, boolean>()
|
||||
function syncPtyBackgroundedDelivery(id: string, caller: string): void {
|
||||
const background =
|
||||
rendererPtyIsKnownHidden(id) && !(runtime?.hasRemoteTerminalViewSubscriber(id) ?? false)
|
||||
rendererPtyIsKnownHidden(id) && !(runtime?.hasRawTerminalViewSubscriber?.(id) ?? false)
|
||||
if ((backgroundedDeliverySyncByPty.get(id) ?? false) === background) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -54,6 +54,8 @@ const {
|
||||
registerHostedReviewHandlersMock,
|
||||
registerExportHandlersMock,
|
||||
registerOnboardingHandlersMock,
|
||||
registerDashboardPopoutHandlersMock,
|
||||
registerTerminalPreviewHandlersMock,
|
||||
registerSpeechHandlersMock,
|
||||
registerSkillsHandlersMock,
|
||||
registerWorkspaceSpaceHandlersMock,
|
||||
@@ -116,6 +118,8 @@ const {
|
||||
registerHostedReviewHandlersMock: vi.fn(),
|
||||
registerExportHandlersMock: vi.fn(),
|
||||
registerOnboardingHandlersMock: vi.fn(),
|
||||
registerDashboardPopoutHandlersMock: vi.fn(),
|
||||
registerTerminalPreviewHandlersMock: vi.fn(),
|
||||
registerSpeechHandlersMock: vi.fn(),
|
||||
registerSkillsHandlersMock: vi.fn(),
|
||||
registerWorkspaceSpaceHandlersMock: vi.fn(),
|
||||
@@ -144,6 +148,14 @@ vi.mock('./onboarding', () => ({
|
||||
registerOnboardingHandlers: registerOnboardingHandlersMock
|
||||
}))
|
||||
|
||||
vi.mock('./dashboard-popout', () => ({
|
||||
registerDashboardPopoutHandlers: registerDashboardPopoutHandlersMock
|
||||
}))
|
||||
|
||||
vi.mock('./terminal-preview', () => ({
|
||||
registerTerminalPreviewHandlers: registerTerminalPreviewHandlersMock
|
||||
}))
|
||||
|
||||
vi.mock('./speech', () => ({
|
||||
registerSpeechHandlers: registerSpeechHandlersMock
|
||||
}))
|
||||
@@ -417,6 +429,8 @@ describe('registerCoreHandlers', () => {
|
||||
registerGitLabHandlersMock.mockReset()
|
||||
registerHostedReviewHandlersMock.mockReset()
|
||||
registerExportHandlersMock.mockReset()
|
||||
registerDashboardPopoutHandlersMock.mockReset()
|
||||
registerTerminalPreviewHandlersMock.mockReset()
|
||||
registerSpeechHandlersMock.mockReset()
|
||||
registerSkillsHandlersMock.mockReset()
|
||||
registerWorkspaceSpaceHandlersMock.mockReset()
|
||||
@@ -493,6 +507,8 @@ describe('registerCoreHandlers', () => {
|
||||
expect(registerNotificationHandlersMock).toHaveBeenCalledWith(store, runtime)
|
||||
expect(registerDeveloperPermissionHandlersMock).toHaveBeenCalled()
|
||||
expect(registerComputerUsePermissionHandlersMock).toHaveBeenCalled()
|
||||
expect(registerDashboardPopoutHandlersMock).toHaveBeenCalledWith(store)
|
||||
expect(registerTerminalPreviewHandlersMock).toHaveBeenCalledWith(runtime)
|
||||
expect(registerSettingsHandlersMock).toHaveBeenCalledWith(store, agentAwakeService)
|
||||
expect(registerSkillsHandlersMock).toHaveBeenCalledWith(store)
|
||||
expect(registerWorkspaceSpaceHandlersMock).toHaveBeenCalledWith(store)
|
||||
|
||||
@@ -30,6 +30,8 @@ import { registerNativeChatHandlers } from './native-chat'
|
||||
import { registerNotificationHandlers } from './notifications'
|
||||
import { registerNotebookHandlers } from './notebook'
|
||||
import { registerOnboardingHandlers } from './onboarding'
|
||||
import { registerDashboardPopoutHandlers } from './dashboard-popout'
|
||||
import { registerTerminalPreviewHandlers } from './terminal-preview'
|
||||
import { registerDeveloperPermissionHandlers } from './developer-permissions'
|
||||
import { registerComputerUsePermissionHandlers } from './computer-use-permissions'
|
||||
import { setTrustedBrowserRendererWebContentsId, setAgentBrowserBridgeRef } from './browser'
|
||||
@@ -155,6 +157,8 @@ export function registerCoreHandlers(
|
||||
registerNotificationHandlers(store, runtime)
|
||||
registerNotebookHandlers(store)
|
||||
registerOnboardingHandlers(store)
|
||||
registerDashboardPopoutHandlers(store)
|
||||
registerTerminalPreviewHandlers(runtime)
|
||||
registerDeveloperPermissionHandlers()
|
||||
// Why: diagnostics handlers are wired alongside telemetry but the two
|
||||
// lanes never share a code path — `ipc/diagnostics.ts` imports only from
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
import type { WebContents } from 'electron'
|
||||
import { iterateTerminalInputChunks } from '../../shared/terminal-input'
|
||||
import type { TerminalPreviewDataPayload } from '../../shared/terminal-preview'
|
||||
|
||||
const OUTPUT_BATCH_MS = 5
|
||||
export const TERMINAL_PREVIEW_OUTPUT_BATCH_MAX_BYTES = 64 * 1024
|
||||
const OUTPUT_IN_FLIGHT_MAX_BYTES = 512 * 1024
|
||||
const OUTPUT_PENDING_MAX_BYTES = 256 * 1024
|
||||
const INITIAL_PENDING_MAX_BYTES = 256 * 1024
|
||||
|
||||
export type TerminalPreviewOutputMeta = {
|
||||
seq?: number
|
||||
rawLength?: number
|
||||
transformed?: boolean
|
||||
}
|
||||
|
||||
type PendingOutput = { data: string; bytes: number; meta?: TerminalPreviewOutputMeta }
|
||||
|
||||
function outputAfterSnapshotSeq(output: PendingOutput, snapshotSeq?: number): string | null {
|
||||
if (
|
||||
typeof snapshotSeq !== 'number' ||
|
||||
typeof output.meta?.seq !== 'number' ||
|
||||
typeof output.meta.rawLength !== 'number'
|
||||
) {
|
||||
return output.data
|
||||
}
|
||||
if (output.meta.seq <= snapshotSeq) {
|
||||
return null
|
||||
}
|
||||
const startSeq = output.meta.seq - output.meta.rawLength
|
||||
if (startSeq >= snapshotSeq || output.meta.transformed === true) {
|
||||
return output.data
|
||||
}
|
||||
return output.data.slice(snapshotSeq - startSeq)
|
||||
}
|
||||
|
||||
/** Owns one preview's bounded snapshot/live output queue and acknowledgements. */
|
||||
export class TerminalPreviewOutputStream {
|
||||
private bufferingSnapshot = true
|
||||
private initialPending: PendingOutput[] = []
|
||||
private initialPendingBytes = 0
|
||||
private initialPendingOverflowed = false
|
||||
private batchChunks: string[] = []
|
||||
private batchBytes = 0
|
||||
private batchTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private inFlightBytes = 0
|
||||
private pendingBatches: { data: string; bytes: number }[] = []
|
||||
private pendingBatchBytes = 0
|
||||
private resyncPending = false
|
||||
private awaitingReconnect = false
|
||||
private unsubscribeData: () => void = () => {}
|
||||
private isDisposed = false
|
||||
|
||||
constructor(
|
||||
readonly contents: WebContents,
|
||||
readonly ptyId: string,
|
||||
private readonly releaseRawView: () => void,
|
||||
private readonly onDispose: (stream: TerminalPreviewOutputStream) => void
|
||||
) {}
|
||||
|
||||
get disposed(): boolean {
|
||||
return this.isDisposed
|
||||
}
|
||||
|
||||
setDataSubscription(unsubscribe: () => void): void {
|
||||
this.unsubscribeData = unsubscribe
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.isDisposed) {
|
||||
return
|
||||
}
|
||||
this.isDisposed = true
|
||||
if (this.batchTimer) {
|
||||
clearTimeout(this.batchTimer)
|
||||
this.batchTimer = null
|
||||
}
|
||||
this.unsubscribeData()
|
||||
this.releaseRawView()
|
||||
this.onDispose(this)
|
||||
}
|
||||
|
||||
append(data: string, meta?: TerminalPreviewOutputMeta): void {
|
||||
if (this.bufferingSnapshot) {
|
||||
this.appendInitial(data, meta)
|
||||
} else {
|
||||
this.appendLive(data)
|
||||
}
|
||||
}
|
||||
|
||||
consumeInitialOverflow(): boolean {
|
||||
if (!this.initialPendingOverflowed) {
|
||||
return false
|
||||
}
|
||||
this.initialPending = []
|
||||
this.initialPendingBytes = 0
|
||||
this.initialPendingOverflowed = false
|
||||
return true
|
||||
}
|
||||
|
||||
completeSnapshot(snapshotSeq?: number): string[] {
|
||||
const replay = this.initialPending.flatMap((output) => {
|
||||
const uncovered = outputAfterSnapshotSeq(output, snapshotSeq)
|
||||
return uncovered ? [uncovered] : []
|
||||
})
|
||||
this.initialPending = []
|
||||
this.initialPendingBytes = 0
|
||||
this.bufferingSnapshot = false
|
||||
return replay
|
||||
}
|
||||
|
||||
pauseForReconnect(): void {
|
||||
if (this.batchTimer) {
|
||||
clearTimeout(this.batchTimer)
|
||||
this.batchTimer = null
|
||||
}
|
||||
this.batchChunks = []
|
||||
this.batchBytes = 0
|
||||
this.pendingBatches = []
|
||||
this.pendingBatchBytes = 0
|
||||
this.awaitingReconnect = true
|
||||
}
|
||||
|
||||
acknowledge(bytes: number): void {
|
||||
this.inFlightBytes = Math.max(
|
||||
0,
|
||||
this.inFlightBytes - Math.min(this.inFlightBytes, Math.floor(bytes))
|
||||
)
|
||||
this.maybeDrain()
|
||||
}
|
||||
|
||||
private send(payload: TerminalPreviewDataPayload): boolean {
|
||||
if (this.isDisposed || this.contents.isDestroyed()) {
|
||||
this.dispose()
|
||||
return false
|
||||
}
|
||||
try {
|
||||
this.contents.send('terminalPreview:data', payload)
|
||||
return true
|
||||
} catch {
|
||||
this.dispose()
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private maybeDrain(): void {
|
||||
if (this.isDisposed || this.awaitingReconnect) {
|
||||
return
|
||||
}
|
||||
if (this.resyncPending) {
|
||||
if (this.inFlightBytes === 0) {
|
||||
this.resyncPending = false
|
||||
this.awaitingReconnect = true
|
||||
this.send({ type: 'resync', ptyId: this.ptyId })
|
||||
}
|
||||
return
|
||||
}
|
||||
while (this.pendingBatches.length > 0) {
|
||||
const next = this.pendingBatches[0]!
|
||||
if (this.inFlightBytes > 0 && this.inFlightBytes + next.bytes > OUTPUT_IN_FLIGHT_MAX_BYTES) {
|
||||
break
|
||||
}
|
||||
this.pendingBatches.shift()
|
||||
this.pendingBatchBytes -= next.bytes
|
||||
if (this.send({ type: 'data', ptyId: this.ptyId, data: next.data, bytes: next.bytes })) {
|
||||
this.inFlightBytes += next.bytes
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private queueBatch(data: string, bytes: number): void {
|
||||
if (this.isDisposed || this.awaitingReconnect || this.resyncPending) {
|
||||
return
|
||||
}
|
||||
if (
|
||||
this.pendingBatches.length === 0 &&
|
||||
(this.inFlightBytes === 0 || this.inFlightBytes + bytes <= OUTPUT_IN_FLIGHT_MAX_BYTES)
|
||||
) {
|
||||
if (this.send({ type: 'data', ptyId: this.ptyId, data, bytes })) {
|
||||
this.inFlightBytes += bytes
|
||||
}
|
||||
return
|
||||
}
|
||||
this.pendingBatches.push({ data, bytes })
|
||||
this.pendingBatchBytes += bytes
|
||||
if (this.pendingBatchBytes > OUTPUT_PENDING_MAX_BYTES) {
|
||||
// Why: a stuck renderer heals from a fresh authoritative snapshot instead of retaining output without bound.
|
||||
this.pendingBatches = []
|
||||
this.pendingBatchBytes = 0
|
||||
this.resyncPending = true
|
||||
}
|
||||
}
|
||||
|
||||
private flushBatch(): void {
|
||||
if (this.batchTimer) {
|
||||
clearTimeout(this.batchTimer)
|
||||
this.batchTimer = null
|
||||
}
|
||||
if (this.batchChunks.length === 0) {
|
||||
return
|
||||
}
|
||||
const data = this.batchChunks.length === 1 ? this.batchChunks[0]! : this.batchChunks.join('')
|
||||
const bytes = this.batchBytes
|
||||
this.batchChunks = []
|
||||
this.batchBytes = 0
|
||||
this.queueBatch(data, bytes)
|
||||
}
|
||||
|
||||
private appendLive(data: string): void {
|
||||
for (const chunk of iterateTerminalInputChunks(data, TERMINAL_PREVIEW_OUTPUT_BATCH_MAX_BYTES)) {
|
||||
const bytes = Buffer.byteLength(chunk, 'utf8')
|
||||
if (
|
||||
this.batchBytes > 0 &&
|
||||
this.batchBytes + bytes > TERMINAL_PREVIEW_OUTPUT_BATCH_MAX_BYTES
|
||||
) {
|
||||
this.flushBatch()
|
||||
}
|
||||
this.batchChunks.push(chunk)
|
||||
this.batchBytes += bytes
|
||||
if (this.batchBytes >= TERMINAL_PREVIEW_OUTPUT_BATCH_MAX_BYTES) {
|
||||
this.flushBatch()
|
||||
} else if (!this.batchTimer) {
|
||||
this.batchTimer = setTimeout(() => this.flushBatch(), OUTPUT_BATCH_MS)
|
||||
this.batchTimer.unref?.()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private appendInitial(data: string, meta?: TerminalPreviewOutputMeta): void {
|
||||
const bytes = Buffer.byteLength(data, 'utf8')
|
||||
this.initialPending.push({ data, bytes, meta })
|
||||
this.initialPendingBytes += bytes
|
||||
while (this.initialPendingBytes > INITIAL_PENDING_MAX_BYTES && this.initialPending.length > 0) {
|
||||
this.initialPendingBytes -= this.initialPending.shift()!.bytes
|
||||
this.initialPendingOverflowed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { handlers, ipcMainMock, isDashboardPopoutRendererMock } = vi.hoisted(() => {
|
||||
const map = new Map<string, (...args: unknown[]) => unknown>()
|
||||
return {
|
||||
handlers: map,
|
||||
ipcMainMock: {
|
||||
removeHandler: vi.fn(),
|
||||
handle: (channel: string, fn: (...args: unknown[]) => unknown) => map.set(channel, fn)
|
||||
},
|
||||
isDashboardPopoutRendererMock: vi.fn(() => true)
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('electron', () => ({ ipcMain: ipcMainMock }))
|
||||
vi.mock('../window/dashboard-popout-window', () => ({
|
||||
isDashboardPopoutRenderer: isDashboardPopoutRendererMock
|
||||
}))
|
||||
|
||||
import { registerTerminalPreviewHandlers } from './terminal-preview'
|
||||
|
||||
type OutputMeta = { seq?: number; rawLength?: number; transformed?: boolean }
|
||||
type Listener = (data: string, meta?: OutputMeta) => void
|
||||
|
||||
function makeRuntime() {
|
||||
const listeners: Listener[] = []
|
||||
const unsubscribe = vi.fn()
|
||||
const releaseRawView = vi.fn()
|
||||
return {
|
||||
listeners,
|
||||
unsubscribe,
|
||||
releaseRawView,
|
||||
serializeTerminalBuffer: vi.fn(
|
||||
async (): Promise<{ data: string; cols: number; rows: number; seq: number } | null> => ({
|
||||
data: 'screen',
|
||||
cols: 80,
|
||||
rows: 20,
|
||||
seq: 5
|
||||
})
|
||||
),
|
||||
subscribeToTerminalData: vi.fn((_ptyId: string, listener: Listener) => {
|
||||
listeners.push(listener)
|
||||
return unsubscribe
|
||||
}),
|
||||
registerRawTerminalViewSubscriber: vi.fn(() => releaseRawView),
|
||||
writeTerminalPreviewInput: vi.fn(async () => true)
|
||||
}
|
||||
}
|
||||
|
||||
function makeSender(id = 1) {
|
||||
const destroyedListeners: (() => void)[] = []
|
||||
return {
|
||||
id,
|
||||
isDestroyed: () => false,
|
||||
send: vi.fn(),
|
||||
once: (event: string, cb: () => void) => {
|
||||
if (event === 'destroyed') {
|
||||
destroyedListeners.push(cb)
|
||||
}
|
||||
},
|
||||
fireDestroyed: () => destroyedListeners.forEach((cb) => cb())
|
||||
}
|
||||
}
|
||||
|
||||
function eventFor(sender: ReturnType<typeof makeSender>) {
|
||||
return { sender } as never
|
||||
}
|
||||
|
||||
describe('registerTerminalPreviewHandlers', () => {
|
||||
beforeEach(() => {
|
||||
handlers.clear()
|
||||
isDashboardPopoutRendererMock.mockReturnValue(true)
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('subscribes before snapshot acquisition and replays only bytes after its sequence', async () => {
|
||||
const runtime = makeRuntime()
|
||||
let resolveSnapshot!: (snapshot: {
|
||||
data: string
|
||||
cols: number
|
||||
rows: number
|
||||
seq: number
|
||||
}) => void
|
||||
runtime.serializeTerminalBuffer.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
resolveSnapshot = resolve
|
||||
})
|
||||
)
|
||||
registerTerminalPreviewHandlers(runtime as never)
|
||||
const sender = makeSender()
|
||||
|
||||
const resultPromise = handlers.get('terminalPreview:connect')!(eventFor(sender), {
|
||||
ptyId: 'p1',
|
||||
opts: { scrollbackRows: 24 }
|
||||
}) as Promise<unknown>
|
||||
|
||||
expect(runtime.subscribeToTerminalData).toHaveBeenCalledBefore(runtime.serializeTerminalBuffer)
|
||||
runtime.listeners[0]!('abc', { seq: 7, rawLength: 3 })
|
||||
resolveSnapshot({ data: 'screen', cols: 80, rows: 20, seq: 6 })
|
||||
|
||||
await expect(resultPromise).resolves.toEqual({
|
||||
snapshot: { data: 'screen', cols: 80, rows: 20, seq: 6 },
|
||||
replay: ['c']
|
||||
})
|
||||
expect(runtime.registerRawTerminalViewSubscriber).toHaveBeenCalledWith('p1')
|
||||
})
|
||||
|
||||
it('coalesces live chunks before crossing IPC and releases them with acknowledgements', async () => {
|
||||
vi.useFakeTimers()
|
||||
const runtime = makeRuntime()
|
||||
registerTerminalPreviewHandlers(runtime as never)
|
||||
const sender = makeSender()
|
||||
await handlers.get('terminalPreview:connect')!(eventFor(sender), { ptyId: 'p1' })
|
||||
|
||||
runtime.listeners[0]!('a')
|
||||
runtime.listeners[0]!('b')
|
||||
expect(sender.send).not.toHaveBeenCalled()
|
||||
await vi.advanceTimersByTimeAsync(5)
|
||||
expect(sender.send).toHaveBeenCalledTimes(1)
|
||||
expect(sender.send).toHaveBeenCalledWith('terminalPreview:data', {
|
||||
type: 'data',
|
||||
ptyId: 'p1',
|
||||
data: 'ab',
|
||||
bytes: 2
|
||||
})
|
||||
|
||||
handlers.get('terminalPreview:ack')!(eventFor(sender), { ptyId: 'p1', bytes: 2 })
|
||||
expect(sender.send).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('bounds an unresponsive renderer and requests a snapshot resync after prior writes drain', async () => {
|
||||
const runtime = makeRuntime()
|
||||
registerTerminalPreviewHandlers(runtime as never)
|
||||
const sender = makeSender()
|
||||
await handlers.get('terminalPreview:connect')!(eventFor(sender), { ptyId: 'p1' })
|
||||
|
||||
const chunk = 'x'.repeat(64 * 1024)
|
||||
for (let index = 0; index < 13; index++) {
|
||||
runtime.listeners[0]!(chunk)
|
||||
}
|
||||
const dataSends = sender.send.mock.calls.filter(([, payload]) => payload.type === 'data')
|
||||
expect(dataSends).toHaveLength(8)
|
||||
|
||||
for (let index = 0; index < 8; index++) {
|
||||
handlers.get('terminalPreview:ack')!(eventFor(sender), {
|
||||
ptyId: 'p1',
|
||||
bytes: 64 * 1024
|
||||
})
|
||||
}
|
||||
expect(sender.send).toHaveBeenLastCalledWith('terminalPreview:data', {
|
||||
type: 'resync',
|
||||
ptyId: 'p1'
|
||||
})
|
||||
})
|
||||
|
||||
it('never overshoots the in-flight byte budget with partial batches', async () => {
|
||||
vi.useFakeTimers()
|
||||
const runtime = makeRuntime()
|
||||
registerTerminalPreviewHandlers(runtime as never)
|
||||
const sender = makeSender()
|
||||
await handlers.get('terminalPreview:connect')!(eventFor(sender), { ptyId: 'p1' })
|
||||
|
||||
const fullChunk = 'x'.repeat(64 * 1024)
|
||||
for (let index = 0; index < 7; index++) {
|
||||
runtime.listeners[0]!(fullChunk)
|
||||
}
|
||||
runtime.listeners[0]!('a'.repeat(40 * 1024))
|
||||
await vi.advanceTimersByTimeAsync(5)
|
||||
runtime.listeners[0]!('b'.repeat(40 * 1024))
|
||||
await vi.advanceTimersByTimeAsync(5)
|
||||
expect(sender.send).toHaveBeenCalledTimes(8)
|
||||
|
||||
handlers.get('terminalPreview:ack')!(eventFor(sender), {
|
||||
ptyId: 'p1',
|
||||
bytes: 64 * 1024
|
||||
})
|
||||
expect(sender.send).toHaveBeenCalledTimes(9)
|
||||
})
|
||||
|
||||
it('fails safe to another resync when output overflows both snapshot captures', async () => {
|
||||
const runtime = makeRuntime()
|
||||
const snapshotResolvers: ((snapshot: {
|
||||
data: string
|
||||
cols: number
|
||||
rows: number
|
||||
seq: number
|
||||
}) => void)[] = []
|
||||
runtime.serializeTerminalBuffer.mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
snapshotResolvers.push(resolve)
|
||||
})
|
||||
)
|
||||
registerTerminalPreviewHandlers(runtime as never)
|
||||
const sender = makeSender()
|
||||
|
||||
const resultPromise = handlers.get('terminalPreview:connect')!(eventFor(sender), {
|
||||
ptyId: 'p1'
|
||||
}) as Promise<unknown>
|
||||
const chunk = 'x'.repeat(64 * 1024)
|
||||
for (let index = 0; index < 5; index++) {
|
||||
runtime.listeners[0]!(chunk)
|
||||
}
|
||||
snapshotResolvers[0]!({ data: 'first', cols: 80, rows: 20, seq: 1 })
|
||||
await vi.waitFor(() => expect(snapshotResolvers).toHaveLength(2))
|
||||
for (let index = 0; index < 5; index++) {
|
||||
runtime.listeners[0]!(chunk)
|
||||
}
|
||||
snapshotResolvers[1]!({ data: 'second', cols: 80, rows: 20, seq: 2 })
|
||||
|
||||
await expect(resultPromise).resolves.toEqual({
|
||||
snapshot: { data: 'second', cols: 80, rows: 20, seq: 2 },
|
||||
replay: [],
|
||||
resyncRequired: true
|
||||
})
|
||||
runtime.listeners[0]!('held until reconnect')
|
||||
expect(sender.send).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('releases output and raw-view presence on unsubscribe and sender destruction', async () => {
|
||||
const runtime = makeRuntime()
|
||||
registerTerminalPreviewHandlers(runtime as never)
|
||||
const sender = makeSender()
|
||||
await handlers.get('terminalPreview:connect')!(eventFor(sender), { ptyId: 'p1' })
|
||||
handlers.get('terminalPreview:unsubscribe')!(eventFor(sender), { ptyId: 'p1' })
|
||||
expect(runtime.unsubscribe).toHaveBeenCalledTimes(1)
|
||||
expect(runtime.releaseRawView).toHaveBeenCalledTimes(1)
|
||||
|
||||
await handlers.get('terminalPreview:connect')!(eventFor(sender), { ptyId: 'p2' })
|
||||
sender.fireDestroyed()
|
||||
expect(runtime.unsubscribe).toHaveBeenCalledTimes(2)
|
||||
expect(runtime.releaseRawView).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('releases output and raw-view presence when no snapshot exists', async () => {
|
||||
const runtime = makeRuntime()
|
||||
runtime.serializeTerminalBuffer.mockResolvedValueOnce(null)
|
||||
registerTerminalPreviewHandlers(runtime as never)
|
||||
const sender = makeSender()
|
||||
|
||||
await expect(
|
||||
handlers.get('terminalPreview:connect')!(eventFor(sender), { ptyId: 'missing' })
|
||||
).resolves.toEqual({ snapshot: null, replay: [] })
|
||||
expect(runtime.unsubscribe).toHaveBeenCalledTimes(1)
|
||||
expect(runtime.releaseRawView).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('rejects non-dashboard senders on every preview channel', async () => {
|
||||
const runtime = makeRuntime()
|
||||
registerTerminalPreviewHandlers(runtime as never)
|
||||
const sender = makeSender()
|
||||
isDashboardPopoutRendererMock.mockReturnValue(false)
|
||||
|
||||
await expect(
|
||||
handlers.get('terminalPreview:connect')!(eventFor(sender), { ptyId: 'p1' })
|
||||
).resolves.toEqual({ snapshot: null, replay: [] })
|
||||
await expect(
|
||||
handlers.get('terminalPreview:input')!(eventFor(sender), { ptyId: 'p1', data: 'x' })
|
||||
).resolves.toBe(false)
|
||||
handlers.get('terminalPreview:ack')!(eventFor(sender), { ptyId: 'p1', bytes: 1 })
|
||||
handlers.get('terminalPreview:unsubscribe')!(eventFor(sender), { ptyId: 'p1' })
|
||||
|
||||
expect(runtime.serializeTerminalBuffer).not.toHaveBeenCalled()
|
||||
expect(runtime.subscribeToTerminalData).not.toHaveBeenCalled()
|
||||
expect(runtime.writeTerminalPreviewInput).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('validates input before routing it to the runtime', async () => {
|
||||
const runtime = makeRuntime()
|
||||
registerTerminalPreviewHandlers(runtime as never)
|
||||
const sender = makeSender()
|
||||
|
||||
await expect(
|
||||
handlers.get('terminalPreview:input')!(eventFor(sender), { ptyId: 'p1', data: 'ls\r' })
|
||||
).resolves.toBe(true)
|
||||
expect(runtime.writeTerminalPreviewInput).toHaveBeenCalledWith('p1', 'ls\r')
|
||||
|
||||
await expect(
|
||||
handlers.get('terminalPreview:input')!(eventFor(sender), { ptyId: '', data: 'x' })
|
||||
).resolves.toBe(false)
|
||||
await expect(
|
||||
handlers.get('terminalPreview:input')!(eventFor(sender), {
|
||||
ptyId: 'x'.repeat(4097),
|
||||
data: 'x'
|
||||
})
|
||||
).resolves.toBe(false)
|
||||
expect(runtime.writeTerminalPreviewInput).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,155 @@
|
||||
import { ipcMain, type WebContents } from 'electron'
|
||||
import type {
|
||||
TerminalPreviewConnectResult,
|
||||
TerminalPreviewSnapshot
|
||||
} from '../../shared/terminal-preview'
|
||||
import type { OrcaRuntimeService } from '../runtime/orca-runtime'
|
||||
import { isDashboardPopoutRenderer } from '../window/dashboard-popout-window'
|
||||
import {
|
||||
TERMINAL_PREVIEW_OUTPUT_BATCH_MAX_BYTES,
|
||||
TerminalPreviewOutputStream
|
||||
} from './terminal-preview-output-stream'
|
||||
|
||||
const PREVIEW_ID_MAX_LENGTH = 4096
|
||||
|
||||
function isValidPtyId(value: unknown): value is string {
|
||||
return typeof value === 'string' && value.length > 0 && value.length <= PREVIEW_ID_MAX_LENGTH
|
||||
}
|
||||
|
||||
/** Pop-out terminal transport with an atomic snapshot/live boundary. */
|
||||
export function registerTerminalPreviewHandlers(runtime: OrcaRuntimeService): void {
|
||||
ipcMain.removeHandler('terminalPreview:connect')
|
||||
ipcMain.removeHandler('terminalPreview:unsubscribe')
|
||||
ipcMain.removeHandler('terminalPreview:input')
|
||||
ipcMain.removeHandler('terminalPreview:ack')
|
||||
|
||||
const subscriptionsByContents = new Map<number, Map<string, TerminalPreviewOutputStream>>()
|
||||
|
||||
const removeSubscription = (subscription: TerminalPreviewOutputStream): void => {
|
||||
const perPty = subscriptionsByContents.get(subscription.contents.id)
|
||||
if (perPty?.get(subscription.ptyId) === subscription) {
|
||||
perPty.delete(subscription.ptyId)
|
||||
}
|
||||
}
|
||||
|
||||
const disposeContents = (contentsId: number): void => {
|
||||
const perPty = subscriptionsByContents.get(contentsId)
|
||||
if (!perPty) {
|
||||
return
|
||||
}
|
||||
for (const subscription of perPty.values()) {
|
||||
subscription.dispose()
|
||||
}
|
||||
subscriptionsByContents.delete(contentsId)
|
||||
}
|
||||
|
||||
const subscriptionsFor = (contents: WebContents): Map<string, TerminalPreviewOutputStream> => {
|
||||
let perPty = subscriptionsByContents.get(contents.id)
|
||||
if (!perPty) {
|
||||
perPty = new Map()
|
||||
subscriptionsByContents.set(contents.id, perPty)
|
||||
contents.once('destroyed', () => disposeContents(contents.id))
|
||||
}
|
||||
return perPty
|
||||
}
|
||||
|
||||
ipcMain.handle(
|
||||
'terminalPreview:connect',
|
||||
async (
|
||||
event,
|
||||
args: { ptyId?: unknown; opts?: { scrollbackRows?: unknown } }
|
||||
): Promise<TerminalPreviewConnectResult> => {
|
||||
if (!isDashboardPopoutRenderer(event.sender) || !isValidPtyId(args?.ptyId)) {
|
||||
return { snapshot: null, replay: [] }
|
||||
}
|
||||
const ptyId = args.ptyId
|
||||
const perPty = subscriptionsFor(event.sender)
|
||||
perPty.get(ptyId)?.dispose()
|
||||
|
||||
const subscription = new TerminalPreviewOutputStream(
|
||||
event.sender,
|
||||
ptyId,
|
||||
runtime.registerRawTerminalViewSubscriber(ptyId),
|
||||
removeSubscription
|
||||
)
|
||||
subscription.setDataSubscription(
|
||||
runtime.subscribeToTerminalData(ptyId, (data, meta) => subscription.append(data, meta))
|
||||
)
|
||||
perPty.set(ptyId, subscription)
|
||||
|
||||
const requestedRows = args.opts?.scrollbackRows
|
||||
const scrollbackRows =
|
||||
typeof requestedRows === 'number' && Number.isFinite(requestedRows)
|
||||
? Math.max(0, Math.min(1000, Math.floor(requestedRows)))
|
||||
: undefined
|
||||
let snapshot: TerminalPreviewSnapshot | null
|
||||
let resyncRequired = false
|
||||
try {
|
||||
snapshot = await runtime.serializeTerminalBuffer(ptyId, { scrollbackRows })
|
||||
if (subscription.consumeInitialOverflow() && !subscription.disposed) {
|
||||
snapshot = await runtime.serializeTerminalBuffer(ptyId, { scrollbackRows })
|
||||
if (subscription.consumeInitialOverflow()) {
|
||||
// Why: never replay a tail with a silently missing middle; the renderer keeps its old frame while reconnecting.
|
||||
resyncRequired = true
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
subscription.dispose()
|
||||
return { snapshot: null, replay: [] }
|
||||
}
|
||||
if (subscription.disposed) {
|
||||
return { snapshot: null, replay: [] }
|
||||
}
|
||||
if (!snapshot) {
|
||||
// Why: a failed lookup has no future live boundary; release raw presence even if the renderer never invokes unsubscribe.
|
||||
subscription.dispose()
|
||||
return { snapshot: null, replay: [] }
|
||||
}
|
||||
|
||||
const replay = subscription.completeSnapshot(snapshot.seq)
|
||||
if (resyncRequired) {
|
||||
// Why: no live writes may outlive this stream and acknowledge bytes against its replacement.
|
||||
subscription.pauseForReconnect()
|
||||
}
|
||||
return { snapshot, replay, ...(resyncRequired ? { resyncRequired: true } : {}) }
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'terminalPreview:input',
|
||||
(event, args: { ptyId?: unknown; data?: unknown }): Promise<boolean> => {
|
||||
if (
|
||||
!isDashboardPopoutRenderer(event.sender) ||
|
||||
!isValidPtyId(args?.ptyId) ||
|
||||
typeof args.data !== 'string'
|
||||
) {
|
||||
return Promise.resolve(false)
|
||||
}
|
||||
return runtime.writeTerminalPreviewInput(args.ptyId, args.data)
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'terminalPreview:ack',
|
||||
(event, args: { ptyId?: unknown; bytes?: unknown }): void => {
|
||||
if (
|
||||
!isDashboardPopoutRenderer(event.sender) ||
|
||||
!isValidPtyId(args?.ptyId) ||
|
||||
typeof args.bytes !== 'number' ||
|
||||
!Number.isFinite(args.bytes) ||
|
||||
args.bytes <= 0 ||
|
||||
args.bytes > TERMINAL_PREVIEW_OUTPUT_BATCH_MAX_BYTES
|
||||
) {
|
||||
return
|
||||
}
|
||||
subscriptionsByContents.get(event.sender.id)?.get(args.ptyId)?.acknowledge(args.bytes)
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle('terminalPreview:unsubscribe', (event, args: { ptyId?: unknown }): void => {
|
||||
if (!isDashboardPopoutRenderer(event.sender) || !isValidPtyId(args?.ptyId)) {
|
||||
return
|
||||
}
|
||||
subscriptionsByContents.get(event.sender.id)?.get(args.ptyId)?.dispose()
|
||||
})
|
||||
}
|
||||
@@ -36,6 +36,7 @@ vi.mock('electron', () => ({
|
||||
|
||||
import {
|
||||
clearTrustedUIRendererWebContentsId,
|
||||
getTrustedUIRendererWindow,
|
||||
registerUIHandlers,
|
||||
sendToTrustedUIRenderer,
|
||||
setTrustedUIRendererWebContentsId
|
||||
@@ -112,6 +113,20 @@ describe('UI IPC', () => {
|
||||
expect(guestSends.reduce((total, send) => total + send.mock.calls.length, 0)).toBe(0)
|
||||
})
|
||||
|
||||
it('resolves only the BrowserWindow that owns the trusted renderer', () => {
|
||||
const renderer = { id: 17, isDestroyed: () => false }
|
||||
const mainWindow = { id: 'main' }
|
||||
fromIdMock.mockReturnValue(renderer)
|
||||
fromWebContentsMock.mockReturnValue(mainWindow)
|
||||
setTrustedUIRendererWebContentsId(17)
|
||||
|
||||
expect(getTrustedUIRendererWindow()).toBe(mainWindow)
|
||||
expect(fromWebContentsMock).toHaveBeenCalledWith(renderer)
|
||||
|
||||
fromIdMock.mockReturnValue({ id: 17, isDestroyed: () => true })
|
||||
expect(getTrustedUIRendererWindow()).toBeNull()
|
||||
})
|
||||
|
||||
it('skips missing, destroyed, and originating renderers', () => {
|
||||
const rendererSend = vi.fn()
|
||||
setTrustedUIRendererWebContentsId(17)
|
||||
|
||||
+16
-5
@@ -20,17 +20,28 @@ export function sendToTrustedUIRenderer(
|
||||
payload: unknown,
|
||||
excludedWebContentsId?: number
|
||||
): void {
|
||||
const renderer = getTrustedUIRendererWebContents(excludedWebContentsId)
|
||||
renderer?.send(channel, payload)
|
||||
}
|
||||
|
||||
export function getTrustedUIRendererWebContents(
|
||||
excludedWebContentsId?: number
|
||||
): WebContents | null {
|
||||
// Why: exact targeting avoids waking retained browser/utility windows that cannot consume app UI events.
|
||||
const rendererId = trustedUIRendererWebContentsId
|
||||
if (rendererId == null || rendererId === excludedWebContentsId) {
|
||||
return
|
||||
return null
|
||||
}
|
||||
const renderer = webContents.fromId(rendererId)
|
||||
if (!renderer || renderer.isDestroyed()) {
|
||||
return
|
||||
return null
|
||||
}
|
||||
// Why: app events belong to the registered UI renderer; enumerating every
|
||||
// WebContents wakes retained browser guests that cannot consume the channel.
|
||||
renderer.send(channel, payload)
|
||||
return renderer
|
||||
}
|
||||
|
||||
export function getTrustedUIRendererWindow(): BrowserWindow | null {
|
||||
const renderer = getTrustedUIRendererWebContents()
|
||||
return renderer ? BrowserWindow.fromWebContents(renderer) : null
|
||||
}
|
||||
|
||||
export function registerUIHandlers(store: Store): void {
|
||||
|
||||
@@ -71,12 +71,16 @@ function createRuntime(mobileAutoRestoreFitMs: number | null = 5_000) {
|
||||
['pty-1', { cols: 150, rows: 40 }]
|
||||
])
|
||||
const resizes: { ptyId: string; cols: number; rows: number }[] = []
|
||||
const writes: string[] = []
|
||||
const driverEvents: { ptyId: string; driver: { kind: string; clientId?: string } }[] = []
|
||||
const fitOverrideEvents: { ptyId: string; mode: string; cols: number; rows: number }[] = []
|
||||
let resizeSucceeds = true
|
||||
|
||||
runtime.setPtyController({
|
||||
write: () => true,
|
||||
write: (_ptyId, data) => {
|
||||
writes.push(data)
|
||||
return true
|
||||
},
|
||||
kill: () => true,
|
||||
getForegroundProcess: async () => null,
|
||||
resize: (ptyId, cols, rows) => {
|
||||
@@ -111,6 +115,7 @@ function createRuntime(mobileAutoRestoreFitMs: number | null = 5_000) {
|
||||
runtime,
|
||||
ptySizes,
|
||||
resizes,
|
||||
writes,
|
||||
driverEvents,
|
||||
fitOverrideEvents,
|
||||
setResizeSucceeds: (next: boolean) => {
|
||||
@@ -128,6 +133,22 @@ describe('mobile presence lock — driver state machine', () => {
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'idle' })
|
||||
})
|
||||
|
||||
it('stops a preview paste when mobile claims the floor between chunks', async () => {
|
||||
const { runtime, writes } = createRuntime()
|
||||
let driverChecks = 0
|
||||
vi.spyOn(runtime, 'getDriver').mockImplementation(() => {
|
||||
driverChecks++
|
||||
return driverChecks >= 3 ? { kind: 'mobile', clientId: 'phone-A' } : { kind: 'idle' }
|
||||
})
|
||||
|
||||
const result = runtime.writeTerminalPreviewInput('pty-1', 'x'.repeat(32 * 1024))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
await expect(result).resolves.toBe(false)
|
||||
expect(writes).toHaveLength(1)
|
||||
expect(Buffer.byteLength(writes[0]!, 'utf8')).toBe(16 * 1024)
|
||||
})
|
||||
|
||||
it('handleMobileSubscribe in auto mode transitions idle → mobile{clientId}', async () => {
|
||||
const { runtime, driverEvents } = createRuntime()
|
||||
await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 })
|
||||
|
||||
@@ -2488,6 +2488,9 @@ export class OrcaRuntimeService {
|
||||
// streams can attach concurrently; mobileSubscribers is consulted too so
|
||||
// grace-window mobile records keep suppressing.
|
||||
private remoteTerminalViewSubscriberCounts = new Map<string, number>()
|
||||
// Preview windows consume the raw stream but deliberately leave terminal
|
||||
// query replies to main's headless emulator.
|
||||
private rawTerminalViewSubscriberCounts = new Map<string, number>()
|
||||
|
||||
// Why: per-PTY driver state. The "driver" is whoever currently owns the
|
||||
// input/resize floor. While `kind === 'mobile'` the desktop renderer drops
|
||||
@@ -7263,6 +7266,37 @@ export class OrcaRuntimeService {
|
||||
}
|
||||
}
|
||||
|
||||
/** Mark a raw-output viewer without transferring terminal query authority. */
|
||||
registerRawTerminalViewSubscriber(ptyId: string): () => void {
|
||||
this.rawTerminalViewSubscriberCounts.set(
|
||||
ptyId,
|
||||
(this.rawTerminalViewSubscriberCounts.get(ptyId) ?? 0) + 1
|
||||
)
|
||||
this.notifyRemoteTerminalViewPresenceChanged(ptyId)
|
||||
let released = false
|
||||
return () => {
|
||||
if (released) {
|
||||
return
|
||||
}
|
||||
released = true
|
||||
const next = (this.rawTerminalViewSubscriberCounts.get(ptyId) ?? 1) - 1
|
||||
if (next <= 0) {
|
||||
this.rawTerminalViewSubscriberCounts.delete(ptyId)
|
||||
} else {
|
||||
this.rawTerminalViewSubscriberCounts.set(ptyId, next)
|
||||
}
|
||||
this.notifyRemoteTerminalViewPresenceChanged(ptyId)
|
||||
}
|
||||
}
|
||||
|
||||
/** Raw stream presence prevents provider thinning without changing reply ownership. */
|
||||
hasRawTerminalViewSubscriber(ptyId: string): boolean {
|
||||
return (
|
||||
(this.rawTerminalViewSubscriberCounts.get(ptyId) ?? 0) > 0 ||
|
||||
this.hasRemoteTerminalViewSubscriber(ptyId)
|
||||
)
|
||||
}
|
||||
|
||||
hasRemoteTerminalViewSubscriber(ptyId: string): boolean {
|
||||
if ((this.remoteTerminalViewSubscriberCounts.get(ptyId) ?? 0) > 0) {
|
||||
return true
|
||||
@@ -7344,6 +7378,28 @@ export class OrcaRuntimeService {
|
||||
return this.serializeTerminalBufferFromAvailableState(ptyId, opts)
|
||||
}
|
||||
|
||||
/** Raw keystroke pass-through for the pop-out dashboard's terminal preview.
|
||||
* Honors the mobile-presence lock like the main window's pty:write path. */
|
||||
async writeTerminalPreviewInput(ptyId: string, data: string): Promise<boolean> {
|
||||
if (data.length === 0 || this.getDriver(ptyId).kind === 'mobile') {
|
||||
return false
|
||||
}
|
||||
try {
|
||||
await assertTerminalInputWithinLimitWithYield(data)
|
||||
await this.writeTerminalInputChunks(ptyId, data, {
|
||||
// Why: a phone can claim the floor while a paste yields between chunks.
|
||||
beforeWrite: () => {
|
||||
if (this.getDriver(ptyId).kind === 'mobile') {
|
||||
throw new Error('terminal_mobile_driver_active')
|
||||
}
|
||||
}
|
||||
})
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
hasHeadlessTerminalState(ptyId: string): boolean {
|
||||
return this.headlessTerminals.has(ptyId)
|
||||
}
|
||||
@@ -9284,6 +9340,7 @@ export class OrcaRuntimeService {
|
||||
// Clean up new mobile state for this PTY
|
||||
this.mobileSubscribers.delete(ptyId)
|
||||
this.remoteTerminalViewSubscriberCounts.delete(ptyId)
|
||||
this.rawTerminalViewSubscriberCounts.delete(ptyId)
|
||||
this.mobileDisplayModes.delete(ptyId)
|
||||
this.resizeListeners.delete(ptyId)
|
||||
this.lastRendererSizes.delete(ptyId)
|
||||
|
||||
@@ -247,6 +247,21 @@ describe('reply ownership matrix', () => {
|
||||
expect(runtime.hasRemoteTerminalViewSubscriber('pty-m')).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps raw preview presence separate from terminal query authority', async () => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
markHiddenRendererPty('pty-preview')
|
||||
const release = runtime.registerRawTerminalViewSubscriber('pty-preview')
|
||||
|
||||
expect(runtime.hasRawTerminalViewSubscriber('pty-preview')).toBe(true)
|
||||
expect(runtime.hasRemoteTerminalViewSubscriber('pty-preview')).toBe(false)
|
||||
runtime.onPtyData('pty-preview', DA1, Date.now())
|
||||
await settle(runtime, 'pty-preview')
|
||||
expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?1;2c'])
|
||||
|
||||
release()
|
||||
expect(runtime.hasRawTerminalViewSubscriber('pty-preview')).toBe(false)
|
||||
})
|
||||
|
||||
it('treats mobile subscriber records as remote view subscribers', async () => {
|
||||
const { runtime } = createResponderRuntime()
|
||||
await runtime.handleMobileSubscribe('pty-mob', 'client-1', { cols: 40, rows: 20 })
|
||||
|
||||
@@ -7,8 +7,7 @@ import {
|
||||
nativeTheme,
|
||||
Notification,
|
||||
powerMonitor,
|
||||
screen,
|
||||
shell
|
||||
screen
|
||||
} from 'electron'
|
||||
import { join } from 'node:path'
|
||||
import { is } from '@electron-toolkit/utils'
|
||||
@@ -17,10 +16,7 @@ import { getAppIconPath } from '../app-icon'
|
||||
import { browserManager } from '../browser/browser-manager'
|
||||
import { browserSessionRegistry } from '../browser/browser-session-registry'
|
||||
import { translateMain } from '../i18n/main-i18n'
|
||||
import {
|
||||
normalizeBrowserNavigationUrl,
|
||||
normalizeExternalBrowserUrl
|
||||
} from '../../shared/browser-url'
|
||||
import { normalizeBrowserNavigationUrl } from '../../shared/browser-url'
|
||||
import { ORCA_BROWSER_GUEST_WEB_PREFERENCES } from '../../shared/browser-guest-web-preferences'
|
||||
import { isCrashReportReason } from '../../shared/crash-reporting'
|
||||
import {
|
||||
@@ -49,6 +45,9 @@ import { getMainE2EConfig } from '../e2e-config'
|
||||
import { buildEditableContextMenuTemplate } from './editable-context-menu'
|
||||
import { clearTrustedUIRendererWebContentsId, setTrustedUIRendererWebContentsId } from '../ipc/ui'
|
||||
import { resolveWindowCloseAction } from './window-close-decision'
|
||||
import { rectHasVisibleAreaOnAnyDisplay } from './window-bounds-validation'
|
||||
import { closeDashboardPopout } from './dashboard-popout-window'
|
||||
import { installPrivilegedWindowNavigationPolicy } from './privileged-window-navigation'
|
||||
|
||||
// Why: show/restore/resume can overlap before the size nudge resets; never capture the temporary width as the next baseline.
|
||||
const activeRepaintJiggles = new WeakSet<BrowserWindow>()
|
||||
@@ -173,34 +172,12 @@ export function createMainWindow(
|
||||
opts?: CreateMainWindowOptions
|
||||
): BrowserWindow {
|
||||
const rawSavedBounds = store?.getUI().windowBounds
|
||||
// Why: discard persisted bounds that are shrink-to-min (corrupt, see freezeBoundsOnQuit) or off-screen, falling back to defaultBounds.
|
||||
// Require ~half MIN_WIDTH/HEIGHT of workArea overlap so a 1px sliver or dock-hidden rect isn't treated as visible.
|
||||
const rectHasVisibleAreaOnAnyDisplay = (b: {
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
height: number
|
||||
}): boolean => {
|
||||
try {
|
||||
return screen.getAllDisplays().some((d) => {
|
||||
const wa = d.workArea
|
||||
const overlapX = Math.max(0, Math.min(b.x + b.width, wa.x + wa.width) - Math.max(b.x, wa.x))
|
||||
const overlapY = Math.max(
|
||||
0,
|
||||
Math.min(b.y + b.height, wa.y + wa.height) - Math.max(b.y, wa.y)
|
||||
)
|
||||
return overlapX >= MIN_WIDTH / 2 && overlapY >= MIN_HEIGHT / 2
|
||||
})
|
||||
} catch (err) {
|
||||
console.warn('[window] screen.getAllDisplays() threw; treating bounds as off-screen', err)
|
||||
return false
|
||||
}
|
||||
}
|
||||
// Why: reject min-size or substantially off-screen bounds so the titlebar stays reachable after display changes.
|
||||
const savedBounds =
|
||||
rawSavedBounds &&
|
||||
rawSavedBounds.width > MIN_WIDTH &&
|
||||
rawSavedBounds.height > MIN_HEIGHT &&
|
||||
rectHasVisibleAreaOnAnyDisplay(rawSavedBounds)
|
||||
rectHasVisibleAreaOnAnyDisplay(rawSavedBounds, MIN_WIDTH / 2, MIN_HEIGHT / 2)
|
||||
? rawSavedBounds
|
||||
: undefined
|
||||
if (rawSavedBounds && !savedBounds) {
|
||||
@@ -417,13 +394,7 @@ export function createMainWindow(
|
||||
mainWindow.webContents.send('window:fullscreen-changed', false)
|
||||
})
|
||||
|
||||
mainWindow.webContents.setWindowOpenHandler((details) => {
|
||||
const externalUrl = normalizeExternalBrowserUrl(details.url)
|
||||
if (externalUrl) {
|
||||
shell.openExternal(externalUrl)
|
||||
}
|
||||
return { action: 'deny' }
|
||||
})
|
||||
installPrivilegedWindowNavigationPolicy(mainWindow.webContents)
|
||||
|
||||
mainWindow.webContents.on('will-attach-webview', (event, webPreferences, params) => {
|
||||
const src = typeof params.src === 'string' ? params.src : ''
|
||||
@@ -458,29 +429,6 @@ export function createMainWindow(
|
||||
browserManager.attachGuestPolicies(guest)
|
||||
})
|
||||
|
||||
// Why: block in-window navigations so remote pages can't inherit the privileged preload bridge (dev server allowed for HMR).
|
||||
mainWindow.webContents.on('will-navigate', (event, url) => {
|
||||
const externalUrl = normalizeExternalBrowserUrl(url)
|
||||
|
||||
if (externalUrl) {
|
||||
const target = new URL(externalUrl)
|
||||
if (is.dev && process.env.ELECTRON_RENDERER_URL) {
|
||||
try {
|
||||
const allowed = new URL(process.env.ELECTRON_RENDERER_URL)
|
||||
if (target.origin === allowed.origin) {
|
||||
return // allow dev server navigations (HMR, etc.)
|
||||
}
|
||||
} catch {
|
||||
// fall through to prevent
|
||||
}
|
||||
}
|
||||
|
||||
shell.openExternal(externalUrl)
|
||||
}
|
||||
|
||||
event.preventDefault()
|
||||
})
|
||||
|
||||
// Why: mirror markdown-editor focus so before-input-event skips Cmd/Ctrl+B while TipTap owns focus (docs/markdown-cmd-b-bold-design.md).
|
||||
let markdownEditorFocused = false
|
||||
let terminalInputFocused = false
|
||||
@@ -1033,6 +981,10 @@ export function createMainWindow(
|
||||
|
||||
ipcMain.on(confirmCloseChannel, onConfirmClose)
|
||||
mainWindow.on('closed', () => {
|
||||
// Why: the dashboard pop-out is a companion of the main window — close it
|
||||
// alongside so it never orphans as a lone window after the app window is
|
||||
// gone (e.g. on macOS where the app stays alive after the window closes).
|
||||
closeDashboardPopout()
|
||||
clearInitialRevealFallbackTimer()
|
||||
// Why: default-deny the Cmd+B carve-out after the window is gone so a stale-true flag can't leak into later state.
|
||||
markdownEditorFocused = false
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
type Display = { workArea: { x: number; y: number; width: number; height: number } }
|
||||
|
||||
const {
|
||||
instances,
|
||||
BrowserWindowMock,
|
||||
nativeThemeMock,
|
||||
appOnMock,
|
||||
appRemoveListenerMock,
|
||||
getAllDisplaysMock,
|
||||
installNavigationPolicyMock,
|
||||
sendToTrustedUIRendererMock,
|
||||
isMock
|
||||
} = vi.hoisted(() => {
|
||||
const created: FakeWindow[] = []
|
||||
|
||||
class FakeWindow {
|
||||
options: Electron.BrowserWindowConstructorOptions
|
||||
private handlers: Record<string, ((...args: unknown[]) => void)[]> = {}
|
||||
private onceHandlers: Record<string, ((...args: unknown[]) => void)[]> = {}
|
||||
destroyed = false
|
||||
minimized = false
|
||||
fullscreen = false
|
||||
webContents = { id: created.length + 1, send: vi.fn(), isDestroyed: () => this.destroyed }
|
||||
bounds = { x: 100, y: 100, width: 960, height: 720 }
|
||||
focus = vi.fn()
|
||||
show = vi.fn()
|
||||
restore = vi.fn(() => {
|
||||
this.minimized = false
|
||||
})
|
||||
loadURL = vi.fn()
|
||||
loadFile = vi.fn()
|
||||
close = vi.fn(() => {
|
||||
this.destroyed = true
|
||||
this.emit('close')
|
||||
this.emit('closed')
|
||||
})
|
||||
|
||||
constructor(options: Electron.BrowserWindowConstructorOptions) {
|
||||
this.options = options
|
||||
created.push(this)
|
||||
}
|
||||
|
||||
on(event: string, cb: (...args: unknown[]) => void): this {
|
||||
;(this.handlers[event] ||= []).push(cb)
|
||||
return this
|
||||
}
|
||||
|
||||
once(event: string, cb: (...args: unknown[]) => void): this {
|
||||
;(this.onceHandlers[event] ||= []).push(cb)
|
||||
return this
|
||||
}
|
||||
|
||||
emit(event: string, ...args: unknown[]): void {
|
||||
for (const cb of this.handlers[event] ?? []) {
|
||||
cb(...args)
|
||||
}
|
||||
for (const cb of this.onceHandlers[event] ?? []) {
|
||||
cb(...args)
|
||||
}
|
||||
}
|
||||
|
||||
isDestroyed(): boolean {
|
||||
return this.destroyed
|
||||
}
|
||||
isMinimized(): boolean {
|
||||
return this.minimized
|
||||
}
|
||||
isFullScreen(): boolean {
|
||||
return this.fullscreen
|
||||
}
|
||||
getBounds(): { x: number; y: number; width: number; height: number } {
|
||||
return this.bounds
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
instances: created,
|
||||
BrowserWindowMock: FakeWindow,
|
||||
nativeThemeMock: { shouldUseDarkColors: true },
|
||||
appOnMock: vi.fn(),
|
||||
appRemoveListenerMock: vi.fn(),
|
||||
getAllDisplaysMock: vi.fn((): Display[] => [
|
||||
{ workArea: { x: 0, y: 0, width: 1920, height: 1080 } }
|
||||
]),
|
||||
installNavigationPolicyMock: vi.fn(),
|
||||
sendToTrustedUIRendererMock: vi.fn(),
|
||||
isMock: { dev: false } as { dev: boolean }
|
||||
}
|
||||
})
|
||||
|
||||
// Static helpers live on the constructor; broadcastPopoutOpenChanged uses
|
||||
// BrowserWindow.getAllWindows(). Return the instances created in this test.
|
||||
;(BrowserWindowMock as unknown as { getAllWindows: () => unknown[] }).getAllWindows = () =>
|
||||
instances
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { on: appOnMock, removeListener: appRemoveListenerMock },
|
||||
BrowserWindow: BrowserWindowMock,
|
||||
nativeTheme: nativeThemeMock,
|
||||
screen: { getAllDisplays: getAllDisplaysMock }
|
||||
}))
|
||||
|
||||
vi.mock('@electron-toolkit/utils', () => ({ is: isMock }))
|
||||
vi.mock('../ipc/ui', () => ({ sendToTrustedUIRenderer: sendToTrustedUIRendererMock }))
|
||||
vi.mock('./privileged-window-navigation', () => ({
|
||||
installPrivilegedWindowNavigationPolicy: installNavigationPolicyMock
|
||||
}))
|
||||
|
||||
import {
|
||||
createOrFocusDashboardPopout,
|
||||
closeDashboardPopout,
|
||||
isDashboardPopoutRenderer
|
||||
} from './dashboard-popout-window'
|
||||
|
||||
type FakeWindow = InstanceType<typeof BrowserWindowMock>
|
||||
|
||||
function makeStore(ui: Record<string, unknown> = {}): {
|
||||
getUI: () => Record<string, unknown>
|
||||
updateUI: ReturnType<typeof vi.fn>
|
||||
} {
|
||||
return { getUI: () => ui, updateUI: vi.fn() }
|
||||
}
|
||||
|
||||
const RENDERER_URL = 'http://localhost:5173'
|
||||
|
||||
describe('createOrFocusDashboardPopout', () => {
|
||||
beforeEach(() => {
|
||||
instances.length = 0
|
||||
isMock.dev = false
|
||||
vi.stubEnv('ELECTRON_RENDERER_URL', '')
|
||||
getAllDisplaysMock.mockReturnValue([{ workArea: { x: 0, y: 0, width: 1920, height: 1080 } }])
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
// Reset the module-level singleton between tests.
|
||||
closeDashboardPopout()
|
||||
vi.unstubAllEnvs()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('creates a native-frame window with the shared preload and no webview surface', () => {
|
||||
createOrFocusDashboardPopout(makeStore() as never)
|
||||
|
||||
expect(instances).toHaveLength(1)
|
||||
const opts = instances[0].options
|
||||
expect(opts.title).toBe('Orca Agent Dashboard')
|
||||
expect(opts.minWidth).toBe(480)
|
||||
expect(opts.minHeight).toBe(360)
|
||||
// Native frame: neither a custom titleBarStyle nor frame:false is set.
|
||||
expect(opts.titleBarStyle).toBeUndefined()
|
||||
expect(opts.frame).toBeUndefined()
|
||||
expect(opts.backgroundColor).toBe('#0a0a0a') // dark theme mock
|
||||
expect(opts.webPreferences?.sandbox).toBe(true)
|
||||
expect(opts.webPreferences?.webviewTag).toBe(false)
|
||||
expect(opts.webPreferences?.preload).toMatch(/preload[\\/]index\.js$/)
|
||||
expect(installNavigationPolicyMock).toHaveBeenCalledWith(instances[0].webContents)
|
||||
expect(sendToTrustedUIRendererMock).toHaveBeenCalledWith('dashboard:popoutOpenChanged', true)
|
||||
})
|
||||
|
||||
it('shows the window on ready-to-show', () => {
|
||||
createOrFocusDashboardPopout(makeStore() as never)
|
||||
const win = instances[0]
|
||||
expect(win.show).not.toHaveBeenCalled()
|
||||
win.emit('ready-to-show')
|
||||
expect(win.show).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('loads the prod file entry with the requested view', () => {
|
||||
createOrFocusDashboardPopout(makeStore() as never, 'kanban')
|
||||
const win = instances[0]
|
||||
expect(win.loadURL).not.toHaveBeenCalled()
|
||||
expect(win.loadFile).toHaveBeenCalledTimes(1)
|
||||
const [file, options] = win.loadFile.mock.calls[0]
|
||||
expect(String(file)).toMatch(/renderer[\\/]popout\.html$/)
|
||||
expect(options).toEqual({ search: 'view=kanban' })
|
||||
})
|
||||
|
||||
it('loads the dev server URL with the requested view when in dev', () => {
|
||||
isMock.dev = true
|
||||
vi.stubEnv('ELECTRON_RENDERER_URL', RENDERER_URL)
|
||||
createOrFocusDashboardPopout(makeStore() as never, 'kanban')
|
||||
const win = instances[0]
|
||||
expect(win.loadFile).not.toHaveBeenCalled()
|
||||
expect(win.loadURL).toHaveBeenCalledWith(`${RENDERER_URL}/popout.html?view=kanban`)
|
||||
})
|
||||
|
||||
it('focuses the existing window instead of creating a second one', () => {
|
||||
const store = makeStore()
|
||||
const first = createOrFocusDashboardPopout(store as never)
|
||||
const second = createOrFocusDashboardPopout(store as never)
|
||||
expect(instances).toHaveLength(1)
|
||||
expect(second).toBe(first)
|
||||
expect(instances[0].focus).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('trusts only the live popout webContents', () => {
|
||||
const win = createOrFocusDashboardPopout(makeStore() as never) as unknown as FakeWindow
|
||||
expect(isDashboardPopoutRenderer(win.webContents as never)).toBe(true)
|
||||
expect(isDashboardPopoutRenderer({ id: win.webContents.id } as never)).toBe(false)
|
||||
win.destroyed = true
|
||||
expect(isDashboardPopoutRenderer(win.webContents as never)).toBe(false)
|
||||
})
|
||||
|
||||
it('restores a minimized window when re-requested', () => {
|
||||
const store = makeStore()
|
||||
const win = createOrFocusDashboardPopout(store as never) as unknown as FakeWindow
|
||||
win.minimized = true
|
||||
createOrFocusDashboardPopout(store as never)
|
||||
expect(win.restore).toHaveBeenCalledTimes(1)
|
||||
expect(win.focus).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('restores valid persisted bounds', () => {
|
||||
const store = makeStore({
|
||||
dashboardPopoutBounds: { x: 200, y: 150, width: 1000, height: 800 }
|
||||
})
|
||||
createOrFocusDashboardPopout(store as never)
|
||||
const opts = instances[0].options
|
||||
expect(opts.x).toBe(200)
|
||||
expect(opts.y).toBe(150)
|
||||
expect(opts.width).toBe(1000)
|
||||
expect(opts.height).toBe(800)
|
||||
})
|
||||
|
||||
it('discards off-screen persisted bounds and falls back to defaults', () => {
|
||||
// Display does not overlap the saved rect at all.
|
||||
getAllDisplaysMock.mockReturnValue([{ workArea: { x: 0, y: 0, width: 800, height: 600 } }])
|
||||
const store = makeStore({
|
||||
dashboardPopoutBounds: { x: 5000, y: 5000, width: 1000, height: 800 }
|
||||
})
|
||||
createOrFocusDashboardPopout(store as never)
|
||||
const opts = instances[0].options
|
||||
expect(opts.x).toBeUndefined()
|
||||
expect(opts.y).toBeUndefined()
|
||||
expect(opts.width).toBe(960)
|
||||
expect(opts.height).toBe(720)
|
||||
})
|
||||
|
||||
it('persists bounds on resize after the debounce, guarding near-minimum sizes', () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const store = makeStore()
|
||||
const win = createOrFocusDashboardPopout(store as never) as unknown as FakeWindow
|
||||
|
||||
win.bounds = { x: 10, y: 10, width: 1200, height: 900 }
|
||||
win.emit('resize')
|
||||
vi.advanceTimersByTime(500)
|
||||
expect(store.updateUI).toHaveBeenCalledWith({
|
||||
dashboardPopoutBounds: { x: 10, y: 10, width: 1200, height: 900 }
|
||||
})
|
||||
|
||||
store.updateUI.mockClear()
|
||||
win.bounds = { x: 10, y: 10, width: 100, height: 100 } // below minimum
|
||||
win.emit('resize')
|
||||
vi.advanceTimersByTime(500)
|
||||
expect(store.updateUI).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('closeDashboardPopout closes an open window', () => {
|
||||
createOrFocusDashboardPopout(makeStore() as never)
|
||||
const win = instances[0]
|
||||
closeDashboardPopout()
|
||||
expect(win.close).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,189 @@
|
||||
import { app, BrowserWindow, nativeTheme, type WebContents } from 'electron'
|
||||
import { join } from 'node:path'
|
||||
import { is } from '@electron-toolkit/utils'
|
||||
import type { Store } from '../persistence'
|
||||
import { rectHasVisibleAreaOnAnyDisplay } from './window-bounds-validation'
|
||||
import { sendToTrustedUIRenderer } from '../ipc/ui'
|
||||
import { installPrivilegedWindowNavigationPolicy } from './privileged-window-navigation'
|
||||
|
||||
const MIN_WIDTH = 480
|
||||
const MIN_HEIGHT = 360
|
||||
const DEFAULT_WIDTH = 960
|
||||
const DEFAULT_HEIGHT = 720
|
||||
const DEFAULT_VIEW = 'kanban'
|
||||
|
||||
// Why: singleton — the dashboard is a companion surface, so a second "Pop Out"
|
||||
// request focuses the existing window rather than spawning duplicates.
|
||||
let dashboardPopoutWindow: BrowserWindow | null = null
|
||||
|
||||
/** The live pop-out window, or null when closed. Used by the dashboard relay to
|
||||
* forward snapshots to the popout's webContents. */
|
||||
export function getDashboardPopoutWindow(): BrowserWindow | null {
|
||||
return dashboardPopoutWindow &&
|
||||
!dashboardPopoutWindow.isDestroyed() &&
|
||||
!dashboardPopoutWindow.webContents.isDestroyed()
|
||||
? dashboardPopoutWindow
|
||||
: null
|
||||
}
|
||||
|
||||
export function isDashboardPopoutRenderer(sender: WebContents): boolean {
|
||||
return getDashboardPopoutWindow()?.webContents === sender
|
||||
}
|
||||
|
||||
// In-process listeners (the dashboard relay clears its cached snapshot on close).
|
||||
const popoutOpenListeners = new Set<(open: boolean) => void>()
|
||||
|
||||
/** Subscribe to pop-out open/close transitions in the main process. */
|
||||
export function onDashboardPopoutOpenChanged(listener: (open: boolean) => void): () => void {
|
||||
popoutOpenListeners.add(listener)
|
||||
return () => popoutOpenListeners.delete(listener)
|
||||
}
|
||||
|
||||
// Why: the main renderer's snapshot publisher only runs while the pop-out is
|
||||
// open. Tell that exact window when the state flips, then notify listeners.
|
||||
function broadcastPopoutOpenChanged(open: boolean): void {
|
||||
sendToTrustedUIRenderer('dashboard:popoutOpenChanged', open)
|
||||
for (const listener of popoutOpenListeners) {
|
||||
listener(open)
|
||||
}
|
||||
}
|
||||
|
||||
function loadDashboardPopout(window: BrowserWindow, view: string): void {
|
||||
const search = `view=${encodeURIComponent(view)}`
|
||||
// Why: mirror loadMainWindow's dev/prod branch — the dev server serves the
|
||||
// second HTML entry, prod loads the emitted file.
|
||||
if (is.dev && process.env.ELECTRON_RENDERER_URL) {
|
||||
void window.loadURL(`${process.env.ELECTRON_RENDERER_URL}/popout.html?${search}`)
|
||||
} else {
|
||||
void window.loadFile(join(__dirname, '../renderer/popout.html'), { search })
|
||||
}
|
||||
}
|
||||
|
||||
function resolveRestoredBounds(store: Store | null): {
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
height: number
|
||||
} | null {
|
||||
const raw = store?.getUI().dashboardPopoutBounds ?? null
|
||||
if (
|
||||
raw &&
|
||||
raw.width >= MIN_WIDTH &&
|
||||
raw.height >= MIN_HEIGHT &&
|
||||
rectHasVisibleAreaOnAnyDisplay(raw, MIN_WIDTH / 2, MIN_HEIGHT / 2)
|
||||
) {
|
||||
return raw
|
||||
}
|
||||
if (raw) {
|
||||
console.warn('[dashboard-popout] Discarding off-screen/near-min popout bounds:', raw)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the pop-out dashboard window, or focus it if already open. The window is
|
||||
* a standalone top-level BrowserWindow with a native frame that reuses the same
|
||||
* preload/window.api as the main window but renders its own React root
|
||||
* (popout.html?view=…).
|
||||
*/
|
||||
export function createOrFocusDashboardPopout(
|
||||
store: Store | null,
|
||||
view: string = DEFAULT_VIEW
|
||||
): BrowserWindow {
|
||||
if (dashboardPopoutWindow && !dashboardPopoutWindow.isDestroyed()) {
|
||||
if (dashboardPopoutWindow.isMinimized()) {
|
||||
dashboardPopoutWindow.restore()
|
||||
}
|
||||
dashboardPopoutWindow.focus()
|
||||
return dashboardPopoutWindow
|
||||
}
|
||||
|
||||
const savedBounds = resolveRestoredBounds(store)
|
||||
|
||||
const window = new BrowserWindow({
|
||||
width: savedBounds?.width ?? DEFAULT_WIDTH,
|
||||
height: savedBounds?.height ?? DEFAULT_HEIGHT,
|
||||
...(savedBounds ? { x: savedBounds.x, y: savedBounds.y } : {}),
|
||||
minWidth: MIN_WIDTH,
|
||||
minHeight: MIN_HEIGHT,
|
||||
title: 'Orca Agent Dashboard',
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
backgroundColor: nativeTheme.shouldUseDarkColors ? '#0a0a0a' : '#ffffff',
|
||||
// Why: the pop-out uses a standard native frame so it is movable, closable,
|
||||
// and minimizable on every platform without reimplementing the main
|
||||
// window's custom titlebar/drag-region/window-control chrome. The main
|
||||
// window is frameless because it draws its own titlebar; the dashboard has
|
||||
// no such chrome yet, so a native frame is the correct default here.
|
||||
webPreferences: {
|
||||
preload: join(__dirname, '../preload/index.js'),
|
||||
sandbox: true,
|
||||
// Why: the dashboard is plain DOM — no <webview> guests — so keep the
|
||||
// guest-embedding surface off for this window.
|
||||
webviewTag: false
|
||||
}
|
||||
})
|
||||
installPrivilegedWindowNavigationPolicy(window.webContents)
|
||||
dashboardPopoutWindow = window
|
||||
broadcastPopoutOpenChanged(true)
|
||||
|
||||
window.once('ready-to-show', () => {
|
||||
if (!window.isDestroyed()) {
|
||||
window.show()
|
||||
}
|
||||
})
|
||||
|
||||
// Bounds persistence — mirrors the main window's debounced/frozen approach so
|
||||
// teardown-time resize/move events can't clobber the remembered size with
|
||||
// near-minimum bounds.
|
||||
let boundsTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let windowClosing = false
|
||||
const saveBounds = (): void => {
|
||||
if (boundsTimer) {
|
||||
clearTimeout(boundsTimer)
|
||||
}
|
||||
boundsTimer = setTimeout(() => {
|
||||
boundsTimer = null
|
||||
if (windowClosing || window.isDestroyed() || window.isMinimized() || window.isFullScreen()) {
|
||||
return
|
||||
}
|
||||
const bounds = window.getBounds()
|
||||
if (bounds.width < MIN_WIDTH || bounds.height < MIN_HEIGHT) {
|
||||
return
|
||||
}
|
||||
store?.updateUI({ dashboardPopoutBounds: bounds })
|
||||
}, 500)
|
||||
}
|
||||
window.on('resize', saveBounds)
|
||||
window.on('move', saveBounds)
|
||||
|
||||
const freezeBounds = (): void => {
|
||||
windowClosing = true
|
||||
if (boundsTimer) {
|
||||
clearTimeout(boundsTimer)
|
||||
boundsTimer = null
|
||||
}
|
||||
}
|
||||
window.on('close', freezeBounds)
|
||||
app.on('before-quit', freezeBounds)
|
||||
|
||||
window.on('closed', () => {
|
||||
app.removeListener('before-quit', freezeBounds)
|
||||
if (dashboardPopoutWindow === window) {
|
||||
dashboardPopoutWindow = null
|
||||
}
|
||||
broadcastPopoutOpenChanged(false)
|
||||
})
|
||||
|
||||
loadDashboardPopout(window, view)
|
||||
return window
|
||||
}
|
||||
|
||||
/** Close the pop-out dashboard if it is open. Called when the main window
|
||||
* closes so the dashboard never orphans without its owning app window. */
|
||||
export function closeDashboardPopout(): void {
|
||||
if (dashboardPopoutWindow && !dashboardPopoutWindow.isDestroyed()) {
|
||||
dashboardPopoutWindow.close()
|
||||
}
|
||||
dashboardPopoutWindow = null
|
||||
}
|
||||
@@ -25,7 +25,7 @@ function safelyFocusApp(app: Pick<App, 'focus'>): void {
|
||||
}
|
||||
}
|
||||
|
||||
function safelyRevealWindow(window: BrowserWindow): void {
|
||||
export function safelyRevealWindow(window: BrowserWindow): void {
|
||||
if (window.isDestroyed()) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { shell, type WebContents } from 'electron'
|
||||
import { is } from '@electron-toolkit/utils'
|
||||
import { normalizeExternalBrowserUrl } from '../../shared/browser-url'
|
||||
|
||||
/** Keep remote documents from inheriting an Orca window's privileged preload. */
|
||||
export function installPrivilegedWindowNavigationPolicy(contents: WebContents): void {
|
||||
contents.setWindowOpenHandler(({ url }) => {
|
||||
const externalUrl = normalizeExternalBrowserUrl(url)
|
||||
if (externalUrl) {
|
||||
void shell.openExternal(externalUrl)
|
||||
}
|
||||
return { action: 'deny' }
|
||||
})
|
||||
|
||||
contents.on('will-navigate', (event, url) => {
|
||||
const externalUrl = normalizeExternalBrowserUrl(url)
|
||||
if (externalUrl) {
|
||||
if (is.dev && process.env.ELECTRON_RENDERER_URL) {
|
||||
try {
|
||||
const target = new URL(externalUrl)
|
||||
const allowed = new URL(process.env.ELECTRON_RENDERER_URL)
|
||||
if (target.origin === allowed.origin) {
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// Fall through and block malformed navigation targets.
|
||||
}
|
||||
}
|
||||
void shell.openExternal(externalUrl)
|
||||
}
|
||||
event.preventDefault()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { screen } from 'electron'
|
||||
|
||||
export type WindowRect = { x: number; y: number; width: number; height: number }
|
||||
|
||||
/**
|
||||
* True when `rect` overlaps some currently-attached display's workArea by at
|
||||
* least the given visible width/height. Used to reject persisted bounds that
|
||||
* would restore a window off-screen — e.g. saved while an external monitor was
|
||||
* connected. workArea excludes the menu bar / dock, so a rect hidden entirely
|
||||
* under the dock is also correctly rejected. Requiring a *meaningful* overlap
|
||||
* (not just >0) avoids a one-pixel sliver leaving the titlebar unreachable.
|
||||
*/
|
||||
export function rectHasVisibleAreaOnAnyDisplay(
|
||||
rect: WindowRect,
|
||||
minVisibleWidth: number,
|
||||
minVisibleHeight: number
|
||||
): boolean {
|
||||
try {
|
||||
return screen.getAllDisplays().some((display) => {
|
||||
const wa = display.workArea
|
||||
const overlapX = Math.max(
|
||||
0,
|
||||
Math.min(rect.x + rect.width, wa.x + wa.width) - Math.max(rect.x, wa.x)
|
||||
)
|
||||
const overlapY = Math.max(
|
||||
0,
|
||||
Math.min(rect.y + rect.height, wa.y + wa.height) - Math.max(rect.y, wa.y)
|
||||
)
|
||||
return overlapX >= minVisibleWidth && overlapY >= minVisibleHeight
|
||||
})
|
||||
} catch (err) {
|
||||
console.warn('[window] screen.getAllDisplays() threw; treating bounds as off-screen', err)
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,11 @@ import type {
|
||||
HostedReviewProvider
|
||||
} from '../shared/hosted-review'
|
||||
import type { NativeFileDropPayload } from '../shared/native-file-drop'
|
||||
import type { DashboardSnapshot, DashboardRevealAgentArgs } from '../shared/dashboard-snapshot'
|
||||
import type {
|
||||
TerminalPreviewConnectResult,
|
||||
TerminalPreviewDataPayload
|
||||
} from '../shared/terminal-preview'
|
||||
import type {
|
||||
TerminalTabCloseRequest,
|
||||
TerminalTabCloseResponse
|
||||
@@ -2212,6 +2217,29 @@ export type PreloadApi = {
|
||||
}
|
||||
) => Promise<OnboardingState>
|
||||
}
|
||||
dashboard: {
|
||||
openPopout: () => Promise<void>
|
||||
publishSnapshot: (snapshot: DashboardSnapshot) => Promise<void>
|
||||
getPopoutOpen: () => Promise<boolean>
|
||||
onPopoutOpenChanged: (callback: (open: boolean) => void) => () => void
|
||||
onSnapshotRequested: (callback: () => void) => () => void
|
||||
onRevealAgent: (callback: (args: DashboardRevealAgentArgs) => void) => () => void
|
||||
onAckAgent: (callback: (paneKey: string) => void) => () => void
|
||||
requestSnapshot: () => Promise<void>
|
||||
onSnapshot: (callback: (snapshot: DashboardSnapshot) => void) => () => void
|
||||
revealAgent: (args: DashboardRevealAgentArgs) => Promise<void>
|
||||
ackAgent: (paneKey: string) => Promise<void>
|
||||
}
|
||||
terminalPreview: {
|
||||
connect: (
|
||||
ptyId: string,
|
||||
opts?: { scrollbackRows?: number }
|
||||
) => Promise<TerminalPreviewConnectResult>
|
||||
input: (ptyId: string, data: string) => Promise<boolean>
|
||||
ack: (ptyId: string, bytes: number) => Promise<void>
|
||||
unsubscribe: (ptyId: string) => Promise<void>
|
||||
onData: (callback: (payload: TerminalPreviewDataPayload) => void) => () => void
|
||||
}
|
||||
developerPermissions: {
|
||||
getStatus: () => Promise<DeveloperPermissionState[]>
|
||||
request: (args: { id: DeveloperPermissionId }) => Promise<DeveloperPermissionRequestResult>
|
||||
|
||||
@@ -4,6 +4,11 @@ import { electronAPI } from '@electron-toolkit/preload'
|
||||
import { preloadE2EConfig } from './e2e-config'
|
||||
import { glApi } from './gitlab'
|
||||
import type { AppIdentity } from '../shared/app-identity'
|
||||
import type { DashboardSnapshot, DashboardRevealAgentArgs } from '../shared/dashboard-snapshot'
|
||||
import type {
|
||||
TerminalPreviewConnectResult,
|
||||
TerminalPreviewDataPayload
|
||||
} from '../shared/terminal-preview'
|
||||
import type { CliInstallStatus } from '../shared/cli-install-types'
|
||||
import type { AgentHookInstallStatus } from '../shared/agent-hook-types'
|
||||
import type { TerminalPaneSplitSource } from '../shared/feature-education-telemetry'
|
||||
@@ -2069,6 +2074,73 @@ const api = {
|
||||
): Promise<OnboardingState> => ipcRenderer.invoke('onboarding:update', updates)
|
||||
},
|
||||
|
||||
dashboard: {
|
||||
// Open the pop-out dashboard window, or focus it if already open.
|
||||
openPopout: (): Promise<void> => ipcRenderer.invoke('dashboardPopout:open'),
|
||||
|
||||
// ── Producer side (main window) ──────────────────────────────────────
|
||||
publishSnapshot: (snapshot: DashboardSnapshot): Promise<void> =>
|
||||
ipcRenderer.invoke('dashboard:publishSnapshot', snapshot),
|
||||
getPopoutOpen: (): Promise<boolean> => ipcRenderer.invoke('dashboard:getPopoutOpen'),
|
||||
onPopoutOpenChanged: (callback: (open: boolean) => void): (() => void) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, open: boolean): void => callback(open)
|
||||
ipcRenderer.on('dashboard:popoutOpenChanged', listener)
|
||||
return () => ipcRenderer.removeListener('dashboard:popoutOpenChanged', listener)
|
||||
},
|
||||
onSnapshotRequested: (callback: () => void): (() => void) => {
|
||||
const listener = (): void => callback()
|
||||
ipcRenderer.on('dashboard:snapshotRequested', listener)
|
||||
return () => ipcRenderer.removeListener('dashboard:snapshotRequested', listener)
|
||||
},
|
||||
onRevealAgent: (callback: (args: DashboardRevealAgentArgs) => void): (() => void) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, args: DashboardRevealAgentArgs): void =>
|
||||
callback(args)
|
||||
ipcRenderer.on('ui:revealDashboardAgent', listener)
|
||||
return () => ipcRenderer.removeListener('ui:revealDashboardAgent', listener)
|
||||
},
|
||||
onAckAgent: (callback: (paneKey: string) => void): (() => void) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, paneKey: string): void =>
|
||||
callback(paneKey)
|
||||
ipcRenderer.on('ui:ackDashboardAgent', listener)
|
||||
return () => ipcRenderer.removeListener('ui:ackDashboardAgent', listener)
|
||||
},
|
||||
|
||||
// ── Consumer side (pop-out window) ───────────────────────────────────
|
||||
requestSnapshot: (): Promise<void> => ipcRenderer.invoke('dashboard:requestSnapshot'),
|
||||
onSnapshot: (callback: (snapshot: DashboardSnapshot) => void): (() => void) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, snapshot: DashboardSnapshot): void =>
|
||||
callback(snapshot)
|
||||
ipcRenderer.on('dashboard:snapshot', listener)
|
||||
return () => ipcRenderer.removeListener('dashboard:snapshot', listener)
|
||||
},
|
||||
revealAgent: (args: DashboardRevealAgentArgs): Promise<void> =>
|
||||
ipcRenderer.invoke('dashboardPopout:revealAgent', args),
|
||||
ackAgent: (paneKey: string): Promise<void> =>
|
||||
ipcRenderer.invoke('dashboardPopout:ackAgent', { paneKey })
|
||||
},
|
||||
|
||||
terminalPreview: {
|
||||
connect: (
|
||||
ptyId: string,
|
||||
opts?: { scrollbackRows?: number }
|
||||
): Promise<TerminalPreviewConnectResult> =>
|
||||
ipcRenderer.invoke('terminalPreview:connect', { ptyId, opts }),
|
||||
input: (ptyId: string, data: string): Promise<boolean> =>
|
||||
ipcRenderer.invoke('terminalPreview:input', { ptyId, data }),
|
||||
ack: (ptyId: string, bytes: number): Promise<void> =>
|
||||
ipcRenderer.invoke('terminalPreview:ack', { ptyId, bytes }),
|
||||
unsubscribe: (ptyId: string): Promise<void> =>
|
||||
ipcRenderer.invoke('terminalPreview:unsubscribe', { ptyId }),
|
||||
onData: (callback: (payload: TerminalPreviewDataPayload) => void): (() => void) => {
|
||||
const listener = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
payload: TerminalPreviewDataPayload
|
||||
): void => callback(payload)
|
||||
ipcRenderer.on('terminalPreview:data', listener)
|
||||
return () => ipcRenderer.removeListener('terminalPreview:data', listener)
|
||||
}
|
||||
},
|
||||
|
||||
developerPermissions: {
|
||||
getStatus: (): Promise<unknown> => ipcRenderer.invoke('developerPermissions:getStatus'),
|
||||
request: (args: { id: string }): Promise<unknown> =>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Orca Agent Dashboard</title>
|
||||
<!-- CSP is relaxed during development; electron-vite injects a stricter policy for production builds -->
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/popout.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -91,6 +91,7 @@ import RecentTabSwitcher from './components/tab-bar/RecentTabSwitcher'
|
||||
import { useGitStatusPolling } from './components/right-sidebar/useGitStatusPolling'
|
||||
import { useEditorExternalWatch } from './hooks/useEditorExternalWatch'
|
||||
import { useAutoAckViewedAgent } from './hooks/useAutoAckViewedAgent'
|
||||
import { useDashboardPopoutBridge } from './components/dashboard/useDashboardPopoutBridge'
|
||||
import { useUnreadDockBadge } from './hooks/useUnreadDockBadge'
|
||||
import {
|
||||
resolvePrimarySelectionMiddleClickPaste,
|
||||
@@ -715,6 +716,7 @@ function App(): React.JSX.Element {
|
||||
useEditorExternalWatch()
|
||||
useGlobalFileDrop()
|
||||
useAutoAckViewedAgent()
|
||||
useDashboardPopoutBridge(settings?.experimentalAgentDashboardPopout === true)
|
||||
|
||||
useEffect(() => {
|
||||
return onOnboardingReopened(setOnboarding)
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import '@testing-library/jest-dom/vitest'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import type { DashboardCard, DashboardSnapshot } from '../../../../shared/dashboard-snapshot'
|
||||
import { AgentKanbanBoard } from './AgentKanbanBoard'
|
||||
|
||||
// Stub the card and dialog so the board test stays free of xterm / Radix
|
||||
// machinery while still exercising the board-owned dialog wiring.
|
||||
vi.mock('./AgentKanbanCard', () => ({
|
||||
AgentKanbanCard: ({
|
||||
card,
|
||||
onOpenTerminal
|
||||
}: {
|
||||
card: DashboardCard
|
||||
onOpenTerminal: (card: DashboardCard) => void
|
||||
}) => (
|
||||
<div
|
||||
data-testid="card"
|
||||
data-bucket={card.bucket}
|
||||
data-unseen={card.unseen}
|
||||
onClick={() => onOpenTerminal(card)}
|
||||
>
|
||||
{card.worktreeName}
|
||||
</div>
|
||||
)
|
||||
}))
|
||||
vi.mock('./AgentTerminalDialog', () => ({
|
||||
AgentTerminalDialog: ({
|
||||
card,
|
||||
onOpenChange
|
||||
}: {
|
||||
card: DashboardCard | null
|
||||
onOpenChange: (open: boolean) => void
|
||||
}) => (
|
||||
<div
|
||||
data-testid="terminal-dialog"
|
||||
data-open={card !== null}
|
||||
data-bucket={card?.bucket}
|
||||
data-pty-id={card?.ptyId ?? undefined}
|
||||
>
|
||||
<button data-testid="terminal-dialog-close" onClick={() => onOpenChange(false)} />
|
||||
</div>
|
||||
)
|
||||
}))
|
||||
|
||||
function card(overrides: Partial<DashboardCard>): DashboardCard {
|
||||
return {
|
||||
paneKey: Math.random().toString(36),
|
||||
ptyId: 'p1',
|
||||
agentType: 'claude',
|
||||
bucket: 'working',
|
||||
dotState: 'working',
|
||||
task: 't',
|
||||
repoId: 'r1',
|
||||
worktreeId: 'w1',
|
||||
tabId: 'tab1',
|
||||
leafId: 'l1',
|
||||
repoName: 'Repo',
|
||||
worktreeName: 'wt',
|
||||
startedAt: 0,
|
||||
stateChangedAt: 0,
|
||||
unseen: false,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function renderBoard(cards: DashboardCard[]): void {
|
||||
const snapshot: DashboardSnapshot = { generatedAt: 1, cards }
|
||||
render(<AgentKanbanBoard snapshot={snapshot} />)
|
||||
}
|
||||
|
||||
const ackAgent = vi.fn(async () => {})
|
||||
|
||||
describe('AgentKanbanBoard', () => {
|
||||
beforeEach(() => {
|
||||
// The board relays seen-acks through the dashboard preload API.
|
||||
;(window as unknown as { api: unknown }).api = { dashboard: { ackAgent } }
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('renders the three fixed columns in order', () => {
|
||||
renderBoard([])
|
||||
const headers = screen.getAllByText(/Needs You|Working|Idle/)
|
||||
expect(headers.map((h) => h.textContent)).toEqual(['Needs You', 'Working', 'Idle'])
|
||||
})
|
||||
|
||||
it('places cards in their bucket column and counts them', () => {
|
||||
renderBoard([
|
||||
card({ bucket: 'attention', worktreeName: 'a1' }),
|
||||
card({ bucket: 'attention', worktreeName: 'a2' }),
|
||||
card({ bucket: 'idle', worktreeName: 'i1' })
|
||||
])
|
||||
const cards = screen.getAllByTestId('card')
|
||||
expect(cards).toHaveLength(3)
|
||||
expect(cards.filter((c) => c.dataset.bucket === 'attention')).toHaveLength(2)
|
||||
expect(within(document.body).getByText('i1').dataset.bucket).toBe('idle')
|
||||
expect(screen.getByText('3 total')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('shows "None" for empty columns', () => {
|
||||
renderBoard([card({ bucket: 'working' })])
|
||||
// attention and idle are empty → two "None" placeholders.
|
||||
expect(screen.getAllByText('None')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('orders cards in a column by most recent bucket entry first', () => {
|
||||
renderBoard([
|
||||
card({ bucket: 'working', worktreeName: 'old-move', stateChangedAt: 1000 }),
|
||||
card({ bucket: 'working', worktreeName: 'new-move', stateChangedAt: 3000 }),
|
||||
card({ bucket: 'working', worktreeName: 'mid-move', stateChangedAt: 2000 })
|
||||
])
|
||||
const names = screen.getAllByTestId('card').map((c) => c.textContent)
|
||||
expect(names).toEqual(['new-move', 'mid-move', 'old-move'])
|
||||
})
|
||||
|
||||
it('keeps the terminal dialog open across bucket moves and card removal', () => {
|
||||
const agent = card({ paneKey: 'pk-1', bucket: 'idle', worktreeName: 'wt1' })
|
||||
const { rerender } = render(<AgentKanbanBoard snapshot={{ generatedAt: 1, cards: [agent] }} />)
|
||||
expect(screen.getByTestId('terminal-dialog').dataset.open).toBe('false')
|
||||
|
||||
fireEvent.click(screen.getByTestId('card'))
|
||||
expect(screen.getByTestId('terminal-dialog').dataset.open).toBe('true')
|
||||
|
||||
// Sending a message flips the agent idle → working; the dialog must
|
||||
// follow the card to its new bucket instead of closing.
|
||||
const moved = { ...agent, bucket: 'working' as const, dotState: 'working' as const }
|
||||
rerender(<AgentKanbanBoard snapshot={{ generatedAt: 2, cards: [moved] }} />)
|
||||
expect(screen.getByTestId('terminal-dialog').dataset.open).toBe('true')
|
||||
expect(screen.getByTestId('terminal-dialog').dataset.bucket).toBe('working')
|
||||
|
||||
// Even a vanished card (pane closed) keeps the dialog up — the user
|
||||
// dismisses it explicitly, but stale live routing is cleared.
|
||||
rerender(<AgentKanbanBoard snapshot={{ generatedAt: 3, cards: [] }} />)
|
||||
expect(screen.getByTestId('terminal-dialog').dataset.open).toBe('true')
|
||||
expect(screen.getByTestId('terminal-dialog').dataset.ptyId).toBeUndefined()
|
||||
})
|
||||
|
||||
it('relays a seen-ack when a dialog opens and when the open agent changes state', () => {
|
||||
const agent = card({ paneKey: 'pk-ack', bucket: 'idle', unseen: true })
|
||||
const { rerender } = render(<AgentKanbanBoard snapshot={{ generatedAt: 1, cards: [agent] }} />)
|
||||
// unseen comes straight from the snapshot (the shared ack map).
|
||||
expect(screen.getByTestId('card').dataset.unseen).toBe('true')
|
||||
|
||||
fireEvent.click(screen.getByTestId('card'))
|
||||
expect(ackAgent).toHaveBeenCalledWith('pk-ack')
|
||||
ackAgent.mockClear()
|
||||
|
||||
// The ack round-trips through the main window; the next snapshot mutes it.
|
||||
rerender(
|
||||
<AgentKanbanBoard snapshot={{ generatedAt: 2, cards: [{ ...agent, unseen: false }] }} />
|
||||
)
|
||||
expect(screen.getByTestId('card').dataset.unseen).toBe('false')
|
||||
expect(ackAgent).not.toHaveBeenCalled()
|
||||
|
||||
// A state change while the dialog is open re-acks (watching counts as
|
||||
// seeing), so the card never flips bold under an open dialog.
|
||||
rerender(
|
||||
<AgentKanbanBoard
|
||||
snapshot={{
|
||||
generatedAt: 3,
|
||||
cards: [{ ...agent, bucket: 'working' as const, stateChangedAt: 2000, unseen: true }]
|
||||
}}
|
||||
/>
|
||||
)
|
||||
expect(ackAgent).toHaveBeenCalledWith('pk-ack')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,172 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import {
|
||||
DASHBOARD_BUCKET_ORDER,
|
||||
type DashboardBucket,
|
||||
type DashboardCard,
|
||||
type DashboardSnapshot
|
||||
} from '../../../../shared/dashboard-snapshot'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { AgentKanbanCard } from './AgentKanbanCard'
|
||||
import { AgentTerminalDialog } from './AgentTerminalDialog'
|
||||
import './agent-board-transitions.css'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
|
||||
function bucketLabel(bucket: DashboardBucket): string {
|
||||
switch (bucket) {
|
||||
case 'attention':
|
||||
return translate('dashboardPopout.bucket.attention', 'Needs You')
|
||||
case 'working':
|
||||
return translate('dashboardPopout.bucket.working', 'Working')
|
||||
case 'idle':
|
||||
return translate('dashboardPopout.bucket.idle', 'Idle')
|
||||
}
|
||||
}
|
||||
|
||||
function groupByBucket(cards: DashboardCard[]): Record<DashboardBucket, DashboardCard[]> {
|
||||
const grouped: Record<DashboardBucket, DashboardCard[]> = {
|
||||
attention: [],
|
||||
working: [],
|
||||
idle: []
|
||||
}
|
||||
for (const card of cards) {
|
||||
grouped[card.bucket].push(card)
|
||||
}
|
||||
// Most-recently-moved first: a card entering a column lands at the top,
|
||||
// matching the view-transition motion the user just watched.
|
||||
for (const bucket of DASHBOARD_BUCKET_ORDER) {
|
||||
grouped[bucket].sort((a, b) => b.stateChangedAt - a.stateChangedAt)
|
||||
}
|
||||
return grouped
|
||||
}
|
||||
|
||||
function KanbanColumn({
|
||||
bucket,
|
||||
cards,
|
||||
now,
|
||||
onOpenTerminal
|
||||
}: {
|
||||
bucket: DashboardBucket
|
||||
cards: DashboardCard[]
|
||||
now: number
|
||||
onOpenTerminal: (card: DashboardCard) => void
|
||||
}): React.JSX.Element {
|
||||
const highlight = bucket === 'attention' && cards.length > 0
|
||||
return (
|
||||
<section
|
||||
className={cn(
|
||||
'flex min-w-[264px] flex-1 flex-col rounded-xl border bg-muted/30',
|
||||
highlight ? 'border-amber-500/40' : 'border-border/60'
|
||||
)}
|
||||
>
|
||||
<header className="flex items-center gap-2 px-3 py-2">
|
||||
<span className="text-[11px] font-semibold uppercase tracking-[0.05em] text-muted-foreground">
|
||||
{bucketLabel(bucket)}
|
||||
</span>
|
||||
<span className="ml-auto rounded-full bg-background px-1.5 text-[11px] tabular-nums text-muted-foreground">
|
||||
{cards.length}
|
||||
</span>
|
||||
</header>
|
||||
<div className="scrollbar-sleek flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-2 pb-2">
|
||||
{cards.length === 0 ? (
|
||||
<p className="px-1 py-2 text-[11px] text-muted-foreground">
|
||||
{translate('dashboardPopout.bucket.empty', 'None')}
|
||||
</p>
|
||||
) : (
|
||||
cards.map((card) => (
|
||||
<AgentKanbanCard
|
||||
key={card.paneKey}
|
||||
card={card}
|
||||
now={now}
|
||||
onOpenTerminal={onOpenTerminal}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/** The pop-out agent board: status columns fed by the relayed snapshot. */
|
||||
export function AgentKanbanBoard({ snapshot }: { snapshot: DashboardSnapshot }): React.JSX.Element {
|
||||
const grouped = useMemo(() => groupByBucket(snapshot.cards), [snapshot.cards])
|
||||
const [now, setNow] = useState(() => Date.now())
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => setNow(Date.now()), 30_000)
|
||||
return () => clearInterval(timer)
|
||||
}, [])
|
||||
|
||||
// The open terminal dialog survives bucket moves: only the paneKey is
|
||||
// remembered, and the card data is re-resolved from each fresh snapshot.
|
||||
// The opened card is kept as a fallback so the dialog also survives the
|
||||
// card vanishing entirely (pane closed) — the user dismisses it explicitly.
|
||||
// Its live routing is cleared because daemon PTY ids can be reused.
|
||||
const [openedCard, setOpenedCard] = useState<DashboardCard | null>(null)
|
||||
const dialogCard = useMemo(() => {
|
||||
if (!openedCard) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
snapshot.cards.find((c) => c.paneKey === openedCard.paneKey) ?? {
|
||||
...openedCard,
|
||||
ptyId: null,
|
||||
leafId: null
|
||||
}
|
||||
)
|
||||
}, [snapshot.cards, openedCard])
|
||||
const handleDialogOpenChange = useCallback((open: boolean) => {
|
||||
if (!open) {
|
||||
setOpenedCard(null)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Seen-state is the app-wide ack map (same signal as the sidebar's bold/mute
|
||||
// rows): opening a dialog acks the agent in the main renderer via the relay,
|
||||
// and the next snapshot comes back with unseen=false.
|
||||
// ?. shields dialog-opening from dev-HMR preload skew (renderer updates
|
||||
// hot, the preload only on app restart) — acks just no-op until restart.
|
||||
const handleOpenTerminal = useCallback((card: DashboardCard) => {
|
||||
void window.api.dashboard.ackAgent?.(card.paneKey)
|
||||
setOpenedCard(card)
|
||||
}, [])
|
||||
// Watching the open dialog counts as seeing state changes as they happen —
|
||||
// without this, an agent finishing while you watch would re-flag its card.
|
||||
useEffect(() => {
|
||||
if (dialogCard?.unseen) {
|
||||
void window.api.dashboard.ackAgent?.(dialogCard.paneKey)
|
||||
}
|
||||
}, [dialogCard?.unseen, dialogCard?.paneKey])
|
||||
|
||||
return (
|
||||
<div className="flex h-screen w-screen flex-col bg-background text-foreground">
|
||||
<div className="flex shrink-0 items-center gap-2 border-b border-border px-4 py-2.5">
|
||||
<h1 className="text-[13px] font-semibold">
|
||||
{translate('dashboardPopout.title', 'Agents')}
|
||||
</h1>
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
{translate('dashboardPopout.total', '{{count}} total', {
|
||||
count: snapshot.cards.length
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
<div className="scrollbar-sleek flex min-h-0 flex-1 overflow-x-auto p-3">
|
||||
{/* Why: columns share the window width up to a readable cap; mx-auto
|
||||
centers the capped board so leftover space splits evenly instead of
|
||||
pooling on the right. In overflow the auto margins collapse to 0,
|
||||
keeping the left edge reachable while scrolling. */}
|
||||
<div className="mx-auto flex w-full max-w-[1280px] gap-3">
|
||||
{DASHBOARD_BUCKET_ORDER.map((bucket) => (
|
||||
<KanbanColumn
|
||||
key={bucket}
|
||||
bucket={bucket}
|
||||
cards={grouped[bucket]}
|
||||
now={now}
|
||||
onOpenTerminal={handleOpenTerminal}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<AgentTerminalDialog card={dialogCard} onOpenChange={handleDialogOpenChange} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import '@testing-library/jest-dom/vitest'
|
||||
import { act, cleanup, render, screen } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { DashboardCard } from '../../../../shared/dashboard-snapshot'
|
||||
import { i18n } from '@/i18n/i18n'
|
||||
import { AgentKanbanCard } from './AgentKanbanCard'
|
||||
|
||||
const agentIconRender = vi.fn()
|
||||
|
||||
vi.mock('@/lib/agent-catalog', () => ({
|
||||
AgentIcon: () => {
|
||||
agentIconRender()
|
||||
return <span data-testid="agent-icon" />
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/components/AgentStateDot', () => ({
|
||||
AgentStateDot: () => <span data-testid="state-dot" />
|
||||
}))
|
||||
|
||||
function card(overrides: Partial<DashboardCard> = {}): DashboardCard {
|
||||
return {
|
||||
paneKey: 'tab:leaf',
|
||||
ptyId: 'pty-1',
|
||||
agentType: 'claude',
|
||||
bucket: 'working',
|
||||
dotState: 'working',
|
||||
task: 'Review the change',
|
||||
repoId: 'repo-1',
|
||||
worktreeId: 'worktree-1',
|
||||
tabId: 'tab',
|
||||
leafId: 'leaf',
|
||||
repoName: 'Orca',
|
||||
worktreeName: 'dashboard-review',
|
||||
startedAt: 1_000,
|
||||
stateChangedAt: 1_000,
|
||||
unseen: false,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('AgentKanbanCard', () => {
|
||||
beforeEach(async () => {
|
||||
await i18n.changeLanguage('en')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('does not render an invented age when the start time is unknown', () => {
|
||||
render(
|
||||
<AgentKanbanCard card={card({ startedAt: 0 })} now={2_000_000_000} onOpenTerminal={vi.fn()} />
|
||||
)
|
||||
|
||||
expect(screen.queryByText(/\d+d/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('skips structured-clone rerenders until visible card data or its age changes', () => {
|
||||
const onOpenTerminal = vi.fn()
|
||||
const initial = card({ startedAt: 1_000 })
|
||||
const { rerender } = render(
|
||||
<AgentKanbanCard card={initial} now={61_500} onOpenTerminal={onOpenTerminal} />
|
||||
)
|
||||
expect(agentIconRender).toHaveBeenCalledTimes(1)
|
||||
expect(screen.getByText('1m')).toBeInTheDocument()
|
||||
|
||||
rerender(<AgentKanbanCard card={{ ...initial }} now={62_000} onOpenTerminal={onOpenTerminal} />)
|
||||
expect(agentIconRender).toHaveBeenCalledTimes(1)
|
||||
|
||||
rerender(
|
||||
<AgentKanbanCard card={{ ...initial }} now={121_500} onOpenTerminal={onOpenTerminal} />
|
||||
)
|
||||
expect(agentIconRender).toHaveBeenCalledTimes(2)
|
||||
expect(screen.getByText('2m')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('updates the relative age when the UI language changes', async () => {
|
||||
render(
|
||||
<AgentKanbanCard card={card({ startedAt: 1_000 })} now={121_500} onOpenTerminal={vi.fn()} />
|
||||
)
|
||||
expect(screen.getByText('2m')).toBeInTheDocument()
|
||||
|
||||
await act(async () => {
|
||||
await i18n.changeLanguage('ja')
|
||||
})
|
||||
|
||||
expect(screen.getByText('2分')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,143 @@
|
||||
import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { AgentIcon } from '@/lib/agent-catalog'
|
||||
import { agentTypeToIconAgent, formatAgentTypeLabel } from '@/lib/agent-status'
|
||||
import { AgentStateDot } from '@/components/AgentStateDot'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { DashboardCard } from '../../../../shared/dashboard-snapshot'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
|
||||
/** Compact "started N ago" (the card is glanceable — coarse units are fine). */
|
||||
function formatStartedAgo(startedAt: number, now: number): string {
|
||||
const seconds = Math.max(0, Math.floor((now - startedAt) / 1000))
|
||||
if (seconds < 60) {
|
||||
return translate('dashboardPopout.card.time.justNow', 'just now')
|
||||
}
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
if (minutes < 60) {
|
||||
return translate('dashboardPopout.card.time.minutes', '{{count}}m', { count: minutes })
|
||||
}
|
||||
const hours = Math.floor(minutes / 60)
|
||||
if (hours < 24) {
|
||||
return translate('dashboardPopout.card.time.hours', '{{count}}h', { count: hours })
|
||||
}
|
||||
return translate('dashboardPopout.card.time.days', '{{count}}d', {
|
||||
count: Math.floor(hours / 24)
|
||||
})
|
||||
}
|
||||
|
||||
function sameCard(a: DashboardCard, b: DashboardCard): boolean {
|
||||
return (
|
||||
a.paneKey === b.paneKey &&
|
||||
a.ptyId === b.ptyId &&
|
||||
a.agentType === b.agentType &&
|
||||
a.bucket === b.bucket &&
|
||||
a.dotState === b.dotState &&
|
||||
a.task === b.task &&
|
||||
a.lastUserMessage === b.lastUserMessage &&
|
||||
a.lastAgentMessage === b.lastAgentMessage &&
|
||||
a.repoId === b.repoId &&
|
||||
a.worktreeId === b.worktreeId &&
|
||||
a.tabId === b.tabId &&
|
||||
a.leafId === b.leafId &&
|
||||
a.repoName === b.repoName &&
|
||||
a.worktreeName === b.worktreeName &&
|
||||
a.startedAt === b.startedAt &&
|
||||
a.stateChangedAt === b.stateChangedAt &&
|
||||
a.unseen === b.unseen &&
|
||||
a.askSummary === b.askSummary
|
||||
)
|
||||
}
|
||||
|
||||
type AgentKanbanCardProps = {
|
||||
card: DashboardCard
|
||||
now: number
|
||||
/** Opens the board-level terminal dialog. The dialog is NOT owned by the
|
||||
* card: bucket moves remount the card, and an embedded dialog would close
|
||||
* the chat mid-conversation. */
|
||||
onOpenTerminal: (card: DashboardCard) => void
|
||||
}
|
||||
|
||||
/** One agent on the kanban board. Clicking opens the board's live terminal dialog. */
|
||||
export const AgentKanbanCard = memo(
|
||||
function AgentKanbanCard({ card, now, onOpenTerminal }: AgentKanbanCardProps): React.JSX.Element {
|
||||
useTranslation()
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onOpenTerminal(card)}
|
||||
// Why: a stable per-agent view-transition-name lets the browser morph
|
||||
// the card from its old column to its new one when its bucket changes.
|
||||
// paneKey has ':'/'/' which aren't valid in a custom-ident, so slugify.
|
||||
style={{ viewTransitionName: `agentcard-${card.paneKey.replace(/[^a-zA-Z0-9]/g, '-')}` }}
|
||||
className={cn(
|
||||
'group flex w-full flex-col gap-1.5 rounded-lg border border-border/60 bg-card p-2.5 text-left',
|
||||
'transition-colors hover:border-border hover:bg-accent/40',
|
||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<AgentIcon agent={agentTypeToIconAgent(card.agentType)} size={14} />
|
||||
<span
|
||||
// Why: same unvisited treatment as the sidebar's DashboardAgentRow —
|
||||
// bold+bright until acked, normal+muted after — so both surfaces
|
||||
// read identically (the ack map is shared).
|
||||
className={cn(
|
||||
'truncate text-[12.5px]',
|
||||
card.unseen ? 'font-semibold text-foreground' : 'font-normal text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{card.worktreeName}
|
||||
</span>
|
||||
<AgentStateDot state={card.dotState} className="ml-auto" />
|
||||
</div>
|
||||
|
||||
{card.lastUserMessage || card.lastAgentMessage ? (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
{card.lastUserMessage ? (
|
||||
<div className="line-clamp-1 text-[11px] leading-snug text-muted-foreground">
|
||||
<span className="font-medium text-foreground/45">
|
||||
{translate('dashboardPopout.card.you', 'You')}
|
||||
</span>{' '}
|
||||
{card.lastUserMessage}
|
||||
</div>
|
||||
) : null}
|
||||
{card.lastAgentMessage ? (
|
||||
<div className="line-clamp-2 text-xs leading-snug text-foreground/90">
|
||||
<span className="font-medium text-foreground/45">
|
||||
{formatAgentTypeLabel(card.agentType)}
|
||||
</span>{' '}
|
||||
{card.lastAgentMessage}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : card.task ? (
|
||||
<div className="line-clamp-2 text-xs leading-snug text-foreground/90">{card.task}</div>
|
||||
) : null}
|
||||
|
||||
{card.askSummary ? (
|
||||
<div className="flex items-start gap-1 rounded-md bg-amber-500/10 px-1.5 py-1 text-[11px] text-amber-600 dark:text-amber-400">
|
||||
<span aria-hidden>✋</span>
|
||||
<span className="line-clamp-2">{card.askSummary}</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex items-center gap-2 text-[11px] text-muted-foreground">
|
||||
<span className="truncate font-mono">{card.repoName}</span>
|
||||
{card.startedAt > 0 ? (
|
||||
<span className="ml-auto shrink-0 tabular-nums">
|
||||
{formatStartedAgo(card.startedAt, now)}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
},
|
||||
(previous, next) =>
|
||||
previous.onOpenTerminal === next.onOpenTerminal &&
|
||||
sameCard(previous.card, next.card) &&
|
||||
(previous.card.startedAt <= 0 ||
|
||||
formatStartedAgo(previous.card.startedAt, previous.now) ===
|
||||
formatStartedAgo(next.card.startedAt, next.now))
|
||||
)
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useCallback } from 'react'
|
||||
import { AgentIcon } from '@/lib/agent-catalog'
|
||||
import { agentTypeToIconAgent, formatAgentTypeLabel } from '@/lib/agent-status'
|
||||
import { agentStateLabel } from '@/components/AgentStateDot'
|
||||
import { Dialog, DialogClose, DialogContent, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import type { DashboardCard } from '../../../../shared/dashboard-snapshot'
|
||||
import { AgentTerminalPreview } from './AgentTerminalPreview'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
|
||||
type AgentTerminalDialogProps = {
|
||||
/** The agent shown in the dialog; null renders the dialog closed. */
|
||||
card: DashboardCard | null
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* The near-fullscreen live-terminal dialog for one agent. Hosted by the BOARD,
|
||||
* not the card: sending a message flips the agent's bucket, which remounts its
|
||||
* card in another column — a card-owned dialog would close mid-conversation.
|
||||
* Only an explicit close (button, click-outside, Esc outside the terminal)
|
||||
* dismisses it.
|
||||
*/
|
||||
export function AgentTerminalDialog({
|
||||
card,
|
||||
onOpenChange
|
||||
}: AgentTerminalDialogProps): React.JSX.Element {
|
||||
const reveal = useCallback(() => {
|
||||
if (!card) {
|
||||
return
|
||||
}
|
||||
void window.api.dashboard.revealAgent({
|
||||
repoId: card.repoId,
|
||||
worktreeId: card.worktreeId,
|
||||
tabId: card.tabId,
|
||||
leafId: card.leafId
|
||||
})
|
||||
}, [card])
|
||||
|
||||
return (
|
||||
<Dialog open={card !== null} onOpenChange={onOpenChange}>
|
||||
{card ? (
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
aria-describedby={undefined}
|
||||
// Why: sm:max-w-lg in DialogContent's base classes would defeat a bare
|
||||
// max-w-*, so the full-width override must carry the same breakpoint.
|
||||
className="flex w-[calc(100vw-40px)] max-w-none flex-col gap-0 p-0 sm:max-w-none"
|
||||
// Why: Esc must reach the agent (interrupt) when typing in the
|
||||
// terminal, not dismiss the dialog; xterm has already consumed the
|
||||
// keystroke by the time Radix sees it. Click-outside still closes.
|
||||
onEscapeKeyDown={(e) => {
|
||||
if (e.target instanceof HTMLElement && e.target.closest('.xterm')) {
|
||||
e.preventDefault()
|
||||
}
|
||||
}}
|
||||
// Why: the preview focuses its terminal once the snapshot paints;
|
||||
// Radix's default focus target would tug focus away first.
|
||||
onOpenAutoFocus={(e) => {
|
||||
if (card.ptyId) {
|
||||
e.preventDefault()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-1.5 px-2.5 py-2">
|
||||
<AgentIcon agent={agentTypeToIconAgent(card.agentType)} size={13} />
|
||||
<DialogTitle className="text-[12px] leading-normal font-semibold">
|
||||
{card.worktreeName}
|
||||
</DialogTitle>
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
{formatAgentTypeLabel(card.agentType)} · {agentStateLabel(card.dotState)}
|
||||
</span>
|
||||
</div>
|
||||
{card.ptyId ? (
|
||||
<AgentTerminalPreview ptyId={card.ptyId} />
|
||||
) : (
|
||||
<div className="px-2.5 pb-2 text-[11px] text-muted-foreground">
|
||||
{translate(
|
||||
'dashboardPopout.terminal.closed',
|
||||
"No live terminal — this agent's pane has closed."
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-end gap-2 px-2.5 py-1.5">
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline" size="xs">
|
||||
{translate('dashboardPopout.terminal.close', 'Close')}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline" size="xs" onClick={reveal}>
|
||||
{translate('dashboardPopout.terminal.focusWorktree', 'Focus worktree')}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
</div>
|
||||
</DialogContent>
|
||||
) : null}
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import '@testing-library/jest-dom/vitest'
|
||||
import { act, cleanup, render, waitFor } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const terminalHarness = vi.hoisted(() => ({
|
||||
instances: [] as {
|
||||
write: ReturnType<typeof vi.fn>
|
||||
writeCallbacks: (() => void)[]
|
||||
onDataListener: ((data: string) => void) | null
|
||||
dispose: ReturnType<typeof vi.fn>
|
||||
resize: ReturnType<typeof vi.fn>
|
||||
reset: ReturnType<typeof vi.fn>
|
||||
}[],
|
||||
userInputListener: null as (() => void) | null,
|
||||
userInputDispose: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('@xterm/xterm', () => ({
|
||||
Terminal: class {
|
||||
rows = 24
|
||||
buffer = { active: { cursorY: 0 } }
|
||||
writeCallbacks: (() => void)[] = []
|
||||
onDataListener: ((data: string) => void) | null = null
|
||||
write = vi.fn((_data: string, callback?: () => void) => {
|
||||
if (callback) {
|
||||
this.writeCallbacks.push(callback)
|
||||
}
|
||||
})
|
||||
open = vi.fn()
|
||||
focus = vi.fn()
|
||||
dispose = vi.fn()
|
||||
resize = vi.fn()
|
||||
reset = vi.fn()
|
||||
onData = vi.fn((listener: (data: string) => void) => {
|
||||
this.onDataListener = listener
|
||||
return { dispose: vi.fn() }
|
||||
})
|
||||
|
||||
constructor() {
|
||||
terminalHarness.instances.push(this)
|
||||
}
|
||||
}
|
||||
}))
|
||||
vi.mock('@/lib/pane-manager/pane-terminal-options', () => ({
|
||||
buildDefaultTerminalOptions: () => ({})
|
||||
}))
|
||||
vi.mock('@/components/terminal-pane/terminal-user-input-signal', () => ({
|
||||
subscribeToTerminalUserInput: (_terminal: unknown, listener: () => void) => {
|
||||
terminalHarness.userInputListener = listener
|
||||
return { dispose: terminalHarness.userInputDispose }
|
||||
}
|
||||
}))
|
||||
vi.mock('@/components/terminal-pane/use-system-prefers-dark', () => ({
|
||||
useSystemPrefersDark: () => false
|
||||
}))
|
||||
vi.mock('@/store', () => ({
|
||||
useAppStore: (selector: (state: { settings: null }) => unknown) => selector({ settings: null })
|
||||
}))
|
||||
|
||||
import { AgentTerminalPreview } from './AgentTerminalPreview'
|
||||
|
||||
describe('AgentTerminalPreview', () => {
|
||||
const input = vi.fn(async () => true)
|
||||
const ack = vi.fn(async () => {})
|
||||
const unsubscribe = vi.fn(async () => {})
|
||||
const connect = vi.fn()
|
||||
let emitData: ((payload: unknown) => void) | null
|
||||
|
||||
beforeEach(() => {
|
||||
terminalHarness.instances.length = 0
|
||||
terminalHarness.userInputListener = null
|
||||
emitData = null
|
||||
connect.mockResolvedValue({
|
||||
snapshot: { data: '', cols: 80, rows: 24, seq: 1 },
|
||||
replay: []
|
||||
})
|
||||
Object.assign(window, {
|
||||
api: {
|
||||
terminalPreview: {
|
||||
connect,
|
||||
input,
|
||||
ack,
|
||||
unsubscribe,
|
||||
onData: (listener: (payload: unknown) => void) => {
|
||||
emitData = listener
|
||||
return vi.fn()
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('routes signaled user input while a live write parses and drops parser replies', async () => {
|
||||
render(<AgentTerminalPreview ptyId="pty-1" />)
|
||||
await waitFor(() => expect(terminalHarness.instances).toHaveLength(1))
|
||||
const terminal = terminalHarness.instances[0]!
|
||||
await waitFor(() => expect(terminal.onDataListener).not.toBeNull())
|
||||
|
||||
act(() => {
|
||||
emitData?.({ type: 'data', ptyId: 'pty-1', data: '\x1b[6n', bytes: 4 })
|
||||
})
|
||||
expect(terminal.write).toHaveBeenCalledWith('\x1b[6n', expect.any(Function))
|
||||
|
||||
act(() => {
|
||||
terminalHarness.userInputListener?.()
|
||||
terminal.onDataListener?.('k')
|
||||
terminal.onDataListener?.('\x1b[1;1R')
|
||||
})
|
||||
expect(input).toHaveBeenCalledTimes(1)
|
||||
expect(input).toHaveBeenCalledWith('pty-1', 'k')
|
||||
|
||||
act(() => terminal.writeCallbacks.shift()?.())
|
||||
expect(ack).toHaveBeenCalledWith('pty-1', 4)
|
||||
})
|
||||
|
||||
it('keeps the existing terminal visible while a resync snapshot is captured', async () => {
|
||||
let resolveRefresh!: (value: {
|
||||
snapshot: { data: string; cols: number; rows: number; seq: number }
|
||||
replay: string[]
|
||||
}) => void
|
||||
connect
|
||||
.mockResolvedValueOnce({
|
||||
snapshot: { data: 'first', cols: 80, rows: 24, seq: 1 },
|
||||
replay: []
|
||||
})
|
||||
.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
resolveRefresh = resolve
|
||||
})
|
||||
)
|
||||
const view = render(<AgentTerminalPreview ptyId="pty-1" />)
|
||||
await waitFor(() => expect(terminalHarness.instances).toHaveLength(1))
|
||||
const terminal = terminalHarness.instances[0]!
|
||||
|
||||
act(() => emitData?.({ type: 'resync', ptyId: 'pty-1' }))
|
||||
await waitFor(() => expect(connect).toHaveBeenCalledTimes(2))
|
||||
expect(terminalHarness.instances).toHaveLength(1)
|
||||
expect(terminal.dispose).not.toHaveBeenCalled()
|
||||
expect(terminal.reset).not.toHaveBeenCalled()
|
||||
expect(view.queryByText(/No live terminal/)).not.toBeInTheDocument()
|
||||
|
||||
await act(async () => {
|
||||
resolveRefresh({
|
||||
snapshot: { data: 'second', cols: 100, rows: 30, seq: 2 },
|
||||
replay: []
|
||||
})
|
||||
})
|
||||
await waitFor(() => expect(terminal.reset).toHaveBeenCalledTimes(1))
|
||||
expect(terminal.resize).toHaveBeenCalledWith(100, 30)
|
||||
expect(terminalHarness.instances).toHaveLength(1)
|
||||
expect(terminal.dispose).not.toHaveBeenCalled()
|
||||
expect(view.queryByText(/No live terminal/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('disposes a stale terminal when resync confirms the pty is gone', async () => {
|
||||
connect
|
||||
.mockResolvedValueOnce({
|
||||
snapshot: { data: 'first', cols: 80, rows: 24, seq: 1 },
|
||||
replay: []
|
||||
})
|
||||
.mockResolvedValueOnce({ snapshot: null, replay: [] })
|
||||
const view = render(<AgentTerminalPreview ptyId="pty-1" />)
|
||||
await waitFor(() => expect(terminalHarness.instances).toHaveLength(1))
|
||||
const terminal = terminalHarness.instances[0]!
|
||||
|
||||
act(() => emitData?.({ type: 'resync', ptyId: 'pty-1' }))
|
||||
|
||||
await waitFor(() => expect(view.getByText(/No live terminal/)).toBeInTheDocument())
|
||||
expect(terminal.dispose).toHaveBeenCalledTimes(1)
|
||||
expect(terminalHarness.userInputDispose).toHaveBeenCalledTimes(1)
|
||||
expect(unsubscribe).toHaveBeenCalledWith('pty-1')
|
||||
})
|
||||
|
||||
it('connects a replacement pty after the previous pty was gone', async () => {
|
||||
connect.mockResolvedValueOnce({ snapshot: null, replay: [] }).mockResolvedValueOnce({
|
||||
snapshot: { data: 'replacement', cols: 80, rows: 24, seq: 1 },
|
||||
replay: []
|
||||
})
|
||||
const view = render(<AgentTerminalPreview ptyId="pty-gone" />)
|
||||
await waitFor(() => expect(view.getByText(/No live terminal/)).toBeInTheDocument())
|
||||
|
||||
view.rerender(<AgentTerminalPreview ptyId="pty-live" />)
|
||||
|
||||
await waitFor(() => expect(terminalHarness.instances).toHaveLength(1))
|
||||
expect(connect).toHaveBeenLastCalledWith('pty-live', { scrollbackRows: 24 })
|
||||
expect(view.queryByText(/No live terminal/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('delays repeated capture after an overflow and cancels the retry on unmount', async () => {
|
||||
vi.useFakeTimers()
|
||||
connect.mockResolvedValue({
|
||||
snapshot: { data: 'screen', cols: 80, rows: 24, seq: 1 },
|
||||
replay: [],
|
||||
resyncRequired: true
|
||||
})
|
||||
const view = render(<AgentTerminalPreview ptyId="pty-1" />)
|
||||
await vi.waitFor(() => expect(terminalHarness.instances).toHaveLength(1))
|
||||
const terminal = terminalHarness.instances[0]!
|
||||
expect(connect).toHaveBeenCalledTimes(1)
|
||||
|
||||
act(() => terminal.writeCallbacks.splice(0).forEach((callback) => callback()))
|
||||
await vi.advanceTimersByTimeAsync(149)
|
||||
expect(connect).toHaveBeenCalledTimes(1)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(connect).toHaveBeenCalledTimes(2)
|
||||
|
||||
act(() => terminal.writeCallbacks.splice(0).forEach((callback) => callback()))
|
||||
view.unmount()
|
||||
await vi.advanceTimersByTimeAsync(150)
|
||||
expect(connect).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,288 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Terminal } from '@xterm/xterm'
|
||||
import '@xterm/xterm/css/xterm.css'
|
||||
import { buildDefaultTerminalOptions } from '@/lib/pane-manager/pane-terminal-options'
|
||||
import { subscribeToTerminalUserInput } from '@/components/terminal-pane/terminal-user-input-signal'
|
||||
import { composeActiveTerminalTheme } from '@/components/terminal-pane/terminal-appearance'
|
||||
import { useSystemPrefersDark } from '@/components/terminal-pane/use-system-prefers-dark'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { getBuiltinTheme, resolveEffectiveTerminalAppearance } from '@/lib/terminal-theme'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useAppStore } from '@/store'
|
||||
import type { TerminalPreviewDataPayload } from '../../../../shared/terminal-preview'
|
||||
|
||||
const PREVIEW_SCROLLBACK_ROWS = 24
|
||||
const FALLBACK_COLS = 80
|
||||
const FALLBACK_ROWS = 24
|
||||
const RESYNC_RETRY_DELAY_MS = 150
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(max, Math.max(min, value))
|
||||
}
|
||||
|
||||
/**
|
||||
* Live peek at an agent's terminal, streaming from the main process's per-PTY
|
||||
* headless emulator. The terminal is created at the pane's REAL cols/rows —
|
||||
* the serialized ANSI was produced at those dimensions, and replaying it into
|
||||
* a narrower terminal rewraps every full-width line into garbage. The box
|
||||
* stays fixed; the oversized terminal is scaled down to fit the width and
|
||||
* bottom-anchored so the tail (prompt, status line) stays visible. Keystrokes
|
||||
* pass through to the PTY; DOM renderer so it never grabs a WebGL context.
|
||||
*/
|
||||
export function AgentTerminalPreview({ ptyId }: { ptyId: string }): React.JSX.Element {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const settings = useAppStore((state) => state.settings)
|
||||
const systemPrefersDark = useSystemPrefersDark()
|
||||
const terminalTheme = useMemo(() => {
|
||||
if (!settings) {
|
||||
return null
|
||||
}
|
||||
const appearance = resolveEffectiveTerminalAppearance(settings, systemPrefersDark)
|
||||
return composeActiveTerminalTheme(
|
||||
appearance.theme ?? getBuiltinTheme(appearance.themeName),
|
||||
settings
|
||||
)
|
||||
}, [settings, systemPrefersDark])
|
||||
// A null snapshot means no serializer knows this pty (it died or was never
|
||||
// spawned this session) — say so instead of painting a silent blank terminal.
|
||||
const [ptyGone, setPtyGone] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
setPtyGone(false)
|
||||
const container = containerRef.current
|
||||
if (!container) {
|
||||
return
|
||||
}
|
||||
let disposed = false
|
||||
let terminal: Terminal | null = null
|
||||
let offData: (() => void) | null = null
|
||||
let userInputDisposable: { dispose: () => void } | null = null
|
||||
let refreshInFlight = false
|
||||
let refreshAgain = false
|
||||
let retryTimer: ReturnType<typeof setTimeout> | null = null
|
||||
const pendingLivePayloads: Extract<TerminalPreviewDataPayload, { type: 'data' }>[] = []
|
||||
|
||||
const fitToBox = (): void => {
|
||||
const screen = container.querySelector<HTMLElement>('.xterm-screen')
|
||||
const box = container.parentElement
|
||||
if (!screen || !box || !terminal) {
|
||||
return
|
||||
}
|
||||
const scale = Math.min(1, box.clientWidth / Math.max(1, screen.offsetWidth))
|
||||
container.style.transform = scale < 1 ? `scale(${scale})` : ''
|
||||
// Anchor whichever end keeps the CURSOR row in view when the terminal is
|
||||
// taller than the box: a fresh shell prompts at the TOP of its screen
|
||||
// (blind bottom-anchoring clipped it away), while a busy TUI keeps its
|
||||
// action at the bottom.
|
||||
const cellHeight = screen.offsetHeight / Math.max(1, terminal.rows)
|
||||
const cursorBottom = (terminal.buffer.active.cursorY + 1) * cellHeight * scale
|
||||
const anchorTop = cursorBottom <= box.clientHeight
|
||||
box.style.alignItems = anchorTop ? 'flex-start' : 'flex-end'
|
||||
container.style.transformOrigin = anchorTop ? 'top left' : 'bottom left'
|
||||
}
|
||||
// Re-fit after every parsed write (cursor may move ends); rAF coalesces.
|
||||
let fitScheduled = false
|
||||
const scheduleFit = (): void => {
|
||||
if (fitScheduled) {
|
||||
return
|
||||
}
|
||||
fitScheduled = true
|
||||
requestAnimationFrame(() => {
|
||||
fitScheduled = false
|
||||
fitToBox()
|
||||
})
|
||||
}
|
||||
|
||||
let replayDepth = 0
|
||||
const writeReplayed = (chunk: string, onDone?: () => void): void => {
|
||||
replayDepth++
|
||||
terminal?.write(chunk, () => {
|
||||
replayDepth--
|
||||
scheduleFit()
|
||||
onDone?.()
|
||||
})
|
||||
}
|
||||
|
||||
const writeLive = (payload: Extract<TerminalPreviewDataPayload, { type: 'data' }>): void => {
|
||||
if (!terminal) {
|
||||
pendingLivePayloads.push(payload)
|
||||
return
|
||||
}
|
||||
writeReplayed(payload.data, () => {
|
||||
if (!disposed) {
|
||||
void window.api.terminalPreview.ack(ptyId, payload.bytes)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const installInputRouting = (): void => {
|
||||
if (!terminal) {
|
||||
return
|
||||
}
|
||||
let pendingUserInputSignals = 0
|
||||
userInputDisposable = subscribeToTerminalUserInput(terminal, () => {
|
||||
pendingUserInputSignals = Math.min(32, pendingUserInputSignals + 1)
|
||||
})
|
||||
terminal.onData((data) => {
|
||||
const signaledUserInput = pendingUserInputSignals > 0
|
||||
if (signaledUserInput) {
|
||||
pendingUserInputSignals--
|
||||
}
|
||||
// Why: core's signal distinguishes real input from parser replies, so typing survives live replay without forwarding synthetic CPR/DA bytes.
|
||||
if (userInputDisposable ? !signaledUserInput : replayDepth > 0) {
|
||||
return
|
||||
}
|
||||
void window.api.terminalPreview.input(ptyId, data)
|
||||
})
|
||||
}
|
||||
|
||||
const replayConnection = (
|
||||
connection: Awaited<ReturnType<typeof window.api.terminalPreview.connect>>,
|
||||
replaceExisting: boolean,
|
||||
requestRefresh: () => void
|
||||
): void => {
|
||||
const snap = connection.snapshot!
|
||||
if (!terminal) {
|
||||
terminal = new Terminal({
|
||||
...buildDefaultTerminalOptions(),
|
||||
cols: clamp(snap.cols ?? FALLBACK_COLS, 2, 500),
|
||||
rows: clamp(snap.rows ?? FALLBACK_ROWS, 2, 200),
|
||||
theme: terminalTheme ?? undefined,
|
||||
scrollback: 1000
|
||||
})
|
||||
try {
|
||||
terminal.open(container)
|
||||
} catch {
|
||||
terminal.dispose()
|
||||
terminal = null
|
||||
return
|
||||
}
|
||||
installInputRouting()
|
||||
} else if (replaceExisting) {
|
||||
// Why: keep the old frame visible during capture, then atomically replace it once the authoritative snapshot arrives.
|
||||
terminal.resize(
|
||||
clamp(snap.cols ?? FALLBACK_COLS, 2, 500),
|
||||
clamp(snap.rows ?? FALLBACK_ROWS, 2, 200)
|
||||
)
|
||||
terminal.reset()
|
||||
}
|
||||
if (snap.scrollbackAnsi) {
|
||||
writeReplayed(snap.scrollbackAnsi)
|
||||
}
|
||||
if (snap.data) {
|
||||
writeReplayed(snap.data)
|
||||
}
|
||||
if (snap.pendingEscapeTailAnsi) {
|
||||
writeReplayed(snap.pendingEscapeTailAnsi)
|
||||
}
|
||||
for (const data of connection.replay) {
|
||||
writeReplayed(data)
|
||||
}
|
||||
for (const payload of pendingLivePayloads.splice(0)) {
|
||||
writeLive(payload)
|
||||
}
|
||||
if (connection.resyncRequired) {
|
||||
refreshAgain = false
|
||||
// Why: sustained output can overflow every capture; delay retries so recovery cannot spin two serializations per event-loop turn.
|
||||
writeReplayed('', () => {
|
||||
if (disposed || retryTimer) {
|
||||
return
|
||||
}
|
||||
retryTimer = setTimeout(() => {
|
||||
retryTimer = null
|
||||
requestRefresh()
|
||||
}, RESYNC_RETRY_DELAY_MS)
|
||||
})
|
||||
} else if (refreshAgain) {
|
||||
refreshAgain = false
|
||||
// Queue behind every replay write so replacement never clears a half-parsed frame.
|
||||
writeReplayed('', requestRefresh)
|
||||
}
|
||||
scheduleFit()
|
||||
terminal.focus()
|
||||
}
|
||||
|
||||
const setup = async (replaceExisting = false): Promise<void> => {
|
||||
if (refreshInFlight) {
|
||||
refreshAgain = true
|
||||
return
|
||||
}
|
||||
refreshInFlight = true
|
||||
const connection = await window.api.terminalPreview.connect(ptyId, {
|
||||
scrollbackRows: PREVIEW_SCROLLBACK_ROWS
|
||||
})
|
||||
if (disposed) {
|
||||
return
|
||||
}
|
||||
const snap = connection.snapshot
|
||||
if (!snap) {
|
||||
refreshInFlight = false
|
||||
setPtyGone(true)
|
||||
offData?.()
|
||||
offData = null
|
||||
userInputDisposable?.dispose()
|
||||
userInputDisposable = null
|
||||
terminal?.dispose()
|
||||
terminal = null
|
||||
void window.api.terminalPreview.unsubscribe(ptyId)
|
||||
return
|
||||
}
|
||||
refreshInFlight = false
|
||||
if (!connection.resyncRequired && retryTimer) {
|
||||
clearTimeout(retryTimer)
|
||||
retryTimer = null
|
||||
}
|
||||
replayConnection(connection, replaceExisting, () => void setup(true))
|
||||
}
|
||||
|
||||
offData = window.api.terminalPreview.onData((payload) => {
|
||||
if (payload.ptyId !== ptyId) {
|
||||
return
|
||||
}
|
||||
if (payload.type === 'resync') {
|
||||
void setup(true)
|
||||
return
|
||||
}
|
||||
writeLive(payload)
|
||||
})
|
||||
|
||||
void setup()
|
||||
|
||||
return () => {
|
||||
disposed = true
|
||||
if (retryTimer) {
|
||||
clearTimeout(retryTimer)
|
||||
}
|
||||
offData?.()
|
||||
userInputDisposable?.dispose()
|
||||
void window.api.terminalPreview.unsubscribe(ptyId)
|
||||
terminal?.dispose()
|
||||
}
|
||||
}, [ptyId, terminalTheme])
|
||||
|
||||
return (
|
||||
// Why: a size FIXED by the viewport (not shrink-to-fit) + overflow-hidden
|
||||
// keeps the dialog stable no matter how wide/tall the pane's serialized
|
||||
// buffer is. The terminal keeps the pane's true dimensions and is scaled/
|
||||
// clipped to fit; fitToBox anchors whichever end keeps the cursor in view.
|
||||
<div
|
||||
className="relative h-[calc(100vh-140px)] w-full overflow-hidden bg-background p-1.5"
|
||||
style={terminalTheme?.background ? { backgroundColor: terminalTheme.background } : undefined}
|
||||
>
|
||||
{ptyGone ? (
|
||||
<div className="absolute inset-0 flex items-center justify-center px-2.5 py-8 text-center text-[11px] text-muted-foreground">
|
||||
{translate(
|
||||
'dashboardPopout.terminal.closed',
|
||||
"No live terminal — this agent's pane has closed."
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
<div
|
||||
aria-hidden={ptyGone || undefined}
|
||||
className={cn('flex h-full w-full items-end overflow-hidden', ptyGone && 'invisible')}
|
||||
>
|
||||
<div ref={containerRef} className="origin-bottom-left" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { AgentKanbanBoard } from './AgentKanbanBoard'
|
||||
import { useDashboardSnapshot } from './useDashboardSnapshot'
|
||||
|
||||
type DashboardPopoutRootProps = {
|
||||
/** The layout requested via popout.html?view=<name>. Only "kanban" exists
|
||||
* today; unknown views fall back to it. */
|
||||
view: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Root of the pop-out dashboard window. Subscribes to the live snapshot relayed
|
||||
* from the main window and renders the requested layout.
|
||||
*/
|
||||
export function DashboardPopoutRoot(_props: DashboardPopoutRootProps): React.JSX.Element {
|
||||
const snapshot = useDashboardSnapshot()
|
||||
return <AgentKanbanBoard snapshot={snapshot} />
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* View-transition tuning for the agent board. Each card carries a unique
|
||||
* `view-transition-name` (agentcard-…), so when a card changes column the
|
||||
* browser morphs it from its old position to the new one. Only loaded in the
|
||||
* pop-out (imported by AgentKanbanBoard), so these document-global pseudo rules
|
||||
* never affect the main window.
|
||||
*/
|
||||
|
||||
/* Card move/resize easing (applies to every transition group). */
|
||||
::view-transition-group(*) {
|
||||
animation-duration: 260ms;
|
||||
animation-timing-function: cubic-bezier(0.2, 0, 0, 1);
|
||||
}
|
||||
|
||||
/* The columns/background don't move, so skip the root cross-fade — it would
|
||||
* otherwise briefly double-image the lane heights as a card leaves/joins. */
|
||||
::view-transition-old(root),
|
||||
::view-transition-new(root) {
|
||||
animation-duration: 0s;
|
||||
}
|
||||
|
||||
/*
|
||||
* Enter/exit. A card that MOVES columns has both an old and a new image, so it
|
||||
* is not `:only-child` and just morphs position (above). A genuinely new or
|
||||
* removed card has only one image (`:only-child`) — fade + scale it.
|
||||
*/
|
||||
@keyframes agent-card-enter {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: scale(0.96);
|
||||
}
|
||||
}
|
||||
@keyframes agent-card-exit {
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: scale(0.96);
|
||||
}
|
||||
}
|
||||
::view-transition-new(*):only-child {
|
||||
animation: 240ms cubic-bezier(0.2, 0, 0, 1) both agent-card-enter;
|
||||
}
|
||||
::view-transition-old(*):only-child {
|
||||
animation: 180ms cubic-bezier(0.4, 0, 1, 1) both agent-card-exit;
|
||||
}
|
||||
|
||||
/* Respect reduced-motion — the JS also skips startViewTransition, but guard the
|
||||
* pseudo animations too. */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
::view-transition-group(*),
|
||||
::view-transition-old(*),
|
||||
::view-transition-new(*) {
|
||||
animation: none !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { flushSync } from 'react-dom'
|
||||
import {
|
||||
EMPTY_DASHBOARD_SNAPSHOT,
|
||||
type DashboardSnapshot
|
||||
} from '../../../../shared/dashboard-snapshot'
|
||||
|
||||
/** Which column each card sits in — the only thing a view transition should
|
||||
* animate on. Content-only updates (such as new messages) must not. */
|
||||
function columnSignature(snapshot: DashboardSnapshot): string {
|
||||
return snapshot.cards
|
||||
.map((card) => `${card.paneKey}:${card.bucket}`)
|
||||
.sort()
|
||||
.join(',')
|
||||
}
|
||||
|
||||
function prefersReducedMotion(): boolean {
|
||||
return window.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true
|
||||
}
|
||||
|
||||
/**
|
||||
* Pop-out side of the dashboard bridge: subscribe to snapshots relayed from the
|
||||
* main window and request an initial one on mount. When a card changes column
|
||||
* (or one appears/disappears), the update is wrapped in a View Transition so
|
||||
* the browser morphs each card from its old position to its new one.
|
||||
*/
|
||||
export function useDashboardSnapshot(): DashboardSnapshot {
|
||||
const [snapshot, setSnapshot] = useState<DashboardSnapshot>(EMPTY_DASHBOARD_SNAPSHOT)
|
||||
const columnSignatureRef = useRef('')
|
||||
|
||||
useEffect(() => {
|
||||
const apply = (next: DashboardSnapshot): void => {
|
||||
const nextSignature = columnSignature(next)
|
||||
const layoutChanged = nextSignature !== columnSignatureRef.current
|
||||
columnSignatureRef.current = nextSignature
|
||||
|
||||
const startViewTransition = document.startViewTransition?.bind(document)
|
||||
if (!layoutChanged || prefersReducedMotion() || !startViewTransition) {
|
||||
setSnapshot(next)
|
||||
return
|
||||
}
|
||||
// flushSync so the DOM reflects `next` synchronously inside the transition
|
||||
// callback — the browser captures the "after" state from it.
|
||||
startViewTransition(() => {
|
||||
flushSync(() => setSnapshot(next))
|
||||
})
|
||||
}
|
||||
|
||||
const unsubscribe = window.api.dashboard.onSnapshot(apply)
|
||||
void window.api.dashboard.requestSnapshot()
|
||||
return unsubscribe
|
||||
}, [])
|
||||
|
||||
return snapshot
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildDashboardSnapshot, type DashboardSnapshotState } from './build-dashboard-snapshot'
|
||||
import {
|
||||
AGENT_STATUS_STALE_AFTER_MS,
|
||||
type AgentStatusEntry
|
||||
} from '../../../../shared/agent-status-types'
|
||||
import { makePaneKey } from '../../../../shared/stable-pane-id'
|
||||
|
||||
const NOW = 1_000_000_000
|
||||
const TAB_ID = 'tab1'
|
||||
const LEAF_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const GONE_LEAF_ID = '22222222-2222-4222-8222-222222222222'
|
||||
const PANE_KEY = makePaneKey(TAB_ID, LEAF_ID)
|
||||
|
||||
function entry(overrides: Partial<AgentStatusEntry>): AgentStatusEntry {
|
||||
return {
|
||||
paneKey: PANE_KEY,
|
||||
state: 'working',
|
||||
prompt: 'do the thing',
|
||||
updatedAt: NOW,
|
||||
stateStartedAt: NOW - 5000,
|
||||
stateHistory: [],
|
||||
agentType: 'claude',
|
||||
tabId: TAB_ID,
|
||||
worktreeId: 'w1',
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function tab(): unknown {
|
||||
return {
|
||||
id: TAB_ID,
|
||||
ptyId: 'pty1',
|
||||
worktreeId: 'w1',
|
||||
title: 'agent',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: NOW
|
||||
}
|
||||
}
|
||||
|
||||
function baseState(overrides: Partial<DashboardSnapshotState>): DashboardSnapshotState {
|
||||
return {
|
||||
repos: [{ id: 'r1', path: '/r1', displayName: 'Repo One', badgeColor: '#000' }],
|
||||
worktreesByRepo: { r1: [{ id: 'w1', displayName: 'wt-one', isArchived: false }] },
|
||||
tabsByWorktree: { w1: [tab()] },
|
||||
agentStatusByPaneKey: {},
|
||||
retainedAgentsByPaneKey: {},
|
||||
migrationUnsupportedByPtyId: {},
|
||||
runtimeAgentOrchestrationByPaneKey: {},
|
||||
terminalLayoutsByTabId: {
|
||||
[TAB_ID]: {
|
||||
root: { type: 'leaf', leafId: LEAF_ID },
|
||||
activeLeafId: LEAF_ID,
|
||||
ptyIdsByLeafId: { [LEAF_ID]: 'pty1' }
|
||||
}
|
||||
},
|
||||
ptyIdsByTabId: { [TAB_ID]: ['pty1'] },
|
||||
runtimePaneTitlesByTabId: {},
|
||||
acknowledgedAgentsByPaneKey: {},
|
||||
...overrides
|
||||
} as unknown as DashboardSnapshotState
|
||||
}
|
||||
|
||||
describe('buildDashboardSnapshot', () => {
|
||||
it('maps a live working agent to the working bucket with a resolved ptyId', () => {
|
||||
const snapshot = buildDashboardSnapshot(
|
||||
baseState({
|
||||
agentStatusByPaneKey: {
|
||||
[PANE_KEY]: entry({ state: 'working', lastAssistantMessage: 'Working on it now' })
|
||||
}
|
||||
}),
|
||||
NOW
|
||||
)
|
||||
expect(snapshot.cards).toHaveLength(1)
|
||||
const card = snapshot.cards[0]
|
||||
expect(card.bucket).toBe('working')
|
||||
expect(card.dotState).toBe('working')
|
||||
expect(card.ptyId).toBe('pty1')
|
||||
expect(card.worktreeName).toBe('wt-one')
|
||||
expect(card.repoName).toBe('Repo One')
|
||||
expect(card.leafId).toBe(LEAF_ID)
|
||||
expect(card.lastUserMessage).toBe('do the thing')
|
||||
expect(card.lastAgentMessage).toBe('Working on it now')
|
||||
// Column ordering key: when the agent entered its current state.
|
||||
expect(card.stateChangedAt).toBe(NOW - 5000)
|
||||
// No ack yet → unseen, mirroring the sidebar's unvisited signal.
|
||||
expect(card.unseen).toBe(true)
|
||||
})
|
||||
|
||||
it('nulls ptyId when the layout entry points at a dead pty', () => {
|
||||
const snapshot = buildDashboardSnapshot(
|
||||
baseState({
|
||||
agentStatusByPaneKey: { [PANE_KEY]: entry({}) },
|
||||
// Layout still remembers pty1 (it survives restarts), but the live
|
||||
// set says that pty is gone — e.g. a parked tab after an app restart.
|
||||
ptyIdsByTabId: { [TAB_ID]: [] }
|
||||
}),
|
||||
NOW
|
||||
)
|
||||
expect(snapshot.cards[0].ptyId).toBeNull()
|
||||
})
|
||||
|
||||
it('mutes unseen once the agent is acknowledged after its state change', () => {
|
||||
const snapshot = buildDashboardSnapshot(
|
||||
baseState({
|
||||
agentStatusByPaneKey: { [PANE_KEY]: entry({}) },
|
||||
acknowledgedAgentsByPaneKey: { [PANE_KEY]: NOW - 1000 }
|
||||
}),
|
||||
NOW
|
||||
)
|
||||
// ack (NOW-1000) is after stateStartedAt (NOW-5000) → seen.
|
||||
expect(snapshot.cards[0].unseen).toBe(false)
|
||||
})
|
||||
|
||||
it('does not mark title-derived rows unseen from synthetic timestamps', () => {
|
||||
const snapshot = buildDashboardSnapshot(
|
||||
baseState({
|
||||
agentStatusByPaneKey: {},
|
||||
runtimePaneTitlesByTabId: {
|
||||
[TAB_ID]: { 1: '⠋ Claude Code' }
|
||||
}
|
||||
}),
|
||||
NOW
|
||||
)
|
||||
|
||||
expect(snapshot.cards).toHaveLength(1)
|
||||
expect(snapshot.cards[0].startedAt).toBe(0)
|
||||
expect(snapshot.cards[0].unseen).toBe(false)
|
||||
})
|
||||
|
||||
it.each(['blocked', 'waiting'] as const)(
|
||||
'routes %s agents to the attention bucket with an ask summary',
|
||||
(state) => {
|
||||
const snapshot = buildDashboardSnapshot(
|
||||
baseState({
|
||||
agentStatusByPaneKey: {
|
||||
[PANE_KEY]: entry({ state, interactivePrompt: 'Approve deploy?' })
|
||||
}
|
||||
}),
|
||||
NOW
|
||||
)
|
||||
expect(snapshot.cards[0].bucket).toBe('attention')
|
||||
expect(snapshot.cards[0].dotState).toBe(state)
|
||||
expect(snapshot.cards[0].askSummary).toBe('Approve deploy?')
|
||||
}
|
||||
)
|
||||
|
||||
it('decays a stale working agent to the idle bucket', () => {
|
||||
const snapshot = buildDashboardSnapshot(
|
||||
baseState({
|
||||
agentStatusByPaneKey: {
|
||||
[PANE_KEY]: entry({
|
||||
state: 'working',
|
||||
updatedAt: NOW - AGENT_STATUS_STALE_AFTER_MS - 1000
|
||||
})
|
||||
}
|
||||
}),
|
||||
NOW
|
||||
)
|
||||
expect(snapshot.cards[0].bucket).toBe('idle')
|
||||
expect(snapshot.cards[0].dotState).toBe('idle')
|
||||
})
|
||||
|
||||
it('folds retained done agents into the idle bucket, keeping a done dot', () => {
|
||||
const donePaneKey = makePaneKey(TAB_ID, GONE_LEAF_ID)
|
||||
const snapshot = buildDashboardSnapshot(
|
||||
baseState({
|
||||
retainedAgentsByPaneKey: {
|
||||
[donePaneKey]: {
|
||||
entry: entry({ paneKey: donePaneKey, state: 'done' }),
|
||||
worktreeId: 'w1',
|
||||
tab: tab() as never,
|
||||
agentType: 'claude',
|
||||
startedAt: NOW - 60_000
|
||||
} as never
|
||||
}
|
||||
}),
|
||||
NOW
|
||||
)
|
||||
const done = snapshot.cards.find((c) => c.dotState === 'done')
|
||||
expect(done).toBeDefined()
|
||||
expect(done?.bucket).toBe('idle')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,172 @@
|
||||
import type { AppState } from '@/store/types'
|
||||
import type {
|
||||
DashboardBucket,
|
||||
DashboardCard,
|
||||
DashboardCardDotState,
|
||||
DashboardSnapshot
|
||||
} from '../../../../shared/dashboard-snapshot'
|
||||
import { parsePaneKey } from '../../../../shared/stable-pane-id'
|
||||
import { migrationUnsupportedToAgentStatusEntry } from '@/lib/migration-unsupported-agent-entry'
|
||||
import { applyAgentRowLineage } from './agent-row-lineage'
|
||||
import type { DashboardAgentRow } from './useDashboardData'
|
||||
import { buildWorktreeAgentRows } from '../sidebar/worktree-agent-rows'
|
||||
import {
|
||||
selectLiveAgentStatusEntriesForWorktree,
|
||||
selectMigrationUnsupportedEntriesForWorktree,
|
||||
selectRetainedAgentEntriesForWorktree,
|
||||
selectRuntimeAgentOrchestrationForWorktree,
|
||||
selectTerminalLayoutsForWorktree
|
||||
} from '../sidebar/worktree-agent-row-selectors'
|
||||
import {
|
||||
selectLivePtyIdsForWorktree,
|
||||
selectRuntimePaneTitlesForWorktree
|
||||
} from '../sidebar/worktree-card-status-inputs'
|
||||
|
||||
/** The store slices the snapshot builder reads. Kept as a Pick so unit tests
|
||||
* can pass a partial store without constructing the whole AppState. */
|
||||
export type DashboardSnapshotState = Pick<
|
||||
AppState,
|
||||
| 'repos'
|
||||
| 'worktreesByRepo'
|
||||
| 'tabsByWorktree'
|
||||
| 'agentStatusByPaneKey'
|
||||
| 'retainedAgentsByPaneKey'
|
||||
| 'migrationUnsupportedByPtyId'
|
||||
| 'runtimeAgentOrchestrationByPaneKey'
|
||||
| 'terminalLayoutsByTabId'
|
||||
| 'ptyIdsByTabId'
|
||||
| 'runtimePaneTitlesByTabId'
|
||||
| 'acknowledgedAgentsByPaneKey'
|
||||
>
|
||||
|
||||
function bucketForState(state: DashboardAgentRow['state']): DashboardBucket {
|
||||
switch (state) {
|
||||
case 'working':
|
||||
return 'working'
|
||||
// 'done' folds into Idle — it's only reported when a completion hook fires,
|
||||
// so it's not a reliable standalone column. The card keeps a done dot.
|
||||
case 'done':
|
||||
case 'idle':
|
||||
return 'idle'
|
||||
// blocked | waiting — the agent needs the user.
|
||||
case 'blocked':
|
||||
case 'waiting':
|
||||
return 'attention'
|
||||
}
|
||||
}
|
||||
|
||||
function rowTask(row: DashboardAgentRow): string {
|
||||
return (row.entry.orchestration?.taskTitle ?? '').trim() || (row.entry.prompt ?? '').trim()
|
||||
}
|
||||
|
||||
function nonEmpty(value: string | undefined): string | undefined {
|
||||
const trimmed = (value ?? '').trim()
|
||||
return trimmed.length > 0 ? trimmed : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive the serializable dashboard snapshot from the live renderer store.
|
||||
* Reuses the exact per-worktree row machinery the sidebar uses
|
||||
* (buildWorktreeAgentRows + the indexed selectors), then flattens every
|
||||
* worktree's rows into presentational cards. Subagent/child rows are excluded
|
||||
* from the board (out of scope for v1).
|
||||
*/
|
||||
export function buildDashboardSnapshot(
|
||||
state: DashboardSnapshotState,
|
||||
now: number
|
||||
): DashboardSnapshot {
|
||||
const cards: DashboardCard[] = []
|
||||
|
||||
for (const repo of state.repos ?? []) {
|
||||
for (const worktree of state.worktreesByRepo?.[repo.id] ?? []) {
|
||||
if (worktree.isArchived) {
|
||||
continue
|
||||
}
|
||||
const worktreeId = worktree.id
|
||||
const liveEntries = selectLiveAgentStatusEntriesForWorktree(state, worktreeId)
|
||||
const migrationUnsupported = selectMigrationUnsupportedEntriesForWorktree(state, worktreeId)
|
||||
const entries =
|
||||
migrationUnsupported.length > 0
|
||||
? [
|
||||
...liveEntries,
|
||||
...migrationUnsupported.flatMap((unsupported) => {
|
||||
const entry = migrationUnsupportedToAgentStatusEntry(unsupported)
|
||||
return entry ? [entry] : []
|
||||
})
|
||||
]
|
||||
: liveEntries
|
||||
const terminalLayoutsByTabId = selectTerminalLayoutsForWorktree(state, worktreeId)
|
||||
|
||||
const rows = applyAgentRowLineage(
|
||||
buildWorktreeAgentRows({
|
||||
tabs: state.tabsByWorktree[worktreeId] ?? [],
|
||||
entries,
|
||||
retained: selectRetainedAgentEntriesForWorktree(state, worktreeId),
|
||||
runtimePaneTitlesByTabId: selectRuntimePaneTitlesForWorktree(state, worktreeId),
|
||||
ptyIdsByTabId: selectLivePtyIdsForWorktree(state, worktreeId),
|
||||
terminalLayoutsByTabId,
|
||||
runtimeAgentOrchestrationByPaneKey: selectRuntimeAgentOrchestrationForWorktree(
|
||||
state,
|
||||
worktreeId
|
||||
),
|
||||
now
|
||||
})
|
||||
)
|
||||
|
||||
for (const row of rows) {
|
||||
// Child rows have no pane of their own; the board lists top-level agents.
|
||||
if (row.rowSource === 'subagent') {
|
||||
continue
|
||||
}
|
||||
// Title-derived rows (a live pane read only from its terminal title, no
|
||||
// agent-hook status) carry synthetic prompt/lastAssistantMessage — the
|
||||
// agent LABEL and a status word like "Idle". They're marked by
|
||||
// startedAt === 0, and must NOT be shown as real conversation.
|
||||
const isTitleDerived = row.startedAt === 0
|
||||
const routingPaneKey = row.activationPaneKey ?? row.paneKey
|
||||
const parsed = parsePaneKey(routingPaneKey)
|
||||
const tabId = parsed?.tabId ?? row.tab.id
|
||||
const leafId = parsed?.leafId ?? null
|
||||
const layoutPtyId =
|
||||
(leafId ? terminalLayoutsByTabId[tabId]?.ptyIdsByLeafId?.[leafId] : undefined) ?? null
|
||||
// Layout entries survive app restarts, but their PTYs may not (parked
|
||||
// tabs keep the pre-restart id). Only advertise a pty the terminal
|
||||
// preview can actually serialize — ptyIdsByTabId is the liveness truth.
|
||||
const ptyId =
|
||||
layoutPtyId && (state.ptyIdsByTabId?.[tabId] ?? []).includes(layoutPtyId)
|
||||
? layoutPtyId
|
||||
: null
|
||||
const dotState = row.state as DashboardCardDotState
|
||||
const bucket = bucketForState(row.state)
|
||||
|
||||
cards.push({
|
||||
paneKey: row.paneKey,
|
||||
ptyId,
|
||||
agentType: row.agentType,
|
||||
bucket,
|
||||
dotState,
|
||||
task: isTitleDerived ? '' : rowTask(row),
|
||||
repoId: repo.id,
|
||||
worktreeId,
|
||||
tabId,
|
||||
leafId,
|
||||
repoName: repo.displayName,
|
||||
worktreeName: worktree.displayName,
|
||||
lastUserMessage: isTitleDerived ? undefined : nonEmpty(row.entry.prompt),
|
||||
lastAgentMessage: isTitleDerived ? undefined : nonEmpty(row.entry.lastAssistantMessage),
|
||||
startedAt: row.startedAt,
|
||||
stateChangedAt: row.entry.stateStartedAt || row.startedAt,
|
||||
// Same derivation as WorktreeCardAgents' unvisitedByPaneKey, so the
|
||||
// board and the sidebar bold/mute the same agents at the same time.
|
||||
unseen:
|
||||
!isTitleDerived &&
|
||||
(state.acknowledgedAgentsByPaneKey?.[row.paneKey] ?? 0) < row.entry.stateStartedAt,
|
||||
askSummary:
|
||||
bucket === 'attention' ? (row.entry.interactivePrompt ?? undefined) : undefined
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { generatedAt: now, cards }
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useAppStore } from '@/store'
|
||||
import { useShallow } from 'zustand/react/shallow'
|
||||
import type { DashboardBucket } from '../../../../shared/dashboard-snapshot'
|
||||
import { buildDashboardSnapshot } from './build-dashboard-snapshot'
|
||||
|
||||
export type AgentBucketCounts = Record<DashboardBucket, number>
|
||||
|
||||
const EMPTY_COUNTS: AgentBucketCounts = { attention: 0, working: 0, idle: 0 }
|
||||
|
||||
/**
|
||||
* Per-state agent counts for the sidebar dashboard entry, derived from the same
|
||||
* builder that feeds the pop-out board so the numbers always agree. Recomputes
|
||||
* only when an input slice changes (mirrors useDashboardData's cost profile).
|
||||
*/
|
||||
export function useAgentBucketCounts(): AgentBucketCounts {
|
||||
const {
|
||||
repos,
|
||||
worktreesByRepo,
|
||||
tabsByWorktree,
|
||||
agentStatusByPaneKey,
|
||||
retainedAgentsByPaneKey,
|
||||
migrationUnsupportedByPtyId,
|
||||
runtimeAgentOrchestrationByPaneKey,
|
||||
terminalLayoutsByTabId,
|
||||
ptyIdsByTabId,
|
||||
runtimePaneTitlesByTabId,
|
||||
agentStatusEpoch
|
||||
} = useAppStore(
|
||||
useShallow((s) => ({
|
||||
repos: s.repos,
|
||||
worktreesByRepo: s.worktreesByRepo,
|
||||
tabsByWorktree: s.tabsByWorktree,
|
||||
agentStatusByPaneKey: s.agentStatusByPaneKey,
|
||||
retainedAgentsByPaneKey: s.retainedAgentsByPaneKey,
|
||||
migrationUnsupportedByPtyId: s.migrationUnsupportedByPtyId,
|
||||
runtimeAgentOrchestrationByPaneKey: s.runtimeAgentOrchestrationByPaneKey,
|
||||
terminalLayoutsByTabId: s.terminalLayoutsByTabId,
|
||||
ptyIdsByTabId: s.ptyIdsByTabId,
|
||||
runtimePaneTitlesByTabId: s.runtimePaneTitlesByTabId,
|
||||
agentStatusEpoch: s.agentStatusEpoch
|
||||
}))
|
||||
)
|
||||
|
||||
return useMemo(() => {
|
||||
const snapshot = buildDashboardSnapshot(
|
||||
{
|
||||
repos,
|
||||
worktreesByRepo,
|
||||
tabsByWorktree,
|
||||
agentStatusByPaneKey,
|
||||
retainedAgentsByPaneKey,
|
||||
migrationUnsupportedByPtyId,
|
||||
runtimeAgentOrchestrationByPaneKey,
|
||||
terminalLayoutsByTabId,
|
||||
ptyIdsByTabId,
|
||||
runtimePaneTitlesByTabId,
|
||||
// Counts do not render acknowledgement state, so avoid subscribing the sidebar to it.
|
||||
acknowledgedAgentsByPaneKey: {}
|
||||
},
|
||||
Date.now()
|
||||
)
|
||||
if (snapshot.cards.length === 0) {
|
||||
return EMPTY_COUNTS
|
||||
}
|
||||
const counts: AgentBucketCounts = { attention: 0, working: 0, idle: 0 }
|
||||
for (const card of snapshot.cards) {
|
||||
counts[card.bucket] += 1
|
||||
}
|
||||
return counts
|
||||
// Why: Date.now() is read inside the memo (not a dep) so idle-decay tracks
|
||||
// agentStatusEpoch ticks, matching useDashboardData.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [
|
||||
repos,
|
||||
worktreesByRepo,
|
||||
tabsByWorktree,
|
||||
agentStatusByPaneKey,
|
||||
retainedAgentsByPaneKey,
|
||||
migrationUnsupportedByPtyId,
|
||||
runtimeAgentOrchestrationByPaneKey,
|
||||
terminalLayoutsByTabId,
|
||||
ptyIdsByTabId,
|
||||
runtimePaneTitlesByTabId,
|
||||
agentStatusEpoch
|
||||
])
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
acknowledgeAgents: vi.fn(),
|
||||
setActiveWorktree: vi.fn(),
|
||||
subscribeStore: vi.fn(() => vi.fn()),
|
||||
onRevealAgent: vi.fn(),
|
||||
onAckAgent: vi.fn(),
|
||||
onPopoutOpenChanged: vi.fn(),
|
||||
onSnapshotRequested: vi.fn(),
|
||||
getPopoutOpen: vi.fn(async () => false),
|
||||
publishSnapshot: vi.fn(async () => undefined),
|
||||
offRevealAgent: vi.fn(),
|
||||
offAckAgent: vi.fn(),
|
||||
offPopoutOpenChanged: vi.fn(),
|
||||
offSnapshotRequested: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
useAppStore: {
|
||||
getState: () => ({
|
||||
acknowledgeAgents: mocks.acknowledgeAgents,
|
||||
setActiveWorktree: mocks.setActiveWorktree
|
||||
}),
|
||||
subscribe: mocks.subscribeStore
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/activate-tab-and-focus-pane', () => ({
|
||||
activateTabAndFocusPane: vi.fn()
|
||||
}))
|
||||
|
||||
import {
|
||||
dashboardSnapshotInputsChanged,
|
||||
useDashboardPopoutBridge
|
||||
} from './useDashboardPopoutBridge'
|
||||
import type { DashboardSnapshotState } from './build-dashboard-snapshot'
|
||||
import type { AppState } from '@/store/types'
|
||||
|
||||
type DashboardSnapshotWatchState = DashboardSnapshotState & Pick<AppState, 'agentStatusEpoch'>
|
||||
|
||||
function makeSnapshotWatchState(): DashboardSnapshotWatchState {
|
||||
return {
|
||||
repos: [],
|
||||
worktreesByRepo: {},
|
||||
tabsByWorktree: {},
|
||||
agentStatusByPaneKey: {},
|
||||
retainedAgentsByPaneKey: {},
|
||||
migrationUnsupportedByPtyId: {},
|
||||
runtimeAgentOrchestrationByPaneKey: {},
|
||||
terminalLayoutsByTabId: {},
|
||||
ptyIdsByTabId: {},
|
||||
runtimePaneTitlesByTabId: {},
|
||||
acknowledgedAgentsByPaneKey: {},
|
||||
agentStatusEpoch: 0
|
||||
}
|
||||
}
|
||||
|
||||
function Harness({ enabled }: { enabled: boolean }): null {
|
||||
useDashboardPopoutBridge(enabled)
|
||||
return null
|
||||
}
|
||||
|
||||
describe('useDashboardPopoutBridge', () => {
|
||||
let root: Root
|
||||
let container: HTMLDivElement
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.onRevealAgent.mockReturnValue(mocks.offRevealAgent)
|
||||
mocks.onAckAgent.mockReturnValue(mocks.offAckAgent)
|
||||
mocks.onPopoutOpenChanged.mockReturnValue(mocks.offPopoutOpenChanged)
|
||||
mocks.onSnapshotRequested.mockReturnValue(mocks.offSnapshotRequested)
|
||||
;(window as unknown as { api: unknown }).api = {
|
||||
dashboard: {
|
||||
onRevealAgent: mocks.onRevealAgent,
|
||||
onAckAgent: mocks.onAckAgent,
|
||||
onPopoutOpenChanged: mocks.onPopoutOpenChanged,
|
||||
onSnapshotRequested: mocks.onSnapshotRequested,
|
||||
getPopoutOpen: mocks.getPopoutOpen,
|
||||
publishSnapshot: mocks.publishSnapshot
|
||||
}
|
||||
}
|
||||
container = document.createElement('div')
|
||||
root = createRoot(container)
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount())
|
||||
})
|
||||
|
||||
it('does not register dashboard or store subscriptions while disabled', async () => {
|
||||
await act(async () => root.render(<Harness enabled={false} />))
|
||||
|
||||
expect(mocks.onRevealAgent).not.toHaveBeenCalled()
|
||||
expect(mocks.onAckAgent).not.toHaveBeenCalled()
|
||||
expect(mocks.onPopoutOpenChanged).not.toHaveBeenCalled()
|
||||
expect(mocks.onSnapshotRequested).not.toHaveBeenCalled()
|
||||
expect(mocks.getPopoutOpen).not.toHaveBeenCalled()
|
||||
expect(mocks.subscribeStore).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ignores unrelated store writes while retaining every snapshot input', () => {
|
||||
const previousState = makeSnapshotWatchState()
|
||||
expect(dashboardSnapshotInputsChanged({ ...previousState }, previousState)).toBe(false)
|
||||
|
||||
const referenceInputs = [
|
||||
'repos',
|
||||
'worktreesByRepo',
|
||||
'tabsByWorktree',
|
||||
'agentStatusByPaneKey',
|
||||
'retainedAgentsByPaneKey',
|
||||
'migrationUnsupportedByPtyId',
|
||||
'runtimeAgentOrchestrationByPaneKey',
|
||||
'terminalLayoutsByTabId',
|
||||
'ptyIdsByTabId',
|
||||
'runtimePaneTitlesByTabId',
|
||||
'acknowledgedAgentsByPaneKey'
|
||||
] as const
|
||||
for (const key of referenceInputs) {
|
||||
expect(
|
||||
dashboardSnapshotInputsChanged({ ...previousState, [key]: {} }, previousState),
|
||||
key
|
||||
).toBe(true)
|
||||
}
|
||||
expect(
|
||||
dashboardSnapshotInputsChanged({ ...previousState, agentStatusEpoch: 1 }, previousState)
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('releases every dashboard listener when the experiment is disabled', async () => {
|
||||
await act(async () => root.render(<Harness enabled />))
|
||||
|
||||
expect(mocks.onRevealAgent).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.onAckAgent).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.onPopoutOpenChanged).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.onSnapshotRequested).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.getPopoutOpen).toHaveBeenCalledTimes(1)
|
||||
|
||||
await act(async () => root.render(<Harness enabled={false} />))
|
||||
|
||||
expect(mocks.offRevealAgent).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.offAckAgent).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.offPopoutOpenChanged).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.offSnapshotRequested).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,157 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useAppStore, type AppState } from '@/store'
|
||||
import { activateTabAndFocusPane } from '@/lib/activate-tab-and-focus-pane'
|
||||
import { buildDashboardSnapshot, type DashboardSnapshotState } from './build-dashboard-snapshot'
|
||||
|
||||
// Why: cap snapshot rebuilds during bursts of agent-status pings. The board is a
|
||||
// glanceable surface, so ~4 updates/sec is plenty and keeps the cross-worktree
|
||||
// rebuild off the hot path.
|
||||
const PUBLISH_THROTTLE_MS = 250
|
||||
|
||||
type DashboardSnapshotWatchState = DashboardSnapshotState & Pick<AppState, 'agentStatusEpoch'>
|
||||
|
||||
export function dashboardSnapshotInputsChanged(
|
||||
state: DashboardSnapshotWatchState,
|
||||
previousState: DashboardSnapshotWatchState
|
||||
): boolean {
|
||||
return (
|
||||
state.repos !== previousState.repos ||
|
||||
state.worktreesByRepo !== previousState.worktreesByRepo ||
|
||||
state.tabsByWorktree !== previousState.tabsByWorktree ||
|
||||
state.agentStatusByPaneKey !== previousState.agentStatusByPaneKey ||
|
||||
state.retainedAgentsByPaneKey !== previousState.retainedAgentsByPaneKey ||
|
||||
state.migrationUnsupportedByPtyId !== previousState.migrationUnsupportedByPtyId ||
|
||||
state.runtimeAgentOrchestrationByPaneKey !== previousState.runtimeAgentOrchestrationByPaneKey ||
|
||||
state.terminalLayoutsByTabId !== previousState.terminalLayoutsByTabId ||
|
||||
state.ptyIdsByTabId !== previousState.ptyIdsByTabId ||
|
||||
state.runtimePaneTitlesByTabId !== previousState.runtimePaneTitlesByTabId ||
|
||||
state.acknowledgedAgentsByPaneKey !== previousState.acknowledgedAgentsByPaneKey ||
|
||||
// Why: freshness can change a bucket without replacing any backing map.
|
||||
state.agentStatusEpoch !== previousState.agentStatusEpoch
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs in the MAIN window (mount once in App). Two responsibilities:
|
||||
* 1. While the pop-out dashboard is open, derive the snapshot from the live
|
||||
* store and publish it to the main process (which relays it to the popout).
|
||||
* Does nothing while the popout is closed, so it's free in the common case.
|
||||
* 2. Handle click-to-focus reveal requests forwarded from the popout: activate
|
||||
* the agent's worktree and focus its pane in this (main) window.
|
||||
*/
|
||||
export function useDashboardPopoutBridge(enabled: boolean): void {
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
return
|
||||
}
|
||||
return window.api.dashboard.onRevealAgent((args) => {
|
||||
useAppStore.getState().setActiveWorktree(args.worktreeId)
|
||||
activateTabAndFocusPane(args.tabId, args.leafId, { flashFocusedPane: true })
|
||||
})
|
||||
}, [enabled])
|
||||
|
||||
// Opening a card's terminal dialog in the popout acks the agent here — the
|
||||
// same ack the sidebar's bold/mute treatment reads, keeping both in lockstep.
|
||||
// ?. shields App mount from dev-HMR preload skew (preload updates only on
|
||||
// app restart).
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
return
|
||||
}
|
||||
return window.api.dashboard.onAckAgent?.((paneKey) => {
|
||||
useAppStore.getState().acknowledgeAgents([paneKey])
|
||||
})
|
||||
}, [enabled])
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
return
|
||||
}
|
||||
let open = false
|
||||
let disposed = false
|
||||
let unsubscribeStore: (() => void) | null = null
|
||||
let trailingTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let lastPublishAt = 0
|
||||
|
||||
const publishNow = (): void => {
|
||||
lastPublishAt = Date.now()
|
||||
const snapshot = buildDashboardSnapshot(useAppStore.getState(), lastPublishAt)
|
||||
void window.api.dashboard.publishSnapshot(snapshot)
|
||||
}
|
||||
|
||||
// Leading + trailing throttle so the first change paints immediately and
|
||||
// bursts collapse into one trailing publish.
|
||||
const publishThrottled = (): void => {
|
||||
if (!open || disposed) {
|
||||
return
|
||||
}
|
||||
const elapsed = Date.now() - lastPublishAt
|
||||
if (elapsed >= PUBLISH_THROTTLE_MS) {
|
||||
if (trailingTimer) {
|
||||
clearTimeout(trailingTimer)
|
||||
trailingTimer = null
|
||||
}
|
||||
publishNow()
|
||||
return
|
||||
}
|
||||
if (!trailingTimer) {
|
||||
trailingTimer = setTimeout(() => {
|
||||
trailingTimer = null
|
||||
if (open && !disposed) {
|
||||
publishNow()
|
||||
}
|
||||
}, PUBLISH_THROTTLE_MS - elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
const setOpen = (next: boolean): void => {
|
||||
if (next === open || disposed) {
|
||||
return
|
||||
}
|
||||
open = next
|
||||
if (open) {
|
||||
if (!unsubscribeStore) {
|
||||
unsubscribeStore = useAppStore.subscribe((state, previousState) => {
|
||||
// Why: unrelated high-frequency store writes must not rebuild a cross-worktree snapshot.
|
||||
if (dashboardSnapshotInputsChanged(state, previousState)) {
|
||||
publishThrottled()
|
||||
}
|
||||
})
|
||||
}
|
||||
publishNow()
|
||||
} else {
|
||||
unsubscribeStore?.()
|
||||
unsubscribeStore = null
|
||||
if (trailingTimer) {
|
||||
clearTimeout(trailingTimer)
|
||||
trailingTimer = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const offOpenChanged = window.api.dashboard.onPopoutOpenChanged((next) => setOpen(next))
|
||||
// Popout mount asks for a fresh snapshot (its cached one may be stale).
|
||||
const offRequested = window.api.dashboard.onSnapshotRequested(() => {
|
||||
if (open) {
|
||||
publishNow()
|
||||
}
|
||||
})
|
||||
// Recover the open state when the main window (re)mounts while a pop-out is
|
||||
// already open — e.g. after a renderer reload.
|
||||
void window.api.dashboard.getPopoutOpen().then((isOpen) => {
|
||||
if (!disposed && isOpen) {
|
||||
setOpen(true)
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
disposed = true
|
||||
offOpenChanged?.()
|
||||
offRequested?.()
|
||||
unsubscribeStore?.()
|
||||
if (trailingTimer) {
|
||||
clearTimeout(trailingTimer)
|
||||
}
|
||||
}
|
||||
}, [enabled])
|
||||
}
|
||||
@@ -134,6 +134,38 @@ describe('ExperimentalPane', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('renders the agent dashboard as an off-by-default searchable experiment', () => {
|
||||
const settings = getDefaultSettings('/tmp')
|
||||
const markup = renderToStaticMarkup(
|
||||
<ExperimentalPane settings={settings} updateSettings={vi.fn()} />
|
||||
)
|
||||
|
||||
expect(settings.experimentalAgentDashboardPopout).toBe(false)
|
||||
expect(markup).toContain('Agent Dashboard')
|
||||
expect(markup).toContain('monitor attention, working, and idle agents')
|
||||
expect(getExperimentalPaneSearchEntries().map((entry) => entry.title)).toContain(
|
||||
'Agent Dashboard'
|
||||
)
|
||||
})
|
||||
|
||||
it('enables the agent dashboard through its experimental switch', async () => {
|
||||
const updateSettings = vi.fn()
|
||||
const { root, container } = await renderExperimentalPane({ updateSettings })
|
||||
const switchButton = container.querySelector<HTMLButtonElement>(
|
||||
'#experimental-agent-dashboard button[role="switch"]'
|
||||
)
|
||||
if (!switchButton) {
|
||||
throw new Error('Agent Dashboard switch was not rendered')
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
switchButton.dispatchEvent(new MouseEvent('click', { bubbles: true }))
|
||||
})
|
||||
|
||||
expect(updateSettings).toHaveBeenCalledWith({ experimentalAgentDashboardPopout: true })
|
||||
root.unmount()
|
||||
})
|
||||
|
||||
it('renders per-workspace environments as an off-by-default experimental subsection', () => {
|
||||
const settings = getDefaultSettings('/tmp')
|
||||
const markup = renderToStaticMarkup(
|
||||
|
||||
@@ -37,6 +37,9 @@ export function ExperimentalPane({
|
||||
const showAgentsView = matchesSettingsSearch(searchQuery, [
|
||||
getExperimentalSearchEntry().agentsView
|
||||
])
|
||||
const showAgentDashboard = matchesSettingsSearch(searchQuery, [
|
||||
getExperimentalSearchEntry().agentDashboard
|
||||
])
|
||||
const showNativeChat = matchesSettingsSearch(searchQuery, [
|
||||
getExperimentalSearchEntry().nativeChat
|
||||
])
|
||||
@@ -148,6 +151,52 @@ export function ExperimentalPane({
|
||||
</SearchableSetting>
|
||||
) : null}
|
||||
|
||||
{showAgentDashboard ? (
|
||||
<SearchableSetting
|
||||
title={translate(
|
||||
'auto.components.settings.ExperimentalPane.agentDashboard.title',
|
||||
'Agent Dashboard'
|
||||
)}
|
||||
description={translate(
|
||||
'auto.components.settings.ExperimentalPane.agentDashboard.description',
|
||||
'Pop-out Kanban board for monitoring agents across worktrees.'
|
||||
)}
|
||||
keywords={getExperimentalSearchEntry().agentDashboard.keywords}
|
||||
className="space-y-3 py-2"
|
||||
id="experimental-agent-dashboard"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="min-w-0 shrink space-y-0.5">
|
||||
<Label>
|
||||
{translate(
|
||||
'auto.components.settings.ExperimentalPane.agentDashboard.title',
|
||||
'Agent Dashboard'
|
||||
)}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{translate(
|
||||
'auto.components.settings.ExperimentalPane.agentDashboard.copy',
|
||||
'Adds an Agent Dashboard entry to the left sidebar. Open it to monitor attention, working, and idle agents in a separate window and jump into their live terminals.'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<SettingsSwitch
|
||||
checked={settings.experimentalAgentDashboardPopout === true}
|
||||
ariaLabel={translate(
|
||||
'auto.components.settings.ExperimentalPane.agentDashboard.toggleLabel',
|
||||
'Toggle Agent Dashboard'
|
||||
)}
|
||||
onChange={() =>
|
||||
updateSettings({
|
||||
experimentalAgentDashboardPopout:
|
||||
settings.experimentalAgentDashboardPopout !== true
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</SearchableSetting>
|
||||
) : null}
|
||||
|
||||
{showNativeChat ? (
|
||||
<NativeChatExperimentalSetting settings={settings} updateSettings={updateSettings} />
|
||||
) : null}
|
||||
|
||||
@@ -95,6 +95,42 @@ export const getExperimentalPaneSearchEntries = createLocalizedCatalog(
|
||||
)
|
||||
]
|
||||
},
|
||||
{
|
||||
title: translate(
|
||||
'auto.components.settings.experimental.search.agentDashboard.title',
|
||||
'Agent Dashboard'
|
||||
),
|
||||
description: translate(
|
||||
'auto.components.settings.experimental.search.agentDashboard.description',
|
||||
'Pop-out Kanban board for monitoring agents across worktrees.'
|
||||
),
|
||||
keywords: [
|
||||
...translateSearchKeyword(
|
||||
'auto.components.settings.experimental.search.0d24759f14',
|
||||
'experimental'
|
||||
),
|
||||
...translateSearchKeyword(
|
||||
'auto.components.settings.experimental.search.agentDashboard.agent',
|
||||
'agent'
|
||||
),
|
||||
...translateSearchKeyword(
|
||||
'auto.components.settings.experimental.search.agentDashboard.dashboard',
|
||||
'dashboard'
|
||||
),
|
||||
...translateSearchKeyword(
|
||||
'auto.components.settings.experimental.search.agentDashboard.kanban',
|
||||
'kanban'
|
||||
),
|
||||
...translateSearchKeyword(
|
||||
'auto.components.settings.experimental.search.agentDashboard.popout',
|
||||
'pop-out'
|
||||
),
|
||||
...translateSearchKeyword(
|
||||
'auto.components.settings.experimental.search.agentDashboard.worktrees',
|
||||
'worktrees'
|
||||
)
|
||||
]
|
||||
},
|
||||
getNativeChatExperimentalSearchEntry(),
|
||||
{
|
||||
title: translate(
|
||||
@@ -206,6 +242,12 @@ export function getExperimentalSearchEntry() {
|
||||
agentsView: findEntry(
|
||||
translate('auto.components.settings.experimental.search.ccc5548ac5', 'Agents View')
|
||||
),
|
||||
agentDashboard: findEntry(
|
||||
translate(
|
||||
'auto.components.settings.experimental.search.agentDashboard.title',
|
||||
'Agent Dashboard'
|
||||
)
|
||||
),
|
||||
nativeChat: findEntry(
|
||||
translate('auto.components.settings.experimental.search.nativeChat.title', 'Native chat')
|
||||
),
|
||||
|
||||
@@ -77,6 +77,7 @@ vi.mock('@/components/ui/context-menu', () => ({
|
||||
|
||||
import {
|
||||
getSetupGuideSidebarEntryReady,
|
||||
shouldShowAgentDashboardButton,
|
||||
shouldShowAgentsButton,
|
||||
shouldShowAutomationsButton,
|
||||
shouldShowMobileButton,
|
||||
@@ -227,6 +228,30 @@ describe('SidebarNav', () => {
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('shows the Agent Dashboard entry only when its experiment is enabled', () => {
|
||||
expect(shouldShowAgentDashboardButton(null)).toBe(false)
|
||||
expect(shouldShowAgentDashboardButton({ experimentalAgentDashboardPopout: false })).toBe(false)
|
||||
expect(shouldShowAgentDashboardButton({ experimentalAgentDashboardPopout: true })).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps the Agent Dashboard row unmounted by default', async () => {
|
||||
const container = await renderSidebarNav()
|
||||
|
||||
expect(queryButtonByText(container, 'Agent Dashboard')).toBeNull()
|
||||
})
|
||||
|
||||
it('mounts the Agent Dashboard row after opt-in', async () => {
|
||||
setSidebarState({
|
||||
settings: {
|
||||
...getDefaultSettings('/tmp'),
|
||||
experimentalAgentDashboardPopout: true
|
||||
}
|
||||
})
|
||||
const container = await renderSidebarNav()
|
||||
|
||||
expect(queryButtonByText(container, 'Agent Dashboard')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('shows the Mobile entry by default for older settings', () => {
|
||||
expect(shouldShowMobileButton(null)).toBe(true)
|
||||
expect(shouldShowMobileButton({})).toBe(true)
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import React from 'react'
|
||||
import { Bell, CalendarClock, EyeOff, Search, Smartphone } from 'lucide-react'
|
||||
import { Bell, CalendarClock, EyeOff, LayoutDashboard, Search, Smartphone } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useAppStore } from '@/store'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { GlobalSettings } from '../../../../shared/types'
|
||||
import { DASHBOARD_BUCKET_ORDER, type DashboardBucket } from '../../../../shared/dashboard-snapshot'
|
||||
import { useAgentBucketCounts } from '@/components/dashboard/useAgentBucketCounts'
|
||||
import { useActivityUnreadCount } from '@/components/activity/useActivityUnreadCount'
|
||||
import { useShortcutKeyComboDetails } from '@/hooks/useShortcutLabel'
|
||||
import { ShortcutKeyCombo } from '@/components/ShortcutKeyCombo'
|
||||
@@ -24,6 +26,12 @@ export function shouldShowAgentsButton(
|
||||
return settings?.experimentalActivity === true
|
||||
}
|
||||
|
||||
export function shouldShowAgentDashboardButton(
|
||||
settings: Pick<GlobalSettings, 'experimentalAgentDashboardPopout'> | null | undefined
|
||||
): boolean {
|
||||
return settings?.experimentalAgentDashboardPopout === true
|
||||
}
|
||||
|
||||
export function shouldShowMobileButton(
|
||||
settings: Pick<GlobalSettings, 'showMobileButton'> | null | undefined
|
||||
): boolean {
|
||||
@@ -36,6 +44,76 @@ export function shouldShowAutomationsButton(
|
||||
return settings?.showAutomationsButton !== false
|
||||
}
|
||||
|
||||
// Per-state dot colors mirror AgentStateDot so the sidebar counts read the same
|
||||
// as the board (amber = needs you, yellow = working, neutral = idle, emerald = done).
|
||||
const DASHBOARD_BUCKET_DOT_CLASS: Record<DashboardBucket, string> = {
|
||||
attention: 'bg-amber-500',
|
||||
working: 'bg-yellow-500',
|
||||
idle: 'bg-neutral-500/50'
|
||||
}
|
||||
|
||||
function dashboardBucketLabel(bucket: DashboardBucket): string {
|
||||
switch (bucket) {
|
||||
case 'attention':
|
||||
return translate('dashboardPopout.bucket.attention', 'Needs You')
|
||||
case 'working':
|
||||
return translate('dashboardPopout.bucket.working', 'Working')
|
||||
case 'idle':
|
||||
return translate('dashboardPopout.bucket.idle', 'Idle')
|
||||
}
|
||||
}
|
||||
|
||||
function DashboardBucketCounts({
|
||||
counts
|
||||
}: {
|
||||
counts: Record<DashboardBucket, number>
|
||||
}): React.JSX.Element | null {
|
||||
const active = DASHBOARD_BUCKET_ORDER.filter((bucket) => counts[bucket] > 0)
|
||||
if (active.length === 0) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<span className="flex items-center gap-1.5">
|
||||
{active.map((bucket) => (
|
||||
<span
|
||||
key={bucket}
|
||||
aria-label={`${dashboardBucketLabel(bucket)}: ${counts[bucket]}`}
|
||||
className="inline-flex items-center gap-1 text-[10px] tabular-nums text-worktree-sidebar-foreground/55"
|
||||
>
|
||||
<span className={cn('size-1.5 rounded-full', DASHBOARD_BUCKET_DOT_CLASS[bucket])} />
|
||||
{counts[bucket]}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// Why: keep the dashboard's broad aggregate subscriptions out of SidebarNav so
|
||||
// agent-status churn only updates this opt-in row, not the full navigation.
|
||||
function AgentDashboardSidebarEntry(): React.JSX.Element {
|
||||
const dashboardBucketCounts = useAgentBucketCounts()
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
void window.api.dashboard.openPopout()
|
||||
}}
|
||||
className={cn(
|
||||
'flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[13px] font-medium tracking-tight transition-colors',
|
||||
'text-worktree-sidebar-foreground/60 hover:bg-worktree-sidebar-foreground/8'
|
||||
)}
|
||||
>
|
||||
<LayoutDashboard
|
||||
className="size-4 shrink-0 text-worktree-sidebar-foreground/30"
|
||||
strokeWidth={1.75}
|
||||
/>
|
||||
<span className="flex-1">{translate('dashboard.sidebar.label', 'Agent Dashboard')}</span>
|
||||
<DashboardBucketCounts counts={dashboardBucketCounts} />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
const SidebarNav = React.memo(function SidebarNav() {
|
||||
// Why: this memo boundary needs its own language subscription, while
|
||||
// translate() preserves Orca's pseudo-localization behavior.
|
||||
@@ -48,6 +126,7 @@ const SidebarNav = React.memo(function SidebarNav() {
|
||||
const updateSettings = useAppStore((s) => s.updateSettings)
|
||||
const activeView = useAppStore((s) => s.activeView)
|
||||
const showAgentsButton = useAppStore((s) => shouldShowAgentsButton(s.settings))
|
||||
const showAgentDashboardButton = useAppStore((s) => shouldShowAgentDashboardButton(s.settings))
|
||||
const showAutomationsButton = useAppStore((s) => shouldShowAutomationsButton(s.settings))
|
||||
const showMobileButton = useAppStore((s) => shouldShowMobileButton(s.settings))
|
||||
const automationsActive = activeView === 'automations'
|
||||
@@ -98,6 +177,7 @@ const SidebarNav = React.memo(function SidebarNav() {
|
||||
<HideSidebarMenu onHide={hideAutomationsButton} />
|
||||
</ContextMenu>
|
||||
) : null}
|
||||
{showAgentDashboardButton ? <AgentDashboardSidebarEntry /> : null}
|
||||
{showAgentsButton ? (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -5479,6 +5479,12 @@
|
||||
"defaultViewLabel": "Default native chat view",
|
||||
"defaultViewTerminal": "Terminal chat",
|
||||
"defaultViewNative": "Native chat"
|
||||
},
|
||||
"agentDashboard": {
|
||||
"title": "Agent Dashboard",
|
||||
"description": "Pop-out Kanban board for monitoring agents across worktrees.",
|
||||
"copy": "Adds an Agent Dashboard entry to the left sidebar. Open it to monitor attention, working, and idle agents in a separate window and jump into their live terminals.",
|
||||
"toggleLabel": "Toggle Agent Dashboard"
|
||||
}
|
||||
},
|
||||
"FloatingWorkspacePane": {
|
||||
@@ -7689,6 +7695,10 @@
|
||||
"title": "Native chat",
|
||||
"description": "Preview the desktop chat surface for supported agent terminal sessions.",
|
||||
"grok": "grok"
|
||||
},
|
||||
"agentDashboard": {
|
||||
"title": "Agent Dashboard",
|
||||
"description": "Pop-out Kanban board for monitoring agents across worktrees."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -13563,5 +13573,42 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"dashboardPopout": {
|
||||
"placeholder": {
|
||||
"title": "Agent dashboard",
|
||||
"description": "This is where all your agents will show up at a glance. The board is coming soon."
|
||||
},
|
||||
"recoverableError": {
|
||||
"title": "Orca dashboard hit an error.",
|
||||
"description": "The dashboard could not finish rendering. Retry to remount it, or reopen it."
|
||||
},
|
||||
"bucket": {
|
||||
"attention": "Needs You",
|
||||
"working": "Working",
|
||||
"idle": "Idle",
|
||||
"empty": "None"
|
||||
},
|
||||
"title": "Agents",
|
||||
"total": "{{count}} total",
|
||||
"card": {
|
||||
"you": "You",
|
||||
"time": {
|
||||
"justNow": "just now",
|
||||
"minutes": "{{count}}m",
|
||||
"hours": "{{count}}h",
|
||||
"days": "{{count}}d"
|
||||
}
|
||||
},
|
||||
"terminal": {
|
||||
"closed": "No live terminal — this agent's pane has closed.",
|
||||
"close": "Close",
|
||||
"focusWorktree": "Focus worktree"
|
||||
}
|
||||
},
|
||||
"dashboard": {
|
||||
"sidebar": {
|
||||
"label": "Agent Dashboard"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5456,6 +5456,12 @@
|
||||
"defaultViewLabel": "Vista predeterminada de chat nativo",
|
||||
"defaultViewTerminal": "Chat en terminal",
|
||||
"defaultViewNative": "Chat nativo"
|
||||
},
|
||||
"agentDashboard": {
|
||||
"title": "Agent Dashboard",
|
||||
"description": "Pop-out Kanban board for monitoring agents across worktrees.",
|
||||
"copy": "Adds an Agent Dashboard entry to the left sidebar. Open it to monitor attention, working, and idle agents in a separate window and jump into their live terminals.",
|
||||
"toggleLabel": "Toggle Agent Dashboard"
|
||||
}
|
||||
},
|
||||
"FloatingWorkspacePane": {
|
||||
@@ -7629,6 +7635,10 @@
|
||||
"title": "Chat nativo",
|
||||
"description": "Previsualiza la interfaz de chat de escritorio para sesiones de terminal de agentes compatibles.",
|
||||
"grok": "grok"
|
||||
},
|
||||
"agentDashboard": {
|
||||
"title": "Agent Dashboard",
|
||||
"description": "Pop-out Kanban board for monitoring agents across worktrees."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -13541,6 +13551,43 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"dashboardPopout": {
|
||||
"placeholder": {
|
||||
"title": "Agent dashboard",
|
||||
"description": "This is where all your agents will show up at a glance. The board is coming soon."
|
||||
},
|
||||
"recoverableError": {
|
||||
"title": "Orca dashboard hit an error.",
|
||||
"description": "The dashboard could not finish rendering. Retry to remount it, or reopen it."
|
||||
},
|
||||
"bucket": {
|
||||
"attention": "Needs You",
|
||||
"working": "Working",
|
||||
"idle": "Idle",
|
||||
"empty": "None"
|
||||
},
|
||||
"title": "Agents",
|
||||
"total": "{{count}} total",
|
||||
"card": {
|
||||
"you": "You",
|
||||
"time": {
|
||||
"justNow": "ahora mismo",
|
||||
"minutes": "{{count}} min",
|
||||
"hours": "{{count}} h",
|
||||
"days": "{{count}} d"
|
||||
}
|
||||
},
|
||||
"terminal": {
|
||||
"closed": "No live terminal — this agent's pane has closed.",
|
||||
"close": "Close",
|
||||
"focusWorktree": "Focus worktree"
|
||||
}
|
||||
},
|
||||
"dashboard": {
|
||||
"sidebar": {
|
||||
"label": "Agent Dashboard"
|
||||
}
|
||||
},
|
||||
"browser": {
|
||||
"loadFailure": {
|
||||
"connectionNotSecure": "Connection isn't secure",
|
||||
|
||||
@@ -5441,6 +5441,12 @@
|
||||
"defaultViewLabel": "デフォルトのネイティブ チャット ビュー",
|
||||
"defaultViewTerminal": "Terminal チャット",
|
||||
"defaultViewNative": "ネイティブチャット"
|
||||
},
|
||||
"agentDashboard": {
|
||||
"title": "Agent Dashboard",
|
||||
"description": "Pop-out Kanban board for monitoring agents across worktrees.",
|
||||
"copy": "Adds an Agent Dashboard entry to the left sidebar. Open it to monitor attention, working, and idle agents in a separate window and jump into their live terminals.",
|
||||
"toggleLabel": "Toggle Agent Dashboard"
|
||||
}
|
||||
},
|
||||
"FloatingWorkspacePane": {
|
||||
@@ -7651,6 +7657,10 @@
|
||||
"title": "ネイティブチャット",
|
||||
"description": "対応エージェントのターミナルセッション用デスクトップチャット画面をプレビューします。",
|
||||
"grok": "grok"
|
||||
},
|
||||
"agentDashboard": {
|
||||
"title": "Agent Dashboard",
|
||||
"description": "Pop-out Kanban board for monitoring agents across worktrees."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -13541,6 +13551,43 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"dashboardPopout": {
|
||||
"placeholder": {
|
||||
"title": "Agent dashboard",
|
||||
"description": "This is where all your agents will show up at a glance. The board is coming soon."
|
||||
},
|
||||
"recoverableError": {
|
||||
"title": "Orca dashboard hit an error.",
|
||||
"description": "The dashboard could not finish rendering. Retry to remount it, or reopen it."
|
||||
},
|
||||
"bucket": {
|
||||
"attention": "Needs You",
|
||||
"working": "Working",
|
||||
"idle": "Idle",
|
||||
"empty": "None"
|
||||
},
|
||||
"title": "Agents",
|
||||
"total": "{{count}} total",
|
||||
"card": {
|
||||
"you": "You",
|
||||
"time": {
|
||||
"justNow": "たった今",
|
||||
"minutes": "{{count}}分",
|
||||
"hours": "{{count}}時間",
|
||||
"days": "{{count}}日"
|
||||
}
|
||||
},
|
||||
"terminal": {
|
||||
"closed": "No live terminal — this agent's pane has closed.",
|
||||
"close": "Close",
|
||||
"focusWorktree": "Focus worktree"
|
||||
}
|
||||
},
|
||||
"dashboard": {
|
||||
"sidebar": {
|
||||
"label": "Agent Dashboard"
|
||||
}
|
||||
},
|
||||
"browser": {
|
||||
"loadFailure": {
|
||||
"connectionNotSecure": "Connection isn't secure",
|
||||
|
||||
@@ -5441,6 +5441,12 @@
|
||||
"defaultViewLabel": "기본 기본 채팅 보기",
|
||||
"defaultViewTerminal": "Terminal 채팅",
|
||||
"defaultViewNative": "네이티브 채팅"
|
||||
},
|
||||
"agentDashboard": {
|
||||
"title": "Agent Dashboard",
|
||||
"description": "Pop-out Kanban board for monitoring agents across worktrees.",
|
||||
"copy": "Adds an Agent Dashboard entry to the left sidebar. Open it to monitor attention, working, and idle agents in a separate window and jump into their live terminals.",
|
||||
"toggleLabel": "Toggle Agent Dashboard"
|
||||
}
|
||||
},
|
||||
"FloatingWorkspacePane": {
|
||||
@@ -7614,6 +7620,10 @@
|
||||
"title": "네이티브 채팅",
|
||||
"description": "지원되는 에이전트 터미널 세션의 데스크톱 채팅 화면을 미리 봅니다.",
|
||||
"grok": "grok"
|
||||
},
|
||||
"agentDashboard": {
|
||||
"title": "Agent Dashboard",
|
||||
"description": "Pop-out Kanban board for monitoring agents across worktrees."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -13541,6 +13551,43 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"dashboardPopout": {
|
||||
"placeholder": {
|
||||
"title": "Agent dashboard",
|
||||
"description": "This is where all your agents will show up at a glance. The board is coming soon."
|
||||
},
|
||||
"recoverableError": {
|
||||
"title": "Orca dashboard hit an error.",
|
||||
"description": "The dashboard could not finish rendering. Retry to remount it, or reopen it."
|
||||
},
|
||||
"bucket": {
|
||||
"attention": "Needs You",
|
||||
"working": "Working",
|
||||
"idle": "Idle",
|
||||
"empty": "None"
|
||||
},
|
||||
"title": "Agents",
|
||||
"total": "{{count}} total",
|
||||
"card": {
|
||||
"you": "You",
|
||||
"time": {
|
||||
"justNow": "방금",
|
||||
"minutes": "{{count}}분",
|
||||
"hours": "{{count}}시간",
|
||||
"days": "{{count}}일"
|
||||
}
|
||||
},
|
||||
"terminal": {
|
||||
"closed": "No live terminal — this agent's pane has closed.",
|
||||
"close": "Close",
|
||||
"focusWorktree": "Focus worktree"
|
||||
}
|
||||
},
|
||||
"dashboard": {
|
||||
"sidebar": {
|
||||
"label": "Agent Dashboard"
|
||||
}
|
||||
},
|
||||
"browser": {
|
||||
"loadFailure": {
|
||||
"connectionNotSecure": "Connection isn't secure",
|
||||
|
||||
@@ -5441,6 +5441,12 @@
|
||||
"defaultViewLabel": "默认原生聊天视图",
|
||||
"defaultViewTerminal": "终端聊天",
|
||||
"defaultViewNative": "原生聊天"
|
||||
},
|
||||
"agentDashboard": {
|
||||
"title": "Agent Dashboard",
|
||||
"description": "Pop-out Kanban board for monitoring agents across worktrees.",
|
||||
"copy": "Adds an Agent Dashboard entry to the left sidebar. Open it to monitor attention, working, and idle agents in a separate window and jump into their live terminals.",
|
||||
"toggleLabel": "Toggle Agent Dashboard"
|
||||
}
|
||||
},
|
||||
"FloatingWorkspacePane": {
|
||||
@@ -7614,6 +7620,10 @@
|
||||
"title": "原生聊天",
|
||||
"description": "预览受支持的智能体终端会话的桌面聊天界面。",
|
||||
"grok": "grok"
|
||||
},
|
||||
"agentDashboard": {
|
||||
"title": "Agent Dashboard",
|
||||
"description": "Pop-out Kanban board for monitoring agents across worktrees."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -13541,6 +13551,43 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"dashboardPopout": {
|
||||
"placeholder": {
|
||||
"title": "Agent dashboard",
|
||||
"description": "This is where all your agents will show up at a glance. The board is coming soon."
|
||||
},
|
||||
"recoverableError": {
|
||||
"title": "Orca dashboard hit an error.",
|
||||
"description": "The dashboard could not finish rendering. Retry to remount it, or reopen it."
|
||||
},
|
||||
"bucket": {
|
||||
"attention": "Needs You",
|
||||
"working": "Working",
|
||||
"idle": "Idle",
|
||||
"empty": "None"
|
||||
},
|
||||
"title": "Agents",
|
||||
"total": "{{count}} total",
|
||||
"card": {
|
||||
"you": "You",
|
||||
"time": {
|
||||
"justNow": "刚刚",
|
||||
"minutes": "{{count}} 分钟",
|
||||
"hours": "{{count}} 小时",
|
||||
"days": "{{count}} 天"
|
||||
}
|
||||
},
|
||||
"terminal": {
|
||||
"closed": "No live terminal — this agent's pane has closed.",
|
||||
"close": "Close",
|
||||
"focusWorktree": "Focus worktree"
|
||||
}
|
||||
},
|
||||
"dashboard": {
|
||||
"sidebar": {
|
||||
"label": "Agent Dashboard"
|
||||
}
|
||||
},
|
||||
"browser": {
|
||||
"loadFailure": {
|
||||
"connectionNotSecure": "Connection isn't secure",
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import './assets/main.css'
|
||||
|
||||
import { StrictMode, useEffect } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { DashboardPopoutRoot } from './components/dashboard-popout/DashboardPopoutRoot'
|
||||
import { RecoverableRenderErrorBoundary } from './components/error-boundaries/RecoverableRenderErrorBoundary'
|
||||
import {
|
||||
installRendererCrashDiagnostics,
|
||||
recordRendererCrashBreadcrumb
|
||||
} from './lib/crash-diagnostics'
|
||||
import { applyDocumentTheme } from './lib/document-theme'
|
||||
import { buildAppFontFamily } from './lib/app-font-family'
|
||||
import { I18nProvider } from './i18n/I18nProvider'
|
||||
import { translate } from './i18n/i18n'
|
||||
import { useAppStore } from './store'
|
||||
import type { GlobalSettings } from '../../shared/types'
|
||||
|
||||
// Why: the pop-out window is a separate BrowserWindow with its own React root,
|
||||
// so it must run the same renderer bootstrap as main.tsx (crash diagnostics,
|
||||
// theme, i18n, error boundary) rather than inheriting anything from the main
|
||||
// window. It shares the preload/window.api but not the DOM or JS context.
|
||||
recordRendererCrashBreadcrumb('popout_bootstrap_started', { dev: import.meta.env.DEV })
|
||||
installRendererCrashDiagnostics()
|
||||
|
||||
function applyPopoutAppearance(settings: GlobalSettings | null): void {
|
||||
applyDocumentTheme(settings?.theme ?? 'system', { disableTransitions: false })
|
||||
document.documentElement.style.setProperty(
|
||||
'--app-font-family',
|
||||
buildAppFontFamily(settings?.appFontFamily)
|
||||
)
|
||||
}
|
||||
|
||||
// Why: the popout owns a separate renderer store; seed appearance synchronously
|
||||
// so a forced light/dark theme does not flash the OS theme before first paint.
|
||||
let startupSettings: GlobalSettings | null = null
|
||||
try {
|
||||
startupSettings = window.api.settings.getSync()
|
||||
} catch {
|
||||
// Async hydration below remains available if the startup read fails.
|
||||
}
|
||||
if (startupSettings) {
|
||||
useAppStore.setState({ settings: startupSettings })
|
||||
}
|
||||
applyPopoutAppearance(startupSettings)
|
||||
|
||||
const rootElement = document.getElementById('root')
|
||||
if (!rootElement) {
|
||||
recordRendererCrashBreadcrumb('popout_root_missing')
|
||||
throw new Error('Pop-out root element not found.')
|
||||
}
|
||||
|
||||
// The main process loads popout.html with ?view=<name> so a single entry can
|
||||
// host different dashboard layouts (kanban, etc.).
|
||||
const requestedView = new URLSearchParams(window.location.search).get('view')
|
||||
|
||||
function PopoutSettingsSync(): null {
|
||||
const settings = useAppStore((state) => state.settings)
|
||||
|
||||
useEffect(() => {
|
||||
let disposed = false
|
||||
const setSettings = (next: GlobalSettings): void => {
|
||||
if (!disposed) {
|
||||
useAppStore.setState({ settings: next })
|
||||
}
|
||||
}
|
||||
const offChanged = window.api.settings.onChanged((updates) => {
|
||||
const current = useAppStore.getState().settings
|
||||
if (current) {
|
||||
setSettings({ ...current, ...updates })
|
||||
}
|
||||
})
|
||||
void window.api.settings
|
||||
.get()
|
||||
.then(setSettings)
|
||||
.catch(() => undefined)
|
||||
return () => {
|
||||
disposed = true
|
||||
offChanged()
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
applyPopoutAppearance(settings)
|
||||
if (settings?.theme !== 'system') {
|
||||
return
|
||||
}
|
||||
const media = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
const handleChange = (): void => applyDocumentTheme('system')
|
||||
media.addEventListener('change', handleChange)
|
||||
return () => media.removeEventListener('change', handleChange)
|
||||
}, [settings])
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function PopoutRoot(): React.JSX.Element {
|
||||
useTranslation()
|
||||
return (
|
||||
<RecoverableRenderErrorBoundary
|
||||
boundaryId="dashboard-popout.root"
|
||||
surface="dashboard-popout"
|
||||
title={translate('dashboardPopout.recoverableError.title', 'Orca dashboard hit an error.')}
|
||||
description={translate(
|
||||
'dashboardPopout.recoverableError.description',
|
||||
'The dashboard could not finish rendering. Retry to remount it, or reopen it.'
|
||||
)}
|
||||
>
|
||||
<DashboardPopoutRoot view={requestedView} />
|
||||
</RecoverableRenderErrorBoundary>
|
||||
)
|
||||
}
|
||||
|
||||
createRoot(rootElement).render(
|
||||
<StrictMode>
|
||||
<I18nProvider>
|
||||
<PopoutSettingsSync />
|
||||
<PopoutRoot />
|
||||
</I18nProvider>
|
||||
</StrictMode>
|
||||
)
|
||||
recordRendererCrashBreadcrumb('popout_bootstrap_rendered')
|
||||
@@ -90,6 +90,10 @@ describe('getDefaultSettings', () => {
|
||||
expect(getDefaultSettings('/tmp').experimentalEphemeralVms).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps the agent dashboard popout disabled by default', () => {
|
||||
expect(getDefaultSettings('/tmp').experimentalAgentDashboardPopout).toBe(false)
|
||||
})
|
||||
|
||||
it('routes fresh Codex profiles through the real-home rollout by default', () => {})
|
||||
|
||||
it('defaults local Windows projects to the host runtime', () => {
|
||||
|
||||
@@ -334,6 +334,7 @@ export function getDefaultSettings(homedir: string): GlobalSettings {
|
||||
// Why: off keeps the cosmetic overlay unmounted for users who never opt in.
|
||||
experimentalPet: false,
|
||||
experimentalActivity: false,
|
||||
experimentalAgentDashboardPopout: false,
|
||||
experimentalActivityDefaultedOffForAllUsers: true,
|
||||
experimentalTerminalAttention: false,
|
||||
experimentalAgentHibernation: false,
|
||||
|
||||
@@ -70,6 +70,7 @@ export type ReactErrorBoundarySurface =
|
||||
| 'modal'
|
||||
| 'overlay'
|
||||
| 'rich-markdown-editor'
|
||||
| 'dashboard-popout'
|
||||
|
||||
export type ReactErrorBoundaryReportArgs = {
|
||||
boundaryId: string
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { AgentType } from './agent-status-types'
|
||||
|
||||
/**
|
||||
* Serializable contract for the pop-out agent dashboard. The main renderer owns
|
||||
* the live store, derives this snapshot, and relays it (through the main
|
||||
* process) to the separate pop-out renderer, which renders it presentationally.
|
||||
* Every field must be structured-clone-safe (no functions / class instances).
|
||||
*/
|
||||
|
||||
/** The three kanban columns. "Idle" is everything that isn't actively working
|
||||
* and isn't blocking you — this includes explicitly-completed ('done') agents,
|
||||
* which Orca only reports when a completion hook fires, so they're folded in
|
||||
* rather than split into a separate, inconsistently-populated column. */
|
||||
export type DashboardBucket = 'attention' | 'working' | 'idle'
|
||||
|
||||
/** Column order shared by producer and pop-out so they never drift. */
|
||||
export const DASHBOARD_BUCKET_ORDER: readonly DashboardBucket[] = ['attention', 'working', 'idle']
|
||||
|
||||
/** Precise per-card state marker (drives AgentStateDot). Kept distinct from
|
||||
* `bucket` so the "Needs You" column can still show amber (waiting/permission)
|
||||
* vs red (blocked) dots. */
|
||||
export type DashboardCardDotState = 'working' | 'blocked' | 'waiting' | 'done' | 'idle'
|
||||
|
||||
export type DashboardCard = {
|
||||
/** Stable identity for React keys. */
|
||||
paneKey: string
|
||||
/** Resolved live PTY id for the terminal preview, or null when the agent has
|
||||
* no live pane (e.g. a retained/done row whose pane is gone). */
|
||||
ptyId: string | null
|
||||
agentType: AgentType
|
||||
bucket: DashboardBucket
|
||||
dotState: DashboardCardDotState
|
||||
/** One-line task/prompt text shown on the card. */
|
||||
task: string
|
||||
/** The most recent message the user sent this agent (its current prompt). */
|
||||
lastUserMessage?: string
|
||||
/** The most recent message the agent sent back. */
|
||||
lastAgentMessage?: string
|
||||
/** Routing target for click-to-focus. leafId is null when unresolved. */
|
||||
repoId: string
|
||||
worktreeId: string
|
||||
tabId: string
|
||||
leafId: string | null
|
||||
repoName: string
|
||||
worktreeName: string
|
||||
/** "Started … ago" display. */
|
||||
startedAt: number
|
||||
/** When the agent entered its current state — column ordering key (cards
|
||||
* that moved into a bucket most recently sort first). 0 when unknown. */
|
||||
stateChangedAt: number
|
||||
/** Mirrors the sidebar's unvisited signal: the agent changed state since the
|
||||
* user last acknowledged it (visited its tab / opened its dashboard dialog).
|
||||
* Derived from the app-wide ack map so both surfaces mute in lockstep. */
|
||||
unseen: boolean
|
||||
/** Short summary of the pending question when bucket === 'attention'. */
|
||||
askSummary?: string
|
||||
}
|
||||
|
||||
export type DashboardSnapshot = {
|
||||
generatedAt: number
|
||||
cards: DashboardCard[]
|
||||
}
|
||||
|
||||
export const EMPTY_DASHBOARD_SNAPSHOT: DashboardSnapshot = { generatedAt: 0, cards: [] }
|
||||
|
||||
/** Routing payload for click-to-focus: reveal this agent's pane in the main
|
||||
* window. leafId is null when the pane could not be resolved (best-effort:
|
||||
* the worktree is still activated). */
|
||||
export type DashboardRevealAgentArgs = {
|
||||
repoId: string
|
||||
worktreeId: string
|
||||
tabId: string
|
||||
leafId: string | null
|
||||
}
|
||||
@@ -239,6 +239,7 @@ export const SETTINGS_CHANGED_WHITELIST = [
|
||||
'experimentalPet',
|
||||
'experimentalNativeChat',
|
||||
'experimentalActivity',
|
||||
'experimentalAgentDashboardPopout',
|
||||
'experimentalTerminalAttention',
|
||||
'experimentalAgentHibernation',
|
||||
'experimentalEphemeralVms',
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
export type TerminalPreviewSnapshot = {
|
||||
data: string
|
||||
cols: number
|
||||
rows: number
|
||||
seq?: number
|
||||
scrollbackAnsi?: string
|
||||
pendingEscapeTailAnsi?: string
|
||||
}
|
||||
|
||||
export type TerminalPreviewConnectResult = {
|
||||
snapshot: TerminalPreviewSnapshot | null
|
||||
/** Live bytes captured while the snapshot was being serialized. */
|
||||
replay: string[]
|
||||
/** Snapshot acquisition overflowed twice; refresh without blanking the existing view. */
|
||||
resyncRequired?: boolean
|
||||
}
|
||||
|
||||
export type TerminalPreviewDataPayload =
|
||||
| { type: 'data'; ptyId: string; data: string; bytes: number }
|
||||
| { type: 'resync'; ptyId: string }
|
||||
@@ -2874,6 +2874,8 @@ export type GlobalSettings = {
|
||||
experimentalSidekick?: boolean
|
||||
/** Experimental: left-sidebar Agents view — threaded feed of agent completions, blocking/unread state, worktree creation. */
|
||||
experimentalActivity: boolean
|
||||
/** Experimental: pop-out Kanban dashboard for monitoring and opening agent terminals across worktrees. */
|
||||
experimentalAgentDashboardPopout?: boolean
|
||||
/** One-shot migration guard for defaulting the Agents view off; later explicit opt-ins persist normally. */
|
||||
experimentalActivityDefaultedOffForAllUsers?: boolean
|
||||
/** Experimental: persistent terminal-pane attention ring for bell + agent-completion events. Opt-in while tuning signal/noise. */
|
||||
@@ -3272,6 +3274,9 @@ export type PersistedUIState = {
|
||||
windowBounds?: { x: number; y: number; width: number; height: number } | null
|
||||
/** Whether the window was maximized when it was last closed. */
|
||||
windowMaximized?: boolean
|
||||
/** Saved bounds for the pop-out dashboard window so it restores to its last
|
||||
* position/size. Independent of the main window's bounds. */
|
||||
dashboardPopoutBounds?: { x: number; y: number; width: number; height: number } | null
|
||||
/** One-shot flag: 'recent' once meant the smart sort (v1→v2 rename), migrated to 'smart' once so the new last-activity 'recent' isn't re-clobbered. */
|
||||
_sortBySmartMigrated?: boolean
|
||||
/** LEGACY inline-agents flag, stamped unconditionally every load so it can't gate migration; kept only for rollback forward-compat (real gate: _inlineAgentsDefaultedForAllUsers). */
|
||||
|
||||
Reference in New Issue
Block a user