fix(ui,gateway): load the served lifecycle vocabulary, and make the page registry match the routes (#890)

* fix(ui): make the served lifecycle vocabulary actually load

base/task-meta.jsx documents the backend as the source of truth: /api/task-meta
returns the statuses (label, pill severity, "needs you") and the operator
actions, and loadTaskMeta() replaces the freeze-dried defaults with that
catalog. Nothing called it. Every pill, status filter and action control read
the snapshot, so a catalogue change on the server never reached the browser --
the module's first paragraph was simply not true.

main.jsx now asks for the catalog once at boot, alongside the capabilities read
it already does for the same reason: the shell paints immediately and upgrades a
moment later.

The two vocabularies the dashboard mirrors rather than serves -- FILE_STATUS
(ids owned by internal/domain/workflow/task/changes.go) and CONFIG_SCHEMA
(events.ConfigCapturedSchema) -- are now documented as the deliberate second
tier, with their two-sided pins named, so the tree stops telling two stories
about where a vocabulary comes from. Both degrade to a raw id or the verbatim
payload rather than rendering something wrong, which is why mirroring is
tolerable there and not for a presentation catalog.

RED before (loader never called):

    x booting the dashboard replaces the freeze-dried vocabulary with the served catalog
      actual: 'custom_status', expected: 'Custom status'

Also repairs a drifted LAW asset. A fresh build of pristine main dirties both
ui/dist/assets/index.css and index.js: 10e7d030 (#889, memory unification slice
5) changed ui/src without rebuilding ui/dist, and task check runs task ui --
which repairs dist instead of verifying it -- so a stale dist is invisible to
the gate. Rebuilding here restores the invariant; a dist-freshness gate is filed
as follow-up.

* fix(ui,gateway): restore the search focus the port dropped, and the page registry truth

An adversarial review of the port (b5e9831d) found three things worth acting on.

1. Topbar search -- a regression the port introduced. The el() version focused
   the input when the narrow-layout toggle opened it, and blurred it after a
   successful jump; the port kept neither. That layout hides the field with
   width:0/pointer-events:none until .is-open or :focus-within, so without
   focus() the caret was not in the field the operator had just opened, and
   without blur() :focus-within left it expanded across the topbar after the
   jump. Both calls are back, with the ref they need.

2. dashboard_tools.go advertised a page that does not exist and omitted two that
   do. The registry calls itself "the single source of truth for what the
   dashboard exposes", but it is a hand-copy of the route table in
   ui/src/main.jsx: /memory stayed after the page was deleted (that deletion
   also left ui/dist stale -- archie-core-1vhh), and /bindings and /curators
   were never added. So the agent could hand the operator a chip to a route that
   now falls back to the dashboard, and could not answer "where do I go for
   playbook bindings?".

3. TestDashboardPagesRegistryCoversEveryRoute did not test that. It asserted
   three hardcoded paths and passed while the registry listed a deleted page. It
   now reads the route table back out of ui/src/main.jsx and compares in both
   directions, which is what makes the registry's claim holdable. RED before:

     route "/bindings" is a dashboard page the registry does not list, so the agent cannot point at it
     route "/curators" is a dashboard page the registry does not list, so the agent cannot point at it
     registry lists "/memory" (Memory), which is not a dashboard route: the agent would send the operator somewhere that does not exist

Also deletes the dead .chat-page rules the deleted chatPage() bridge left
behind: nothing renders .chat-page any more (chat.jsx renders
.chat-page-content, and the drawer sizes it from layout.css).

Not changed: the unreachable `soon` path, which predates the port and was
reported rather than acted on.

* fix(build): verify ui/dist is fresh instead of never looking at it

ui/dist is committed because the Go build embeds it, so it is a generated
source file. Nothing in the gate read it: task check does not run task ui, and
nothing else compares the bundle with ui/src. So when 10e7d030 (#889) changed
ui/src without rebuilding, the committed bundle went on serving the Memory page
whose source had been deleted -- with the gate green throughout.

task ui:check (tools/uidist.sh) rebuilds into a temporary directory and compares,
never rewriting the committed artifact. That is the rule docs:check already
states for the contract reference -- a gate that silently rewrote the artifact
would bless an unintended change with no reviewer ever seeing it -- and it
matters more now that several agents work in their own worktrees, where each
could otherwise pass while producing a different bundle.

Evidence:
  fresh tree                            exit 0, matches
  hand-staled bundle                    exit 1, names the differing file
  the #889 drift replayed               exit 1, names BOTH index.css and index.js
  (pre-#889 bundle, post-#889 sources)
  git status after a run                unchanged: the check never writes ui/dist

Cost: ui:check declares ui:deps like ui and test:ui do, so the gate runs npm
install once per dependent. Task's sources/generates up-to-date check does not
apply to a node_modules directory (measured: it ran on every invocation), so the
target does not claim otherwise; guarding that is follow-up work.

Gate: task check exit 0, UI suite 230/230, all Go packages ok.

* fix(ui): make the served vocabulary reach an already-painted page

Greptile's finding on the first cut of this fix, and it was right: loadTaskMeta()
resolves after a page has painted and only mutated module state. The route tree
renders into its own root, so App re-rendering cannot reach it, and a painted
page kept the freeze-dried labels it read on the way up.

show() is split so the page render can be repeated on its own: renderRoute()
mounts the current route into the outlet without the teardown/chrome side
effects, and the catalog effect calls it once the catalog lands. The key is
unchanged, so Preact re-renders the mounted page in place and keeps its state.

Deeper instance of the same defect, found while fixing that one:
task-filters.jsx captured the vocabulary in module-level constants at import
(ATTENTION_STATUSES/TASK_STATUSES), so the task filter could never see a served
status, no matter when or how correctly the catalog landed. Both are read at
call time now.

Tests, and what they actually cover:
  - the task-filter test has teeth: with the source fix stashed it fails, with
    the fix it passes.
  - task-meta-late-catalog.test.js guards the boot fetch end to end (it fails
    when loadTaskMeta is never called), but it does NOT isolate the re-render:
    a page also re-renders for its own reasons, so the assertion holds without
    renderRoute too. Said plainly here rather than implied as coverage -- the
    fix makes the re-render deterministic instead of incidental, and this
    harness cannot tell those apart.
  - it lives in its own file because main.jsx boots once per process; a second
    test in the same file would assert against a detached tree.

UI suite 232/232, task check exit 0.
This commit is contained in:
sam authored and GitHub committed 2026-09-19 23:38:19 +10:00
1 parent c29cdf6f79
commit 2d3e4e59ad
14 files changed
+356 -37

No files matched your search

+31 -1
View File
@@ -176,6 +176,31 @@ tasks:
cmds:
- npm run build
ui:check:
desc: Rebuild the dashboard into a temporary directory and reject a stale ui/dist
summary: |
ui/dist is committed because the Go build embeds it, so it is a generated
source file. Nothing else in the gate reads it and `task ui` rewrites it
in place, so before this a change to ui/src that landed without the
rebuilt bundle was invisible -- and two agents in two worktrees could each
"pass" while producing different dashboards.
Builds somewhere temporary and compares, never rewriting the committed
artifact, which is the rule docs:check already follows for the contract
reference. A gate that rebuilt ui/dist in place would bless an unintended
UI change with no reviewer ever seeing it.
Fix a failure with `task ui`, then commit the rebuilt bundle in the same
commit as the source change that caused it.
Declares ui:deps like `ui` and `test:ui` do, so a fresh clone works; that
means the gate runs `npm install` once for each dependent. Task's
sources/generates up-to-date check does not apply to a node_modules
directory, so the guard against that is a follow-up, not a claim here.
deps: [ui:deps]
cmds:
- bash tools/uidist.sh check
test:ui:
desc: Run the dashboard's node tests (DOM-building primitives)
dir: ui
@@ -330,7 +355,7 @@ tasks:
- go -C tools test -mod=readonly ./... -count=1
check:
desc: "Full quality gate: fmt, go fix, proto, docs, vet, lint, build, test, tools tests, ui tests"
desc: "Full quality gate: fmt, go fix, proto, docs, vet, lint, build, test, tools tests, ui tests and bundle"
cmds:
- task: fmt
- go fix ./...
@@ -348,6 +373,11 @@ tasks:
# The dashboard's suite runs here too. Left out of the gate it rots
# silently: nothing else executes it, so a broken DOM primitive ships.
- task: test:ui
# ...and so is the bundle that suite is built from. ui/dist is committed
# and embedded; nothing else checks it against ui/src, and `task ui`
# rewrites it in place, so a forgotten rebuild used to leave no trace in
# the gate at all.
- task: ui:check
contract:
desc: "Report contract conformance: declared surfaces, their consumers, and the drift between them"
+2 -1
View File
@@ -33,9 +33,10 @@ var dashboardPages = []DashboardPage{
{Path: "/logs", Label: "Logs", Description: "The daemon log stream, filterable by level and component."},
{Path: "/captures", Label: "Event inspector", Description: "Captured inbound events for inspection."},
{Path: "/mappings", Label: "Field mappings", Description: "How inbound event fields map onto internal ones."},
{Path: "/bindings", Label: "Playbook bindings", Description: "How captured events are bound to the workflows they start."},
{Path: "/skills", Label: "Skills", Description: "The SKILL.md capabilities Archie can activate."},
{Path: "/workflows", Label: "Workflows", Description: "The routed workflows (bootstrap, implement, tdd, feasibility) and their run history."},
{Path: "/memory", Label: "Memory", Description: "What Archie carries between conversations and the tools that read it."},
{Path: "/curators", Label: "Curators", Description: "The scheduled passes that curate Archie's memory and captures."},
{Path: "/channels", Label: "Channels", Description: "Inbound chat and notification channels (e.g. Telegram) and their state."},
{Path: "/settings", Label: "Configuration", Description: "Daemon configuration editable from the dashboard."},
}
+61 -5
View File
@@ -2,6 +2,10 @@ package gateway
import (
"context"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
)
@@ -9,6 +13,51 @@ import (
// the signature, so a background context is safe and deterministic.
func quietContext() context.Context { return context.Background() }
// routePathRe matches one route entry's path in the dashboard's route table.
var routePathRe = regexp.MustCompile(`path:\s*"([^"]+)"`)
// dashboardRoutesFromSource reads the dashboard's route table out of the UI
// source.
//
// The page registry is what the agent is told the dashboard exposes, and it is
// a hand-copy of that table. Hand-copies drift: /memory stayed in the registry
// after the page was deleted, and /bindings and /curators were never added --
// so the agent offered the operator a route that no longer existed and was
// blind to two that did. Reading the table back is what turns the registry's
// "single source of truth" claim into something a test can hold.
func dashboardRoutesFromSource(t *testing.T) []string {
t.Helper()
path := filepath.Join("..", "..", "ui", "src", "main.jsx")
src, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
block := string(src)
start := strings.Index(block, "const routes = [")
if start < 0 {
t.Fatalf("%s: no routes table", path)
}
block = block[start:]
if end := strings.Index(block, "\n];"); end >= 0 {
block = block[:end]
}
// One route per line. A detail route (nav: false) is addressed by URL but is
// not a navigation entry, so the registry does not carry it.
var paths []string
for line := range strings.SplitSeq(block, "\n") {
match := routePathRe.FindStringSubmatch(line)
if match == nil || strings.Contains(line, "nav: false") {
continue
}
paths = append(paths, match[1])
}
if len(paths) == 0 {
t.Fatalf("%s: parsed no routes", path)
}
return paths
}
func TestDashboardPagesRegistryCoversEveryRoute(t *testing.T) {
pages := DashboardPages()
if len(pages) == 0 {
@@ -24,11 +73,18 @@ func TestDashboardPagesRegistryCoversEveryRoute(t *testing.T) {
}
seen[p.Path] = true
}
// The dashboard's primary surfaces must be present so the agent can point
// the operator at the control room and the work queue.
for _, want := range []string{"/", "/tasks", "/logs"} {
if !seen[want] {
t.Errorf("page index does not cover %q", want)
routes := dashboardRoutesFromSource(t)
inDashboard := map[string]bool{}
for _, route := range routes {
inDashboard[route] = true
if !seen[route] {
t.Errorf("route %q is a dashboard page the registry does not list, so the agent cannot point at it", route)
}
}
for _, p := range pages {
if !inDashboard[p.Path] {
t.Errorf("registry lists %q (%s), which is not a dashboard route: the agent would send the operator somewhere that does not exist", p.Path, p.Label)
}
}
}
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
# Verify the committed dashboard bundle matches a fresh build of ui/src.
#
# ui/dist is committed because the Go build embeds it, so it is a generated
# source file: a change to ui/src that lands without the rebuilt bundle ships a
# dashboard no reviewer ever saw. Rebuilding it in place here would bless
# exactly that, silently -- and with more than one agent working in its own
# worktree, each could "pass" while producing a different bundle.
#
# So this builds somewhere temporary and compares, the rule docs:check already
# follows for docs/data/generated/contracts.json. A mismatch means ui/src
# changed without `task ui`, or the bundle was hand-edited; the fix is the same
# either way.
set -euo pipefail
cd "$(dirname "$0")/.."
case "${1:-check}" in
check) ;;
*)
echo 'usage: bash tools/uidist.sh check' >&2
exit 2
;;
esac
out="$(mktemp -d)"
trap 'rm -rf "$out"' EXIT
# The comparison only means something if the build is deterministic, so a
# failure here is staleness rather than toolchain noise. It is: vite is
# configured to emit fixed asset names (no content hashes), and rebuilding an
# unchanged tree produces byte-identical output.
if ! build_log="$(cd ui && npm run build --silent -- --outDir "$out" --emptyOutDir 2>&1)"; then
echo "$build_log" >&2
echo 'the dashboard does not build; fix that before checking freshness' >&2
exit 1
fi
if ! differences="$(diff -rq ui/dist "$out" 2>&1)"; then
cat >&2 <<EOF
ui/dist does not match a fresh build of ui/src:
$differences
Run \`task ui\` and commit the rebuilt bundle in the same commit as the change
that caused it. The Go build embeds ui/dist, so a stale bundle ships a
dashboard nobody reviewed.
EOF
exit 1
fi
echo 'ui/dist matches a fresh build of ui/src'
+1 -1
View File
@@ -1 +1 @@
:root{--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:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.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:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#5d6878;--accent:#4c8dff;--accent-fg:#fff;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#8c99ab;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.visually-hidden{clip-path:inset(50%);white-space:nowrap;border:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}body{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);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);align-items:center;gap:2px;margin:0 auto;padding:3px;display:flex}.nav-item{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);display:inline-flex}.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}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{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);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.mobile-search-toggle{display:none}.icon-btn{border-radius:var(--radius-pill);border:1px solid var(--hairline);background:var(--surface-glass-strong);width:32px;height:32px;color:var(--fg-muted);cursor:pointer;transition:color var(--transition), background var(--transition);place-items:center;display:grid}.Line truncated
:root{--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:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.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:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#5d6878;--accent:#4c8dff;--accent-fg:#fff;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#8c99ab;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.visually-hidden{clip-path:inset(50%);white-space:nowrap;border:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}body{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);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);align-items:center;gap:2px;margin:0 auto;padding:3px;display:flex}.nav-item{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);display:inline-flex}.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}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{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);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.mobile-search-toggle{display:none}.icon-btn{border-radius:var(--radius-pill);border:1px solid var(--hairline);background:var(--surface-glass-strong);width:32px;height:32px;color:var(--fg-muted);cursor:pointer;transition:color var(--transition), background var(--transition);place-items:center;display:grid}.Line truncated
+6 -6
View File
@@ -1,9 +1,9 @@
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e,t,n,r,i,a,o,s,c,l,u,d,f,p,m={},h=[],g=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_=Array.isArray;function v(e,t){for(var n in t)e[n]=t[n];return e}function y(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function b(t,n,r){var i,a,o,s={};for(o in n)o==`key`?i=n[o]:o==`ref`?a=n[o]:s[o]=n[o];if(arguments.length>2&&(s.children=arguments.length>3?e.call(arguments,2):r),typeof t==`function`&&t.defaultProps!=null)for(o in t.defaultProps)s[o]===void 0&&(s[o]=t.defaultProps[o]);return x(t,s,i,a,null)}function x(e,r,i,a,o){var s={type:e,props:r,key:i,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++n,__i:-1,__u:0};return o==null&&t.vnode!=null&&t.vnode(s),s}function S(e){return e.children}function C(e,t){this.props=e,this.context=t}function w(e,t){if(t==null)return e.__?w(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type==`function`?w(e):null}function T(e){if(e.__P&&e.__d){var n=e.__v,r=n.__e,i=[],a=[],o=v({},n);o.__v=n.__v+1,t.vnode&&t.vnode(o),I(e.__P,o,n,e.__n,e.__P.namespaceURI,32&n.__u?[r]:null,i,r??w(n),!!(32&n.__u),a),o.__v=n.__v,o.__.__k[o.__i]=o,ee(i,o,a),n.__e=n.__=null,o.__e!=r&&E(o)}}function E(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),E(e)}function D(e){(!e.__d&&(e.__d=!0)&&r.push(e)&&!O.__r++||i!=t.debounceRendering)&&((i=t.debounceRendering)||a)(O)}function O(){try{for(var e,t=1;r.length;)r.length>t&&r.sort(o),e=r.shift(),t=r.length,T(e)}finally{r.length=O.__r=0}}function k(e,t,n,r,i,a,o,s,c,l,u){var d,f,p,g,_,v,y=r&&r.__k||h,b=t.length;for(c=A(n,t,y,c,b),d=0;d<b;d++)(p=n.__k[d])!=null&&(f=p.__i!=-1&&y[p.__i]||m,p.__i=d,v=I(e,p,f,i,a,o,s,c,l,u),g=p.__e,p.ref&&f.ref!=p.ref&&(f.ref&&te(f.ref,null,p),u.push(p.ref,p.__c||g,p)),_==null&&g!=null&&(_=g),4&p.__u?(c=j(p,c,e),f.__e&&(f.__e=null)):typeof p.type==`function`&&v!==void 0?c=v:g&&(c=g.nextSibling),p.__u&=-7);return n.__e=_,c}function A(e,t,n,r,i){var a,o,s,c,l,u=n.length,d=u,f=0;for(e.__k=Array(i),a=0;a<i;a++)(o=t[a])!=null&&typeof o!=`boolean`&&typeof o!=`function`?(typeof o==`string`||typeof o==`number`||typeof o==`bigint`||o.constructor==String?o=e.__k[a]=x(null,o,null,null,null):_(o)?o=e.__k[a]=x(S,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=e.__k[a]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[a]=o,c=a+f,o.__=e,o.__b=e.__b+1,s=null,(l=o.__i=M(o,n,c,d))!=-1&&(d--,(s=n[l])&&(s.__u|=2)),s==null||s.__v==null?(l==-1&&(i>u?f--:i<u&&f++),typeof o.type!=`function`&&(o.__u|=4)):l!=c&&(l==c-1?f--:l==c+1?f++:(l>c?f--:f++,o.__u|=4))):e.__k[a]=null;if(d)for(a=0;a<u;a++)(s=n[a])!=null&&!(2&s.__u)&&(s.__e==r&&(r=w(s)),B(s,s));return r}function j(e,t,n){var r,i;if(typeof e.type==`function`){for(r=e.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=e,t=j(r[i],t,n));return t}e.__e!=t&&(t&&e.type&&!t.parentNode&&(t=w(e)),t=n.insertBefore(e.__e,t||null));do t&&=t.nextSibling;while(t!=null&&t.nodeType==8);return t}function M(e,t,n,r){var i,a,o,s=e.key,c=e.type,l=t[n],u=l!=null&&!(2&l.__u);if(l===null&&s==null||u&&s==l.key&&c==l.type)return n;if(r>+!!u){for(i=n-1,a=n+1;i>=0||a<t.length;)if((l=t[o=i>=0?i--:a++])!=null&&!(2&l.__u)&&s==l.key&&c==l.type)return o}return-1}function N(e,t,n){t[0]==`-`?e.setProperty(t,n??``):e[t]=n==null?``:typeof n!=`number`||g.test(t)?n:n+`px`}function P(e,t,n,r,i){var a,o;n:if(t==`style`)if(typeof n==`string`)e.style.cssText=n;else{if(typeof r==`string`&&(e.style.cssText=r=``),r)for(t in r)n&&t in n||N(e.style,t,``);if(n)for(t in n)r&&n[t]==r[t]||N(e.style,t,n[t])}else if(t[0]==`o`&&t[1]==`n`)a=t!=(t=t.replace(u,`$1`)),o=t.toLowerCase(),t=o in e||t==`onFocusOut`||t==`onFocusIn`?o.slice(2):t.slice(2),e.l||={},e.l[t+a]=n,n?r?n[l]=r[l]:(n[l]=d,e.addEventListener(t,a?p:f,a)):e.removeEventListener(t,a?p:f,a);else{if(i==`http://www.w3.org/2000/svg`)t=t.replace(/xlink(H|:h)/,`h`).replace(/sName$/,`s`);else if(t!=`width`&&t!=`height`&&t!=`href`&&t!=`list`&&t!=`form`&&t!=`tabIndex`&&t!=`download`&&t!=`rowSpan`&&t!=`colSpan`&&t!=`role`&&t!=`popover`&&t in e)try{e[t]=n??``;break n}catch{}typeof n==`function`||(n==null||!1===n&&t[4]!=`-`?e.removeAttribute(t):e.setAttribute(t,t==`popover`&&n==1?``:n))}}function F(e){return function(n){if(this.l){var r=thiLine truncated
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Oe=class extends Error{constructor(e,t){super(e),this.status=t}};function ke(e){let t=e instanceof Oe?e.status:void 0,n=e?.message||`Action failed`;return t===401?{kind:`session-expired`,message:n}:t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Ae(e,t){let n=await fetch(e,t);if(!n.ok)throw new Oe(await De(n),n.status);return n}async function J(e,{method:t=`GET`,body:n,timeoutMs:r=Te,parse:i=!0}={}){let a={Accept:`application/json`},o={method:t,headers:a,signal:AbortSignal.timeout(r)};t!==`GET`&&(a[`Content-Type`]=`application/json`,a[`X-Archie-CSRF`]=`1`),n!==void 0&&(o.body=JSON.stringify(n));let s=await Ae(e,o);return i?s.json():void 0}var Y={summary:()=>J(`/api/summary`),tasks:()=>J(`/api/tasks`),taskMeta:()=>J(`/api/task-meta`),task:e=>J(`/api/tasks/${e}`),taskAttempts:e=>J(`/api/tasks/${e}/attempts`),taskChanges:(e,t)=>J(`/api/tasks/${e}/changes`+Ee(t)),taskDebug:(e,t)=>J(`/api/tasks/${e}/debug`+Ee(t)),taskAction:(e,t)=>J(`/api/tasks/${e}/action`,{method:`POST`,body:{action:t}}),setup:()=>J(`/api/setup`),capabilities:()=>J(`/api/capabilities`),workflows:()=>J(`/api/workflows`),workRequest:e=>J(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>J(`/api/skills`),channels:()=>J(`/api/channels`),curators:()=>J(`/api/curators`),channelReload:e=>J(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>J(`/api/config`),version:()=>J(`/api/version`),configUpdate:e=>J(`/api/config`,{method:`PATCH`,body:{updates:e}}),configRepoUpdate:(e,t,n,r)=>J(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,body:{field:n,value:r}}),configReset:e=>J(`/api/config/reset`,{method:`POST`,body:{key:e}}),logs:e=>J(`/api/logs`+Ee(e)),taskLogs:(e,t)=>J(`/api/tasks/${e}/logs`+Ee(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${e}/logs/download`+(t==null?``:`?attempt=${t}`),captures:e=>J(`/api/captures`+Ee({limit:e})),mappings:()=>J(`/api/mappings`),mappingCreate:e=>J(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>J(`/api/mappings/${e}`,{method:`PATCH`,body:t}),mappingDelete:e=>J(`/api/mappings/${e}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>J(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>J(`/api/bindings`),bindingCreate:e=>J(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>J(`/api/bindings/${e}`,{method:`PATCH`,body:t}),bindingDelete:e=>J(`/api/bindings/${e}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>J(`/api/bindings/${e}/approve`,{method:`POST`}),memory:()=>J(`/api/memory`),chatSessions:()=>J(`/api/chat/sessions`),chatMessages:e=>J(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>J(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>J(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>J(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:we(),text:t,page:location.hash.slice(1)||`/`}}),chatPersona:(e,t)=>J(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatUpdate:()=>J(`/api/chat/update`),chatUpdateDefer:e=>J(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),chatUpdateInstall:e=>J(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:12e4}),chatDangerous:()=>J(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>J(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>J(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,{signal:t}={})=>Ae(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t})};function je(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function Me(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function Ne(e,t){return e?t.filter(t=>t.section&&e[t.section]===!1).map(e=>e.path):[]}var Pe=0;Array.isArray;function X(e,n,r,i,a,o){n||={};var s,c,l=n;if(`ref`in l)for(c in l={},n)c==`ref`?s=n[c]:l[c]=n[c];var u={type:e,props:l,key:r,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Pe,__i:-1,__u:0,__source:a,__self:o};if(typeof e==`function`&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return t.vnode&&t.vnode(u),u}var Fe={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:`Line truncated
`),children:[X(`td`,{className:`strong`,children:e.label||e.id}),X(`td`,{className:`mono`,children:e.install_type||`—`}),X(`td`,{className:`mono`,children:e.running_version||`—`}),X(`td`,{className:`mono`,children:e.latest_available||`—`}),X(`td`,{children:X(Q,{text:Jn[e.status]||e.status,kind:Yn[e.status]||`idle`})})]},e.id||e.label))})]})})})}function $({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Zn({title:e,sub:t,children:n}){return X(`div`,{className:`card cfg-section`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:e}),X(`p`,{className:`card-sub`,children:t})]})}),n]})}function Qn({origins:e}){return e?.length?X(Zn,{title:`Configuration sources`,sub:`Applied from top to bottom; later entries take precedence over earlier ones.`,children:X(`div`,{className:`kv-list`,children:e.map((e,t)=>X(Wn,{label:`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,value:e.path},t))})}):X(Zn,{title:`Configuration sources`,sub:`The files that supplied the running configuration.`,children:X($,{title:`Source provenance is unavailable.`})})}function $n(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function er({data:e,error:t}){if(t)return X(Zn,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships.`,children:X($,{title:`Lifecycle unavailable`,detail:t})});let n=e?.statuses||[],r=e?.actions||[];return X(Zn,{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.`,children:[X(`h3`,{className:`cfg-subhead`,children:`Statuses`}),n.length?X(`div`,{className:`kv-list`,children:n.map(e=>{let t=e.label??We(e.id),n=e.kind??Ge(e.id);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(Q,{text:t,kind:n})})]},e.id)})}):X($,{title:`No statuses reported`,detail:`The server did not return any lifecycle statuses.`}),X(`h3`,{className:`cfg-subhead`,children:`Actions`}),r.length?X(`div`,{className:`kv-list`,children:r.map(e=>{let t=e.label??e.id,n=$n(e.kind);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(`button`,{className:`btn btn-small ${n}`,type:`button`,disabled:!0,children:t})})]},e.id)})}):X($,{title:`No actions reported`,detail:`The server did not return any operator actions.`})]})}function tr({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=W(!1),[o,s]=W(null),[c,l]=W(!!e[t]);return r?X(`td`,{children:[X(`input`,{className:`repo-field-checkbox`,type:`checkbox`,checked:c,onChange:async r=>{let i=r.target.checked;l(i),a(!0),s(null);try{await Y.configRepoUpdate(e.owner,e.name,t,i),n?.()}catch(e){l(!i),s(String(e.message||e))}finally{a(!1)}},disabled:i}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{children:c?`yes`:`no`})}function nr({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=W(String(e[t]??0)),[o,s]=W(null),[c,l]=W(!1);return r?X(`td`,{children:[X(`input`,{className:`kv-input`,type:`text`,value:i,onChange:e=>a(e.target.value),onBlur:async()=>{let r=parseInt(i,10);if(Number.isNaN(r)){s(`Enter a whole number`);return}l(!0),s(null);try{await Y.configRepoUpdate(e.owner,e.name,t,r),n?.()}catch(e){s(String(e.message||e))}finally{l(!1)}},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),e.target.blur())},disabled:c}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{className:`mono`,children:i})}function rr({repos:e,onSaved:t,editable:n=!0}){if(!e?.length)return X(Zn,{title:`Repositories`,sub:`The repositories Archie polls for work.`,children:X($,{title:`No repositories configured`,detail:`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`})});let r=e=>e?.length?e.map(e=>e.join(` `)).join(` → `):`—`;return X(Zn,{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.`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Repository`}),X(`th`,{children:`Base branch`}),X(`th`,{children:`Ecosystem`}),X(`th`,{children:`Quality gate`}),X(`th`,{children:`Protected paths`}),X(`th`,{children:`Concurrent`}),X(`th`,{children:`Max retries`}),X(`th`,{children:`Self-review`})]})}),X(`tbody`,{children:e.map((e,i)=>X(`tr`,{children:[X(`td`,{className:`strong`,children:[e.owner,`/`,e.name]}),X(`td`,{className:`mono`,children:e.base}),X(`td`,{children:e.ecosystem||`go`}),X(`td`,{className:`mono`,children:r(e.gate)}),X(`td`,{className:`mono`,children:e.protect?.length?e.protect.join(`, `):`—`}),X(tr,{r:e,field:`alloLine truncated
`),i=[],a=null,o=null,s=0,c=()=>{i.length&&(n.push(X(`p`,{children:Wr(i.join(` `))},s++)),i=[])},l=()=>{if(!a)return;let e=a.items.map((e,t)=>X(`li`,{children:Wr(e)},t));n.push(a.tag===`ol`?X(`ol`,{children:e},s++):X(`ul`,{children:e},s++)),a=null};for(let e=0;e<r.length;e++){let t=r[e];if(t.startsWith("```")){c(),l(),o?(n.push(X(`pre`,{children:X(`code`,{children:o.join(`
`)})},s++)),o=null):o=[];continue}if(o){o.push(t);continue}let u=Kr(t),d=e+1<r.length?Kr(r[e+1]):null;if(u&&d&&qr(d)&&u.length===d.length){c(),l();let t=[];for(e+=2;e<r.length;e++){let n=Kr(r[e]);if(!n||n.length!==u.length){e--;break}t.push(n)}n.push(X(`table`,{children:[X(`thead`,{children:X(`tr`,{children:u.map((e,t)=>X(`th`,{children:Wr(e)},t))})}),X(`tbody`,{children:t.map((e,t)=>X(`tr`,{children:e.map((e,t)=>X(`td`,{children:Wr(e)},t))},t))})]},s++));continue}if(!t.trim()){c(),l();continue}let f=t.match(/^(#{1,3})\s+(.+)$/);if(f){c(),l();let e=`h${f[1].length}`;n.push(X(e,{children:Wr(f[2])},s++));continue}let p=t.match(/^\s*[-*]\s+(.+)$/),m=t.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){c();let e=m?`ol`:`ul`;(!a||a.tag!==e)&&(l(),a={tag:e,items:[]}),a.items.push((p||m)[1]);continue}if(t.startsWith(`>`)){c(),l(),n.push(X(`blockquote`,{children:Wr(t.replace(/^>\s?/,``))},s++));continue}i.push(t)}return c(),l(),o&&n.push(X(`pre`,{children:X(`code`,{children:o.join(`
`)})},s++)),X(`div`,{className:t,children:n})}function Kr(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function qr(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var Jr=`archie.web.chat.channel`;function Yr(){let e=localStorage.getItem(Jr);return e||(e=we(),localStorage.setItem(Jr,e)),e}function Xr(e){return{text:e,sourceID:we()}}function Zr(e){return{...e}}function Qr(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?Zr(e.turn):Xr(r),isRetry:n}}function $r(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function ei(e){return e?.status===501?null:`Could not check for updates.`}function ti(){return location.hash.slice(1)||`/`}function ni(){let[e,t]=W([]),[n,r]=W(``),[i,a]=W([]),[o,s]=W(``),[c,l]=W(`Ready`),[u,d]=W(!1),[f,p]=W({}),[m,h]=W(``),[g,_]=W(``),[v,y]=W(``),[b,x]=W([]),[C,w]=W([]),[T,E]=W(0),[D,O]=W(!1),[k,A]=W(null),[j,M]=W(null),[N,P]=W(null),[F,I]=W(``),[L,ee]=W(``),[R,z]=W(null),te=K(null),B=K(null),V=K(null),ne=K(null),re=K(null),H=K(u);H.current=u,G(()=>{te.current&&(te.current.scrollTop=te.current.scrollHeight)},[i,R]),G(()=>{le().catch(e=>{l(e.message||`Chat unavailable`)}),ie();let e=()=>{V.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),V.current?.abort()}},[]);async function ie(){try{let e=await Y.chatUpdate();M(e?.snapshot||null),A(e)}catch(e){let t=ei(e);A(t?{error:t}:null)}}async function ae(){if(j)try{await Y.chatUpdateDefer(j),A({snapshot:{deferred:!0},available:[]}),l(`Update deferred`)}catch(e){l(e.message||`Could not defer update`)}}async function oe(){if(j)try{l(`Installing…`);let e=await Y.chatUpdateInstall(j);M(null),A({snapshot:{},available:[]}),l(e?.result?.restart_requested?`Update installed; restart queued`:`Update complete`)}catch(e){l(e.message||`Update install failed`)}}async function se(){try{let e=await Y.chatDangerous();P(e)}catch(e){P({error:e.message||`Dangerous actions unavailable`})}}async function U(e,t){if(t)try{await Y.chatDangerousRequest(e,t),l(`Approval requested`),await se()}catch(e){l(e.message||`Could not request action`)}}async function ce(e,t){try{await Y.chatDangerousDecision(e,t),l(t===`deny`?`Action denied`:`Action approved`),await se()}catch(e){l(e.message||`Approval failed`)}}async function le(){let e=await Y.chatSessions(),r=e.sessions||[];t(r),p(e),h(e.active_persona||``);let i=e.providers||[],a=e.active_provider||i[0]||``;_(a),y(e.active_model||``);let o=(e.commands||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e);x(o),e.dangerous_available&&await se(),!n&&r[0]&&await ue(r[0].session_id,e,r)}async function ue(e,t,n){let i=t||f;r(e),a([]),z(null);let o=i.active_personas?.[e]||i.active_persona||``;h(o);try{await Y.chatMessage(Yr(),`/resume ${e}`);let[t,n]=await Promise.all([Y.chatMessages(e),Y.chatTurns(e)]),r=new Map;for(let e of n||[]){let t=e.assistant_message_id||e.AssistantMessageID;t&&r.set(t,e)}let i=(t||[]).map(e=>{let t=e.message_id||e.MessageID,n=r.get(t);return n?{...e,tool_calls:n.tool_calls||n.ToolCalls||[]}:e});a(i)}catch(e){l(e.message||`Could not load session messages`)}}async function de(e){if(n)try{l(`Working…`);let t=await Y.chatMessage(Yr(),e);t.session_id&&r(t.session_id),l(t.reply||`Session updated`),await le(),(t.session_id||n)&&await ue(t.session_id||n),ne.current&&(ne.current.open=!1)}catch(e){l(e.message||`Session action failed`)}}function fe(e,t){let n=window.prompt(t);n?.trim()&&de(`${e} ${n.trim()}`)}function pe(e){let t=e.target.value;h(t),!(!n||!t)&&Y.chatPersona(n,t).then(()=>{p(e=>({...e,active_personas:{...e.active_personas||{},[n]:t}})),l(`Personality: ${t}`)}).catch(e=>{l(e.message||`Failed to set personality`)})}async function me(e){let t=e.target.value;if(_(t),t)try{let e=await Y.chatMessage(Yr(),`/model --provider ${t}`);l(e.reply||`Provider updated`),await le()}catch(e){l(`Provider update failed: ${e.message||e}`)}}async function he(e){let t=e.target.value;if(y(t),t)try{let e=await Y.chatMessage(Yr(),`/model ${t}`);l(e.reply||`Model updated`),await le()}catch(e){l(`Model update failed: ${e.message||e}`)}}function ge(){window.confirm(`Reload the Telegram chat adapter?`)&&(s(`/restart`),q({textOverride:`/restart`}))}function _e(){s(`/new`),q({textOverride:`/new`})}function ve(e){let t=e.target.value;s(t);let n=t.slice(0,e.target.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);if(n){let e=n[1].toLowerCase(),t=b.filter(t=>`${t.command} ${t.description}`.toLowerCase().includes(e)).slice(0,8);if(t.length){w(t),E(0),O(!0);return}}O(!1),w([])}function ye(e){let t=C[e];if(!t||!B.current)return;let n=B.current,r=n.value.slice(0,n.selectionStart),i=n.value.slice(n.selectionStart),a=r.search(/(?:^|\s)\/[^\s]*$/),o=a<0?r.length:a+ +(r[a]===` `),c=`${r.slice(0,o)}${t.command} ${i}`;s(c),O(!1);let l=o+t Line truncated
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Oe=class extends Error{constructor(e,t){super(e),this.status=t}};function ke(e){let t=e instanceof Oe?e.status:void 0,n=e?.message||`Action failed`;return t===401?{kind:`session-expired`,message:n}:t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Ae(e,t){let n=await fetch(e,t);if(!n.ok)throw new Oe(await De(n),n.status);return n}async function J(e,{method:t=`GET`,body:n,timeoutMs:r=Te,parse:i=!0}={}){let a={Accept:`application/json`},o={method:t,headers:a,signal:AbortSignal.timeout(r)};t!==`GET`&&(a[`Content-Type`]=`application/json`,a[`X-Archie-CSRF`]=`1`),n!==void 0&&(o.body=JSON.stringify(n));let s=await Ae(e,o);return i?s.json():void 0}var Y={summary:()=>J(`/api/summary`),tasks:()=>J(`/api/tasks`),taskMeta:()=>J(`/api/task-meta`),task:e=>J(`/api/tasks/${e}`),taskAttempts:e=>J(`/api/tasks/${e}/attempts`),taskChanges:(e,t)=>J(`/api/tasks/${e}/changes`+Ee(t)),taskDebug:(e,t)=>J(`/api/tasks/${e}/debug`+Ee(t)),taskAction:(e,t)=>J(`/api/tasks/${e}/action`,{method:`POST`,body:{action:t}}),setup:()=>J(`/api/setup`),capabilities:()=>J(`/api/capabilities`),workflows:()=>J(`/api/workflows`),workRequest:e=>J(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>J(`/api/skills`),channels:()=>J(`/api/channels`),curators:()=>J(`/api/curators`),channelReload:e=>J(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>J(`/api/config`),version:()=>J(`/api/version`),configUpdate:e=>J(`/api/config`,{method:`PATCH`,body:{updates:e}}),configRepoUpdate:(e,t,n,r)=>J(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,body:{field:n,value:r}}),configReset:e=>J(`/api/config/reset`,{method:`POST`,body:{key:e}}),logs:e=>J(`/api/logs`+Ee(e)),taskLogs:(e,t)=>J(`/api/tasks/${e}/logs`+Ee(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${e}/logs/download`+(t==null?``:`?attempt=${t}`),captures:e=>J(`/api/captures`+Ee({limit:e})),mappings:()=>J(`/api/mappings`),mappingCreate:e=>J(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>J(`/api/mappings/${e}`,{method:`PATCH`,body:t}),mappingDelete:e=>J(`/api/mappings/${e}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>J(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>J(`/api/bindings`),bindingCreate:e=>J(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>J(`/api/bindings/${e}`,{method:`PATCH`,body:t}),bindingDelete:e=>J(`/api/bindings/${e}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>J(`/api/bindings/${e}/approve`,{method:`POST`}),chatSessions:()=>J(`/api/chat/sessions`),chatMessages:e=>J(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>J(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>J(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>J(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:we(),text:t,page:location.hash.slice(1)||`/`}}),chatPersona:(e,t)=>J(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatUpdate:()=>J(`/api/chat/update`),chatUpdateDefer:e=>J(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),chatUpdateInstall:e=>J(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:12e4}),chatDangerous:()=>J(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>J(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>J(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,{signal:t}={})=>Ae(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t})};function je(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function Me(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function Ne(e,t){return e?t.filter(t=>t.section&&e[t.section]===!1).map(e=>e.path):[]}var Pe=[{id:`queued`,label:`Queued`,kind:`idle`},{id:`running`,label:`Working`,kind:`info`},{id:`waiting_human`,label:`Waiting for you`,kind:`warn`,needs_you:!0},{id:`pr_open`,label:`In review`,kind:`ok`},{id:`merged`,label:`Merged`,kind:`ok`},{id:`parked`,label:`Parked`,kind:`warn`,needs_you:!0},{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`}],Fe=[{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}"? ThiLine truncated
`),children:[X(`td`,{className:`strong`,children:e.label||e.id}),X(`td`,{className:`mono`,children:e.install_type||`—`}),X(`td`,{className:`mono`,children:e.running_version||`—`}),X(`td`,{className:`mono`,children:e.latest_available||`—`}),X(`td`,{children:X(Q,{text:Yn[e.status]||e.status,kind:Xn[e.status]||`idle`})})]},e.id||e.label))})]})})})}function $({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Qn({title:e,sub:t,children:n}){return X(`div`,{className:`card cfg-section`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:e}),X(`p`,{className:`card-sub`,children:t})]})}),n]})}function $n({origins:e}){return e?.length?X(Qn,{title:`Configuration sources`,sub:`Applied from top to bottom; later entries take precedence over earlier ones.`,children:X(`div`,{className:`kv-list`,children:e.map((e,t)=>X(Gn,{label:`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,value:e.path},t))})}):X(Qn,{title:`Configuration sources`,sub:`The files that supplied the running configuration.`,children:X($,{title:`Source provenance is unavailable.`})})}function er(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function tr({data:e,error:t}){if(t)return X(Qn,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships.`,children:X($,{title:`Lifecycle unavailable`,detail:t})});let n=e?.statuses||[],r=e?.actions||[];return X(Qn,{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.`,children:[X(`h3`,{className:`cfg-subhead`,children:`Statuses`}),n.length?X(`div`,{className:`kv-list`,children:n.map(e=>{let t=e.label??He(e.id),n=e.kind??Ue(e.id);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(Q,{text:t,kind:n})})]},e.id)})}):X($,{title:`No statuses reported`,detail:`The server did not return any lifecycle statuses.`}),X(`h3`,{className:`cfg-subhead`,children:`Actions`}),r.length?X(`div`,{className:`kv-list`,children:r.map(e=>{let t=e.label??e.id,n=er(e.kind);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(`button`,{className:`btn btn-small ${n}`,type:`button`,disabled:!0,children:t})})]},e.id)})}):X($,{title:`No actions reported`,detail:`The server did not return any operator actions.`})]})}function nr({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=W(!1),[o,s]=W(null),[c,l]=W(!!e[t]);return r?X(`td`,{children:[X(`input`,{className:`repo-field-checkbox`,type:`checkbox`,checked:c,onChange:async r=>{let i=r.target.checked;l(i),a(!0),s(null);try{await Y.configRepoUpdate(e.owner,e.name,t,i),n?.()}catch(e){l(!i),s(String(e.message||e))}finally{a(!1)}},disabled:i}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{children:c?`yes`:`no`})}function rr({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=W(String(e[t]??0)),[o,s]=W(null),[c,l]=W(!1);return r?X(`td`,{children:[X(`input`,{className:`kv-input`,type:`text`,value:i,onChange:e=>a(e.target.value),onBlur:async()=>{let r=parseInt(i,10);if(Number.isNaN(r)){s(`Enter a whole number`);return}l(!0),s(null);try{await Y.configRepoUpdate(e.owner,e.name,t,r),n?.()}catch(e){s(String(e.message||e))}finally{l(!1)}},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),e.target.blur())},disabled:c}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{className:`mono`,children:i})}function ir({repos:e,onSaved:t,editable:n=!0}){if(!e?.length)return X(Qn,{title:`Repositories`,sub:`The repositories Archie polls for work.`,children:X($,{title:`No repositories configured`,detail:`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`})});let r=e=>e?.length?e.map(e=>e.join(` `)).join(` → `):`—`;return X(Qn,{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.`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Repository`}),X(`th`,{children:`Base branch`}),X(`th`,{children:`Ecosystem`}),X(`th`,{children:`Quality gate`}),X(`th`,{children:`Protected paths`}),X(`th`,{children:`Concurrent`}),X(`th`,{children:`Max retries`}),X(`th`,{children:`Self-review`})]})}),X(`tbody`,{children:e.map((e,i)=>X(`tr`,{children:[X(`td`,{className:`strong`,children:[e.owner,`/`,e.name]}),X(`td`,{className:`mono`,children:e.base}),X(`td`,{children:e.ecosystem||`go`}),X(`td`,{className:`mono`,children:r(e.gate)}),X(`td`,{className:`mono`,children:e.protect?.length?e.protect.join(`, `):`—`}),X(nr,{r:e,field:`alloLine truncated
`),i=[],a=null,o=null,s=0,c=()=>{i.length&&(n.push(X(`p`,{children:Br(i.join(` `))},s++)),i=[])},l=()=>{if(!a)return;let e=a.items.map((e,t)=>X(`li`,{children:Br(e)},t));n.push(a.tag===`ol`?X(`ol`,{children:e},s++):X(`ul`,{children:e},s++)),a=null};for(let e=0;e<r.length;e++){let t=r[e];if(t.startsWith("```")){c(),l(),o?(n.push(X(`pre`,{children:X(`code`,{children:o.join(`
`)})},s++)),o=null):o=[];continue}if(o){o.push(t);continue}let u=Hr(t),d=e+1<r.length?Hr(r[e+1]):null;if(u&&d&&Ur(d)&&u.length===d.length){c(),l();let t=[];for(e+=2;e<r.length;e++){let n=Hr(r[e]);if(!n||n.length!==u.length){e--;break}t.push(n)}n.push(X(`table`,{children:[X(`thead`,{children:X(`tr`,{children:u.map((e,t)=>X(`th`,{children:Br(e)},t))})}),X(`tbody`,{children:t.map((e,t)=>X(`tr`,{children:e.map((e,t)=>X(`td`,{children:Br(e)},t))},t))})]},s++));continue}if(!t.trim()){c(),l();continue}let f=t.match(/^(#{1,3})\s+(.+)$/);if(f){c(),l();let e=`h${f[1].length}`;n.push(X(e,{children:Br(f[2])},s++));continue}let p=t.match(/^\s*[-*]\s+(.+)$/),m=t.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){c();let e=m?`ol`:`ul`;(!a||a.tag!==e)&&(l(),a={tag:e,items:[]}),a.items.push((p||m)[1]);continue}if(t.startsWith(`>`)){c(),l(),n.push(X(`blockquote`,{children:Br(t.replace(/^>\s?/,``))},s++));continue}i.push(t)}return c(),l(),o&&n.push(X(`pre`,{children:X(`code`,{children:o.join(`
`)})},s++)),X(`div`,{className:t,children:n})}function Hr(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function Ur(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var Wr=`archie.web.chat.channel`;function Gr(){let e=localStorage.getItem(Wr);return e||(e=we(),localStorage.setItem(Wr,e)),e}function Kr(e){return{text:e,sourceID:we()}}function qr(e){return{...e}}function Jr(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?qr(e.turn):Kr(r),isRetry:n}}function Yr(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function Xr(e){return e?.status===501?null:`Could not check for updates.`}function Zr(){return location.hash.slice(1)||`/`}function Qr(){let[e,t]=W([]),[n,r]=W(``),[i,a]=W([]),[o,s]=W(``),[c,l]=W(`Ready`),[u,d]=W(!1),[f,p]=W({}),[m,h]=W(``),[g,_]=W(``),[v,y]=W(``),[b,x]=W([]),[C,w]=W([]),[T,E]=W(0),[D,O]=W(!1),[k,A]=W(null),[j,M]=W(null),[N,P]=W(null),[F,I]=W(``),[L,ee]=W(``),[R,z]=W(null),te=K(null),B=K(null),V=K(null),ne=K(null),re=K(null),H=K(u);H.current=u,G(()=>{te.current&&(te.current.scrollTop=te.current.scrollHeight)},[i,R]),G(()=>{le().catch(e=>{l(e.message||`Chat unavailable`)}),ie();let e=()=>{V.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),V.current?.abort()}},[]);async function ie(){try{let e=await Y.chatUpdate();M(e?.snapshot||null),A(e)}catch(e){let t=Xr(e);A(t?{error:t}:null)}}async function ae(){if(j)try{await Y.chatUpdateDefer(j),A({snapshot:{deferred:!0},available:[]}),l(`Update deferred`)}catch(e){l(e.message||`Could not defer update`)}}async function oe(){if(j)try{l(`Installing…`);let e=await Y.chatUpdateInstall(j);M(null),A({snapshot:{},available:[]}),l(e?.result?.restart_requested?`Update installed; restart queued`:`Update complete`)}catch(e){l(e.message||`Update install failed`)}}async function se(){try{let e=await Y.chatDangerous();P(e)}catch(e){P({error:e.message||`Dangerous actions unavailable`})}}async function U(e,t){if(t)try{await Y.chatDangerousRequest(e,t),l(`Approval requested`),await se()}catch(e){l(e.message||`Could not request action`)}}async function ce(e,t){try{await Y.chatDangerousDecision(e,t),l(t===`deny`?`Action denied`:`Action approved`),await se()}catch(e){l(e.message||`Approval failed`)}}async function le(){let e=await Y.chatSessions(),r=e.sessions||[];t(r),p(e),h(e.active_persona||``);let i=e.providers||[],a=e.active_provider||i[0]||``;_(a),y(e.active_model||``);let o=(e.commands||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e);x(o),e.dangerous_available&&await se(),!n&&r[0]&&await ue(r[0].session_id,e,r)}async function ue(e,t,n){let i=t||f;r(e),a([]),z(null);let o=i.active_personas?.[e]||i.active_persona||``;h(o);try{await Y.chatMessage(Gr(),`/resume ${e}`);let[t,n]=await Promise.all([Y.chatMessages(e),Y.chatTurns(e)]),r=new Map;for(let e of n||[]){let t=e.assistant_message_id||e.AssistantMessageID;t&&r.set(t,e)}let i=(t||[]).map(e=>{let t=e.message_id||e.MessageID,n=r.get(t);return n?{...e,tool_calls:n.tool_calls||n.ToolCalls||[]}:e});a(i)}catch(e){l(e.message||`Could not load session messages`)}}async function de(e){if(n)try{l(`Working…`);let t=await Y.chatMessage(Gr(),e);t.session_id&&r(t.session_id),l(t.reply||`Session updated`),await le(),(t.session_id||n)&&await ue(t.session_id||n),ne.current&&(ne.current.open=!1)}catch(e){l(e.message||`Session action failed`)}}function fe(e,t){let n=window.prompt(t);n?.trim()&&de(`${e} ${n.trim()}`)}function pe(e){let t=e.target.value;h(t),!(!n||!t)&&Y.chatPersona(n,t).then(()=>{p(e=>({...e,active_personas:{...e.active_personas||{},[n]:t}})),l(`Personality: ${t}`)}).catch(e=>{l(e.message||`Failed to set personality`)})}async function me(e){let t=e.target.value;if(_(t),t)try{let e=await Y.chatMessage(Gr(),`/model --provider ${t}`);l(e.reply||`Provider updated`),await le()}catch(e){l(`Provider update failed: ${e.message||e}`)}}async function he(e){let t=e.target.value;if(y(t),t)try{let e=await Y.chatMessage(Gr(),`/model ${t}`);l(e.reply||`Model updated`),await le()}catch(e){l(`Model update failed: ${e.message||e}`)}}function ge(){window.confirm(`Reload the Telegram chat adapter?`)&&(s(`/restart`),q({textOverride:`/restart`}))}function _e(){s(`/new`),q({textOverride:`/new`})}function ve(e){let t=e.target.value;s(t);let n=t.slice(0,e.target.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);if(n){let e=n[1].toLowerCase(),t=b.filter(t=>`${t.command} ${t.description}`.toLowerCase().includes(e)).slice(0,8);if(t.length){w(t),E(0),O(!0);return}}O(!1),w([])}function ye(e){let t=C[e];if(!t||!B.current)return;let n=B.current,r=n.value.slice(0,n.selectionStart),i=n.value.slice(n.selectionStart),a=r.search(/(?:^|\s)\/[^\s]*$/),o=a<0?r.length:a+ +(r[a]===` `),c=`${r.slice(0,o)}${t.command} ${i}`;s(c),O(!1);let l=o+t Line truncated
`);o=a.pop()||``;for(let e of a){let t=e.split(`
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&r(n.session_id),n.type===`delta`&&(f+=n.text,z(e=>e?{...e,text:f}:null)),n.type===`tool`&&(u=[...u,n],z(e=>e?{...e,tools:u}:null)),n.type===`navigate`&&(u=[...u,n],z(e=>e?{...e,tools:u}:null)),n.type===`done`&&(p=!0,f||=n.text),n.type===`error`)throw Error(n.text)}if(i)break}if(!p)throw Error(`chat stream ended before completion`);a(e=>[...e,{from:`assistant`,text:f,tool_calls:u}]),z(null),l(`Ready`),await le()}catch(e){if(e.name===`AbortError`&&!m)z({text:`Turn stopped.`,tools:u,isError:!1,turn:i,isRetry:c}),l(`Stopped`);else{let t=`Unable to complete that turn: ${e.message||e}`;z({text:t,tools:u,isError:!0,turn:Zr(i),isRetry:c}),l(`Error — retry available`)}}finally{clearTimeout(h),V.current=null,d(!1),B.current&&B.current.focus()}}function xe(){l(`Stopping…`),n&&Y.chatCancel(n).catch(()=>{}),V.current?.abort()}let Se=f.models_by_provider||{},Ce=g&&Se[g]?Se[g]:f.models||[];return X(`div`,{className:`chat-page-content`,children:[X(`header`,{className:`chat-topbar`,children:[X(`div`,{children:[X(`span`,{className:`chat-kicker`,children:`ARCHIE WORKSPACE`}),X(`h1`,{className:`page-title`,children:`Chat`})]}),X(`div`,{className:`chat-topbar-actions`,children:[X(`span`,{className:`chat-status`,children:c}),f.restart_available&&X(`button`,{className:`btn`,type:`button`,onClick:ge,children:`Reload Telegram`}),X(`button`,{className:`btn`,type:`button`,onClick:ie,children:`Check updates`}),X(`select`,{className:`chat-select`,"aria-label":`Personality`,value:m,onChange:pe,children:[X(`option`,{value:``,children:`Personality`}),(f.personas||[]).map(e=>X(`option`,{value:e,children:e},e))]}),(f.providers||[]).length>0&&X(`select`,{className:`chat-select`,"aria-label":`Provider`,value:g,onChange:me,children:[X(`option`,{value:``,children:`Provider`}),(f.providers||[]).map(e=>X(`option`,{value:e,children:e},e))]}),X(`select`,{className:`chat-select`,"aria-label":`Model`,value:v,onChange:he,children:[X(`option`,{value:``,children:`Model`}),Ce.map(e=>X(`option`,{value:e,children:e},e))]})]})]}),k&&X(`div`,{className:`chat-update-panel`,children:k.error?X(`span`,{children:k.error}):k.available?.length?X(S,{children:[X(`div`,{children:[X(`strong`,{children:`Update available`}),X(`span`,{children:k.available.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `)})]}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:ae,children:`Defer`}),k.can_install&&X(`button`,{className:`btn btn-primary`,type:`button`,onClick:oe,children:`Install update`})]})]}):X(`span`,{children:k.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`})}),f.dangerous_available&&N&&X(`div`,{className:`chat-dangerous-panel`,children:[X(`div`,{className:`chat-dangerous-head`,children:[X(`strong`,{children:`Dangerous actions`}),X(`span`,{className:`chat-hint`,children:`Every action requires approval.`})]}),X(`div`,{className:`chat-dangerous-controls`,children:[X(`div`,{children:[X(`select`,{className:`chat-select`,"aria-label":`Checkpoint`,value:F,onChange:e=>I(e.target.value),children:[X(`option`,{value:``,children:`Select checkpoint`}),(N.checkpoints||[]).map(e=>X(`option`,{value:e.Number??e.number,children:[e.Number??e.number,` — `,e.Label??e.label??`checkpoint`]},e.Number??e.number))]}),X(`button`,{className:`btn`,type:`button`,onClick:()=>U(`rollback`,F),children:`Request rollback`})]}),X(`div`,{children:[X(`input`,{className:`chat-dangerous-input`,placeholder:`Process name or id`,"aria-label":`Process name or id`,value:L,onInput:e=>ee(e.target.value)}),X(`button`,{className:`btn`,type:`button`,onClick:()=>U(`stop`,L),children:`Request stop`})]})]}),X(`div`,{className:`chat-dangerous-pending-list`,children:(N.pending||[]).length?N.pending.map(e=>X(`div`,{className:`chat-dangerous-pending`,children:[X(`span`,{children:e.description}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>ce(e.id,`approve`),children:`Approve`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>ce(e.id,`permanent`),children:`Approve for 24h`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>ce(e.id,`deny`),children:`Deny`})]})]},e.id)):X(`span`,{className:`chat-hint`,children:`No pending dangerous actions.`})})]}),X(`div`,{className:`chat-layout`,children:[X(`aside`,{className:`chat-sidebar`,children:[X(`div`,{className:`chat-sidebar-head`,children:[X(`strong`,{children:`Conversations`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:_e,children:`+ New chat`})]}),X(`div`,{className:`chat-session-list`,children:e.length?e.map(e=>X(`button`,{className:`chat-session ${n===e.session_id?`active`:``}`,type:`button`,onClick:()=>ue(e.session_id),children:[X(`strong`,{children:$r(e)}),X(`span`,{children:new Date(e.last_active_at).toLocaleString()})]},e.session_id)):X(`div`,{className:`chat-empty`,children:`Your conversations will aLine truncated
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&r(n.session_id),n.type===`delta`&&(f+=n.text,z(e=>e?{...e,text:f}:null)),n.type===`tool`&&(u=[...u,n],z(e=>e?{...e,tools:u}:null)),n.type===`navigate`&&(u=[...u,n],z(e=>e?{...e,tools:u}:null)),n.type===`done`&&(p=!0,f||=n.text),n.type===`error`)throw Error(n.text)}if(i)break}if(!p)throw Error(`chat stream ended before completion`);a(e=>[...e,{from:`assistant`,text:f,tool_calls:u}]),z(null),l(`Ready`),await le()}catch(e){if(e.name===`AbortError`&&!m)z({text:`Turn stopped.`,tools:u,isError:!1,turn:i,isRetry:c}),l(`Stopped`);else{let t=`Unable to complete that turn: ${e.message||e}`;z({text:t,tools:u,isError:!0,turn:qr(i),isRetry:c}),l(`Error — retry available`)}}finally{clearTimeout(h),V.current=null,d(!1),B.current&&B.current.focus()}}function xe(){l(`Stopping…`),n&&Y.chatCancel(n).catch(()=>{}),V.current?.abort()}let Se=f.models_by_provider||{},Ce=g&&Se[g]?Se[g]:f.models||[];return X(`div`,{className:`chat-page-content`,children:[X(`header`,{className:`chat-topbar`,children:[X(`div`,{children:[X(`span`,{className:`chat-kicker`,children:`ARCHIE WORKSPACE`}),X(`h1`,{className:`page-title`,children:`Chat`})]}),X(`div`,{className:`chat-topbar-actions`,children:[X(`span`,{className:`chat-status`,children:c}),f.restart_available&&X(`button`,{className:`btn`,type:`button`,onClick:ge,children:`Reload Telegram`}),X(`button`,{className:`btn`,type:`button`,onClick:ie,children:`Check updates`}),X(`select`,{className:`chat-select`,"aria-label":`Personality`,value:m,onChange:pe,children:[X(`option`,{value:``,children:`Personality`}),(f.personas||[]).map(e=>X(`option`,{value:e,children:e},e))]}),(f.providers||[]).length>0&&X(`select`,{className:`chat-select`,"aria-label":`Provider`,value:g,onChange:me,children:[X(`option`,{value:``,children:`Provider`}),(f.providers||[]).map(e=>X(`option`,{value:e,children:e},e))]}),X(`select`,{className:`chat-select`,"aria-label":`Model`,value:v,onChange:he,children:[X(`option`,{value:``,children:`Model`}),Ce.map(e=>X(`option`,{value:e,children:e},e))]})]})]}),k&&X(`div`,{className:`chat-update-panel`,children:k.error?X(`span`,{children:k.error}):k.available?.length?X(S,{children:[X(`div`,{children:[X(`strong`,{children:`Update available`}),X(`span`,{children:k.available.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `)})]}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:ae,children:`Defer`}),k.can_install&&X(`button`,{className:`btn btn-primary`,type:`button`,onClick:oe,children:`Install update`})]})]}):X(`span`,{children:k.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`})}),f.dangerous_available&&N&&X(`div`,{className:`chat-dangerous-panel`,children:[X(`div`,{className:`chat-dangerous-head`,children:[X(`strong`,{children:`Dangerous actions`}),X(`span`,{className:`chat-hint`,children:`Every action requires approval.`})]}),X(`div`,{className:`chat-dangerous-controls`,children:[X(`div`,{children:[X(`select`,{className:`chat-select`,"aria-label":`Checkpoint`,value:F,onChange:e=>I(e.target.value),children:[X(`option`,{value:``,children:`Select checkpoint`}),(N.checkpoints||[]).map(e=>X(`option`,{value:e.Number??e.number,children:[e.Number??e.number,` — `,e.Label??e.label??`checkpoint`]},e.Number??e.number))]}),X(`button`,{className:`btn`,type:`button`,onClick:()=>U(`rollback`,F),children:`Request rollback`})]}),X(`div`,{children:[X(`input`,{className:`chat-dangerous-input`,placeholder:`Process name or id`,"aria-label":`Process name or id`,value:L,onInput:e=>ee(e.target.value)}),X(`button`,{className:`btn`,type:`button`,onClick:()=>U(`stop`,L),children:`Request stop`})]})]}),X(`div`,{className:`chat-dangerous-pending-list`,children:(N.pending||[]).length?N.pending.map(e=>X(`div`,{className:`chat-dangerous-pending`,children:[X(`span`,{children:e.description}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>ce(e.id,`approve`),children:`Approve`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>ce(e.id,`permanent`),children:`Approve for 24h`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>ce(e.id,`deny`),children:`Deny`})]})]},e.id)):X(`span`,{className:`chat-hint`,children:`No pending dangerous actions.`})})]}),X(`div`,{className:`chat-layout`,children:[X(`aside`,{className:`chat-sidebar`,children:[X(`div`,{className:`chat-sidebar-head`,children:[X(`strong`,{children:`Conversations`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:_e,children:`+ New chat`})]}),X(`div`,{className:`chat-session-list`,children:e.length?e.map(e=>X(`button`,{className:`chat-session ${n===e.session_id?`active`:``}`,type:`button`,onClick:()=>ue(e.session_id),children:[X(`strong`,{children:Yr(e)}),X(`span`,{children:new Date(e.last_active_at).toLocaleString()})]},e.session_id)):X(`div`,{className:`chat-empty`,children:`Your conversations will aLine truncated
+14
View File
@@ -8,6 +8,20 @@
// 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 = [
-4
View File
@@ -1,7 +1,3 @@
.chat-page { height: calc(100vh - 5rem); display: flex; flex-direction: column; overflow: hidden; }
/* When the chat is a drawer (shell), it fills the panel; the standalone page
keeps its viewport-minus-chrome height. */
.chat-drawer .chat-page { height: 100%; }
.chat-page-content { display: flex; flex-direction: column; flex: 1 1 auto; min-height: 0; overflow: hidden; }
.chat-topbar { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 1rem; margin-bottom: 1rem; }
.chat-kicker, .chat-workspace-label { color: var(--fg-muted); font-size: .68rem; font-weight: 700; letter-spacing: .12em; }
+53 -15
View File
@@ -1,8 +1,9 @@
import "./css/_main.css";
import { h, render } from "preact";
import { useCallback, useEffect, useState } from "preact/hooks";
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";
@@ -76,6 +77,7 @@ function navEntries(hidden) {
function Topbar({ activePath, hidden, onNavigate, chatOpen, onToggleChat, theme, onToggleTheme }) {
const [searchOpen, setSearchOpen] = useState(false);
const searchRef = useRef(null);
const closeSearch = () => setSearchOpen(false);
@@ -99,6 +101,7 @@ function Topbar({ activePath, hidden, onNavigate, chatOpen, onToggleChat, theme,
if (hit) {
onNavigate(hit.path);
event.target.value = "";
event.target.blur();
closeSearch();
}
};
@@ -139,11 +142,17 @@ function Topbar({ activePath, hidden, onNavigate, chatOpen, onToggleChat, theme,
type="button"
aria-label="Open Jump to navigation"
aria-expanded={searchOpen ? "true" : "false"}
onClick={() => setSearchOpen(true)}
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"
@@ -242,26 +251,22 @@ function RouteView({ view, search, params }) {
let outlet = null;
let chrome = null;
function show(rawPath) {
// 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 || {};
// 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));
// The chat is a drawer, not a page: /chat opens it rather than mounting a
// second ChatPage (which would duplicate session state and the stream).
const isChat = route.path === "/chat";
chrome?.setChatOpen(isChat);
if (!outlet) return;
if (isChat) {
if (route.path === "/chat") {
render(null, outlet);
return;
}
@@ -284,6 +289,25 @@ function show(rawPath) {
);
}
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));
// The chat is a drawer, not a page: /chat opens it rather than mounting a
// second ChatPage (which would duplicate session state and the stream).
chrome?.setChatOpen(route.path === "/chat");
renderRoute(rawPath);
}
function navigate(next) {
if (location.hash !== `#${next}`) location.hash = next;
else show(next);
@@ -329,6 +353,20 @@ function App() {
.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 (
<div className="shell">
<Topbar
+6
View File
@@ -9,6 +9,12 @@
// 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) {
+6
View File
@@ -8,6 +8,12 @@ import { ago } from "../base/format.jsx";
// 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",
+10 -4
View File
@@ -5,16 +5,22 @@ import { attentionStatusIds, statusIds } from "../base/task-meta.jsx";
// 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.
const ATTENTION_STATUSES = attentionStatusIds();
const TASK_STATUSES = new Set(["needs_you", ...statusIds()]);
//
// 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 TASK_STATUSES.has(requested) ? requested : "";
return taskStatuses().has(requested) ? requested : "";
}
export function taskMatchesStatus(task, status) {
if (!status) return true;
if (status === "needs_you") return ATTENTION_STATUSES.has(task.status);
if (status === "needs_you") return attentionStatusIds().has(task.status);
return task.status === status;
}
+62
View File
@@ -0,0 +1,62 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { waitFor } from "@testing-library/preact";
// The dashboard's lifecycle vocabulary is *served*: /api/task-meta is the
// source of truth, and base/task-meta.jsx keeps a freeze-dried default only so
// the first paint has labels. That default is meant to be replaced at boot.
//
// This pins the boot step. Without it the module documents a single source of
// truth that never loads, so a server-side catalogue change silently stops
// reaching the browser -- which is exactly what had happened: loadTaskMeta()
// was exported with no callers, and everything read the frozen snapshot.
import { api } from "../src/base/api.jsx";
import { actionFor, statusIds, statusKind, statusLabel } from "../src/base/task-meta.jsx";
globalThis.fetch = async () => {
throw new Error("no daemon in this test");
};
// jsdom has no EventSource and the dashboard subscribes on mount.
class InertEventSource {
close() {}
}
globalThis.EventSource = InertEventSource;
test("booting the dashboard replaces the freeze-dried vocabulary with the served catalog", async () => {
api.taskMeta = async () => ({
statuses: [{ id: "custom_status", label: "Custom status", kind: "danger", needs_you: false }],
actions: [{ id: "custom_action", label: "Custom action", kind: "primary" }],
});
api.capabilities = async () => ({});
document.body.innerHTML = '<div id="app"></div>';
location.hash = "#/";
await import("../src/main.jsx");
await waitFor(() => assert.equal(statusLabel("custom_status"), "Custom status"));
assert.equal(statusKind("custom_status"), "danger");
assert.deepEqual(statusIds(), ["custom_status"]);
assert.equal(actionFor("custom_action")?.label, "Custom action");
});
// The task filter used to capture the vocabulary in module-level constants at
// import, which froze the defaults for the life of the process: no catalog,
// however late or however correct, could reach it.
test("the task filter reads the served catalog rather than an import-time snapshot", async () => {
const { loadTaskMeta } = await import("../src/base/task-meta.jsx");
const { initialTaskFilter, taskMatchesStatus } = await import("../src/tasks/task-filters.jsx");
api.taskMeta = async () => ({
statuses: [
{ id: "custom_status", label: "Custom status", kind: "danger", needs_you: true },
{ id: "running", label: "Working", kind: "info" },
],
actions: [],
});
await loadTaskMeta();
assert.equal(initialTaskFilter(new URLSearchParams("status=custom_status")), "custom_status");
assert.equal(taskMatchesStatus({ status: "custom_status" }, "needs_you"), true);
assert.equal(taskMatchesStatus({ status: "queued" }, "needs_you"), false);
});
+52
View File
@@ -0,0 +1,52 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { waitFor } from "@testing-library/preact";
// Greptile's finding on the first cut of the served-vocabulary fix: the catalog
// resolves after a page has painted, and loadTaskMeta() only mutated module
// state. The route tree renders into its own root, so nothing re-rendered it
// and the painted page kept the freeze-dried labels.
//
// This lives in its own file because main.jsx boots on import and renders into
// #app: the module registry is per process, so a second test in the same file
// would reset the DOM of an app that never re-mounts and assert against a
// detached tree.
import { api } from "../src/base/api.jsx";
// A read that never settles. The page must not be able to pick up the catalog by
// re-rendering for its own reasons, or this test would pass without the
// re-render it exists to pin -- which is what the first version of it did: a
// failing fetch was enough to re-render the page and drag the served labels in.
// With the read pending, the catalog landing is the only thing that can re-render
// it. The status filter renders above the list's loading state, so it is on
// screen either way.
globalThis.fetch = () => new Promise(() => {});
class InertEventSource {
close() {}
}
globalThis.EventSource = InertEventSource;
test("a page that painted before the catalog lands picks up the served vocabulary", async () => {
api.taskMeta = async () => ({
statuses: [{ id: "custom_status", label: "Custom status", kind: "danger", needs_you: true }],
actions: [],
});
api.capabilities = async () => ({});
document.body.innerHTML = '<div id="app"></div>';
location.hash = "#/tasks";
await import("../src/main.jsx");
// The status filter renders one option per known status, so its option list
// is the painted page's own view of the vocabulary. It renders above the
// list's loading and failure states, which is why this assertion does not
// depend on the tasks read (which cannot succeed here).
await waitFor(() => {
const options = [...document.querySelectorAll(".task-filter option")].map((option) => option.textContent);
assert.ok(
options.includes("Custom status"),
`the painted filter must re-render with the served statuses, got: ${options.join(" | ")}`,
);
});
});