feat(webui): bootstrap Vue 3 + shadcn-vue, replacing the Preact dashboard

Sam owns this codebase and reads Vue fluently, not Preact; a UI its maintainer
cannot read is the liability that outweighs the port. shadcn-vue is Vue-only,
so adopting it means the framework moves with it.

Scaffolded per the official Vite guide: `npm create vite --template vue-ts`,
Tailwind v4 via @tailwindcss/vite, `shadcn-vue init` (Reka UI, Lucide, neutral
base, CSS variables). Button and DropdownMenu are added, the latter being what
the pending navigation restructure needs.

Two deviations from the guide, both forced:

  - The guide sets `baseUrl` alongside `paths`. TypeScript 6 deprecates
    `baseUrl` and errors on it, and this project is heading for TS 7 native, so
    `paths` stands alone and resolves relative to the config file. Not a
    downgrade: the scaffold's typescript ~6.0.2 is untouched.
  - vite.config.ts keeps `base: "./"` and unhashed asset names. ui/embed.go
    embeds a committed dist/, served from a path the build does not know;
    hashed names would also orphan a file in git on every rebuild.

The Preact app and its 43 test files are deleted rather than ported, on Sam's
instruction: tests return when there is behaviour worth pinning rather than a
port to re-assert. `task test:ui` is now a vue-tsc typecheck, which is what
would actually catch a broken component; an empty `npm test` would pass
vacuously.

ui/src/router/index.ts carries the route table and is the new source of truth
for TestDashboardPagesRegistryCoversEveryRoute, which parsed main.jsx before.
Keeping that contract alive matters: it is what caught the stale /chat entry
earlier today. Every route resolves to a named placeholder view, so an unported
page is visibly unported rather than blank.

golangci-lint now excludes ui/node_modules. The dashboard toolchain pulls in
`flatted`, which ships a Go implementation beside its JavaScript, and the gate
was failing on complexity in a vendored third-party file.

The shadcn MCP server is registered in the root .mcp.json. `shadcn-vue mcp init`
writes it to the directory it runs in, which for a nested ui/ is a path Claude
Code never reads.
This commit is contained in:
sam committed 2026-09-20 17:14:47 +10:00
1 parent da0116f0ba
commit d933d36449
166 files changed
+6768 -16833

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
<script setup lang="ts"></script>
<template>
<RouterView />
</template>
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="77" height="47" fill="none" aria-labelledby="vite-logo-title" viewBox="0 0 77 47"><title id="vite-logo-title">Vite</title><style>.parenthesis{fill:#000}@media (prefers-color-scheme:dark){.parenthesis{fill:#fff}}</style><path fill="#9135ff" d="M40.151 45.71c-.663.844-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.493c-.92 0-1.457-1.04-.92-1.788l7.479-10.471c1.07-1.498 0-3.578-1.842-3.578H15.443c-.92 0-1.456-1.04-.92-1.788l9.696-13.576c.213-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.472c-1.07 1.497 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.087.89 1.83L40.153 45.712z"/><mask id="a" width="48" height="47" x="14" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M40.047 45.71c-.663.843-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.389c-.92 0-1.457-1.04-.92-1.788l7.479-10.472c1.07-1.497 0-3.578-1.842-3.578H15.34c-.92 0-1.456-1.04-.92-1.788l9.696-13.575c.213-.297.556-.474.92-.474H53.93c.92 0 1.456 1.04.92 1.788L47.37 13.03c-1.07 1.498 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.088.89 1.831L40.049 45.712z"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#eee6ff" rx="5.508" ry="14.704" transform="rotate(269.814 20.96 11.29)scale(-1 1)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#eee6ff" rx="10.399" ry="29.851" transform="rotate(89.814 -16.902 -8.275)scale(1 -1)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#8900ff" rx="5.508" ry="30.487" transform="rotate(89.814 -19.197 -7.127)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.928 4.177)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.738 5.52)scale(1 -1)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#eee6ff" rx="14.072" ry="22.078" transform="rotate(93.35 31.245 55.578)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx="14.592" cy="9.743" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(39.51 14.592 9.743)"/></g><g filter="url(#k)"><ellipse cx="61.728" cy="-5.321" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 61.728 -5.32)"/></g><g filter="url(#l)"><ellipse cx="55.618" cy="7.104" fill="#00c2ff" rx="5.971" ry="9.665" transform="rotate(37.892 55.618 7.104)"/></g><g filter="url(#m)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#n)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#o)"><ellipse cx="49.857" cy="30.678" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 49.857 30.678)"/></g><g filter="url(#p)"><ellipse cx="52.623" cy="33.171" fill="#00c2ff" rx="5.971" ry="15.297" transform="rotate(37.892 52.623 33.17)"/></g></g><path d="M6.919 0c-9.198 13.166-9.252 33.575 0 46.789h6.215c-9.25-13.214-9.196-33.623 0-46.789zm62.424 0h-6.215c9.198 13.166 9.252 33.575 0 46.789h6.215c9.25-13.214 9.196-33.623 0-46.789" class="parenthesis"/><defs><filter id="b" width="60.045" height="41.654" x="-5.564" y="16.92" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-40.407" y="-6.762" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="d" width="79.355" height="29.4" x="-35.435" y="2.801" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="e" width="79.579" height="29.4" x="-30.84" y="20.8" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="f" width="79.579" height="29.4" x="-29.307" y="21.949" color-interpolation-filters="sRGB" filterUnits="usLine truncated

After

Width:  |  Height:  |  Size: 8.5 KiB

-197
View File
@@ -1,197 +0,0 @@
// Single place that knows how to talk to archied. Every feature folder goes
// through api.* below, and every api.* method goes through send(), so the CSRF
// header, the Content-Type, the request timeout, and the error shape live in
// this one file. ui/test/api-client.test.js asserts that: it fails if a second
// fetch() call appears here, and it fails if any method omits a header the
// server requires.
import { randomUUID } from "./uuid.jsx";
import { streamStateFor } from "./stream-state.js";
// DEFAULT_TIMEOUT_MS bounds a request so a daemon that accepts the connection
// but never answers cannot leave the UI in a loading state with no way back.
// The retry affordances rely on fetch settling, so bound it.
const DEFAULT_TIMEOUT_MS = 15000;
// qs builds a query string, omitting empty values so the server sees an
// absent filter rather than an empty one.
function qs(params) {
const q = new URLSearchParams();
for (const [k, v] of Object.entries(params || {})) {
if (v !== "" && v != null) q.set(k, v);
}
const s = q.toString();
return s ? `?${s}` : "";
}
// errorMessage prefers what the server actually said. archied answers these
// with http.Error, i.e. a plain-text reason -- "task is not awaiting
// approval", "max retries reached (3/3)", "Content-Type must be
// application/json" -- and discarding it in favour of "409 Conflict" throws
// away the only part an operator can act on.
async function errorMessage(res) {
try {
const body = (await res.text()).trim();
if (body) return body.split("\n")[0].slice(0, 200);
} catch {
// Body already consumed or unreadable; fall through to the status.
}
return `${res.status} ${res.statusText}`;
}
export class ApiError extends Error {
constructor(message, status) {
super(message);
this.status = status;
}
}
// classifyActionError turns a failed operator action into a rendering
// decision. archied's own handlers already return distinguishable status
// codes for a refused mutation (400/403/409/415 -- bad input, missing CSRF,
// cross-origin, conflicting state, a body that is not JSON) versus a broken
// one (5xx, or no status at all when fetch itself failed -- network drop,
// timeout); 401 additionally means the session -- archied's own token cookie,
// or an upstream forward-auth proxy sitting in front of it -- has expired
// rather than that the action was rejected or the daemon is unwell.
export function classifyActionError(err) {
const status = err instanceof ApiError ? err.status : undefined;
const message = err?.message || "Action failed";
if (status === 401) return { kind: "session-expired", message };
if (status >= 400 && status < 500) return { kind: "refused", message };
return { kind: "broken", message };
}
// send is the only fetch() in the dashboard. It converts a non-ok response
// into an ApiError carrying the server's own explanation and a usable status,
// and hands the raw Response back so the streaming caller can read the body
// itself.
async function send(path, init) {
const res = await fetch(path, init);
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res;
}
// request performs a JSON request. Every mutating method must declare a JSON
// body: archied's handlers run authorizeTaskMutation first, and it answers 415
// unless Content-Type is application/json -- including for a mutation that has
// no body to send, because that requirement is what makes a simple cross-origin
// form post inexpressible. Sending the header on every mutation, rather than
// only where a payload happens to exist, is what keeps a bodyless DELETE or
// approve from being refused.
async function request(path, { method = "GET", body, timeoutMs = DEFAULT_TIMEOUT_MS, parse = true } = {}) {
const headers = { Accept: "application/json" };
const init = { method, headers, signal: AbortSignal.timeout(timeoutMs) };
if (method !== "GET") {
headers["Content-Type"] = "application/json";
headers["X-Archie-CSRF"] = "1";
}
if (body !== undefined) init.body = JSON.stringify(body);
const res = await send(path, init);
return parse ? res.json() : undefined;
}
export const api = {
summary: () => request("/api/summary"),
tasks: () => request("/api/tasks"),
taskMeta: () => request("/api/task-meta"),
task: (id) => request(`/api/tasks/${id}`),
taskAttempts: (id) => request(`/api/tasks/${id}/attempts`),
taskChanges: (id, params) => request(`/api/tasks/${id}/changes` + qs(params)),
taskDebug: (id, params) => request(`/api/tasks/${id}/debug` + qs(params)),
taskAction: (id, action) => request(`/api/tasks/${id}/action`, { method: "POST", body: { action } }),
setup: () => request("/api/setup"),
capabilities: () => request("/api/capabilities"),
workflows: () => request("/api/workflows"),
workRequest: (workRequest) => request("/api/work-requests", { method: "POST", body: workRequest }),
skills: () => request("/api/skills"),
channels: () => request("/api/channels"),
curators: () => request("/api/curators"),
channelReload: (id) => request(`/api/channels/${encodeURIComponent(id)}/reload`, { method: "POST", body: {} }),
config: () => request("/api/config"),
version: () => request("/api/version"),
configUpdate: (updates) => request("/api/config", { method: "PATCH", body: { updates } }),
configRepoUpdate: (owner, name, field, value) =>
request(`/api/config/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, { method: "PATCH", body: { field, value } }),
configReset: (key) => request("/api/config/reset", { method: "POST", body: { key } }),
logs: (params) => request("/api/logs" + qs(params)),
taskLogs: (id, params) => request(`/api/tasks/${id}/logs` + qs(params)),
// A download is a navigation, not a fetch: the browser must own the
// Content-Disposition filename and stream the body to disk rather than hold
// a whole log in memory. The URL builder is the client-side contract, and
// base/log-row's sibling module keeps it beside the panel that uses it.
taskLogDownloadURL: (id, attempt) => `/api/tasks/${id}/logs/download` + (attempt == null ? "" : `?attempt=${attempt}`),
captures: (limit) => request("/api/captures" + qs({ limit })),
mappings: () => request("/api/mappings"),
mappingCreate: (mapping) => request("/api/mappings", { method: "POST", body: mapping }),
mappingUpdate: (id, mapping) => request(`/api/mappings/${id}`, { method: "PATCH", body: mapping }),
// A delete answers 204, so there is no body to parse.
mappingDelete: (id) => request(`/api/mappings/${id}`, { method: "DELETE", parse: false }),
mappingPreview: (captureId, fields) => request("/api/mappings/preview", { method: "POST", body: { capture_id: captureId, fields } }),
bindings: () => request("/api/bindings"),
bindingCreate: (binding) => request("/api/bindings", { method: "POST", body: binding }),
bindingUpdate: (id, binding) => request(`/api/bindings/${id}`, { method: "PATCH", body: binding }),
bindingDelete: (id) => request(`/api/bindings/${id}`, { method: "DELETE", parse: false }),
bindingApprove: (id) => request(`/api/bindings/${id}/approve`, { method: "POST" }),
chatSessions: () => request("/api/chat/sessions"),
chatMessages: (id) => request(`/api/chat/sessions/${encodeURIComponent(id)}/messages`),
chatTurns: (id) => request(`/api/chat/sessions/${encodeURIComponent(id)}/turns`),
chatCancel: (sessionID) => request("/api/chat/cancel", { method: "POST", body: { session_id: sessionID } }),
chatMessage: (channelID, text) =>
request("/api/chat/message", {
method: "POST",
body: { channel_id: channelID, source_id: randomUUID(), text, page: location.hash.slice(1) || "/" },
}),
chatPersona: (sessionID, name) => request("/api/chat/persona", { method: "POST", body: { session_id: sessionID, name } }),
chatUpdate: () => request("/api/chat/update"),
chatUpdateDefer: (snapshot) => request("/api/chat/update/defer", { method: "POST", body: { snapshot } }),
// Installing restarts archied, so it is allowed far longer than a normal
// request before the UI gives up.
chatUpdateInstall: (snapshot) => request("/api/chat/update/install", { method: "POST", body: { snapshot }, timeoutMs: 120000 }),
chatDangerous: () => request("/api/chat/dangerous"),
chatDangerousRequest: (kind, spec) =>
request(`/api/chat/dangerous/${encodeURIComponent(kind)}`, { method: "POST", body: { spec } }),
chatDangerousDecision: (id, decision) =>
request(`/api/chat/dangerous/${encodeURIComponent(id)}/decision`, { method: "POST", body: { decision } }),
// A server-sent event stream cannot be parsed as JSON and outlives a normal
// request, so the caller owns the abort controller and the timeout, and
// reads the body itself. Only the URL, headers, and failure shape are shared.
chatStream: (payload, { signal } = {}) =>
send("/api/chat/stream", {
method: "POST",
headers: { Accept: "text/event-stream", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
body: JSON.stringify(payload),
signal,
}),
};
/**
* Subscribe to archied's event stream. Returns an unsubscribe function.
* Reconnection is the browser's job via EventSource, but a closed stream is
* surfaced to the caller so the UI can show it rather than silently freezing.
*/
export function subscribeEvents(onEvent, onStateChange) {
const src = new EventSource("/events");
src.onopen = () => onStateChange?.("live");
src.onerror = () => onStateChange?.("reconnecting");
src.onmessage = (e) => {
try {
onEvent(JSON.parse(e.data));
} catch {
/* a malformed frame should not kill the stream */
}
};
return () => src.close();
}
export function subscribeLogs(onEntry, onStateChange) {
const src = new EventSource("/api/logs/stream");
src.onopen = () => onStateChange?.("live");
// onerror fires both for a drop the browser will retry and for one it has
// given up on; readyState is what tells them apart.
src.onerror = () => onStateChange?.(streamStateFor(src.readyState));
src.onmessage = (event) => {
try { onEntry(JSON.parse(event.data)); } catch { /* malformed log frame */ }
};
return () => src.close();
}
-32
View File
@@ -1,32 +0,0 @@
/**
* Display formatting shared across the dashboard pages. Pure functions: no
* DOM, no framework.
*/
/** Humanised relative time: "2 min ago". Raw timestamps make people do maths. */
export function ago(value) {
if (!value) return "—";
const then = value instanceof Date ? value : new Date(value);
const secs = Math.floor((Date.now() - then.getTime()) / 1000);
if (!Number.isFinite(secs)) return "—";
if (secs < 45) return "just now";
const units = [
["min", 60],
["hr", 3600],
["day", 86400],
["wk", 604800],
];
let label = "min",
size = 60;
for (const [l, s] of units) {
if (secs >= s) [label, size] = [l, s];
}
const n = Math.floor(secs / size);
return `${n} ${label}${n === 1 ? "" : "s"} ago`;
}
/** Compact number: 2_400_000 -> "2.4M". Long digit strings do not scan. */
export function compact(n) {
if (n == null || Number.isNaN(n)) return "—";
return new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 }).format(n);
}
-90
View File
@@ -1,90 +0,0 @@
import { h } from "preact";
/**
* Arc gauge for a single headline percentage.
*
* A percentage that decides whether you need to act deserves more than a line
* of text -- the arc is readable at a glance from across a room, which a
* number is not. Colour follows the value, so "is this bad" is answered before
* the digits are read.
*/
export function Gauge({ value, label, size = 168 }) {
const pct = Math.max(0, Math.min(100, Number(value) || 0));
const stroke = pct >= 90 ? "var(--ok)" : pct >= 70 ? "var(--warn)" : "var(--danger)";
// 240-degree arc, opening downward, so the value reads left-to-right.
const r = 62;
const cx = size / 2;
const cy = size / 2;
const sweep = 240;
const start = 150;
const circumference = 2 * Math.PI * r * (sweep / 360);
const arc = (from, deg) => {
const a0 = (from * Math.PI) / 180;
const a1 = ((from + deg) * Math.PI) / 180;
const large = deg > 180 ? 1 : 0;
return [
`M ${cx + r * Math.cos(a0)} ${cy + r * Math.sin(a0)}`,
`A ${r} ${r} 0 ${large} 1 ${cx + r * Math.cos(a1)} ${cy + r * Math.sin(a1)}`,
].join(" ");
};
return (
<div className="gauge-wrap">
<svg className="gauge" viewBox={`0 0 ${size} ${size * 0.78}`} role="img" aria-label={`${label}: ${pct}%`}>
<path d={arc(start, sweep)} fill="none" stroke="var(--border)" stroke-width="12" stroke-linecap="round" />
<path
d={arc(start, sweep)}
fill="none"
stroke={stroke}
stroke-width="12"
stroke-linecap="round"
stroke-dasharray={circumference}
stroke-dashoffset={circumference * (1 - pct / 100)}
className="gauge-value"
/>
</svg>
<div className="gauge-center">
<div className="gauge-pct">{`${Math.round(pct)}%`}</div>
<div className="gauge-label">{label}</div>
</div>
</div>
);
}
/**
* Segmented proportional bar with a legend.
*
* segments: [{ label, value, kind }] where kind maps to a status token.
* Used for budget composition -- what is spent, committed and still free --
* because three related quantities are easier to compare in one bar than in
* three separate numbers.
*/
export function SegmentBar({ segments }) {
const total = segments.reduce((a, s) => a + (s.value || 0), 0) || 1;
return (
<div>
<div className="segbar">
{segments
.filter((s) => s.value > 0)
.map((s) => (
<span
key={s.label}
className={`segbar-part segbar-${s.kind || "idle"}`}
style={`width:${((s.value / total) * 100).toFixed(1)}%`}
title={`${s.label}: ${s.value}`}
/>
))}
</div>
<div className="segbar-legend">
{segments.map((s) => (
<span className="segbar-key" key={s.label}>
<span className={`segbar-dot segbar-${s.kind || "idle"}`} />
{s.label}
</span>
))}
</div>
</div>
);
}
-64
View File
@@ -1,64 +0,0 @@
import { h } from "preact";
/**
* Icon set.
*
* A single stroked 24-grid system rather than Unicode glyphs: glyphs render at
* different weights and baselines per platform, cannot inherit stroke width,
* and have no consistent optical size. Every icon here shares the same grid,
* stroke and cap style, so a row of them lines up.
*/
const paths = {
dashboard: '<rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/>',
chat: '<path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v7a2.5 2.5 0 0 1-2.5 2.5H11l-4.5 4v-4.1A2.5 2.5 0 0 1 4 12.5z"/><path d="M8 8h8M8 11h5"/>',
tasks: '<path d="M9 6h11M9 12h11M9 18h11"/><path d="M4 6l1 1 2-2M4 12l1 1 2-2M4 18l1 1 2-2"/>',
logs: '<path d="M4 5h16M4 10h16M4 15h10M4 20h7"/>',
skills: '<path d="M12 3l2.6 5.6 6.1.8-4.5 4.2 1.2 6-5.4-3-5.4 3 1.2-6L3.3 9.4l6.1-.8z"/>',
workflows: '<path d="M4 7h6a3 3 0 0 1 3 3v4a3 3 0 0 0 3 3h4"/><path d="M17 4l3 3-3 3"/><path d="M7 21l-3-3 3-3"/>',
memory: '<circle cx="12" cy="12" r="3.2"/><path d="M12 3v3.4M12 17.6V21M3 12h3.4M17.6 12H21M5.6 5.6l2.4 2.4M16 16l2.4 2.4M18.4 5.6L16 8M8 16l-2.4 2.4"/>',
channels: '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3.5 7l8.5 6 8.5-6"/>',
curators: '<circle cx="12" cy="12" r="8"/><path d="M12 8v4l3 2"/>',
captures: '<path d="M12 3v11M12 14l-4-4M12 14l4-4"/><path d="M4 14v4a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-4"/>',
mappings: '<circle cx="5" cy="7" r="2"/><circle cx="5" cy="17" r="2"/><circle cx="19" cy="12" r="2"/><path d="M7 7l10 5M7 17l10-5"/>',
bindings: '<rect x="3" y="9" width="8" height="6" rx="2.5"/><rect x="13" y="9" width="8" height="6" rx="2.5"/><path d="M9 12h6"/>',
settings: '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-2.9 1.2V21a2 2 0 1 1-4 0v-.1A1.7 1.7 0 0 0 7 19.4a1.7 1.7 0 0 0-1.9.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1A1.7 1.7 0 0 0 3 15H3a2 2 0 1 1 0-4h.1A1.7 1.7 0 0 0 4.6 7a1.7 1.7 0 0 0-.3-1.9l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1A1.7 1.7 0 0 0 9 3.6V3a2 2 0 1 1 4 0v.1A1.7 1.7 0 0 0 15 4.6h.1a1.7 1.7 0 0 0 1.9-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.9V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/>',
search: '<circle cx="11" cy="11" r="7"/><path d="M20 20l-3.6-3.6"/>',
moon: '<path d="M20 14.5A8.5 8.5 0 0 1 9.5 4a8.5 8.5 0 1 0 10.5 10.5z"/>',
sun: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4"/>',
refresh: '<path d="M20 11a8 8 0 1 0-1.2 5.2"/><path d="M20 4v7h-7"/>',
bell: '<path d="M18 9a6 6 0 1 0-12 0c0 6-2 7-2 7h16s-2-1-2-7"/><path d="M13.7 20a2 2 0 0 1-3.4 0"/>',
trendUp: '<path d="M4 17L10 11l4 4 6-6"/><path d="M14 7h6v6"/>',
trendDown: '<path d="M4 7l6 6 4-4 6 6"/><path d="M14 17h6v-6"/>',
check: '<path d="M4.5 12.5l5 5 10-11"/>',
close: '<path d="M6 6l12 12M18 6L6 18"/>',
"message-circle-plus": '<path d="M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"/><path d="M8 12h8"/><path d="M12 8v8"/>',
help: '<circle cx="12" cy="12" r="9"/><path d="M9.6 9.4a2.5 2.5 0 1 1 3.3 2.4c-.6.2-.9.8-.9 1.4v.4"/><path d="M12 17.2h.01"/>',
};
/**
* Icon draws one glyph from the set. size is the rendered box; the grid is
* always 24 so stroke weight stays optically consistent at any size.
*
* The glyph bodies are the `paths` strings above, injected as raw SVG. They are
* in-repo constants and Preact cannot turn markup into elements, so re-authoring
* twenty multi-element glyphs as JSX would trade a data table for code without
* changing a single drawn pixel.
*/
export function Icon({ name, size = 18, className = "" }) {
return (
<svg
viewBox="0 0 24 24"
width={size}
height={size}
fill="none"
stroke="currentColor"
stroke-width="1.6"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
className={`ico ${className}`.trim()}
dangerouslySetInnerHTML={{ __html: paths[name] || paths.dashboard }}
/>
);
}
-65
View File
@@ -1,65 +0,0 @@
import { h } from "preact";
/**
* Shared log-entry rendering. Both the daemon-wide log page
* (ui/src/logs/logs.jsx) and a task's own attempt log
* (ui/src/tasks/task-logs.jsx) render the same Entry shape from
* internal/logging, so the row markup lives here rather than being
* duplicated a second time -- see CLAUDE.md's "extract to base on the
* second distinct consumer".
*/
// The level filter vocabulary. Server-side level filtering takes a CSV of
// levels (`splitCSV` in internal/webui/api_tasks_logs.go), so the combined
// options are a wire concern too, not a display choice. It lives here because
// both the daemon log page and a task attempt's log pane filter by level.
export const LOG_LEVELS = [
{ value: "", label: "All levels" },
{ value: "ERROR", label: "Errors" },
{ value: "WARN,ERROR", label: "Warnings and errors" },
{ value: "INFO,WARN,ERROR", label: "Info and above" },
{ value: "DEBUG", label: "Debug only" },
];
export function levelKind(level) {
switch ((level || "").toUpperCase()) {
case "ERROR":
return "danger";
case "WARN":
return "warn";
case "DEBUG":
return "idle";
default:
return "info";
}
}
export function LogRow({ entry }) {
const fields = entry.fields || {};
return (
<div className={`log-row log-${levelKind(entry.level)}`}>
<span className="log-time mono">{shortTime(entry.time)}</span>
<span className="log-level">{(entry.level || "info").toUpperCase()}</span>
<span className="log-body">
<span className="log-msg">{entry.message || entry.msg || ""}</span>
{Object.entries(fields).map(([k, v]) => (
<span className="log-field" key={k}>
<span className="log-field-key">{k}</span>
{String(fmtValue(v))}
</span>
))}
</span>
</div>
);
}
export function fmtValue(v) {
if (v == null) return "";
return typeof v === "object" ? JSON.stringify(v) : v;
}
export function shortTime(value) {
const d = value instanceof Date ? value : new Date(value);
if (Number.isNaN(d.getTime())) return "--:--:--";
return d.toTimeString().slice(0, 8);
}
-13
View File
@@ -1,13 +0,0 @@
import { h } from "preact";
/**
* Status pill: a small labeled badge whose color follows a semantic kind
* (ok/warn/danger/info/idle -- see css/pill.css). Extracted from 11
* independent, byte-identical local copies (tasks, logs, mappings,
* captures, settings, update-status, skills, dashboard, memory, channels,
* curators) per organisation.md's "extract on the second distinct
* consumer" rule -- archie-core-mlro.
*/
export function Pill({ text, kind = "idle" }) {
return <span className={`pill pill-${kind}`}>{text}</span>;
}
-68
View File
@@ -1,68 +0,0 @@
import { h } from "preact";
import { Icon } from "./icons.jsx";
/**
* A KPI tile: label, big value, trend against a stated comparison window, and
* a sparkline. The comparison line is not decoration -- a number without a
* baseline cannot be acted on, so `compare` is required.
*
* trend > 0 renders as an increase. `goodDirection` says whether that is good,
* because rising latency and rising success rate are not the same news.
*
* The headline value is rendered whatever its type, including 0 and "": a tile
* that showed a label and a comparison line with no number above them read as
* a broken dashboard on every fresh install.
*/
export function StatTile({ label, value, unit, trend, compare, series = [], goodDirection = "up" }) {
const dir = trend == null ? null : trend >= 0 ? "up" : "down";
const good = dir == null ? null : dir === goodDirection;
return (
<div className="card stat">
<div className="stat-head">
<span className="stat-label">{label}</span>
{dir ? (
<span className={`stat-trend ${good ? "up" : "down"}`}>
<Icon name={dir === "up" ? "trendUp" : "trendDown"} size={13} />
{`${Math.abs(trend).toFixed(1)}%`}
</span>
) : null}
</div>
<div className="stat-value">
{value}
{unit ? <span className="stat-unit">{unit}</span> : null}
</div>
{compare ? <div className="stat-compare">{compare}</div> : null}
{series.length > 1 ? <Sparkline series={series} stroke={good === false ? "var(--danger)" : "var(--ok)"} /> : null}
</div>
);
}
/**
* Inline SVG sparkline. Shows shape, not exact values -- the tile's headline
* number carries the precision.
*/
export function Sparkline({ series, stroke = "var(--ok)", width = 220, height = 34 }) {
const max = Math.max(...series, 1);
const min = Math.min(...series, 0);
const span = max - min || 1;
const step = series.length > 1 ? width / (series.length - 1) : width;
const points = series
.map((v, i) => `${(i * step).toFixed(1)},${(height - ((v - min) / span) * height).toFixed(1)}`)
.join(" ");
return (
<svg className="spark" viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none" aria-hidden="true">
<polyline
points={points}
fill="none"
stroke={stroke}
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
vector-effect="non-scaling-stroke"
/>
</svg>
);
}
-24
View File
@@ -1,24 +0,0 @@
// What an EventSource error actually means.
//
// In base/ rather than logs/ because this is EventSource semantics, not a
// logs concept, and base must not import a feature folder.
//
// EventSource fires onerror both for a dropped connection it will retry and
// for one it has given up on. Reporting "reconnecting" for both left the logs
// page showing a permanent amber "reconnecting" pill against a stream that had
// stopped for good, next to text claiming live logs were still arriving
// (archie-core-c5bz).
//
// readyState is the difference: CONNECTING means a retry is scheduled, CLOSED
// means the browser will not try again.
/**
* streamStateFor maps an EventSource readyState to the state the UI reports:
* "live", "reconnecting", or "unavailable".
*/
export function streamStateFor(readyState) {
// Numeric literals rather than EventSource.* so this is testable without one.
if (readyState === 0) return "reconnecting";
if (readyState === 1) return "live";
return "unavailable";
}
-104
View File
@@ -1,104 +0,0 @@
// Central lifecycle vocabulary for the dashboard. The backend is the source of
// truth: /api/task-meta returns the statuses (label, pill severity, "needs you"
// grouping) and operator actions (label, button variant, confirm prompt). This
// module fetches that catalog and exposes the accessors the rest of the UI
// reads, so no surface keeps a hand-synced copy of the vocabulary.
//
// The defaults below are a freeze-dried snapshot that render immediately and
// keep working when archied is unreachable; loadTaskMeta() replaces them with
// the live catalog as soon as it arrives. They must match the backend catalog
// so drawing the page never flashes a stale label.
//
// loadTaskMeta() is called once at boot by main.jsx, and that call is the whole
// mechanism: without it these accessors serve the snapshot forever and a
// catalogue change on the server never reaches the browser, however true the
// paragraph above reads.
//
// The dashboard draws a line here between two kinds of vocabulary. Anything
// that is *presentation* -- a status's label, pill severity and "needs you"
// grouping, or a control's label and confirm prompt -- is served, because the
// server owns the words as well as the ids. A wire id the daemon produces and
// the dashboard merely labels is mirrored instead, with a literal pin on each
// side so a one-sided rename fails a test rather than drifting quietly: see
// tasks/changed-files.jsx (FILE_STATUS) and tasks/attempt-config.jsx
// (CONFIG_SCHEMA).
import { api } from "./api.jsx";
const DEFAULT_STATUSES = [
{ id: "queued", label: "Queued", kind: "idle" },
{ id: "running", label: "Working", kind: "info" },
{ id: "waiting_human", label: "Waiting for you", kind: "warn", needs_you: true },
{ id: "pr_open", label: "In review", kind: "ok" },
{ id: "merged", label: "Merged", kind: "ok" },
{ id: "parked", label: "Parked", kind: "warn", needs_you: true },
{ id: "dead", label: "Stopped (too many retries)", kind: "danger" },
{ id: "rejected", label: "Rejected", kind: "danger" },
{ id: "closed_wont_do", label: "Won't do", kind: "idle" },
];
const DEFAULT_ACTIONS = [
{ id: "cancel", label: "Cancel", kind: "quiet", confirm: `Cancel "{title}"? This closes the forge issue.` },
{ id: "stop", label: "Stop", kind: "primary", confirm: `Stop "{title}"? Recoverable work will remain parked.` },
{ id: "approve", label: "Approve", kind: "primary" },
{ id: "reject", label: "Reject", kind: "quiet", confirm: `Reject "{title}"? This closes the forge issue.` },
{ id: "retry", label: "Retry", kind: "primary" },
{ id: "abandon", label: "Abandon", kind: "quiet", confirm: `Abandon "{title}"? This closes the forge issue.` },
{ id: "archive", label: "Archive", kind: "quiet", confirm: `Archive the local record for "{title}"?` },
{ id: "open_pr", label: "Open PR", kind: "link" },
{ id: "open_issue", label: "Open issue", kind: "link" },
];
let statuses = [...DEFAULT_STATUSES];
let actions = [...DEFAULT_ACTIONS];
let statusById = new Map(statuses.map((s) => [s.id, s]));
let actionById = new Map(actions.map((a) => [a.id, a]));
function rebuildIndexes() {
statusById = new Map(statuses.map((s) => [s.id, s]));
actionById = new Map(actions.map((a) => [a.id, a]));
}
// loadTaskMeta upgrades the dashboard from the server catalog. It never throws:
// a failed fetch keeps the defaults so the UI still renders.
export async function loadTaskMeta() {
try {
const data = await api.taskMeta();
if (Array.isArray(data?.statuses)) statuses = data.statuses;
if (Array.isArray(data?.actions)) actions = data.actions;
rebuildIndexes();
} catch {
// archied unreachable or not yet serving this route; keep the defaults.
}
}
// statusLabel is the human-readable name for a lifecycle status.
export function statusLabel(id) {
return statusById.get(id)?.label || id || "Unknown";
}
// statusKind is the pill severity token (idle, info, ok, warn, danger).
export function statusKind(id) {
return statusById.get(id)?.kind || "idle";
}
// statusList returns every known lifecycle status in display order.
export function statusList() {
return statuses;
}
// statusIds returns every known lifecycle status id, in display order.
export function statusIds() {
return statuses.map((s) => s.id);
}
// attentionStatusIds is the set of statuses that count toward the "Needs you"
// filter (work that is waiting on a human).
export function attentionStatusIds() {
return new Set(statuses.filter((s) => s.needs_you).map((s) => s.id));
}
// actionFor returns the presentation metadata for an operator control, or null
// if the backend has never seen it.
export function actionFor(id) {
return actionById.get(id) || null;
}
-20
View File
@@ -1,20 +0,0 @@
// randomUUID keeps client-generated identifiers working on HTTP deployments.
// crypto.randomUUID is restricted to secure contexts, while getRandomValues
// remains available on the older browsers and plain-HTTP origins Archie
// supports.
export function randomUUID(cryptoAPI = globalThis.crypto) {
if (typeof cryptoAPI?.randomUUID === "function") return cryptoAPI.randomUUID();
const bytes = new Uint8Array(16);
if (typeof cryptoAPI?.getRandomValues === "function") {
cryptoAPI.getRandomValues(bytes);
} else {
for (let index = 0; index < bytes.length; index += 1) {
bytes[index] = Math.floor(Math.random() * 256);
}
}
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
}
-46
View File
@@ -1,46 +0,0 @@
import { h } from "preact";
import { Pill } from "../base/pill.jsx";
/**
* Pure rendering logic for the bindings editor, split out from
* bindings.jsx so it is unit-testable without the page's fetch wiring,
* mirroring mappings/mapping-editor.jsx.
*/
const STATUS_LABELS = {
draft: "draft",
pending_approval: "pending approval",
armed: "armed",
};
const STATUS_KINDS = {
draft: "idle",
pending_approval: "warn",
armed: "ok",
};
/** Renders a binding's Status as a labeled pill -- draft/pending_approval/armed. */
export function StatusPill({ status }) {
return <Pill text={STATUS_LABELS[status] || status} kind={STATUS_KINDS[status] || "idle"} />;
}
/** One saved binding's summary row for the bindings list. */
export function BindingRow({ binding: b, onEdit, onApprove, onDelete }) {
const repoPin = b.owner && b.repo ? `${b.owner}/${b.repo}` : "—";
return (
<tr>
<td>{b.name}</td>
<td className="mono">{b.matcher?.source || "—"}</td>
<td>{b.workflow}</td>
<td className="mono">{repoPin}</td>
<td><StatusPill status={b.status} /></td>
<td>
<button className="btn btn-small" type="button" onClick={() => onEdit?.(b)}>Edit</button>
{b.status === "pending_approval" && (
<button className="btn btn-small btn-primary" type="button" onClick={() => onApprove?.(b)}>Approve</button>
)}
<button className="btn btn-small" type="button" onClick={() => onDelete?.(b)}>Delete</button>
</td>
</tr>
);
}
-32
View File
@@ -1,32 +0,0 @@
/* Playbook binding editor: tie a matcher, a field mapping, and a
workflow together, gated by an explicit approval state machine. */
.binding-form {
margin-bottom: var(--sp-4);
padding: var(--sp-4);
}
.binding-form-row {
display: flex;
flex-direction: column;
gap: var(--sp-1);
margin-bottom: var(--sp-3);
font-size: var(--text-sm);
color: var(--fg-subtle);
}
.binding-input,
.binding-select {
padding: var(--sp-2);
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
background: var(--bg-raised);
color: var(--fg);
font: inherit;
}
.binding-error {
color: var(--danger, #e5484d);
font-size: var(--text-sm);
margin-bottom: var(--sp-3);
}
-221
View File
@@ -1,221 +0,0 @@
import { h } from "preact";
import { useState, useEffect } from "preact/hooks";
import "./bindings.css";
import { api } from "../base/api.jsx";
import { BindingRow } from "./binding-editor.jsx";
export function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
/**
* Playbook bindings (t2db.8): tie a matcher + payload mapping + workflow
* together, with a draft -> pending_approval -> armed state machine so
* nothing self-arms. See docs/architecture/bindings.md and
* docs/prds/payload-field-mapping.md. Owner/Repo optionally pin a
* multi-repo deployment's dispatch target (archie-core-t2db.8's backend
* fix, commit ac42f64).
*/
export function bindingsPage(query) {
return <BindingsApp query={query} />;
}
function emptyEditor() {
return {
id: null,
name: "",
source: "",
mappingId: "",
workflow: "",
owner: "",
repo: "",
secret: "",
actionError: null,
};
}
function BindingsApp({ query }) {
const [bindings, setBindings] = useState([]);
const [mappings, setMappings] = useState([]);
const [workflows, setWorkflows] = useState([]);
const [loadError, setLoadError] = useState(null);
const [editor, setEditor] = useState(null);
const load = async () => {
try {
const [bRes, mRes, wRes] = await Promise.all([api.bindings(), api.mappings(), api.workflows()]);
setBindings(bRes.bindings || []);
setMappings(mRes.mappings || []);
setWorkflows((wRes.definitions || []).filter((d) => d.enabled));
setLoadError(null);
} catch (err) {
setLoadError(String(err.message || err));
}
};
useEffect(() => {
load();
}, []);
const startCreate = () => {
setEditor(emptyEditor());
};
const startEdit = (b) => {
setEditor({
id: b.id,
name: b.name,
source: b.matcher?.source || "",
mappingId: b.mapping_id ? String(b.mapping_id) : "",
workflow: b.workflow || "",
owner: b.owner || "",
repo: b.repo || "",
secret: "",
actionError: null,
});
};
const cancel = () => setEditor(null);
const save = async () => {
const body = {
name: editor.name,
matcher: { source: editor.source },
mapping_id: Number(editor.mappingId) || 0,
workflow: editor.workflow,
owner: editor.owner,
repo: editor.repo,
secret: editor.secret,
};
try {
if (editor.id) {
await api.bindingUpdate(editor.id, body);
} else {
await api.bindingCreate(body);
}
setEditor(null);
await load();
} catch (err) {
setEditor((prev) => ({ ...prev, actionError: String(err.message || err) }));
}
};
const approve = async (b) => {
try {
await api.bindingApprove(b.id);
await load();
} catch (err) {
setLoadError(String(err.message || err));
}
};
const remove = async (b) => {
if (!window.confirm(`Delete binding "${b.name}"?`)) return;
try {
await api.bindingDelete(b.id);
await load();
} catch (err) {
setLoadError(String(err.message || err));
}
};
const renderList = () => (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Playbook bindings</h1>
<p className="page-sub">Tie a matcher, a field mapping, and a workflow together. New and edited bindings need explicit approval before they can fire.</p>
</div>
<div className="page-actions">
<button className="btn btn-primary" type="button" onClick={startCreate}>New binding</button>
</div>
</div>
{loadError ? (
<Empty title="Cannot reach archied" detail={loadError} />
) : bindings.length ? (
<div className="card">
<div className="table-scroll">
<table className="table">
<thead>
<tr>
{["Name", "Source", "Workflow", "Repo pin", "Status", ""].map((h, i) => (
<th key={i}>{h}</th>
))}
</tr>
</thead>
<tbody>
{bindings.map((b) => (
<BindingRow key={b.id} binding={b} onEdit={() => startEdit(b)} onApprove={() => approve(b)} onDelete={() => remove(b)} />
))}
</tbody>
</table>
</div>
</div>
) : (
<Empty title="No bindings yet" detail="Create one from a saved field mapping to turn a captured webhook into a workflow." />
)}
</div>
);
const renderEditor = () => (
<div>
<div className="page-head">
<div>
<h1 className="page-title">{editor.id ? "Edit binding" : "New binding"}</h1>
</div>
<div className="page-actions">
<button className="btn" type="button" onClick={cancel}>Cancel</button>
<button className="btn btn-primary" type="button" onClick={save}>Save</button>
</div>
</div>
{editor.actionError && <div className="binding-error">{editor.actionError}</div>}
<div className="card binding-form">
<label className="binding-form-row">
Name
<input className="binding-input" value={editor.name} onInput={(e) => setEditor((p) => ({ ...p, name: e.target.value }))} />
</label>
<label className="binding-form-row">
Source (the path segment senders POST to, e.g. "sentry")
<input className="binding-input" value={editor.source} onInput={(e) => setEditor((p) => ({ ...p, source: e.target.value }))} />
</label>
<label className="binding-form-row">
Field mapping
<select className="binding-select" value={editor.mappingId} onChange={(e) => setEditor((p) => ({ ...p, mappingId: e.target.value }))}>
<option value="">— pick a saved mapping —</option>
{mappings.map((m) => (
<option key={m.id} value={m.id}>{m.name}</option>
))}
</select>
</label>
<label className="binding-form-row">
Workflow
<select className="binding-select" value={editor.workflow} onChange={(e) => setEditor((p) => ({ ...p, workflow: e.target.value }))}>
<option value="">— pick a workflow —</option>
{workflows.map((w) => (
<option key={w.id} value={w.id}>{w.name}</option>
))}
</select>
</label>
<label className="binding-form-row">
Repo pin -- owner (optional; leave both blank for the single-configured-repo default)
<input className="binding-input" value={editor.owner} onInput={(e) => setEditor((p) => ({ ...p, owner: e.target.value }))} />
</label>
<label className="binding-form-row">
Repo pin -- repo
<input className="binding-input" value={editor.repo} onInput={(e) => setEditor((p) => ({ ...p, repo: e.target.value }))} />
</label>
<label className="binding-form-row">
Shared secret ({editor.id ? "leave blank to keep the current secret" : "senders sign with this via HMAC-SHA256"})
<input className="binding-input" type="password" value={editor.secret} onInput={(e) => setEditor((p) => ({ ...p, secret: e.target.value }))} />
</label>
</div>
</div>
);
return editor ? renderEditor() : renderList();
}
-18
View File
@@ -1,18 +0,0 @@
// Which dashboard sections the serving process can actually back.
//
// From the UI cutover the dashboard is served by one composition: the
// extracted UI service, which holds two remote contracts (Gateway ChatContract
// and the State Store) and no daemon runtime handles. A section with nothing
// behind it still answers -- an empty list, a "disabled" marker, a 501 -- and
// the browser cannot tell that from a quiet deployment. GET /api/capabilities
// says which sections are backed here, and the nav drops the rest
// (archie-core-8cda.5.4).
// hiddenRoutes returns the paths whose section the server reported it cannot
// serve. An unreported section stays visible: a page that says "unavailable"
// is recoverable, a navigation entry that silently vanished is not, so an
// older server or a failed capabilities read shows everything.
export function hiddenRoutes(sections, routes) {
if (!sections) return [];
return routes.filter((r) => r.section && sections[r.section] === false).map((r) => r.path);
}
-75
View File
@@ -1,75 +0,0 @@
import { h, Fragment } from "preact";
import { ago } from "../base/format.jsx";
import { Pill } from "../base/pill.jsx";
/**
* One captured event's summary row, plus its expandable detail row when
* expanded is true. Split out from captures.js so it can be unit tested
* without the page's fetch/SSE wiring, mirroring tasks/task-row.js.
*/
export function CaptureRow({ capture: c, expanded, onToggle }) {
const handleKeyDown = (e) => {
if (e.key !== "Enter" && e.key !== " ") return;
e.preventDefault();
onToggle(e);
};
return (
<Fragment>
<tr
className="capture-row"
tabIndex="0"
aria-expanded={String(expanded)}
onClick={onToggle}
onKeyDown={handleKeyDown}
>
<td className="mono">{c.source || "(unknown)"}</td>
<td title={c.received_at || ""}>{ago(c.received_at)}</td>
<td><Pill text="Unbound" kind="idle" /></td>
<td className="mono">{c.content_type || "—"}</td>
<td>
<button className="btn btn-small" type="button">
{expanded ? "Hide" : "View"}
</button>
</td>
</tr>
{expanded && <CaptureDetailRow capture={c} />}
</Fragment>
);
}
export function CaptureDetailRow({ capture: c }) {
return (
<tr className="capture-detail-row">
<td colSpan="5">
<div className="capture-detail">
<div className="capture-detail-section">
<div className="capture-detail-title">Payload</div>
<PayloadView raw={c.body} />
</div>
<div className="capture-detail-section">
<div className="capture-detail-title">Headers</div>
<PayloadView raw={c.headers} />
</div>
</div>
</td>
</tr>
);
}
function PayloadView({ raw }) {
if (!raw) return <div className="capture-empty">(empty)</div>;
return <pre className="capture-payload">{prettyPrint(raw)}</pre>;
}
// prettyPrint indents valid JSON for readability; a non-JSON payload (the
// capture endpoint stores whatever arrives, JSON or not, per
// docs/prds/webhook-intake-security.md) is shown as-is rather than failing
// to render.
export function prettyPrint(raw) {
try {
return JSON.stringify(JSON.parse(raw), null, 2);
} catch {
return raw;
}
}
-61
View File
@@ -1,61 +0,0 @@
/* Event inspector: captured payloads, explorable per row. */
.capture-row {
cursor: pointer;
}
.capture-row:hover {
background: var(--bg-raised);
}
.capture-row:focus-visible {
outline: 2px solid var(--accent);
outline-offset: -2px;
}
.capture-detail-row td {
padding: var(--sp-3) var(--sp-3) var(--sp-4);
border-bottom: 1px solid var(--border);
}
.capture-detail {
display: grid;
gap: var(--sp-4);
grid-template-columns: 1fr 1fr;
}
.capture-detail-section {
min-width: 0;
}
.capture-detail-title {
font-size: var(--text-xs);
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--fg-subtle);
margin-bottom: var(--sp-2);
}
.capture-payload {
background: var(--bg-raised);
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
padding: var(--sp-3);
font-family: var(--font-mono);
font-size: var(--text-xs);
white-space: pre-wrap;
word-break: break-word;
max-height: 24rem;
overflow: auto;
}
.capture-empty {
color: var(--fg-muted);
font-size: var(--text-sm);
}
@media (max-width: 640px) {
.capture-detail {
grid-template-columns: 1fr;
}
}
-122
View File
@@ -1,122 +0,0 @@
import { h, Fragment } from "preact";
import { useState, useEffect } from "preact/hooks";
import "./captures.css";
import { api, subscribeEvents } from "../base/api.jsx";
import { CaptureRow } from "./capture-row.jsx";
import { Pill } from "../base/pill.jsx";
export function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
/**
* Event inspector (t2db.2): the operator-facing half of capture. Recent
* inbound events, newest first, with the full redacted payload explorable
* per row -- see docs/prds/event-capture-storage.md for what the backend
* guarantees (retention, redaction, disk bounds).
*
* Live updates ride the same /events SSE stream every other page uses
* (Server.emit publishes a "capture" kind event on every successful
* capture) rather than polling, so a captured event appears here without a
* manual refresh. That event is deliberately lightweight (id + source only,
* no payload -- see handleCapture's comment on why): it is treated purely
* as an invalidation signal, triggering a refetch of the authoritative list
* rather than being merged into local state directly.
*/
export function capturesPage(query) {
return <CapturesApp query={query} />;
}
function CapturesApp({ query }) {
const [captures, setCaptures] = useState([]);
const [expandedId, setExpandedId] = useState(null);
const [loadError, setLoadError] = useState(null);
const [enabled, setEnabled] = useState(true);
const [streamState, setStreamState] = useState({ text: "connecting", kind: "idle" });
const load = async () => {
try {
const res = await api.captures(100);
setEnabled(res.enabled !== false);
setCaptures(res.captures || []);
setLoadError(null);
} catch (err) {
setLoadError(String(err.message || err));
}
};
useEffect(() => {
load();
const unsubscribe = subscribeEvents(
(event) => {
if (event.kind !== "capture") return;
load();
},
(state) => {
setStreamState({
text: state,
kind: state === "live" ? "ok" : "warn",
});
}
);
return () => unsubscribe();
}, []);
const renderRows = () => {
if (loadError) {
return <Empty title="Cannot reach archied" detail={loadError} />;
}
if (!enabled) {
return <Empty title="Capture is not configured" detail="This deployment has no capture storage wired up." />;
}
if (!captures.length) {
return <Empty title="No captures yet" detail="Point a webhook at /webhooks/capture/<source> and it will show up here." />;
}
return (
<div className="table-scroll">
<table className="table">
<thead>
<tr>
{["Source", "Received", "Binding", "Content type", ""].map((h, i) => (
<th key={i}>{h}</th>
))}
</tr>
</thead>
<tbody>
{captures.map((c) => (
<CaptureRow
key={c.id}
capture={c}
expanded={expandedId === c.id}
onToggle={() => setExpandedId(expandedId === c.id ? null : c.id)}
/>
))}
</tbody>
</table>
</div>
);
};
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Event inspector</h1>
<p className="page-sub">Real inbound payloads archie has captured, most recent first.</p>
</div>
<div className="page-actions">
<Pill text={streamState.text} kind={streamState.kind} />
<button className="btn" onClick={load}>Refresh</button>
</div>
</div>
<div className="card">
{renderRows()}
</div>
</div>
);
}
-19
View File
@@ -1,19 +0,0 @@
/* Channels-only styles. */
.channel-card {
display: flex;
flex-direction: column;
gap: var(--sp-1);
}
.channel-desc {
color: var(--fg-muted);
font-size: var(--text-sm);
margin: 0;
}
.channel-detail {
color: var(--fg-subtle);
font-size: var(--text-xs);
margin: 0;
}
-101
View File
@@ -1,101 +0,0 @@
import { h } from "preact";
import { useState, useEffect } from "preact/hooks";
import "./channels.css";
import { api } from "../base/api.jsx";
import { Pill } from "../base/pill.jsx";
export function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
function stateTone(state, configured) {
if (state === "running") return "ok";
if (state === "failed" || state === "degraded") return "warn";
return configured ? "idle" : "idle";
}
function ChannelsApp() {
const [channels, setChannels] = useState([]);
const [error, setError] = useState(null);
const load = async () => {
try {
const res = await api.channels();
setChannels(res?.channels || []);
setError(null);
} catch (err) {
setError(String(err.message || err));
}
};
useEffect(() => {
load();
}, []);
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Channels</h1>
<p className="page-sub">The conversational front-ends Archie can be reached through.</p>
</div>
<div className="page-actions">
<button className="btn" onClick={load}>Refresh</button>
</div>
</div>
<div className="grid grid-2">
{error ? (
<Empty title="Cannot reach archied" detail={error} />
) : channels.length === 0 ? (
<Empty
title="No channels configured"
detail="Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard."
/>
) : (
channels.map(channel => (
<div className="card channel-card" key={channel.id || channel.name}>
<div className="card-head">
<h3 className="card-title">{channel.name}</h3>
<Pill
text={channel.state || (channel.configured ? "configured" : "stopped")}
kind={stateTone(channel.state, channel.configured)}
/>
</div>
<p className="channel-desc">{channel.description}</p>
<p className="channel-detail">{channel.detail}</p>
{channel.reload_supported ? (
<button
className="btn"
onClick={async (event) => {
event.currentTarget.disabled = true;
try {
await api.channelReload(channel.id || channel.name.toLowerCase());
await load();
} catch (err) {
// skip
} finally {
if (event.currentTarget) event.currentTarget.disabled = false;
}
}}
>
Reload
</button>
) : (
<p className="channel-detail">Reload requires a daemon restart for this adapter.</p>
)}
</div>
))
)}
</div>
</div>
);
}
export function channelsPage(query) {
return <ChannelsApp query={query} />;
}
-23
View File
@@ -1,23 +0,0 @@
/**
* Chat presentation helpers that are not components.
*
* The bubble row markup that used to live here is gone with the imperative DOM
* layer: `assistantBubble`/`chatBubble` were a parallel, unreachable renderer
* (nothing in `src/` called them except the equally unreachable chat-tools
* helpers), and chat.jsx builds those rows as JSX itself.
*/
export function sessionTitle(session) {
return session.title || session.branch_name || `Conversation ${session.session_id.slice(0, 8)}`;
}
/**
* panelTitle names the launcher panel's header. The panel is small and the
* session switcher sits below it, so the header says which conversation is
* open rather than repeating the product name.
*/
export function panelTitle(sessions, currentSession) {
if (!currentSession) return "Archie";
const session = (sessions || []).find((item) => item.session_id === currentSession);
return session ? sessionTitle(session) : "Archie";
}
-24
View File
@@ -1,24 +0,0 @@
import { randomUUID } from "../base/uuid.jsx";
export function newChatTurn(text) {
return { text, sourceID: randomUUID() };
}
export function retryChatTurn(turn) {
return { ...turn };
}
// resolveTurn decides what to send: a real retry descriptor's original turn,
// or a fresh turn built from the composer text. `retry` is untrusted here --
// a DOM event handler bound as `el.onclick = sendMessage` (rather than
// `() => sendMessage()`) hands the click's MouseEvent to this function as
// `retry`, and a MouseEvent is truthy but has no `.turn`. Only an object
// carrying a `turn.text` string counts as a genuine retry; anything else
// (including no argument) falls back to the composer text instead of
// throwing on a missing property.
export function resolveTurn(retry, composerValue) {
const isRetry = !!(retry && typeof retry === "object" && retry.turn && typeof retry.turn.text === "string");
const text = isRetry ? retry.turn.text : composerValue.trim();
const turn = isRetry ? retryChatTurn(retry.turn) : newChatTurn(text);
return { text, turn, isRetry };
}
-12
View File
@@ -1,12 +0,0 @@
import { randomUUID } from "../base/uuid.jsx";
const CHANNEL_KEY = "archie.web.chat.channel";
export function channelID() {
let id = localStorage.getItem(CHANNEL_KEY);
if (!id) {
id = randomUUID();
localStorage.setItem(CHANNEL_KEY, id);
}
return id;
}
-15
View File
@@ -1,15 +0,0 @@
// updateUnavailableMessage decides what -- if anything -- refreshUpdate should
// show when fetching /api/chat/update fails.
//
// A 501 means the release-update-check feature simply isn't configured for
// this deployment (chat.telegram.update_check_command is unset) -- a normal
// state, the same category as an unconfigured chat channel, not a fetch
// failure. It gets no visible banner: callers should render nothing.
//
// Any other error (network failure, 500, ...) is a genuine problem and gets a
// clear, fixed human message -- never the raw fetch error text, which leaks
// implementation detail like literal HTTP status codes into the UI.
export function updateUnavailableMessage(err) {
if (err?.status === 501) return null;
return "Could not check for updates.";
}
-226
View File
@@ -1,226 +0,0 @@
/* The panel's own column. ChatApp is mounted in a ~440px launcher panel, never
on a page, so there is one column and every row earns its height
(archie-core-hesx). */
.chat-panel-content {
display: grid;
/* header, bar, then the conversation takes the rest: without the third
track the transcript sized to its content and left the composer floating
above dead space. */
grid-template-rows: auto auto minmax(0, 1fr);
flex: 1 1 auto;
min-height: 0;
overflow: hidden;
}
/* One row for everything that is not the conversation: which conversation,
a new one, and the model controls folded away behind a disclosure. */
.chat-bar {
display: flex;
align-items: center;
gap: var(--sp-2);
padding: var(--sp-2) var(--sp-3);
border-bottom: 1px solid var(--border);
}
.chat-session-switch {
flex: 1 1 auto;
min-width: 0;
}
.chat-session-switch select {
width: 100%;
background: var(--surface-hover);
color: var(--fg);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--sp-2);
font: inherit;
font-size: var(--text-sm);
}
.chat-new,
.chat-settings > summary {
flex: none;
}
.chat-settings {
position: relative;
flex: none;
}
.chat-settings > summary {
display: grid;
place-items: center;
width: 32px;
height: 32px;
border-radius: var(--radius-sm);
color: var(--fg-muted);
cursor: pointer;
list-style: none;
}
.chat-settings > summary::-webkit-details-marker {
display: none;
}
.chat-settings > summary:hover {
background: var(--surface-hover);
color: var(--fg);
}
/* Opens over the transcript rather than pushing it down: the panel is short
and the conversation should not jump when the controls are consulted. */
.chat-settings-body {
position: absolute;
top: calc(100% + var(--sp-2));
right: 0;
z-index: 2;
display: grid;
gap: var(--sp-3);
width: 15rem;
padding: var(--sp-3);
background: var(--bg-raised);
border: 1px solid var(--border);
border-radius: var(--radius-md);
box-shadow: var(--shadow-md);
}
.chat-settings-body label {
display: grid;
gap: var(--sp-1);
font-size: var(--text-xs);
color: var(--fg-muted);
}
.chat-settings-body .chat-select {
width: 100%;
}
.chat-layout {
display: grid;
min-height: 0;
overflow: hidden;
}
.chat-workspace {
display: grid;
grid-template-rows: auto minmax(0, 1fr) auto;
min-width: 0;
overflow: hidden;
}
.chat-workspace-head {
display: flex;
align-items: center;
gap: var(--sp-2);
padding: var(--sp-2) var(--sp-3);
border-bottom: 1px solid var(--border);
font-size: var(--text-xs);
}
.chat-update-panel { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 1rem; margin: 0 0 .75rem; padding: .7rem .9rem; border: 1px solid var(--border); border-radius: .75rem; color: var(--fg-muted); font-size: .8rem; }
.chat-update-panel > div:first-child { display: grid; gap: .2rem; }
.chat-update-panel strong { color: var(--fg); }
.chat-update-actions { display: flex; gap: .45rem; flex-shrink: 0; }
.chat-dangerous-panel { flex: 0 0 auto; margin: 0 0 .75rem; padding: .8rem .9rem; border: 1px solid color-mix(in srgb, var(--danger) 45%, var(--border)); border-radius: .75rem; }
.chat-dangerous-head, .chat-dangerous-controls, .chat-dangerous-pending { display: flex; align-items: center; justify-content: space-between; gap: .6rem; }
.chat-dangerous-head { margin-bottom: .7rem; }
.chat-dangerous-controls { align-items: stretch; flex-wrap: wrap; }
.chat-dangerous-controls > div { display: flex; gap: .45rem; flex: 1 1 18rem; }
.chat-dangerous-input { min-width: 0; flex: 1; padding: .5rem .65rem; background: var(--surface-hover); color: var(--fg); border: 1px solid var(--border-strong); border-radius: .5rem; font: inherit; }
.chat-dangerous-pending-list { display: grid; gap: .45rem; margin-top: .75rem; }
.chat-dangerous-pending { padding-top: .55rem; border-top: 1px solid var(--border); color: var(--fg-muted); font-size: .8rem; }
.chat-session-list { display: grid; gap: .35rem; margin-top: 1rem; }
.chat-session { display: grid; gap: .25rem; text-align: left; background: transparent; color: var(--fg-muted); border: 1px solid transparent; border-radius: .65rem; padding: .7rem; cursor: pointer; }
.chat-session:hover, .chat-session.active { background: var(--surface-hover); color: var(--fg); border-color: var(--border-strong); }
.chat-session span { font-size: .72rem; }
.chat-session-tools { position: relative; margin-left: .6rem; color: var(--fg-muted); font-size: .78rem; }
.chat-session-tools summary { cursor: pointer; }
.chat-session-tool-list { position: absolute; z-index: 2; right: 0; top: calc(100% + .45rem); display: flex; flex-wrap: wrap; gap: .35rem; width: min(22rem, 72vw); padding: .55rem; background: var(--surface); border: 1px solid var(--border-strong); border-radius: .65rem; box-shadow: 0 .7rem 2rem color-mix(in srgb, #000 30%, transparent); }
.chat-select { background: var(--surface-hover); color: var(--fg); border: 1px solid var(--border-strong); border-radius: .5rem; padding: .5rem .65rem; }
.chat-transcript { overflow: auto; padding: var(--sp-4); display: grid; align-content: start; gap: var(--sp-4); }
.chat-empty-state { align-self: center; justify-self: center; width: 100%; padding: var(--sp-5) 0; text-align: center; }
.chat-empty-mark { display: grid; place-items: center; width: 2.2rem; height: 2.2rem; margin: 0 auto var(--sp-3); border: 1px solid var(--border-strong); border-radius: .8rem; color: var(--accent); font-weight: 700; }
.chat-empty-state h2 { margin: 0; font-size: var(--text-lg); letter-spacing: -.02em; }
.chat-empty-state p { margin: var(--sp-2) 0 var(--sp-4); color: var(--fg-muted); font-size: var(--text-sm); }
.chat-prompt-grid { display: grid; gap: var(--sp-2); }
.chat-prompt { padding: var(--sp-2) var(--sp-3); font-size: var(--text-sm); text-align: left; border: 1px solid var(--border); border-radius: 999px; background: var(--surface-hover); color: var(--fg-muted); cursor: pointer; }
.chat-prompt:hover { color: var(--fg); border-color: var(--border-strong); }
.chat-bubble-row { display: flex; }
.chat-bubble-row.user { justify-content: flex-end; }
.chat-bubble { max-width: min(78ch, 86%); padding: .8rem 1rem; border-radius: .85rem; background: var(--surface-hover); line-height: 1.5; }
.chat-bubble-row.user .chat-bubble { background: color-mix(in srgb, var(--accent) 18%, var(--surface)); }
.chat-bubble-meta { font-size: .7rem; color: var(--fg-muted); margin-bottom: .3rem; }
.chat-bubble-text { white-space: pre-wrap; overflow-wrap: anywhere; }
.chat-bubble-text p { margin: 0 0 .7rem; }
.chat-bubble-text p:last-child { margin-bottom: 0; }
.chat-bubble-text h1, .chat-bubble-text h2, .chat-bubble-text h3 { margin: .2rem 0 .6rem; line-height: 1.2; letter-spacing: -.02em; }
.chat-bubble-text h1 { font-size: 1.25rem; }
.chat-bubble-text h2 { font-size: 1.1rem; }
.chat-bubble-text h3 { font-size: 1rem; }
.chat-bubble-text ul, .chat-bubble-text ol { margin: .25rem 0 .75rem; padding-left: 1.35rem; }
.chat-bubble-text blockquote { margin: .5rem 0; padding: .35rem .75rem; border-left: 3px solid var(--accent); color: var(--fg-muted); }
.chat-bubble-text code { padding: .1rem .3rem; border-radius: .3rem; background: color-mix(in srgb, var(--fg) 10%, transparent); font-size: .9em; }
.chat-bubble-text pre { margin: .6rem 0; padding: .75rem; overflow: auto; border: 1px solid var(--border); border-radius: .5rem; background: color-mix(in srgb, var(--surface) 75%, #000); }
.chat-bubble-text pre code { padding: 0; background: transparent; }
.chat-bubble-text a { color: var(--accent); }
.chat-media-img { max-width: 100%; max-height: 24rem; border-radius: .5rem; margin: .4rem 0; display: block; border: 1px solid var(--border); object-fit: contain; background: var(--surface); cursor: pointer; }
.chat-bubble-text table { width: 100%; margin: .7rem 0; border-collapse: collapse; font-size: .92em; }
.chat-bubble-text th, .chat-bubble-text td { padding: .45rem .6rem; text-align: left; border: 1px solid var(--border); }
.chat-bubble-text th { color: var(--fg); background: color-mix(in srgb, var(--surface) 70%, transparent); font-weight: 700; }
/* Tool activity: a quiet log above the answer it produced. It is deliberately
smaller and dimmer than the reply -- it is evidence, not the point. An empty
list renders nothing, so a turn that called no tools looks untouched. */
.chat-tools { display: grid; gap: .2rem; margin-bottom: .5rem; font-size: .78rem; }
.chat-tools:empty { display: none; }
.chat-tool { display: flex; gap: .4rem; align-items: baseline; color: var(--fg-muted); overflow-wrap: anywhere; }
.chat-tool-name { color: var(--fg); font-weight: 600; }
.chat-tool.failed .chat-tool-summary { color: var(--danger); }
/* A dashboard_navigate result: a clickable chip that routes the operator to a
dashboard page. It is an action, not evidence, so it is styled as a button
beside the tool list rather than a muted log line, and it visibly invites a
click. It is the only clickable navigation surface in the transcript. */
.chat-nav-chip {
display: inline-flex;
align-items: center;
gap: .4rem;
padding: .4rem .7rem;
border-radius: 999px;
border: 1px solid color-mix(in srgb, var(--accent) 45%, var(--border));
background: var(--accent-soft);
color: var(--accent);
font-size: .82rem;
font-weight: 600;
cursor: pointer;
transition: background var(--transition), border-color var(--transition), color var(--transition);
}
.chat-nav-chip:hover {
border-color: var(--accent);
background: color-mix(in srgb, var(--accent) 16%, var(--surface));
}
.chat-nav-chip:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.chat-nav-chip-icon { font-size: .8rem; line-height: 1; }
.chat-compose { padding: var(--sp-3); border-top: 1px solid var(--border); }
/* Text and actions share one row: the buttons sit at the right of the input,
not on a line of their own under it. */
.chat-composer-shell { position: relative; display: flex; align-items: flex-end; gap: var(--sp-2); padding: .7rem .8rem; background: var(--surface-hover); border: 1px solid var(--border-strong); border-radius: .9rem; }
.chat-composer { flex: 1 1 auto; min-width: 0; min-height: 2.6rem; resize: none; box-sizing: border-box; background: transparent; color: var(--fg); border: 0; padding: .25rem 0; font: inherit; }
.chat-composer:focus { outline: 0; }
.chat-command-menu { position: absolute; z-index: 3; right: .8rem; bottom: calc(100% - .25rem); left: .8rem; display: grid; gap: .15rem; max-height: 18rem; overflow: auto; padding: .35rem; background: var(--surface); border: 1px solid var(--border-strong); border-radius: .7rem; box-shadow: 0 .7rem 2rem color-mix(in srgb, #000 30%, transparent); }
.chat-command-menu[hidden] { display: none; }
.chat-command-option { display: grid; grid-template-columns: minmax(8rem, 14rem) 1fr; gap: .65rem; align-items: center; padding: .5rem .6rem; text-align: left; color: var(--fg-muted); background: transparent; border: 1px solid transparent; border-radius: .45rem; cursor: pointer; }
.chat-command-option:hover, .chat-command-option[aria-selected="true"] { color: var(--fg); background: var(--surface-hover); border-color: var(--border); }
.chat-command-option code { color: var(--fg); }
.chat-compose-actions { display: flex; align-items: center; flex: none; gap: var(--sp-2); }
.chat-hint, .chat-empty { color: var(--fg-muted); font-size: .78rem; }
.chat-command-help { color: var(--fg-muted); font-size: .78rem; margin-right: auto; }
.chat-command-help summary { cursor: pointer; }
.chat-command-list { min-width: min(34rem, 70vw); max-width: 40rem; padding-top: .4rem; line-height: 1.45; }
.chat-command-item { display: grid; grid-template-columns: minmax(10rem, 16rem) 1fr; gap: .7rem; padding: .3rem 0; }
.chat-command-item code { color: var(--fg); }
@media (max-width: 520px) { .chat-update-panel { align-items: flex-start; flex-direction: column; } }
-810
View File
@@ -1,810 +0,0 @@
import { h, Fragment } from "preact";
import { useState, useEffect, useRef } from "preact/hooks";
import { api } from "../base/api.jsx";
import { Icon } from "../base/icons.jsx";
import { ChatMarkdown } from "./markdown.jsx";
import { channelID } from "./chat-state.jsx";
import { newChatTurn, retryChatTurn, resolveTurn } from "./chat-retry.jsx";
import { commandScrollTop } from "./command-scroll.js";
import { panelTitle, sessionTitle } from "./chat-render.jsx";
import "./chat.css";
function currentPage() {
return location.hash.slice(1) || "/";
}
export function ChatApp({ open = true }) {
const [sessions, setSessions] = useState([]);
const [currentSession, setCurrentSession] = useState("");
const [messages, setMessages] = useState([]);
const [composerText, setComposerText] = useState("");
const [statusText, setStatusText] = useState("Ready");
const [isSending, setIsSending] = useState(false);
const [selectorData, setSelectorData] = useState({});
const [selectedPersona, setSelectedPersona] = useState("");
const [selectedProvider, setSelectedProvider] = useState("");
const [selectedModel, setSelectedModel] = useState("");
const [commandSpecs, setCommandSpecs] = useState([]);
const [commandMatches, setCommandMatches] = useState([]);
const [commandSelection, setCommandSelection] = useState(0);
const [isCommandMenuOpen, setIsCommandMenuOpen] = useState(false);
const [streamingTurn, setStreamingTurn] = useState(null);
// streamingTurn: { text: string, tools: [], isError: bool, turn: object, isRetry: bool }
const transcriptRef = useRef(null);
const composerRef = useRef(null);
const activeControllerRef = useRef(null);
const sessionToolsRef = useRef(null);
const commandMenuRef = useRef(null);
const settingsRef = useRef(null);
const isSendingRef = useRef(isSending);
isSendingRef.current = isSending;
useEffect(() => {
const closeSettings = (event) => {
const details = settingsRef.current;
if (!details?.open) return;
if (event.target instanceof Node && details.contains(event.target)) return;
details.open = false;
};
document.addEventListener("pointerdown", closeSettings);
document.addEventListener("focusin", closeSettings);
return () => {
document.removeEventListener("pointerdown", closeSettings);
document.removeEventListener("focusin", closeSettings);
};
}, []);
// The panel stays mounted so the session survives navigation, so opening it
// is a prop change rather than a mount: focus the composer on that edge.
useEffect(() => {
if (open) composerRef.current?.focus();
}, [open]);
// Arrow keys move the palette selection; the list scrolls so the highlight
// stays visible once the matches run past the visible rows.
useEffect(() => {
if (!isCommandMenuOpen) return;
const menu = commandMenuRef.current;
const option = menu?.children?.[commandSelection];
if (!menu || !option) return;
menu.scrollTop = commandScrollTop({
scrollTop: menu.scrollTop,
viewportHeight: menu.clientHeight,
optionTop: option.offsetTop,
optionHeight: option.offsetHeight,
});
}, [commandSelection, isCommandMenuOpen]);
// Auto scroll transcript to bottom on new messages or streaming tokens
useEffect(() => {
if (transcriptRef.current) {
transcriptRef.current.scrollTop = transcriptRef.current.scrollHeight;
}
}, [messages, streamingTurn]);
useEffect(() => {
refreshSessions().catch((err) => {
setStatusText(err.message || "Chat unavailable");
});
const onTeardown = () => {
activeControllerRef.current?.abort();
};
window.addEventListener("archie:teardown", onTeardown);
return () => {
window.removeEventListener("archie:teardown", onTeardown);
activeControllerRef.current?.abort();
};
}, []);
async function refreshSessions() {
const data = await api.chatSessions();
const sessionList = data.sessions || [];
setSessions(sessionList);
setSelectorData(data);
setSelectedPersona(data.active_persona || "");
const provs = data.providers || [];
const activeProv = data.active_provider || provs[0] || "";
setSelectedProvider(activeProv);
setSelectedModel(data.active_model || "");
const specs = (data.commands || []).map((item) =>
typeof item === "string" ? { command: item, usage: item, description: "" } : item
);
setCommandSpecs(specs);
if (!currentSession && sessionList[0]) {
await selectSession(sessionList[0].session_id, data, sessionList);
}
}
async function selectSession(id, dataOverride, listOverride) {
const data = dataOverride || selectorData;
setCurrentSession(id);
setMessages([]);
setStreamingTurn(null);
const activePersona = data.active_personas?.[id] || data.active_persona || "";
setSelectedPersona(activePersona);
try {
await api.chatMessage(channelID(), `/resume ${id}`);
const [msgs, turns] = await Promise.all([api.chatMessages(id), api.chatTurns(id)]);
const byAssistantMessage = new Map();
for (const turn of turns || []) {
const assistantID = turn.assistant_message_id || turn.AssistantMessageID;
if (assistantID) byAssistantMessage.set(assistantID, turn);
}
const hydrated = (msgs || []).map((message) => {
const messageID = message.message_id || message.MessageID;
const turn = byAssistantMessage.get(messageID);
return turn ? { ...message, tool_calls: turn.tool_calls || turn.ToolCalls || [] } : message;
});
setMessages(hydrated);
} catch (err) {
setStatusText(err.message || "Could not load session messages");
}
}
async function runSessionCommand(command) {
if (!currentSession) return;
try {
setStatusText("Working…");
const result = await api.chatMessage(channelID(), command);
if (result.session_id) setCurrentSession(result.session_id);
setStatusText(result.reply || "Session updated");
await refreshSessions();
if (result.session_id || currentSession) {
await selectSession(result.session_id || currentSession);
}
if (sessionToolsRef.current) sessionToolsRef.current.open = false;
} catch (err) {
setStatusText(err.message || "Session action failed");
}
}
function promptSessionCommand(command, message) {
const value = window.prompt(message);
if (value?.trim()) runSessionCommand(`${command} ${value.trim()}`);
}
function handlePersonaChange(e) {
const val = e.target.value;
setSelectedPersona(val);
if (!currentSession || !val) return;
api.chatPersona(currentSession, val).then(() => {
setSelectorData((prev) => ({
...prev,
active_personas: { ...(prev.active_personas || {}), [currentSession]: val },
}));
setStatusText(`Personality: ${val}`);
}).catch((err) => {
setStatusText(err.message || "Failed to set personality");
});
}
async function handleProviderChange(e) {
const prov = e.target.value;
setSelectedProvider(prov);
if (!prov) return;
try {
const result = await api.chatMessage(channelID(), `/model --provider ${prov}`);
setStatusText(result.reply || "Provider updated");
await refreshSessions();
} catch (err) {
setStatusText(`Provider update failed: ${err.message || err}`);
}
}
async function handleModelChange(e) {
const mod = e.target.value;
setSelectedModel(mod);
if (!mod) return;
try {
const result = await api.chatMessage(channelID(), `/model ${mod}`);
setStatusText(result.reply || "Model updated");
await refreshSessions();
} catch (err) {
setStatusText(`Model update failed: ${err.message || err}`);
}
}
function handleNewChat() {
setComposerText("/new");
sendMessage({ textOverride: "/new" });
}
function handleComposerInput(e) {
const val = e.target.value;
setComposerText(val);
const before = val.slice(0, e.target.selectionStart);
const match = before.match(/(?:^|\s)\/([^\s]*)$/);
if (match) {
const query = match[1].toLowerCase();
const matches = commandSpecs.filter((spec) => {
const haystack = `${spec.command} ${spec.description}`.toLowerCase();
return haystack.includes(query);
}).slice(0, 8);
if (matches.length) {
setCommandMatches(matches);
setCommandSelection(0);
setIsCommandMenuOpen(true);
return;
}
}
setIsCommandMenuOpen(false);
setCommandMatches([]);
}
function chooseCommand(index) {
const spec = commandMatches[index];
if (!spec || !composerRef.current) return;
const input = composerRef.current;
const before = input.value.slice(0, input.selectionStart);
const after = input.value.slice(input.selectionStart);
const start = before.search(/(?:^|\s)\/[^\s]*$/);
const tokenStart = start < 0 ? before.length : start + (before[start] === " " ? 1 : 0);
const nextVal = `${before.slice(0, tokenStart)}${spec.command} ${after}`;
setComposerText(nextVal);
setIsCommandMenuOpen(false);
const cursor = tokenStart + spec.command.length + 1;
setTimeout(() => {
input.focus();
input.setSelectionRange(cursor, cursor);
}, 0);
}
function handleComposerKeyDown(event) {
if (isCommandMenuOpen && commandMatches.length) {
if (
event.key === "Enter" &&
!event.shiftKey &&
!event.ctrlKey &&
!event.metaKey &&
commandMatches.some((spec) => spec.command === composerText.trim())
) {
event.preventDefault();
setIsCommandMenuOpen(false);
sendMessage();
return;
}
if (event.key === "ArrowDown") {
event.preventDefault();
setCommandSelection((prev) => (prev + 1) % commandMatches.length);
return;
}
if (event.key === "ArrowUp") {
event.preventDefault();
setCommandSelection((prev) => (prev + commandMatches.length - 1) % commandMatches.length);
return;
}
if (event.key === "Enter" && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
event.preventDefault();
chooseCommand(commandSelection);
return;
}
if (event.key === "Escape") {
event.preventDefault();
setIsCommandMenuOpen(false);
return;
}
}
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
sendMessage();
}
}
async function sendMessage(retryOpts = null) {
const explicitText = retryOpts?.textOverride;
const rawVal = explicitText !== undefined ? explicitText : composerText;
const { text, turn, isRetry } = resolveTurn(retryOpts, rawVal);
if (!text || isSendingRef.current) return;
setIsCommandMenuOpen(false);
setIsSending(true);
setStatusText(isRetry ? "Retrying…" : "Thinking…");
if (!isRetry) {
setMessages((prev) => [...prev, { from: "web", text }]);
setComposerText("");
}
let activeTools = [];
setStreamingTurn({ text: "", tools: [], isError: false, turn, isRetry });
let streamedText = "";
let finished = false;
let timedOut = false;
let timeoutId = null;
try {
const controller = new AbortController();
activeControllerRef.current = controller;
timeoutId = setTimeout(() => {
timedOut = true;
controller.abort();
}, 120000);
const response = await api.chatStream(
{
channel_id: channelID(),
source_id: turn.sourceID,
text: turn.text,
page: currentPage(),
},
{ signal: controller.signal },
);
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
for (;;) {
const { value, done } = await reader.read();
buffer += decoder.decode(value || new Uint8Array(), { stream: !done });
const frames = buffer.split("\n\n");
buffer = frames.pop() || "";
for (const frame of frames) {
const line = frame.split("\n").find((part) => part.startsWith("data: "));
if (!line) continue;
const event = JSON.parse(line.slice(6));
if (event.session_id) setCurrentSession(event.session_id);
if (event.type === "delta") {
streamedText += event.text;
setStreamingTurn((prev) => (prev ? { ...prev, text: streamedText } : null));
}
if (event.type === "tool") {
activeTools = [...activeTools, event];
setStreamingTurn((prev) => (prev ? { ...prev, tools: activeTools } : null));
}
if (event.type === "navigate") {
activeTools = [...activeTools, event];
setStreamingTurn((prev) => (prev ? { ...prev, tools: activeTools } : null));
}
if (event.type === "done") {
finished = true;
if (!streamedText) {
streamedText = event.text;
}
}
if (event.type === "error") throw new Error(event.text);
}
if (done) break;
}
if (!finished) throw new Error("chat stream ended before completion");
// Commit finished message into transcript
setMessages((prev) => [
...prev,
{
from: "assistant",
text: streamedText,
tool_calls: activeTools,
},
]);
setStreamingTurn(null);
setStatusText("Ready");
await refreshSessions();
} catch (err) {
if (err.name === "AbortError" && !timedOut) {
setStreamingTurn({
text: "Turn stopped.",
tools: activeTools,
isError: false,
turn,
isRetry,
});
setStatusText("Stopped");
} else {
const failedText = `Unable to complete that turn: ${err.message || err}`;
setStreamingTurn({
text: failedText,
tools: activeTools,
isError: true,
turn: retryChatTurn(turn),
isRetry,
});
setStatusText("Error — retry available");
}
} finally {
clearTimeout(timeoutId);
activeControllerRef.current = null;
setIsSending(false);
if (composerRef.current) composerRef.current.focus();
}
}
function handleStop() {
setStatusText("Stopping…");
if (currentSession) {
void api.chatCancel(currentSession).catch(() => {});
}
activeControllerRef.current?.abort();
}
const groupedModels = selectorData.models_by_provider || {};
const currentModels =
selectedProvider && groupedModels[selectedProvider]
? groupedModels[selectedProvider]
: selectorData.models || [];
return (
<div className="chat-panel-content">
<div className="chat-drawer-head">
<strong className="chat-panel-title">{panelTitle(sessions, currentSession)}</strong>
<div className="chat-head-actions">
<button className="icon-btn chat-new" type="button" title="New chat" aria-label="New chat" onClick={handleNewChat}>
<Icon name="message-circle-plus" />
</button>
</div>
</div>
<div className="chat-bar">
<label className="chat-session-switch">
<span className="sr-only">Conversation</span>
<select
value={currentSession}
onChange={(e) => selectSession(e.target.value)}
disabled={!sessions.length}
>
{!sessions.length ? (
<option value="">No conversations yet</option>
) : (
sessions.map((session) => (
<option key={session.session_id} value={session.session_id}>
{sessionTitle(session)}
</option>
))
)}
</select>
</label>
<details className="chat-settings" ref={settingsRef}>
<summary aria-label="Chat settings" title="Chat settings">
<span aria-hidden="true">⚙</span>
</summary>
<div className="chat-settings-body">
<span className="chat-status">{statusText}</span>
<label>
Personality
<select
className="chat-select"
aria-label="Personality"
value={selectedPersona}
onChange={handlePersonaChange}
>
<option value="">Default</option>
{(selectorData.personas || []).map((name) => (
<option key={name} value={name}>
{name}
</option>
))}
</select>
</label>
{(selectorData.providers || []).length > 0 && (
<label>
Provider
<select
className="chat-select"
aria-label="Provider"
value={selectedProvider}
onChange={handleProviderChange}
>
<option value="">Default</option>
{(selectorData.providers || []).map((provider) => (
<option key={provider} value={provider}>
{provider}
</option>
))}
</select>
</label>
)}
<label>
Model
<select
className="chat-select"
aria-label="Model"
value={selectedModel}
onChange={handleModelChange}
>
<option value="">Default</option>
{currentModels.map((model) => (
<option key={model} value={model}>
{model}
</option>
))}
</select>
</label>
</div>
</details>
</div>
<div className="chat-layout">
<section className="chat-workspace">
<div className="chat-workspace-head">
<details
className="chat-session-tools"
ref={sessionToolsRef}
hidden={!currentSession}
>
<summary>Session actions</summary>
<div className="chat-session-tool-list">
<button
className="btn"
type="button"
onClick={() => runSessionCommand("/retry")}
>
Retry
</button>
<button
className="btn"
type="button"
onClick={() => runSessionCommand("/undo")}
>
Undo
</button>
<button
className="btn"
type="button"
onClick={() => promptSessionCommand("/title", "Session title")}
>
Rename
</button>
<button
className="btn"
type="button"
onClick={() => promptSessionCommand("/branch", "Branch name (optional)")}
>
Branch
</button>
<button
className="btn"
type="button"
onClick={() => runSessionCommand("/compress --preview")}
>
Preview compression
</button>
</div>
</details>
</div>
{/* Transcript */}
<div className="chat-transcript" ref={transcriptRef}>
{!messages.length && !streamingTurn ? (
<div className="chat-empty-state">
<span className="chat-empty-mark">A</span>
<h2>What are we working on?</h2>
<p>Ask Archie anything, or start with one of these prompts.</p>
<div className="chat-prompt-grid">
<button
className="chat-prompt"
type="button"
onClick={() => {
setComposerText("Summarise active tasks");
composerRef.current?.focus();
}}
>
Summarise active tasks
</button>
<button
className="chat-prompt"
type="button"
onClick={() => {
setComposerText("Show running agents");
composerRef.current?.focus();
}}
>
Show running agents
</button>
<button
className="chat-prompt"
type="button"
onClick={() => {
setComposerText("Check system status");
composerRef.current?.focus();
}}
>
Check system status
</button>
</div>
</div>
) : (
<Fragment>
{messages.map((message, idx) => {
const from = message.from ?? message.From ?? "";
const text = message.text ?? message.Text ?? "";
const isAssistant = from !== "web";
const tools = message.tool_calls || message.ToolCalls || [];
return (
<div
key={idx}
className={`chat-bubble-row ${isAssistant ? "assistant" : "user"}`}
>
<div className="chat-bubble">
{isAssistant ? (
<Fragment>
{tools.length > 0 && (
<div className="chat-tools">
{tools.map((tool, tIdx) => {
if (tool.path) {
return (
<a
key={tIdx}
className="chat-nav-chip"
href={`#${tool.path}`}
title={`Go to ${tool.label || tool.path}`}
>
<span className="chat-nav-chip-icon" aria-hidden="true">
↗
</span>
<span className="chat-nav-chip-label">
{tool.label || tool.path}
</span>
</a>
);
}
const name = tool.name || tool.Name || tool.tool || "tool";
const parameters = tool.parameters || tool.Parameters || "";
const summary =
tool.summary ||
tool.Summary ||
tool.text ||
tool.err ||
tool.Err ||
"done";
const failed = Boolean(tool.err || tool.Err || tool.failed);
return (
<div
key={tIdx}
className={`chat-tool ${failed ? "failed" : ""}`}
>
<span className="chat-tool-icon">🔧</span>
<span className="chat-tool-name">{name}</span>
{parameters && (
<code className="chat-tool-parameters">{parameters}</code>
)}
<span className="chat-tool-summary">{summary}</span>
</div>
);
})}
</div>
)}
<ChatMarkdown text={text} />
</Fragment>
) : (
<div className="chat-bubble-text">{text}</div>
)}
</div>
</div>
);
})}
{/* Live streaming assistant turn */}
{streamingTurn && (
<div className="chat-bubble-row assistant">
<div className="chat-bubble">
{streamingTurn.tools?.length > 0 && (
<div className="chat-tools">
{streamingTurn.tools.map((tool, tIdx) => {
if (tool.path) {
return (
<a
key={tIdx}
className="chat-nav-chip"
href={`#${tool.path}`}
title={`Go to ${tool.label || tool.path}`}
>
<span className="chat-nav-chip-icon" aria-hidden="true">
↗
</span>
<span className="chat-nav-chip-label">
{tool.label || tool.path}
</span>
</a>
);
}
const name = tool.name || tool.tool || "tool";
const parameters = tool.parameters || "";
const summary = tool.summary || tool.text || (tool.failed ? "failed" : "running…");
const failed = Boolean(tool.failed);
return (
<div
key={tIdx}
className={`chat-tool ${failed ? "failed" : ""}`}
>
<span className="chat-tool-icon">🔧</span>
<span className="chat-tool-name">{name}</span>
{parameters && (
<code className="chat-tool-parameters">{parameters}</code>
)}
<span className="chat-tool-summary">{summary}</span>
</div>
);
})}
</div>
)}
<ChatMarkdown text={streamingTurn.text || "…"} />
{streamingTurn.isError && (
<button
className="btn chat-retry"
type="button"
onClick={() => sendMessage({ turn: streamingTurn.turn })}
>
Retry
</button>
)}
</div>
</div>
)}
</Fragment>
)}
</div>
{/* Composer */}
<div className="chat-compose">
<div className="chat-composer-shell">
<textarea
ref={composerRef}
className="chat-composer"
rows={3}
placeholder="Message Archie, or type / for commands"
aria-label="Message Archie"
value={composerText}
onInput={handleComposerInput}
onKeyDown={handleComposerKeyDown}
/>
{isCommandMenuOpen && commandMatches.length > 0 && (
<div
className="chat-command-menu"
ref={commandMenuRef}
role="listbox"
aria-label="Commands"
>
{commandMatches.map((spec, index) => (
<button
key={spec.command}
type="button"
role="option"
aria-selected={String(index === commandSelection)}
className="chat-command-option"
onMouseDown={(e) => e.preventDefault()}
onClick={() => chooseCommand(index)}
>
<code>{spec.command}</code>
<span>{spec.description || spec.usage || ""}</span>
</button>
))}
</div>
)}
<div className="chat-compose-actions">
{isSending && (
<button className="btn" type="button" onClick={handleStop}>
Stop
</button>
)}
<button
className="btn btn-primary"
type="button"
disabled={isSending || !composerText.trim()}
onClick={() => sendMessage()}
>
Send
</button>
</div>
</div>
</div>
</section>
</div>
</div>
);
}
-28
View File
@@ -1,28 +0,0 @@
// Keeping the arrow-key selection visible in the command palette.
//
// The palette caps its height and scrolls, so once the matches run past the
// visible rows the selection walked off-screen and the highlight was invisible
// (archie-core-ifay). Browsers have scrollIntoView, but the decision is pure
// arithmetic and worth testing on its own, so the effect only applies what
// this returns.
/**
* commandScrollTop returns the scrollTop that brings the selected option fully
* into view, or the current scrollTop when it is already visible. Mirrors
* `scrollIntoView({ block: "nearest" })`: it moves the minimum distance, and
* scrolls up for an option above the viewport, down for one below.
*/
export function commandScrollTop({ scrollTop, viewportHeight, optionTop, optionHeight }) {
// An option taller than the viewport cannot be shown whole. Align its top,
// which holds the command itself; aligning the bottom would scroll the name
// out of sight and leave only the tail of its description.
if (optionHeight >= viewportHeight) return optionTop;
if (optionTop < scrollTop) return optionTop;
const optionBottom = optionTop + optionHeight;
const viewportBottom = scrollTop + viewportHeight;
if (optionBottom > viewportBottom) return optionBottom - viewportHeight;
return scrollTop;
}
-195
View File
@@ -1,195 +0,0 @@
import { h } from "preact";
/**
* Chat markdown.
*
* Telegram-style rich blocks -- headings, lists, quotes, fenced code, tables,
* inline emphasis/links/images -- rendered as semantic HTML. It is a
* component rather than a DOM builder so a streamed reply can be diffed: the
* transcript re-renders on every frame, and diffing is what stops the whole
* bubble being rebuilt each time the answer grows.
*/
const INLINE =
/(!\[[^\]]*\]\((?:https?:\/\/[^\s)]+|data:image\/[^\s)]+|\/[^\s)]+)\)|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\((?:https?:\/\/[^\s)]+|\/[^\s)]+)\)|\*[^*]+\*|_[^_]+_)/g;
// inlineMarkdown returns the children of one line: plain text and the element
// each matched span becomes, in order.
function inlineMarkdown(text) {
const children = [];
let cursor = 0;
let key = 0;
for (const match of String(text).matchAll(INLINE)) {
if (match.index > cursor) children.push(text.slice(cursor, match.index));
const value = match[0];
if (value.startsWith("![")) {
const img = value.match(/^!\[([^\]]*)\]\((.+)\)$/);
if (img) {
children.push(
<img className="chat-media-img" src={img[2]} alt={img[1] || "Image"} loading="lazy" key={key++} />,
);
}
} else if (value.startsWith("~~")) {
children.push(<del key={key++}>{value.slice(2, -2)}</del>);
} else if (value.startsWith("**") || value.startsWith("__")) {
children.push(<strong key={key++}>{value.slice(2, -2)}</strong>);
} else if (value.startsWith("`")) {
children.push(<code key={key++}>{value.slice(1, -1)}</code>);
} else if (value.startsWith("[")) {
const link = value.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+|\/[^\s)]+)\)$/);
if (link) {
children.push(
<a href={link[2]} target="_blank" rel="noreferrer" key={key++}>
{link[1]}
</a>,
);
}
} else {
children.push(<em key={key++}>{value.slice(1, -1)}</em>);
}
cursor = match.index + value.length;
}
if (cursor < text.length) children.push(text.slice(cursor));
return children;
}
export function ChatMarkdown({ text, className = "chat-bubble-text" }) {
const blocks = [];
const lines = String(text || "").split("\n");
let paragraph = [];
let list = null;
let code = null;
let key = 0;
const flushParagraph = () => {
if (paragraph.length) {
blocks.push(<p key={key++}>{inlineMarkdown(paragraph.join(" "))}</p>);
paragraph = [];
}
};
const flushList = () => {
if (!list) return;
const items = list.items.map((item, i) => <li key={i}>{inlineMarkdown(item)}</li>);
blocks.push(list.tag === "ol" ? <ol key={key++}>{items}</ol> : <ul key={key++}>{items}</ul>);
list = null;
};
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
if (line.startsWith("```")) {
flushParagraph();
flushList();
if (code) {
blocks.push(
<pre key={key++}>
<code>{code.join("\n")}</code>
</pre>,
);
code = null;
} else {
code = [];
}
continue;
}
if (code) {
code.push(line);
continue;
}
const headerCells = tableCells(line);
const separatorCells = index + 1 < lines.length ? tableCells(lines[index + 1]) : null;
if (
headerCells &&
separatorCells &&
isTableSeparator(separatorCells) &&
headerCells.length === separatorCells.length
) {
flushParagraph();
flushList();
const rows = [];
for (index += 2; index < lines.length; index++) {
const cells = tableCells(lines[index]);
if (!cells || cells.length !== headerCells.length) {
index--;
break;
}
rows.push(cells);
}
blocks.push(
<table key={key++}>
<thead>
<tr>
{headerCells.map((cell, i) => (
<th key={i}>{inlineMarkdown(cell)}</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, r) => (
<tr key={r}>
{row.map((cell, c) => (
<td key={c}>{inlineMarkdown(cell)}</td>
))}
</tr>
))}
</tbody>
</table>,
);
continue;
}
if (!line.trim()) {
flushParagraph();
flushList();
continue;
}
const heading = line.match(/^(#{1,3})\s+(.+)$/);
if (heading) {
flushParagraph();
flushList();
const Tag = `h${heading[1].length}`;
blocks.push(<Tag key={key++}>{inlineMarkdown(heading[2])}</Tag>);
continue;
}
const bullet = line.match(/^\s*[-*]\s+(.+)$/);
const ordered = line.match(/^\s*\d+[.)]\s+(.+)$/);
if (bullet || ordered) {
flushParagraph();
const tag = ordered ? "ol" : "ul";
if (!list || list.tag !== tag) {
flushList();
list = { tag, items: [] };
}
list.items.push((bullet || ordered)[1]);
continue;
}
if (line.startsWith(">")) {
flushParagraph();
flushList();
blocks.push(<blockquote key={key++}>{inlineMarkdown(line.replace(/^>\s?/, ""))}</blockquote>);
continue;
}
paragraph.push(line);
}
flushParagraph();
flushList();
if (code) {
blocks.push(
<pre key={key++}>
<code>{code.join("\n")}</code>
</pre>,
);
}
return <div className={className}>{blocks}</div>;
}
function tableCells(line) {
const value = String(line || "").trim();
if (!value.includes("|")) return null;
const unwrapped = value.replace(/^\|/, "").replace(/\|$/, "");
const cells = unwrapped.split("|").map((cell) => cell.trim());
return cells.length > 1 && cells.every((cell) => cell !== "") ? cells : null;
}
function isTableSeparator(cells) {
return cells.every((cell) => /^:?-{3,}:?$/.test(cell));
}
+31
View File
@@ -0,0 +1,31 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import type { ButtonVariants } from '.'
import { Primitive } from 'reka-ui'
import { cn } from '@/lib/utils'
import { buttonVariants } from '.'
interface Props extends PrimitiveProps {
variant?: ButtonVariants['variant']
size?: ButtonVariants['size']
class?: HTMLAttributes['class']
}
const props = withDefaults(defineProps<Props>(), {
as: 'button',
})
</script>
<template>
<Primitive
data-slot="button"
:data-variant="variant"
:data-size="size"
:as="as"
:as-child="asChild"
:class="cn(buttonVariants({ variant, size }), props.class)"
>
<slot />
</Primitive>
</template>
+35
View File
@@ -0,0 +1,35 @@
import type { VariantProps } from 'class-variance-authority'
import { cva } from 'class-variance-authority'
export { default as Button } from './Button.vue'
export const buttonVariants = cva(
'focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:aria-invalid:border-destructive/50 rounded-lg border border-transparent bg-clip-padding text-sm font-medium focus-visible:ring-3 aria-invalid:ring-3 active:not-aria-[haspopup]:translate-y-px [&_svg:not([class*=size-])]:size-4 group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap transition-all outline-none select-none disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0',
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground [a]:hover:bg-primary/80',
outline: 'border-border bg-background hover:bg-muted hover:text-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50 aria-expanded:bg-muted aria-expanded:text-foreground',
secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground',
ghost: 'hover:bg-muted hover:text-foreground dark:hover:bg-muted/50 aria-expanded:bg-muted aria-expanded:text-foreground',
destructive: 'bg-destructive/10 hover:bg-destructive/20 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/20 text-destructive focus-visible:border-destructive/40 dark:hover:bg-destructive/30',
link: 'text-primary underline-offset-4 hover:underline',
},
size: {
'default': 'h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2',
'xs': 'h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*=size-])]:size-3',
'sm': 'h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*=size-])]:size-3.5',
'lg': 'h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2',
'icon': 'size-8',
'icon-xs': 'size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*=size-])]:size-3',
'icon-sm': 'size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg',
'icon-lg': 'size-9',
},
},
defaultVariants: {
variant: 'default',
size: 'default',
},
},
)
export type ButtonVariants = VariantProps<typeof buttonVariants>
@@ -0,0 +1,19 @@
<script setup lang="ts">
import type { DropdownMenuRootEmits, DropdownMenuRootProps } from 'reka-ui'
import { DropdownMenuRoot, useForwardPropsEmits } from 'reka-ui'
const props = defineProps<DropdownMenuRootProps>()
const emits = defineEmits<DropdownMenuRootEmits>()
const forwarded = useForwardPropsEmits(props, emits)
</script>
<template>
<DropdownMenuRoot
v-slot="slotProps"
data-slot="dropdown-menu"
v-bind="forwarded"
>
<slot v-bind="slotProps" />
</DropdownMenuRoot>
</template>
@@ -0,0 +1,43 @@
<script setup lang="ts">
import type { DropdownMenuCheckboxItemEmits, DropdownMenuCheckboxItemProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { CheckIcon } from '@lucide/vue'
import { reactiveOmit } from '@vueuse/core'
import {
DropdownMenuCheckboxItem,
DropdownMenuItemIndicator,
useForwardPropsEmits,
} from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<DropdownMenuCheckboxItemProps & { class?: HTMLAttributes['class'] }>()
const emits = defineEmits<DropdownMenuCheckboxItemEmits>()
const delegatedProps = reactiveOmit(props, 'class')
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<DropdownMenuCheckboxItem
data-slot="dropdown-menu-checkbox-item"
v-bind="forwarded"
:class="cn(
'focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm data-inset:pl-7 [&_svg:not([class*=size-])]:size-4 relative flex cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0',
props.class,
)"
>
<span
class="absolute right-2 flex items-center justify-center pointer-events-none"
data-slot="dropdown-menu-checkbox-item-indicator"
>
<DropdownMenuItemIndicator>
<slot name="indicator-icon">
<CheckIcon />
</slot>
</DropdownMenuItemIndicator>
</span>
<slot />
</DropdownMenuCheckboxItem>
</template>
@@ -0,0 +1,40 @@
<script setup lang="ts">
import type { DropdownMenuContentEmits, DropdownMenuContentProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import {
DropdownMenuContent,
DropdownMenuPortal,
useForwardPropsEmits,
} from 'reka-ui'
import { cn } from '@/lib/utils'
defineOptions({
inheritAttrs: false,
})
const props = withDefaults(
defineProps<DropdownMenuContentProps & { class?: HTMLAttributes['class'] }>(),
{
align: 'start',
sideOffset: 4,
},
)
const emits = defineEmits<DropdownMenuContentEmits>()
const delegatedProps = reactiveOmit(props, 'class')
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<DropdownMenuPortal>
<DropdownMenuContent
data-slot="dropdown-menu-content"
v-bind="{ ...$attrs, ...forwarded }"
:class="cn('data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 bg-popover text-popover-foreground min-w-32 rounded-lg p-1 shadow-md ring-1 duration-100 cn-menu-translucent z-50 max-h-(--reka-dropdown-menu-content-available-height) w-(--reka-dropdown-menu-trigger-width) origin-(--reka-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto data-[state=closed]:overflow-hidden', props.class)"
>
<slot />
</DropdownMenuContent>
</DropdownMenuPortal>
</template>
@@ -0,0 +1,15 @@
<script setup lang="ts">
import type { DropdownMenuGroupProps } from 'reka-ui'
import { DropdownMenuGroup } from 'reka-ui'
const props = defineProps<DropdownMenuGroupProps>()
</script>
<template>
<DropdownMenuGroup
data-slot="dropdown-menu-group"
v-bind="props"
>
<slot />
</DropdownMenuGroup>
</template>
@@ -0,0 +1,31 @@
<script setup lang="ts">
import type { DropdownMenuItemProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { DropdownMenuItem, useForwardProps } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = withDefaults(defineProps<DropdownMenuItemProps & {
class?: HTMLAttributes['class']
inset?: boolean
variant?: 'default' | 'destructive'
}>(), {
variant: 'default',
})
const delegatedProps = reactiveOmit(props, 'inset', 'variant', 'class')
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<DropdownMenuItem
data-slot="dropdown-menu-item"
:data-inset="inset ? '' : undefined"
:data-variant="variant"
v-bind="forwardedProps"
:class="cn('focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:text-destructive not-data-[variant=destructive]:focus:**:text-accent-foreground gap-1.5 rounded-md px-1.5 py-1 text-sm data-inset:pl-7 [&_svg:not([class*=size-])]:size-4 group/dropdown-menu-item relative flex cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0', props.class)"
>
<slot />
</DropdownMenuItem>
</template>
@@ -0,0 +1,23 @@
<script setup lang="ts">
import type { DropdownMenuLabelProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { DropdownMenuLabel, useForwardProps } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<DropdownMenuLabelProps & { class?: HTMLAttributes['class'], inset?: boolean }>()
const delegatedProps = reactiveOmit(props, 'class', 'inset')
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<DropdownMenuLabel
data-slot="dropdown-menu-label"
:data-inset="inset ? '' : undefined"
v-bind="forwardedProps"
:class="cn('text-muted-foreground px-1.5 py-1 text-xs font-medium data-inset:pl-7', props.class)"
>
<slot />
</DropdownMenuLabel>
</template>
@@ -0,0 +1,21 @@
<script setup lang="ts">
import type { DropdownMenuRadioGroupEmits, DropdownMenuRadioGroupProps } from 'reka-ui'
import {
DropdownMenuRadioGroup,
useForwardPropsEmits,
} from 'reka-ui'
const props = defineProps<DropdownMenuRadioGroupProps>()
const emits = defineEmits<DropdownMenuRadioGroupEmits>()
const forwarded = useForwardPropsEmits(props, emits)
</script>
<template>
<DropdownMenuRadioGroup
data-slot="dropdown-menu-radio-group"
v-bind="forwarded"
>
<slot />
</DropdownMenuRadioGroup>
</template>
@@ -0,0 +1,44 @@
<script setup lang="ts">
import type { DropdownMenuRadioItemEmits, DropdownMenuRadioItemProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { CheckIcon } from '@lucide/vue'
import { reactiveOmit } from '@vueuse/core'
import {
DropdownMenuItemIndicator,
DropdownMenuRadioItem,
useForwardPropsEmits,
} from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<DropdownMenuRadioItemProps & { class?: HTMLAttributes['class'] }>()
const emits = defineEmits<DropdownMenuRadioItemEmits>()
const delegatedProps = reactiveOmit(props, 'class')
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<DropdownMenuRadioItem
data-slot="dropdown-menu-radio-item"
v-bind="forwarded"
:class="cn(
'focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm data-inset:pl-7 [&_svg:not([class*=size-])]:size-4 relative flex cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0',
props.class,
)"
>
<span
class="absolute right-2 flex items-center justify-center pointer-events-none"
data-slot="dropdown-menu-radio-item-indicator"
>
<DropdownMenuItemIndicator>
<slot name="indicator-icon">
<CheckIcon />
</slot>
</DropdownMenuItemIndicator>
</span>
<slot />
</DropdownMenuRadioItem>
</template>
@@ -0,0 +1,23 @@
<script setup lang="ts">
import type { DropdownMenuSeparatorProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import {
DropdownMenuSeparator,
} from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<DropdownMenuSeparatorProps & {
class?: HTMLAttributes['class']
}>()
const delegatedProps = reactiveOmit(props, 'class')
</script>
<template>
<DropdownMenuSeparator
data-slot="dropdown-menu-separator"
v-bind="delegatedProps"
:class="cn('bg-border -mx-1 my-1 h-px', props.class)"
/>
</template>
@@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<span
data-slot="dropdown-menu-shortcut"
:class="cn('text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground ml-auto text-xs tracking-widest', props.class)"
>
<slot />
</span>
</template>
@@ -0,0 +1,18 @@
<script setup lang="ts">
import type { DropdownMenuSubEmits, DropdownMenuSubProps } from 'reka-ui'
import {
DropdownMenuSub,
useForwardPropsEmits,
} from 'reka-ui'
const props = defineProps<DropdownMenuSubProps>()
const emits = defineEmits<DropdownMenuSubEmits>()
const forwarded = useForwardPropsEmits(props, emits)
</script>
<template>
<DropdownMenuSub v-slot="slotProps" data-slot="dropdown-menu-sub" v-bind="forwarded">
<slot v-bind="slotProps" />
</DropdownMenuSub>
</template>
@@ -0,0 +1,27 @@
<script setup lang="ts">
import type { DropdownMenuSubContentEmits, DropdownMenuSubContentProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import {
DropdownMenuSubContent,
useForwardPropsEmits,
} from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<DropdownMenuSubContentProps & { class?: HTMLAttributes['class'] }>()
const emits = defineEmits<DropdownMenuSubContentEmits>()
const delegatedProps = reactiveOmit(props, 'class')
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<DropdownMenuSubContent
data-slot="dropdown-menu-sub-content"
v-bind="forwarded"
:class="cn('data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 bg-popover text-popover-foreground min-w-[96px] rounded-lg p-1 shadow-lg ring-1 duration-100 cn-menu-translucent z-50 max-w-(--reka-dropdown-menu-content-available-width) origin-(--reka-dropdown-menu-content-transform-origin) overflow-hidden', props.class)"
>
<slot />
</DropdownMenuSubContent>
</template>
@@ -0,0 +1,32 @@
<script setup lang="ts">
import type { DropdownMenuSubTriggerProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { ChevronRightIcon } from '@lucide/vue'
import { reactiveOmit } from '@vueuse/core'
import {
DropdownMenuSubTrigger,
useForwardProps,
} from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<DropdownMenuSubTriggerProps & { class?: HTMLAttributes['class'], inset?: boolean }>()
const delegatedProps = reactiveOmit(props, 'class', 'inset')
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<DropdownMenuSubTrigger
data-slot="dropdown-menu-sub-trigger"
:data-inset="inset ? '' : undefined"
v-bind="forwardedProps"
:class="cn(
'focus:bg-accent focus:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground gap-1.5 rounded-md px-1.5 py-1 text-sm data-inset:pl-7 [&_svg:not([class*=size-])]:size-4 flex cursor-default items-center outline-hidden select-none [&_svg]:pointer-events-none [&_svg]:shrink-0',
props.class,
)"
>
<slot />
<ChevronRightIcon class="cn-rtl-flip ml-auto" />
</DropdownMenuSubTrigger>
</template>
@@ -0,0 +1,17 @@
<script setup lang="ts">
import type { DropdownMenuTriggerProps } from 'reka-ui'
import { DropdownMenuTrigger, useForwardProps } from 'reka-ui'
const props = defineProps<DropdownMenuTriggerProps>()
const forwardedProps = useForwardProps(props)
</script>
<template>
<DropdownMenuTrigger
data-slot="dropdown-menu-trigger"
v-bind="forwardedProps"
>
<slot />
</DropdownMenuTrigger>
</template>
@@ -0,0 +1,16 @@
export { default as DropdownMenu } from './DropdownMenu.vue'
export { default as DropdownMenuCheckboxItem } from './DropdownMenuCheckboxItem.vue'
export { default as DropdownMenuContent } from './DropdownMenuContent.vue'
export { default as DropdownMenuGroup } from './DropdownMenuGroup.vue'
export { default as DropdownMenuItem } from './DropdownMenuItem.vue'
export { default as DropdownMenuLabel } from './DropdownMenuLabel.vue'
export { default as DropdownMenuRadioGroup } from './DropdownMenuRadioGroup.vue'
export { default as DropdownMenuRadioItem } from './DropdownMenuRadioItem.vue'
export { default as DropdownMenuSeparator } from './DropdownMenuSeparator.vue'
export { default as DropdownMenuShortcut } from './DropdownMenuShortcut.vue'
export { default as DropdownMenuSub } from './DropdownMenuSub.vue'
export { default as DropdownMenuSubContent } from './DropdownMenuSubContent.vue'
export { default as DropdownMenuSubTrigger } from './DropdownMenuSubTrigger.vue'
export { default as DropdownMenuTrigger } from './DropdownMenuTrigger.vue'
export { DropdownMenuPortal } from 'reka-ui'
-17
View File
@@ -1,17 +0,0 @@
/*
* Style entry point. One file per concern, imported here in cascade order:
* tokens first (everything depends on them), then element defaults, then
* layout, then components. Feature folders own their own CSS and import it
* from their JS rather than adding to this list.
*/
@import "./tokens.css";
@import "./base.css";
@import "./layout.css";
@import "./page.css";
@import "./button.css";
@import "./card.css";
@import "./pill.css";
@import "./table.css";
@import "./empty.css";
@import "./responsive.css";
-70
View File
@@ -1,70 +0,0 @@
/* Element defaults. Nothing here is component-specific. */
/*
* App shell and shared primitives. Feature folders style their own specifics;
* anything that appears on more than one page lives here so pages cannot
* drift into three visual languages.
*/
*,
*::before,
*::after {
box-sizing: border-box;
}
html,
body {
margin: 0;
height: 100%;
}
body {
color: var(--fg);
font-family: var(--font-sans);
font-size: var(--text-base);
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
a {
color: inherit;
text-decoration: none;
}
/* The focus floor. A component may style its own focus state; this guarantees
that nothing is ever focused and invisible for a keyboard user. `:focus-visible`
rather than `:focus` so a mouse click does not draw a ring around what was
clicked. */
:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
/* Accessible-only text: present to assistive technology, out of the visual
layout. Used for live-region status lines, which announce a change without
drawing a second, visible copy of the pane's own copy. */
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
padding: 0;
border: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
/* Visible to assistive technology only. For a control whose purpose is clear
from its position but which still needs a name in the accessibility tree. */
.sr-only {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
padding: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
border: 0;
}
-37
View File
@@ -1,37 +0,0 @@
/* Buttons. One shape, three weights. */
.btn {
display: inline-flex;
align-items: center;
gap: var(--sp-2);
padding: var(--sp-2) var(--sp-4);
border-radius: var(--radius-pill);
border: 1px solid var(--border-strong);
background: var(--surface);
color: var(--fg);
font: inherit;
font-size: var(--text-sm);
cursor: pointer;
transition: background var(--transition), border-color var(--transition);
}
.btn:hover {
background: var(--surface-hover);
}
.btn-primary {
background: var(--accent);
border-color: var(--accent);
color: var(--accent-fg);
font-weight: 500;
}
.btn-primary:hover {
filter: brightness(1.08);
background: var(--accent);
}
.btn-icon {
padding: var(--sp-2);
border-radius: var(--radius-sm);
}
-53
View File
@@ -1,53 +0,0 @@
/* Cards and the grids that arrange them. */
.card {
background: var(--surface-glass);
backdrop-filter: blur(14px);
border: 1px solid var(--hairline);
border-radius: var(--radius-lg);
padding: var(--sp-5);
box-shadow: var(--shadow-sm);
/* Wide content (data tables, long values) scrolls inside the card on
narrow screens instead of stretching the page. */
overflow-x: auto;
}
.card-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-3);
margin-bottom: var(--sp-4);
flex-wrap: wrap;
}
.card-title {
font-size: var(--text-base);
font-weight: 600;
margin: 0;
}
.card-sub {
font-size: var(--text-xs);
color: var(--fg-muted);
margin: var(--sp-1) 0 0;
}
.grid {
display: grid;
gap: var(--sp-4);
}
/* Grid tracks never grow past the viewport: an item that would blow out
scrolls inside its own scroll container instead. */
.grid > * {
min-width: 0;
}
.grid-4 {
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
}
.grid-2 {
grid-template-columns: repeat(auto-fit, minmax(340px, 1fr));
}
-26
View File
@@ -1,26 +0,0 @@
/* Empty and loading states. */
.empty {
text-align: center;
padding: var(--sp-7) var(--sp-4);
color: var(--fg-muted);
}
.empty-title {
color: var(--fg);
font-weight: 500;
margin-bottom: var(--sp-1);
}
.skeleton {
background: linear-gradient(90deg, var(--surface) 25%, var(--surface-hover) 50%, var(--surface) 75%);
background-size: 200% 100%;
animation: shimmer 1.4s infinite;
border-radius: var(--radius-sm);
}
@keyframes shimmer {
to {
background-position: -200% 0;
}
}
-498
View File
@@ -1,498 +0,0 @@
/* The shell: one contained, rounded application surface floating on a lit
* canvas.
*
* The dashboard is a *workspace*, not a document that fills the viewport --
* framing it gives the panels an edge to sit against, and lets the canvas
* behind read as light rather than wallpaper. Everything inside is translucent
* so that light carries through instead of stopping at the first opaque card.
*/
body {
/* The luminous canvas. Large, off-axis and low-frequency, so it lights the
workspace rather than competing with it. */
background:
radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%),
radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%),
radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%),
var(--bg);
background-attachment: fixed;
padding: var(--sp-4);
}
.shell {
min-height: calc(100vh - var(--sp-4) * 2);
display: flex;
flex-direction: column;
border-radius: var(--radius-xl);
border: 1px solid var(--hairline);
background: var(--workspace);
backdrop-filter: blur(28px) saturate(120%);
box-shadow: var(--shadow-workspace);
overflow: hidden;
}
/* ── Command bar ────────────────────────────────────────────────────────── */
.topbar {
display: flex;
align-items: center;
gap: var(--sp-4);
padding: var(--sp-3) var(--sp-4);
border-bottom: 1px solid var(--hairline);
background: var(--bg-blur);
position: sticky;
top: 0;
z-index: 10;
}
.brand {
display: flex;
align-items: center;
gap: var(--sp-2);
font-weight: 600;
font-size: var(--text-sm);
letter-spacing: -0.01em;
flex: none;
}
.brand-mark {
width: 26px;
height: 26px;
border-radius: 8px;
background: linear-gradient(135deg, var(--accent), var(--accent-2));
display: grid;
place-items: center;
color: #fff;
font-size: var(--text-xs);
font-weight: 700;
}
/* Navigation is always labelled. Operators should never have to memorise an
icon vocabulary just to move around the control plane. */
.nav {
display: flex;
align-items: center;
gap: 2px;
margin: 0 auto;
/* The nav is the only region that can afford to lose width, so it is the
only one allowed to shrink. min-width:0 lets it actually do so inside a
flex row, and the scroll is the last resort before anything clips --
.app sets overflow:hidden, so an unshrinkable row loses the utility
cluster off the right edge with no way to reach it. */
flex: 0 1 auto;
min-width: 0;
overflow-x: auto;
scrollbar-width: none;
padding: 3px;
border-radius: var(--radius-pill);
background: var(--surface-glass-strong);
border: 1px solid var(--hairline);
}
.nav::-webkit-scrollbar {
display: none;
}
.nav-item {
display: inline-flex;
flex: none;
align-items: center;
gap: var(--sp-2);
padding: var(--sp-2) var(--sp-3);
border-radius: var(--radius-pill);
color: var(--fg-muted);
font-size: var(--text-sm);
white-space: nowrap;
cursor: pointer;
transition: background var(--transition), color var(--transition);
}
.nav-item:hover {
color: var(--fg);
background: var(--surface-hover);
}
.nav-item[aria-current="page"] {
background: var(--accent);
color: var(--accent-fg);
font-weight: 500;
}
.nav-item .nav-label {
display: inline;
}
/* ── Utility cluster ────────────────────────────────────────────────────── */
.topbar-end {
display: flex;
align-items: center;
gap: var(--sp-2);
flex: none;
}
.topbar-search {
display: flex;
align-items: center;
gap: var(--sp-2);
padding: var(--sp-2) var(--sp-3);
border-radius: var(--radius-pill);
background: var(--surface-glass-strong);
border: 1px solid var(--hairline);
color: var(--fg-subtle);
}
.topbar-search input {
background: none;
border: 0;
color: var(--fg);
font: inherit;
font-size: var(--text-sm);
width: 8rem;
outline: none;
}
.topbar-search input::placeholder {
color: var(--fg-subtle);
}
.mobile-search-toggle {
display: none;
}
.icon-btn {
display: grid;
place-items: center;
width: 32px;
height: 32px;
border-radius: var(--radius-pill);
border: 1px solid var(--hairline);
background: var(--surface-glass-strong);
color: var(--fg-muted);
cursor: pointer;
transition: color var(--transition), background var(--transition);
}
.icon-btn:hover {
color: var(--fg);
background: var(--surface-hover);
}
.avatar {
width: 32px;
height: 32px;
border-radius: var(--radius-pill);
display: grid;
place-items: center;
font-size: var(--text-xs);
font-weight: 600;
color: #fff;
background: linear-gradient(135deg, var(--accent), var(--accent-2));
cursor: pointer;
flex: none;
}
.ico {
flex: none;
display: block;
}
/* ── Canvas ─────────────────────────────────────────────────────────────── */
.main {
padding: var(--sp-6);
width: 100%;
flex: 1;
overflow-x: hidden;
}
/* ── Chat launcher and panel ─────────────────────────────────────────── */
/* A floating launcher, bottom-right, and the panel it opens immediately to
its left. The two share a bottom edge and the panel grows out of the button,
so the launcher never moves and always reads as the thing that produced the
panel.
Deliberately not a modal: no scrim, no body scroll lock, no focus trap. The
operator asks Archie about the page they are on, so that page has to stay
readable, scrollable and clickable while the panel is open. */
.chat-dock {
--fab-size: 56px;
--fab-inset: var(--sp-5);
--fab-gap: var(--sp-3);
position: fixed;
right: var(--fab-inset);
bottom: var(--fab-inset);
z-index: 40;
}
.chat-fab {
position: relative;
display: grid;
place-items: center;
width: var(--fab-size);
height: var(--fab-size);
border: 0;
border-radius: var(--radius-pill);
background: linear-gradient(135deg, var(--accent), var(--accent-2));
color: #fff;
cursor: pointer;
box-shadow: var(--shadow-md);
transition: transform var(--transition), box-shadow var(--transition);
}
.chat-fab:hover {
transform: translateY(-1px);
box-shadow: 0 12px 34px color-mix(in srgb, var(--accent) 38%, transparent);
}
.chat-fab:active {
transform: translateY(0);
}
/* Both glyphs are stacked and cross-faded, so the button keeps one size and
the swap cannot reflow the dock. */
.chat-fab-icon {
grid-area: 1 / 1;
display: grid;
place-items: center;
transition: opacity var(--transition), transform var(--transition);
}
.chat-fab-icon-close,
.chat-dock.is-open .chat-fab-icon-open {
opacity: 0;
transform: scale(0.7) rotate(-45deg);
}
.chat-fab-icon-open,
.chat-dock.is-open .chat-fab-icon-close {
opacity: 1;
transform: none;
}
/* The panel is positioned off the dock, not the viewport: it sits one gap to
the left of the launcher and rises from the shared bottom edge. */
.chat-drawer {
position: absolute;
right: calc(var(--fab-size) + var(--fab-gap));
bottom: 0;
width: min(440px, calc(100vw - var(--fab-size) - var(--fab-gap) - var(--fab-inset) * 2));
height: min(640px, calc(100vh - var(--fab-inset) * 2));
pointer-events: none;
}
/* The panel grows out of the launcher. Closed, it is collapsed to a small
round shape sitting exactly over the button; open, it is the full panel
beside it. Scaling from the bottom-right corner and translating by the
launcher's own width is what makes the button appear to become the panel,
rather than a panel merely fading in next to it. */
.chat-drawer-panel {
pointer-events: auto;
display: grid;
/* One child: ChatApp, which owns its own header row. A second track here
left an empty band under the composer. */
grid-template-rows: minmax(0, 1fr);
width: 100%;
height: 100%;
background: var(--surface);
border: 1px solid var(--border);
box-shadow: var(--shadow-md);
overflow: hidden;
opacity: 0;
border-radius: var(--radius-pill);
transform-origin: bottom right;
transform: translateX(calc(var(--fab-size) + var(--fab-gap))) scale(0.16);
transition:
opacity 160ms cubic-bezier(0.4, 0, 0.2, 1),
transform 260ms cubic-bezier(0.22, 1, 0.36, 1),
border-radius 260ms cubic-bezier(0.22, 1, 0.36, 1);
}
.chat-drawer.is-open .chat-drawer-panel {
opacity: 1;
border-radius: var(--radius-lg);
transform: none;
}
/* The contents follow the shape rather than stretching with it: they fade in
once the panel is most of the way open, so the morph reads as a container
opening instead of a page being scaled up. */
.chat-drawer-panel > * {
opacity: 0;
transition: opacity 120ms linear;
}
.chat-drawer.is-open .chat-drawer-panel > * {
opacity: 1;
transition: opacity 160ms linear 120ms;
}
/* A closed panel is still mounted so the session and its stream survive. It
must not take hits or reach the tab order while invisible. */
.chat-drawer:not(.is-open) .chat-drawer-panel {
pointer-events: none;
visibility: hidden;
transition:
opacity 140ms cubic-bezier(0.4, 0, 0.2, 1),
transform 200ms cubic-bezier(0.4, 0, 1, 1),
border-radius 200ms cubic-bezier(0.4, 0, 1, 1),
visibility 0s linear 200ms;
}
.chat-drawer-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-2);
padding: var(--sp-3) var(--sp-4);
border-bottom: 1px solid var(--border);
}
/* Below this there is no room beside the launcher, so the panel stops being
anchored to it and becomes a sheet on the viewport. The launcher hides while
the sheet is up: its own close button is the way out. */
@media (max-width: 720px) {
.chat-dock {
--fab-inset: var(--sp-4);
}
.chat-drawer {
position: fixed;
right: var(--fab-inset);
left: var(--fab-inset);
/* Clears the launcher, which stays put as the close control. */
bottom: calc(var(--fab-inset) + var(--fab-size) + var(--fab-gap));
width: auto;
height: min(72vh, calc(100vh - var(--fab-inset) * 2 - var(--fab-size) - var(--fab-gap)));
}
/* The sheet sits above the launcher rather than beside it, so it grows down
toward the button instead of sideways. */
.chat-drawer-panel {
transform-origin: bottom right;
transform: translateY(calc(var(--fab-size) + var(--fab-gap))) scale(0.16);
}
/* The launcher is the only way to close the panel, so it stays above the
sheet rather than hiding under it. */
.chat-fab {
position: relative;
z-index: 1;
}
}
/* ── Collapsed search ───────────────────────────────────────────────────── */
/* The always-open "Jump to" field is the widest thing in the utility cluster
and the least often used. Past this width it collapses to its icon and
expands on demand, which is what keeps the nav from having to scroll at
ordinary laptop sizes. Measured: the labelled nav needs 917px and the
collapsed cluster 160px, so an expanded field does not fit beside them until
about 1430px -- collapsing to 1500 keeps 1440 comfortable rather than
marginal. */
@media (max-width: 1500px) {
.topbar-search {
padding: 0;
border: 0;
background: transparent;
overflow: hidden;
}
.topbar-search-icon {
display: none;
}
.mobile-search-toggle {
display: grid;
}
.topbar-search input {
width: 0;
padding: 0;
opacity: 0;
pointer-events: none;
transition: width var(--transition), opacity var(--transition);
}
.topbar-search.is-open,
.topbar-search:focus-within {
padding-right: var(--sp-2);
border: 1px solid var(--hairline);
background: var(--surface-glass-strong);
}
.topbar-search.is-open input,
.topbar-search:focus-within input {
width: min(9rem, 34vw);
opacity: 1;
pointer-events: auto;
}
}
/* ── Constrained desktop ────────────────────────────────────────────────── */
/* The nav needs 917px on one line. Below the width where it still fits beside
the brand and the collapsed cluster it takes a row of its own, which reads
better than the scroll that would otherwise kick in. */
@media (max-width: 1270px) and (min-width: 901px) {
.topbar {
flex-wrap: wrap;
}
.nav {
order: 3;
width: 100%;
margin: 0;
justify-content: center;
flex-wrap: wrap;
border-radius: var(--radius-lg);
}
}
/* ── Narrow screens ─────────────────────────────────────────────────────── */
/* The frame is a desktop affordance. Below the breakpoint the workspace goes
edge to edge -- a rounded card inset on a phone wastes the only axis that
matters -- and the icon bar becomes a scrollable labelled row. */
@media (max-width: 900px) {
body {
padding: 0;
}
.shell {
min-height: 100vh;
border-radius: 0;
border: 0;
box-shadow: none;
}
.topbar {
flex-wrap: wrap;
padding: var(--sp-3);
gap: var(--sp-2);
}
.nav {
order: 3;
width: 100%;
overflow-x: auto;
justify-content: flex-start;
flex-wrap: nowrap;
border-radius: var(--radius-lg);
scrollbar-width: none;
}
.nav::-webkit-scrollbar {
display: none;
}
.nav-item .nav-label {
display: inline;
}
.main {
padding: var(--sp-4);
}
}
-29
View File
@@ -1,29 +0,0 @@
/* Page header: title, subtitle and the actions that belong to a page. */
.page-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: var(--sp-5);
margin-bottom: var(--sp-6);
flex-wrap: wrap;
}
.page-title {
font-size: var(--text-2xl);
font-weight: 600;
letter-spacing: -0.02em;
margin: 0;
}
.page-sub {
color: var(--fg-muted);
font-size: var(--text-sm);
margin: var(--sp-1) 0 0;
}
.page-actions {
display: flex;
gap: var(--sp-2);
align-items: center;
}
-43
View File
@@ -1,43 +0,0 @@
/* Status pills. The only place status colour is decided. */
/* Status is always a pill, never bare text: a colour and a shape are read at
a glance where a word has to be parsed. */
.pill {
display: inline-flex;
align-items: center;
gap: var(--sp-1);
padding: 2px var(--sp-2);
border-radius: var(--radius-pill);
font-size: var(--text-xs);
font-weight: 500;
white-space: nowrap;
}
.pill::before {
content: "";
width: 5px;
height: 5px;
border-radius: 50%;
background: currentColor;
}
.pill-ok {
color: var(--ok);
background: var(--ok-soft);
}
.pill-warn {
color: var(--warn);
background: var(--warn-soft);
}
.pill-danger {
color: var(--danger);
background: var(--danger-soft);
}
.pill-info {
color: var(--info);
background: var(--info-soft);
}
.pill-idle {
color: var(--idle);
background: var(--idle-soft);
}
-30
View File
@@ -1,30 +0,0 @@
/* Motion preferences and narrow viewports. */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
.nav-soon {
margin-left: auto;
font-size: var(--text-xs);
color: var(--fg-subtle);
background: var(--surface-hover);
padding: 1px var(--sp-2);
border-radius: var(--radius-pill);
}
.nav-item[aria-disabled] {
opacity: 0.55;
cursor: default;
}
.nav-item[aria-disabled]:hover {
background: none;
color: var(--fg-muted);
}
-55
View File
@@ -1,55 +0,0 @@
/* Data tables. */
.table {
width: 100%;
border-collapse: collapse;
font-size: var(--text-sm);
}
/* Contained horizontal scrolling for wide tables: the page stays put and the
table scrolls inside this wrapper, so a 7-column table is usable at 390px. */
.table-scroll {
max-width: 100%;
min-width: 0;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
.table-scroll > .table {
min-width: 42rem;
}
.table th {
text-align: left;
font-weight: 500;
font-size: var(--text-xs);
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--fg-subtle);
padding: 0 var(--sp-3) var(--sp-3);
border-bottom: 1px solid var(--border);
}
.table td {
padding: var(--sp-3);
border-bottom: 1px solid var(--border);
color: var(--fg-muted);
}
.table tbody tr:last-child td {
border-bottom: 0;
}
.table tbody tr:hover td {
background: var(--surface-hover);
}
.table td.strong {
color: var(--fg);
font-weight: 500;
}
.mono {
font-family: var(--font-mono);
font-size: 0.95em;
}
-137
View File
@@ -1,137 +0,0 @@
/*
* Design tokens. Dark is the default because archied is a daemon you check at
* odd hours; light is a toggle, not an afterthought, so both themes define the
* same variable set and nothing else in the app references a raw colour.
*
* Semantic names only. Never `--blue`; always `--accent` or `--status-running`,
* so a palette change is one file rather than a grep.
*/
:root {
/* Type */
--font-sans:
ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;
--font-mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;
--text-xs: 0.6875rem;
--text-sm: 0.8125rem;
--text-base: 0.875rem;
--text-lg: 1.0625rem;
--text-xl: 1.375rem;
--text-2xl: 1.875rem;
--text-3xl: 2.5rem;
/* Spacing: a 4px scale. Layout uses these, never magic pixels. */
--sp-1: 0.25rem;
--sp-2: 0.5rem;
--sp-3: 0.75rem;
--sp-4: 1rem;
--sp-5: 1.5rem;
--sp-6: 2rem;
--sp-7: 3rem;
--radius-sm: 6px;
--radius-md: 10px;
--radius-lg: 14px;
--radius-xl: 20px;
--radius-pill: 999px;
--transition: 140ms cubic-bezier(0.4, 0, 0.2, 1);
}
/* ── Dark (default) ─────────────────────────────────────────────────────── */
[data-theme="dark"] {
color-scheme: dark;
--bg: #0d1014;
--bg-raised: #141920;
--surface: #171d25;
--surface-hover: #1d242e;
--border: #232b36;
--border-strong: #303a48;
--fg: #e8edf4;
--fg-muted: #8b97a8;
--fg-subtle: #7d8b9e;
--accent: #4c8dff;
/* Near-black, not white: white on this blue is 3.2:1 and fails AA on the
active nav item and every primary button. The accent stays as-is because
it is also the link colour, where it reads correctly on the dark canvas. */
--accent-fg: #0d1014;
--accent-soft: rgba(76, 141, 255, 0.14);
/* Status. Used for task state, gate results and trend direction alike, so
the same colour always means the same thing wherever it appears. */
--ok: #3fbf7f;
--ok-soft: rgba(63, 191, 127, 0.14);
--warn: #e8a33d;
--warn-soft: rgba(232, 163, 61, 0.14);
--danger: #f0616d;
--danger-soft: rgba(240, 97, 109, 0.14);
--info: #4c8dff;
--info-soft: rgba(76, 141, 255, 0.14);
--idle: #6b7688;
--idle-soft: rgba(107, 118, 136, 0.14);
--accent-2: #7b5cff;
--bg-blur: rgba(20, 25, 32, 0.55);
/* Panels are translucent so the canvas wash shows through and the whole
workspace reads as one lit surface rather than opaque cards on a picture. */
--surface-glass: rgba(23, 29, 37, 0.62);
--surface-glass-strong: rgba(20, 25, 32, 0.78);
--workspace: rgba(17, 21, 27, 0.55);
--hairline: rgba(255, 255, 255, 0.06);
--wash-a: rgba(76, 141, 255, 0.10);
--wash-b: rgba(123, 92, 255, 0.12);
--wash-c: rgba(63, 191, 127, 0.06);
--shadow-workspace: 0 24px 70px rgba(0, 0, 0, 0.5);
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.4);
--shadow-md: 0 8px 28px rgba(0, 0, 0, 0.42);
}
/* ── Light ──────────────────────────────────────────────────────────────── */
[data-theme="light"] {
color-scheme: light;
--bg: #f6f8fb;
--bg-raised: #ffffff;
--surface: #ffffff;
--surface-hover: #f1f4f9;
--border: #e2e8f0;
--border-strong: #cbd5e1;
--fg: #16202e;
--fg-muted: #5a6779;
--fg-subtle: #636f82;
--accent: #2563eb;
--accent-fg: #ffffff;
--accent-soft: rgba(37, 99, 235, 0.1);
--ok: #10935c;
--ok-soft: rgba(16, 147, 92, 0.12);
--warn: #b87514;
--warn-soft: rgba(184, 117, 20, 0.12);
--danger: #d4344a;
--danger-soft: rgba(212, 52, 74, 0.12);
--info: #2563eb;
--info-soft: rgba(37, 99, 235, 0.1);
--idle: #64748b;
--idle-soft: rgba(100, 116, 139, 0.12);
--accent-2: #7c3aed;
--bg-blur: rgba(255, 255, 255, 0.6);
--surface-glass: rgba(255, 255, 255, 0.72);
--surface-glass-strong: rgba(255, 255, 255, 0.88);
--workspace: rgba(255, 255, 255, 0.55);
--hairline: rgba(15, 23, 42, 0.06);
--wash-a: rgba(37, 99, 235, 0.10);
--wash-b: rgba(124, 58, 237, 0.12);
--wash-c: rgba(16, 147, 92, 0.07);
--shadow-workspace: 0 24px 70px rgba(15, 23, 42, 0.14);
--shadow-sm: 0 1px 2px rgba(15, 23, 42, 0.06);
--shadow-md: 0 8px 28px rgba(15, 23, 42, 0.10);
}
-62
View File
@@ -1,62 +0,0 @@
/* Curators-only styles. */
.curator-card {
display: flex;
flex-direction: column;
gap: var(--sp-2);
}
.curator-health-message {
color: var(--fg-muted);
font-size: var(--text-sm);
margin: 0;
}
.curator-meta {
color: var(--fg-subtle);
font-size: var(--text-xs);
margin: 0;
}
.curator-actions {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: var(--sp-2);
}
.curator-action {
border-top: 1px solid var(--border);
padding-top: var(--sp-2);
}
.curator-action-head {
display: flex;
justify-content: space-between;
gap: var(--sp-2);
font-size: var(--text-sm);
}
.curator-action-type {
font-weight: 600;
color: var(--fg);
}
.curator-action-time {
color: var(--fg-subtle);
font-size: var(--text-xs);
}
.curator-action-detail {
color: var(--fg-muted);
font-size: var(--text-sm);
margin: var(--sp-1) 0 0;
}
.curator-action-reason {
color: var(--fg-subtle);
font-size: var(--text-xs);
margin: var(--sp-1) 0 0;
}
-124
View File
@@ -1,124 +0,0 @@
import { h, Fragment } from "preact";
import { useState, useEffect } from "preact/hooks";
import "./curators.css";
import { api } from "../base/api.jsx";
import { ago } from "../base/format.jsx";
import { Pill } from "../base/pill.jsx";
function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
/**
* Curator observability (archie-core-1786637489932-6). Backed by GET
* /api/curators, which reads the daemon's live curator.Registry: which
* curators are registered, their point-in-time health, and their recent
* activity (last run, action count, and the actions themselves with the
* reason each one happened) -- see internal/webui/api_curators.go.
*/
export function curatorsPage(query) {
return <CuratorsApp query={query} />;
}
function CuratorsApp({ query }) {
const [curators, setCurators] = useState([]);
const [loadError, setLoadError] = useState(null);
const load = async () => {
try {
const res = await api.curators();
setCurators(res?.curators || []);
setLoadError(null);
} catch (err) {
setLoadError(String(err.message || err));
}
};
useEffect(() => {
load();
}, []);
const renderCards = () => {
if (loadError) {
return <Empty title="Cannot reach archied" detail={loadError} />;
}
if (!curators.length) {
return (
<Empty
title="No curators registered"
detail="Curators are background agent loops that maintain memory and skills. None are registered on this daemon."
/>
);
}
return curators.map(c => <CuratorCard key={c.name} curator={c} />);
};
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Curators</h1>
<p className="page-sub">Background agents that maintain memory and skills: what ran, and why.</p>
</div>
<div className="page-actions">
<button className="btn" onClick={load}>Refresh</button>
</div>
</div>
<div className="grid grid-2">
{renderCards()}
</div>
</div>
);
}
function healthKind(status) {
switch (status) {
case "healthy":
return "ok";
case "degraded":
return "warn";
case "unhealthy":
return "danger";
default:
return "idle";
}
}
function CuratorCard({ curator: c }) {
const actions = c.recent_actions || [];
return (
<div className="card curator-card">
<div className="card-head">
<h3 className="card-title">{c.name}</h3>
<Pill text={c.health?.status || "unknown"} kind={healthKind(c.health?.status)} />
</div>
{c.health?.message && <p className="curator-health-message">{c.health.message}</p>}
<p className="curator-meta">
{c.last_run_at
? `Last ran ${ago(c.last_run_at)} · ${c.last_run_actions} action${c.last_run_actions === 1 ? "" : "s"}`
: "Has not run yet"}
</p>
{actions.length ? (
<ul className="curator-actions">
{actions.map((a, i) => (
<li className="curator-action" key={i}>
<div className="curator-action-head">
<span className="curator-action-type">{a.type || "action"}</span>
<span className="curator-action-time">{ago(a.at)}</span>
</div>
{a.detail && <p className="curator-action-detail">{a.detail}</p>}
{a.reason && <p className="curator-action-reason">Why: {a.reason}</p>}
</li>
))}
</ul>
) : (
<p className="curator-meta">No recorded activity yet.</p>
)}
</div>
);
}
-30
View File
@@ -1,30 +0,0 @@
// Live activity's detail column.
//
// The daemon puts whatever a stage produced into an event's detail, so the
// column holds anything from "session-memory" to a few thousand characters of
// agent transcript. Printed raw, one agent_finish row was taller than six
// viewports and the table stopped being scannable (archie-core-qo7f).
//
// The rule is one line in the cell, the whole payload still available. The cut
// happens here rather than in CSS because the row also needs to know whether
// there is more to show.
// Long enough for a useful parked reason, short enough that every row is the
// same height at the widths the table is used at.
const CELL_LIMIT = 160;
/**
* activityDetail returns `{ text, full, truncated }` for one event:
* `text` is the single line the cell renders, `full` the untouched payload,
* and `truncated` whether the two differ.
*/
export function activityDetail(event) {
const full = String(event?.detail || event?.message || "");
if (!full) return { text: "", full: "", truncated: false };
// The first line that says something: agent output often opens with blanks.
const firstLine = full.split("\n").map((line) => line.trim()).find(Boolean) || "";
const clipped = firstLine.length > CELL_LIMIT ? `${firstLine.slice(0, CELL_LIMIT).trimEnd()}…` : firstLine;
return { text: clipped, full, truncated: clipped !== full };
}
-423
View File
@@ -1,423 +0,0 @@
/* Dashboard-only styles. Feature folders own their CSS and import it from
their JS, so a section can be added or removed without editing _main.css. */
/* ── Stat tiles ─────────────────────────────────────────────────────────── */
.stat-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-2);
}
.stat-label {
font-size: var(--text-sm);
color: var(--fg-muted);
}
.stat-trend {
display: inline-flex;
align-items: center;
gap: 3px;
font-size: var(--text-xs);
font-weight: 500;
}
.stat-trend.up {
color: var(--ok);
}
.stat-trend.down {
color: var(--danger);
}
.stat-value {
font-size: var(--text-3xl);
font-weight: 600;
letter-spacing: -0.03em;
margin: var(--sp-2) 0 0;
}
.stat-unit {
font-size: var(--text-lg);
color: var(--fg-muted);
margin-left: var(--sp-1);
}
.stat-compare {
font-size: var(--text-xs);
color: var(--fg-subtle);
margin-top: var(--sp-1);
}
.spark {
width: 100%;
height: 34px;
margin-top: var(--sp-3);
display: block;
}
/* ── Getting started checklist ──────────────────────────────────────────── */
.setup {
margin-bottom: var(--sp-4);
}
.setup-pct {
font-size: var(--text-lg);
font-weight: 600;
color: var(--accent);
}
.setup-complete-actions {
display: flex;
align-items: center;
gap: var(--sp-2);
}
.setup-dismiss {
width: 28px;
height: 28px;
font-size: var(--text-lg);
line-height: 1;
}
.setup-done .setup-pct {
color: var(--ok);
}
.setup-bar {
height: 5px;
border-radius: var(--radius-pill);
background: var(--border);
overflow: hidden;
margin-bottom: var(--sp-4);
}
.setup-bar-fill {
height: 100%;
background: var(--accent);
border-radius: var(--radius-pill);
transition: width var(--transition);
}
.setup-list {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: var(--sp-3);
}
.setup-step {
display: flex;
gap: var(--sp-3);
align-items: flex-start;
}
.setup-check {
width: 18px;
height: 18px;
flex: none;
border-radius: 50%;
border: 1.5px solid var(--border-strong);
display: grid;
place-items: center;
font-size: var(--text-xs);
color: var(--fg-subtle);
margin-top: 1px;
}
.setup-step.done .setup-check {
background: var(--ok-soft);
border-color: transparent;
color: var(--ok);
}
.setup-step-title {
font-size: var(--text-sm);
}
.setup-step.done .setup-step-title {
color: var(--fg-muted);
text-decoration: line-through;
}
.setup-step-detail {
font-size: var(--text-xs);
color: var(--fg-subtle);
margin-top: 2px;
}
/* ── Hero: greeting and the actions that belong with it ─────────────────── */
.hero {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: var(--sp-5);
flex-wrap: wrap;
margin-bottom: var(--sp-5);
}
.hero-title {
font-size: var(--text-3xl);
font-weight: 600;
letter-spacing: -0.03em;
margin: 0;
}
.hero-sub {
color: var(--fg-muted);
font-size: var(--text-sm);
margin: var(--sp-2) 0 0;
}
.hero-actions {
display: flex;
gap: var(--sp-2);
align-items: center;
flex-wrap: wrap;
}
/* ── Top row: checklist / pulse side by side ────────────────────────────── */
.dash-top {
display: grid;
grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr);
gap: var(--sp-4);
margin-bottom: var(--sp-4);
}
/* Either column must be allowed to shrink below its content width so the
other one does not get pushed off-screen on narrow viewports. */
.dash-top > *,
.dash-split > * {
min-width: 0;
}
/* Each HEALTH card takes its own content height. Equalising them (the earlier
fix for this row) was right when both held a checklist, but once setup is
complete that card is a title and one line while Gate pulse carries a gauge
and four rows, so matching heights left a ~400px empty box taking a quarter
of the first screen. A ragged bottom edge is the lesser cost.
(archie-core-1786637500926-421-7c63bcd3) */
.dash-top {
align-items: start;
}
/* No setup panel to show: the gate pulse spans the whole row instead of
leaving an empty half. */
.dash-top-standalone {
grid-template-columns: minmax(0, 1fr);
}
@media (max-width: 1080px) {
.dash-top {
grid-template-columns: minmax(0, 1fr);
}
}
/* ── Gauge ──────────────────────────────────────────────────────────────── */
.gauge-wrap {
position: relative;
display: grid;
place-items: center;
}
.gauge {
width: 100%;
max-width: 200px;
display: block;
}
.gauge-value {
transition: stroke-dashoffset 600ms cubic-bezier(0.4, 0, 0.2, 1);
}
.gauge-center {
position: absolute;
top: 52%;
transform: translateY(-50%);
text-align: center;
}
.gauge-pct {
font-size: var(--text-2xl);
font-weight: 600;
letter-spacing: -0.03em;
}
.gauge-label {
font-size: var(--text-xs);
color: var(--fg-muted);
}
.pulse-list {
list-style: none;
margin: var(--sp-4) 0 0;
padding: 0;
display: flex;
flex-direction: column;
gap: var(--sp-2);
}
.pulse-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-3);
font-size: var(--text-sm);
padding: var(--sp-2) var(--sp-3);
border-radius: var(--radius-sm);
background: var(--bg-raised);
}
.pulse-name {
color: var(--fg-muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* ── Segmented bar ──────────────────────────────────────────────────────── */
.segbar {
display: flex;
height: 10px;
border-radius: var(--radius-pill);
overflow: hidden;
background: var(--border);
gap: 2px;
}
.segbar-part {
display: block;
height: 100%;
}
.segbar-ok { background: var(--ok); }
.segbar-warn { background: var(--warn); }
.segbar-danger { background: var(--danger); }
.segbar-info { background: var(--info); }
.segbar-idle { background: var(--idle); }
.segbar-legend {
display: flex;
gap: var(--sp-4);
margin-top: var(--sp-3);
flex-wrap: wrap;
}
.segbar-key {
display: inline-flex;
align-items: center;
gap: var(--sp-2);
font-size: var(--text-xs);
color: var(--fg-muted);
}
.segbar-dot {
width: 8px;
height: 8px;
border-radius: 50%;
}
.forecast-value {
font-size: var(--text-3xl);
font-weight: 600;
letter-spacing: -0.03em;
margin-bottom: var(--sp-1);
}
.forecast-note {
font-size: var(--text-xs);
color: var(--fg-subtle);
margin-bottom: var(--sp-4);
}
.dash-split {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1.5fr);
gap: var(--sp-4);
margin-top: var(--sp-4);
}
@media (max-width: 1080px) {
.dash-split {
grid-template-columns: minmax(0, 1fr);
}
}
.stat-card {
position: relative;
overflow: hidden;
}
/* ── Section grouping ───────────────────────────────────────────────────── */
/* Panels are grouped under a quiet section label so the dashboard reads as one
surface with regions, rather than a scatter of unrelated cards. */
.dash-section {
margin-bottom: var(--sp-5);
}
.dash-section-head {
display: flex;
align-items: baseline;
gap: var(--sp-3);
margin-bottom: var(--sp-3);
padding-left: var(--sp-1);
}
.dash-section-title {
font-size: var(--text-xs);
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--fg-subtle);
font-weight: 600;
margin: 0;
}
.dash-section-note {
font-size: var(--text-xs);
color: var(--fg-subtle);
}
.hero-actions-inner {
display: flex;
gap: var(--sp-2);
flex-wrap: wrap;
align-items: center;
}
/* An action that exists because something needs attention should look unlike
one that is always present. */
.btn-attention {
border-color: var(--warn);
color: var(--warn);
background: var(--warn-soft);
font-weight: 500;
}
.btn-attention:hover {
background: var(--warn-soft);
filter: brightness(1.1);
}
/* Live activity's detail column. activity-detail.js already cuts the payload
to one line; this stops a long unbroken token (a path, a URL, a hash) from
widening the column past the table and keeps every row the same height. */
.activity-detail {
max-width: 0;
width: 55%;
}
.activity-detail span {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
-448
View File
@@ -1,448 +0,0 @@
import { h, Fragment } from "preact";
import { useState, useEffect, useRef } from "preact/hooks";
import "./dashboard.css";
import { api, subscribeEvents } from "../base/api.jsx";
import { ago, compact } from "../base/format.jsx";
import { statusKind } from "../base/task-meta.jsx";
import { StatTile } from "../base/statTile.jsx";
import { Gauge, SegmentBar } from "../base/gauge.jsx";
import { activityDetail } from "./activity-detail.js";
import { Icon } from "../base/icons.jsx";
import { Pill } from "../base/pill.jsx";
import { dismissSetupComplete, setupPanelState } from "./setup-preference.jsx";
import { dashboardTaskTargets } from "./task-targets.jsx";
function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
function taskIDForEvent(event, taskIDsBySource) {
if (Number(event.task_id) > 0) return Number(event.task_id);
if (!event.repo || !event.issue) return 0;
return Number(taskIDsBySource.get(`${event.repo}#${event.issue}`)) || 0;
}
function greeting() {
const h = new Date().getHours();
if (h < 5) return "Still up?";
if (h < 12) return "Good morning";
if (h < 18) return "Good afternoon";
return "Good evening";
}
function trendPct(series) {
if (series.length < 4) return null;
const mid = Math.floor(series.length / 2);
const older = series.slice(0, mid).reduce((a, b) => a + b, 0);
const newer = series.slice(mid).reduce((a, b) => a + b, 0);
if (!older) return null;
return ((newer - older) / older) * 100;
}
function DashboardApp() {
const [activity, setActivity] = useState([]);
const [streamStateText, setStreamStateText] = useState("connecting");
const [streamStateKind, setStreamStateKind] = useState("idle");
const [taskIDsBySource, setTaskIDsBySource] = useState(new Map());
const [summary, setSummary] = useState(null);
const [setup, setSetup] = useState(null);
const [workflows, setWorkflows] = useState(null);
const [tasks, setTasks] = useState(null); // null means loading, [] means loaded
const [error, setError] = useState(null);
// force a re-render when setup is dismissed
const [, setSetupDismissed] = useState(false);
const load = async () => {
setError(null);
try {
const [_summary, _setup, _workflows, _tasks] = await Promise.all([
api.summary(),
api.setup().catch(() => null),
api.workflows().catch(() => null),
api.tasks().catch(() => []),
]);
const map = new Map();
for (const task of _tasks) {
if (task.owner && task.repo && task.issue_number) {
map.set(`${task.owner}/${task.repo}#${task.issue_number}`, task.id);
}
}
setTaskIDsBySource(map);
setSummary(_summary);
setSetup(_setup);
setWorkflows(_workflows);
setTasks(_tasks);
} catch (err) {
setError(String(err.message || err));
}
};
useEffect(() => {
load();
const unsubscribe = subscribeEvents(
(event) => {
setActivity((prev) => {
const next = [event, ...prev];
next.splice(50);
return next;
});
},
(state) => {
setStreamStateText(state);
setStreamStateKind(state === "live" ? "ok" : "warn");
}
);
return unsubscribe;
}, []);
const handleDismissSetup = () => {
dismissSetupComplete();
setSetupDismissed(s => !s); // force re-eval of setupState
};
const currentGreeting = setup?.operator ? `${greeting()}, ${setup.operator}` : greeting();
// ACTIONS
let actions = null;
if (error) {
actions = (
<button className="btn btn-primary" onClick={load}>
<Icon name="refresh" size={15} /> Retry
</button>
);
} else if (tasks !== null) {
const targets = dashboardTaskTargets(tasks);
const blocked = targets.attention.count;
const running = targets.running.count;
actions = (
<Fragment>
{blocked > 0 && (
<a className="btn btn-attention" href={targets.attention.href}>
<Icon name="tasks" size={15} /> {blocked} need{blocked === 1 ? "s" : ""} you
</a>
)}
{running > 0 && (
<a className="btn" href={targets.running.href}>
<Icon name="workflows" size={15} /> {running} running
</a>
)}
<a className="btn" href="#/logs">
<Icon name="logs" size={15} /> Logs
</a>
<button className="btn btn-primary" onClick={load}>
<Icon name="refresh" size={15} /> Refresh
</button>
</Fragment>
);
}
// STATS
let statsRow = null;
if (error) {
statsRow = (
<div className="card">
<Empty title="Cannot reach archied" detail={error} />
</div>
);
} else if (summary) {
const counts = summary?.statuses || {};
const done = (counts.merged || 0) + (counts.pr_open || 0);
const attention = (counts.parked || 0) + (counts.waiting_human || 0);
const total = Object.values(counts).reduce((a, b) => a + b, 0);
const tokens = summary?.tokens_by_day || [];
statsRow = (
<Fragment>
<StatTile
label="Working now"
value={counts.running || 0}
compare={`${counts.queued || 0} waiting to start`}
series={tokens.map((d) => d.tokens || 0)}
/>
<StatTile
label="Needs you"
value={attention}
compare={attention ? "Parked or awaiting a reply" : "Nothing is blocked"}
goodDirection="down"
/>
<StatTile
label="Delivered"
value={done}
compare={total ? `${Math.round((done / total) * 100)}% of all tasks` : "No tasks yet"}
/>
<StatTile
label="Tokens used"
value={compact(tokens.reduce((a, d) => a + (d.tokens || 0), 0))}
compare={`Across ${tokens.length || 0} days`}
trend={trendPct(tokens.map((d) => d.tokens || 0))}
goodDirection="down"
series={tokens.map((d) => d.tokens || 0)}
/>
</Fragment>
);
}
// SETUP
let setupSlot = null;
const state = setupPanelState(setup);
const omit = state.kind === "omit" || state.kind === "dismissed";
if (!omit) {
const remaining = state.remaining;
if (remaining.length) {
const pct = Math.round(((setup.steps.length - remaining.length) / setup.steps.length) * 100);
setupSlot = (
<div className="card setup">
<div className="card-head">
<div>
<h2 className="card-title">Finish setting up</h2>
<p className="card-sub">Archie needs these before it can work on its own.</p>
</div>
<span className="setup-pct">{pct}%</span>
</div>
<div className="setup-bar">
<div className="setup-bar-fill" style={{ width: `${pct}%` }} />
</div>
<ul className="setup-list">
{setup.steps.map((step, i) => (
<li key={i} className={`setup-step ${step.done ? "done" : ""}`}>
<span className="setup-check">{step.done ? <Icon name="check" size={12} /> : ""}</span>
<div>
<div className="setup-step-title">{step.title}</div>
{step.detail && <div className="setup-step-detail">{step.detail}</div>}
</div>
</li>
))}
</ul>
</div>
);
} else {
setupSlot = (
<div className="card setup setup-done">
<div className="card-head">
<div>
<h2 className="card-title">Setup complete</h2>
<p className="card-sub">Archie is configured and ready to work.</p>
</div>
<div className="setup-complete-actions">
<span className="setup-pct"><Icon name="check" size={16} /></span>
<button
className="icon-btn setup-dismiss"
type="button"
title="Dismiss setup complete"
aria-label="Dismiss setup complete"
onClick={handleDismissSetup}
>
×
</button>
</div>
</div>
</div>
);
}
}
// PULSE
let pulseSlot = null;
if (summary) {
const wStats = workflows?.workflows || [];
const runs = wStats.reduce((a, w) => a + (w.runs || 0), 0);
const merged = wStats.reduce((a, w) => a + (w.merged || 0) + (w.pr_open || 0), 0);
const parked = wStats.reduce((a, w) => a + (w.parked || 0), 0);
if (!runs) {
pulseSlot = (
<div className="card">
<div className="card-head"><h2 className="card-title">Gate pulse</h2></div>
<Empty title="No completed runs yet" detail="Once Archie finishes a task, its gate pass rate appears here." />
</div>
);
} else {
const pct = (merged / runs) * 100;
pulseSlot = (
<div className="card">
<div className="card-head">
<div>
<h2 className="card-title">Gate pulse</h2>
<p className="card-sub">Work that passed its quality gates</p>
</div>
</div>
<Gauge value={pct} label="pass rate" />
<ul className="pulse-list">
{wStats.slice(0, 3).map((w, i) => (
<li key={i} className="pulse-item">
<span className="pulse-name">{w.workflow || "workflow"}</span>
<Pill
text={`${w.merged || 0}/${w.runs || 0}`}
kind={(w.merged || 0) === (w.runs || 0) ? "ok" : (w.parked || 0) > 0 ? "warn" : "info"}
/>
</li>
))}
{parked > 0 && (
<li className="pulse-item">
<span className="pulse-name">Parked, awaiting you</span>
<Pill text={String(parked)} kind="warn" />
</li>
)}
</ul>
</div>
);
}
}
// FORECAST
let forecastSlot = null;
if (summary) {
const days = summary?.tokens_by_day || [];
const used = days.reduce((a, d) => a + (d.tokens || 0), 0);
if (!days.length) {
forecastSlot = (
<div className="card">
<div className="card-head"><h2 className="card-title">Token outlook</h2></div>
<Empty title="Nothing spent yet" detail="Usage appears here once Archie runs its first task." />
</div>
);
} else {
const perDay = used / days.length;
const projected = Math.round(perDay * 30);
const recent = days.slice(-7).reduce((a, d) => a + (d.tokens || 0), 0);
forecastSlot = (
<div className="card">
<div className="card-head">
<div>
<h2 className="card-title">Token outlook</h2>
<p className="card-sub">Next 30 days at the current rate</p>
</div>
</div>
<div className="forecast-value">{compact(projected)}</div>
<div className="forecast-note">Based on {compact(Math.round(perDay))} per day over {days.length} days</div>
<SegmentBar
segments={[
{ label: `Last 7 days (${compact(recent)})`, value: recent, kind: "info" },
{ label: `Earlier (${compact(used - recent)})`, value: Math.max(used - recent, 0), kind: "idle" },
]}
/>
</div>
);
}
}
return (
<Fragment>
<div className="hero">
<div>
<h1 className="hero-title">{currentGreeting}</h1>
<p className="hero-sub">
Your agent's control room — what it is working on, what needs you, and what it is spending.
</p>
</div>
<div className="hero-actions">
<div className="hero-actions-inner">{actions}</div>
</div>
</div>
<div className="dash-section">
<div className="dash-section-head">
<h2 className="dash-section-title">Health</h2>
</div>
<div className={`dash-top ${omit ? "dash-top-standalone" : ""}`}>
<div>{setupSlot}</div>
<div>{pulseSlot}</div>
</div>
</div>
<div className="dash-section">
<div className="dash-section-head">
<h2 className="dash-section-title">Throughput</h2>
<span className="dash-section-note">Across all repositories</span>
</div>
<div className="grid grid-4">{statsRow}</div>
</div>
<div className="dash-section">
<div className="dash-section-head">
<h2 className="dash-section-title">Right now</h2>
</div>
<div className="dash-split">
<div>{forecastSlot}</div>
<div className="card">
<div className="card-head">
<div>
<h2 className="card-title">Live activity</h2>
<p className="card-sub">Last 50, newest first</p>
</div>
<Pill text={streamStateText} kind={streamStateKind} />
</div>
<div className="table-scroll">
<table className="table">
<thead>
<tr>
<th>Event</th>
<th>Task</th>
<th>Detail</th>
<th>When</th>
</tr>
</thead>
<tbody>
{!activity.length ? (
<tr>
<td colSpan="4">
<Empty title="Waiting for activity" detail="Events appear here as Archie works." />
</td>
</tr>
) : (
activity.map((event, i) => {
const taskID = taskIDForEvent(event, taskIDsBySource);
const hasTask = taskID > 0;
const detail = activityDetail(event);
const openTask = () => {
if (hasTask) location.hash = `#/tasks?task=${encodeURIComponent(taskID)}`;
};
return (
<tr
key={i}
className={hasTask ? "activity-row" : ""}
role={hasTask ? "link" : undefined}
tabIndex={hasTask ? "0" : undefined}
title={hasTask ? "Open task details" : undefined}
onClick={hasTask ? openTask : undefined}
onKeyDown={hasTask ? (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
openTask();
}
} : undefined}
>
<td className="strong">
<span>{event.kind || event.type || "event"}</span>
</td>
<td className="mono">{hasTask ? `#${taskID}` : "—"}</td>
<td className="activity-detail">
<span title={detail.truncated ? detail.full : undefined}>{detail.text}</span>
</td>
<td>{ago(event.at || Date.now())}</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
</div>
</div>
</div>
</Fragment>
);
}
export function dashboardPage() {
return <DashboardApp />;
}
-21
View File
@@ -1,21 +0,0 @@
export const SETUP_DISMISSAL_KEY = "archie.setup-complete.dismissed.v1";
// setupPanelState reconciles persisted presentation state with current setup
// truth. If setup later becomes incomplete, an old dismissal is cleared so
// the operator cannot miss the new work.
export function setupPanelState(setup, storage = globalThis.localStorage) {
if (!setup?.steps?.length) return { kind: "omit", remaining: [] };
const remaining = setup.steps.filter((step) => !step.done);
if (remaining.length) {
storage?.removeItem?.(SETUP_DISMISSAL_KEY);
return { kind: "incomplete", remaining };
}
if (storage?.getItem?.(SETUP_DISMISSAL_KEY) === "1") {
return { kind: "dismissed", remaining: [] };
}
return { kind: "complete", remaining: [] };
}
export function dismissSetupComplete(storage = globalThis.localStorage) {
storage?.setItem?.(SETUP_DISMISSAL_KEY, "1");
}
-21
View File
@@ -1,21 +0,0 @@
const ATTENTION_STATUSES = new Set(["waiting_human", "parked"]);
// Dashboard task links are derived from the actual task list, not just count
// aggregates, so a single item can open directly while a group opens a useful
// filtered board.
export function dashboardTaskTargets(tasks = []) {
const attention = tasks.filter((task) => ATTENTION_STATUSES.has(task.status));
const running = tasks.filter((task) => task.status === "running");
return {
attention: {
count: attention.length,
href: attention.length === 1
? `#/tasks?task=${encodeURIComponent(attention[0].id)}`
: "#/tasks?status=needs_you",
},
running: {
count: running.length,
href: "#/tasks?status=running",
},
};
}
+7
View File
@@ -0,0 +1,7 @@
import type { ClassValue } from "clsx"
import { clsx } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
-29
View File
@@ -1,29 +0,0 @@
// What the logs list says when it has nothing to show.
//
// Three different situations produced one message, which is how the page ended
// up promising that "live daemon logs will appear here" while the stream that
// would deliver them had already given up (archie-core-c5bz).
/**
* logsEmptyTitle names the situation: a dead stream, a deployment with no
* durable history, or filters that match nothing.
*/
export function logsEmptyTitle(durableUnavailable, streamState) {
if (streamState === "unavailable") return "Log stream unavailable";
if (durableUnavailable) return "No logs yet";
return "Nothing matches";
}
/**
* logsEmptyDetail says what to expect next, and never promises live logs from
* a stream that has stopped.
*/
export function logsEmptyDetail(durableUnavailable, streamState) {
if (streamState === "unavailable") {
return "The daemon is not serving /api/logs/stream. Reload once it is reachable.";
}
if (durableUnavailable) {
return "This deployment keeps no durable history. Live daemon logs appear here while the page is open.";
}
return "Try a wider level or clear the search.";
}
-145
View File
@@ -1,145 +0,0 @@
/* Log view. Dense by design: the point is scanning many lines quickly, so the
type is smaller and the rows tighter than elsewhere in the dashboard. */
.log-filters {
display: flex;
gap: var(--sp-2);
align-items: center;
flex-wrap: wrap;
}
.log-status {
display: flex;
gap: var(--sp-3);
align-items: center;
}
.log-meta {
font-size: var(--text-xs);
color: var(--fg-subtle);
font-family: var(--font-mono);
}
.log-select,
.log-search {
background: var(--bg-raised);
border: 1px solid var(--border-strong);
color: var(--fg);
border-radius: var(--radius-sm);
padding: var(--sp-2) var(--sp-3);
font: inherit;
font-size: var(--text-sm);
}
.log-search {
min-width: 220px;
}
.log-select:focus,
.log-search:focus {
outline: 2px solid var(--accent);
outline-offset: -1px;
}
.log-list {
max-height: 62vh;
overflow-y: auto;
font-family: var(--font-mono);
font-size: var(--text-xs);
border-top: 1px solid var(--border);
}
.log-loading {
padding: var(--sp-5);
color: var(--fg-muted);
text-align: center;
}
.log-row {
display: grid;
grid-template-columns: 62px 52px 1fr;
gap: var(--sp-3);
padding: var(--sp-2) var(--sp-1);
border-bottom: 1px solid var(--border);
align-items: baseline;
}
.log-row:hover {
background: var(--surface-hover);
}
.log-time {
color: var(--fg-subtle);
}
.log-level {
font-size: 10px;
font-weight: 600;
letter-spacing: 0.04em;
}
/* Level colour lives on the row so the message inherits emphasis without a
second rule per level. */
.log-danger .log-level {
color: var(--danger);
}
.log-warn .log-level {
color: var(--warn);
}
.log-info .log-level {
color: var(--info);
}
.log-idle .log-level {
color: var(--idle);
}
.log-danger .log-msg {
color: var(--fg);
}
.log-body {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2);
align-items: baseline;
min-width: 0;
}
.log-msg {
color: var(--fg);
word-break: break-word;
}
/* Structured fields read as attached detail, not part of the sentence. */
.log-field {
color: var(--fg-muted);
background: var(--bg-raised);
border-radius: var(--radius-sm);
padding: 0 var(--sp-2);
white-space: nowrap;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
}
.log-field-key {
color: var(--fg-subtle);
}
.log-field-key::after {
content: "=";
opacity: 0.6;
}
@media (max-width: 860px) {
.log-row {
grid-template-columns: 56px 1fr;
}
.log-level {
display: none;
}
.log-search {
min-width: 0;
flex: 1;
}
}
-200
View File
@@ -1,200 +0,0 @@
import { h } from "preact";
import { useState, useEffect, useRef, useMemo } from "preact/hooks";
import "./logs.css";
import { api, subscribeLogs } from "../base/api.jsx";
import { LOG_LEVELS, LogRow } from "../base/log-row.jsx";
import { Pill } from "../base/pill.jsx";
import { logsEmptyTitle, logsEmptyDetail } from "./logs-empty.js";
function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
function entryKey(entry) {
return `${entry.time || ""}|${entry.level || ""}|${entry.message || entry.msg || ""}|${JSON.stringify(entry.fields || {})}`;
}
function LogsApp() {
const [filters, setFilters] = useState({ level: "", component: "", q: "" });
const [paused, setPaused] = useState(false);
const [componentOptions, setComponentOptions] = useState([]);
const [historyEntries, setHistoryEntries] = useState([]);
const liveEntriesRef = useRef(new Map());
const [liveEntriesCounter, setLiveEntriesCounter] = useState(0);
const [durableUnavailable, setDurableUnavailable] = useState(false);
const [streamState, setStreamState] = useState("connecting");
const [meta, setMeta] = useState("Refreshing…");
const listRef = useRef(null);
const searchTimeout = useRef(null);
const load = async () => {
setMeta("Refreshing…");
try {
const res = await api.logs({
level: filters.level,
component: filters.component,
q: filters.q,
limit: 500,
});
setComponentOptions(prev => {
const newComps = res.components || [];
if (prev.length === newComps.length && prev.every((v, i) => v === newComps[i])) return prev;
return newComps;
});
setDurableUnavailable(!!res.disabled);
const newMeta = res.disabled ? "Live only" : res.truncated
? `showing the most recent matches from ${res.file}`
: res.file || "";
setMeta(newMeta);
setHistoryEntries(res.entries || []);
} catch (err) {
setMeta("Cannot read logs");
}
};
useEffect(() => {
load();
}, [filters]);
useEffect(() => {
const handleEvent = (event) => {
if (pausedRef.current) return;
const entry = event;
if (!matchesLocallyRef.current(entry)) return;
liveEntriesRef.current.set(entryKey(entry), entry);
if (entry.fields?.component) {
setComponentOptions(prev => {
if (!prev.includes(entry.fields.component)) return [...prev, entry.fields.component];
return prev;
});
}
setLiveEntriesCounter(c => c + 1);
};
const unsubscribe = subscribeLogs(
handleEvent,
(state) => {
setStreamState(state);
}
);
return () => unsubscribe();
}, []); // Only run once
const pausedRef = useRef(paused);
pausedRef.current = paused;
const matchesLocally = (entry) => {
if (filters.level && !filters.level.split(",").includes((entry.level || "").toUpperCase())) {
return false;
}
if (filters.component && entry.fields?.component !== filters.component) return false;
if (filters.q) {
const needle = filters.q.toLowerCase();
const hay = `${entry.message || entry.msg || ""} ${JSON.stringify(entry.fields || {})}`.toLowerCase();
if (!hay.includes(needle)) return false;
}
return true;
};
const matchesLocallyRef = useRef(matchesLocally);
matchesLocallyRef.current = matchesLocally;
const entriesToRender = useMemo(() => {
const byID = new Map();
for (const entry of historyEntries) byID.set(entryKey(entry), entry);
for (const [id, entry] of liveEntriesRef.current) byID.set(id, entry);
return [...byID.values()].filter(matchesLocally).slice(-1000);
}, [historyEntries, liveEntriesCounter, filters]);
useEffect(() => {
if (listRef.current) {
listRef.current.scrollTop = listRef.current.scrollHeight;
}
}, [entriesToRender]);
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Logs</h1>
<p className="page-sub">What Archie has been doing, newest last.</p>
</div>
<div className="page-actions">
<button
className={`btn ${paused ? "btn-primary" : ""}`}
onClick={() => setPaused(!paused)}
>
{paused ? "Resume" : "Pause"}
</button>
<button className="btn" onClick={load}>Refresh</button>
</div>
</div>
<div className="card">
<div className="card-head">
<div className="log-filters">
<select
className="log-select"
value={filters.level}
onChange={(e) => setFilters(f => ({ ...f, level: e.target.value }))}
>
{LOG_LEVELS.map(l => <option key={l.value} value={l.value}>{l.label}</option>)}
</select>
<select
className="log-select"
value={filters.component}
onChange={(e) => setFilters(f => ({ ...f, component: e.target.value }))}
>
<option value="">All components</option>
{componentOptions.map(c => <option key={c} value={c}>{c}</option>)}
</select>
<input
className="log-search"
type="search"
placeholder="Search messages and fields…"
onInput={(e) => {
const v = e.target.value;
if (searchTimeout.current) clearTimeout(searchTimeout.current);
searchTimeout.current = setTimeout(() => {
setFilters(f => ({ ...f, q: v }));
}, 250);
}}
/>
</div>
<div className="log-status">
<span className="log-meta">{meta}</span>
<Pill
text={streamState}
kind={streamState === "live" ? "ok" : streamState === "unavailable" ? "danger" : "warn"}
/>
</div>
</div>
<div className="log-list" ref={listRef}>
{meta === "Cannot read logs" ? (
<Empty title="Cannot read logs" />
) : !entriesToRender.length ? (
<Empty
title={logsEmptyTitle(durableUnavailable, streamState)}
detail={logsEmptyDetail(durableUnavailable, streamState)}
/>
) : (
entriesToRender.map(entry => <LogRow key={entryKey(entry)} entry={entry} />)
)}
</div>
</div>
</div>
);
}
export function logsPage(query) {
return <LogsApp query={query} />;
}
-410
View File
@@ -1,410 +0,0 @@
import "./css/_main.css";
import { Fragment, h, render } from "preact";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { api } from "./base/api.jsx";
import { hiddenRoutes } from "./capabilities.jsx";
import { loadTaskMeta } from "./base/task-meta.jsx";
import { Icon } from "./base/icons.jsx";
import { dashboardPage } from "./dashboard/dashboard.jsx";
import { tasksPage } from "./tasks/tasks.jsx";
import { taskDetailPage } from "./tasks/task-detail.jsx";
import { skillsPage } from "./skills/skills.jsx";
import { workflowsPage } from "./workflows/workflows.jsx";
import { channelsPage } from "./channels/channels.jsx";
import { curatorsPage } from "./curators/curators.jsx";
import { settingsPage } from "./settings/settings.jsx";
import { logsPage } from "./logs/logs.jsx";
import { capturesPage } from "./captures/captures.jsx";
import { mappingsPage } from "./mappings/mappings.jsx";
import { bindingsPage } from "./bindings/bindings.jsx";
import { ChatApp } from "./chat/chat.jsx";
import { matchRoute, navPath } from "./routing.jsx";
/**
* Routes are declared once here. Adding a section means adding a feature
* folder and one entry -- there is no switch statement to hunt for.
*
* `soon: true` sections are deliberately visible before they are built: a
* greyed, labelled entry tells you the capability exists and is coming, which
* is more honest than hiding it and more useful than a 404.
*/
// section names the capability a route needs, as reported by
// GET /api/capabilities. A route with no section is served in every
// composition. The dashboard is rendered by two different processes -- the
// daemon and the extracted UI service -- and a section the serving process
// cannot back would otherwise render as permanently empty rather than as
// absent (archie-core-8cda.5.4).
//
// A route may also carry:
// nav:false -- addressed by URL but not a navigation entry (a detail page
// reached from its section)
// navPath -- the navigation entry this route keeps current; a parameterised
// route is not itself in the nav, so without this the section it
// belongs to would lose its aria-current highlight
// :name -- one captured path segment, e.g. /tasks/:id
const routes = [
{ path: "/", label: "Dashboard", icon: "dashboard", view: dashboardPage },
{ path: "/tasks", label: "Tasks", icon: "tasks", view: tasksPage },
{ path: "/tasks/:id", label: "Task run", view: taskDetailPage, nav: false, navPath: "/tasks" },
{ path: "/logs", label: "Logs", icon: "logs", view: logsPage, section: "logs" },
{ path: "/captures", label: "Event inspector", icon: "captures", view: capturesPage, section: "captures" },
{ path: "/mappings", label: "Field mappings", icon: "mappings", view: mappingsPage, section: "mappings" },
{ path: "/bindings", label: "Playbook bindings", icon: "bindings", view: bindingsPage, section: "bindings" },
{ path: "/skills", label: "Skills", icon: "skills", view: skillsPage, section: "skills" },
{ path: "/workflows", label: "Workflows", icon: "workflows", view: workflowsPage, section: "workflows" },
{ path: "/curators", label: "Curators", icon: "curators", view: curatorsPage, section: "curators" },
{ path: "/channels", label: "Channels", icon: "channels", view: channelsPage, section: "channels" },
{ path: "/settings", label: "Configuration", icon: "settings", view: settingsPage, section: "settings" },
];
const THEME_KEY = "archie.theme";
function currentTheme() {
return localStorage.getItem(THEME_KEY) || "dark";
}
function applyTheme(theme) {
document.documentElement.dataset.theme = theme;
localStorage.setItem(THEME_KEY, theme);
}
// navEntries lists what gets a navigation item: a detail route (nav:false) is
// addressed by URL but reached from its section, so it is not an entry.
function navEntries(hidden) {
return routes.filter((route) => route.nav !== false && !hidden.includes(route.path));
}
function Topbar({ activePath, hidden, onNavigate, theme, onToggleTheme }) {
const [searchOpen, setSearchOpen] = useState(false);
const searchRef = useRef(null);
const closeSearch = () => setSearchOpen(false);
const onSearchKeyDown = (event) => {
if (event.key === "Escape") {
// preventDefault so the window-level handler (chat drawer close) does not
// also fire: dismissing the search should not dismiss the drawer.
event.preventDefault();
closeSearch();
event.target.blur();
return;
}
if (event.key !== "Enter") return;
// Search jumps between sections. It is deliberately not a data search: the
// sections own their own filtering, and a second search that means
// something different in each place is worse than none.
const query = event.target.value.trim().toLowerCase();
const hit = routes.find(
(route) => route.nav !== false && !route.soon && route.label.toLowerCase().startsWith(query),
);
if (hit) {
onNavigate(hit.path);
event.target.value = "";
event.target.blur();
closeSearch();
}
};
return (
<header className="topbar">
<div className="brand">
<span className="brand-mark">A</span>
Archie
</div>
<nav className="nav">
{navEntries(hidden).map((route) => (
<a
className="nav-item"
key={route.path}
href={`#${route.path}`}
aria-current={route.path === activePath ? "page" : undefined}
aria-disabled={route.soon || undefined}
title={route.soon ? "Coming soon" : undefined}
onClick={(event) => {
if (route.soon) event.preventDefault();
else onNavigate(route.path);
}}
>
<Icon name={route.icon} />
<span className="nav-label">{route.label}</span>
{route.soon ? <span className="nav-soon">soon</span> : null}
</a>
))}
</nav>
<div className="topbar-end">
<div className={`topbar-search${searchOpen ? " is-open" : ""}`}>
<span className="topbar-search-icon" aria-hidden="true">
<Icon name="search" size={15} />
</span>
<button
className="icon-btn mobile-search-toggle"
type="button"
aria-label="Open Jump to navigation"
aria-expanded={searchOpen ? "true" : "false"}
onClick={() => {
setSearchOpen(true);
// The field is always mounted -- the narrow layout only hides it --
// so focus can land in it straight away instead of on the toggle.
searchRef.current?.focus();
}}
>
<Icon name="search" size={15} />
</button>
<input
ref={searchRef}
type="search"
placeholder="Jump to…"
aria-label="Jump to a section"
onKeyDown={onSearchKeyDown}
/>
</div>
<button className="icon-btn" title="Documentation" aria-label="Documentation">
<Icon name="help" />
</button>
<button
className="icon-btn"
title="Toggle light and dark"
aria-label="Toggle light and dark"
onClick={onToggleTheme}
>
<Icon name={theme === "dark" ? "moon" : "sun"} />
</button>
<div className="avatar" title="Signed in locally">
A
</div>
</div>
</header>
);
}
// Chat is a floating launcher and the panel it opens, mounted once beside the
// outlet. It is not a route: the operator asks Archie about the page they are
// already on, so navigating must not close it and opening must not replace the
// work that prompted the question.
//
// The panel anchors to the launcher and opens leftward from it, sharing its
// bottom edge, so the button stays put and reads as the thing the panel came
// out of. Nothing is dimmed and the page keeps scrolling: this is a companion
// to the work, not a modal over it.
//
// It hosts a single ChatApp instance, so session state and the stream survive
// navigation rather than being rebuilt per page.
const CHAT_PANEL_ID = "chat-panel";
function ChatLauncher() {
const [open, setOpen] = useState(false);
const fabRef = useRef(null);
const close = useCallback(() => {
setOpen(false);
// Focus goes back to the control that opened the panel; otherwise a
// keyboard user who dismisses it lands at the top of the document.
fabRef.current?.focus();
}, []);
useEffect(() => {
if (!open) return undefined;
const onKeyDown = (event) => {
// A focused control (the composer dismissing its command menu, or the
// topbar search) already handled Escape via preventDefault; closing the
// panel too would make that menu impossible to dismiss on its own.
if (event.defaultPrevented || event.key !== "Escape") return;
close();
};
document.addEventListener("keydown", onKeyDown);
return () => document.removeEventListener("keydown", onKeyDown);
}, [open, close]);
return (
<div className={`chat-dock${open ? " is-open" : ""}`}>
<aside
className={`chat-drawer${open ? " is-open" : ""}`}
id={CHAT_PANEL_ID}
aria-label="Chat with Archie"
aria-hidden={open ? undefined : "true"}
>
<div className="chat-drawer-panel">
{/* ChatApp owns the header: the title is the open conversation. It
carries no close button -- the launcher stays visible and is the
one control that opens and closes the panel. */}
<ChatApp open={open} />
</div>
</aside>
<button
ref={fabRef}
type="button"
className="chat-fab"
aria-label={open ? "Close chat" : "Chat with Archie"}
title={open ? "Close chat" : "Chat with Archie"}
aria-expanded={open ? "true" : "false"}
aria-controls={CHAT_PANEL_ID}
onClick={() => (open ? close() : setOpen(true))}
>
<span className="chat-fab-icon chat-fab-icon-open" aria-hidden="true">
<Icon name="chat" size={22} />
</span>
<span className="chat-fab-icon chat-fab-icon-close" aria-hidden="true">
<Icon name="close" size={22} />
</span>
</button>
</div>
);
}
function ComingSoon({ label }) {
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">{label}</h1>
</div>
</div>
<div className="card">
<div className="empty">
<div className="empty-title">{`${label} is not built yet`}</div>
<div>This section is next up. Nothing is broken.</div>
</div>
</div>
</div>
);
}
// RouteView gives the router a keyed boundary. A page is a function of its
// query and its path parameters, and two ids on the same parameterised route
// must be two instances: without the key the second id diffs the first one in
// place and the operator's open tab from the previous task stays open on the
// next (W11).
function RouteView({ view, search, params }) {
return view(search, params);
}
// Routing is wired once, at import, and pages render into one long-lived outlet
// rather than as children of App.
//
// The listeners cannot live in an effect: a page installs its own
// hash-sensitive state as it mounts, and the outgoing page has to be gone in
// the same tick the hash changes. Task detail writes the tab selection back
// with replaceState as it settles; if it is still mounted when the hashchange
// lands, it canonicalises the URL back to its own route and the navigation is
// silently lost. App publishes its outlet and its two navigation-owned pieces
// of chrome through a callback ref, which runs at commit time -- before any
// page effect can run.
let outlet = null;
let chrome = null;
// renderRoute mounts the route's page into the outlet. It is separate from
// show() because the lifecycle catalog arrives after the first paint and the
// route tree renders into its own root: App re-rendering cannot reach into the
// outlet, so a late catalog has to re-render the page explicitly or it keeps
// the freeze-dried labels it read on the way up. The key is unchanged, so Preact
// re-renders the mounted page in place and keeps its state.
function renderRoute(rawPath) {
if (!outlet) return;
const [path, query = ""] = String(rawPath).split("?", 2);
const match = matchRoute(routes, path);
const route = match?.route || routes[0];
const params = match?.params || {};
// The key covers the path and its parameters, but NOT the query: the query
// string is an entry state, so a navigation that only changes the query of
// the page already mounted keeps the operator's own filter selection.
render(
route.view ? (
<RouteView
key={`${route.path}|${Object.values(params).join("/")}`}
view={route.view}
search={new URLSearchParams(query)}
params={params}
/>
) : (
<ComingSoon label={route.label} />
),
outlet,
);
}
function show(rawPath) {
const [path] = String(rawPath).split("?", 2);
const match = matchRoute(routes, path);
const route = match?.route || routes[0];
// Let a page release its subscriptions before it is replaced, so the SSE
// stream does not leak a connection per navigation. The event goes to the
// outgoing page's root, before the swap.
outlet?.firstElementChild?.dispatchEvent(new CustomEvent("archie:teardown"));
// A detail route highlights the section it belongs to, so the nav item for
// Tasks stays current on #/tasks/42 instead of every item losing it.
chrome?.setActive(navPath(route));
renderRoute(rawPath);
}
function navigate(next) {
if (location.hash !== `#${next}`) location.hash = next;
else show(next);
}
window.addEventListener("hashchange", () => show(location.hash.slice(1) || "/"));
function App() {
const [active, setActive] = useState("/");
const [theme, setTheme] = useState(currentTheme);
const [hidden, setHidden] = useState([]);
// Publishes the router's handles. A callback ref runs at commit time, so a
// hashchange that lands right after the first paint already finds them.
const publish = useCallback((element) => {
outlet = element;
chrome = { setActive };
}, []);
useEffect(() => {
applyTheme(theme);
}, [theme]);
// Asked for once, after the shell is up: the nav renders immediately and
// loses the entries this process cannot back a moment later, rather than
// holding the whole page behind one request.
useEffect(() => {
api
.capabilities()
.then((caps) => setHidden(hiddenRoutes(caps?.sections, routes)))
.catch(() => {});
}, []);
// The lifecycle vocabulary -- status labels, pill severity, "needs you"
// grouping, and the operator actions -- is served by /api/task-meta. Ask for
// it once, after the shell is up: the freeze-dried defaults paint
// immediately and this replaces them, so a catalogue change on the server
// reaches the browser without a UI release. loadTaskMeta never throws (a
// failed fetch keeps the defaults), so it needs no catch here.
useEffect(() => {
// The catalog lands after the first paint, and the route tree renders into
// its own root: without re-rendering it, an already-painted page keeps the
// freeze-dried labels it read on the way up until something else happens to
// re-render it.
loadTaskMeta().then(() => renderRoute(location.hash.slice(1) || "/"));
}, []);
return (
<Fragment>
<div className="shell">
<Topbar
activePath={active}
hidden={hidden}
onNavigate={navigate}
theme={theme}
onToggleTheme={() => setTheme((current) => (current === "dark" ? "light" : "dark"))}
/>
<main className="main" ref={publish} />
</div>
{/* Outside .shell on purpose: its backdrop-filter is a containing block
for fixed positioning, so a launcher nested inside would anchor to the
scrolling shell and ride off the bottom of a long page. */}
<ChatLauncher />
</Fragment>
);
}
applyTheme(currentTheme());
render(<App />, document.getElementById("app"));
show(location.hash.slice(1) || "/");
+7
View File
@@ -0,0 +1,7 @@
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import "./style.css";
createApp(App).use(router).mount("#app");
-166
View File
@@ -1,166 +0,0 @@
import { h, Fragment } from "preact";
import { Pill } from "../base/pill.jsx";
/**
* Pure rendering + path/type logic for the mapping editor, split out from
* mappings.js so it is unit-testable without the page's fetch wiring,
* mirroring captures/capture-row.js.
*/
const FIELD_TYPES = ["string", "number", "bool", "object", "array", "any"];
/** Infers the FieldType a freshly-clicked example value suggests. */
export function fieldTypeFromValue(value) {
if (value === null || value === undefined) return "any";
if (Array.isArray(value)) return "array";
switch (typeof value) {
case "string":
return "string";
case "number":
return "number";
case "boolean":
return "bool";
case "object":
return "object";
default:
return "any";
}
}
export function pathAppendKey(path, key) {
return path ? `${path}.${key}` : key;
}
export function pathAppendIndex(path, index) {
return `${path}[${index}]`;
}
/**
* Renders payload as a clickable tree: every key/index and every leaf calls
* onPick({ path, type, name }) when clicked, so the editor can bind a field
* without the operator ever typing a JSON path by hand -- "click through
* its payload, bind JSON paths" per docs/prds/payload-field-mapping.md.
*/
export function PayloadTree({ value, path = "", name = "", onPick }) {
if (value !== null && typeof value === "object") {
const entries = Array.isArray(value)
? value.map((v, i) => [String(i), v, pathAppendIndex(path, i)])
: Object.entries(value).map(([k, v]) => [k, v, pathAppendKey(path, k)]);
return (
<ul className="mapping-tree-list">
{entries.map(([key, child, childPath]) => (
<li className="mapping-tree-item" key={childPath}>
<span
className="mapping-tree-key"
onClick={(e) => {
e.stopPropagation();
if (onPick) onPick({ path: childPath, type: fieldTypeFromValue(child), name: key });
}}
>
{key}
</span>
<PayloadTree value={child} path={childPath} name={key} onPick={onPick} />
</li>
))}
</ul>
);
}
return (
<span
className="mapping-tree-value"
onClick={(e) => {
e.stopPropagation();
if (onPick) onPick({ path, type: fieldTypeFromValue(value), name });
}}
>
{JSON.stringify(value)}
</span>
);
}
/**
* Renders the bound-fields table. preview is { values, failures } | null --
* null means "not previewed yet" and every row shows a neutral status
* rather than a false pass, since an unresolved field is not the same
* claim as a resolved one.
*/
export function FieldsTable({ fields, preview, onRemove, onNameChange, onTypeChange, onRequiredChange }) {
if (!fields.length) {
return <div className="mapping-empty-fields">Click a value in the payload to bind a field.</div>;
}
const failureByField = new Map((preview?.failures || []).map((f) => [f.field_name, f]));
return (
<table className="table mapping-fields-table">
<thead>
<tr>
{["Field name", "Path", "Type", "Required", "Preview", ""].map((h, i) => (
<th key={i}>{h}</th>
))}
</tr>
</thead>
<tbody>
{fields.map((f, i) => (
<tr key={i}>
<td>
<input
className="mapping-input"
value={f.name}
onInput={(e) => onNameChange?.(i, e.target.value)}
/>
</td>
<td className="mono">{f.path}</td>
<td>
<select
className="mapping-select"
value={f.type}
onChange={(e) => onTypeChange?.(i, e.target.value)}
>
{FIELD_TYPES.map((t) => (
<option key={t} value={t}>{t}</option>
))}
</select>
</td>
<td>
<input
type="checkbox"
checked={f.required}
onChange={(e) => onRequiredChange?.(i, e.target.checked)}
/>
</td>
<td>
<PreviewStatus field={f} preview={preview} failureByField={failureByField} />
</td>
<td>
<button className="btn btn-small" type="button" onClick={() => onRemove?.(i)}>Remove</button>
</td>
</tr>
))}
</tbody>
</table>
);
}
function PreviewStatus({ field, preview, failureByField }) {
if (!preview) return <Pill text="not previewed" kind="idle" />;
const failure = failureByField.get(field.name);
if (failure) return <Pill text={failure.reason} kind="danger" />;
if (Object.prototype.hasOwnProperty.call(preview.values || {}, field.name)) {
return <Pill text={JSON.stringify(preview.values[field.name])} kind="ok" />;
}
return <Pill text="skipped (optional)" kind="idle" />;
}
/** One saved mapping's summary row for the mapping list. */
export function MappingRow({ mapping: m, onEdit, onDelete }) {
return (
<tr>
<td>{m.name}</td>
<td className="mono">{m.source_hint || "—"}</td>
<td>{String(m.fields?.length ?? 0)}</td>
<td>
<button className="btn btn-small" type="button" onClick={() => onEdit?.(m)}>Edit</button>
<button className="btn btn-small" type="button" onClick={() => onDelete?.(m)}>Delete</button>
</td>
</tr>
);
}
-82
View File
@@ -1,82 +0,0 @@
/* Field mapping editor: bind named fields to JSON paths by clicking a
captured event's payload, then preview the resolution before saving. */
.mapping-form,
.mapping-fields,
.mapping-payload {
margin-bottom: var(--sp-4);
padding: var(--sp-4);
}
.mapping-form-row {
display: flex;
flex-direction: column;
gap: var(--sp-1);
margin-bottom: var(--sp-3);
font-size: var(--text-sm);
color: var(--fg-subtle);
}
.mapping-input,
.mapping-select {
padding: var(--sp-2);
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
background: var(--bg-raised);
color: var(--fg);
font: inherit;
}
.mapping-section-title {
font-size: var(--text-xs);
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--fg-subtle);
margin-bottom: var(--sp-2);
}
.mapping-fields-table .mapping-input {
width: 100%;
}
.mapping-empty-fields {
color: var(--fg-muted);
font-size: var(--text-sm);
padding: var(--sp-3) 0;
}
.mapping-error {
color: var(--danger, #e5484d);
font-size: var(--text-sm);
margin-bottom: var(--sp-3);
}
.mapping-tree-list {
list-style: none;
margin: 0;
padding-left: var(--sp-4);
font-family: var(--font-mono);
font-size: var(--text-xs);
}
.mapping-tree-item {
padding: 2px 0;
}
.mapping-tree-key,
.mapping-tree-value {
cursor: pointer;
border-radius: var(--radius-sm);
padding: 0 4px;
}
.mapping-tree-key:hover,
.mapping-tree-value:hover {
background: var(--bg-raised);
outline: 1px solid var(--accent);
}
.mapping-tree-value {
color: var(--fg-subtle);
margin-left: var(--sp-1);
}
-272
View File
@@ -1,272 +0,0 @@
import { h, Fragment } from "preact";
import { useState, useEffect } from "preact/hooks";
import "./mappings.css";
import { api } from "../base/api.jsx";
import { FieldsTable, MappingRow, PayloadTree } from "./mapping-editor.jsx";
export function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
/**
* Payload field mapping (t2db.3): bind named fields to JSON paths inside a
* real captured event, preview the resolution before saving, and manage
* saved mappings. See docs/prds/payload-field-mapping.md. t2db.4 (binding
* a mapping + matcher to a workflow) is a separate, not-yet-built page --
* this one only produces the mapping entity and its preview.
*/
export function mappingsPage(query) {
return <MappingsApp query={query} />;
}
function MappingsApp({ query }) {
const [mappings, setMappings] = useState([]);
const [captures, setCaptures] = useState([]);
const [loadError, setLoadError] = useState(null);
const [editor, setEditor] = useState(null);
const load = async () => {
try {
const [mRes, cRes] = await Promise.all([api.mappings(), api.captures(100)]);
setMappings(mRes.mappings || []);
setCaptures(cRes.captures || []);
setLoadError(null);
} catch (err) {
setLoadError(String(err.message || err));
}
};
useEffect(() => {
load();
}, []);
const startCreate = () => {
setEditor({ id: null, name: "", sourceHint: "", fields: [], captureId: null, payload: null, payloadError: null, preview: null, actionError: null });
};
const startEdit = (m) => {
setEditor({
id: m.id,
name: m.name,
sourceHint: m.source_hint || "",
fields: (m.fields || []).map((f) => ({ ...f })),
captureId: null,
payload: null,
payloadError: null,
preview: null,
actionError: null,
});
};
const remove = async (m) => {
if (!window.confirm(`Delete mapping "${m.name}"?`)) return;
try {
await api.mappingDelete(m.id);
await load();
} catch (err) {
setLoadError(String(err.message || err));
}
};
const selectCapture = (captureId) => {
const c = captures.find((c) => String(c.id) === String(captureId));
setEditor(prev => {
const next = { ...prev, captureId: c ? c.id : null, preview: null };
if (!c) {
next.payload = null;
next.payloadError = null;
} else {
try {
next.payload = JSON.parse(c.body);
next.payloadError = null;
} catch {
next.payload = null;
next.payloadError = "This capture's body is not valid JSON, so its fields cannot be mapped by path.";
}
}
return next;
});
};
const addField = ({ path, type, name }) => {
setEditor(prev => {
const existing = new Set(prev.fields.map((f) => f.name));
let candidate = name || "field";
let n = 1;
while (existing.has(candidate)) candidate = `${name || "field"}_${++n}`;
const newFields = [...prev.fields, { name: candidate, path, type, required: true }];
return { ...prev, fields: newFields, preview: null };
});
};
const removeField = (i) => {
setEditor(prev => {
const newFields = prev.fields.slice();
newFields.splice(i, 1);
return { ...prev, fields: newFields, preview: null };
});
};
const mutateField = (i, patch) => {
setEditor(prev => {
const newFields = prev.fields.slice();
newFields[i] = { ...newFields[i], ...patch };
return { ...prev, fields: newFields, preview: null };
});
};
const renameField = (i, name) => mutateField(i, { name });
const retypeField = (i, type) => mutateField(i, { type });
const requireField = (i, required) => mutateField(i, { required });
const preview = async () => {
if (!editor.captureId) {
setEditor(prev => ({ ...prev, actionError: "Pick a captured event to preview against." }));
return;
}
try {
const previewRes = await api.mappingPreview(editor.captureId, editor.fields);
setEditor(prev => ({ ...prev, preview: previewRes, actionError: null }));
} catch (err) {
setEditor(prev => ({ ...prev, actionError: String(err.message || err) }));
}
};
const save = async () => {
const body = { name: editor.name, source_hint: editor.sourceHint, fields: editor.fields };
try {
if (editor.id) {
await api.mappingUpdate(editor.id, body);
} else {
await api.mappingCreate(body);
}
setEditor(null);
await load();
} catch (err) {
setEditor(prev => ({ ...prev, actionError: String(err.message || err) }));
}
};
const cancel = () => {
setEditor(null);
};
const renderList = () => {
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Field mappings</h1>
<p className="page-sub">Bind named fields to JSON paths from a real captured event, ready for a playbook binding.</p>
</div>
<div className="page-actions">
<button className="btn btn-primary" type="button" onClick={startCreate}>New mapping</button>
</div>
</div>
{loadError ? (
<Empty title="Cannot reach archied" detail={loadError} />
) : mappings.length ? (
<div className="card">
<div className="table-scroll">
<table className="table">
<thead>
<tr>
{["Name", "Source hint", "Fields", ""].map((h, i) => (
<th key={i}>{h}</th>
))}
</tr>
</thead>
<tbody>
{mappings.map((m) => (
<MappingRow key={m.id} mapping={m} onEdit={() => startEdit(m)} onDelete={() => remove(m)} />
))}
</tbody>
</table>
</div>
</div>
) : (
<Empty title="No mappings yet" detail="Create one from a captured event to reuse fields in a future playbook binding." />
)}
</div>
);
};
const renderEditor = () => {
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">{editor.id ? "Edit mapping" : "New mapping"}</h1>
</div>
<div className="page-actions">
<button className="btn" type="button" onClick={cancel}>Cancel</button>
<button className="btn btn-primary" type="button" onClick={save}>Save</button>
</div>
</div>
{editor.actionError && <div className="mapping-error">{editor.actionError}</div>}
<div className="card mapping-form">
<label className="mapping-form-row">
Name
<input
className="mapping-input"
value={editor.name}
onInput={(e) => setEditor(prev => ({ ...prev, name: e.target.value }))}
/>
</label>
<label className="mapping-form-row">
Source hint (organisational only)
<input
className="mapping-input"
value={editor.sourceHint}
onInput={(e) => setEditor(prev => ({ ...prev, sourceHint: e.target.value }))}
/>
</label>
<label className="mapping-form-row">
Preview against captured event
<select
className="mapping-select"
value={editor.captureId || ""}
onChange={(e) => selectCapture(e.target.value)}
>
<option value="">— pick a captured event —</option>
{captures.map((c) => (
<option key={c.id} value={c.id}>
{c.source || "(unknown)"} — {c.received_at || ""}
</option>
))}
</select>
</label>
</div>
<div className="card mapping-fields">
<div className="mapping-section-title">Bound fields</div>
<FieldsTable
fields={editor.fields}
preview={editor.preview}
onRemove={removeField}
onNameChange={renameField}
onTypeChange={retypeField}
onRequiredChange={requireField}
/>
<button className="btn" type="button" onClick={preview}>Preview</button>
</div>
<div className="card mapping-payload">
<div className="mapping-section-title">Payload — click a value to bind it</div>
{editor.payloadError ? (
<div className="mapping-error">{editor.payloadError}</div>
) : editor.payload !== null ? (
<PayloadTree value={editor.payload} onPick={addField} />
) : (
<div className="mapping-empty-fields">Pick a captured event above to see its payload.</div>
)}
</div>
</div>
);
};
return editor ? renderEditor() : renderList();
}
+39
View File
@@ -0,0 +1,39 @@
import { createRouter, createWebHashHistory } from "vue-router";
import Placeholder from "@/views/Placeholder.vue";
// The dashboard's route table, and the single source of truth for what the
// dashboard exposes.
//
// internal/gateway/dashboard_tools.go hand-copies this list so the chat agent
// can navigate the operator, and TestDashboardPagesRegistryCoversEveryRoute
// parses this file to hold the two in step. That test reads `const routes = [`
// through to `];`, one route per line, skipping `nav: false` entries -- keep
// the shape below literal enough for it to parse.
//
// Hash history, not web history: the dashboard is served from a path the build
// does not know (ui/embed.go embeds a relative-base bundle), and every existing
// link, bookmark and agent-issued navigation is of the form #/tasks.
const routes = [
{ path: "/", name: "dashboard", label: "Dashboard", component: Placeholder },
{ path: "/tasks", name: "tasks", label: "Tasks", component: Placeholder },
{ path: "/tasks/:id", name: "task-detail", label: "Task run", component: Placeholder, nav: false },
{ path: "/logs", name: "logs", label: "Logs", component: Placeholder, section: "logs" },
{ path: "/captures", name: "captures", label: "Event inspector", component: Placeholder, section: "captures" },
{ path: "/mappings", name: "mappings", label: "Field mappings", component: Placeholder, section: "mappings" },
{ path: "/bindings", name: "bindings", label: "Playbook bindings", component: Placeholder, section: "bindings" },
{ path: "/skills", name: "skills", label: "Skills", component: Placeholder, section: "skills" },
{ path: "/workflows", name: "workflows", label: "Workflows", component: Placeholder, section: "workflows" },
{ path: "/curators", name: "curators", label: "Curators", component: Placeholder, section: "curators" },
{ path: "/channels", name: "channels", label: "Channels", component: Placeholder, section: "channels" },
{ path: "/settings", name: "settings", label: "Configuration", component: Placeholder, section: "settings" },
];
export const dashboardRoutes = routes;
export const router = createRouter({
history: createWebHashHistory(),
routes,
});
export default router;
-59
View File
@@ -1,59 +0,0 @@
// Hash-route matching.
//
// Every route is declared with a literal path in main.jsx and matched in full:
// `#/tasks` and `#/tasks/42` are different pages, and a prefix rule would send
// every path under a section to the same view, so a typo would render a page
// instead of the dashboard. A segment written `:name` captures exactly one path
// segment, which is how a task id rides in the URL (`#/tasks/42`) rather than
// only in the query string (`#/tasks?task=42` -- an existing deep link that
// keeps working).
//
// This lives in its own module because main.jsx renders on import and cannot be
// imported by a test; the matcher is the piece with decisions in it.
/**
* matchRoute returns `{ route, params }` for the first route whose pattern
* matches, or null. `params` is an object, empty for a literal route.
*/
export function matchRoute(routes, rawPath) {
const path = normalisePath(rawPath);
for (const route of routes) {
const params = matchPattern(route.path, path);
if (params) return { route, params };
}
return null;
}
/**
* navPath is the navigation section a route belongs to. A parameterised route
* is not a nav entry itself, so it names the section it was opened from -- the
* per-task page keeps the Tasks item current instead of blanking the highlight.
*/
export function navPath(route) {
return route?.navPath || route?.path || "/";
}
function normalisePath(rawPath) {
const path = String(rawPath ?? "/").split("?", 1)[0].split("#", 1)[0];
if (!path) return "/";
// A trailing slash names the same route: #/tasks/ is #/tasks, and #/tasks/42/
// is #/tasks/42.
return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
}
function matchPattern(pattern, path) {
const want = String(pattern).split("/");
const got = String(path).split("/");
if (want.length !== got.length) return null;
const params = {};
for (let i = 0; i < want.length; i += 1) {
const segment = want[i];
if (segment.startsWith(":")) {
if (!got[i]) return null;
params[segment.slice(1)] = decodeURIComponent(got[i]);
continue;
}
if (segment !== got[i]) return null;
}
return params;
}
-162
View File
@@ -1,162 +0,0 @@
import { h } from "preact";
import { useState, useRef, useEffect } from "preact/hooks";
import { api } from "../base/api.jsx";
export function valueText(value) {
if (value === null || value === undefined || value === "") return "—";
return String(value);
}
export function Row({ label, value, opts }) {
const text = valueText(value);
const [isEditing, setIsEditing] = useState(false);
const [editValue, setEditValue] = useState("");
const [error, setError] = useState(null);
const [saving, setSaving] = useState(false);
const [resetting, setResetting] = useState(false);
const key = opts?.key;
if (!key) {
return (
<div className="kv">
<span className="kv-label" title={opts?.hint}>{label}</span>
<span className={`kv-value mono ${text === "—" ? "is-empty" : ""}`} title={text}>{text}</span>
</div>
);
}
const lockedReason = opts.locked?.[key];
if (lockedReason) {
return (
<div className="kv is-locked">
<span className="kv-label" title={opts.hint}>{label}</span>
<span className={`kv-value mono ${text === "—" ? "is-empty" : ""}`} title={text}>{text}</span>
<span className="kv-note">{lockedReason}</span>
</div>
);
}
if (opts.editable === false) {
return (
<div className="kv">
<span className="kv-label" title={opts.hint}>{label}</span>
<span className={`kv-value mono ${text === "—" ? "is-empty" : ""}`} title={text}>{text}</span>
</div>
);
}
const overridden = opts.overridden?.includes(key);
const startEdit = () => {
setEditValue(String(opts.raw ?? ""));
setError(null);
setIsEditing(true);
};
const handleReset = async () => {
setResetting(true);
setError(null);
try {
await api.configReset(key);
opts.onSaved?.();
} catch (err) {
setError(String(err.message || err));
} finally {
setResetting(false);
}
};
const handleSave = async () => {
const parsed = parseEdit(opts.type, editValue);
if (parsed.error) {
setError(parsed.error);
return;
}
setSaving(true);
setError(null);
try {
const save = opts.save || ((val) => api.configUpdate({ [key]: val }));
await save(parsed.value);
setIsEditing(false);
opts.onSaved?.();
} catch (err) {
setError(String(err.message || err));
} finally {
setSaving(false);
}
};
if (isEditing) {
const inputRef = useRef(null);
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
const handleKeyDown = (e) => {
if (e.key === "Enter") {
e.preventDefault();
handleSave();
}
if (e.key === "Escape") setIsEditing(false);
};
let inputEl;
if (opts.type === "bool") {
inputEl = (
<select className="kv-input" value={editValue} onChange={e => setEditValue(e.target.value)} onKeyDown={handleKeyDown} ref={inputRef}>
<option value="true">true</option>
<option value="false">false</option>
</select>
);
} else if (opts.type === "enum") {
inputEl = (
<select className="kv-input" value={editValue} onChange={e => setEditValue(e.target.value)} onKeyDown={handleKeyDown} ref={inputRef}>
{(opts.options || []).map(o => <option key={o} value={o}>{o}</option>)}
</select>
);
} else {
inputEl = <input className="kv-input" type="text" value={editValue} onInput={e => setEditValue(e.target.value)} onKeyDown={handleKeyDown} ref={inputRef} />;
}
return (
<div className="kv">
<span className="kv-label" title={opts.hint}>{label}</span>
{inputEl}
<div className="kv-actions">
<button className="kv-save" type="button" onClick={handleSave} disabled={saving}>Save</button>
<button className="kv-cancel" type="button" onClick={() => setIsEditing(false)} disabled={saving}>Cancel</button>
</div>
{error && <span className="kv-note is-error">{error}</span>}
</div>
);
}
return (
<div className="kv">
<span className="kv-label" title={opts.hint}>{label}</span>
<span className={`kv-value mono ${text === "—" ? "is-empty" : ""}`} title={text}>{text}</span>
<div className="kv-actions">
{overridden && <span className="kv-flag" title="Set from the dashboard; this shadows the value in the config file">overridden</span>}
<button className="kv-btn" type="button" title={`Edit ${label}`} onClick={startEdit}>Edit</button>
{overridden && <button className="kv-btn" type="button" title="Discard the dashboard value and fall back to the config file" onClick={handleReset} disabled={resetting}>Reset</button>}
</div>
{error && <span className="kv-note is-error">{error}</span>}
</div>
);
}
export function parseEdit(type, text) {
switch (type) {
case "int": {
const n = parseInt(text, 10);
if (Number.isNaN(n)) return { error: "Enter a whole number" };
return { value: n };
}
case "bool":
return { value: text === "true" };
default:
return { value: text };
}
}
-150
View File
@@ -1,150 +0,0 @@
import { h, Fragment } from "preact";
import { useState } from "preact/hooks";
/**
* Operator controls that used to sit in the chat panel.
*
* Installing an update and approving a dangerous action are things you do to
* the deployment, not things you say to Archie. They lived in the chat surface
* only because that is where they were first built; in a launcher panel a few
* hundred pixels wide they crowded out the conversation, so they moved here
* with Configuration's other operator controls (archie-core-tf20).
*
* The handlers are optional so the cards can be rendered and asserted on
* without wiring: an unwired card still shows the state it was handed.
*/
function Section({ title, sub, children }) {
return (
<div className="card cfg-section">
<div className="card-head">
<div>
<h2 className="card-title">{title}</h2>
<p className="card-sub">{sub}</p>
</div>
</div>
{children}
</div>
);
}
function updateSummary(data) {
if (data?.error) return data.error;
if (data?.snapshot?.deferred) return "Update deferred.";
return "Archie is up to date.";
}
/**
* UpdateActionsCard is the actionable half of update checking: what is
* available, and the two decisions you can make about it. The read-only
* component/version comparison stays in UpdateStatusCard above it.
*/
export function UpdateActionsCard({ data, onDefer, onInstall }) {
const available = data?.available || [];
if (!available.length) {
return (
<Section title="Updates" sub="Whether a newer release is available, and what to do about it.">
<p className="cfg-note">{updateSummary(data)}</p>
</Section>
);
}
return (
<Section title="Updates" sub="Whether a newer release is available, and what to do about it.">
<p className="cfg-note">
{available.map((c) => `${c.Label || c.label}: ${c.Available || c.available}`).join(" · ")}
</p>
<div className="cfg-actions">
<button className="btn" type="button" onClick={() => onDefer?.(data.snapshot)}>
Defer
</button>
{data.can_install && (
<button className="btn btn-primary" type="button" onClick={() => onInstall?.(data.snapshot)}>
Install update
</button>
)}
</div>
</Section>
);
}
const checkpointNumber = (cp) => cp.Number ?? cp.number;
const checkpointLabel = (cp) => cp.Label ?? cp.label ?? "checkpoint";
/**
* DangerousActionsCard requests and adjudicates the actions that are gated
* behind approval. Nothing here acts on its own: a request only queues an
* approval, and the decision buttons are the only thing that lets one run.
*/
export function DangerousActionsCard({ data, onRequest, onDecide }) {
const [checkpoint, setCheckpoint] = useState("");
const [stopSpec, setStopSpec] = useState("");
if (data?.error) {
return (
<Section title="Dangerous actions" sub="Actions that need explicit approval before they run.">
<p className="cfg-note">{data.error}</p>
</Section>
);
}
const pending = data?.pending || [];
return (
<Section title="Dangerous actions" sub="Actions that need explicit approval before they run. Requesting one only queues it.">
<div className="cfg-request-row">
<select
aria-label="Checkpoint"
value={checkpoint}
onChange={(e) => setCheckpoint(e.target.value)}
>
<option value="">Select checkpoint</option>
{(data?.checkpoints || []).map((cp) => (
<option key={checkpointNumber(cp)} value={String(checkpointNumber(cp))}>
{checkpointNumber(cp)} — {checkpointLabel(cp)}
</option>
))}
</select>
<button className="btn" type="button" disabled={!checkpoint} onClick={() => onRequest?.("rollback", checkpoint)}>
Request rollback
</button>
</div>
<div className="cfg-request-row">
<input
placeholder="Process name or id"
aria-label="Process name or id"
value={stopSpec}
onInput={(e) => setStopSpec(e.target.value)}
/>
<button className="btn" type="button" disabled={!stopSpec.trim()} onClick={() => onRequest?.("stop", stopSpec)}>
Request stop
</button>
</div>
{!pending.length ? (
<p className="cfg-note">No pending dangerous actions.</p>
) : (
<Fragment>
{pending.map((action) => (
<div className="cfg-pending" key={action.id}>
<span>{action.description}</span>
<div className="cfg-actions">
<button className="btn" type="button" onClick={() => onDecide?.(action.id, "approve")}>
Approve
</button>
<button className="btn" type="button" onClick={() => onDecide?.(action.id, "permanent")}>
Approve for 24h
</button>
<button className="btn" type="button" onClick={() => onDecide?.(action.id, "deny")}>
Deny
</button>
</div>
</div>
))}
</Fragment>
)}
</Section>
);
}
-352
View File
@@ -1,352 +0,0 @@
/* Configuration-only styles.
*
* Rewritten because the previous layout had three compounding faults, all
* visible on a wide screen:
*
* 1. .cfg-row used `justify-content: space-between` on a full-width card,
* so the label sat at the far left and the value at the far right with
* ~1000px of dead space between them. Pairing a label to its value meant
* tracking across the whole viewport. An earlier "tighten spacing" pass
* reduced vertical padding only, which is why it did not help.
* 2. .cfg-value had no `min-width: 0`, so a long value could not shrink
* inside its flex parent and overflowed into the Edit button, visually
* truncating the number ("400" reading as "40") and colliding with it.
* 3. The locked-row reason was a flex sibling of an overflowing value, so
* it ran straight onto the end of the path with no visible separation
* ("...archie/work" + "pins the daemon's working layout").
*
* The replacement is a three-column grid: label, value, actions. Label and
* value are adjacent and left-aligned so the eye travels a fixed short
* distance regardless of viewport width; the value column is `minmax(0, 1fr)`
* so it can actually shrink; actions occupy a reserved column so nothing can
* ever overlap them. Secondary text (locked reason, override note, error)
* gets its own grid row rather than being crammed onto the value line.
*/
/* Cap and centre the whole page, not the individual lists.
*
* The page ran the full width of the shell, so a card was ~1300px of which
* the content used the left third. Earlier attempts fought that inside the
* card, capping or shrinking .kv-list, which only moved the imbalance around
* and left the Repositories and Providers tables stretched just as far.
*
* Constraining the page container fixes every child at once: cards, key/value
* lists and tables all take a readable measure, and the leftover space sits
* outside the cards where it reads as margin rather than as a hole in the
* layout. Scoped to this page rather than added to .page-head, which is
* shared with every other view.
*/
.cfg-page {
max-width: 70rem;
margin: 0 auto;
}
.cfg-section {
margin-bottom: var(--sp-4);
}
.cfg-subhead {
font-size: var(--text-sm);
font-weight: 600;
color: var(--fg-muted);
margin: var(--sp-5) 0 var(--sp-2);
}
.cfg-subhead:first-child {
margin-top: 0;
}
/* Key/value list.
*
* Two separate things were conflated in earlier attempts at this:
*
* - how far the value sits from its label, and
* - how wide the row is.
*
* They are different knobs. The original bug was the first (label left,
* value flung to the right edge), and shrinking the whole list to its
* content fixed it by breaking the second: rows became narrow, every list
* ended at a different width, the row separators stopped mid-card, and the
* Edit buttons no longer lined up with each other.
*
* So: the label column hugs its content (max-content, so the value starts
* immediately after the longest label), the value column takes the slack,
* and the actions column is pinned to the right edge. The row spans the
* card, which keeps the separators full width and puts every Edit in one
* consistent column, while the label-to-value distance stays short.
*/
/* The list owns the columns, not the row. Each .kv used to be its own grid,
which meant no row could size a column against any other row: a
max-content label track would end at a different x per row and the values
would come out ragged. Declaring the tracks once on the list and having
each row adopt them with `subgrid` gives one shared label column, sized to
the longest label and no wider. */
.kv-list {
display: grid;
grid-template-columns: max-content minmax(0, 1fr) auto;
column-gap: var(--sp-4);
row-gap: 0;
}
.kv {
display: grid;
grid-template-columns: subgrid;
grid-column: 1 / -1;
align-items: center;
row-gap: var(--sp-1);
padding: var(--sp-2) 0;
border-radius: var(--radius-sm);
}
/* Without subgrid the row cannot borrow the list's tracks, so fall back to a
per-row grid with a bounded label column. Values align because every row
resolves the same fixed range against the same container width. */
@supports not (grid-template-columns: subgrid) {
.kv-list {
display: flex;
flex-direction: column;
width: auto;
}
.kv {
grid-template-columns: minmax(8rem, 16rem) minmax(0, 1fr) auto;
column-gap: var(--sp-4);
}
}
.kv + .kv {
border-top: 1px solid var(--border);
}
.kv:hover {
background: var(--surface-hover);
}
.kv-label {
font-size: var(--text-sm);
color: var(--fg-muted);
}
/* min-width: 0 is load-bearing. A grid item defaults to min-width: auto,
which refuses to shrink below its content and is what pushed long paths
into the action column. */
.kv-value {
min-width: 0;
font-size: var(--text-sm);
color: var(--fg);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.kv-value.is-empty {
color: var(--fg-subtle);
}
.kv-actions {
display: flex;
align-items: center;
gap: var(--sp-2);
justify-self: end;
}
/* Secondary line: locked reason, override note, validation error. Starts in
the value column so it aligns under the value it describes. */
.kv-note {
grid-column: 2 / -1;
font-size: var(--text-xs);
color: var(--fg-subtle);
}
.kv-note.is-error {
color: var(--danger);
}
.kv.is-locked .kv-value {
color: var(--fg-muted);
}
/* Actions stay visible rather than appearing on hover: a control that only
exists on hover is invisible to touch and to anyone scanning for what is
editable. Low contrast until the row is hovered or focused instead. */
.kv-btn {
font: inherit;
font-size: var(--text-xs);
color: var(--fg-subtle);
background: transparent;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 2px var(--sp-2);
cursor: pointer;
flex: none;
transition: color 0.12s ease, border-color 0.12s ease, background 0.12s ease;
}
.kv:hover .kv-btn,
.kv:focus-within .kv-btn {
color: var(--fg-muted);
border-color: var(--border-strong);
}
.kv-btn:hover {
color: var(--fg);
border-color: var(--accent);
background: var(--accent-soft);
}
.kv-btn:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 1px;
}
.kv-flag {
font-size: var(--text-xs);
color: var(--warn);
background: var(--warn-soft);
border-radius: var(--radius-pill);
padding: 1px var(--sp-2);
flex: none;
}
.kv-input {
font: inherit;
font-size: var(--text-sm);
color: var(--fg);
background: var(--bg, var(--surface));
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
padding: var(--sp-1) var(--sp-2);
min-width: 0;
width: 100%;
}
.kv-input:focus {
outline: 2px solid var(--accent);
outline-offset: -1px;
}
.kv-save,
.kv-cancel {
font: inherit;
font-size: var(--text-xs);
border-radius: var(--radius-sm);
padding: var(--sp-1) var(--sp-2);
cursor: pointer;
flex: none;
}
.kv-save {
background: var(--accent);
border: 1px solid var(--accent);
color: var(--accent-fg);
font-weight: 500;
}
.kv-save:disabled {
opacity: 0.6;
cursor: default;
}
.kv-cancel {
background: transparent;
border: 1px solid var(--border-strong);
color: var(--fg-muted);
}
.kv-cancel:hover {
color: var(--fg);
}
.cfg-notice {
border-left: 3px solid var(--warn);
}
.cfg-notice p {
margin: 0;
font-size: var(--text-sm);
color: var(--warn);
}
/* Narrow viewports: stack label over value so neither has to truncate to a
few characters. Actions move onto the label line to keep the row compact. */
@media (max-width: 700px) {
/* Drop out of subgrid: a shared label column is the wrong shape once the
row stacks, and a row still adopting the list's three tracks would place
its stacked children into columns that no longer exist. */
.kv-list {
display: flex;
flex-direction: column;
width: auto;
}
.kv {
grid-template-columns: minmax(0, 1fr) auto;
column-gap: var(--sp-4);
}
.kv-label {
grid-column: 1;
}
.kv-actions {
grid-column: 2;
grid-row: 1;
}
.kv-value,
.kv-note {
grid-column: 1 / -1;
white-space: normal;
overflow-wrap: anywhere;
}
}
/* Operator controls rehomed from the chat panel (archie-core-tf20). */
.cfg-note {
margin: 0;
color: var(--fg-muted);
font-size: var(--text-sm);
}
.cfg-actions {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2);
margin-top: var(--sp-3);
}
.cfg-request-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--sp-2);
margin-bottom: var(--sp-3);
}
.cfg-request-row select,
.cfg-request-row input {
flex: 0 1 22rem;
min-width: 0;
padding: var(--sp-2) var(--sp-3);
background: var(--surface-hover);
color: var(--fg);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
font: inherit;
font-size: var(--text-sm);
}
/* One queued action: what it would do, and the decisions open on it. */
.cfg-pending {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: var(--sp-3);
padding: var(--sp-3) 0;
border-top: 1px solid var(--hairline);
}
.cfg-pending .cfg-actions {
margin-top: 0;
}
-492
View File
@@ -1,492 +0,0 @@
import { h } from "preact";
import { useState, useEffect } from "preact/hooks";
import "./settings.css";
import { api } from "../base/api.jsx";
import { statusKind, statusLabel } from "../base/task-meta.jsx";
import { Pill } from "../base/pill.jsx";
import { Row } from "./config-row.jsx";
import { UpdateStatusCard } from "./update-status.jsx";
import { UpdateActionsCard, DangerousActionsCard } from "./operator-cards.jsx";
function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
function Section({ title, sub, children }) {
return (
<div className="card cfg-section">
<div className="card-head">
<div>
<h2 className="card-title">{title}</h2>
<p className="card-sub">{sub}</p>
</div>
</div>
{children}
</div>
);
}
function ProvenanceCard({ origins }) {
if (!origins?.length) return (
<Section title="Configuration sources" sub="The files that supplied the running configuration.">
<Empty title="Source provenance is unavailable." />
</Section>
);
return (
<Section title="Configuration sources" sub="Applied from top to bottom; later entries take precedence over earlier ones.">
<div className="kv-list">
{origins.map((origin, i) => (
<Row key={i} label={`${origin.layer} ${origin.role}${origin.feature ? ` (${origin.feature})` : ""}`} value={origin.path} />
))}
</div>
</Section>
);
}
function roleButtonClass(kind) {
return kind === "quiet" ? "btn-quiet" : kind === "danger" ? "btn-danger" : "";
}
function LifecycleCard({ data, error }) {
if (error) {
return (
<Section title="Work lifecycle" sub="The task statuses and operator actions archied ships.">
<Empty title="Lifecycle unavailable" detail={error} />
</Section>
);
}
const statuses = data?.statuses || [];
const actions = data?.actions || [];
return (
<Section title="Work lifecycle" sub="The task statuses and operator actions archied ships. Add one on the backend and it appears here without a frontend change.">
<h3 className="cfg-subhead">Statuses</h3>
{statuses.length ? (
<div className="kv-list">
{statuses.map(s => {
const label = s.label ?? statusLabel(s.id);
const kind = s.kind ?? statusKind(s.id);
return (
<div className="kv" key={s.id}>
<span className="kv-label">{s.id}</span>
<span className="kv-value"><Pill text={label} kind={kind} /></span>
</div>
);
})}
</div>
) : (
<Empty title="No statuses reported" detail="The server did not return any lifecycle statuses." />
)}
<h3 className="cfg-subhead">Actions</h3>
{actions.length ? (
<div className="kv-list">
{actions.map(a => {
const label = a.label ?? a.id;
const cls = roleButtonClass(a.kind);
return (
<div className="kv" key={a.id}>
<span className="kv-label">{a.id}</span>
<span className="kv-value">
<button className={`btn btn-small ${cls}`} type="button" disabled>{label}</button>
</span>
</div>
);
})}
</div>
) : (
<Empty title="No actions reported" detail="The server did not return any operator actions." />
)}
</Section>
);
}
function RepoBoolCell({ r, field, onSaved, editable = true }) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [checked, setChecked] = useState(!!r[field]);
const handleChange = async (e) => {
const next = e.target.checked;
setChecked(next);
setLoading(true);
setError(null);
try {
await api.configRepoUpdate(r.owner, r.name, field, next);
onSaved?.();
} catch (err) {
setChecked(!next);
setError(String(err.message || err));
} finally {
setLoading(false);
}
};
if (!editable) {
return <td>{checked ? "yes" : "no"}</td>;
}
return (
<td>
<input className="repo-field-checkbox" type="checkbox" checked={checked} onChange={handleChange} disabled={loading} />
{error && <span className="kv-note is-error">{error}</span>}
</td>
);
}
function RepoIntCell({ r, field, onSaved, editable = true }) {
const [val, setVal] = useState(String(r[field] ?? 0));
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const commit = async () => {
const n = parseInt(val, 10);
if (Number.isNaN(n)) {
setError("Enter a whole number");
return;
}
setLoading(true);
setError(null);
try {
await api.configRepoUpdate(r.owner, r.name, field, n);
onSaved?.();
} catch (err) {
setError(String(err.message || err));
} finally {
setLoading(false);
}
};
const handleKeyDown = (e) => {
if (e.key === "Enter") {
e.preventDefault();
e.target.blur();
}
};
if (!editable) {
return <td className="mono">{val}</td>;
}
return (
<td>
<input
className="kv-input"
type="text"
value={val}
onChange={e => setVal(e.target.value)}
onBlur={commit}
onKeyDown={handleKeyDown}
disabled={loading}
/>
{error && <span className="kv-note is-error">{error}</span>}
</td>
);
}
// editable is false in a process that only renders a published
// configuration snapshot: its PATCH routes answer 503, so the cells are
// values rather than controls (archie-core-ymut).
export function RepositoriesCard({ repos, onSaved, editable = true }) {
if (!repos?.length) {
return (
<Section title="Repositories" sub="The repositories Archie polls for work.">
<Empty title="No repositories configured" detail="Add a [[repos]] entry in config.toml so Archie has somewhere to work." />
</Section>
);
}
const gateSummary = (gate) => {
if (!gate?.length) return "—";
return gate.map((cmd) => cmd.join(" ")).join(" → ");
};
return (
<Section title="Repositories" sub="Each repository Archie polls, and the quality gate a change must pass before it opens a pull request. Concurrent tasks, retries, and self-review are per-repository overrides -- PATCH /api/config/repos/{owner}/{name}, not the file config.toml directly.">
<div className="table-scroll">
<table className="table">
<thead>
<tr>
<th>Repository</th><th>Base branch</th><th>Ecosystem</th><th>Quality gate</th><th>Protected paths</th><th>Concurrent</th><th>Max retries</th><th>Self-review</th>
</tr>
</thead>
<tbody>
{repos.map((r, i) => (
<tr key={i}>
<td className="strong">{r.owner}/{r.name}</td>
<td className="mono">{r.base}</td>
<td>{r.ecosystem || "go"}</td>
<td className="mono">{gateSummary(r.gate)}</td>
<td className="mono">{r.protect?.length ? r.protect.join(", ") : "—"}</td>
<RepoBoolCell r={r} field="allow_concurrent" onSaved={onSaved} editable={editable} />
<RepoIntCell r={r} field="max_retries" onSaved={onSaved} editable={editable} />
<RepoBoolCell r={r} field="review_enabled" onSaved={onSaved} editable={editable} />
</tr>
))}
</tbody>
</table>
</div>
</Section>
);
}
function roleLabel(role) {
if (!role) return "Unknown role";
return role.charAt(0).toUpperCase() + role.slice(1).replace(/_/g, " ");
}
function ModelsAndProvidersCard({ models, providers }) {
const modelEntries = Object.entries(models || {});
const providerEntries = Object.entries(providers || {});
return (
<Section title="Models & providers" sub="Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.">
<h3 className="cfg-subhead">Model roles</h3>
{modelEntries.length ? (
<div className="kv-list">
{modelEntries.map(([role, ref]) => (
<Row key={role} label={roleLabel(role)} value={ref} />
))}
</div>
) : (
<Empty title="No model roles configured" detail='Assign a model to at least one role (e.g. "builder") in [models].' />
)}
<h3 className="cfg-subhead">Providers</h3>
{providerEntries.length ? (
<div className="table-scroll">
<table className="table">
<thead>
<tr><th>Provider</th><th>Class</th><th>Base URL</th><th>API key env var</th><th>Status</th></tr>
</thead>
<tbody>
{providerEntries.map(([name, p]) => (
<tr key={name}>
<td className="strong">{name}</td>
<td>{p.class}</td>
<td className="mono">{p.base_url || "default"}</td>
<td className="mono">{p.api_key_env || "—"}</td>
<td>
{p.configured ? <Pill text="configured" kind="ok" /> : <Pill text="missing credentials" kind="warn" />}
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<Empty title="No providers configured" detail="Add a [providers.<name>] entry so a model role above has something to run on." />
)}
</Section>
);
}
function SettingsApp() {
const [cfg, setCfg] = useState(null);
const [cfgError, setCfgError] = useState(null);
const [versionData, setVersionData] = useState(null);
const [versionError, setVersionError] = useState(null);
const [versionMissing, setVersionMissing] = useState(false);
const [lifecycleData, setLifecycleData] = useState(null);
const [lifecycleError, setLifecycleError] = useState(null);
// Update actions and dangerous-action approvals, rehomed from the chat panel
// (archie-core-tf20). Both degrade to absent rather than to an error banner:
// a deployment that does not wire them should show nothing, not a failure.
const [updateData, setUpdateData] = useState(null);
const [dangerousData, setDangerousData] = useState(null);
const loadAll = () => {
loadCfg();
loadVersion();
loadLifecycle();
loadUpdate();
loadDangerous();
};
const loadUpdate = async () => {
try {
setUpdateData(await api.chatUpdate());
} catch (err) {
setUpdateData(err?.status === 501 ? null : { error: String(err.message || err) });
}
};
const loadDangerous = async () => {
try {
setDangerousData(await api.chatDangerous());
} catch (err) {
setDangerousData(err?.status === 501 ? null : { error: String(err.message || err) });
}
};
const deferUpdate = async (snapshot) => {
await api.chatUpdateDefer(snapshot);
await loadUpdate();
};
const installUpdate = async (snapshot) => {
await api.chatUpdateInstall(snapshot);
await loadUpdate();
};
const requestDangerous = async (kind, spec) => {
await api.chatDangerousRequest(kind, spec);
await loadDangerous();
};
const decideDangerous = async (id, decision) => {
await api.chatDangerousDecision(id, decision);
await loadDangerous();
};
const loadCfg = async () => {
try {
const data = await api.config();
setCfg(data);
setCfgError(null);
} catch (err) {
setCfgError(String(err.message || err));
}
};
const loadVersion = async () => {
try {
const data = await api.version();
setVersionData(data?.components || []);
setVersionError(null);
setVersionMissing(false);
} catch (err) {
if (err?.status === 501) {
setVersionMissing(true);
} else {
setVersionError(String(err.message || err));
}
}
};
const loadLifecycle = async () => {
try {
const data = await api.taskMeta();
setLifecycleData(data);
setLifecycleError(null);
} catch (err) {
setLifecycleError(String(err.message || err));
}
};
useEffect(() => {
loadAll();
}, []);
return (
<div className="cfg-page">
<div className="page-head">
<div>
<h1 className="page-title">Configuration</h1>
<p className="page-sub">What archied is actually running with right now.</p>
</div>
<div className="page-actions">
<button className="btn" onClick={loadAll}>Refresh</button>
</div>
</div>
<div>
{/* A 501 is a deployment that did not wire update checking, which is a
legitimate state and a different thing from a broken one. Saying so
once here covers the absent UpdateActionsCard below too. */}
{versionMissing ? (
<div className="card cfg-section">
<div className="card-head">
<div>
<h2 className="card-title">Update status</h2>
<p className="card-sub">Not configured on this deployment, so there is nothing to check against.</p>
</div>
</div>
</div>
) : versionError ? (
<div className="card"><Empty title="Update status unavailable" detail={versionError} /></div>
) : versionData ? (
<UpdateStatusCard components={versionData} />
) : null}
</div>
{updateData && (
<div>
<UpdateActionsCard data={updateData} onDefer={deferUpdate} onInstall={installUpdate} />
</div>
)}
{dangerousData && (
<div>
<DangerousActionsCard data={dangerousData} onRequest={requestDangerous} onDecide={decideDangerous} />
</div>
)}
<div>
<LifecycleCard data={lifecycleData} error={lifecycleError} />
</div>
<div>
{cfgError ? (
<div className="card"><Empty title="Cannot reach archied" detail={cfgError} /></div>
) : !cfg || Object.keys(cfg).length === 0 ? (
<div className="card"><Empty title="No configuration loaded" detail="archied is running without a config file wired into the dashboard, so there is nothing to show." /></div>
) : (
<>
{cfg.reload?.overlay_unavailable && (
<div className="card cfg-notice"><p>The runtime config overlay is not in effect: {cfg.reload.overlay_unavailable}</p></div>
)}
{cfg.reload?.last_error && (
<div className="card cfg-notice"><p>The last config reload failed; the running config is unchanged: {cfg.reload.last_error}</p></div>
)}
{(cfg.schema || []).map((s, i) => {
const rows = s.fields.filter(f => f.type !== "structured");
if (!rows.length) return null;
return (
<Section title={s.label} sub={s.description} key={i}>
<div className="kv-list">
{rows.map(f => (
<Row
key={f.key}
label={f.label}
value={f.value}
opts={{
key: f.key,
type: f.type,
options: f.options,
raw: f.value,
hint: f.description,
editable: f.editable && cfg.editable !== false,
locked: cfg.locked || {},
overridden: cfg.overridden || [],
onSaved: loadCfg
}}
/>
))}
</div>
</Section>
);
})}
<RepositoriesCard repos={cfg.repositories} onSaved={loadCfg} editable={cfg.editable !== false} />
<ModelsAndProvidersCard models={cfg.models} providers={cfg.providers} />
<ProvenanceCard origins={cfg.provenance} />
</>
)}
</div>
</div>
);
}
export function settingsPage(query) {
return <SettingsApp query={query} />;
}
-71
View File
@@ -1,71 +0,0 @@
import { h } from "preact";
import { Pill } from "../base/pill.jsx";
function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
function Section({ sub, title, children }) {
return (
<div className="card cfg-section">
<div className="card-head">
<div>
<h2 className="card-title">{title || "Update status"}</h2>
<p className="card-sub">{sub}</p>
</div>
</div>
{children}
</div>
);
}
const STATUS_LABELS = { ok: "OK", update_available: "Update available", drift: "Drift", unknown: "Unknown" };
const STATUS_KINDS = { ok: "ok", update_available: "info", drift: "danger", unknown: "idle" };
export function UpdateStatusCard({ components }) {
if (!components || !components.length) {
return (
<Section sub="How each component is deployed, and whether what's running matches what's installed.">
<Empty title="No components reported" detail="The configured update-check command returned nothing." />
</Section>
);
}
return (
<Section sub="How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.">
<div className="table-scroll">
<table className="table">
<thead>
<tr>
<th>Component</th><th>Install type</th><th>Running</th><th>Latest available</th><th>Status</th>
</tr>
</thead>
<tbody>
{components.map(c => {
const basis = [
`Installed claim: ${c.installed_claim || "unknown"}`,
`Running: ${c.running_version || "not observed"}`,
c.reference ? `Reference: ${c.reference}` : null,
].filter(Boolean).join("\n");
return (
<tr title={basis} key={c.id || c.label}>
<td className="strong">{c.label || c.id}</td>
<td className="mono">{c.install_type || "—"}</td>
<td className="mono">{c.running_version || "—"}</td>
<td className="mono">{c.latest_available || "—"}</td>
<td>
<Pill text={STATUS_LABELS[c.status] || c.status} kind={STATUS_KINDS[c.status] || "idle"} />
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</Section>
);
}
-34
View File
@@ -1,34 +0,0 @@
/* Skills-only styles. */
.skill-search {
font: inherit;
font-size: var(--text-sm);
color: var(--fg);
background: var(--surface);
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
padding: var(--sp-2) var(--sp-3);
width: 220px;
}
.skill-search:focus {
outline: 2px solid var(--accent-soft);
outline-offset: 1px;
}
.skill-card {
display: flex;
flex-direction: column;
}
.skill-desc {
color: var(--fg-muted);
font-size: var(--text-sm);
margin: 0 0 var(--sp-3);
flex: 1;
}
.skill-source {
font-size: var(--text-xs);
color: var(--fg-subtle);
}
-98
View File
@@ -1,98 +0,0 @@
import { h, Fragment } from "preact";
import { useState, useEffect, useMemo } from "preact/hooks";
import "./skills.css";
import { api } from "../base/api.jsx";
import { Pill } from "../base/pill.jsx";
function Empty({ title, detail }) {
return (
<div class="empty">
<div class="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
export function skillsPage(query) {
return <SkillsApp query={query} />;
}
function SkillsApp() {
const [skills, setSkills] = useState([]);
const [search, setSearch] = useState("");
const [loadError, setLoadError] = useState(null);
const load = async () => {
try {
const res = await api.skills();
setSkills(res?.skills || []);
setLoadError(null);
} catch (err) {
setSkills([]);
setLoadError(String(err.message || err));
}
};
useEffect(() => {
load();
}, []);
const matches = (skill, term) => {
if (!term) return true;
const haystack = `${skill.name} ${skill.description}`.toLowerCase();
return haystack.includes(term);
};
const filteredSkills = useMemo(() => skills.filter((s) => matches(s, search)), [skills, search]);
return (
<div>
<div class="page-head">
<div>
<h1 class="page-title">Skills</h1>
<p class="page-sub">What Archie can do, in plain language.</p>
</div>
<div class="page-actions">
<button class="btn" onClick={load}>Refresh</button>
</div>
</div>
<div class="card">
<div class="card-head">
<div>
<h2 class="card-title">Catalogue</h2>
<p class="card-sub">Project, shared, and user-global skills</p>
</div>
<input
class="skill-search"
type="search"
placeholder="Search skills…"
onInput={(e) => setSearch(e.target.value.trim().toLowerCase())}
/>
</div>
<div class="grid grid-2">
{loadError ? (
<Empty title="Cannot reach archied" detail={loadError} />
) : !skills.length ? (
<Empty
title="No skills discovered yet"
detail="Skills live as SKILL.md files under project, shared, or user-global .agents/skills/<name>/ directories. Add one and refresh to make it available."
/>
) : !filteredSkills.length ? (
<Empty title="No skills match" detail={`Nothing found for "${search}".`} />
) : (
filteredSkills.map((skill) => (
<div class="card skill-card" key={skill.name}>
<div class="card-head">
<h3 class="card-title">{skill.name || "Untitled skill"}</h3>
{skill.workflow && <Pill text={skill.workflow} kind="info" />}
</div>
<p class="skill-desc">{skill.description || "No description provided."}</p>
<div class="skill-source">{skill.source || "Unknown source"}</div>
</div>
))
)}
</div>
</div>
</div>
);
}
+127
View File
@@ -0,0 +1,127 @@
@import url('https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&display=swap');
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn-vue/tailwind.css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--font-sans: 'Geist Variable', sans-serif;
--font-heading: var(--font-sans);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--color-foreground: var(--foreground);
--color-background: var(--background);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--radius: 0.625rem;
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
@apply font-sans;
}
}
-92
View File
@@ -1,92 +0,0 @@
// The per-attempt effective configuration (R4).
//
// There is no config endpoint: the document arrives inside the task's event
// stream, which this page already fetches for the stage rail's agent reports
// and the timeline. So this panel issues no request of its own and adds nothing
// to the API client contract.
//
// Selection is by kind AND attempt. Selecting by kind alone would show the
// newest attempt's configuration on every attempt, which is exactly the
// merge-attempts bug the attempt column exists to prevent.
// The schema name is owned by the daemon (events.ConfigCapturedSchema in
// internal/events/events.go). A payload in an unrecognised schema is shown
// verbatim with a note rather than reinterpreted, so a server-side bump
// degrades to the raw view instead of rendering something wrong. The literal is
// pinned on both sides (internal/events/events_test.go and
// ui/test/attempt-config.test.js) so a one-sided rename fails.
export const CONFIG_SCHEMA = "archie/task-config@1";
export function selectConfigEvent(events, attempt) {
return (
(events || []).find(
(ev) => ev && ev.kind === "config_captured" && Number(ev.attempt) === Number(attempt),
) || null
);
}
export function AttemptConfig({ events, attempt, onRetry }) {
if (events === undefined) {
return <div className="run-loading">Loading this task's events…</div>;
}
if (events === null) {
return (
<div className="run-error">
<div className="run-error-title">Could not load this task's events</div>
<div className="run-error-detail">
The configuration is recorded as an event on the task, so it cannot be shown while the
event stream is unreadable. archied did not answer — retry, or check the daemon.
</div>
{onRetry ? (
<button className="btn" type="button" onClick={onRetry}>
Retry
</button>
) : null}
</div>
);
}
const event = selectConfigEvent(events, attempt);
if (!event) {
return (
<div className="empty">
<div className="empty-title">Not captured for this run</div>
<div>
Archie records the effective configuration when it dispatches an attempt. Attempt {attempt}{" "}
has no such record — it predates the record, or the capture did not run. Nothing here says
the run used the defaults.
</div>
</div>
);
}
const data = event.data || {};
const schema = data.schema || "";
const document = data.document;
return (
<div className="run-config">
<p className="run-config-scope">
This is attempt {event.attempt}'s effective task-runtime configuration: a non-secret subset
covering bot identity, models, limits, budgets, dispatch, diff cap, notifications, forge host
and tool policy. It is not the dashboard configuration view — providers, repositories,
identities, credentials and lock state are not part of it.
</p>
<div className="run-config-when">
Captured {event.at || "at an unrecorded time"}
{event.stage ? ` in stage ${event.stage}` : ""}
</div>
{schema === CONFIG_SCHEMA ? (
<pre className="run-json">{JSON.stringify(document ?? {}, null, 2)}</pre>
) : (
<>
<div className="run-config-unknown">
Recorded in an unknown schema{schema ? ` (${schema})` : ""}. The raw payload is shown
verbatim; nothing here reinterprets it.
</div>
<pre className="run-json">{JSON.stringify(data, null, 2)}</pre>
</>
)}
</div>
);
}
-202
View File
@@ -1,202 +0,0 @@
import { ago } from "../base/format.jsx";
// Changed files for one attempt (R3), from `GET /api/tasks/{id}/changes`.
//
// The capture happens at the producer: archied records the diffstat at the
// moment it commits or pushes an attempt's work. So the honest empty state is
// "no capture was recorded for this attempt", never "no files changed" -- a run
// that predates capture, or one that produced no commit, has no capture and
// nothing here can turn that into a claim about the repository.
// The change-status ids are a wire vocabulary owned by the daemon
// (internal/domain/workflow/task/changes.go). Only the words are the
// dashboard's: an id added on the server renders as its raw id rather than
// breaking the row. ui/test/changed-files.test.js pins the id set on this side
// and the constants' own test pins it on the other, so a one-sided rename fails
// instead of drifting.
const FILE_STATUS = {
added: "Added",
modified: "Modified",
deleted: "Deleted",
renamed: "Renamed",
typechange: "Type changed",
};
export function fileStatusLabel(status) {
return FILE_STATUS[status] || status || "unknown";
}
// The forge links come from the same projection the task list uses: the task's
// own repo/PR URLs, or the capture's if the server attached them. A link is
// rendered only when there is a URL to render -- a capture with no forge
// coordinates shows its owner/repo and PR number as text rather than a dead
// link.
export function captureLinks(capture, task) {
const repo = capture?.repo_url || task?.repo_url || "";
const samePR =
task && String(task.pr_number ?? "") !== "" && String(task.pr_number) === String(capture?.pr_number ?? "");
const pr = capture?.pr_url || (samePR ? task.pr_url || "" : "");
return { repo, pr };
}
export function totalsLabel(totals = {}) {
const files = Number(totals.files) || 0;
const parts = [`${files} file${files === 1 ? "" : "s"}`];
if (totals.additions) parts.push(`+${totals.additions}`);
if (totals.deletions) parts.push(`−${totals.deletions}`);
return parts.join(" · ");
}
function FileTable({ capture }) {
const files = capture.files || [];
const total = Number(capture.totals?.files) || files.length;
if (!files.length) {
return (
<div className="run-changes-empty">
This capture recorded no file entries
{total ? `, though its totals cover ${total} file${total === 1 ? "" : "s"}` : ""}.
</div>
);
}
return (
<>
<table className="table run-changes-table">
<thead>
<tr>
<th>Path</th>
<th>Change</th>
<th className="run-changes-count">Added</th>
<th className="run-changes-count">Deleted</th>
</tr>
</thead>
<tbody>
{files.map((file, i) => (
<tr key={`${file.path}:${i}`}>
<td className="mono run-changes-path">
{file.old_path ? <span className="run-changes-old">{file.old_path} → </span> : null}
{file.path}
</td>
<td>
{fileStatusLabel(file.status)}
{/* binary means "no textual hunks were recorded", not "this is a
binary file on disk": the counts beside it are still real. */}
{file.binary ? <span className="run-changes-hint">no textual hunks</span> : null}
</td>
<td className="run-changes-count mono">{file.additions ? `+${file.additions}` : "—"}</td>
<td className="run-changes-count mono">{file.deletions ? `−${file.deletions}` : "—"}</td>
</tr>
))}
</tbody>
</table>
{capture.truncated ? (
<p className="run-changes-note">
Showing the first {files.length} of {total} files. The totals above cover every file in
this capture.
</p>
) : null}
</>
);
}
function Capture({ capture, task }) {
const links = captureLinks(capture, task);
const prNumber = capture.pr_number;
return (
<section className="run-capture">
<div className="run-capture-head">
<span className="run-capture-when">
{capture.captured_after ? `Captured after ${capture.captured_after}` : "Captured"}
{capture.stage ? ` in stage ${capture.stage}` : ""}
</span>
<span className="run-capture-at">{capture.captured_at ? ago(capture.captured_at) : ""}</span>
</div>
<div className="run-capture-meta">
<span className="mono">
{links.repo ? (
<a className="run-capture-link" href={links.repo} target="_blank" rel="noreferrer">
{capture.owner}/{capture.repo}
</a>
) : (
`${capture.owner || ""}/${capture.repo || ""}`
)}
</span>
{capture.branch ? (
<span className="mono run-capture-branch">
{capture.branch}
{capture.base ? ` → ${capture.base}` : ""}
</span>
) : null}
{capture.head_sha ? <span className="mono run-capture-sha">{String(capture.head_sha).slice(0, 8)}</span> : null}
{prNumber ? (
links.pr ? (
<a className="run-capture-link" href={links.pr} target="_blank" rel="noreferrer">
PR #{prNumber}
</a>
) : (
<span className="mono">PR #{prNumber}</span>
)
) : null}
<span className="run-capture-totals">{totalsLabel(capture.totals)}</span>
</div>
<FileTable capture={capture} />
</section>
);
}
export function ChangedFiles({ state, task, onRetry }) {
if (state === undefined) {
return <div className="run-loading">Loading changed files…</div>;
}
if (state === null) {
return (
<div className="run-error">
<div className="run-error-title">Could not load this attempt's changed files</div>
<div className="run-error-detail">
archied did not answer for this attempt. It may be restarting — retry, or check the daemon.
</div>
{onRetry ? (
<button className="btn" type="button" onClick={onRetry}>
Retry
</button>
) : null}
</div>
);
}
const captures = state.captures || [];
// A capture event WAS recorded but its payload could not be read. The server
// reports `found` from the event's existence precisely so this is not
// reported as "no capture was recorded", which would be a false statement
// about a run whose diffstat demonstrably was captured.
if (state.found === true && !captures.length) {
return (
<div className="empty">
<div className="empty-title">A change capture was recorded but could not be read</div>
<div>
This attempt has a change capture event, but this dashboard could not decode its
payload. That is a read failure, not a statement about what the attempt changed.
</div>
</div>
);
}
if (!state.found || !captures.length) {
return (
<div className="empty">
<div className="empty-title">No change capture was recorded for this attempt</div>
<div>
Archie records what an attempt changed when it commits or pushes that work. Nothing was
recorded here — the attempt may predate capture, or it produced no commit. This is not the
same as "no files changed".
</div>
</div>
);
}
return (
<div className="run-changes">
{captures.map((capture, i) => (
<Capture key={`${capture.captured_at || ""}:${i}`} capture={capture} task={task} />
))}
</div>
);
}
-41
View File
@@ -1,41 +0,0 @@
// Raw debug view (R7): the stored task record and the task's events, verbatim.
//
// The events are deliberately NOT filtered to the selected attempt. A debug
// view that silently hid events would be worse than useless, so every event is
// shown and each carries its own `attempt` for the operator to attribute. The
// selected attempt is reported in the note and in the envelope's own `attempt`
// field; nothing here is summarised, projected or prettified beyond JSON
// indentation.
export function DebugView({ state, attempt, onRetry }) {
if (state === undefined) {
return <div className="run-loading">Loading the stored record…</div>;
}
if (state === null) {
return (
<div className="run-error">
<div className="run-error-title">Could not load the stored record</div>
<div className="run-error-detail">
archied did not answer for this task's debug view. It may be restarting — retry, or check
the daemon.
</div>
{onRetry ? (
<button className="btn" type="button" onClick={onRetry}>
Retry
</button>
) : null}
</div>
);
}
return (
<div className="run-debug">
<p className="run-debug-note">
The stored task record and its events, verbatim. Events are unfiltered on purpose: this is
every event the task has, and each one carries the attempt it belongs to. Attempt {attempt}{" "}
is the one selected above.
</p>
<pre className="run-json">{JSON.stringify(state, null, 2)}</pre>
</div>
);
}
-196
View File
@@ -1,196 +0,0 @@
import { Pill } from "../base/pill.jsx";
import { describeTimelineEvent, duration } from "./timeline-event.jsx";
// The per-attempt stage rail (R1).
//
// The rail is built from `GET /api/tasks/{id}/attempts`, which returns each
// attempt with its stages inline, so the selector and the rail can never
// disagree about which attempt is on screen. The rail only ever renders one
// attempt: merging two attempts by stage name is the failure this design
// exists to avoid.
//
// What a stage status means, and what it does not:
//
// a stage fails when its Go function returned an error. There is NO exit
// code, no pass/fail verdict, and no notion of "the work was correct" --
// a stage that returned nil after producing a poor diff is `ok`. So the rail
// never renders a checkmark, a badge or an exit status; it renders the
// status word, the duration and the error text, and says plainly what `ok`
// means. The agent's own self-reported outcome (`agent_finish`) is shown
// separately, labelled as the agent's report rather than as archie's verdict.
//
// A per-run elapsed time is deliberately NOT rendered. `waiting_human` can span
// days, so wall time from an attempt's start is not a duration of work; only
// per-stage durations exist and only those are shown.
const STAGE_STATUS = {
ok: { label: "ok", kind: "ok" },
failed: { label: "failed", kind: "danger" },
interrupted: { label: "interrupted", kind: "warn" },
running: { label: "running", kind: "info" },
unknown: { label: "unknown", kind: "idle" },
};
export function stageStatusMeta(status) {
return STAGE_STATUS[status] || { label: status || "unknown", kind: "idle" };
}
// agentReports returns the agent's own account of a stage: the `agent_finish`
// events whose attempt and stage both match. Returning an array rather than one
// value keeps a stage that ran two agents honest instead of showing the last.
export function agentReports(events, attemptNumber, stage) {
return (events || [])
.filter(
(ev) =>
ev &&
ev.kind === "agent_finish" &&
Number(ev.attempt) === Number(attemptNumber) &&
(ev.stage || "") === (stage || ""),
)
.map((ev) => describeTimelineEvent(ev));
}
// An attempt's start is rendered as an absolute instant, never as "started 2
// days ago": on a still-running attempt a relative stamp reads as two days of
// work, which is exactly the elapsed-time claim the design forbids. The
// attempt's own `duration_ms` is never rendered for the same reason -- it is
// wall time, and waiting_human can span days.
function startedAt(value) {
const when = value instanceof Date ? value : new Date(value);
if (Number.isNaN(when.getTime())) return "start time not recorded";
return `started ${when.toISOString().replace("T", " ").slice(0, 16)} UTC`;
}
function StageRow({ stage, attemptNumber, events }) {
const meta = stageStatusMeta(stage.status);
const ran = duration(stage.duration_ms);
const reports = agentReports(events, attemptNumber, stage.name);
return (
<li className="run-stage" data-status={stage.status || "unknown"}>
<span className="run-stage-node" aria-hidden="true" />
<div className="run-stage-body">
<div className="run-stage-head">
<span className="run-stage-name mono">{stage.name || "(unnamed stage)"}</span>
<Pill text={meta.label} kind={meta.kind} />
<span className="run-stage-duration">
{ran ? `ran for ${ran}` : "duration not recorded"}
</span>
</div>
{stage.error ? <div className="run-stage-error">{stage.error}</div> : null}
{reports.map((report, i) => (
<div className="run-agent-report" key={i}>
<span className="run-agent-report-label">Agent's own report, not verified by archie: </span>
{[report.title, report.detail].filter(Boolean).join(" · ")}
</div>
))}
</div>
</li>
);
}
function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
// The events no attempt owns. It renders in EVERY rail state, the empty ones
// included: a deployment where every event predates the attempt column answers
// with no attempts at all, and reporting "No attempts recorded" there without
// the count would present unattributable history as nothing having happened.
function UnattributedNote({ count }) {
const n = Number(count) || 0;
if (!n) return null;
return (
<p className="run-rail-note">
{n} event{n === 1 ? "" : "s"} on this task predate attempt attribution and cannot be assigned to a
run.
</p>
);
}
export function StageRail({ state, attemptNumber, events, onRetry }) {
if (state === undefined) {
return <div className="run-loading">Loading this task's attempts…</div>;
}
if (state === null) {
return (
<div className="run-error">
<div className="run-error-title">Could not load this task's attempts</div>
<div className="run-error-detail">
archied did not answer for this task's run history. It may be restarting — retry, or check
the daemon.
</div>
{onRetry ? (
<button className="btn" type="button" onClick={onRetry}>
Retry
</button>
) : null}
</div>
);
}
const attempts = state?.attempts || [];
if (!attempts.length) {
return (
<>
<Empty
title="No attempts recorded"
detail="This task has no recorded run. An attempt is written when a stage event is emitted, and none exist here."
/>
<UnattributedNote count={state?.unattributed_events} />
</>
);
}
const attempt = attempts.find((a) => Number(a.attempt) === Number(attemptNumber));
if (!attempt) {
return (
<>
<Empty
title={`Attempt ${attemptNumber} is not recorded for this task`}
detail={`This task recorded attempt ${attempts.map((a) => a.attempt).join(", ")}.`}
/>
<UnattributedNote count={state?.unattributed_events} />
</>
);
}
const stages = attempt.stages || [];
const meta = stageStatusMeta(attempt.status);
return (
<div className="run-rail">
<div className="run-rail-head">
<span className="run-rail-attempt">Attempt {attempt.attempt}</span>
<Pill text={meta.label} kind={meta.kind} />
<span className="run-rail-when">{startedAt(attempt.started_at)}</span>
</div>
{stages.length ? (
<ol className="run-stages" aria-label={`Stages recorded in attempt ${attempt.attempt}`}>
{stages.map((stage, i) => (
<StageRow
key={`${stage.seq ?? i}:${stage.name}`}
stage={stage}
attemptNumber={attempt.attempt}
events={events}
/>
))}
</ol>
) : (
<Empty
title="No stages recorded for this attempt"
detail="The attempt exists, but nothing recorded a stage for it."
/>
)}
<p className="run-rail-legend">
<strong>ok</strong> means the stage returned without error. Archie records no exit code and
does not verify that the work was correct, so this is a progress status, not a check result.
</p>
<UnattributedNote count={state?.unattributed_events} />
</div>
);
}
-69
View File
@@ -1,69 +0,0 @@
import { useRef } from "preact/hooks";
// A tab bar for the run detail page. There is no other consumer yet, so it
// stays in tasks/ rather than in base (organisation.md extracts on the second
// distinct consumer).
//
// Keyboard behaviour follows the WAI-ARIA tabs pattern with automatic
// activation: the tab list is one stop in the page's tab order (roving
// tabindex), Left/Right move between tabs and select as they go, Home/End jump
// to the ends. Automatic activation is the right choice here because every
// panel is a local render, not a fetch: there is no cost to switching.
export function tabId(prefix, id) {
return `${prefix}-tab-${id}`;
}
export function panelId(prefix, id) {
return `${prefix}-panel-${id}`;
}
export function TabBar({ tabs, active, onSelect, prefix = "run", label = "Run detail views" }) {
const refs = useRef([]);
const select = (index) => {
const tab = tabs[index];
if (!tab) return;
onSelect?.(tab.id);
refs.current[index]?.focus?.();
};
const onKeyDown = (event) => {
const current = tabs.findIndex((tab) => tab.id === active);
if (current < 0) return;
let next;
if (event.key === "ArrowRight") next = (current + 1) % tabs.length;
else if (event.key === "ArrowLeft") next = (current - 1 + tabs.length) % tabs.length;
else if (event.key === "Home") next = 0;
else if (event.key === "End") next = tabs.length - 1;
else return;
event.preventDefault();
select(next);
};
return (
<div className="tab-bar" role="tablist" aria-label={label} onKeyDown={onKeyDown}>
{tabs.map((tab, index) => {
const selected = tab.id === active;
return (
<button
key={tab.id}
ref={(node) => {
refs.current[index] = node;
}}
id={tabId(prefix, tab.id)}
className={`tab${selected ? " is-selected" : ""}`}
type="button"
role="tab"
aria-selected={selected}
aria-controls={panelId(prefix, tab.id)}
tabIndex={selected ? 0 : -1}
onClick={() => onSelect?.(tab.id)}
>
{tab.label}
</button>
);
})}
</div>
);
}
-617
View File
@@ -1,617 +0,0 @@
/* The per-task run detail page.
Colour comes only from the shared tokens in css/tokens.css, so both themes
are covered by construction; the layout is one column of panels that
collapses on narrow viewports. Motion is limited to hover/selection
transitions and is switched off for reduced-motion users. */
.run-meta {
display: flex;
align-items: center;
gap: var(--sp-4);
flex-wrap: wrap;
margin: calc(var(--sp-2) * -1) 0 var(--sp-4);
font-size: var(--text-sm);
}
.run-meta-item {
display: inline-flex;
align-items: center;
gap: var(--sp-2);
}
.run-meta-label {
color: var(--fg-muted);
font-size: var(--text-xs);
text-transform: uppercase;
letter-spacing: 0.05em;
}
.run-meta-value {
color: var(--fg);
}
.run-meta-muted {
color: var(--fg-muted);
}
.run-meta-link {
color: var(--accent);
}
.run-meta-link:hover {
text-decoration: underline;
}
.run-note {
margin: 0 0 var(--sp-4);
padding: var(--sp-3) var(--sp-4);
border-left: 3px solid var(--warn);
background: var(--warn-soft);
border-radius: var(--radius-sm);
color: var(--fg);
font-size: var(--text-sm);
}
/* ── New run ─────────────────────────────────────────────────────────────── */
.run-restart {
display: flex;
align-items: center;
gap: var(--sp-3);
flex-wrap: wrap;
margin-bottom: var(--sp-4);
}
.run-restart-copy {
flex: 1 1 22rem;
margin: 0;
color: var(--fg-muted);
font-size: var(--text-sm);
}
.run-restart-unavailable {
flex: 1 1 22rem;
margin: 0;
color: var(--fg-muted);
font-size: var(--text-sm);
}
.run-restart-error {
flex: 1 1 100%;
margin: 0;
font-size: var(--text-sm);
}
.run-restart-error-refused {
color: var(--warn);
}
.run-restart-error-broken {
color: var(--danger);
}
.run-restart-error-session-expired {
color: var(--warn);
}
/* ── Attempt selector ────────────────────────────────────────────────────── */
.run-attempts {
display: flex;
gap: var(--sp-2);
flex-wrap: wrap;
margin-bottom: var(--sp-4);
}
.run-attempt {
display: inline-flex;
align-items: center;
gap: var(--sp-2);
padding: var(--sp-2) var(--sp-3);
border: 1px solid var(--border);
border-radius: var(--radius-pill);
background: var(--surface);
color: var(--fg-muted);
font: inherit;
font-size: var(--text-sm);
cursor: pointer;
transition: border-color var(--transition), color var(--transition);
}
.run-attempt:hover {
border-color: var(--border-strong);
color: var(--fg);
}
.run-attempt.is-selected {
border-color: var(--accent);
background: var(--accent-soft);
color: var(--fg);
}
.run-attempt-id {
font-weight: 500;
}
.run-attempt-meta {
color: var(--fg-muted);
font-size: var(--text-xs);
}
/* ── Tabs ────────────────────────────────────────────────────────────────── */
.run-card {
padding-top: var(--sp-4);
}
.tab-bar {
display: flex;
gap: var(--sp-1);
border-bottom: 1px solid var(--border);
margin-bottom: var(--sp-4);
overflow-x: auto;
scrollbar-width: thin;
}
.tab {
position: relative;
padding: var(--sp-2) var(--sp-3);
border: 0;
border-bottom: 2px solid transparent;
border-radius: var(--radius-sm) var(--radius-sm) 0 0;
background: transparent;
color: var(--fg-muted);
font: inherit;
font-size: var(--text-sm);
white-space: nowrap;
cursor: pointer;
transition: color var(--transition), background var(--transition);
}
.tab:hover {
color: var(--fg);
background: var(--surface-hover);
}
.tab.is-selected {
color: var(--fg);
border-bottom-color: var(--accent);
font-weight: 500;
}
.run-panel {
min-width: 0;
min-height: 6rem;
}
.run-panel:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 4px;
}
/* ── Shared panel states ─────────────────────────────────────────────────── */
.run-loading {
padding: var(--sp-5) 0;
color: var(--fg-muted);
font-size: var(--text-sm);
}
.run-error {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: var(--sp-2);
padding: var(--sp-3) 0;
}
.run-error-title {
color: var(--fg);
font-weight: 500;
}
.run-error-detail {
color: var(--fg-muted);
font-size: var(--text-sm);
max-width: 60ch;
}
.run-json {
margin: 0;
padding: var(--sp-3);
max-height: 60vh;
overflow: auto;
background: var(--bg-raised);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
font-family: var(--font-mono);
font-size: var(--text-xs);
line-height: 1.5;
/* pre-wrap keeps the indentation the JSON is printed with while letting a
long value wrap instead of forcing the panel to scroll sideways. */
white-space: pre-wrap;
overflow-wrap: anywhere;
}
/* ── Stage rail ──────────────────────────────────────────────────────────── */
.run-rail-head {
display: flex;
align-items: center;
gap: var(--sp-3);
flex-wrap: wrap;
margin-bottom: var(--sp-4);
}
.run-rail-attempt {
font-weight: 600;
}
.run-rail-when {
color: var(--fg-muted);
font-size: var(--text-xs);
}
.run-stages {
list-style: none;
margin: 0;
padding: 0;
}
.run-stage {
position: relative;
display: grid;
grid-template-columns: 1.75rem 1fr;
gap: var(--sp-2);
padding-bottom: var(--sp-4);
}
/* The rail line: a single vertical stroke behind the stage nodes, so the
sequence reads as one run rather than as unrelated rows. */
.run-stage::before {
content: "";
position: absolute;
left: 0.6875rem;
top: 1rem;
bottom: 0;
width: 1px;
background: var(--border-strong);
}
.run-stage:last-child::before {
display: none;
}
.run-stage-node {
position: relative;
z-index: 1;
width: 0.875rem;
height: 0.875rem;
margin: 0.25rem 0 0 0.25rem;
border-radius: 50%;
border: 2px solid var(--border-strong);
background: var(--bg-raised);
}
.run-stage[data-status="ok"] .run-stage-node {
border-color: var(--ok);
}
.run-stage[data-status="failed"] .run-stage-node {
border-color: var(--danger);
}
.run-stage[data-status="interrupted"] .run-stage-node {
border-color: var(--warn);
}
.run-stage[data-status="running"] .run-stage-node {
border-color: var(--info);
}
.run-stage-body {
min-width: 0;
}
.run-stage-head {
display: flex;
align-items: center;
gap: var(--sp-2);
flex-wrap: wrap;
}
.run-stage-name {
font-weight: 500;
color: var(--fg);
/* A stage name is one unbroken token often enough that it has to be allowed
to break, or a long one pushes the status and duration off the row. */
overflow-wrap: anywhere;
min-width: 0;
}
.run-stage-duration {
color: var(--fg-muted);
font-size: var(--text-xs);
}
.run-stage-error {
margin-top: var(--sp-2);
padding: var(--sp-2) var(--sp-3);
border-left: 3px solid var(--danger);
background: var(--danger-soft);
border-radius: var(--radius-sm);
color: var(--fg-muted);
font-size: var(--text-sm);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.run-agent-report {
margin-top: var(--sp-2);
color: var(--fg-muted);
font-size: var(--text-xs);
}
.run-agent-report-label {
color: var(--fg-muted);
}
.run-rail-legend,
.run-rail-note {
margin: var(--sp-3) 0 0;
color: var(--fg-muted);
font-size: var(--text-xs);
max-width: 70ch;
}
.run-rail-legend strong {
color: var(--fg-muted);
}
/* ── Changed files ───────────────────────────────────────────────────────── */
.run-capture + .run-capture {
margin-top: var(--sp-5);
padding-top: var(--sp-4);
border-top: 1px solid var(--border);
}
.run-capture-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: var(--sp-3);
flex-wrap: wrap;
}
.run-capture-when {
color: var(--fg);
font-size: var(--text-sm);
font-weight: 500;
}
.run-capture-at {
color: var(--fg-muted);
font-size: var(--text-xs);
}
.run-capture-meta {
display: flex;
align-items: center;
gap: var(--sp-3);
flex-wrap: wrap;
margin: var(--sp-2) 0 var(--sp-3);
color: var(--fg-muted);
font-size: var(--text-xs);
}
.run-capture-link {
color: var(--accent);
}
.run-capture-link:hover {
text-decoration: underline;
}
.run-capture-branch,
.run-capture-sha {
color: var(--fg-muted);
}
.run-capture-totals {
color: var(--fg-muted);
}
.run-changes-table td {
padding: var(--sp-2) var(--sp-3);
vertical-align: top;
}
.run-changes-path {
color: var(--fg);
word-break: break-all;
}
.run-changes-old {
color: var(--fg-muted);
}
.run-changes-count {
text-align: right;
white-space: nowrap;
}
.run-changes-hint,
.run-changes-note,
.run-changes-empty {
color: var(--fg-muted);
font-size: var(--text-xs);
}
.run-changes-hint {
display: block;
}
.run-changes-empty {
padding: var(--sp-3) 0;
}
/* ── Configuration ───────────────────────────────────────────────────────── */
.run-config-scope {
margin: 0 0 var(--sp-2);
color: var(--fg-muted);
font-size: var(--text-sm);
max-width: 75ch;
}
.run-config-when {
margin-bottom: var(--sp-3);
color: var(--fg-muted);
font-size: var(--text-xs);
}
.run-config-unknown {
margin-bottom: var(--sp-2);
color: var(--warn);
font-size: var(--text-sm);
}
/* ── Log pane ────────────────────────────────────────────────────────────── */
.task-log-filters {
padding-bottom: var(--sp-3);
border-bottom: 1px solid var(--border);
}
.task-log-attempt {
color: var(--fg);
font-size: var(--text-sm);
font-weight: 500;
}
.task-log-filter {
display: inline-flex;
align-items: center;
gap: var(--sp-2);
}
.task-log-filter-label {
color: var(--fg-muted);
font-size: var(--text-xs);
text-transform: uppercase;
letter-spacing: 0.05em;
}
.task-log-filter-note {
flex: 1 1 100%;
margin: 0;
color: var(--fg-muted);
font-size: var(--text-xs);
max-width: 80ch;
}
/* On the detail page the log is the primary content, so it takes the tallest
read surface and a framed edge of its own rather than the bare top rule the
inline list-page pane uses. Scoped to .run-panel so the list-page pane keeps
its 40vh cap. */
.run-panel .task-log-list {
max-height: 62vh;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg-raised);
padding: 0 var(--sp-2);
}
/* ── Status pills on this page ───────────────────────────────────────────── */
/* The shared .pill palette draws its small status WORD in the semantic hue on
that hue's own tint. Measured against the card this page renders on, that
fails WCAG AA 4.5:1 for small text in the light theme (ok 3.39:1, warn
3.26:1, danger 4.03:1, idle 4.09:1) and for `unknown` in the dark theme
(idle 3.31:1). Raising the shared tokens is an app-wide design change, not
this page's to make, so here the status word is drawn in the full-contrast
foreground colour (>=12.6:1 both themes) and the hue is carried by the dot
the pill already has -- which still clears the 3:1 non-text minimum
(worst pair 3.26:1). */
.run-page .pill {
color: var(--fg);
}
.run-page .pill-ok::before {
background: var(--ok);
}
.run-page .pill-warn::before {
background: var(--warn);
}
.run-page .pill-danger::before {
background: var(--danger);
}
.run-page .pill-info::before {
background: var(--info);
}
.run-page .pill-idle::before {
background: var(--idle);
}
/* ── Narrow viewports: the rail collapses ────────────────────────────────── */
@media (max-width: 700px) {
.run-meta {
margin-bottom: var(--sp-3);
}
.run-restart {
align-items: flex-start;
}
.run-attempts {
overflow-x: auto;
flex-wrap: nowrap;
padding-bottom: var(--sp-1);
}
/* The connector line and its gutter are what make the rail a timeline; on a
phone they cost the width the stage names need, so the rail becomes a plain
list of stages in order. */
.run-stage {
grid-template-columns: 1fr;
padding-bottom: var(--sp-3);
border-bottom: 1px solid var(--border);
}
.run-stage::before {
display: none;
}
.run-stage-node {
display: none;
}
.run-capture-head {
flex-direction: column;
align-items: flex-start;
gap: var(--sp-1);
}
}
@media (max-width: 480px) {
.tab {
padding: var(--sp-2);
}
.run-json {
max-height: 45vh;
}
}
@media (prefers-reduced-motion: reduce) {
.run-attempt,
.tab {
transition: none;
}
}
-556
View File
@@ -1,556 +0,0 @@
import { useState, useEffect, useRef } from "preact/hooks";
import "./task-detail.css";
import { api, classifyActionError } from "../base/api.jsx";
import { Pill } from "../base/pill.jsx";
import { actionFor, statusKind, statusLabel } from "../base/task-meta.jsx";
import { TabBar, panelId, tabId } from "./tab-bar.jsx";
import { StageRail, stageStatusMeta } from "./stage-rail.jsx";
import { ChangedFiles } from "./changed-files.jsx";
import { AttemptConfig } from "./attempt-config.jsx";
import { DebugView } from "./debug-view.jsx";
import { EMPTY_LOG_FILTERS, TaskLogPanel, logCacheKey } from "./task-logs.jsx";
// The per-task run detail page (R1, R3-R9), reached at #/tasks/{id}.
//
// One page, one task: which run it is showing, what each stage of that run did,
// its log, what it changed, the configuration it ran under, and the raw record.
// The task id rides in the path and the view state (`tab`, `attempt`) rides in
// the query string, so every view of this page is a deep link that survives a
// reload -- #/tasks/42?tab=changes&attempt=2.
//
// The attempt is the unit of every panel. Nothing on this page merges two
// attempts: the rail, the log, the capture and the config are all selected by
// attempt, and the two views of the same task's attempts (the selector and the
// rail) come from a single response.
export const RUN_TABS = [
{ id: "stages", label: "Stages" },
{ id: "log", label: "Log" },
{ id: "changes", label: "Changed files" },
{ id: "config", label: "Configuration" },
{ id: "debug", label: "Debug" },
];
const TAB_PREFIX = "run";
const TAB_IDS = new Set(RUN_TABS.map((tab) => tab.id));
export function parseTaskId(raw) {
const value = String(raw ?? "").trim();
if (!/^\d+$/.test(value)) return null;
const n = Number(value);
return Number.isSafeInteger(n) && n > 0 ? n : null;
}
export function initialTab(query) {
const requested = query?.get?.("tab") || "";
return TAB_IDS.has(requested) ? requested : RUN_TABS[0].id;
}
// `?attempt=2` pins attempt 2. An absent, empty or non-numeric value follows
// whatever the server reports as current, and 0 is the wire's own spelling of
// "the current attempt" (taskLogTarget, internal/webui/api_tasks_logs.go), so it
// selects the current attempt rather than a nonexistent attempt 0.
export function initialAttempt(query) {
const raw = query?.get?.("attempt");
if (raw == null || raw === "") return null;
const n = Number(raw);
return Number.isInteger(n) && n > 0 ? n : null;
}
export function runHash(id, tab, attempt) {
const params = new URLSearchParams();
params.set("tab", tab || RUN_TABS[0].id);
if (attempt) params.set("attempt", String(attempt));
return `#/tasks/${id}?${params.toString()}`;
}
// Selection is written back with replaceState rather than by assigning
// location.hash: replaceState does not fire a hashchange, so the router does not
// remount and refetch the page on every tab click, while the address bar still
// holds the full state for a copy, a bookmark or a reload.
export function writeRunHash(id, tab, attempt) {
try {
window.history.replaceState(null, "", `${location.pathname}${location.search}${runHash(id, tab, attempt)}`);
} catch {
// A deployment that refuses the history write still renders every panel;
// only the shareable URL is lost, and the page never depends on it.
}
}
function attemptKey(id, attempt) {
return `${id}|${Number(attempt) || 0}`;
}
function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
function NotFound({ id }) {
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Task not found</h1>
<p className="page-sub">No task with id {id} in this deployment.</p>
</div>
<div className="page-actions">
<a className="btn" href="#/tasks">
Back to tasks
</a>
</div>
</div>
<div className="card">
<div className="empty">
<div className="empty-title">Nothing is recorded for task {id}</div>
<div>archied answered that this task does not exist, so there is no run history to show.</div>
</div>
</div>
</div>
);
}
function InvalidId({ raw }) {
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Not a task id</h1>
<p className="page-sub">The run view addresses one task by its id: #/tasks/42</p>
</div>
<div className="page-actions">
<a className="btn" href="#/tasks">
Back to tasks
</a>
</div>
</div>
<div className="card">
<div className="empty">
<div className="empty-title">“{raw}” is not a task id</div>
<div>A task id is a positive whole number. Nothing was requested.</div>
</div>
</div>
</div>
);
}
function AttemptSelector({ attempts, selected, onSelect }) {
const list = attempts?.attempts || [];
if (!list.length) return null;
return (
<div className="run-attempts" role="group" aria-label="Attempts of this task">
{list.map((attempt) => {
const meta = stageStatusMeta(attempt.status);
const selectedNow = Number(attempt.attempt) === Number(selected);
return (
<button
key={attempt.attempt}
type="button"
className={`run-attempt${selectedNow ? " is-selected" : ""}`}
aria-pressed={selectedNow}
onClick={() => onSelect(attempt.attempt)}
>
<span className="run-attempt-id">Attempt {attempt.attempt}</span>
<Pill text={meta.label} kind={meta.kind} />
<span className="run-attempt-meta">
{(attempt.stages || []).length} stage{(attempt.stages || []).length === 1 ? "" : "s"}
</span>
</button>
);
})}
</div>
);
}
function RunDetail({ id, query }) {
const [tab, setTab] = useState(() => initialTab(query));
const [requestedAttempt, setRequestedAttempt] = useState(() => initialAttempt(query));
const [taskList, setTaskList] = useState(undefined);
const [attempts, setAttempts] = useState(undefined);
const [missing, setMissing] = useState(false);
const [events, setEvents] = useState(undefined);
const [filters, setFilters] = useState(EMPTY_LOG_FILTERS);
const [logs, setLogs] = useState(new Map());
const [changes, setChanges] = useState(new Map());
const [debug, setDebug] = useState(new Map());
const [retryBusy, setRetryBusy] = useState(false);
const [retryError, setRetryError] = useState(null);
const [refreshToken, setRefreshToken] = useState(0);
const started = useRef(new Set());
const task = Array.isArray(taskList) ? taskList.find((t) => String(t.id) === String(id)) || null : null;
const currentAttempt = Number(attempts?.current_attempt) > 0 ? Number(attempts.current_attempt) : null;
// The wire spells "the task's current attempt" as 0, which is not an attempt
// number: a task with no run at all must not address attempt 0.
const attemptNumber = requestedAttempt ?? currentAttempt;
const selectedAttempt = (attempts?.attempts || []).find(
(a) => Number(a.attempt) === Number(attemptNumber),
);
const stageNames = [
...new Set((selectedAttempt?.stages || []).map((stage) => stage.name).filter(Boolean)),
];
// Every keyed fetch goes through here: the key is what the response belongs
// to, so a late response for an attempt the operator has already left lands
// under its own key and is never shown against another attempt.
const keyedLoad = (cacheKey, fetcher, setter, { force = false } = {}) => {
if (started.current.has(cacheKey) && !force) return;
started.current.add(cacheKey);
setter((prev) => new Map(prev).set(cacheKey, undefined));
fetcher()
.then((res) => setter((prev) => new Map(prev).set(cacheKey, res)))
.catch(() => setter((prev) => new Map(prev).set(cacheKey, null)));
};
const loadTaskList = () => {
setTaskList(undefined);
api
.tasks()
.then((res) => setTaskList(res))
.catch(() => setTaskList(null));
};
const loadAttempts = () => {
setAttempts(undefined);
setMissing(false);
api
.taskAttempts(id)
.then((res) => setAttempts(res))
.catch((err) => {
if (err?.status === 404) setMissing(true);
setAttempts(null);
});
};
const loadEvents = () => {
setEvents(undefined);
api
.task(id)
.then((res) => setEvents(res || []))
.catch(() => setEvents(null));
};
const loadLogs = (attempt, opts) =>
keyedLoad(
logCacheKey(id, attempt, filters),
() =>
api.taskLogs(id, {
attempt: attempt || undefined,
level: filters.level,
stage: filters.stage,
limit: 500,
}),
setLogs,
opts,
);
const loadChanges = (attempt, opts) =>
keyedLoad(attemptKey(id, attempt), () => api.taskChanges(id, { attempt }), setChanges, opts);
const loadDebug = (attempt, opts) =>
keyedLoad(attemptKey(id, attempt), () => api.taskDebug(id, { attempt }), setDebug, opts);
const refreshAll = () => {
// Drop every cache and let the effects refetch: a manual refresh must not
// show a stale capture or log beside fresh attempt history.
started.current = new Set();
setLogs(new Map());
setChanges(new Map());
setDebug(new Map());
loadTaskList();
loadAttempts();
loadEvents();
setRefreshToken((n) => n + 1);
};
useEffect(() => {
loadTaskList();
loadAttempts();
loadEvents();
// The page loads once for the task it was opened for; the route remounts it
// when that changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (attemptNumber == null) return;
// Only the visible tab's lazy payload is fetched: the debug envelope repeats
// the whole event list, so fetching it on every page load would duplicate a
// large body for nothing.
if (tab === "log") loadLogs(attemptNumber);
else if (tab === "changes") loadChanges(attemptNumber);
else if (tab === "debug") loadDebug(attemptNumber);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tab, attemptNumber, filters, refreshToken]);
useEffect(() => {
writeRunHash(id, tab, attemptNumber);
}, [id, tab, attemptNumber]);
const performRetry = async () => {
const title = task?.title || `task ${id}`;
const confirmed = window.confirm(
`Start a new run for "${title}"? This is a new attempt, and the previous attempt's commits are discarded.`,
);
if (!confirmed) return;
setRetryError(null);
setRetryBusy(true);
try {
await api.taskAction(id, "retry");
// A new attempt starts here. Everything cached belongs to the attempt
// that just ended, so it is dropped rather than shown against the new
// run: the attempt history, the events, every cached log, capture and
// debug payload. The new attempt then becomes the selected run without a
// reload.
started.current = new Set();
setLogs(new Map());
setChanges(new Map());
setDebug(new Map());
setRequestedAttempt(null);
loadTaskList();
loadAttempts();
loadEvents();
setRefreshToken((n) => n + 1);
} catch (err) {
setRetryError(classifyActionError(err));
} finally {
setRetryBusy(false);
}
};
if (missing) return <NotFound id={id} />;
const logKey = attemptNumber == null ? null : logCacheKey(id, attemptNumber, filters);
const changeKey = attemptKey(id, attemptNumber);
const debugKey = attemptKey(id, attemptNumber);
const panel = () => {
// The rail owns its own loading, failure and empty-rail states.
if (tab === "stages") {
return (
<StageRail
state={attempts}
attemptNumber={attemptNumber}
events={events}
onRetry={loadAttempts}
/>
);
}
// Every other panel is scoped to one attempt, and "no attempt" is a claim
// only a successful read of the run history can make -- a failed read is
// reported as a failed read.
if (attempts === undefined) {
return <div className="run-loading">Loading this task's attempts…</div>;
}
if (attempts === null) {
return (
<div className="run-error">
<div className="run-error-title">Could not load this task's attempts</div>
<div className="run-error-detail">
This panel reads one attempt, and the task's run history could not be read.
</div>
<button className="btn" type="button" onClick={loadAttempts}>
Retry
</button>
</div>
);
}
if (attemptNumber == null) {
return (
<Empty
title="No attempt recorded"
detail="This task has no recorded run, so there is nothing to read for an attempt."
/>
);
}
switch (tab) {
case "log":
return (
<TaskLogPanel
state={logKey && logs.has(logKey) ? logs.get(logKey) : undefined}
attempt={attemptNumber}
stages={stageNames}
filters={filters}
onFilterChange={setFilters}
taskId={id}
onRetry={() => loadLogs(attemptNumber, { force: true })}
/>
);
case "changes":
return (
<ChangedFiles
state={changes.has(changeKey) ? changes.get(changeKey) : undefined}
task={task}
onRetry={() => loadChanges(attemptNumber, { force: true })}
/>
);
case "config":
return <AttemptConfig events={events} attempt={attemptNumber} onRetry={loadEvents} />;
case "debug":
return (
<DebugView
state={debug.has(debugKey) ? debug.get(debugKey) : undefined}
attempt={attemptNumber}
onRetry={() => loadDebug(attemptNumber, { force: true })}
/>
);
default:
return (
<StageRail
state={attempts}
attemptNumber={attemptNumber}
events={events}
onRetry={loadAttempts}
/>
);
}
};
const retryMeta = actionFor("retry");
const canRetry = Boolean(retryMeta && (task?.actions || []).includes("retry"));
return (
<div className="run-page">
<div className="page-head">
<div>
<h1 className="page-title">{task?.title || `Task #${id}`}</h1>
<p className="page-sub">
One run of task {id}
{task?.workflow ? ` · ${task.workflow} workflow` : ""}
{task?.repo ? ` · ${task.owner}/${task.repo}` : ""}
</p>
</div>
<div className="page-actions">
<a className="btn" href="#/tasks">
Back to tasks
</a>
<button className="btn" type="button" onClick={refreshAll}>
Refresh
</button>
</div>
</div>
<div className="run-meta">
<span className="run-meta-item">
<span className="run-meta-label">Task status</span>
{taskList === undefined ? (
<span className="run-meta-muted">loading…</span>
) : task ? (
<Pill text={statusLabel(task.status)} kind={statusKind(task.status)} />
) : (
<span className="run-meta-muted">not read</span>
)}
</span>
<span className="run-meta-item">
<span className="run-meta-label">Attempt</span>
<span className="run-meta-value">
{attempts === null
? "run history unreadable"
: attempts === undefined
? "loading…"
: attemptNumber == null
? "none recorded"
: `attempt ${attemptNumber} of ${currentAttempt ?? attemptNumber}`}
</span>
</span>
{task?.repo_url ? (
<a className="run-meta-link" href={task.repo_url} target="_blank" rel="noreferrer">
{task.owner}/{task.repo}
</a>
) : null}
{task?.issue_url && task.issue_number ? (
<a className="run-meta-link" href={task.issue_url} target="_blank" rel="noreferrer">
Issue #{task.issue_number}
</a>
) : null}
{task?.pr_url && task.pr_number ? (
<a className="run-meta-link" href={task.pr_url} target="_blank" rel="noreferrer">
PR #{task.pr_number}
</a>
) : null}
</div>
{taskList === null ? (
<p className="run-note">
The task list could not be read, so this page cannot show the task's current status or its
operator controls. The run history below comes from the task's own endpoints.
</p>
) : null}
{Array.isArray(taskList) && !task ? (
<p className="run-note">
Task {id} is not among the tasks this dashboard lists (the list covers the 100 most
recently updated). Its recorded attempts are shown below; the Debug tab holds the stored
record verbatim.
</p>
) : null}
<section className="run-restart" aria-label="Start a new run">
<button
className={`btn ${retryMeta?.kind === "primary" ? "btn-primary" : ""}`}
type="button"
disabled={!canRetry || retryBusy}
title="Retry this task as a new run"
onClick={performRetry}
>
{retryBusy ? "Starting…" : "Start a new run"}
</button>
<p className="run-restart-copy">
Starts a new attempt for this task: a fresh worktree reset onto the base branch. The
previous attempt's commits are discarded — they are not carried into the new run.
</p>
{!canRetry && taskList !== undefined ? (
<p className="run-restart-unavailable">
{task
? `A new run can only start from a parked task. This task is ${statusLabel(task.status)}.`
: "This task's operator controls could not be read, so a new run cannot be started from here."}
</p>
) : null}
{retryError ? (
<p className={`run-restart-error run-restart-error-${retryError.kind}`}>
{retryError.kind === "session-expired"
? "Your session has expired. Reload to sign in."
: retryError.kind === "refused"
? `${retryError.message} — this run cannot be restarted from here.`
: `${retryError.message} — try again, or check the daemon.`}
</p>
) : null}
</section>
<AttemptSelector
attempts={attempts}
selected={attemptNumber}
onSelect={(value) => setRequestedAttempt(value)}
/>
<div className="card run-card">
<TabBar tabs={RUN_TABS} active={tab} onSelect={setTab} prefix={TAB_PREFIX} />
<div
className="run-panel"
role="tabpanel"
id={panelId(TAB_PREFIX, tab)}
aria-labelledby={tabId(TAB_PREFIX, tab)}
tabIndex={0}
>
{panel()}
</div>
</div>
</div>
);
}
export function taskDetailPage(query, params) {
const raw = params?.id;
const id = parseTaskId(raw);
if (id === null) return <InvalidId raw={raw ?? ""} />;
// The key is load-bearing, not cosmetic. The router renders this page with
// Preact's own render() into one long-lived outlet (main.jsx, show()), so
// navigating from #/tasks/1 to #/tasks/2 diffs the same element in place and
// RunDetail is never remounted. Without the key every piece of task-scoped
// state -- the open tab, the pinned attempt, the run history, the events, and
// the log/change/debug caches -- stays with the task that was left, and the
// new task is rendered against another task's reads. Keying by id makes the
// remount RunDetail's own comment assumes actually happen.
return <RunDetail key={id} id={id} query={query} />;
}
-26
View File
@@ -1,26 +0,0 @@
import { attentionStatusIds, statusIds } from "../base/task-meta.jsx";
// The vocabulary is the server catalog, not a hand-synced copy: the "needs
// you" grouping and the set of known statuses come straight from task-meta so
// a status added on the backend shows up here without a frontend change.
// "needs_you" is a UI pseudo-status (work waiting on a human), so it is
// prepended rather than stored in the catalog.
//
// Both are read at call time rather than captured at import. The catalog
// arrives after this module loads, so module-level constants here would freeze
// the defaults for the life of the process -- which is what they did, leaving
// the task filter unable to see a served status no matter when it landed.
function taskStatuses() {
return new Set(["needs_you", ...statusIds()]);
}
export function initialTaskFilter(params) {
const requested = params?.get?.("status") || "";
return taskStatuses().has(requested) ? requested : "";
}
export function taskMatchesStatus(task, status) {
if (!status) return true;
if (status === "needs_you") return attentionStatusIds().has(task.status);
return task.status === status;
}
-205
View File
@@ -1,205 +0,0 @@
import { LogRow, LOG_LEVELS } from "../base/log-row.jsx";
// A task attempt's log pane (R5).
//
// Three read outcomes are kept apart, because only one of them is about the
// operator's configuration or about this attempt:
//
// disabled -- this process cannot read task logs at all (deployment)
// found: false -- a reader exists and this attempt has no log file
// entries: [] -- a log exists and nothing matches the current filter
//
// The filter controls render ABOVE all three, and above the loading and failed
// states too. Putting them inside the success branch is how a deployment that
// cannot read logs ends up showing an empty filtered pane instead of saying so.
// They render when the page can act on a filter change (the list page's inline
// pane has no filter state, and a control that filters nothing is worse than no
// control); the ordering rule belongs here either way.
//
// The attempt is not a filter here: the page selects the attempt and this pane
// reports which one it is showing, so the pane can never read attempt 1's log
// while claiming attempt 2.
// Task-log download URL. The attempt is named explicitly so a download matches
// the attempt the panel is showing rather than whatever is current by the time
// the operator clicks.
export function taskLogDownloadURL(id, attempt) {
return `/api/tasks/${id}/logs/download` + (attempt == null ? "" : `?attempt=${attempt}`);
}
export const EMPTY_LOG_FILTERS = { level: "", stage: "" };
// The identity of a log read: a task, an attempt, and the filters that produced
// the response. Keying by task alone cannot represent two attempts -- the bug
// this replaces -- and keying without the filters would serve attempt 2's
// unfiltered log in answer to a filtered request.
export function logCacheKey(id, attempt, filters = EMPTY_LOG_FILTERS) {
const applied = filters || EMPTY_LOG_FILTERS;
return [id, Number(attempt) || 0, applied.level || "", applied.stage || ""].join("|");
}
function FilterBar({ filters, onFilterChange, stages, attempt }) {
const change = (patch) => onFilterChange?.({ ...filters, ...patch });
const shown = Number(attempt) || 0;
return (
<div className="log-filters task-log-filters">
<span className="task-log-attempt">{shown > 0 ? `Attempt ${shown}` : "Current attempt"}</span>
{/* Controls appear only where the page can act on a change: a filter that
filters nothing is worse than no filter. */}
{onFilterChange ? (
<>
<label className="task-log-filter">
<span className="task-log-filter-label">Level</span>
<select
className="task-filter"
value={filters.level}
aria-label="Filter log entries by level"
onChange={(e) => change({ level: e.target.value })}
>
{LOG_LEVELS.map((level) => (
<option key={level.value} value={level.value}>
{level.label}
</option>
))}
</select>
</label>
<label className="task-log-filter">
<span className="task-log-filter-label">Stage</span>
<select
className="task-filter"
value={filters.stage}
aria-label="Filter log entries by stage"
onChange={(e) => change({ stage: e.target.value })}
>
<option value="">All stages</option>
{(stages || []).map((stage) => (
<option key={stage} value={stage}>
{stage}
</option>
))}
</select>
</label>
{/* A stage filter is a narrowing, not a clean sweep: only lines a
stage tagged carry a stage, and agent/tool output never does.
Saying so beside the control is what keeps a sparse result from
reading as a broken pane. */}
{filters.stage ? (
<p className="task-log-filter-note">
A stage filter matches only log lines that record a stage. Agent and tool output
carries none, so it is not shown while this filter is set.
</p>
) : null}
{!filters.stage && !(stages || []).length ? (
<p className="task-log-filter-note">
This attempt recorded no stage names, so the stage filter has nothing to match.
</p>
) : null}
</>
) : null}
</div>
);
}
// The pane's state, announced once. It is a live region for STATE, not for the
// log's lines: putting aria-live on the list itself would read every entry
// aloud on every load, which for a 500-entry pane is unusable. `aria-atomic`
// makes the whole sentence re-announce rather than a fragment of it.
function LogStatus({ text }) {
return (
<p className="visually-hidden" role="status" aria-live="polite" aria-atomic="true">
{text}
</p>
);
}
export function TaskLogPanel({
state,
onRetry,
taskId,
attempt,
filters = EMPTY_LOG_FILTERS,
onFilterChange,
stages = [],
}) {
const resolvedAttempt = Number(attempt) || Number(state?.attempt) || 0;
// One live-region sentence per read outcome, so the pane announces WHICH case
// it is in. The two unavailable cases stay distinct in the announcement the
// same way they stay distinct on screen.
let status;
let body;
if (state === undefined) {
status = "Loading this attempt's log";
body = <div className="task-log-loading">Loading attempt log…</div>;
} else if (state === null) {
status = "This attempt's log could not be loaded";
body = (
<div className="task-log-error">
<div className="task-timeline-detail">Could not load this attempt's log.</div>
<button className="btn" onClick={onRetry}>
Retry
</button>
</div>
);
} else if (state.found === false && !state.disabled) {
// A reader exists in this process but the attempt has no log file. That is
// a fact about the attempt, and saying "logging was not enabled" here (which
// this panel used to do) told the operator to go and change a setting that
// was already correct.
status = "No log recorded for this attempt";
body = (
<div className="empty">
<div className="empty-title">No log recorded for this attempt</div>
<div>This attempt produced no output, or it has not started writing yet.</div>
</div>
);
} else if (state.disabled) {
// This process cannot read task logs at all. That IS about the deployment,
// and it is the only case where the panel may say so.
status = "This dashboard cannot read task logs";
body = (
<div className="empty">
<div className="empty-title">No persisted log for this attempt</div>
<div>This dashboard cannot read task logs. The service that owns the log files is not reporting a log reader.</div>
</div>
);
} else {
const entries = state.entries || [];
const download = taskId != null ? taskLogDownloadURL(taskId, resolvedAttempt || null) : null;
const footer = download ? (
<a className="btn btn-small task-log-download" href={download} download>
Download log
</a>
) : null;
if (!entries.length) {
status = "This attempt's log has no entries matching the current filter";
body = (
<div className="empty">
<div className="empty-title">Nothing recorded</div>
<div>This attempt's log file has no entries matching the current filter.</div>
{footer}
</div>
);
} else {
status = `${entries.length} log entr${entries.length === 1 ? "y" : "ies"} shown`;
body = (
<>
<div className="log-list task-log-list">
{entries.map((entry, i) => (
<LogRow key={i} entry={entry} />
))}
</div>
{footer}
</>
);
}
}
return (
<>
<FilterBar filters={filters} onFilterChange={onFilterChange} stages={stages} attempt={resolvedAttempt} />
<LogStatus text={status} />
{body}
</>
);
}
-8
View File
@@ -1,8 +0,0 @@
export function taskRowA11y(task, expanded) {
const title = task.title || "untitled task";
return {
"aria-expanded": String(expanded),
"aria-controls": `task-timeline-${task.id}`,
"aria-label": `${expanded ? "Collapse" : "Expand"} timeline for ${title}`,
};
}
-350
View File
@@ -1,350 +0,0 @@
/* Tasks-only styles. */
.task-summary {
margin-bottom: var(--sp-5);
}
.task-filters {
display: flex;
gap: var(--sp-2);
align-items: center;
flex-wrap: wrap;
}
.task-search,
.task-filter {
font: inherit;
font-size: var(--text-sm);
color: var(--fg);
background: var(--surface);
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
padding: var(--sp-2) var(--sp-3);
}
.task-search {
width: 220px;
}
.task-search:focus,
.task-filter:focus {
outline: 2px solid var(--accent-soft);
outline-offset: 1px;
}
.task-row {
cursor: pointer;
}
.task-expand {
width: 1.5rem;
height: 1.5rem;
margin-right: var(--sp-2);
padding: 0;
color: var(--fg-muted);
background: transparent;
border: 1px solid var(--border);
border-radius: 50%;
font: inherit;
line-height: 1;
cursor: pointer;
}
.task-expand:hover,
.task-expand:focus-visible {
color: var(--fg);
border-color: var(--accent);
}
.activity-row {
cursor: pointer;
}
.activity-row:hover td,
.activity-row:focus td {
background: var(--surface-hover);
}
.activity-row:focus {
outline: 2px solid var(--accent);
outline-offset: -2px;
}
.task-source-link {
color: var(--accent);
text-decoration: none;
}
.task-source-link:hover {
text-decoration: underline;
}
/* The title cell links to the task's run detail page. It inherits the title's
colour so the row still reads as a list, and underlines on hover so the link
is discoverable. */
.task-detail-link {
color: inherit;
}
.task-detail-link:hover,
.task-detail-link:focus-visible {
text-decoration: underline;
text-decoration-color: var(--accent);
}
.task-actions {
display: flex;
gap: var(--sp-1);
white-space: nowrap;
flex-wrap: wrap;
}
.btn-small {
padding: var(--sp-1) var(--sp-2);
font-size: var(--text-xs);
}
.btn-quiet {
color: var(--fg-muted);
}
.task-action-error {
max-width: 220px;
font-size: var(--text-xs);
white-space: normal;
}
.task-action-error-refused {
color: var(--warn);
}
.task-action-error-broken {
color: var(--danger);
}
.task-action-error-session {
color: var(--warn);
display: inline-flex;
align-items: center;
gap: var(--sp-1);
flex-wrap: wrap;
}
.task-decision {
margin-bottom: var(--sp-4);
padding: var(--sp-3);
border-left: 3px solid var(--accent);
background: var(--surface);
}
.task-detail-actions {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-3);
margin-bottom: var(--sp-4);
padding-bottom: var(--sp-3);
border-bottom: 1px solid var(--hairline);
}
.task-decision-title {
color: var(--fg);
font-weight: 600;
}
.task-decision-plan {
margin-top: var(--sp-2);
color: var(--fg-muted);
white-space: pre-wrap;
}
.task-logs-section {
margin-top: var(--sp-4);
}
.task-logs-section .task-decision-title {
display: flex;
align-items: center;
justify-content: space-between;
}
.task-log-list {
max-height: 40vh;
overflow-y: auto;
font-family: var(--font-mono);
font-size: var(--text-xs);
border-top: 1px solid var(--border);
margin-top: var(--sp-2);
}
.task-log-loading,
.task-log-error {
padding: var(--sp-3) 0;
color: var(--fg-muted);
}
/* On phones the filter controls take their own row and full width instead of
crowding the card title. */
@media (max-width: 700px) {
.task-filters {
width: 100%;
}
.task-search {
width: 100%;
}
.task-filter {
flex: 1 1 100%;
}
/* The task table becomes stacked cards instead of forcing the action
column off-screen. It remains a semantic table for assistive technology;
only its visual layout changes. */
.table-scroll:has(.task-row) {
overflow: visible;
}
.table:has(.task-row),
.table:has(.task-row) tbody {
display: block;
}
.table-scroll > .table:has(.task-row) {
width: 100%;
min-width: 0;
}
.table:has(.task-row) thead {
display: none;
}
.task-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: var(--sp-2) var(--sp-4);
margin-bottom: var(--sp-3);
padding: var(--sp-3);
border: 1px solid var(--hairline);
border-radius: var(--radius-lg);
background: var(--surface-glass);
}
.task-row td {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-2);
padding: var(--sp-1) 0;
border: 0;
text-align: right;
}
.task-row td::before {
content: attr(data-label);
color: var(--fg-subtle);
font-size: var(--text-xs);
font-weight: 500;
text-align: left;
}
.task-row td:nth-child(3),
.task-row td:last-child {
grid-column: 1 / -1;
}
.task-row td:last-child {
align-items: flex-start;
}
.task-timeline-row,
.task-timeline-row td {
display: block;
width: 100%;
}
.task-timeline-row td {
margin: calc(var(--sp-2) * -1) 0 var(--sp-4);
border-radius: 0 0 var(--radius-lg) var(--radius-lg);
}
.task-detail-actions {
align-items: flex-start;
flex-direction: column;
}
}
@media (max-width: 480px) {
.task-row {
grid-template-columns: 1fr;
}
.task-row td:nth-child(3),
.task-row td:last-child {
grid-column: auto;
}
}
.task-timeline-row td {
background: var(--bg-raised);
padding: var(--sp-4);
}
.task-timeline-loading {
color: var(--fg-muted);
font-size: var(--text-sm);
}
.task-timeline-error {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: var(--sp-2);
}
.task-timeline-error .task-timeline-title {
font-weight: 500;
color: var(--fg);
}
.task-timeline {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: var(--sp-3);
}
.task-timeline-entry {
display: flex;
gap: var(--sp-3);
align-items: flex-start;
}
.task-timeline-dot {
width: 8px;
height: 8px;
margin-top: 5px;
flex: none;
border-radius: 50%;
background: var(--accent);
}
.task-timeline-kind {
font-size: var(--text-sm);
font-weight: 500;
color: var(--fg);
}
.task-timeline-detail {
font-size: var(--text-xs);
color: var(--fg-muted);
margin-top: 2px;
}
.task-timeline-when {
font-size: var(--text-xs);
color: var(--fg-subtle);
margin-top: 2px;
}
-601
View File
@@ -1,601 +0,0 @@
import { Fragment } from "preact";
import { useState, useEffect, useRef } from "preact/hooks";
import "./tasks.css";
import { api, classifyActionError } from "../base/api.jsx";
import { ago } from "../base/format.jsx";
import { Pill } from "../base/pill.jsx";
import { StatTile } from "../base/statTile.jsx";
import { taskRowA11y } from "./task-row.jsx";
import { initialTaskFilter, taskMatchesStatus } from "./task-filters.jsx";
import { describeTimelineEvent } from "./timeline-event.jsx";
import { TaskLogPanel, logCacheKey } from "./task-logs.jsx";
import { actionFor, statusIds, statusKind, statusLabel } from "../base/task-meta.jsx";
// The shell's global reduced-motion rule switches CSS transitions and
// animations, NOT the JS smooth scroll this page performs when it reveals a
// deep-linked row. The decision therefore has to be made here, in JavaScript,
// and is exported so it can be tested directly (jsdom implements neither
// matchMedia nor scrollIntoView).
export function prefersReducedMotion() {
return typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches === true;
}
export function revealBehavior() {
return prefersReducedMotion() ? "auto" : "smooth";
}
// renderActionError distinguishes a refused action ("you cannot do that" --
// bad input, a conflicting task state) from a broken one (5xx, network drop,
// timeout -- "try again or check the daemon"), and special-cases an expired
// session with a prompt to reload rather than either framing.
function renderActionError({ kind, message }) {
if (kind === "session-expired") {
return (
<span className="task-action-error task-action-error-session">
Your session has expired.{" "}
<button className="button btn btn-small" type="button" onClick={() => window.location.reload()}>
Reload to sign in
</button>
</span>
);
}
if (kind === "refused") {
return <span className="task-action-error task-action-error-refused">{message} — you can't do that.</span>;
}
return <span className="task-action-error task-action-error-broken">{message} — try again, or check the daemon.</span>;
}
function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
// The open log pane loads its own attempt's log whenever it is showing an
// attempt it has no cached entry for: a retry moves the pane to a new attempt,
// a forced reload drops its own entry, and a row can be reopened long after the
// click that first opened it. Loading only from that click is what would leave
// the pane sitting on "Loading…" with nothing fetching it.
function TaskLogSection({ taskId, attempt, state, onLoad, onRetry }) {
const load = useRef(onLoad);
load.current = onLoad;
useEffect(() => {
if (state === undefined) load.current();
}, [state]);
return <TaskLogPanel state={state} taskId={taskId} attempt={attempt} onRetry={onRetry} />;
}
function TasksApp({ query }) {
const [tasks, setTasks] = useState(null);
const [error, setError] = useState(null);
const [filterStatus, setFilterStatus] = useState(() => initialTaskFilter(query));
const [search, setSearch] = useState("");
const requestedTask = Number(query.get("task"));
const initialExpandedId = Number.isFinite(requestedTask) && requestedTask > 0 ? requestedTask : null;
const [expandedId, setExpandedId] = useState(initialExpandedId);
const [focusRequestedTask, setFocusRequestedTask] = useState(initialExpandedId !== null);
const [eventCache, setEventCache] = useState(new Map());
const [logCache, setLogCache] = useState(new Map());
const logRequests = useRef(new Set());
const [logsExpanded, setLogsExpanded] = useState(new Set());
const [actionErrors, setActionErrors] = useState(new Map());
const [actionsInFlight, setActionsInFlight] = useState(new Set());
const load = async () => {
try {
setError(null);
const res = await api.tasks();
setTasks(res);
if (expandedId && res.some(t => String(t.id) === String(expandedId))) {
if (!eventCache.has(expandedId)) {
loadTimeline(expandedId);
}
}
return res;
} catch (err) {
setError(String(err.message || err));
setTasks(null);
return null;
}
};
useEffect(() => {
load();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const loadTimeline = async (id) => {
try {
const events = await api.task(id);
setEventCache(prev => new Map(prev).set(id, events || []));
} catch {
setEventCache(prev => new Map(prev).set(id, null));
}
};
const loadTaskLogs = async (id, attempt, { force = false } = {}) => {
// The cache entry is identified by the task AND the attempt: a task alone
// cannot tell two runs apart, so a retry used to leave the previous
// attempt's log on screen under the new run. One request per key, unless a
// control explicitly asks for the read again.
const key = logCacheKey(id, attempt);
if (logRequests.current.has(key) && !force) return;
logRequests.current.add(key);
if (force) {
setLogCache(prev => {
const next = new Map(prev);
next.delete(key);
return next;
});
}
try {
const res = await api.taskLogs(id, { attempt: attempt || undefined, limit: 500 });
setLogCache(prev => new Map(prev).set(key, res));
} catch {
setLogCache(prev => new Map(prev).set(key, null));
}
};
// An operator action can change a task's timeline -- a retry begins a new
// attempt -- so the events cached for that task are dropped rather than served
// against the new state. The log cache needs no invalidation here: its key
// already carries the attempt, so the new run is a different entry and can
// never be answered by the ended attempt's log.
const invalidateTaskCaches = (id) => {
setEventCache(prev => {
const next = new Map(prev);
next.delete(id);
return next;
});
};
const performAction = async (id, action) => {
setActionErrors(prev => {
const next = new Map(prev);
next.delete(id);
return next;
});
setActionsInFlight(prev => new Set(prev).add(id));
try {
await api.taskAction(id, action);
setActionsInFlight(prev => {
const next = new Set(prev);
next.delete(id);
return next;
});
if (action === "archive") setExpandedId(null);
invalidateTaskCaches(id);
const res = await load();
// A row that is still open reloads against the attempt the task now has;
// otherwise it would sit on "Loading…" with its cache entry gone.
const updated = Array.isArray(res) ? res.find(t => String(t.id) === String(id)) : null;
if (updated && expandedId === id) {
loadTimeline(id);
}
} catch (err) {
setActionsInFlight(prev => {
const next = new Set(prev);
next.delete(id);
return next;
});
setActionErrors(prev => new Map(prev).set(id, classifyActionError(err)));
}
};
useEffect(() => {
if (focusRequestedTask && expandedId && tasks) {
setFocusRequestedTask(false);
// requestAnimationFrame to ensure it has rendered
requestAnimationFrame(() => {
const row = document.getElementById(`task-row-${expandedId}`);
if (row) {
row.focus({ preventScroll: true });
// Optional call: focusing a deep-linked row is a nicety, and not every
// environment implements scrollIntoView on an element.
row.scrollIntoView?.({ block: "center", behavior: revealBehavior() });
}
});
}
}, [focusRequestedTask, expandedId, tasks]);
const toggleTask = (id, event) => {
if (event) event.stopPropagation();
const isExpanding = expandedId !== id;
setExpandedId(isExpanding ? id : null);
if (isExpanding) {
loadTimeline(id);
}
};
const toggleLogs = (id) => {
setLogsExpanded(prev => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
const renderSummary = () => {
if (!tasks) return null;
const total = tasks.length;
const counts = {};
for (const t of tasks) counts[t.status] = (counts[t.status] || 0) + 1;
const working = counts.running || 0;
const needsYou = (counts.waiting_human || 0) + (counts.parked || 0);
const delivered = (counts.merged || 0) + (counts.pr_open || 0);
return (
<div className="grid grid-4 task-summary">
<StatTile
label="Total tasks"
value={total}
compare={total ? "Everything archied has ever picked up" : "No tasks yet"}
/>
<StatTile
label="Working now"
value={working}
compare={total ? `${working} of ${total} in progress` : "Nothing running"}
/>
<StatTile
label="Needs you"
value={needsYou}
compare={needsYou ? "Parked or awaiting a reply" : "Nothing is blocked"}
goodDirection="down"
/>
<StatTile
label="Delivered"
value={delivered}
compare={total ? `${Math.round((delivered / total) * 100)}% of all tasks` : "No tasks yet"}
/>
</div>
);
};
const renderTaskActions = (t) => {
const actionError = actionErrors.get(t.id);
const errorMsg = actionError ? renderActionError(actionError) : null;
const busy = actionsInFlight.has(t.id);
const variantToken = (kind) =>
kind === "quiet" ? "btn-quiet" : kind === "danger" ? "btn-danger" : "";
const controls = (t.actions || []).map(action => {
const meta = actionFor(action);
if (!meta) return null;
const title = t.title || "this task";
const confirmText = meta.confirm ? meta.confirm.replaceAll("{title}", title) : undefined;
const cls = ["button", "btn", "btn-small", variantToken(meta.kind)].filter(Boolean).join(" ");
if (meta.kind === "link") {
if (action === "open_pr") return taskLink(t, "pull_request", t.pr_number, meta.label);
if (action === "open_issue") return taskLink(t, "issue", t.issue_number, meta.label);
}
return (
<button
key={action}
className={cls}
type="button"
disabled={busy}
onClick={(e) => {
e.stopPropagation();
if (confirmText && !window.confirm(confirmText)) return;
performAction(t.id, action);
}}
>
{meta.label}
</button>
);
}).filter(Boolean);
if (!controls.length && !errorMsg) return "—";
return <div className="task-actions">{errorMsg}{controls}</div>;
};
const taskLink = (t, kind, number, label) => {
const href = kind === "issue" ? t.issue_url : t.pr_url;
if (!href || !number || (kind === "issue" && t.source === "chat")) {
return (
<button className="btn btn-small" type="button" disabled title={`${label} is unavailable`}>
{label}
</button>
);
}
return (
<a className="btn btn-small" href={href} target="_blank" rel="noreferrer" onClick={e => e.stopPropagation()}>
{label}
</a>
);
};
const repoLink = (t) => {
const base = t.repo_url;
if (!base) return null;
return (
<a
className="task-source-link"
href={base}
target="_blank"
rel="noreferrer"
title={`Open ${t.owner}/${t.repo} on the forge`}
onClick={e => e.stopPropagation()}
>
{t.owner}/{t.repo}
</a>
);
};
const issueLink = (t) => {
const href = t.issue_url;
if (t.source === "chat" || !href || !t.issue_number) return null;
return (
<a
className="task-source-link"
href={href}
target="_blank"
rel="noreferrer"
title={`Open issue #${t.issue_number} on the forge`}
onClick={e => e.stopPropagation()}
>
#{t.issue_number}
</a>
);
};
const renderTimelineRow = (t) => {
const logKey = logCacheKey(t.id, t.attempt);
const cached = eventCache.get(t.id);
const logsExpandedForTask = logsExpanded.has(t.id);
return (
<tr className="task-timeline-row" id={`task-timeline-${t.id}`}>
<td colSpan={8}>
<div className="task-detail-actions">
<div className="task-decision-title">Available actions</div>
{renderTaskActions(t)}
</div>
{t.status === "waiting_human" && t.plan && (
<div className="task-decision">
<div className="task-decision-title">Decision required</div>
<div className="task-decision-plan">{t.plan}</div>
</div>
)}
{t.status === "parked" && t.park_reason && (
<div className="task-decision">
<div className="task-decision-title">Park reason</div>
<div className="task-decision-plan">{t.park_reason}</div>
</div>
)}
{cached === undefined ? (
<div className="task-timeline-loading">Loading timeline…</div>
) : cached === null ? (
<div className="task-timeline-error">
<div className="task-timeline-title">Could not load timeline</div>
<div className="task-timeline-detail">archied did not answer for this task's events. It may be restarting — retry, or check the daemon.</div>
<button className="btn" onClick={() => loadTimeline(t.id)}>Retry</button>
</div>
) : cached.length ? (
<ul className="task-timeline">
{cached.map((ev, i) => {
const desc = describeTimelineEvent(ev);
return (
<li className="task-timeline-entry" key={i}>
<span className="task-timeline-dot"></span>
<div>
<div className="task-timeline-kind">{desc.title}</div>
{desc.detail && <div className="task-timeline-detail">{desc.detail}</div>}
<div className="task-timeline-when">{ago(ev.at)}</div>
</div>
</li>
);
})}
</ul>
) : (
<Empty title="No events yet" detail="This task has not recorded any transitions." />
)}
<div className="task-logs-section">
<div className="task-decision-title">
Attempt log
<button className="btn btn-small" onClick={() => toggleLogs(t.id)} style={{ marginLeft: "10px" }}>
{logsExpandedForTask ? "Hide" : "Show"}
</button>
</div>
{logsExpandedForTask && (
<TaskLogSection
taskId={t.id}
attempt={t.attempt}
state={logCache.has(logKey) ? logCache.get(logKey) : undefined}
onLoad={() => loadTaskLogs(t.id, t.attempt)}
onRetry={() => loadTaskLogs(t.id, t.attempt, { force: true })}
/>
)}
</div>
</td>
</tr>
);
};
const renderBody = () => {
if (error) {
return (
<tr>
<td colSpan={8}>
<Empty title="Cannot reach archied" detail={error} />
</td>
</tr>
);
}
if (!tasks) {
return (
<tr>
<td colSpan={8}>
<div className="task-timeline-loading">Loading tasks...</div>
</td>
</tr>
);
}
if (!tasks.length) {
return (
<tr>
<td colSpan={8}>
<Empty title="No tasks yet" detail="Tasks appear here once archied picks up an issue to work." />
</td>
</tr>
);
}
const filtered = tasks.filter(t => {
if (!taskMatchesStatus(t, filterStatus)) return false;
if (!search) return true;
const hay = `${t.title} ${t.repo}`.toLowerCase();
return hay.includes(search);
});
if (!filtered.length) {
return (
<tr>
<td colSpan={8}>
<Empty title="No matching tasks" detail="Try a different search or status filter." />
</td>
</tr>
);
}
return filtered.map(t => {
const expanded = expandedId === t.id;
const timelineID = `task-timeline-${t.id}`;
return (
<Fragment key={t.id}>
<tr
className="task-row"
id={`task-row-${t.id}`}
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
toggleTask(t.id, e);
}
}}
onClick={(e) => toggleTask(t.id, e)}
{...taskRowA11y(t, expanded)}
>
<td className="mono" data-label="Repository">
<button
className="task-expand"
type="button"
aria-expanded={String(expanded)}
aria-controls={timelineID}
aria-label={`${expanded ? "Collapse" : "Expand"} timeline for ${t.title || "untitled task"}`}
onClick={(e) => toggleTask(t.id, e)}
>
{expanded ? "−" : "+"}
</button>
{repoLink(t) ?? `${t.owner}/${t.repo}`}
</td>
<td className="mono" data-label="Issue">
{issueLink(t) ?? `#${t.issue_number}`}
</td>
<td className="strong" data-label="Title">
<a
className="task-detail-link"
href={`#/tasks/${t.id}`}
title="Open the run detail for this task"
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => e.stopPropagation()}
>
{t.title || "(untitled)"}
</a>
</td>
<td data-label="Status">
<Pill text={statusLabel(t.status)} kind={statusKind(t.status)} />
</td>
<td data-label="Workflow">{t.workflow || "—"}</td>
<td data-label="Stage">{t.stage || "—"}</td>
<td
data-label="Last activity"
title={t.created_at ? `Created ${ago(t.created_at)}` : ""}
>
{ago(t.updated_at)}
</td>
<td data-label="Actions">{renderTaskActions(t)}</td>
</tr>
{expanded && renderTimelineRow(t)}
</Fragment>
);
});
};
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Tasks</h1>
<p className="page-sub">Every issue archied has picked up, and where it stands.</p>
</div>
<div className="page-actions">
<button className="btn" onClick={load}>Refresh</button>
</div>
</div>
{error ? (
<div className="grid grid-4 task-summary">
<div className="card">
<Empty title="Cannot reach archied" detail={error} />
</div>
</div>
) : (
renderSummary()
)}
<div className="card">
<div className="card-head">
<div>
<h2 className="card-title">All tasks</h2>
<p className="card-sub">Click a row for its timeline</p>
</div>
<div className="task-filters">
<input
className="task-search"
type="search"
placeholder="Search by title or repo…"
value={search}
onInput={e => setSearch(e.target.value.trim().toLowerCase())}
/>
<select
className="task-filter"
value={filterStatus}
onChange={e => setFilterStatus(e.target.value)}
>
<option value="">All statuses</option>
<option value="needs_you">Needs you</option>
{statusIds().map(value => (
<option key={value} value={value}>{statusLabel(value)}</option>
))}
</select>
</div>
</div>
<div className="table-scroll">
<table className="table">
<thead>
<tr>
{["Repo", "Issue", "Title", "Status", "Workflow", "Stage", "Last activity", "Action"].map(hText => (
<th key={hText}>{hText}</th>
))}
</tr>
</thead>
<tbody>{renderBody()}</tbody>
</table>
</div>
</div>
</div>
);
}
export function tasksPage(query) {
return <TasksApp query={query} />;
}
-101
View File
@@ -1,101 +0,0 @@
function words(value) {
return String(value || "event")
.replaceAll("_", " ")
.replace(/\b\w/g, (letter) => letter.toUpperCase());
}
// Exported so the stage rail renders a duration exactly the way the timeline
// does; a second formatter would eventually disagree with this one.
export function duration(milliseconds) {
const ms = Number(milliseconds);
if (!Number.isFinite(ms) || ms < 0) return "";
if (ms < 1000) return `${Math.round(ms)} ms`;
const seconds = ms / 1000;
// Under 60s: 1 dp when seconds < 10, 0 dp otherwise (40.6 s, but 41 s).
if (seconds < 60) return `${seconds.toFixed(seconds < 10 ? 1 : 0)} s`;
const roundedSeconds = Math.round(seconds);
const minutes = Math.floor(roundedSeconds / 60);
const remSec = roundedSeconds % 60;
if (minutes < 60) return remSec === 0 ? `${minutes} min` : `${minutes} min ${remSec} s`;
const hours = Math.floor(minutes / 60);
const remMin = minutes - hours * 60;
return remMin === 0 ? `${hours} h` : `${hours} h ${remMin} min`;
}
function count(value) {
const n = Number(value);
// Render only for positive counts; zero is treated as "no metric
// reported" so a partially-populated agent_finish (pre-v0.1.24 events,
// or a failed run whose result is the zero Result) does not appear as
// "0 prompt · 0 completion · 0 cached".
if (!Number.isFinite(n) || n <= 0) return "";
return n.toLocaleString("en-US");
}
export function describeTimelineEvent(ev = {}) {
const data = ev.data || {};
const stage = ev.stage || "unknown stage";
const workflow = ev.workflow ? `${ev.workflow} workflow` : "";
if (ev.kind === "stage_start") {
return { title: `Started stage: ${stage}`, detail: workflow };
}
if (ev.kind === "stage_finish") {
const elapsed = duration(data.duration_ms);
const context = [workflow, elapsed && `ran for ${elapsed}`].filter(Boolean).join(" · ");
return {
title: data.interrupted ? `Stage interrupted: ${stage}` : data.error ? `Stage failed: ${stage}` : `Finished stage: ${stage}`,
detail: [context, data.error].filter(Boolean).join(" — "),
};
}
if (ev.kind === "task_retried") {
const count = Number(data.retry_count);
const attempt = Number.isFinite(count) && count > 0 ? `Retry ${count}` : "Retry requested";
const previous = [data.previous_stage && `after ${data.previous_stage}`, data.previous_reason]
.filter(Boolean)
.join(": ");
return { title: attempt, detail: previous || ev.detail || "" };
}
if (ev.kind === "agent_finish") {
const iterations = count(data.iterations);
const total = count(data.tokens);
const cachedRaw = Number(data.cached_tokens) || 0;
// data.prompt_tokens INCLUDES cache hits -- showing it next to "cached"
// reads as two separate charges when it's really one figure containing
// the other. Show the fresh (full-price) remainder instead, so a
// heavily-cached run doesn't look ~10x more expensive than it was billed.
const fresh = count((Number(data.prompt_tokens) || 0) - cachedRaw);
const completion = count(data.completion_tokens);
const cached = count(data.cached_tokens);
const usage = [
iterations && `${iterations} iterations`,
total && `${total} tokens`,
fresh && `${fresh} fresh prompt`,
completion && `${completion} completion`,
cached && `${cached} cached`,
data.model,
].filter(Boolean);
return {
title: `Agent ${data.status || "finished"}: ${stage}`,
detail: usage.join(" · ") || ev.detail || "",
};
}
// Condition (d): the two provenance kinds render as one human line. The
// captured payload is rendered by its own panel, never dumped into the
// timeline, so these cases name what was recorded and nothing more.
if (ev.kind === "config_captured") {
return {
title: "Configuration captured",
detail: "The effective task-runtime configuration for this run.",
};
}
if (ev.kind === "changes_captured") {
const fileCount = Number(data.totals?.files);
const files = Number.isFinite(fileCount) && fileCount > 0 ? `${fileCount} file${fileCount === 1 ? "" : "s"} changed` : "";
const after = data.captured_after ? `captured after ${data.captured_after}` : "";
return { title: "Change capture recorded", detail: [files, after].filter(Boolean).join(" · ") };
}
return { title: words(ev.kind || ev.type), detail: ev.detail || "" };
}
+15
View File
@@ -0,0 +1,15 @@
<script setup lang="ts">
import { useRoute } from "vue-router";
// Every route resolves here until its view is ported. Named so an unported
// page is obvious in the running app rather than rendering blank -- the
// failure mode the Preact /chat route had.
const route = useRoute();
</script>
<template>
<section class="p-8">
<h1 class="text-2xl font-semibold tracking-tight">{{ route.path }}</h1>
<p class="text-muted-foreground mt-2 text-sm">Not yet ported to Vue.</p>
</section>
</template>
-36
View File
@@ -1,36 +0,0 @@
// Merging workflow definitions with their run statistics.
//
// The rows used to come from the definition list alone, so a workflow that had
// run but was no longer in that list (or a definitions fetch that came back
// empty while the stats fetch succeeded) produced no rows at all. The page then
// showed "No workflow runs yet" directly above the stage tables listing those
// very runs (archie-core-rcbf).
//
// A run is evidence the workflow exists. Anything with either a definition or
// statistics gets a row.
/**
* workflowRows returns one row per known workflow, definitions first and in
* their declared order, then any workflow seen only in the statistics.
*/
export function workflowRows(workflows, definitions) {
const stats = new Map((workflows || []).map((w) => [w.workflow, w]));
const rows = [];
const claimed = new Set();
for (const definition of definitions || []) {
claimed.add(definition.id);
rows.push({
...definition,
...(stats.get(definition.id) || { workflow: definition.id, runs: 0, merged: 0 }),
});
}
for (const workflow of workflows || []) {
if (claimed.has(workflow.workflow)) continue;
// No definition to describe it, so the id is the only name it has.
rows.push({ id: workflow.workflow, name: workflow.workflow, ...workflow });
}
return rows;
}
-87
View File
@@ -1,87 +0,0 @@
/* Workflows-only styles. */
.wf-stage-card {
margin-top: var(--sp-4);
}
.wf-rate {
font-size: var(--text-sm);
color: var(--fg);
display: flex;
align-items: baseline;
gap: var(--sp-2);
}
.wf-rate-sub {
font-size: var(--text-xs);
color: var(--fg-subtle);
}
.wf-bar {
height: 5px;
border-radius: var(--radius-pill);
background: var(--border);
overflow: hidden;
margin-top: var(--sp-2);
width: 140px;
}
.wf-bar-fill {
height: 100%;
border-radius: var(--radius-pill);
transition: width var(--transition);
}
.wf-bar-ok {
background: var(--ok);
}
.wf-bar-warn {
background: var(--warn);
}
.wf-bar-danger {
background: var(--danger);
}
.wf-bar-info {
background: var(--info);
}
/* Stacked form for "Start work". This was .cfg-rows, a class owned by the
Configuration page, so restyling Configuration could silently restyle
this form. Named for what it is and owned by this feature instead. */
.wf-form {
display: flex;
flex-direction: column;
gap: var(--sp-2);
}
.wf-form input,
.wf-form select,
.wf-form textarea {
font: inherit;
font-size: var(--text-sm);
color: var(--fg);
background: var(--surface);
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
padding: var(--sp-2);
width: 100%;
}
.wf-form textarea {
resize: vertical;
}
.wf-form input:focus,
.wf-form select:focus,
.wf-form textarea:focus {
outline: 2px solid var(--accent);
outline-offset: -1px;
}
.wf-form input::placeholder,
.wf-form textarea::placeholder {
color: var(--fg-subtle);
}
-313
View File
@@ -1,313 +0,0 @@
import { h, Fragment } from "preact";
import { useState, useEffect } from "preact/hooks";
import "./workflows.css";
import { api } from "../base/api.jsx";
import { workflowRows } from "./workflow-rows.js";
const WORKFLOW_LABELS = {
bootstrap: "Bootstrap",
implement: "Implement",
tdd: "TDD",
feasibility: "Feasibility check",
};
function workflowLabel(name) {
if (WORKFLOW_LABELS[name]) return WORKFLOW_LABELS[name];
if (!name) return "Unknown";
return name.charAt(0).toUpperCase() + name.slice(1).replace(/_/g, " ");
}
function pct(part, whole) {
if (!whole) return 0;
return Math.round((part / whole) * 100);
}
function formatMs(ms) {
if (!ms) return "—";
if (ms < 1000) return `${ms} ms`;
const secs = ms / 1000;
if (secs < 60) return `${secs.toFixed(1)} s`;
return `${(secs / 60).toFixed(1)} min`;
}
function Empty({ title, detail }) {
return (
<div class="empty">
<div class="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
function Bar({ fraction, kind = "ok" }) {
const boundedFraction = Math.min(100, Math.max(0, fraction));
return (
<div class="wf-bar">
<div class={`wf-bar-fill wf-bar-${kind}`} style={{ width: `${boundedFraction}%` }}></div>
</div>
);
}
export function workflowsPage(query) {
return <WorkflowsApp query={query} />;
}
function WorkflowsApp() {
const [definitions, setDefinitions] = useState([]);
const [workflows, setWorkflows] = useState([]);
const [stages, setStages] = useState([]);
const [error, setError] = useState(null);
const load = async () => {
try {
const data = await api.workflows();
setDefinitions(data?.definitions || []);
setWorkflows(data?.workflows || []);
setStages(data?.stages || []);
setError(null);
} catch (err) {
setError(String(err.message || err));
}
};
useEffect(() => {
load();
}, []);
return (
<div>
<div class="page-head">
<div>
<h1 class="page-title">Workflows</h1>
<p class="page-sub">Run outcomes and spend per workflow, and where stages get stuck.</p>
</div>
<div class="page-actions">
<button class="btn" onClick={load}>Refresh</button>
</div>
</div>
<StartWork definitions={definitions} />
{error ? (
<div class="card">
<Empty title="Cannot reach archied" detail={error} />
</div>
) : (
<Fragment>
<Workflows workflows={workflows} definitions={definitions} />
<Stages stages={stages} />
</Fragment>
)}
</div>
);
}
function StartWork({ definitions }) {
if (!definitions.length) return null;
const defaultWorkflow = definitions.filter((d) => d.enabled)[0]?.id || "";
const [identity, setIdentity] = useState("");
const [repository, setRepository] = useState("");
const [workflow, setWorkflow] = useState(defaultWorkflow);
const [title, setTitle] = useState("");
const [instructions, setInstructions] = useState("");
const [submitting, setSubmitting] = useState(false);
const [notice, setNotice] = useState("");
useEffect(() => {
if (!workflow && defaultWorkflow) {
setWorkflow(defaultWorkflow);
}
}, [defaultWorkflow, workflow]);
const onSubmit = async (e) => {
e.preventDefault();
setSubmitting(true);
setNotice("");
try {
const result = await api.workRequest({ identity, repository, workflow, title, instructions });
setNotice(`Queued task #${result.task_id}.`);
setIdentity("");
setRepository("");
setWorkflow(defaultWorkflow);
setTitle("");
setInstructions("");
} catch (err) {
setNotice(String(err.message || err));
} finally {
setSubmitting(false);
}
};
return (
<div class="card">
<div class="card-head">
<div>
<h2 class="card-title">Start work</h2>
<p class="card-sub">This enters Archie’s normal admitted task queue.</p>
</div>
</div>
<form class="wf-form" onSubmit={onSubmit}>
<input placeholder="Identity" required value={identity} onInput={(e) => setIdentity(e.target.value)} />
<input placeholder="owner/repository" required value={repository} onInput={(e) => setRepository(e.target.value)} />
<select required value={workflow} onInput={(e) => setWorkflow(e.target.value)}>
{definitions.filter((d) => d.enabled).map((d) => (
<option key={d.id} value={d.id}>{workflowLabel(d.name || d.id)}</option>
))}
</select>
<input placeholder="Short task title" required value={title} onInput={(e) => setTitle(e.target.value)} />
<textarea placeholder="Instructions for the work" required rows={3} value={instructions} onInput={(e) => setInstructions(e.target.value)}></textarea>
<button class="btn" type="submit" disabled={submitting}>Start work</button>
{notice && <p class="card-sub">{notice}</p>}
</form>
</div>
);
}
function Workflows({ workflows, definitions }) {
const rows = workflowRows(workflows, definitions);
if (!rows.length) {
return (
<div class="card">
<div class="card-head">
<div><h2 class="card-title">Per workflow</h2></div>
</div>
<Empty title="No workflow runs yet" detail="Stats appear here once a task has run through a workflow." />
</div>
);
}
return (
<div class="card">
<div class="card-head">
<div>
<h2 class="card-title">Per workflow</h2>
<p class="card-sub">Success rate is merged tasks over all runs</p>
</div>
</div>
<div class="table-scroll">
<table class="table">
<thead>
<tr>
<th>Workflow</th>
<th>Origin</th>
<th>Runs</th>
<th>Success rate</th>
<th>Avg tokens</th>
<th>Avg steps</th>
</tr>
</thead>
<tbody>
{rows.map((w) => {
const rate = pct(w.merged, w.runs);
return (
<tr key={w.workflow}>
<td class="strong">{workflowLabel(w.workflow)}</td>
<td class="mono">{w.origin || "registry"}</td>
<td>{`${w.runs} run${w.runs === 1 ? "" : "s"}`}</td>
<td>
<div class="wf-rate">
{rate}%<span class="wf-rate-sub">{w.merged} of {w.runs} merged</span>
</div>
<Bar fraction={rate} kind={rate >= 50 ? "ok" : "warn"} />
</td>
<td class="mono">{w.avg_tokens ? w.avg_tokens.toLocaleString() : "—"}</td>
<td class="mono">{w.avg_steps ? w.avg_steps.toFixed(1) : "—"}</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
);
}
function Stages({ stages }) {
if (!stages.length) {
return (
<div class="card wf-stage-card">
<div class="card-head">
<div><h2 class="card-title">Per stage</h2></div>
</div>
<Empty title="No stage data yet" detail="Stage timing and failures appear here once workflows have run." />
</div>
);
}
const maxMs = Math.max(...stages.map((s) => s.avg_ms || 0), 1);
const byDuration = [...stages].sort((a, b) => (b.avg_ms || 0) - (a.avg_ms || 0));
const byErrors = [...stages].filter((s) => s.errors > 0).sort((a, b) => b.errors - a.errors);
return (
<div class="grid grid-2 wf-stage-card">
<div class="card">
<div class="card-head">
<div>
<h2 class="card-title">Slowest stages</h2>
<p class="card-sub">Average duration, this workflow's stages</p>
</div>
</div>
<div class="table-scroll">
<table class="table">
<thead>
<tr>
<th>Workflow</th>
<th>Stage</th>
<th>Runs</th>
<th>Avg duration</th>
</tr>
</thead>
<tbody>
{byDuration.map((s, idx) => (
<tr key={idx}>
<td>{workflowLabel(s.workflow)}</td>
<td class="strong">{s.stage}</td>
<td>{s.runs}</td>
<td>
<div class="wf-rate">{formatMs(s.avg_ms)}</div>
<Bar fraction={pct(s.avg_ms, maxMs)} kind="info" />
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
<div class="card">
<div class="card-head">
<div>
<h2 class="card-title">Most failures</h2>
<p class="card-sub">Stages that error out, over their runs</p>
</div>
</div>
{byErrors.length ? (
<div class="table-scroll">
<table class="table">
<thead>
<tr>
<th>Workflow</th>
<th>Stage</th>
<th>Failures</th>
</tr>
</thead>
<tbody>
{byErrors.map((s, idx) => (
<tr key={idx}>
<td>{workflowLabel(s.workflow)}</td>
<td class="strong">{s.stage}</td>
<td>
<div class="wf-rate">{s.errors} of {s.runs}</div>
<Bar fraction={pct(s.errors, s.runs)} kind="danger" />
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<Empty title="No failures recorded" detail="Every stage has completed cleanly so far." />
)}
</div>
</div>
);
}