Initial commit

This commit is contained in:
Jordan
2026-04-01 23:16:45 +01:00
commit 91cfdaee72
200 changed files with 25589 additions and 0 deletions

884
dashboard/css/main.css Normal file
View File

@@ -0,0 +1,884 @@
/* ============================================================
Agentic Dashboard — Design System
============================================================ */
/* --- CSS Custom Properties --- */
:root {
/* Backgrounds */
--bg-primary: #0d1117;
--bg-secondary: #161b22;
--bg-surface: #1c2128;
--bg-hover: #252c35;
--bg-input: #0d1117;
/* Text */
--text-primary: #e6edf3;
--text-secondary: #8b949e;
--text-muted: #6e7681;
--text-inverse: #0d1117;
/* Accent */
--accent: #58a6ff;
--accent-hover: #79c0ff;
--accent-muted: #1f3a5f;
/* Status */
--status-success: #3fb950;
--status-warning: #d29922;
--status-error: #f85149;
--status-info: #58a6ff;
/* Agent roles */
--agent-planner: #bc8cff;
--agent-coder: #3fb950;
--agent-collector: #d29922;
--agent-reviewer: #f778ba;
--agent-orchestrator: #58a6ff;
/* Event types */
--event-lifecycle: #58a6ff;
--event-content: #3fb950;
--event-tool: #d29922;
--event-orchestration: #bc8cff;
--event-error: #f85149;
--event-keepalive: #6e7681;
/* Borders */
--border: #30363d;
--border-subtle: #21262d;
/* Misc */
--radius: 8px;
--radius-sm: 4px;
--radius-lg: 12px;
--shadow: 0 2px 8px rgba(0,0,0,.3);
--transition: 150ms ease;
--font-mono: 'SF Mono', 'Fira Code', 'Cascadia Code', monospace;
--font-sans: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Noto Sans', Helvetica, Arial, sans-serif;
/* Layout */
--sidebar-width: 260px;
--inspector-width: 340px;
--toolbar-height: 48px;
}
/* --- Light theme --- */
[data-theme="light"] {
--bg-primary: #ffffff;
--bg-secondary: #f6f8fa;
--bg-surface: #ffffff;
--bg-hover: #f3f4f6;
--bg-input: #f6f8fa;
--text-primary: #1f2328;
--text-secondary: #656d76;
--text-muted: #8b949e;
--text-inverse: #ffffff;
--accent: #0969da;
--accent-hover: #0550ae;
--accent-muted: #ddf4ff;
--border: #d0d7de;
--border-subtle: #e1e4e8;
--shadow: 0 1px 3px rgba(0,0,0,.12);
--bg-surface: #f6f8fa;
}
/* --- Reset & Base --- */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html, body {
height: 100%;
font-family: var(--font-sans);
font-size: 14px;
line-height: 1.5;
color: var(--text-primary);
background: var(--bg-primary);
overflow: hidden;
}
a { color: var(--accent); text-decoration: none; }
a:hover { color: var(--accent-hover); }
/* --- Scrollbar --- */
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }
/* ============================================================
Layout — 3-column grid
============================================================ */
#app {
display: grid;
grid-template-rows: var(--toolbar-height) 1fr;
grid-template-columns: var(--sidebar-width) 1fr var(--inspector-width);
grid-template-areas:
"toolbar toolbar toolbar"
"sidebar main inspector";
height: 100vh;
}
#toolbar { grid-area: toolbar; }
#sidebar { grid-area: sidebar; }
#main { grid-area: main; }
#inspector { grid-area: inspector; }
/* ============================================================
Toolbar
============================================================ */
#toolbar {
display: flex;
align-items: center;
gap: 12px;
padding: 0 16px;
background: var(--bg-secondary);
border-bottom: 1px solid var(--border);
z-index: 10;
}
.toolbar-brand {
font-weight: 600;
font-size: 15px;
color: var(--text-primary);
white-space: nowrap;
}
.toolbar-separator {
width: 1px;
height: 20px;
background: var(--border);
}
.toolbar-session-id {
font-family: var(--font-mono);
font-size: 12px;
color: var(--text-secondary);
cursor: pointer;
padding: 2px 8px;
border-radius: var(--radius-sm);
background: var(--bg-surface);
border: 1px solid var(--border-subtle);
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.toolbar-session-id:hover { background: var(--bg-hover); }
.toolbar-spacer { flex: 1; }
.toolbar-actions {
display: flex;
gap: 6px;
align-items: center;
}
/* ============================================================
Sidebar
============================================================ */
#sidebar {
display: flex;
flex-direction: column;
background: var(--bg-secondary);
border-right: 1px solid var(--border);
overflow: hidden;
}
.sidebar-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 14px;
border-bottom: 1px solid var(--border-subtle);
}
.sidebar-header h3 {
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: .5px;
color: var(--text-secondary);
}
.session-list {
flex: 1;
overflow-y: auto;
padding: 6px;
}
.session-item {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 10px;
border-radius: var(--radius);
cursor: pointer;
transition: background var(--transition);
font-family: var(--font-mono);
font-size: 12px;
color: var(--text-secondary);
}
.session-item:hover { background: var(--bg-hover); }
.session-item.active {
background: var(--accent-muted);
color: var(--accent);
}
.session-item .delete-btn {
margin-left: auto;
opacity: 0;
transition: opacity var(--transition);
background: none;
border: none;
color: var(--text-muted);
cursor: pointer;
font-size: 14px;
padding: 2px 4px;
border-radius: var(--radius-sm);
}
.session-item:hover .delete-btn { opacity: 1; }
.session-item .delete-btn:hover { color: var(--status-error); }
.sidebar-footer {
padding: 10px 14px;
border-top: 1px solid var(--border-subtle);
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
color: var(--text-muted);
}
/* ============================================================
Status Dot
============================================================ */
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
flex-shrink: 0;
}
.status-dot.idle { background: var(--status-success); }
.status-dot.active { background: var(--status-success); }
.status-dot.executing { background: var(--status-warning); animation: pulse 1.5s infinite; }
.status-dot.completed { background: var(--text-muted); }
.status-dot.error { background: var(--status-error); }
.status-dot.connected { background: var(--status-success); }
.status-dot.disconnected { background: var(--status-error); }
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: .4; }
}
/* ============================================================
Main Panel
============================================================ */
#main {
display: flex;
flex-direction: column;
overflow: hidden;
background: var(--bg-primary);
}
/* --- Chat messages --- */
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 20px 24px;
display: flex;
flex-direction: column;
gap: 16px;
}
.chat-empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
flex: 1;
color: var(--text-muted);
gap: 8px;
}
.chat-empty .icon { font-size: 40px; opacity: .3; }
.chat-empty p { font-size: 13px; }
.message {
max-width: 85%;
padding: 12px 16px;
border-radius: var(--radius-lg);
font-size: 14px;
line-height: 1.6;
word-wrap: break-word;
}
.message.user {
align-self: flex-end;
background: var(--accent);
color: var(--text-inverse);
border-bottom-right-radius: 4px;
}
.message.assistant {
align-self: flex-start;
background: var(--bg-surface);
border: 1px solid var(--border-subtle);
border-bottom-left-radius: 4px;
}
.message.assistant .agent-badge {
display: inline-block;
font-size: 10px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: .5px;
padding: 1px 6px;
border-radius: 3px;
margin-bottom: 6px;
}
.message.system {
align-self: center;
background: transparent;
color: var(--text-muted);
font-size: 12px;
padding: 4px 12px;
border: 1px dashed var(--border);
border-radius: var(--radius);
}
/* Markdown inside messages */
.message h1, .message h2, .message h3 {
margin: 8px 0 4px;
font-size: 14px;
font-weight: 700;
}
.message h3 { font-size: 13px; }
.message p { margin: 4px 0; }
.message ul, .message ol { padding-left: 20px; margin: 4px 0; }
.message pre {
background: var(--bg-primary);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 10px 12px;
margin: 8px 0;
overflow-x: auto;
font-family: var(--font-mono);
font-size: 12px;
line-height: 1.5;
}
.message code {
font-family: var(--font-mono);
font-size: 12px;
background: var(--bg-primary);
padding: 1px 5px;
border-radius: 3px;
}
.message pre code { background: none; padding: 0; }
.message strong { font-weight: 700; }
/* --- Execution indicator --- */
.execution-indicator {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
background: var(--bg-surface);
border: 1px solid var(--border-subtle);
border-radius: var(--radius);
font-size: 12px;
color: var(--text-secondary);
align-self: flex-start;
}
.execution-indicator .spinner {
width: 14px;
height: 14px;
border: 2px solid var(--border);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin .8s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
/* --- Chat input --- */
.chat-input-area {
padding: 12px 24px 16px;
border-top: 1px solid var(--border);
background: var(--bg-secondary);
}
.chat-input-wrapper {
display: flex;
gap: 8px;
align-items: flex-end;
}
.chat-input-wrapper textarea {
flex: 1;
resize: none;
border: 1px solid var(--border);
background: var(--bg-input);
color: var(--text-primary);
border-radius: var(--radius);
padding: 10px 14px;
font-family: var(--font-sans);
font-size: 14px;
line-height: 1.5;
min-height: 42px;
max-height: 160px;
outline: none;
transition: border-color var(--transition);
}
.chat-input-wrapper textarea:focus { border-color: var(--accent); }
.chat-input-wrapper textarea::placeholder { color: var(--text-muted); }
.chat-input-wrapper textarea:disabled {
opacity: .5;
cursor: not-allowed;
}
/* ============================================================
Event Log (collapsible, below chat)
============================================================ */
.event-log-panel {
border-top: 1px solid var(--border);
background: var(--bg-secondary);
display: flex;
flex-direction: column;
max-height: 0;
overflow: hidden;
transition: max-height .3s ease;
}
.event-log-panel.open { max-height: 280px; }
.event-log-header {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 16px;
cursor: pointer;
border-bottom: 1px solid var(--border-subtle);
user-select: none;
font-size: 12px;
font-weight: 600;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: .5px;
}
.event-log-header .chevron {
transition: transform var(--transition);
font-size: 10px;
}
.event-log-panel.open .event-log-header .chevron { transform: rotate(180deg); }
.event-log-filters {
display: flex;
gap: 4px;
padding: 6px 12px;
flex-wrap: wrap;
border-bottom: 1px solid var(--border-subtle);
}
.event-filter-btn {
font-size: 10px;
padding: 2px 8px;
border-radius: 10px;
border: 1px solid var(--border);
background: transparent;
color: var(--text-secondary);
cursor: pointer;
transition: all var(--transition);
}
.event-filter-btn.active {
background: var(--accent-muted);
color: var(--accent);
border-color: var(--accent);
}
.event-log-entries {
flex: 1;
overflow-y: auto;
padding: 4px 8px;
font-family: var(--font-mono);
font-size: 11px;
}
.event-entry {
display: flex;
gap: 8px;
padding: 3px 6px;
border-radius: var(--radius-sm);
align-items: flex-start;
}
.event-entry:hover { background: var(--bg-hover); }
.event-time { color: var(--text-muted); white-space: nowrap; flex-shrink: 0; }
.event-type-badge {
font-size: 10px;
padding: 0 6px;
border-radius: 3px;
font-weight: 600;
white-space: nowrap;
flex-shrink: 0;
}
.event-data {
color: var(--text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex: 1;
cursor: pointer;
}
.event-data.expanded {
white-space: pre-wrap;
word-break: break-all;
}
/* Event type colors */
.event-type-badge.lifecycle { background: rgba(88,166,255,.15); color: var(--event-lifecycle); }
.event-type-badge.content { background: rgba(63,185,80,.15); color: var(--event-content); }
.event-type-badge.tool { background: rgba(210,153,34,.15); color: var(--event-tool); }
.event-type-badge.orchestration { background: rgba(188,140,255,.15); color: var(--event-orchestration); }
.event-type-badge.error { background: rgba(248,81,73,.15); color: var(--event-error); }
.event-type-badge.keepalive { background: rgba(110,118,129,.1); color: var(--event-keepalive); }
/* ============================================================
Inspector (right panel)
============================================================ */
#inspector {
display: flex;
flex-direction: column;
background: var(--bg-secondary);
border-left: 1px solid var(--border);
overflow-y: auto;
}
.inspector-empty {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
color: var(--text-muted);
font-size: 13px;
}
.inspector-section {
padding: 12px 14px;
border-bottom: 1px solid var(--border-subtle);
}
.inspector-section-title {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: .5px;
color: var(--text-muted);
margin-bottom: 8px;
}
.inspector-field {
display: flex;
justify-content: space-between;
align-items: center;
padding: 3px 0;
font-size: 13px;
}
.inspector-field .label {
color: var(--text-secondary);
}
.inspector-field .value {
font-family: var(--font-mono);
font-size: 12px;
color: var(--text-primary);
}
/* --- Status badge --- */
.badge {
display: inline-block;
font-size: 11px;
font-weight: 600;
padding: 1px 8px;
border-radius: 10px;
text-transform: capitalize;
}
.badge.idle { background: rgba(63,185,80,.15); color: var(--status-success); }
.badge.active { background: rgba(63,185,80,.15); color: var(--status-success); }
.badge.executing { background: rgba(210,153,34,.15); color: var(--status-warning); }
.badge.completed { background: rgba(110,118,129,.15); color: var(--text-muted); }
.badge.error { background: rgba(248,81,73,.15); color: var(--status-error); }
.badge.pending { background: rgba(110,118,129,.1); color: var(--text-muted); }
.badge.planning { background: rgba(188,140,255,.15); color: var(--agent-planner); }
.badge.reviewing { background: rgba(247,120,186,.15); color: var(--agent-reviewer); }
.badge.failed { background: rgba(248,81,73,.15); color: var(--status-error); }
/* --- Agent timeline --- */
.timeline {
position: relative;
padding-left: 20px;
}
.timeline::before {
content: '';
position: absolute;
left: 7px;
top: 0;
bottom: 0;
width: 2px;
background: var(--border);
}
.timeline-step {
position: relative;
padding: 6px 0 12px;
}
.timeline-step::before {
content: '';
position: absolute;
left: -17px;
top: 10px;
width: 10px;
height: 10px;
border-radius: 50%;
border: 2px solid var(--border);
background: var(--bg-secondary);
}
.timeline-step.active::before {
border-color: var(--status-warning);
background: var(--status-warning);
animation: pulse 1.5s infinite;
}
.timeline-step.completed::before {
border-color: var(--status-success);
background: var(--status-success);
}
.timeline-step.failed::before {
border-color: var(--status-error);
background: var(--status-error);
}
.timeline-step-header {
display: flex;
align-items: center;
gap: 6px;
font-size: 12px;
}
.timeline-step-desc {
font-size: 12px;
color: var(--text-secondary);
margin-top: 2px;
line-height: 1.4;
}
.timeline-tools {
margin-top: 4px;
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.tool-chip {
font-size: 10px;
font-family: var(--font-mono);
padding: 1px 6px;
border-radius: 3px;
background: rgba(210,153,34,.1);
color: var(--event-tool);
border: 1px solid rgba(210,153,34,.2);
}
/* --- Agent role badge --- */
.role-badge {
font-size: 10px;
font-weight: 600;
padding: 1px 6px;
border-radius: 3px;
text-transform: uppercase;
letter-spacing: .3px;
}
.role-badge.planner { background: rgba(188,140,255,.15); color: var(--agent-planner); }
.role-badge.coder { background: rgba(63,185,80,.15); color: var(--agent-coder); }
.role-badge.collector { background: rgba(210,153,34,.15); color: var(--agent-collector); }
.role-badge.reviewer { background: rgba(247,120,186,.15); color: var(--agent-reviewer); }
.role-badge.orchestrator { background: rgba(88,166,255,.15); color: var(--agent-orchestrator); }
/* ============================================================
Buttons
============================================================ */
.btn {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 14px;
border-radius: var(--radius);
border: 1px solid var(--border);
background: var(--bg-surface);
color: var(--text-primary);
font-size: 13px;
font-family: var(--font-sans);
cursor: pointer;
transition: all var(--transition);
white-space: nowrap;
}
.btn:hover { background: var(--bg-hover); }
.btn:disabled { opacity: .4; cursor: not-allowed; }
.btn-primary {
background: var(--accent);
color: var(--text-inverse);
border-color: var(--accent);
}
.btn-primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); }
.btn-danger {
color: var(--status-error);
border-color: transparent;
background: transparent;
}
.btn-danger:hover { background: rgba(248,81,73,.1); }
.btn-sm { padding: 3px 10px; font-size: 12px; }
.btn-icon {
padding: 4px 8px;
border: none;
background: transparent;
color: var(--text-secondary);
cursor: pointer;
border-radius: var(--radius-sm);
font-size: 16px;
}
.btn-icon:hover { background: var(--bg-hover); color: var(--text-primary); }
/* ============================================================
Modal
============================================================ */
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(0,0,0,.6);
display: flex;
align-items: center;
justify-content: center;
z-index: 100;
opacity: 0;
pointer-events: none;
transition: opacity .2s ease;
}
.modal-overlay.open { opacity: 1; pointer-events: auto; }
.modal {
background: var(--bg-surface);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
width: 520px;
max-height: 80vh;
overflow-y: auto;
box-shadow: 0 8px 30px rgba(0,0,0,.4);
}
.modal-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 18px;
border-bottom: 1px solid var(--border-subtle);
}
.modal-header h2 { font-size: 15px; font-weight: 600; }
.modal-body { padding: 18px; }
.modal-footer {
display: flex;
justify-content: flex-end;
gap: 8px;
padding: 12px 18px;
border-top: 1px solid var(--border-subtle);
}
/* --- Form fields --- */
.form-group {
margin-bottom: 14px;
}
.form-group label {
display: block;
font-size: 12px;
font-weight: 600;
color: var(--text-secondary);
margin-bottom: 4px;
}
.form-group textarea,
.form-group input {
width: 100%;
border: 1px solid var(--border);
background: var(--bg-input);
color: var(--text-primary);
border-radius: var(--radius);
padding: 8px 12px;
font-family: var(--font-mono);
font-size: 12px;
outline: none;
transition: border-color var(--transition);
}
.form-group textarea:focus,
.form-group input:focus { border-color: var(--accent); }
.form-group textarea { min-height: 80px; resize: vertical; }
.form-group .error-text {
font-size: 11px;
color: var(--status-error);
margin-top: 3px;
}
.rules-list { display: flex; flex-direction: column; gap: 6px; }
.rule-row {
display: flex;
gap: 6px;
align-items: center;
}
.rule-row input { flex: 1; }
/* ============================================================
JSON tree viewer
============================================================ */
.json-tree details { margin-left: 14px; }
.json-tree summary {
cursor: pointer;
color: var(--text-secondary);
font-family: var(--font-mono);
font-size: 12px;
user-select: none;
}
.json-tree summary:hover { color: var(--text-primary); }
.json-tree .json-key { color: var(--accent); }
.json-tree .json-string { color: var(--status-success); }
.json-tree .json-number { color: var(--agent-planner); }
.json-tree .json-bool { color: var(--status-warning); }
.json-tree .json-null { color: var(--text-muted); }
.json-tree .json-leaf {
margin-left: 14px;
font-family: var(--font-mono);
font-size: 12px;
padding: 1px 0;
}
/* ============================================================
Responsive
============================================================ */
@media (max-width: 1200px) {
#app {
grid-template-columns: var(--sidebar-width) 1fr;
grid-template-areas:
"toolbar toolbar"
"sidebar main";
}
#inspector { display: none; }
}
@media (max-width: 768px) {
#app {
grid-template-columns: 1fr;
grid-template-areas:
"toolbar"
"main";
}
#sidebar { display: none; }
}
/* ============================================================
Utility
============================================================ */
.hidden { display: none !important; }
.truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.mono { font-family: var(--font-mono); }
.text-muted { color: var(--text-muted); }
.text-sm { font-size: 12px; }
.mt-2 { margin-top: 8px; }
.gap-4 { gap: 4px; }

33
dashboard/index.html Normal file
View File

@@ -0,0 +1,33 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Agentic Dashboard</title>
<link rel="stylesheet" href="/dashboard/css/main.css">
</head>
<body>
<div id="app">
<div id="toolbar"></div>
<div id="sidebar"></div>
<div id="main">
<div class="chat-messages">
<div class="chat-empty">
<div class="icon">&#9881;</div>
<p>Loading...</p>
</div>
</div>
</div>
<div id="inspector">
<div class="inspector-empty">No session selected</div>
</div>
</div>
<!-- Modal overlay -->
<div class="modal-overlay" id="modal-overlay"></div>
<script type="module" src="/dashboard/js/app.js"></script>
</body>
</html>

133
dashboard/js/api.js Normal file
View File

@@ -0,0 +1,133 @@
/**
* API Client — all fetch calls + EventSource wrapper
*/
const BASE = '/api/v1';
class ApiClient {
constructor() {
this._eventSources = new Map();
this._bus = new EventTarget();
}
// --- Event bus ---
on(event, fn) { this._bus.addEventListener(event, fn); }
off(event, fn) { this._bus.removeEventListener(event, fn); }
_emit(event, detail) {
this._bus.dispatchEvent(new CustomEvent(event, { detail }));
}
// --- HTTP helpers ---
async _fetch(path, opts = {}) {
try {
const res = await fetch(`${BASE}${path}`, {
headers: { 'Content-Type': 'application/json', ...opts.headers },
...opts,
});
if (!res.ok) {
const err = await res.json().catch(() => ({ detail: res.statusText }));
throw new Error(err.detail || `HTTP ${res.status}`);
}
return res.json();
} catch (e) {
this._emit('error', { message: e.message, path });
throw e;
}
}
// --- Health ---
async checkHealth() {
try {
const data = await fetch('/health').then(r => r.json());
this._emit('health', data);
return data;
} catch {
this._emit('health', { status: 'disconnected' });
return { status: 'disconnected' };
}
}
// --- Sessions ---
async createSession(body) {
const data = await this._fetch('/sessions', {
method: 'POST',
body: JSON.stringify(body),
});
this._emit('session:created', data);
return data;
}
async getSession(sessionId) {
const data = await this._fetch(`/sessions/${sessionId}`);
this._emit('session:state', data);
return data;
}
async deleteSession(sessionId) {
const data = await this._fetch(`/sessions/${sessionId}`, { method: 'DELETE' });
this._emit('session:deleted', { session_id: sessionId });
return data;
}
async getEvents(sessionId) {
return this._fetch(`/sessions/${sessionId}/events`);
}
// --- Messages ---
async sendMessage(sessionId, message, stream = false) {
return this._fetch(`/sessions/${sessionId}/messages`, {
method: 'POST',
body: JSON.stringify({ message, stream }),
});
}
// --- SSE ---
subscribeSSE(sessionId) {
this.unsubscribeSSE(sessionId);
const url = `${BASE}/sessions/${sessionId}/stream`;
const es = new EventSource(url);
const eventTypes = [
'session.created', 'execution.started', 'agent.delta',
'tool.started', 'tool.completed', 'subagent.assigned',
'execution.completed', 'error', 'keepalive',
];
for (const type of eventTypes) {
es.addEventListener(type, (e) => {
try {
const payload = JSON.parse(e.data);
this._emit('sse', { type, ...payload });
this._emit(`sse:${type}`, payload);
} catch {
this._emit('sse', { type, raw: e.data });
}
});
}
es.onerror = () => {
this._emit('sse:error', { sessionId });
};
this._eventSources.set(sessionId, es);
return es;
}
unsubscribeSSE(sessionId) {
const es = this._eventSources.get(sessionId);
if (es) {
es.close();
this._eventSources.delete(sessionId);
}
}
unsubscribeAll() {
for (const [id, es] of this._eventSources) {
es.close();
}
this._eventSources.clear();
}
}
export const api = new ApiClient();

252
dashboard/js/app.js Normal file
View File

@@ -0,0 +1,252 @@
/**
* Application bootstrap — state management, health polling, routing
*/
import { api } from './api.js';
import { initSidebar, renderSessions } from './components/sidebar.js';
import { initSessionForm } from './components/session-form.js';
import { initToolbar, updateToolbar } from './components/toolbar.js';
import { initChat, addMessage, setStreamingContent, clearChat, setInputEnabled, showExecutionIndicator, hideExecutionIndicator } from './components/chat.js';
import { initEventLog, addEvent, clearEvents } from './components/event-log.js';
import { initInspector, updateInspector, clearInspector } from './components/session-inspector.js';
import { initTimeline, addTimelineStep, updateTimelineStep, clearTimeline } from './components/agent-timeline.js';
// --- Global state ---
export const state = {
sessions: JSON.parse(localStorage.getItem('agentic_sessions') || '[]'),
activeSessionId: null,
sessionState: null,
health: null,
isExecuting: false,
streamingContent: '',
currentAgent: '',
};
function saveSessions() {
localStorage.setItem('agentic_sessions', JSON.stringify(state.sessions));
}
// --- Session management ---
export async function selectSession(sessionId) {
api.unsubscribeAll();
state.activeSessionId = sessionId;
state.streamingContent = '';
state.currentAgent = '';
clearChat();
clearEvents();
clearTimeline();
clearInspector();
if (!sessionId) {
updateToolbar(null);
renderSessions();
return;
}
location.hash = `session=${sessionId}`;
renderSessions();
try {
const session = await api.getSession(sessionId);
state.sessionState = session;
updateToolbar(session);
updateInspector(session);
const events = await api.getEvents(sessionId);
for (const ev of events) addEvent(ev);
api.subscribeSSE(sessionId);
setInputEnabled(true);
} catch (e) {
addMessage('system', `Error loading session: ${e.message}`);
}
}
export async function createSession(body) {
const data = await api.createSession(body);
if (!state.sessions.includes(data.session_id)) {
state.sessions.unshift(data.session_id);
saveSessions();
}
await selectSession(data.session_id);
return data;
}
export async function deleteSession(sessionId) {
try {
await api.deleteSession(sessionId);
} catch { /* ignore 404 */ }
api.unsubscribeSSE(sessionId);
state.sessions = state.sessions.filter(s => s !== sessionId);
saveSessions();
if (state.activeSessionId === sessionId) {
state.activeSessionId = null;
state.sessionState = null;
location.hash = '';
clearChat();
clearEvents();
clearTimeline();
clearInspector();
updateToolbar(null);
}
renderSessions();
}
export async function sendMessage(message, stream = false) {
if (!state.activeSessionId || state.isExecuting) return;
state.isExecuting = true;
state.streamingContent = '';
setInputEnabled(false);
addMessage('user', message);
showExecutionIndicator();
try {
if (stream) {
await api.sendMessage(state.activeSessionId, message, true);
// Response comes via SSE — handled by event listeners
} else {
const result = await api.sendMessage(state.activeSessionId, message, false);
hideExecutionIndicator();
addMessage('assistant', result.content || JSON.stringify(result, null, 2));
state.isExecuting = false;
setInputEnabled(true);
// Refresh state
const session = await api.getSession(state.activeSessionId);
state.sessionState = session;
updateToolbar(session);
updateInspector(session);
}
} catch (e) {
hideExecutionIndicator();
addMessage('system', `Error: ${e.message}`);
state.isExecuting = false;
setInputEnabled(true);
}
}
// --- SSE event handlers ---
function setupSSEListeners() {
api.on('sse', (e) => {
addEvent(e.detail);
});
api.on('sse:execution.started', () => {
state.isExecuting = true;
showExecutionIndicator('Starting execution...');
});
api.on('sse:subagent.assigned', (e) => {
const d = e.detail.data || e.detail;
state.currentAgent = d.agent || '';
showExecutionIndicator(`Step ${d.step}/${d.total_steps}${d.agent}`);
addTimelineStep({
step: d.step,
totalSteps: d.total_steps,
agent: d.agent,
description: d.description,
status: 'executing',
});
});
api.on('sse:agent.delta', (e) => {
const d = e.detail.data || e.detail;
state.streamingContent += d.delta || '';
setStreamingContent(state.streamingContent, state.currentAgent);
});
api.on('sse:tool.started', (e) => {
const d = e.detail.data || e.detail;
showExecutionIndicator(`Running tool: ${d.tool}`);
});
api.on('sse:tool.completed', (e) => {
const d = e.detail.data || e.detail;
if (state.currentAgent) {
updateTimelineStep(state.currentAgent, { tool: d.tool, status: d.status });
}
});
api.on('sse:execution.completed', async (e) => {
hideExecutionIndicator();
if (state.streamingContent) {
// Finalize the streaming message
addMessage('assistant', state.streamingContent);
state.streamingContent = '';
}
state.isExecuting = false;
state.currentAgent = '';
setInputEnabled(true);
// Refresh session state
if (state.activeSessionId) {
try {
const session = await api.getSession(state.activeSessionId);
state.sessionState = session;
updateToolbar(session);
updateInspector(session);
} catch { /* ignore */ }
}
});
api.on('sse:error', (e) => {
const d = e.detail.data || e.detail;
addMessage('system', `Error: ${JSON.stringify(d)}`);
hideExecutionIndicator();
state.isExecuting = false;
setInputEnabled(true);
});
}
// --- Health polling ---
let healthInterval;
function startHealthPolling() {
const poll = async () => {
state.health = await api.checkHealth();
};
poll();
healthInterval = setInterval(poll, 10000);
}
// --- Theme ---
export function toggleTheme() {
const current = document.documentElement.getAttribute('data-theme');
const next = current === 'light' ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', next);
localStorage.setItem('agentic_theme', next);
}
// --- Init ---
function init() {
// Restore theme
const savedTheme = localStorage.getItem('agentic_theme') || 'dark';
if (savedTheme === 'light') {
document.documentElement.setAttribute('data-theme', 'light');
}
// Init components
initToolbar();
initSidebar();
initSessionForm();
initChat();
initEventLog();
initInspector();
initTimeline();
// SSE listeners
setupSSEListeners();
// Health
startHealthPolling();
// Restore session from hash
const hash = location.hash;
const match = hash.match(/session=([a-f0-9]+)/);
if (match && state.sessions.includes(match[1])) {
selectSession(match[1]);
}
renderSessions();
}
document.addEventListener('DOMContentLoaded', init);

View File

@@ -0,0 +1,101 @@
/**
* Agent Timeline — visual execution timeline built from SSE events
*/
let containerEl;
let steps = [];
export function initTimeline() {
// The timeline renders inside the inspector; this module manages the data
containerEl = null;
steps = [];
}
export function addTimelineStep({ step, totalSteps, agent, description, status }) {
steps.push({
step,
totalSteps,
agent,
description,
status: status || 'executing',
tools: [],
});
renderTimeline();
}
export function updateTimelineStep(agent, { tool, status }) {
// Find the last step for this agent
for (let i = steps.length - 1; i >= 0; i--) {
if (steps[i].agent === agent) {
if (tool) {
steps[i].tools.push({ name: tool, status: status || 'completed' });
}
break;
}
}
renderTimeline();
}
export function clearTimeline() {
steps = [];
renderTimeline();
}
function renderTimeline() {
// Find or create the timeline container in the inspector
const inspector = document.getElementById('inspector');
if (!inspector) return;
// Remove existing timeline section
let existing = document.getElementById('live-timeline-section');
if (existing) existing.remove();
if (steps.length === 0) return;
const section = document.createElement('div');
section.className = 'inspector-section';
section.id = 'live-timeline-section';
let html = '<div class="inspector-section-title">Live Timeline</div>';
html += '<div class="timeline">';
for (const s of steps) {
const stepClass = s.status === 'executing' ? 'active' : s.status === 'completed' ? 'completed' : s.status === 'failed' ? 'failed' : '';
html += `
<div class="timeline-step ${stepClass}">
<div class="timeline-step-header">
<span class="role-badge ${s.agent}">${s.agent}</span>
<span class="text-sm text-muted">Step ${s.step}/${s.totalSteps}</span>
</div>
<div class="timeline-step-desc">${escapeHtml(s.description)}</div>
`;
if (s.tools.length > 0) {
html += '<div class="timeline-tools">';
for (const t of s.tools) {
html += `<span class="tool-chip">${escapeHtml(t.name)}</span>`;
}
html += '</div>';
}
html += '</div>';
}
html += '</div>';
section.innerHTML = html;
// Insert at the top of inspector (after session info if present)
const firstSection = inspector.querySelector('.inspector-section');
if (firstSection && firstSection.nextSibling) {
inspector.insertBefore(section, firstSection.nextSibling);
} else {
inspector.appendChild(section);
}
}
function escapeHtml(str) {
if (!str) return '';
return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

View File

@@ -0,0 +1,180 @@
/**
* Chat — message input + conversation view + streaming
*/
import { sendMessage } from '../app.js';
let messagesEl;
let inputEl;
let sendBtn;
let streamBtn;
let indicatorEl;
let streamingBubble = null;
// Minimal markdown renderer
function renderMarkdown(text) {
let html = text
// Code blocks
.replace(/```(\w*)\n([\s\S]*?)```/g, '<pre><code>$2</code></pre>')
// Inline code
.replace(/`([^`]+)`/g, '<code>$1</code>')
// Headers
.replace(/^### (.+)$/gm, '<h3>$1</h3>')
.replace(/^## (.+)$/gm, '<h2>$1</h2>')
.replace(/^# (.+)$/gm, '<h1>$1</h1>')
// Bold
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
// Lists
.replace(/^\- (.+)$/gm, '<li>$1</li>')
.replace(/^\* (.+)$/gm, '<li>$1</li>')
// Paragraphs (double newlines)
.replace(/\n\n/g, '</p><p>')
// Single newlines
.replace(/\n/g, '<br>');
// Wrap loose <li> in <ul>
html = html.replace(/(<li>.*?<\/li>)/gs, '<ul>$1</ul>');
html = html.replace(/<\/ul>\s*<ul>/g, '');
return `<p>${html}</p>`;
}
export function initChat() {
const main = document.getElementById('main');
main.innerHTML = `
<div class="chat-messages" id="chat-messages">
<div class="chat-empty">
<div class="icon">&#9881;</div>
<p>Select or create a session to start</p>
</div>
</div>
<div class="event-log-panel" id="event-log-panel"></div>
<div class="chat-input-area">
<div class="chat-input-wrapper">
<textarea id="chat-input" placeholder="Send a message..." rows="1" disabled></textarea>
<button class="btn btn-primary" id="btn-send" disabled>Send</button>
<button class="btn" id="btn-stream" disabled title="Send with SSE streaming">Stream</button>
</div>
</div>
`;
messagesEl = document.getElementById('chat-messages');
inputEl = document.getElementById('chat-input');
sendBtn = document.getElementById('btn-send');
streamBtn = document.getElementById('btn-stream');
// Auto-resize textarea
inputEl.addEventListener('input', () => {
inputEl.style.height = 'auto';
inputEl.style.height = Math.min(inputEl.scrollHeight, 160) + 'px';
});
// Send
sendBtn.addEventListener('click', () => doSend(false));
streamBtn.addEventListener('click', () => doSend(true));
// Keyboard shortcuts
inputEl.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
doSend(false);
}
if (e.key === 'Enter' && e.ctrlKey) {
e.preventDefault();
doSend(true);
}
});
}
function doSend(stream) {
const text = inputEl.value.trim();
if (!text) return;
inputEl.value = '';
inputEl.style.height = 'auto';
sendMessage(text, stream);
}
export function addMessage(role, content) {
// Remove empty state
const empty = messagesEl.querySelector('.chat-empty');
if (empty) empty.remove();
// Remove streaming bubble if finalizing
if (role === 'assistant' && streamingBubble) {
streamingBubble.remove();
streamingBubble = null;
}
const div = document.createElement('div');
div.className = `message ${role}`;
if (role === 'assistant') {
div.innerHTML = renderMarkdown(content);
} else if (role === 'system') {
div.textContent = content;
} else {
div.textContent = content;
}
messagesEl.appendChild(div);
messagesEl.scrollTop = messagesEl.scrollHeight;
}
export function setStreamingContent(content, agent) {
// Remove empty state
const empty = messagesEl.querySelector('.chat-empty');
if (empty) empty.remove();
if (!streamingBubble) {
streamingBubble = document.createElement('div');
streamingBubble.className = 'message assistant';
messagesEl.appendChild(streamingBubble);
}
let badgeHtml = '';
if (agent) {
badgeHtml = `<span class="agent-badge role-badge ${agent}">${agent}</span><br>`;
}
streamingBubble.innerHTML = badgeHtml + renderMarkdown(content);
messagesEl.scrollTop = messagesEl.scrollHeight;
}
export function clearChat() {
if (!messagesEl) return;
streamingBubble = null;
messagesEl.innerHTML = `
<div class="chat-empty">
<div class="icon">&#9881;</div>
<p>Select or create a session to start</p>
</div>
`;
}
export function setInputEnabled(enabled) {
if (!inputEl) return;
inputEl.disabled = !enabled;
sendBtn.disabled = !enabled;
streamBtn.disabled = !enabled;
if (enabled) inputEl.focus();
}
export function showExecutionIndicator(text) {
hideExecutionIndicator();
const empty = messagesEl.querySelector('.chat-empty');
if (empty) empty.remove();
indicatorEl = document.createElement('div');
indicatorEl.className = 'execution-indicator';
indicatorEl.innerHTML = `<div class="spinner"></div><span>${text || 'Executing...'}</span>`;
messagesEl.appendChild(indicatorEl);
messagesEl.scrollTop = messagesEl.scrollHeight;
}
export function hideExecutionIndicator() {
if (indicatorEl) {
indicatorEl.remove();
indicatorEl = null;
}
}

View File

@@ -0,0 +1,171 @@
/**
* Event Log — real-time SSE events with filtering
*/
const EVENT_CATEGORIES = {
'session.created': 'lifecycle',
'execution.started': 'lifecycle',
'execution.completed': 'lifecycle',
'agent.delta': 'content',
'tool.started': 'tool',
'tool.completed': 'tool',
'subagent.assigned': 'orchestration',
'error': 'error',
'keepalive': 'keepalive',
};
const CATEGORY_LABELS = ['lifecycle', 'content', 'tool', 'orchestration', 'error'];
let entriesEl;
let activeFilters = new Set(CATEGORY_LABELS);
let stickToBottom = true;
let events = [];
export function initEventLog() {
const panel = document.getElementById('event-log-panel');
panel.innerHTML = `
<div class="event-log-header" id="event-log-toggle">
<span class="chevron">&#9660;</span>
<span>Event Log</span>
<span class="toolbar-spacer"></span>
<span class="text-muted text-sm" id="event-count">0 events</span>
<button class="btn btn-sm" id="btn-clear-events" style="margin-left:8px">Clear</button>
<button class="btn btn-sm" id="btn-export-events">Export</button>
</div>
<div class="event-log-filters" id="event-filters"></div>
<div class="event-log-entries" id="event-entries"></div>
`;
entriesEl = document.getElementById('event-entries');
// Toggle panel
document.getElementById('event-log-toggle').addEventListener('click', () => {
panel.classList.toggle('open');
});
// Filters
const filtersEl = document.getElementById('event-filters');
for (const cat of CATEGORY_LABELS) {
const btn = document.createElement('button');
btn.className = `event-filter-btn active`;
btn.textContent = cat;
btn.dataset.category = cat;
btn.addEventListener('click', () => {
if (activeFilters.has(cat)) {
activeFilters.delete(cat);
btn.classList.remove('active');
} else {
activeFilters.add(cat);
btn.classList.add('active');
}
renderEvents();
});
filtersEl.appendChild(btn);
}
// Auto-scroll detection
entriesEl.addEventListener('scroll', () => {
const { scrollTop, scrollHeight, clientHeight } = entriesEl;
stickToBottom = scrollHeight - scrollTop - clientHeight < 20;
});
// Clear
document.getElementById('btn-clear-events').addEventListener('click', (e) => {
e.stopPropagation();
clearEvents();
});
// Export
document.getElementById('btn-export-events').addEventListener('click', (e) => {
e.stopPropagation();
const blob = new Blob([JSON.stringify(events, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `events-${Date.now()}.json`;
a.click();
URL.revokeObjectURL(url);
});
}
export function addEvent(event) {
events.push(event);
document.getElementById('event-count').textContent = `${events.length} events`;
const type = event.type || '';
const category = EVENT_CATEGORIES[type] || 'lifecycle';
if (!activeFilters.has(category)) return;
if (category === 'keepalive') return; // Hide keepalives by default
const entry = createEventEntry(event, type, category);
entriesEl.appendChild(entry);
if (stickToBottom) {
entriesEl.scrollTop = entriesEl.scrollHeight;
}
}
function createEventEntry(event, type, category) {
const el = document.createElement('div');
el.className = 'event-entry';
const time = event.timestamp
? new Date(event.timestamp).toLocaleTimeString('en-US', { hour12: false, fractionalSecondDigits: 3 })
: '--:--:--';
const data = event.data || {};
const summary = summarizeEventData(type, data);
el.innerHTML = `
<span class="event-time">${time}</span>
<span class="event-type-badge ${category}">${type.split('.').pop()}</span>
<span class="event-data" title="Click to expand">${summary}</span>
`;
// Toggle expand
const dataEl = el.querySelector('.event-data');
dataEl.addEventListener('click', () => {
if (dataEl.classList.contains('expanded')) {
dataEl.classList.remove('expanded');
dataEl.textContent = summary;
} else {
dataEl.classList.add('expanded');
dataEl.textContent = JSON.stringify(data, null, 2);
}
});
return el;
}
function summarizeEventData(type, data) {
switch (type) {
case 'agent.delta': return `[${data.agent || '?'}] "${(data.delta || '').substring(0, 60)}..."`;
case 'tool.started': return `Tool: ${data.tool}`;
case 'tool.completed': return `Tool: ${data.tool}${data.status}`;
case 'subagent.assigned': return `Step ${data.step}/${data.total_steps}: ${data.agent}${(data.description || '').substring(0, 50)}`;
case 'execution.started': return `Session: ${(data.session_id || '').substring(0, 12)}`;
case 'execution.completed': return `Steps: ${data.steps_completed}${data.status}`;
case 'error': return JSON.stringify(data);
default: return JSON.stringify(data).substring(0, 80);
}
}
function renderEvents() {
entriesEl.innerHTML = '';
for (const event of events) {
const type = event.type || '';
const category = EVENT_CATEGORIES[type] || 'lifecycle';
if (!activeFilters.has(category)) continue;
if (category === 'keepalive') continue;
entriesEl.appendChild(createEventEntry(event, type, category));
}
}
export function clearEvents() {
events = [];
if (entriesEl) entriesEl.innerHTML = '';
const countEl = document.getElementById('event-count');
if (countEl) countEl.textContent = '0 events';
}

View File

@@ -0,0 +1,147 @@
/**
* Session creation modal
*/
import { createSession } from '../app.js';
let overlay;
export function initSessionForm() {
overlay = document.getElementById('modal-overlay');
overlay.innerHTML = `
<div class="modal">
<div class="modal-header">
<h2>New Session</h2>
<button class="btn-icon" id="modal-close">&times;</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Project Profile (JSON)</label>
<textarea id="field-profile" spellcheck="false">{
"name": "",
"tech_stack": [],
"description": ""
}</textarea>
<div class="error-text hidden" id="err-profile"></div>
</div>
<div class="form-group">
<label>Immutable Rules</label>
<div class="rules-list" id="rules-list">
<div class="rule-row">
<input type="text" placeholder="Add a rule..." />
<button class="btn btn-sm" id="btn-add-rule">+</button>
</div>
</div>
</div>
<div class="form-group">
<label>Metadata (JSON)</label>
<textarea id="field-metadata" spellcheck="false">{}</textarea>
<div class="error-text hidden" id="err-metadata"></div>
</div>
</div>
<div class="modal-footer">
<button class="btn" id="btn-cancel">Cancel</button>
<button class="btn btn-primary" id="btn-create">Create Session</button>
</div>
</div>
`;
document.getElementById('modal-close').addEventListener('click', closeModal);
document.getElementById('btn-cancel').addEventListener('click', closeModal);
document.getElementById('btn-create').addEventListener('click', handleCreate);
document.getElementById('btn-add-rule').addEventListener('click', addRuleRow);
overlay.addEventListener('click', (e) => {
if (e.target === overlay) closeModal();
});
// Format JSON on blur
for (const id of ['field-profile', 'field-metadata']) {
document.getElementById(id).addEventListener('blur', (e) => {
try {
const parsed = JSON.parse(e.target.value);
e.target.value = JSON.stringify(parsed, null, 2);
e.target.nextElementSibling.classList.add('hidden');
} catch (err) {
e.target.nextElementSibling.textContent = `Invalid JSON: ${err.message}`;
e.target.nextElementSibling.classList.remove('hidden');
}
});
}
}
function addRuleRow() {
const list = document.getElementById('rules-list');
const addBtn = document.getElementById('btn-add-rule');
const row = document.createElement('div');
row.className = 'rule-row';
row.innerHTML = `
<input type="text" placeholder="Add a rule..." />
<button class="btn btn-sm btn-danger remove-rule">&minus;</button>
`;
row.querySelector('.remove-rule').addEventListener('click', () => row.remove());
list.insertBefore(row, addBtn.closest('.rule-row'));
}
function getRules() {
const inputs = document.querySelectorAll('#rules-list input');
return Array.from(inputs).map(i => i.value.trim()).filter(Boolean);
}
function validateJSON(id) {
const el = document.getElementById(id);
try {
return JSON.parse(el.value);
} catch (err) {
const errEl = document.getElementById(`err-${id.replace('field-', '')}`);
errEl.textContent = `Invalid JSON: ${err.message}`;
errEl.classList.remove('hidden');
return null;
}
}
async function handleCreate() {
const profile = validateJSON('field-profile');
const metadata = validateJSON('field-metadata');
if (profile === null || metadata === null) return;
const rules = getRules();
const btn = document.getElementById('btn-create');
btn.disabled = true;
btn.textContent = 'Creating...';
try {
await createSession({
project_profile: profile,
immutable_rules: rules,
metadata,
});
closeModal();
resetForm();
} catch (e) {
alert(`Failed: ${e.message}`);
} finally {
btn.disabled = false;
btn.textContent = 'Create Session';
}
}
function resetForm() {
document.getElementById('field-profile').value = '{\n "name": "",\n "tech_stack": [],\n "description": ""\n}';
document.getElementById('field-metadata').value = '{}';
const list = document.getElementById('rules-list');
const rows = list.querySelectorAll('.rule-row');
rows.forEach((r, i) => { if (i < rows.length - 1) r.remove(); });
const lastInput = list.querySelector('input');
if (lastInput) lastInput.value = '';
}
export function openSessionForm() {
overlay.classList.add('open');
}
function closeModal() {
overlay.classList.remove('open');
}

View File

@@ -0,0 +1,144 @@
/**
* Session Inspector — right panel with full state rendering
*/
let inspectorEl;
export function initInspector() {
inspectorEl = document.getElementById('inspector');
clearInspector();
}
export function clearInspector() {
if (!inspectorEl) return;
inspectorEl.innerHTML = '<div class="inspector-empty">No session selected</div>';
}
export function updateInspector(session) {
if (!inspectorEl || !session) return;
inspectorEl.innerHTML = '';
// Header
inspectorEl.appendChild(buildSection('Session', `
<div class="inspector-field">
<span class="label">ID</span>
<span class="value truncate" style="max-width:180px" title="${session.session_id}">${session.session_id.substring(0, 16)}...</span>
</div>
<div class="inspector-field">
<span class="label">Status</span>
<span class="badge ${session.status}">${session.status}</span>
</div>
<div class="inspector-field">
<span class="label">Turns</span>
<span class="value">${session.turn_count}</span>
</div>
<div class="inspector-field">
<span class="label">Created</span>
<span class="value">${formatTime(session.created_at)}</span>
</div>
<div class="inspector-field">
<span class="label">Updated</span>
<span class="value">${formatTime(session.updated_at)}</span>
</div>
`));
// Current Task
if (session.current_task) {
const task = session.current_task;
let taskHtml = `
<div class="inspector-field">
<span class="label">Objective</span>
</div>
<div class="text-sm" style="margin-bottom:6px;color:var(--text-primary)">${escapeHtml(task.objective)}</div>
<div class="inspector-field">
<span class="label">Status</span>
<span class="badge ${task.status}">${task.status}</span>
</div>
<div class="inspector-field">
<span class="label">Step</span>
<span class="value">${task.current_step_index + 1} / ${(task.plan || []).length}</span>
</div>
`;
// Facts
if (task.facts_extracted && task.facts_extracted.length > 0) {
taskHtml += '<div class="mt-2"><span class="label text-sm">Facts:</span><ul style="padding-left:16px;margin-top:4px">';
for (const f of task.facts_extracted.slice(-8)) {
taskHtml += `<li class="text-sm">${escapeHtml(f)}</li>`;
}
taskHtml += '</ul></div>';
}
// Constraints
if (task.constraints && task.constraints.length > 0) {
taskHtml += '<div class="mt-2"><span class="label text-sm">Constraints:</span><ul style="padding-left:16px;margin-top:4px">';
for (const c of task.constraints) {
taskHtml += `<li class="text-sm">${escapeHtml(c)}</li>`;
}
taskHtml += '</ul></div>';
}
inspectorEl.appendChild(buildSection('Current Task', taskHtml));
// Plan
if (task.plan && task.plan.length > 0) {
let planHtml = '<div class="timeline">';
for (let i = 0; i < task.plan.length; i++) {
const step = task.plan[i];
const stepStatus = step.status || 'pending';
const isActive = i === task.current_step_index && task.status === 'executing';
const stepClass = isActive ? 'active' : (stepStatus === 'completed' ? 'completed' : stepStatus === 'failed' ? 'failed' : '');
planHtml += `
<div class="timeline-step ${stepClass}">
<div class="timeline-step-header">
<span class="role-badge ${step.agent_role || 'coder'}">${step.agent_role || 'coder'}</span>
<span class="badge ${stepStatus}">${stepStatus}</span>
</div>
<div class="timeline-step-desc">${escapeHtml(step.description)}</div>
${step.tools_used && step.tools_used.length > 0 ? `
<div class="timeline-tools">
${step.tools_used.map(t => `<span class="tool-chip">${escapeHtml(t)}</span>`).join('')}
</div>
` : ''}
${step.result_summary ? `<div class="text-sm text-muted mt-2">${escapeHtml(step.result_summary.substring(0, 200))}</div>` : ''}
</div>
`;
}
planHtml += '</div>';
inspectorEl.appendChild(buildSection('Execution Plan', planHtml));
}
}
// Completed tasks
if (session.completed_tasks && session.completed_tasks.length > 0) {
let html = '<ul style="padding-left:16px">';
for (const t of session.completed_tasks) {
html += `<li class="text-sm mono">${t}</li>`;
}
html += '</ul>';
inspectorEl.appendChild(buildSection(`Completed (${session.completed_tasks.length})`, html));
}
}
function buildSection(title, innerHtml) {
const section = document.createElement('div');
section.className = 'inspector-section';
section.innerHTML = `<div class="inspector-section-title">${title}</div>${innerHtml}`;
return section;
}
function formatTime(isoStr) {
if (!isoStr) return '—';
try {
return new Date(isoStr).toLocaleTimeString('en-US', { hour12: false });
} catch {
return isoStr;
}
}
function escapeHtml(str) {
if (!str) return '';
return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

View File

@@ -0,0 +1,67 @@
/**
* Sidebar — session list + health indicator
*/
import { state, selectSession, deleteSession, createSession } from '../app.js';
import { api } from '../api.js';
import { openSessionForm } from './session-form.js';
let listEl;
let healthDot;
let healthText;
export function initSidebar() {
const sidebar = document.getElementById('sidebar');
sidebar.innerHTML = `
<div class="sidebar-header">
<h3>Sessions</h3>
<button class="btn btn-sm btn-primary" id="btn-new-session">+ New</button>
</div>
<div class="session-list" id="session-list"></div>
<div class="sidebar-footer">
<span class="status-dot disconnected" id="health-dot"></span>
<span id="health-text">Connecting...</span>
</div>
`;
listEl = document.getElementById('session-list');
healthDot = document.getElementById('health-dot');
healthText = document.getElementById('health-text');
document.getElementById('btn-new-session').addEventListener('click', openSessionForm);
// Health updates
api.on('health', (e) => {
const ok = e.detail.status === 'ok';
healthDot.className = `status-dot ${ok ? 'connected' : 'disconnected'}`;
healthText.textContent = ok ? 'Connected' : 'Disconnected';
});
}
export function renderSessions() {
if (!listEl) return;
listEl.innerHTML = '';
for (const sid of state.sessions) {
const item = document.createElement('div');
item.className = `session-item${sid === state.activeSessionId ? ' active' : ''}`;
item.innerHTML = `
<span class="status-dot idle"></span>
<span class="truncate">${sid.substring(0, 12)}...</span>
<button class="delete-btn" title="Delete session">&times;</button>
`;
item.querySelector('.truncate').addEventListener('click', () => selectSession(sid));
item.querySelector('.delete-btn').addEventListener('click', (e) => {
e.stopPropagation();
if (confirm('Delete this session?')) deleteSession(sid);
});
listEl.appendChild(item);
}
if (state.sessions.length === 0) {
listEl.innerHTML = '<div class="text-muted text-sm" style="padding:20px 10px;text-align:center">No sessions yet</div>';
}
}

View File

@@ -0,0 +1,199 @@
/**
* Toolbar — top bar with session info and actions
*/
import { state, deleteSession, toggleTheme } from '../app.js';
import { api } from '../api.js';
let sessionIdEl;
let statusBadge;
export function initToolbar() {
const toolbar = document.getElementById('toolbar');
toolbar.innerHTML = `
<span class="toolbar-brand">Agentic Microservice</span>
<span class="toolbar-separator"></span>
<span class="toolbar-session-id" id="toolbar-session-id" title="Click to copy">No session</span>
<span class="badge idle" id="toolbar-status" style="display:none"></span>
<span class="toolbar-spacer"></span>
<div class="toolbar-actions">
<button class="btn btn-sm" id="btn-refresh" title="Refresh state">&#8635; Refresh</button>
<button class="btn btn-sm" id="btn-context-debug" title="View context debug">&#128270; Context</button>
<button class="btn btn-sm" id="btn-raw-state" title="View raw JSON">{ } Raw</button>
<button class="btn btn-sm" id="btn-theme" title="Toggle theme">&#9681;</button>
<button class="btn btn-sm btn-danger" id="btn-delete-session" title="Delete session">&#128465;</button>
</div>
`;
sessionIdEl = document.getElementById('toolbar-session-id');
statusBadge = document.getElementById('toolbar-status');
// Copy session ID
sessionIdEl.addEventListener('click', () => {
if (state.activeSessionId) {
navigator.clipboard.writeText(state.activeSessionId);
const orig = sessionIdEl.textContent;
sessionIdEl.textContent = 'Copied!';
setTimeout(() => { sessionIdEl.textContent = orig; }, 1000);
}
});
// Refresh
document.getElementById('btn-refresh').addEventListener('click', async () => {
if (!state.activeSessionId) return;
try {
const session = await api.getSession(state.activeSessionId);
state.sessionState = session;
updateToolbar(session);
// Dispatch event so inspector updates too
const { updateInspector } = await import('./session-inspector.js');
updateInspector(session);
} catch (e) {
alert(`Refresh failed: ${e.message}`);
}
});
// Context debug
document.getElementById('btn-context-debug').addEventListener('click', async () => {
if (!state.activeSessionId) return;
try {
const res = await fetch(`/api/v1/sessions/${state.activeSessionId}/context-debug`);
const data = await res.json();
const win = window.open('', '_blank', 'width=900,height=700');
win.document.title = 'Context Debug';
win.document.write(renderContextDebugHTML(data));
} catch (e) {
alert(`Failed: ${e.message}`);
}
});
// Raw state
document.getElementById('btn-raw-state').addEventListener('click', async () => {
if (!state.activeSessionId) return;
try {
const session = await api.getSession(state.activeSessionId);
const win = window.open('', '_blank', 'width=600,height=500');
win.document.write(`<pre style="font-size:12px;padding:16px;background:#0d1117;color:#e6edf3;font-family:monospace">${JSON.stringify(session, null, 2)}</pre>`);
} catch (e) {
alert(`Failed: ${e.message}`);
}
});
// Theme
document.getElementById('btn-theme').addEventListener('click', toggleTheme);
// Delete
document.getElementById('btn-delete-session').addEventListener('click', () => {
if (!state.activeSessionId) return;
if (confirm('Delete this session permanently?')) {
deleteSession(state.activeSessionId);
}
});
}
export function updateToolbar(session) {
if (!session) {
sessionIdEl.textContent = 'No session';
statusBadge.style.display = 'none';
return;
}
sessionIdEl.textContent = session.session_id;
statusBadge.textContent = session.status;
statusBadge.className = `badge ${session.status}`;
statusBadge.style.display = '';
}
function renderContextDebugHTML(data) {
const css = `
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #0d1117; color: #e6edf3; padding: 24px; font-size: 14px; }
h1 { font-size: 18px; margin-bottom: 16px; color: #58a6ff; }
h2 { font-size: 15px; margin: 20px 0 10px; color: #bc8cff; border-bottom: 1px solid #30363d; padding-bottom: 6px; }
h3 { font-size: 13px; margin: 12px 0 6px; color: #d29922; }
.meta { color: #8b949e; font-size: 12px; margin-bottom: 16px; }
.build { background: #161b22; border: 1px solid #30363d; border-radius: 8px; padding: 16px; margin-bottom: 16px; }
.build-header { display: flex; gap: 12px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; }
.tag { font-size: 11px; padding: 2px 8px; border-radius: 10px; font-weight: 600; }
.tag.agent { background: rgba(63,185,80,.15); color: #3fb950; }
.tag.tokens { background: rgba(88,166,255,.15); color: #58a6ff; }
.tag.sections { background: rgba(188,140,255,.15); color: #bc8cff; }
.tag.compacted { background: rgba(248,81,73,.15); color: #f85149; }
.section-row { display: grid; grid-template-columns: 140px 60px 60px 1fr; gap: 8px; padding: 6px 8px; border-radius: 4px; font-size: 12px; align-items: start; }
.section-row:nth-child(odd) { background: rgba(255,255,255,.02); }
.section-row .type { color: #58a6ff; font-weight: 600; font-family: 'SF Mono', monospace; }
.section-row .num { color: #8b949e; text-align: right; font-family: 'SF Mono', monospace; }
.section-row .preview { color: #8b949e; font-size: 11px; line-height: 1.4; word-break: break-all; }
.section-header { display: grid; grid-template-columns: 140px 60px 60px 1fr; gap: 8px; padding: 4px 8px; font-size: 11px; color: #6e7681; font-weight: 600; text-transform: uppercase; letter-spacing: .5px; border-bottom: 1px solid #21262d; margin-bottom: 4px; }
.bar { height: 6px; border-radius: 3px; margin-top: 8px; background: #21262d; overflow: hidden; }
.bar-fill { height: 100%; border-radius: 3px; }
.user-msg { background: #1c2128; border: 1px solid #30363d; border-radius: 6px; padding: 10px 14px; font-size: 12px; font-family: 'SF Mono', monospace; color: #e6edf3; margin-top: 8px; white-space: pre-wrap; word-break: break-word; }
.empty { color: #6e7681; font-style: italic; padding: 40px; text-align: center; }
</style>
`;
if (!data.history || data.history.length === 0) {
return css + '<body><h1>Context Debug</h1><div class="empty">No context builds yet. Send a message first.</div></body>';
}
let html = css + '<body>';
html += '<h1>Context Engine Debug</h1>';
html += '<div class="meta">Session: ' + data.session_id + ' &mdash; ' + data.total_builds + ' context build(s)</div>';
// Reverse to show most recent first
const builds = [...data.history].reverse();
for (let i = 0; i < builds.length; i++) {
const b = builds[i];
const time = new Date(b.timestamp * 1000).toLocaleTimeString('en-US', { hour12: false, fractionalSecondDigits: 2 });
const maxTokens = 120000;
const pct = Math.min(100, (b.total_tokens / maxTokens) * 100);
const barColor = pct > 80 ? '#f85149' : pct > 50 ? '#d29922' : '#3fb950';
html += '<div class="build">';
html += '<div class="build-header">';
html += '<span class="tag agent">' + b.agent + '</span>';
html += '<span class="tag tokens">~' + b.total_tokens.toLocaleString() + ' tokens</span>';
html += '<span class="tag sections">' + b.sections_count + ' sections</span>';
if (b.compacted) html += '<span class="tag compacted">COMPACTED</span>';
html += '<span style="color:#6e7681;font-size:11px;margin-left:auto">' + time + '</span>';
html += '</div>';
// Token usage bar
html += '<div class="bar"><div class="bar-fill" style="width:' + pct.toFixed(1) + '%;background:' + barColor + '"></div></div>';
html += '<div style="font-size:11px;color:#6e7681;margin-top:2px">' + pct.toFixed(1) + '% of context window (' + b.total_tokens.toLocaleString() + ' / ' + maxTokens.toLocaleString() + ')</div>';
// Sections table
html += '<h3>Sections</h3>';
html += '<div class="section-header"><span>Type</span><span style="text-align:right">Tokens</span><span style="text-align:right">Prio</span><span>Preview</span></div>';
for (const s of b.sections) {
html += '<div class="section-row">';
html += '<span class="type">' + s.type + '</span>';
html += '<span class="num">' + s.tokens + '</span>';
html += '<span class="num">' + s.priority + '</span>';
html += '<span class="preview">' + escapeHtml(s.preview) + '</span>';
html += '</div>';
}
// User message
html += '<h3>User Message Sent to Model</h3>';
html += '<div class="user-msg">' + escapeHtml(b.user_message_preview) + '</div>';
// Extra info
html += '<div style="margin-top:10px;font-size:11px;color:#6e7681">';
html += 'Artifacts: ' + b.artifacts_count + ' | Working items: ' + b.working_items_count + ' | System prompt tokens: ' + b.system_prompt_tokens;
html += '</div>';
html += '</div>';
}
html += '</body>';
return html;
}
function escapeHtml(str) {
if (!str) return '';
return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}