mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-01 04:59:41 +02:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d59c1764d | ||
|
|
cfcd9d288b | ||
|
|
9c22114b5a | ||
|
|
98b2124d7e |
@@ -1,5 +1,40 @@
|
||||
# aicodeman
|
||||
|
||||
## 1.1.14
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Ultracode (Workflow-tool) floating windows — agent transcripts in-page, and minimize-to-tab.
|
||||
- **Agent transcripts open in-page, connected, instead of a detached browser popup.** Clicking an agent card (in a run window or the dock panel) now opens the agent's live transcript as its own draggable floating window, tied by a connector line to its parent run window (falling back to the run's session tab if that window has since closed) — the same line idiom the run windows use. Re-clicking a card focuses the existing window; closing it removes the window and its line. (Previously this spawned a separate `window.open` browser popup.)
|
||||
- **The window "−" button now minimizes into the originating session tab**, mirroring the subagent-window idiom. The window genie-animates into its tab and is tracked there; the tab shows an `ULTRA` badge whose hover/click dropdown lists each minimized item (🧬 run windows, 📄 agent transcripts). Click an item to restore its floating window, or dismiss it with ×. A run minimized while still active keeps tracking in the background and its badge auto-clears shortly after the run finishes. Both run windows and agent-transcript windows minimize into the same merged badge.
|
||||
- Removed the old collapse-to-header behavior that the "−" button previously triggered (now superseded by minimize-to-tab).
|
||||
|
||||
## 1.1.13
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Keep the `/compact` button in the extended (full) mobile keyboard accessory bar; only the simple bar drops it. (1.1.12 had removed it from both.)
|
||||
|
||||
## 1.1.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Remove the `/compact` button from the mobile keyboard accessory bar. It had been reintroduced in 1.1.10; this removes the button from both the simple and full accessory-bar layouts (the underlying command handler is left in place as inert plumbing).
|
||||
|
||||
## 1.1.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Ultracode (Workflow-tool) run visualization — much better live tracking.
|
||||
|
||||
While a run is in flight, the watcher previously showed empty agent slots ("agent N", 0 tokens, raw `wf_…` id as the title) because the detailed completion JSON only lands when the run finishes. The live path now enriches in-flight runs directly from the on-disk transcript tree:
|
||||
- **Real per-agent stats mid-run** — tokens and tool-call counts are parsed from each `agent-<id>.jsonl` transcript (tool counts match the final accounting exactly; token totals land within ~1% of the completion value), with model and a prompt preview. All mtime-cached (transcripts, journal, and script meta) so idle polls do no extra reads.
|
||||
- **Readable window/run title** — workflow name, summary, and phases are derived from the persisted `workflows/scripts/<name>-<runId>.js` instead of showing the raw run id.
|
||||
- **Agent status colors** — done agents show green, working agents show yellow (this also fixes the run/agent status badges, which referenced undefined `--success`/`--warning` CSS variables and were rendering with no color).
|
||||
- **Connector line** — the floating-window → session-tab line now uses the session-tab accent blue (was purple).
|
||||
- **Click a run to open its floating window** — clicking a workflow in the dock panel opens (or focuses) its floating window with the connector line, in addition to the auto-popped windows.
|
||||
- Agents are ordered by journal launch order; concurrent run-detail fetches are de-duplicated.
|
||||
|
||||
## 1.1.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -56,7 +56,7 @@ When user says "COM":
|
||||
|
||||
CI runs `npm run check:lockfile` on every push/PR, so lockfile drift fails the build even if the `version-packages` script is bypassed.
|
||||
|
||||
**Version**: 1.1.10 (must match `package.json`)
|
||||
**Version**: 1.1.14 (must match `package.json`)
|
||||
|
||||
## Project Overview
|
||||
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "aicodeman",
|
||||
"version": "1.1.10",
|
||||
"version": "1.1.14",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "aicodeman",
|
||||
"version": "1.1.10",
|
||||
"version": "1.1.14",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "aicodeman",
|
||||
"version": "1.1.10",
|
||||
"version": "1.1.14",
|
||||
"description": "Mission control for AI coding agents - run 20 autonomous agents with real-time monitoring and session persistence",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
|
||||
@@ -2773,6 +2773,10 @@ class CodemanApp {
|
||||
const minimizedCount = minimizedAgents?.size || 0;
|
||||
const subagentBadge = minimizedCount > 0 ? this.renderSubagentTabBadge(id, minimizedAgents) : '';
|
||||
|
||||
// Ultracode runs + agent transcripts minimized to this tab (ultracode-windows.js
|
||||
// renders one merged ULTRA badge; returns '' when nothing is minimized).
|
||||
const ultracodeBadge = this.renderUltracodeTabBadge ? this.renderUltracodeTabBadge(id) : '';
|
||||
|
||||
// Show folder name if session has a custom name AND tall tabs setting is enabled
|
||||
const folderName = session.workingDir ? session.workingDir.split('/').pop() || '' : '';
|
||||
const tallTabsEnabled = this._tallTabsEnabled ?? false;
|
||||
@@ -2792,6 +2796,7 @@ class CodemanApp {
|
||||
</span>
|
||||
${hasRunningTasks ? `<span class="tab-badge" onclick="event.stopPropagation(); app.toggleTaskPanel()" aria-label="${taskStats.running} running tasks">${taskStats.running}</span>` : ''}
|
||||
${subagentBadge}
|
||||
${ultracodeBadge}
|
||||
<span class="tab-gear" onclick="event.stopPropagation(); app.openSessionOptions('${escapeHtml(id)}')" title="Session options" aria-label="Session options" tabindex="0">⚙</span>
|
||||
<span class="tab-detach" onclick="event.stopPropagation(); app.detachSession('${escapeHtml(id)}')" title="Open in a new window" aria-label="Open session in a new window" tabindex="0">⧉</span>
|
||||
<span class="tab-close" onclick="event.stopPropagation(); app.requestCloseSession('${escapeHtml(id)}')" title="Close session" aria-label="Close session" tabindex="0">×</span>
|
||||
|
||||
@@ -58,7 +58,6 @@ const KeyboardAccessoryBar = {
|
||||
</svg>
|
||||
</button>
|
||||
<button class="accessory-btn" data-action="esc" title="Escape">Esc</button>
|
||||
<button class="accessory-btn" data-action="compact" title="/compact">/compact</button>
|
||||
<button class="accessory-btn accessory-btn-dismiss" data-action="dismiss" title="Dismiss keyboard">
|
||||
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3">
|
||||
<path d="M19 9l-7 7-7-7"/>
|
||||
|
||||
+93
-16
@@ -5573,6 +5573,45 @@ kbd {
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
|
||||
/* Ultracode run minimized-to-tab badge — same chip shape as the subagent badge but a
|
||||
distinct purple (matches the ultracode window accent), and a SEPARATE class so the
|
||||
incremental tab-update path (which keys on .tab-subagent-badge) never touches it.
|
||||
Reuses the shared .subagent-dropdown for its restore/dismiss list. */
|
||||
.session-tab .tab-ultracode-badge {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 2px;
|
||||
height: 16px;
|
||||
padding: 0 5px;
|
||||
border-radius: 8px;
|
||||
font-size: 0.6rem;
|
||||
cursor: pointer;
|
||||
background: #a855f7;
|
||||
color: white;
|
||||
margin-left: 4px;
|
||||
transition: transform 0.1s, background 0.15s;
|
||||
}
|
||||
@media (hover: hover) {
|
||||
.session-tab .tab-ultracode-badge:hover {
|
||||
background: #9333ea;
|
||||
transform: scale(1.05);
|
||||
}
|
||||
}
|
||||
.session-tab .tab-ultracode-badge .subagent-label {
|
||||
font-size: 0.55rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
/* Per-item type glyph in the ULTRA dropdown (🧬 run vs 📄 transcript). */
|
||||
.subagent-dropdown-item .ultracode-dd-icon {
|
||||
font-size: 0.7rem;
|
||||
line-height: 1;
|
||||
flex-shrink: 0;
|
||||
margin-right: 1px;
|
||||
}
|
||||
|
||||
/* Subagent Dropdown - compact, hover-triggered */
|
||||
.subagent-dropdown {
|
||||
display: none;
|
||||
@@ -8473,14 +8512,14 @@ kbd {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.ultracode-status.completed {
|
||||
background: var(--success);
|
||||
background: var(--green);
|
||||
}
|
||||
.ultracode-status.active {
|
||||
background: var(--warning);
|
||||
background: var(--yellow);
|
||||
color: black;
|
||||
}
|
||||
.ultracode-status.failed {
|
||||
background: var(--error, #b3261e);
|
||||
background: var(--red, #b3261e);
|
||||
color: white;
|
||||
}
|
||||
|
||||
@@ -8531,6 +8570,16 @@ kbd {
|
||||
border-radius: 6px;
|
||||
padding: 0.4rem 0.5rem;
|
||||
margin-bottom: 0.35rem;
|
||||
border-left: 3px solid transparent;
|
||||
}
|
||||
/* At-a-glance agent state: yellow while working, green when done. */
|
||||
.ultracode-agent-card.uw-state-working {
|
||||
border-left-color: var(--yellow);
|
||||
background: color-mix(in srgb, var(--yellow) 9%, var(--bg-input));
|
||||
}
|
||||
.ultracode-agent-card.uw-state-done {
|
||||
border-left-color: var(--green);
|
||||
background: color-mix(in srgb, var(--green) 9%, var(--bg-input));
|
||||
}
|
||||
.ultracode-agent-card--clickable {
|
||||
cursor: pointer;
|
||||
@@ -8539,6 +8588,14 @@ kbd {
|
||||
.ultracode-agent-card--clickable:hover {
|
||||
background: var(--bg-card);
|
||||
}
|
||||
/* Keep the state tint on hover (equal specificity to the hover rule, so it must
|
||||
come after it) — a tad stronger so the hover still reads as interactive. */
|
||||
.ultracode-agent-card--clickable.uw-state-working:hover {
|
||||
background: color-mix(in srgb, var(--yellow) 16%, var(--bg-card));
|
||||
}
|
||||
.ultracode-agent-card--clickable.uw-state-done:hover {
|
||||
background: color-mix(in srgb, var(--green) 16%, var(--bg-card));
|
||||
}
|
||||
.ultracode-agent-top {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -8564,10 +8621,10 @@ kbd {
|
||||
color: white;
|
||||
}
|
||||
.ultracode-agent-state.completed {
|
||||
background: var(--success);
|
||||
background: var(--green);
|
||||
}
|
||||
.ultracode-agent-state.active {
|
||||
background: var(--warning);
|
||||
background: var(--yellow);
|
||||
color: black;
|
||||
}
|
||||
.ultracode-agent-state.idle {
|
||||
@@ -8629,13 +8686,6 @@ kbd {
|
||||
transform: scale(0.92);
|
||||
opacity: 0;
|
||||
}
|
||||
.ultracode-window.collapsed {
|
||||
height: auto !important;
|
||||
resize: none;
|
||||
}
|
||||
.ultracode-window.collapsed .ultracode-window-body {
|
||||
display: none;
|
||||
}
|
||||
.ultracode-window-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -8707,14 +8757,15 @@ kbd {
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
/* Ultracode connector line — distinct purple to set it apart from blue subagent lines. */
|
||||
/* Ultracode connector line — the session-tab accent blue (dashed to stay distinct
|
||||
from the solid subagent lines, per the same-blue-as-the-tab request). */
|
||||
.connection-line.ultracode-connection {
|
||||
stroke: #a855f7;
|
||||
stroke: var(--accent);
|
||||
stroke-width: 3;
|
||||
stroke-dasharray: 6 3;
|
||||
filter: drop-shadow(0 0 2px rgba(0, 0, 0, 0.8))
|
||||
drop-shadow(0 0 5px rgba(168, 85, 247, 0.85))
|
||||
drop-shadow(0 0 10px rgba(168, 85, 247, 0.5));
|
||||
drop-shadow(0 0 5px rgba(var(--accent-rgb), 0.85))
|
||||
drop-shadow(0 0 10px rgba(var(--accent-rgb), 0.5));
|
||||
animation: ultracode-conn-pulse 1.4s ease-in-out infinite;
|
||||
}
|
||||
.connection-line.ultracode-connection:hover {
|
||||
@@ -8725,6 +8776,32 @@ kbd {
|
||||
50% { opacity: 1; }
|
||||
}
|
||||
|
||||
/* Agent-transcript window: spawned from an agent card (in a run window or the dock
|
||||
panel), tied to its parent run window by its own connector line. Reuses the
|
||||
.ultracode-window chrome; wider with a monospace transcript body. */
|
||||
.ultracode-agent-window {
|
||||
width: 470px;
|
||||
height: 420px;
|
||||
border-color: #38bdf8;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.45), 0 0 0 1px rgba(56, 189, 248, 0.18);
|
||||
}
|
||||
.ultracode-agent-window .ultracode-window-body .uw-transcript {
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.68rem;
|
||||
line-height: 1.45;
|
||||
color: var(--text);
|
||||
}
|
||||
/* Distinguish the parent→agent line from the tab→run line: solid cyan, no dashes.
|
||||
Must follow .ultracode-connection (equal specificity → source order wins). */
|
||||
.connection-line.ultracode-agent-connection {
|
||||
stroke: #38bdf8;
|
||||
stroke-dasharray: none;
|
||||
filter: drop-shadow(0 0 2px rgba(0, 0, 0, 0.8)) drop-shadow(0 0 5px rgba(56, 189, 248, 0.85));
|
||||
}
|
||||
|
||||
/* Plan-usage chip (App Settings → Display → "Plan Usage Limits"). Shows the
|
||||
live 5-hour + weekly plan limits parsed from the Claude statusline. Hidden by
|
||||
default via the marker class below; the server strips it at render when the
|
||||
|
||||
@@ -461,6 +461,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
if (typeof this._appendUltracodeConnectionLines === 'function') {
|
||||
this._appendUltracodeConnectionLines(svg, rects);
|
||||
}
|
||||
// Agent-transcript windows → their run window / tab (ultracode-windows.js).
|
||||
if (typeof this._appendUltracodeAgentConnectionLines === 'function') {
|
||||
this._appendUltracodeAgentConnectionLines(svg, rects);
|
||||
}
|
||||
},
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -96,6 +96,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.activeWorkflowPhaseIndex = null; // reset phase filter on run change
|
||||
this._fetchWorkflowRunDetail(runId);
|
||||
this.renderUltracodeAgentsPanel();
|
||||
// Clicking a run also pops its floating window (with connector line to the
|
||||
// session tab), like the auto-popped one — an explicit open, so it ignores the
|
||||
// floating-windows auto-pop toggle (ultracode-windows.js).
|
||||
if (typeof this.openUltracodeWindowForRun === 'function') this.openUltracodeWindowForRun(runId);
|
||||
},
|
||||
selectWorkflowPhase(phaseIndex) {
|
||||
this._ensureWorkflowState();
|
||||
@@ -105,6 +109,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
|
||||
async _fetchWorkflowRunDetail(runId) {
|
||||
// De-dupe concurrent fetches for the same run — selecting a run can trigger both
|
||||
// a panel refresh and a floating-window open, which would otherwise double-fetch.
|
||||
if (!this._wfDetailInFlight) this._wfDetailInFlight = new Set();
|
||||
if (this._wfDetailInFlight.has(runId)) return;
|
||||
this._wfDetailInFlight.add(runId);
|
||||
try {
|
||||
const res = await fetch(`/api/workflows/${encodeURIComponent(runId)}`);
|
||||
const env = await res.json();
|
||||
@@ -117,15 +126,20 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
} catch {
|
||||
/* transient — next update retries */
|
||||
} finally {
|
||||
this._wfDetailInFlight.delete(runId);
|
||||
}
|
||||
},
|
||||
|
||||
// Phase 4: open an agent's live transcript by agentId. The workflow agent's
|
||||
// Phase 4: fetch an agent's live transcript by agentId. The workflow agent's
|
||||
// agentId is byte-identical to the agent-<id>.jsonl stem already tracked by
|
||||
// subagent-watcher, so we reuse the existing transcript route — no watcher edits.
|
||||
// Graceful when the agent isn't tracked yet / aged out / tracking disabled.
|
||||
async openWorkflowAgentTranscript(agentId) {
|
||||
if (!agentId) return;
|
||||
// Returns { formatted: string[], entryCount } or null when nothing is available
|
||||
// (queued / aged out of tracking / tracking disabled). Rendering into a connected
|
||||
// in-page floating window lives in ultracode-windows.js (openUltracodeAgentWindow) —
|
||||
// we no longer spawn a detached browser popup.
|
||||
async _fetchWorkflowAgentTranscript(agentId) {
|
||||
if (!agentId) return null;
|
||||
let data = null;
|
||||
try {
|
||||
const res = await fetch(`/api/subagents/${encodeURIComponent(agentId)}/transcript?format=formatted`);
|
||||
@@ -136,21 +150,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
const ok = data && data.success && data.data;
|
||||
const formatted = ok ? data.data.formatted : null;
|
||||
const entryCount = ok ? data.data.entryCount || 0 : 0;
|
||||
if (!formatted || !entryCount) {
|
||||
alert(
|
||||
'No transcript available for this agent yet — it may be queued, aged out of tracking, or subagent tracking is disabled.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
const win = window.open('', '_blank', 'width=860,height=640');
|
||||
if (!win) return; // popup blocked
|
||||
win.document.write(
|
||||
`<html><head><title>Workflow agent ${escapeHtml(agentId)} transcript</title>` +
|
||||
`<style>body{background:#1a1a2e;color:#eee;font-family:monospace;padding:20px}pre{white-space:pre-wrap;word-wrap:break-word}</style>` +
|
||||
`</head><body><h2>Workflow agent ${escapeHtml(agentId)} (${entryCount} entries)</h2>` +
|
||||
`<pre>${escapeHtml(formatted.join('\n'))}</pre></body></html>`
|
||||
);
|
||||
win.document.close();
|
||||
if (!formatted || !entryCount) return null;
|
||||
return { formatted, entryCount };
|
||||
},
|
||||
|
||||
// ----- Render (debounced) -----
|
||||
@@ -251,13 +252,13 @@ Object.assign(CodemanApp.prototype, {
|
||||
const header =
|
||||
`<div class="ultracode-phase-header"><span>${escapeHtml(title)}</span>` +
|
||||
`<span class="ultracode-phase-sub">${this._fmtNum(tok)} tok · ${tools} tools</span></div>`;
|
||||
return header + group.map((a) => this._workflowAgentCardHtml(a)).join('');
|
||||
return header + group.map((a) => this._workflowAgentCardHtml(a, runId)).join('');
|
||||
})
|
||||
.join('');
|
||||
detail.innerHTML = html;
|
||||
},
|
||||
|
||||
_workflowAgentCardHtml(a) {
|
||||
_workflowAgentCardHtml(a, runId) {
|
||||
const state = String(a.state || 'start');
|
||||
const stateCls = this._workflowAgentStateClass(state);
|
||||
const stateLabel = state === 'start' ? 'queued' : state === 'progress' ? 'running' : state;
|
||||
@@ -274,10 +275,12 @@ Object.assign(CodemanApp.prototype, {
|
||||
// to the agent-<id>.jsonl stem already tracked by subagent-watcher). 'start' agents have
|
||||
// no agentId yet, so they stay non-clickable.
|
||||
const clickable = !!a.agentId;
|
||||
// At-a-glance state tint on the whole card: green when done, yellow while working.
|
||||
const cardStateCls = state === 'done' ? ' uw-state-done' : state === 'progress' ? ' uw-state-working' : '';
|
||||
const cardAttrs = clickable
|
||||
? ` class="ultracode-agent-card ultracode-agent-card--clickable" role="button" tabindex="0"` +
|
||||
` title="View transcript" onclick="app.openWorkflowAgentTranscript('${escapeHtml(a.agentId)}')"`
|
||||
: ` class="ultracode-agent-card"`;
|
||||
? ` class="ultracode-agent-card ultracode-agent-card--clickable${cardStateCls}" role="button" tabindex="0"` +
|
||||
` title="View transcript" onclick="app.openUltracodeAgentWindow('${escapeHtml(a.agentId)}','${escapeHtml(runId || '')}')"`
|
||||
: ` class="ultracode-agent-card${cardStateCls}"`;
|
||||
return (
|
||||
`<div${cardAttrs}>` +
|
||||
`<div class="ultracode-agent-top">` +
|
||||
|
||||
@@ -33,9 +33,12 @@
|
||||
Object.assign(CodemanApp.prototype, {
|
||||
/** Lazily seed the floating-window state maps (constructor also seeds them). */
|
||||
_ensureUltracodeWindowState() {
|
||||
if (!this.ultracodeWindows) this.ultracodeWindows = new Map(); // runId -> { element, parentSessionId, dragListeners, collapsed }
|
||||
if (!this.ultracodeWindows) this.ultracodeWindows = new Map(); // runId -> { element, parentSessionId, dragListeners }
|
||||
if (!this.ultracodeWindowsClosed) this.ultracodeWindowsClosed = new Set(); // runIds the user dismissed
|
||||
if (!this.ultracodeWindowCloseTimers) this.ultracodeWindowCloseTimers = new Map(); // runId -> setTimeout id
|
||||
if (!this.ultracodeAgentWindows) this.ultracodeAgentWindows = new Map(); // agentId -> { element, runId, dragListeners }
|
||||
if (!this.minimizedUltracodeRuns) this.minimizedUltracodeRuns = new Map(); // sessionId -> Set<runId> minimized to a tab
|
||||
if (!this.minimizedUltracodeAgents) this.minimizedUltracodeAgents = new Map(); // sessionId -> Map<agentId,{runId,label}>
|
||||
if (this.ultracodeWindowZIndex === undefined) this.ultracodeWindowZIndex = 1000;
|
||||
},
|
||||
|
||||
@@ -77,12 +80,29 @@ Object.assign(CodemanApp.prototype, {
|
||||
_syncUltracodeFloatingWindow(run, opts) {
|
||||
this._ensureUltracodeWindowState();
|
||||
if (!run || !run.runId) return;
|
||||
if (!this._ultracodeFloatingEnabled()) return;
|
||||
const runId = run.runId;
|
||||
const existing = this.ultracodeWindows.get(runId);
|
||||
// Auto-pop is gated on the floating-windows toggle, but an ALREADY-open window
|
||||
// (e.g. one opened by clicking the run in the dock) keeps refreshing regardless.
|
||||
if (!existing && !this._ultracodeFloatingEnabled()) return;
|
||||
if (this.ultracodeWindowsClosed.has(runId)) return; // respect explicit dismissal
|
||||
|
||||
const active = this._isWorkflowRunActive(run);
|
||||
const existing = this.ultracodeWindows.get(runId);
|
||||
|
||||
// Minimized to a tab — keep it there (don't re-pop a window). Clear the tab badge a
|
||||
// short while after the run finishes, mirroring the floating window's finish grace.
|
||||
if (this._isUltracodeRunMinimized(runId)) {
|
||||
if (!active && !this.ultracodeWindowCloseTimers.has(runId)) {
|
||||
const timer = setTimeout(() => {
|
||||
this.ultracodeWindowCloseTimers.delete(runId);
|
||||
this._removeMinimizedUltracodeRun(runId);
|
||||
this.renderSessionTabs();
|
||||
this.updateConnectionLines();
|
||||
}, 8000);
|
||||
this.ultracodeWindowCloseTimers.set(runId, timer);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (active) {
|
||||
// Run is alive — cancel any pending auto-close.
|
||||
@@ -120,6 +140,31 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Explicitly open (or focus) the floating window for a run — the click-through
|
||||
* from the dock panel's run list. Unlike auto-pop this ignores the floating-windows
|
||||
* toggle and clears any prior dismissal (it's a direct user action), then draws the
|
||||
* connector line from the run's session tab.
|
||||
*/
|
||||
openUltracodeWindowForRun(runId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
if (!runId) return;
|
||||
const run = this.workflowRuns && this.workflowRuns.get(runId);
|
||||
if (!run) return;
|
||||
this.ultracodeWindowsClosed.delete(runId); // an explicit open overrides a past dismissal
|
||||
this._removeMinimizedUltracodeRun(runId); // …and a past minimize-to-tab
|
||||
const existing = this.ultracodeWindows.get(runId);
|
||||
if (existing) {
|
||||
// Already open — bring to front and refresh.
|
||||
existing.element.style.zIndex = ++this.ultracodeWindowZIndex;
|
||||
this.renderUltracodeWindowContent(runId);
|
||||
this._fetchWorkflowRunDetail(runId);
|
||||
this.updateConnectionLines();
|
||||
} else {
|
||||
this.createUltracodeWindow(run);
|
||||
}
|
||||
},
|
||||
|
||||
/** Build and mount a floating window for a run, positioned near its parent tab. */
|
||||
createUltracodeWindow(run) {
|
||||
this._ensureUltracodeWindowState();
|
||||
@@ -140,7 +185,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
<span class="uw-status"></span>
|
||||
</div>
|
||||
<div class="ultracode-window-actions">
|
||||
<button class="uw-min" type="button" title="Collapse">─</button>
|
||||
<button class="uw-min" type="button" title="Minimize to tab">─</button>
|
||||
<button class="uw-close" type="button" title="Close">×</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -171,7 +216,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
win.querySelector('.uw-min').addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
this.toggleUltracodeWindowCollapse(runId);
|
||||
this.minimizeUltracodeWindowToTab(runId);
|
||||
});
|
||||
win.querySelector('.uw-close').addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
@@ -184,19 +229,261 @@ Object.assign(CodemanApp.prototype, {
|
||||
nameEl.addEventListener('click', () => this.selectSession(parentSessionId));
|
||||
}
|
||||
|
||||
this.ultracodeWindows.set(runId, { element: win, parentSessionId, dragListeners, collapsed: false });
|
||||
this.ultracodeWindows.set(runId, { element: win, parentSessionId, dragListeners });
|
||||
|
||||
this.renderUltracodeWindowContent(runId);
|
||||
this._fetchWorkflowRunDetail(runId); // pull agents[] for the body
|
||||
this.updateConnectionLines();
|
||||
},
|
||||
|
||||
/** Collapse/expand the window to header-only (line stays connected). */
|
||||
toggleUltracodeWindowCollapse(runId) {
|
||||
// ── Minimize a run window into its originating tab (same idiom as subagent windows) ──
|
||||
|
||||
/** Is this run currently minimized to a tab (so auto-pop should leave it alone)? */
|
||||
_isUltracodeRunMinimized(runId) {
|
||||
if (!this.minimizedUltracodeRuns) return false;
|
||||
for (const set of this.minimizedUltracodeRuns.values()) {
|
||||
if (set.has(runId)) return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
/** Drop a run from the minimized-to-tab tracking (all sessions, or a specific one). */
|
||||
_removeMinimizedUltracodeRun(runId, sessionId) {
|
||||
if (!this.minimizedUltracodeRuns) return;
|
||||
if (sessionId) {
|
||||
const set = this.minimizedUltracodeRuns.get(sessionId);
|
||||
if (set) {
|
||||
set.delete(runId);
|
||||
if (!set.size) this.minimizedUltracodeRuns.delete(sessionId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (const [sid, set] of this.minimizedUltracodeRuns) {
|
||||
if (set.delete(runId) && !set.size) this.minimizedUltracodeRuns.delete(sid);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Minimize the floating run window into its originating session tab: record it as
|
||||
* minimized (so a badge renders on the tab), genie-animate the window toward that
|
||||
* tab, then remove the floating element. Restorable from the tab badge dropdown.
|
||||
*/
|
||||
minimizeUltracodeWindowToTab(runId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
const data = this.ultracodeWindows.get(runId);
|
||||
if (!data) return;
|
||||
data.collapsed = !data.collapsed;
|
||||
data.element.classList.toggle('collapsed', data.collapsed);
|
||||
|
||||
let parentSessionId = data.parentSessionId;
|
||||
if (!parentSessionId) {
|
||||
const summary = this.workflowRuns && this.workflowRuns.get(runId);
|
||||
parentSessionId = summary ? this._resolveUltracodeParentSession(summary) : null;
|
||||
}
|
||||
// No tab to fly into → fall back to a plain close so the window isn't orphaned.
|
||||
if (!parentSessionId) {
|
||||
this.closeUltracodeWindow(runId, true);
|
||||
return;
|
||||
}
|
||||
|
||||
// Cancel any pending finish auto-close — the badge owns the run's lifecycle now.
|
||||
const pending = this.ultracodeWindowCloseTimers.get(runId);
|
||||
if (pending) {
|
||||
clearTimeout(pending);
|
||||
this.ultracodeWindowCloseTimers.delete(runId);
|
||||
}
|
||||
|
||||
if (!this.minimizedUltracodeRuns.has(parentSessionId)) this.minimizedUltracodeRuns.set(parentSessionId, new Set());
|
||||
this.minimizedUltracodeRuns.get(parentSessionId).add(runId);
|
||||
|
||||
const element = data.element;
|
||||
const dragListeners = data.dragListeners;
|
||||
this._animateUltracodeWindowToTab(element, parentSessionId, () => {
|
||||
this._teardownUltracodeDrag(dragListeners);
|
||||
if (element) element.remove();
|
||||
this.ultracodeWindows.delete(runId);
|
||||
// Full rebuild so the tab badge renders (the incremental path only knows subagent badges).
|
||||
this._fullRenderSessionTabs();
|
||||
this.updateConnectionLines();
|
||||
});
|
||||
},
|
||||
|
||||
/** Genie the window toward the center of its tab, then invoke `done` to tear it down. */
|
||||
_animateUltracodeWindowToTab(element, sessionId, done) {
|
||||
const tab = sessionId ? document.querySelector(`.session-tab[data-id="${sessionId}"]`) : null;
|
||||
if (!tab || !element) {
|
||||
done();
|
||||
return;
|
||||
}
|
||||
const w = element.getBoundingClientRect();
|
||||
const t = tab.getBoundingClientRect();
|
||||
const dx = t.left + t.width / 2 - (w.left + w.width / 2);
|
||||
const dy = t.top + t.height / 2 - (w.top + w.height / 2);
|
||||
element.style.transformOrigin = 'center center';
|
||||
element.style.transition = 'transform 0.26s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.26s ease';
|
||||
element.style.pointerEvents = 'none';
|
||||
requestAnimationFrame(() => {
|
||||
element.style.transform = `translate(${dx}px, ${dy}px) scale(0.06)`;
|
||||
element.style.opacity = '0';
|
||||
});
|
||||
let finished = false;
|
||||
const finish = () => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
done();
|
||||
};
|
||||
element.addEventListener('transitionend', finish, { once: true });
|
||||
setTimeout(finish, 320); // fallback in case transitionend doesn't fire
|
||||
},
|
||||
|
||||
/** Tab badge (with restore/dismiss dropdown) for runs minimized to this session's tab. */
|
||||
renderUltracodeTabBadge(sessionId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
const runSet = this.minimizedUltracodeRuns.get(sessionId);
|
||||
const agentMap = this.minimizedUltracodeAgents.get(sessionId);
|
||||
const total = (runSet ? runSet.size : 0) + (agentMap ? agentMap.size : 0);
|
||||
if (total === 0) return '';
|
||||
|
||||
const trunc = (s) => (s.length > 25 ? s.slice(0, 25) + '…' : s);
|
||||
const items = [];
|
||||
// Minimized run windows (🧬) first…
|
||||
if (runSet) {
|
||||
for (const runId of runSet) {
|
||||
const run = this.workflowRuns && this.workflowRuns.get(runId);
|
||||
const name = run ? run.workflowName || run.summary || runId : runId;
|
||||
const statusCls = this._workflowStatusClass(run ? String(run.status || '') : '');
|
||||
items.push(
|
||||
`<div class="subagent-dropdown-item" onclick="event.stopPropagation(); app.restoreUltracodeRunFromTab('${escapeHtml(runId)}','${escapeHtml(sessionId)}')" title="Click to restore run">` +
|
||||
`<span class="subagent-dropdown-status ${statusCls}"></span>` +
|
||||
`<span class="ultracode-dd-icon">🧬</span>` +
|
||||
`<span class="subagent-dropdown-name">${escapeHtml(trunc(name))}</span>` +
|
||||
`<span class="subagent-dropdown-close" onclick="event.stopPropagation(); app.dismissMinimizedUltracodeRun('${escapeHtml(runId)}','${escapeHtml(sessionId)}')" title="Dismiss">×</span>` +
|
||||
`</div>`
|
||||
);
|
||||
}
|
||||
}
|
||||
// …then minimized agent transcripts (📄).
|
||||
if (agentMap) {
|
||||
for (const [agentId, entry] of agentMap) {
|
||||
const name = (entry && entry.label) || agentId;
|
||||
items.push(
|
||||
`<div class="subagent-dropdown-item" onclick="event.stopPropagation(); app.restoreUltracodeAgentFromTab('${escapeHtml(agentId)}','${escapeHtml(sessionId)}')" title="Click to restore transcript">` +
|
||||
`<span class="subagent-dropdown-status"></span>` +
|
||||
`<span class="ultracode-dd-icon">📄</span>` +
|
||||
`<span class="subagent-dropdown-name">${escapeHtml(trunc(name))}</span>` +
|
||||
`<span class="subagent-dropdown-close" onclick="event.stopPropagation(); app.dismissMinimizedUltracodeAgent('${escapeHtml(agentId)}','${escapeHtml(sessionId)}')" title="Dismiss">×</span>` +
|
||||
`</div>`
|
||||
);
|
||||
}
|
||||
}
|
||||
const label = total === 1 ? 'ULTRA' : `ULTRA (${total})`;
|
||||
return (
|
||||
`<span class="tab-ultracode-badge" onmouseenter="app.showSubagentDropdown(this)" onmouseleave="app.scheduleHideSubagentDropdown(this)" onclick="event.stopPropagation(); app.pinSubagentDropdown(this);">` +
|
||||
`<span class="subagent-label">${label}</span>` +
|
||||
`<div class="subagent-dropdown" onmouseenter="app.cancelHideSubagentDropdown()" onmouseleave="app.scheduleHideSubagentDropdown(this.parentElement)">${items.join('')}</div>` +
|
||||
`</span>`
|
||||
);
|
||||
},
|
||||
|
||||
/** Restore a minimized run from its tab badge: re-open the floating window. */
|
||||
restoreUltracodeRunFromTab(runId, sessionId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
this._removeMinimizedUltracodeRun(runId, sessionId);
|
||||
this._fullRenderSessionTabs();
|
||||
this.openUltracodeWindowForRun(runId);
|
||||
},
|
||||
|
||||
/** Dismiss a minimized run from its tab badge (don't re-pop it). */
|
||||
dismissMinimizedUltracodeRun(runId, sessionId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
this._removeMinimizedUltracodeRun(runId, sessionId);
|
||||
this.ultracodeWindowsClosed.add(runId);
|
||||
this._fullRenderSessionTabs();
|
||||
this.updateConnectionLines();
|
||||
},
|
||||
|
||||
// ── Minimize an agent transcript window into its tab (same idiom as run windows) ──
|
||||
|
||||
/** Is this agent transcript currently minimized to a tab? */
|
||||
_isUltracodeAgentMinimized(agentId) {
|
||||
if (!this.minimizedUltracodeAgents) return false;
|
||||
for (const map of this.minimizedUltracodeAgents.values()) {
|
||||
if (map.has(agentId)) return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
/** Look up a minimized agent's {runId,label} entry (across sessions). */
|
||||
_getMinimizedUltracodeAgent(agentId) {
|
||||
if (!this.minimizedUltracodeAgents) return null;
|
||||
for (const map of this.minimizedUltracodeAgents.values()) {
|
||||
if (map.has(agentId)) return map.get(agentId);
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
||||
/** Drop an agent from minimized tracking (all sessions, or a specific one). */
|
||||
_removeMinimizedUltracodeAgent(agentId, sessionId) {
|
||||
if (!this.minimizedUltracodeAgents) return;
|
||||
if (sessionId) {
|
||||
const map = this.minimizedUltracodeAgents.get(sessionId);
|
||||
if (map) {
|
||||
map.delete(agentId);
|
||||
if (!map.size) this.minimizedUltracodeAgents.delete(sessionId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (const [sid, map] of this.minimizedUltracodeAgents) {
|
||||
if (map.delete(agentId) && !map.size) this.minimizedUltracodeAgents.delete(sid);
|
||||
}
|
||||
},
|
||||
|
||||
/** Minimize an agent transcript window into the run's originating session tab. */
|
||||
minimizeUltracodeAgentWindowToTab(agentId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
const info = this.ultracodeAgentWindows.get(agentId);
|
||||
if (!info) return;
|
||||
const runId = info.runId;
|
||||
const summary = runId && this.workflowRuns ? this.workflowRuns.get(runId) : null;
|
||||
let parentSessionId = summary ? this._resolveUltracodeParentSession(summary) : null;
|
||||
if (!parentSessionId && this.activeSessionId && this.sessions && this.sessions.has(this.activeSessionId)) {
|
||||
parentSessionId = this.activeSessionId;
|
||||
}
|
||||
// No tab to fly into → plain close rather than orphan it.
|
||||
if (!parentSessionId) {
|
||||
this.closeUltracodeAgentWindow(agentId);
|
||||
return;
|
||||
}
|
||||
const labelEl = info.element.querySelector('.uw-name');
|
||||
const label = labelEl ? labelEl.textContent : agentId;
|
||||
if (!this.minimizedUltracodeAgents.has(parentSessionId))
|
||||
this.minimizedUltracodeAgents.set(parentSessionId, new Map());
|
||||
this.minimizedUltracodeAgents.get(parentSessionId).set(agentId, { runId, label });
|
||||
|
||||
const element = info.element;
|
||||
const dragListeners = info.dragListeners;
|
||||
this._animateUltracodeWindowToTab(element, parentSessionId, () => {
|
||||
this._teardownUltracodeDrag(dragListeners);
|
||||
if (element) element.remove();
|
||||
this.ultracodeAgentWindows.delete(agentId);
|
||||
this._fullRenderSessionTabs();
|
||||
this.updateConnectionLines();
|
||||
});
|
||||
},
|
||||
|
||||
/** Restore a minimized agent transcript from its tab badge: re-open its window. */
|
||||
restoreUltracodeAgentFromTab(agentId, sessionId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
const entry = this._getMinimizedUltracodeAgent(agentId);
|
||||
const runId = entry ? entry.runId : null;
|
||||
this._removeMinimizedUltracodeAgent(agentId, sessionId);
|
||||
this._fullRenderSessionTabs();
|
||||
this.openUltracodeAgentWindow(agentId, runId);
|
||||
},
|
||||
|
||||
/** Dismiss a minimized agent transcript from its tab badge. */
|
||||
dismissMinimizedUltracodeAgent(agentId, sessionId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
this._removeMinimizedUltracodeAgent(agentId, sessionId);
|
||||
this._fullRenderSessionTabs();
|
||||
this.updateConnectionLines();
|
||||
},
|
||||
|
||||
@@ -233,19 +520,149 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
// ── Agent-transcript windows ────────────────────────────────────────────────
|
||||
// Clicking an agent card (in a run window OR the dock panel) opens the agent's
|
||||
// live transcript as its OWN in-page floating window, line-tied to its parent run
|
||||
// window (or the run's session tab when that window is closed). Replaces the old
|
||||
// detached `window.open` browser popup so the transcript stays inside the same
|
||||
// draggable, connector-line floating-window system as the run windows.
|
||||
|
||||
/** Open (or focus) the floating transcript window for a workflow agent. */
|
||||
async openUltracodeAgentWindow(agentId, runId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
if (!agentId) return;
|
||||
this._removeMinimizedUltracodeAgent(agentId); // an explicit open overrides a past minimize
|
||||
const existing = this.ultracodeAgentWindows.get(agentId);
|
||||
if (existing && existing.element) {
|
||||
// Already open — bring to front and refresh transcript.
|
||||
existing.element.style.zIndex = ++this.ultracodeWindowZIndex;
|
||||
this.updateConnectionLines();
|
||||
} else if (!this.createUltracodeAgentWindow(agentId, runId)) {
|
||||
return;
|
||||
}
|
||||
// Body shows a loading state until the fetch lands (re-fetch on focus too, so a
|
||||
// still-running agent's transcript grows as you re-click).
|
||||
const data = this._fetchWorkflowAgentTranscript ? await this._fetchWorkflowAgentTranscript(agentId) : null;
|
||||
this.renderUltracodeAgentWindowContent(agentId, data);
|
||||
},
|
||||
|
||||
/** Build and mount the floating agent-transcript window shell near its parent. */
|
||||
createUltracodeAgentWindow(agentId, runId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
if (this.ultracodeAgentWindows.has(agentId)) return this.ultracodeAgentWindows.get(agentId).element;
|
||||
|
||||
const label = this._ultracodeAgentLabel(agentId, runId) || agentId;
|
||||
const win = document.createElement('div');
|
||||
win.className = 'ultracode-window ultracode-agent-window spawning';
|
||||
win.id = `ultracode-agent-window-${agentId}`;
|
||||
win.style.zIndex = ++this.ultracodeWindowZIndex;
|
||||
win.innerHTML = `
|
||||
<div class="ultracode-window-header">
|
||||
<div class="ultracode-window-title" title="${escapeHtml(label)} — transcript">
|
||||
<span class="icon">📄</span>
|
||||
<span class="uw-name">${escapeHtml(label)}</span>
|
||||
</div>
|
||||
<div class="ultracode-window-actions">
|
||||
<button class="uw-min" type="button" title="Minimize to tab">─</button>
|
||||
<button class="uw-close" type="button" title="Close">×</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ultracode-window-body">
|
||||
<div class="subagent-empty">Loading transcript…</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Position: offset from the parent run window if it's open, else cascade.
|
||||
const parentWin = runId ? this.ultracodeWindows.get(runId) : null;
|
||||
if (parentWin && parentWin.element) {
|
||||
const r = parentWin.element.getBoundingClientRect();
|
||||
win.style.left = `${Math.max(8, Math.min(r.left + 40, window.innerWidth - 472))}px`;
|
||||
win.style.top = `${Math.max(8, Math.min(r.top + 40, window.innerHeight - 160))}px`;
|
||||
} else {
|
||||
const n = this.ultracodeAgentWindows.size;
|
||||
win.style.left = `${Math.min(140 + n * 28, Math.max(8, window.innerWidth - 472))}px`;
|
||||
win.style.top = `${110 + n * 28}px`;
|
||||
}
|
||||
|
||||
document.body.appendChild(win);
|
||||
requestAnimationFrame(() => win.classList.remove('spawning'));
|
||||
|
||||
const header = win.querySelector('.ultracode-window-header');
|
||||
const dragListeners = this.makeWindowDraggable(win, header);
|
||||
win.querySelector('.uw-min').addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
this.minimizeUltracodeAgentWindowToTab(agentId);
|
||||
});
|
||||
win.querySelector('.uw-close').addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
this.closeUltracodeAgentWindow(agentId);
|
||||
});
|
||||
|
||||
this.ultracodeAgentWindows.set(agentId, { element: win, runId, dragListeners });
|
||||
this.updateConnectionLines();
|
||||
return win;
|
||||
},
|
||||
|
||||
/** Resolve a human label for an agent from the run's fetched detail.agents[]. */
|
||||
_ultracodeAgentLabel(agentId, runId) {
|
||||
const detail = this.workflowRunDetails && runId ? this.workflowRunDetails.get(runId) : null;
|
||||
const agents = detail && Array.isArray(detail.agents) ? detail.agents : null;
|
||||
if (agents) {
|
||||
const found = agents.find((a) => a.agentId === agentId);
|
||||
if (found && found.label) return found.label;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
||||
/** Fill an agent window's body with the fetched transcript (or a friendly empty state). */
|
||||
renderUltracodeAgentWindowContent(agentId, data) {
|
||||
const info = this.ultracodeAgentWindows.get(agentId);
|
||||
if (!info || !info.element) return;
|
||||
const body = info.element.querySelector('.ultracode-window-body');
|
||||
if (!body) return;
|
||||
if (!data || !data.formatted || !data.entryCount) {
|
||||
body.innerHTML =
|
||||
'<div class="subagent-empty">No transcript available yet — the agent may be queued, aged out of tracking, or subagent tracking is disabled.</div>';
|
||||
return;
|
||||
}
|
||||
const text = escapeHtml(data.formatted.join('\n'));
|
||||
body.innerHTML = `<div class="uw-summary">${data.entryCount} entries</div><pre class="uw-transcript">${text}</pre>`;
|
||||
},
|
||||
|
||||
/** Close one floating agent-transcript window. */
|
||||
closeUltracodeAgentWindow(agentId) {
|
||||
this._ensureUltracodeWindowState();
|
||||
const info = this.ultracodeAgentWindows.get(agentId);
|
||||
if (!info) return;
|
||||
this._teardownUltracodeDrag(info.dragListeners);
|
||||
if (info.element) info.element.remove();
|
||||
this.ultracodeAgentWindows.delete(agentId);
|
||||
this.updateConnectionLines();
|
||||
},
|
||||
|
||||
/** Tear down every floating window (called on SSE reconnect; keeps user dismissals). */
|
||||
removeAllUltracodeWindows() {
|
||||
this._ensureUltracodeWindowState();
|
||||
const had = this.ultracodeWindows.size > 0;
|
||||
const hadMinimized = this.minimizedUltracodeRuns.size > 0 || this.minimizedUltracodeAgents.size > 0;
|
||||
const had = this.ultracodeWindows.size > 0 || this.ultracodeAgentWindows.size > 0;
|
||||
for (const [, data] of this.ultracodeWindows) {
|
||||
this._teardownUltracodeDrag(data.dragListeners);
|
||||
if (data.element) data.element.remove();
|
||||
}
|
||||
this.ultracodeWindows.clear();
|
||||
for (const [, info] of this.ultracodeAgentWindows) {
|
||||
this._teardownUltracodeDrag(info.dragListeners);
|
||||
if (info.element) info.element.remove();
|
||||
}
|
||||
this.ultracodeAgentWindows.clear();
|
||||
for (const t of this.ultracodeWindowCloseTimers.values()) clearTimeout(t);
|
||||
this.ultracodeWindowCloseTimers.clear();
|
||||
this.minimizedUltracodeRuns.clear();
|
||||
this.minimizedUltracodeAgents.clear();
|
||||
// Redraw so the now-orphaned connector lines are cleared from the shared SVG.
|
||||
if (had) this.updateConnectionLines();
|
||||
// Drop any now-stale tab badges.
|
||||
if (hadMinimized) this.renderSessionTabs();
|
||||
},
|
||||
|
||||
/** When the feature is toggled on, pop windows for any currently-active runs. */
|
||||
@@ -328,7 +745,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
const header =
|
||||
`<div class="ultracode-phase-header"><span>${escapeHtml(title)}</span>` +
|
||||
`<span class="ultracode-phase-sub">${this._fmtNum(tok)} tok · ${tools} tools</span></div>`;
|
||||
return header + group.map((a) => this._workflowAgentCardHtml(a)).join('');
|
||||
return header + group.map((a) => this._workflowAgentCardHtml(a, run.runId)).join('');
|
||||
})
|
||||
.join('');
|
||||
return head + grid;
|
||||
@@ -381,4 +798,51 @@ Object.assign(CodemanApp.prototype, {
|
||||
svg.appendChild(line);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Append agent-window → parent connector lines into the shared SVG. Parent is the
|
||||
* agent's run floating window when open, else the run's session tab. Called right
|
||||
* after `_appendUltracodeConnectionLines` so it shares the same batched pass + the
|
||||
* tab-rect cache.
|
||||
*/
|
||||
_appendUltracodeAgentConnectionLines(svg, rects) {
|
||||
this._ensureUltracodeWindowState();
|
||||
if (!svg || !this.ultracodeAgentWindows.size) return;
|
||||
if (!rects) rects = new Map();
|
||||
|
||||
for (const [agentId, info] of this.ultracodeAgentWindows) {
|
||||
if (!info.element) continue;
|
||||
const winRect = info.element.getBoundingClientRect();
|
||||
// Anchor: parent run window bottom-center if open, else the run's tab.
|
||||
let px, py;
|
||||
const runWin = info.runId ? this.ultracodeWindows.get(info.runId) : null;
|
||||
if (runWin && runWin.element) {
|
||||
const pr = runWin.element.getBoundingClientRect();
|
||||
px = pr.left + pr.width / 2;
|
||||
py = pr.bottom;
|
||||
} else {
|
||||
const summary = info.runId && this.workflowRuns ? this.workflowRuns.get(info.runId) : null;
|
||||
const parentSessionId = summary ? this._resolveUltracodeParentSession(summary) : null;
|
||||
if (!parentSessionId) continue;
|
||||
const tabKey = 'tab:' + parentSessionId;
|
||||
if (!rects.has(tabKey)) {
|
||||
const tab = document.querySelector(`.session-tab[data-id="${parentSessionId}"]`);
|
||||
if (tab) rects.set(tabKey, tab.getBoundingClientRect());
|
||||
}
|
||||
const tabRect = rects.get(tabKey);
|
||||
if (!tabRect) continue;
|
||||
px = tabRect.left + tabRect.width / 2;
|
||||
py = tabRect.bottom;
|
||||
}
|
||||
const x2 = winRect.left + winRect.width / 2;
|
||||
const y2 = winRect.top;
|
||||
const midY = (py + y2) / 2;
|
||||
const path = `M ${px} ${py} C ${px} ${midY}, ${x2} ${midY}, ${x2} ${y2}`;
|
||||
const line = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
||||
line.setAttribute('d', path);
|
||||
line.setAttribute('class', 'connection-line ultracode-connection ultracode-agent-connection');
|
||||
line.setAttribute('data-agent-id', agentId);
|
||||
svg.appendChild(line);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
+380
-49
@@ -53,16 +53,99 @@ const RUN_FILE_PREFIX = 'wf_';
|
||||
const RUN_FILE_SUFFIX = '.json';
|
||||
const LIVE_JOURNAL_FILE = 'journal.jsonl';
|
||||
const LIVE_AGENT_PREFIX = 'agent-';
|
||||
const LIVE_TRANSCRIPT_SUFFIX = '.jsonl';
|
||||
const SCRIPTS_SUBDIR = 'scripts';
|
||||
|
||||
/** Hard caps on the largest per-agent strings so a 28-agent run stays compact. */
|
||||
const PROMPT_PREVIEW_MAX = 200;
|
||||
const RESULT_PREVIEW_MAX = 240;
|
||||
/** Cap a live script read so a runaway/huge embedded script can't blow memory. */
|
||||
const SCRIPT_READ_MAX_BYTES = 512 * 1024;
|
||||
/** LRU cap on cached per-agent transcript stats across all live runs. */
|
||||
const MAX_CACHED_AGENT_STATS = 2000;
|
||||
|
||||
function truncate(value: string | undefined, max: number): string | undefined {
|
||||
if (typeof value !== 'string') return undefined;
|
||||
return value.length > max ? `${value.slice(0, max)}…` : value;
|
||||
}
|
||||
|
||||
/** First text from a transcript message's `content` (string or content-block array). */
|
||||
function extractMessageText(content: unknown): string | undefined {
|
||||
if (typeof content === 'string') return content.trim() || undefined;
|
||||
if (Array.isArray(content)) {
|
||||
for (const block of content) {
|
||||
if (block && typeof block === 'object' && (block as { type?: string }).type === 'text') {
|
||||
const t = (block as { text?: string }).text;
|
||||
if (typeof t === 'string' && t.trim()) return t.trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Isolate the `meta = { … }` object literal from a workflow script so that later
|
||||
* declarations (e.g. JSON-Schema objects with their own `description:`/`title:`
|
||||
* fields, or prose containing `phases: [`) can't be mistaken for meta. Brace-matches
|
||||
* naively — a `{`/`}` inside a string value can still confuse it, in which case we
|
||||
* return undefined and the caller falls back to scanning the whole body. Best-effort.
|
||||
*/
|
||||
function extractMetaBlock(body: string): string | undefined {
|
||||
const m = /(?:^|[^A-Za-z0-9_])(?:export\s+const|const|let|var)\s+meta\s*=\s*\{/.exec(body);
|
||||
if (!m) return undefined;
|
||||
const open = body.indexOf('{', m.index);
|
||||
if (open < 0) return undefined;
|
||||
let depth = 0;
|
||||
for (let i = open; i < body.length; i++) {
|
||||
if (body[i] === '{') depth++;
|
||||
else if (body[i] === '}' && --depth === 0) return body.slice(open, i + 1);
|
||||
}
|
||||
return undefined; // unterminated (truncated script) — caller falls back to whole body
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort extraction of a single/double-quoted `key: '...'` value from a workflow
|
||||
* `meta` literal (the script is JS we must not eval). The key is anchored to a key
|
||||
* position (`{`/`,`/whitespace before it) so e.g. `description` can't match the tail
|
||||
* of `..._description`; pass the scoped meta block so later same-named schema fields
|
||||
* can't win. Returns undefined on no match.
|
||||
*/
|
||||
function extractMetaString(body: string, key: string): string | undefined {
|
||||
const re = new RegExp(`(?:^|[{,\\s])${key}\\s*:\\s*(['"])((?:\\\\.|(?!\\1).)*)\\1`);
|
||||
const m = re.exec(body);
|
||||
return m ? m[2].replace(/\\(['"\\`])/g, '$1') : undefined;
|
||||
}
|
||||
|
||||
/** Best-effort `meta.phases: [{title, detail}, …]` extraction (pass the scoped meta block). */
|
||||
function extractMetaPhases(body: string): WorkflowRunPhase[] {
|
||||
const keyMatch = /(?:^|[^A-Za-z0-9_])phases\s*:\s*\[/.exec(body);
|
||||
if (!keyMatch) return [];
|
||||
const open = body.indexOf('[', keyMatch.index);
|
||||
if (open < 0) return [];
|
||||
// Brace-match to the array's closing ] so nested arrays don't end it early.
|
||||
let depth = 0;
|
||||
let end = -1;
|
||||
for (let i = open; i < body.length; i++) {
|
||||
if (body[i] === '[') depth++;
|
||||
else if (body[i] === ']' && --depth === 0) {
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (end < 0) return [];
|
||||
const block = body.slice(open, end + 1);
|
||||
const phases: WorkflowRunPhase[] = [];
|
||||
const re = /title\s*:\s*(['"])((?:\\.|(?!\1).)*)\1(?:\s*,\s*detail\s*:\s*(['"])((?:\\.|(?!\3).)*)\3)?/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(block)) !== null && phases.length < 20) {
|
||||
phases.push({
|
||||
title: m[2].replace(/\\(['"\\`])/g, '$1'),
|
||||
detail: (m[4] || '').replace(/\\(['"\\`])/g, '$1'),
|
||||
});
|
||||
}
|
||||
return phases;
|
||||
}
|
||||
|
||||
/** Drop the heavy `agents[]` for list/snapshot use. */
|
||||
export function summarizeRun(info: WorkflowRunInfo): WorkflowRunSummary {
|
||||
const { agents: _agents, ...summary } = info;
|
||||
@@ -85,6 +168,34 @@ interface DiscoveredLiveRun {
|
||||
runId: string;
|
||||
}
|
||||
|
||||
/** Per-agent stats parsed from one `agent-<id>.jsonl` transcript (mtime-cached). */
|
||||
interface AgentTranscriptStats {
|
||||
/** Tokens for the agent's LAST usage-bearing message (in+out+cache) ≈ the completion-JSON `tokens`. */
|
||||
tokens: number;
|
||||
/** Count of `tool_use` blocks across the transcript (matches the completion-JSON `toolCalls`). */
|
||||
toolCalls: number;
|
||||
/** Most-recent model id seen. */
|
||||
model: string;
|
||||
/** Name of the most-recent `tool_use` block. */
|
||||
lastToolName?: string;
|
||||
/** First user-message text, truncated — a hint of what the agent was asked. */
|
||||
promptPreview?: string;
|
||||
}
|
||||
|
||||
/** Workflow meta derived live from `workflows/scripts/<name>-<runId>.js`. */
|
||||
interface LiveWorkflowMeta {
|
||||
workflowName?: string;
|
||||
summary?: string;
|
||||
phases: WorkflowRunPhase[];
|
||||
}
|
||||
|
||||
/** A live agent file on disk (transcript and/or meta), keyed by its `<id>` stem. */
|
||||
interface LiveAgentFile {
|
||||
agentId: string;
|
||||
transcriptPath?: string;
|
||||
transcriptMtime?: number;
|
||||
}
|
||||
|
||||
/** A `workflowProgress[]` entry as it appears on disk (loosely typed for defensive parsing). */
|
||||
interface RawProgressEntry {
|
||||
type?: string;
|
||||
@@ -123,6 +234,17 @@ export class WorkflowRunWatcher extends EventEmitter {
|
||||
private liveDirMtimes = new Map<string, number>();
|
||||
/** runId -> absolute live transcript-dir path (for mtime cleanup on removal). */
|
||||
private runIdToLiveDir = new Map<string, string>();
|
||||
/** transcript abs path -> { mtimeMs, stats }; re-parse a transcript only when its mtime moves. */
|
||||
private agentStatCache = new LRUMap<string, { mtimeMs: number; stats: AgentTranscriptStats }>({
|
||||
maxSize: MAX_CACHED_AGENT_STATS,
|
||||
});
|
||||
/** runId -> derived script meta (immutable per run; re-derived only until a name is found). */
|
||||
private liveMetaCache = new Map<string, LiveWorkflowMeta>();
|
||||
/** journal abs path -> { mtimeMs, parsed }; re-parse the journal only when it grows. */
|
||||
private journalCache = new Map<
|
||||
string,
|
||||
{ mtimeMs: number; parsed: { startedOrder: string[]; doneIds: Set<string> } }
|
||||
>();
|
||||
/** watched-dir absolute path -> chokidar watcher (workflows/ + subagents/workflows/). */
|
||||
private dirWatchers = new Map<string, ChokidarWatcher>();
|
||||
|
||||
@@ -160,6 +282,9 @@ export class WorkflowRunWatcher extends EventEmitter {
|
||||
this.runIdToPath.clear();
|
||||
this.liveDirMtimes.clear();
|
||||
this.runIdToLiveDir.clear();
|
||||
this.agentStatCache.clear();
|
||||
this.liveMetaCache.clear();
|
||||
this.journalCache.clear();
|
||||
}
|
||||
|
||||
/** All cached runs (no recency filter), most-recently-active first. */
|
||||
@@ -243,7 +368,18 @@ export class WorkflowRunWatcher extends EventEmitter {
|
||||
if (path) this.fileMtimes.delete(path);
|
||||
this.runIdToPath.delete(runId);
|
||||
const liveDir = this.runIdToLiveDir.get(runId);
|
||||
if (liveDir) this.liveDirMtimes.delete(liveDir);
|
||||
if (liveDir) {
|
||||
this.liveDirMtimes.delete(liveDir);
|
||||
// Drop cached transcript stats + journal parse under this run's live dir.
|
||||
const prefix = liveDir.endsWith('/') ? liveDir : liveDir + '/';
|
||||
for (const key of Array.from(this.agentStatCache.keys())) {
|
||||
if (key.startsWith(prefix)) this.agentStatCache.delete(key);
|
||||
}
|
||||
for (const key of Array.from(this.journalCache.keys())) {
|
||||
if (key.startsWith(prefix)) this.journalCache.delete(key);
|
||||
}
|
||||
}
|
||||
this.liveMetaCache.delete(runId);
|
||||
this.runIdToLiveDir.delete(runId);
|
||||
this.emit('run_removed', { runId });
|
||||
}
|
||||
@@ -346,14 +482,58 @@ export class WorkflowRunWatcher extends EventEmitter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-synthesize an in-flight run from its transcript dir when its newest member
|
||||
* mtime moved (skip otherwise so we don't re-emit run_updated on idle polls).
|
||||
* Re-synthesize an in-flight run from its transcript dir. Cheap pass first: stat
|
||||
* the dir members and skip entirely when the newest mtime is unchanged, so an idle
|
||||
* poll never reads a single (large) transcript. Only on a real change do we parse —
|
||||
* and even then per-transcript stats come from an mtime-keyed cache, so only the
|
||||
* transcripts that actually grew are re-read.
|
||||
*/
|
||||
private async maybeParseLive(live: DiscoveredLiveRun): Promise<void> {
|
||||
const info = await this.parseLiveDir(live);
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = await readdir(live.dirPath);
|
||||
} catch {
|
||||
return; // vanished between discover and read
|
||||
}
|
||||
|
||||
// Cheap pass: newest member mtime + the agent-file set (no transcript reads yet).
|
||||
let newestMtime = 0;
|
||||
let journalPath: string | null = null;
|
||||
let journalMtime = 0;
|
||||
const agentFiles = new Map<string, LiveAgentFile>();
|
||||
for (const name of entries) {
|
||||
if (name !== LIVE_JOURNAL_FILE && !name.startsWith(LIVE_AGENT_PREFIX)) continue;
|
||||
const full = join(live.dirPath, name);
|
||||
let m = 0;
|
||||
try {
|
||||
m = (await stat(full)).mtimeMs;
|
||||
} catch {
|
||||
continue; // entry vanished — ignore
|
||||
}
|
||||
if (m > newestMtime) newestMtime = m;
|
||||
if (name === LIVE_JOURNAL_FILE) {
|
||||
journalPath = full;
|
||||
journalMtime = m;
|
||||
continue;
|
||||
}
|
||||
// agent-<stem>.jsonl (transcript) or agent-<stem>.meta.json (queued-slot marker)
|
||||
const stem = name.slice(LIVE_AGENT_PREFIX.length).replace(/\.(meta\.json|jsonl)$/, '');
|
||||
if (!stem) continue;
|
||||
const slot = agentFiles.get(stem) || { agentId: stem };
|
||||
if (name.endsWith(LIVE_TRANSCRIPT_SUFFIX)) {
|
||||
slot.transcriptPath = full;
|
||||
slot.transcriptMtime = m;
|
||||
}
|
||||
agentFiles.set(stem, slot);
|
||||
}
|
||||
if (agentFiles.size === 0) return; // nothing to show yet
|
||||
|
||||
// Skip the expensive parse when nothing changed since the last synthesis.
|
||||
if (this.liveDirMtimes.get(live.dirPath) === newestMtime) return;
|
||||
this.liveDirMtimes.set(live.dirPath, newestMtime);
|
||||
|
||||
const info = await this.parseLiveDir(live, agentFiles, journalPath, journalMtime, newestMtime);
|
||||
if (!info) return;
|
||||
if (this.liveDirMtimes.get(live.dirPath) === info.lastActivityAt) return;
|
||||
this.liveDirMtimes.set(live.dirPath, info.lastActivityAt);
|
||||
|
||||
const existed = this.runs.has(info.runId);
|
||||
this.runs.set(info.runId, info);
|
||||
@@ -362,56 +542,87 @@ export class WorkflowRunWatcher extends EventEmitter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a minimal ACTIVE WorkflowRunInfo from `subagents/workflows/wf_<id>/`.
|
||||
* The transcript tree carries no phases/tokens — those arrive with the
|
||||
* completion wf_*.json — so we expose: the agent slots (keyed by agentId, so the
|
||||
* card→transcript click still works), each marked done/running from journal
|
||||
* `result` lines, and lastActivityAt from the newest agent/journal mtime.
|
||||
* Build an ACTIVE WorkflowRunInfo from a live transcript dir, ENRICHED so the
|
||||
* floating window / panel show real data mid-run rather than empty slots:
|
||||
* - per-agent tokens + tool-calls + model + last tool, parsed from each
|
||||
* `agent-<id>.jsonl` (mtime-cached — only changed transcripts are re-read);
|
||||
* - per-agent state: 'done' once the journal logs a `result` (→ green badge),
|
||||
* 'progress' once it logs `started` or a transcript exists (→ yellow), else 'start';
|
||||
* - run name/summary/phases from the live `workflows/scripts/<name>-<runId>.js`
|
||||
* (the completion wf_<id>.json, which carries these, only lands at the end);
|
||||
* - run totals = sums of the per-agent stats.
|
||||
*/
|
||||
private async parseLiveDir(live: DiscoveredLiveRun): Promise<WorkflowRunInfo | null> {
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = await readdir(live.dirPath);
|
||||
} catch {
|
||||
return null; // vanished between discover and read
|
||||
}
|
||||
private async parseLiveDir(
|
||||
live: DiscoveredLiveRun,
|
||||
agentFiles: Map<string, LiveAgentFile>,
|
||||
journalPath: string | null,
|
||||
journalMtime: number,
|
||||
newestMtime: number
|
||||
): Promise<WorkflowRunInfo | null> {
|
||||
const { startedOrder, doneIds } = journalPath
|
||||
? await this.readJournal(journalPath, journalMtime)
|
||||
: { startedOrder: [] as string[], doneIds: new Set<string>() };
|
||||
const startIndex = new Map<string, number>();
|
||||
startedOrder.forEach((id, i) => startIndex.set(id, i));
|
||||
|
||||
const agentIds = new Set<string>();
|
||||
let newestMtime = 0;
|
||||
for (const name of entries) {
|
||||
if (name.startsWith(LIVE_AGENT_PREFIX)) {
|
||||
const stem = name.slice(LIVE_AGENT_PREFIX.length).replace(/\.(meta\.json|jsonl)$/, '');
|
||||
if (stem) agentIds.add(stem);
|
||||
}
|
||||
if (name === LIVE_JOURNAL_FILE || name.startsWith(LIVE_AGENT_PREFIX)) {
|
||||
try {
|
||||
const m = (await stat(join(live.dirPath, name))).mtimeMs;
|
||||
if (m > newestMtime) newestMtime = m;
|
||||
} catch {
|
||||
// entry vanished — ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
if (agentIds.size === 0) return null; // nothing to show yet
|
||||
// Order agents by journal launch order; not-yet-started ones trail (sorted by id).
|
||||
const ids = Array.from(agentFiles.keys()).sort((a, b) => {
|
||||
const ia = startIndex.has(a) ? (startIndex.get(a) as number) : Number.MAX_SAFE_INTEGER;
|
||||
const ib = startIndex.has(b) ? (startIndex.get(b) as number) : Number.MAX_SAFE_INTEGER;
|
||||
if (ia !== ib) return ia - ib;
|
||||
return a < b ? -1 : a > b ? 1 : 0;
|
||||
});
|
||||
|
||||
const doneIds = await this.readJournalDoneAgents(join(live.dirPath, LIVE_JOURNAL_FILE));
|
||||
const agents: WorkflowAgentInfo[] = Array.from(agentIds)
|
||||
.sort()
|
||||
.map((id, i) => ({
|
||||
let totalTokens = 0;
|
||||
let totalToolCalls = 0;
|
||||
let defaultModel = '';
|
||||
const agents: WorkflowAgentInfo[] = [];
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
const id = ids[i];
|
||||
const file = agentFiles.get(id) as LiveAgentFile;
|
||||
const stats = file.transcriptPath
|
||||
? await this.agentTranscriptStats(file.transcriptPath, file.transcriptMtime || 0)
|
||||
: null;
|
||||
const state = doneIds.has(id) ? 'done' : startIndex.has(id) || file.transcriptPath ? 'progress' : 'start';
|
||||
if (stats) {
|
||||
totalTokens += stats.tokens;
|
||||
totalToolCalls += stats.toolCalls;
|
||||
if (stats.model && !defaultModel) defaultModel = stats.model;
|
||||
}
|
||||
agents.push({
|
||||
index: i + 1,
|
||||
label: `agent ${i + 1}`,
|
||||
phaseIndex: 1,
|
||||
phaseTitle: '',
|
||||
model: '',
|
||||
state: doneIds.has(id) ? 'done' : 'progress',
|
||||
model: stats?.model || '',
|
||||
state,
|
||||
agentId: id,
|
||||
}));
|
||||
tokens: stats ? stats.tokens : undefined,
|
||||
toolCalls: stats ? stats.toolCalls : undefined,
|
||||
lastToolName: stats?.lastToolName,
|
||||
promptPreview: stats?.promptPreview,
|
||||
});
|
||||
}
|
||||
|
||||
// Script meta is immutable for the life of a run, so derive it at most once.
|
||||
// Re-derive only while we still lack a name (the script can land a poll or two
|
||||
// after the first transcripts, which seed the run before the script exists).
|
||||
let meta = this.liveMetaCache.get(live.runId);
|
||||
if (!meta || !meta.workflowName) {
|
||||
meta = await this.deriveLiveWorkflowMeta(live);
|
||||
this.liveMetaCache.set(live.runId, meta);
|
||||
}
|
||||
|
||||
return {
|
||||
runId: live.runId,
|
||||
workflowName: meta.workflowName,
|
||||
summary: meta.summary,
|
||||
status: 'running',
|
||||
agentCount: agents.length,
|
||||
phases: [],
|
||||
totalTokens,
|
||||
totalToolCalls,
|
||||
defaultModel: defaultModel || undefined,
|
||||
phases: meta.phases,
|
||||
agents,
|
||||
sessionUuid: live.sessionUuid,
|
||||
projectHash: live.projectHash,
|
||||
@@ -419,25 +630,145 @@ export class WorkflowRunWatcher extends EventEmitter {
|
||||
};
|
||||
}
|
||||
|
||||
/** Agent ids that already emitted a `result` event in the run journal. */
|
||||
private async readJournalDoneAgents(journalPath: string): Promise<Set<string>> {
|
||||
const done = new Set<string>();
|
||||
/** Parse one agent transcript for token/tool stats; cached on the file's mtime. */
|
||||
private async agentTranscriptStats(path: string, mtimeMs: number): Promise<AgentTranscriptStats | null> {
|
||||
// peek (not get) on the hit-check so a cache HIT doesn't churn the LRU — every
|
||||
// active agent is looked up each poll, and get() would delete+reinsert each time.
|
||||
const cached = this.agentStatCache.peek(path);
|
||||
if (cached && cached.mtimeMs === mtimeMs) return cached.stats;
|
||||
let text: string;
|
||||
try {
|
||||
text = await readFile(path, 'utf-8');
|
||||
} catch {
|
||||
return null; // vanished mid-poll
|
||||
}
|
||||
let tokens = 0;
|
||||
let toolCalls = 0;
|
||||
let model = '';
|
||||
let lastToolName: string | undefined;
|
||||
let promptPreview: string | undefined;
|
||||
for (const line of text.split('\n')) {
|
||||
if (!line) continue;
|
||||
let entry: { type?: string; message?: unknown };
|
||||
try {
|
||||
entry = JSON.parse(line) as { type?: string; message?: unknown };
|
||||
} catch {
|
||||
continue; // tolerate a partially-written trailing line
|
||||
}
|
||||
const msg = entry.message as
|
||||
| {
|
||||
model?: string;
|
||||
usage?: {
|
||||
input_tokens?: number;
|
||||
output_tokens?: number;
|
||||
cache_read_input_tokens?: number;
|
||||
cache_creation_input_tokens?: number;
|
||||
};
|
||||
content?: Array<{ type?: string; name?: string; text?: string }> | string;
|
||||
}
|
||||
| undefined;
|
||||
if (!promptPreview && entry.type === 'user' && msg) {
|
||||
promptPreview = truncate(extractMessageText(msg.content), PROMPT_PREVIEW_MAX);
|
||||
}
|
||||
if (!msg || typeof msg !== 'object') continue;
|
||||
if (typeof msg.model === 'string' && msg.model) model = msg.model;
|
||||
const u = msg.usage;
|
||||
if (u) {
|
||||
const total =
|
||||
(u.input_tokens || 0) +
|
||||
(u.output_tokens || 0) +
|
||||
(u.cache_read_input_tokens || 0) +
|
||||
(u.cache_creation_input_tokens || 0);
|
||||
// Anthropic usage already reflects cumulative context, so the agent's running
|
||||
// token total ≈ its LATEST usage-bearing message — last non-zero wins.
|
||||
if (total > 0) tokens = total;
|
||||
}
|
||||
if (Array.isArray(msg.content)) {
|
||||
for (const block of msg.content) {
|
||||
if (block && block.type === 'tool_use' && typeof block.name === 'string') {
|
||||
toolCalls++;
|
||||
lastToolName = block.name;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const stats: AgentTranscriptStats = { tokens, toolCalls, model, lastToolName, promptPreview };
|
||||
this.agentStatCache.set(path, { mtimeMs, stats });
|
||||
return stats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the run journal: agent ids in `started` order plus the set that already
|
||||
* logged a terminal `result`. (`started` lines appear in launch order.)
|
||||
*/
|
||||
private async readJournal(
|
||||
journalPath: string,
|
||||
mtimeMs: number
|
||||
): Promise<{ startedOrder: string[]; doneIds: Set<string> }> {
|
||||
const cached = this.journalCache.get(journalPath);
|
||||
if (cached && cached.mtimeMs === mtimeMs) return cached.parsed;
|
||||
const startedOrder: string[] = [];
|
||||
const seenStarted = new Set<string>();
|
||||
const doneIds = new Set<string>();
|
||||
let text: string;
|
||||
try {
|
||||
text = await readFile(journalPath, 'utf-8');
|
||||
} catch {
|
||||
return done; // journal not written yet — all agents still in progress
|
||||
return { startedOrder, doneIds }; // journal not written yet
|
||||
}
|
||||
for (const line of text.split('\n')) {
|
||||
if (!line) continue;
|
||||
try {
|
||||
const ev = JSON.parse(line) as { type?: string; agentId?: string };
|
||||
if (ev && ev.type === 'result' && typeof ev.agentId === 'string') done.add(ev.agentId);
|
||||
if (!ev || typeof ev.agentId !== 'string') continue;
|
||||
if (ev.type === 'started' && !seenStarted.has(ev.agentId)) {
|
||||
seenStarted.add(ev.agentId);
|
||||
startedOrder.push(ev.agentId);
|
||||
} else if (ev.type === 'result') {
|
||||
doneIds.add(ev.agentId);
|
||||
}
|
||||
} catch {
|
||||
// tolerate a partially-written trailing line
|
||||
}
|
||||
}
|
||||
return done;
|
||||
const parsed = { startedOrder, doneIds };
|
||||
this.journalCache.set(journalPath, { mtimeMs, parsed });
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive name/summary/phases for a live run from its persisted script file
|
||||
* `…/workflows/scripts/<name>-<runId>.js`. The filename yields a reliable name;
|
||||
* `meta.description`/`meta.phases` are best-effort regex extractions (the script is
|
||||
* JS we must not eval), so any parse miss simply leaves those optional fields absent.
|
||||
*/
|
||||
private async deriveLiveWorkflowMeta(live: DiscoveredLiveRun): Promise<LiveWorkflowMeta> {
|
||||
const empty: LiveWorkflowMeta = { phases: [] };
|
||||
const scriptsDir = join(this.projectsDir, live.projectHash, live.sessionUuid, WORKFLOWS_SUBDIR, SCRIPTS_SUBDIR);
|
||||
let names: string[];
|
||||
try {
|
||||
names = await readdir(scriptsDir);
|
||||
} catch {
|
||||
return empty;
|
||||
}
|
||||
const suffix = `-${live.runId}.js`;
|
||||
const fileName = names.find((n) => n.endsWith(suffix)) || names.find((n) => n.includes(live.runId));
|
||||
if (!fileName) return empty;
|
||||
const nameFromFile = fileName.endsWith(suffix) ? fileName.slice(0, -suffix.length) : fileName.replace(/\.js$/, '');
|
||||
let body = '';
|
||||
try {
|
||||
body = (await readFile(join(scriptsDir, fileName), 'utf-8')).slice(0, SCRIPT_READ_MAX_BYTES);
|
||||
} catch {
|
||||
return { workflowName: nameFromFile || undefined, phases: [] };
|
||||
}
|
||||
// Scope name/summary/phases parsing to the `meta` literal so later script
|
||||
// declarations (schemas, prose) can't be mistaken for it.
|
||||
const metaBlock = extractMetaBlock(body) || body;
|
||||
return {
|
||||
workflowName: nameFromFile || extractMetaString(metaBlock, 'name') || undefined,
|
||||
summary: extractMetaString(metaBlock, 'description') || undefined,
|
||||
phases: extractMetaPhases(metaBlock),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -317,3 +317,99 @@ describe('WorkflowRunWatcher — in-flight (live) runs', () => {
|
||||
expect(watcher.getAllRuns()).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Live ENRICHMENT: while a run is in-flight the watcher now parses each agent
|
||||
* transcript for real tokens/tool-calls/model, maps state→colour from the journal,
|
||||
* and derives the run name/summary/phases from the persisted script — so the
|
||||
* floating window/panel show real data mid-run instead of "0 tok / agent N".
|
||||
*/
|
||||
describe('WorkflowRunWatcher — live enrichment (tokens/state/name)', () => {
|
||||
const RUN = 'wf_enrich01-abc';
|
||||
let projectsDir: string;
|
||||
let watcher: WorkflowRunWatcher;
|
||||
|
||||
beforeEach(async () => {
|
||||
projectsDir = await mkdtemp(join(tmpdir(), 'wfw-enrich-'));
|
||||
const sessionDir = join(projectsDir, PROJECT_HASH, SESSION_UUID);
|
||||
const liveDir = join(sessionDir, 'subagents', 'workflows', RUN);
|
||||
await mkdir(liveDir, { recursive: true });
|
||||
const scriptsDir = join(sessionDir, 'workflows', 'scripts');
|
||||
await mkdir(scriptsDir, { recursive: true });
|
||||
|
||||
// Agent aaa: a user prompt + two assistant turns with usage + two tool_use blocks.
|
||||
await writeFile(
|
||||
join(liveDir, 'agent-aaa.jsonl'),
|
||||
[
|
||||
'{"type":"user","message":{"role":"user","content":"Audit the docs"}}',
|
||||
'{"type":"assistant","message":{"model":"claude-opus-4-8","usage":{"input_tokens":1000,"output_tokens":40},"content":[{"type":"tool_use","name":"Bash"}]}}',
|
||||
'{"type":"assistant","message":{"model":"claude-opus-4-8","usage":{"input_tokens":2000,"cache_read_input_tokens":500,"output_tokens":80},"content":[{"type":"tool_use","name":"Edit"},{"type":"text","text":"done"}]}}',
|
||||
].join('\n') + '\n',
|
||||
'utf-8'
|
||||
);
|
||||
await writeFile(join(liveDir, 'agent-aaa.meta.json'), JSON.stringify({ agentType: 'workflow-subagent' }), 'utf-8');
|
||||
// Agent bbb: started, no result yet, minimal transcript (no usage).
|
||||
await writeFile(join(liveDir, 'agent-bbb.jsonl'), '{"type":"assistant","message":{"content":[]}}\n', 'utf-8');
|
||||
// bbb starts BEFORE aaa, so journal launch order ['bbb','aaa'] differs from the
|
||||
// old alphabetical sort ['aaa','bbb'] — the ordering assertion below is adversarial.
|
||||
await writeFile(
|
||||
join(liveDir, 'journal.jsonl'),
|
||||
'{"type":"started","agentId":"bbb"}\n{"type":"started","agentId":"aaa"}\n{"type":"result","agentId":"aaa","result":{}}\n',
|
||||
'utf-8'
|
||||
);
|
||||
// Persisted script — name from filename, summary/phases from the meta literal.
|
||||
await writeFile(
|
||||
join(scriptsDir, `my-cool-workflow-${RUN}.js`),
|
||||
"export const meta = {\n name: 'my-cool-workflow',\n description: 'Audit and update the docs',\n phases: [ { title: 'Plan', detail: 'plan it' }, { title: 'Do', detail: 'do it' } ],\n}\n",
|
||||
'utf-8'
|
||||
);
|
||||
watcher = new WorkflowRunWatcher(projectsDir);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
watcher.stop();
|
||||
await rm(projectsDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function firstRun(): Promise<WorkflowRunInfo> {
|
||||
return new Promise<WorkflowRunInfo>((resolve, reject) => {
|
||||
const t = setTimeout(() => reject(new Error('timed out')), 5000);
|
||||
watcher.once('run_discovered', (info: WorkflowRunInfo) => {
|
||||
clearTimeout(t);
|
||||
resolve(info);
|
||||
});
|
||||
watcher.start();
|
||||
});
|
||||
}
|
||||
|
||||
it('derives workflowName/summary/phases from the live script file', async () => {
|
||||
const info = await firstRun();
|
||||
expect(info.workflowName).toBe('my-cool-workflow');
|
||||
expect(info.summary).toBe('Audit and update the docs');
|
||||
expect(info.phases.map((p) => p.title)).toEqual(['Plan', 'Do']);
|
||||
});
|
||||
|
||||
it('parses per-agent tokens (last usage-bearing message) + tool-call counts from the transcript', async () => {
|
||||
const info = await firstRun();
|
||||
const aaa = info.agents.find((a) => a.agentId === 'aaa')!;
|
||||
expect(aaa.tokens).toBe(2580); // last turn: 2000 in + 500 cache + 80 out
|
||||
expect(aaa.toolCalls).toBe(2); // Bash + Edit
|
||||
expect(aaa.model).toBe('claude-opus-4-8');
|
||||
expect(aaa.promptPreview).toBe('Audit the docs');
|
||||
});
|
||||
|
||||
it('maps state to done (→green) / progress (→yellow) from the journal', async () => {
|
||||
const info = await firstRun();
|
||||
expect(info.agents.find((a) => a.agentId === 'aaa')!.state).toBe('done');
|
||||
expect(info.agents.find((a) => a.agentId === 'bbb')!.state).toBe('progress');
|
||||
});
|
||||
|
||||
it('orders agents by journal launch order (NOT alphabetical) and sums run-level totals', async () => {
|
||||
const info = await firstRun();
|
||||
// bbb started first in the journal though it sorts after aaa — launch order wins.
|
||||
expect(info.agents.map((a) => a.agentId)).toEqual(['bbb', 'aaa']);
|
||||
expect(info.agents[0].label).toBe('agent 1'); // = bbb, the first-launched
|
||||
expect(info.totalToolCalls).toBe(2);
|
||||
expect(info.totalTokens).toBe(2580);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user